context
stringlengths
2.52k
185k
gt
stringclasses
1 value
using System; using System.IO; using NUnit.Framework; using Org.BouncyCastle.Asn1.Cms; using Org.BouncyCastle.Utilities.IO; using Org.BouncyCastle.Utilities.Encoders; namespace Org.BouncyCastle.Asn1.Tests { [TestFixture] public class ParseTest { private static readonly byte[] classCastTest = Base64.Decode( "MIIXqAYJKoZIhvcNAQcDoIIXmTCCF5UCAQAxggG1MIIBsQIBADCBmDCBkDEL" + "MAkGA1UEBhMCVVMxETAPBgNVBAgTCE1pY2hpZ2FuMQ0wCwYDVQQHEwRUcm95" + "MQwwCgYDVQQKEwNFRFMxGTAXBgNVBAsTEEVMSVQgRW5naW5lZXJpbmcxJDAi" + "BgkqhkiG9w0BCQEWFUVsaXQuU2VydmljZXNAZWRzLmNvbTEQMA4GA1UEAxMH" + "RURTRUxJVAIDD6FBMA0GCSqGSIb3DQEBAQUABIIBAGh04C2SyEnH9J2Va18w" + "3vdp5L7immD5h5CDZFgdgHln5QBzT7hodXMVHmyGnycsWnAjYqpsil96H3xQ" + "A6+9a7yB6TYSLTNv8zhL2qU3IrfdmUJyxxfsFJlWFO1MlRmu9xEAW5CeauXs" + "RurQCT+C5tLc5uytbvw0Jqbz+Qp1+eaRbfvyhWFGkO/BYZ89hVL9Yl1sg/Ls" + "mA5jwTj2AvHkAwis+F33ZhYlto2QDvbPsUa0cldnX8+1Pz4QzKMHmfUbFD2D" + "ngaYN1tDlmezCsYFQmNx1th1SaQtTefvPr+qaqRsm8KEXlWbJQXmIfdyi0zY" + "qiwztEtO81hXZYkKqc5fKMMwghXVBgkqhkiG9w0BBwEwFAYIKoZIhvcNAwcE" + "CEq3cLLWVds9gIIVsAAik3al6Nn5pr7r0mSy9Ki3vEeCBcV9EzEG44BvNHNA" + "WyEsqQsdSxuF7h1/DJAMuZFwCbGflaRGx/1L94zrmtpeuH501lzPMvvZCmpj" + "KrOF8e1B4MVQ5TfQTdUVyRnbcDa6E4V1ZZIdAI7BgDeJttS4+L6btquXfxUg" + "ttPYQkevF7MdShYNnfLkY4vUMDOp3+iVzrOlq0elM95dfSA7OdBavgDJbz/7" + "mro3AFTytnWjGz8TUos+oUujTk9/kHOn4cEAIm0hHrNhPS5qoj3QnNduNrad" + "rLpGtcYyNlHIsYCsvPMxwoHmIw+r9xQQRjjzmVYzidn+cNOt0FmLs6YE8ds4" + "wvHRO9S69TgKPHRgk2bihgHqII9lF9qIzfG40YwJLHzGoEwVO1O0+wn8j2EP" + "O9I/Q3vreCH+5VbpUD2NGTwsMwZ3YlUesurLwse/YICxmgdN5Ro4DeQJSa9M" + "iJnRFYWRq+58cKgr+L11mNc9nApZBShlpPP7pdNqWOafStIEjo+dsY/J+iyS" + "6WLlUvNt/12qF4NAgZMb3FvRQ9PrMe87lqSRnHcpLWHcFjuKbMKCBvcdWGWI" + "R7JR8UNzUvoLGGAUI9Ck+yTq4QtfgtL5MLmdBGxSKzgs44Mmek+LnrFx+e9n" + "pkrdDf2gM/m7E50FnLYqzUjctKYGLNYpXQorq9MJx6TB20CHXcqOOoQqesXa" + "9jL9PIOtBQy1Ow5Bh4SP07nTFWFSMI/Wt4ZvNvWJj3ecA9KjMOA9EXWUDS/H" + "k9iCb2EEMo7fe5mhoyxMxPO+EIa1sEC9A1+rDACKPQCHOLI0uPmsdo0AEECC" + "QLgOQkcwQlkHexOyHiOOtBxehtGZ1eBQQZ+31DF+RRU6WvS6grg58eS4gGOQ" + "bd7CS9yYebvAQkz61J8KprWdtZuG1gBGma12wKMuQuC6RuWlKsj+rPMvaQCt" + "8mucGbkElPGZVhdyD8/BvpSCNbgRwb6iSiw4EECovu4P4GFJaMGUYEuCA711" + "itEieYc1QqS6ULjb3LFL/RcwSw0fGdjnt6B2nHckC2VsYKU1NwU7j0R1Omb4" + "y5AvSgpuWjTXWnHnE9Ey0B+KP5ERZA+jJGiwYz48ynYlvQFSbBm4I6nh/DuI" + "dWB2dLNxWuhdfzafBGtEHhLHzjW3WQwwRZsKesgHLrrj9hBUObodl1uvqvZN" + "AjMOj8DrqbGOhAClj1t4S1Zk1ZekuMjsuoxEL+/lgtbT+056ES0k3A/LnpRb" + "uxA1ZBr26Im+GVFzEcsV0hB4vNujSwStTTZH5jX5rMyi085yJfnikcLYUn9N" + "apl+srhpIZlDJPw7IHaw8tsqXKDxF7MozIXo8B45CKv5Am+BMrIemCMX/ehu" + "PODICl98Ur8tNAn1L+m0nj7H3c8HW2vNuBLEI3SEHHgm2Ij3IY5pyyeVUaWC" + "pumhy8Ru5dj3fZcfKgYuJBQxWMf+UqPsf4iUK3923pouJ1cQ8XU8gOXIRrtX" + "e41d/yR+UAZXSig6SITLw+wLtvitSvtxvjcUSUOI9CYTovKyuz1PQKiaLsV5" + "4CoJhMQ5uRlVFS3H829I2d2gLRpSp6pNWeIZO2NMBxPYf2qcSHyHqQjR7xP2" + "ZTg7U3OO6dZHORfXxzAnW2ExavBIYQmZh1gLn5jSS4wXFPXyvnJAsF4s5wed" + "YHsyAqM/ek0n2Oo/zAh7UcP2vcb9FOoeRK8qC9HjTciS6WbjskRN0ft4T69G" + "+1RsH8/edBxo2LZeA48BSCXDXOlBZJBsOptzYJD8HSZONPnef0jn23lk0fkU" + "C3BjJu2ubFChctRvJniTko4klpidkHwuJgrTnL4er8rG3RfiiEHn/d5era15" + "E1cekdVYWqwQOObOd4v+0gZSJgI48TBc5Qdy8F6wIU38DR2pn/5uNthNDgXk" + "NcV9a2gOE3DoLe8CEIPMihqYMPY8NuSp97eHB2YhKpjP7qX9TUMoOdE2Iat2" + "klNxadJt6JTFeiBPL6R9RHAD5sVBrkrl0S+oYtgF92f9WHVwAXU7zP6IgM4x" + "hhzeJT07yyIp44mKd//F+7ntbgQjZ/iLbHh0mtOlUmzkFsDR0UNSXEQoourZ" + "EY4A62HXj0DMqEQbik6QwEF7FKuwZX2opdOyVKH9MzJxNfDLd5dc8wAc8bCX" + "jcCx5/GzHx2S5DndWQEVhp2hOQYuoJS3r6QCYFaHtDPKnFHS2PBFyFWL+2UK" + "c0WsvVaHYqYKnksmxse9I9oU75kx5O05DZCThPX6h8J8MHRuxU9tcuuleIUQ" + "XY8On+JeEtLSUZgp+Z7ITLuagf6yuKQpaR396MlDii/449/dvBiXAXeduyO1" + "QzSkQCh37fdasqGL3mP0ssMcxM/qpOwQsx3gMtwiHQRi1oQE1QHb8qZHDE4m" + "I5afQJ9O/H/m/EVlGUSn2yYOsPlZrWuI3BBZKoRzRq1lZOQDtOh18BE3tWmX" + "viGIAxajam0i2Ce3h2U7vNwtiePRNEgPmQ7RwTTv0U6X8qqkjeYskiF4Cv9G" + "nrB0WreC19ih5psEWLIkCYKTr+OhQuRrtv7RcyUi9QSneh7BjcvRjlGB6joA" + "F6J4Y6ENAA/nzOZJ699VkljTi59bbNJYlONpQhOeRTu8M/wExkIJz7yR9DTY" + "bY4/JdbdHNFf5DSDmYAHaFLmdnnfuRy+tC9CGGJvlcLVv5LMFJQGt2Wi15p8" + "lctx7sL6yNCi7OakWbEOCvGPOxY7ejnvOjVK/Krx1T+dAXNUqrsDZmvmakOP" + "We+P4Di1GqcyLVOTP8wNCkuAUoN0JFoBHy336/Xnae91KlY4DciPMpEOIpPN" + "oB+3h6CozV7IWX5Wh3rhfC25nyGJshIBUS6cMXAsswQI8rOylMlGaekNcSU4" + "gNKNDZAK5jNkS0Z/ziIrElSvMNTfYbnx3gCkY0pV18uadmchXihVT11Bt77O" + "8KCKHycR39WYFIRO09wvGv6P42CRBFTdQbWFtkSwRiH8l6x39Z7pIkDFxokT" + "Dp6Htkj3ywfQXNbFgRXZUXqgD1gZVFDFx920hcJnuu65CKz6pEL6X0XUwNPg" + "vtraA2nj4wjVB/y+Cxc+1FgzeELB4CAmWO1OfRVLjYe7WEe/X5DPT6p8HBkB" + "5mWuv+iQ3e37e1Lrsjt2frRYQWoOSP5Lv7c8tZiNfuIp07IYnJKBWZLTqNf9" + "60uiY93ssE0gr3mfYOj+fSbbjy6NgAenT7NRZmFCjFwAfmapIV0hJoqnquaN" + "jj5KKOP72hp+Zr9l8cEcvIhG/BbkY3kYbx3JJ9lnujBVr69PphHQTdw67CNB" + "mDkH7y3bvZ+YaDY0vdKOJif9YwW2qoALXKgVBu1T2BONbCTIUTOzrKhWEvW8" + "D6x03JsWrMMqOKeoyomf1iMt4dIOjp7yGl/lQ3iserzzLsAzR699W2+PWrAT" + "5vLgklJPX/Fb3Tojbsc074lBq669WZe3xzlj85hFcBmoLPPyBE91BLhEwlGC" + "+lWmwFOENLFGZE0mGoRN+KYxwqfA2N6H8TWoz6m0oPUW4uQvy9sGtYTSyQO9" + "6ZwVNT3ndlFrP5p2atdEFVc5aO5FsK8/Fenwez06B2wv9cE9QTVpFrnJkKtF" + "SaPCZkignj64XN7cHbk7Ys6nC3WIrTCcj1UOyp5ihuMS9eL9vosYADsmrR6M" + "uqqeqHsf2+6U1sO1JBkDYtLzoaILTJoqg9/eH7cTA0T0mEfxVos9kAzk5nVN" + "nVOKFrCGVIbOStpYlWP6wyykIKVkssfO6D42D5Im0zmgUwgNEkB+Vxvs8bEs" + "l1wPuB2YPRDCEvwM3A5d5vTKhPtKMECIcDxpdwkD5RmLt+iaYN6oSFzyeeU0" + "YvXBQzq8gfpqJu/lP8cFsjEJ0qCKdDHVTAAeWE6s5XpIzXt5cEWa5JK7Us+I" + "VbSmri4z0sVwSpuopXmhLqLlNWLGXRDyTjZSGGJbguczXCq5XJ2E3E4WGYd6" + "mUWhnP5H7gfW7ILOUN8HLbwOWon8A6xZlMQssL/1PaP3nL8ukvOqzbIBCZQY" + "nrIYGowGKDU83zhO6IOgO8RIVQBJsdjXbN0FyV/sFCs5Sf5WyPlXw/dUAXIA" + "cQiVKM3GiVeAg/q8f5nfrr8+OD4TGMVtUVYujfJocDEtdjxBuyFz3aUaKj0F" + "r9DM3ozAxgWcEvl2CUqJLPHH+AWn5kM7bDyQ2sTIUf5M6hdeick09hwrmXRF" + "NdIoUpn7rZORh0h2VX3XytLj2ERmvv/jPVC97VKU916n1QeMJLprjIsp7GsH" + "KieC1RCKEfg4i9uHoIyHo/VgnKrnTOGX/ksj2ArMhviUJ0yjDDx5jo/k5wLn" + "Rew2+bhiQdghRSriUMkubFh7TN901yl1kF2BBP5PHbpgfTP6R7qfl8ZEwzzO" + "elHe7t7SvI7ff5LkwDvUXSEIrHPGajYvBNZsgro+4Sx5rmaE0QSXACG228OQ" + "Qaju8qWqA2UaPhcHSPHO/u7ad/r8kHceu0dYnSFNe1p5v9Tjux0Yn6y1c+xf" + "V1cu3plCwzW3Byw14PH9ATmi8KJpZQaJOqTxn+zD9TvOa93blK/9b5KDY1QM" + "1s70+VOq0lEMI6Ch3QhFbXaslpgMUJLgvEa5fz3GhmD6+BRHkqjjwlLdwmyR" + "qbr4v6o+vnJKucoUmzvDT8ZH9nH2WCtiiEtQaLNU2vsJ4kZvEy0CEajOrqUF" + "d8qgEAHgh9it5oiyGBB2X/52notXWOi6OMKgWlxxKHPTJDvEVcQ4zZUverII" + "4vYrveRXdiDodggfrafziDrA/0eEKWpcZj7fDBYjUBazwjrsn5VIWfwP2AUE" + "wNn+xR81/so8Nl7EDBeoRXttyH7stbZYdRnkPK025CQug9RLzfhEAgjdgQYw" + "uG+z0IuyctJW1Q1E8YSOpWEFcOK5okQkLFUfB63sO1M2LS0dDHzmdZriCfIE" + "F+9aPMzojaHg3OQmZD7MiIjioV6w43bzVmtMRG22weZIYH/Sh3lDRZn13AS9" + "YV6L7hbFtKKYrie79SldtYazYT8FTSNml/+Qv2TvYTjVwYwHpm7t479u+MLh" + "LxMRVsVeJeSxjgufHmiLk7yYJajNyS2j9Kx/fmXmJbWZNcerrfLP+q+b594Y" + "1TGWr8E6ZTh9I1gU2JR7WYl/hB2/eT6sgSYHTPyGSxTEvEHP242lmjkiHY94" + "CfiTMDu281gIsnAskl05aeCBkj2M5S0BWCxy7bpVAVFf5nhf74EFIBOtHaJl" + "/8psz1kGVF3TzgYHkZXpUjVX/mJX8FG0R8HN7g/xK73HSvqeamr4qVz3Kmm/" + "kMtYRbZre7E1D10qh/ksNYnOkYBcG4P2JyjZ5q+8CQNungz2/b0Glg5LztNz" + "hUgG27xDOUraJXjkkZl/GOh0eTqhfLHXC/TfyoEAQOPcA59MKqvroFC5Js0Q" + "sTgqm2lWzaLNz+PEXpJHuSifHFXaYIkLUJs+8X5711+0M03y8iP4jZeEOrjI" + "l9t3ZYbazwsI3hBIke2hGprw4m3ZmSvQ22g+N6+hnitnDALMsZThesjb6aJd" + "XOwhjLkWRD4nQN594o6ZRrfv4bFEPTp4ev8l6diouKlXSFFnVqz7AZw3Pe53" + "BvIsoh66zHBpZhauPV/s/uLb5x6Z8sU2OK6AoJ7b8R9V/AT7zvonBi/XQNw3" + "nwkwGnTS9Mh7PFnGHLJWTKKlYXrSpNviR1vPxqHMO6b+Lki10d/YMY0vHQrY" + "P6oSVkA6RIKsepHWo11+rV838+2NRrdedCe91foUmOs+eoWQnwmTy2CTZmQ5" + "b7/TTcau9ewimZAqI+MtDWcmWoZfgibZmnIITGcduNOJDRn+aLt9dz+zr1qA" + "HxlLXCOyBPdtfx6eo4Jon+fVte37i3HmxHk+8ZGMMSS9hJbLQEkA59b4E+7L" + "GI3JZjvEkhizB4n/aFeG7KT7K3x072DMbHLZ7VgsXQ1VDDmcZmizFwgyNqKy" + "hKCKxU+I2O10IMtiZUpEzV1Pw7hD5Kv/eFCsJFPXOJ2j3KP6qPtX5IYki1qH" + "Juo5C5uGKtqNc6OzkXsvNUfBz5sJkEYl0WfitSSo4ARyshFUNh2hGxNxUVKM" + "2opOcuHSxBgwUSmVprym50C305zdHulBXv3mLzGjvRstE9qfkQ8qVJYLQEkL" + "1Yn7E92ex71YsC8JhNNMy0/YZwMkiFrqyaFd/LrblWpBbGumhe4reCJ4K3mk" + "lFGEsICcMoe+zU1+QuLlz/bQ+UtvClHUe8hTyIjfY04Fwo2vbdSc1U/SHho5" + "thQy+lOZ/HijzCmfWK3aTqYMdwCUTCsoxri2N8vyD/K2kbMLQWUfUlBQfDOK" + "VrksBoSfcluNVaO56uEUw3enPhhJghfNlJnpr5gUcrAMES53DfkjNr0dCsfM" + "JOY2ZfQEwwYey1c4W1MNNMoegSTg4aXzjVc0xDgKa7RGbtRmVNbOxIhUNAVi" + "thQV3Qujoz1ehDt2GyLpjGjHSpQo3WlIU4OUqJaQfF6EH+3khFqUmp1LT7Iq" + "zH3ydYsoCDjvdXSSEY3hLcZVijUJqoaNWBLb/LF8OG5qTjsM2gLgy2vgO/lM" + "NsqkHnWTtDimoaRRjZBlYLhdzf6QlfLi7RPmmRriiAOM0nXmylF5xBPHQLoz" + "LO9lXYIfNbVJVqQsV43z52MvEQCqPNpGqjB+Au/PZalYHbosiVOQLgTB9hTI" + "sGutSXXeLnf5rftCFvWyL3n5DgURzDFLibrbyVGGKAk166bK1RyVP9XZJonr" + "hPYELk4KawCysJJSmC0E8sSsuXpfd6PPDru6nCV1EdXKR7DybS7NVHCktiPR" + "4B4y8O/AgfJX8sb6LuxmjaINtUKEJ1+O88Gb69uy6b/Kpu2ri/SUBaNNw4Sn" + "/tuaD+jxroL7RlZmt9ME/saNKn9OmLuggd6IUKAL4Ifsx9i7+JKcYuP8Cjdf" + "Rx6U6H4qkEwwYGXnZYqF3jxplyOfqA2Vpvp4rnf8mST6dRLKk49IhKGTzwZr" + "4za/RZhyl6lyoRAFDrVs1b+tj6RYZk0QnK3dLiN1MFYojLyz5Uvi5KlSyFw9" + "trsvXyfyWdyRmJqo1fT7OUe0ImJW2RN3v/qs1k+EXizgb7DW4Rc2goDsCGrZ" + "ZdMwuAdpRnyg9WNtmWwp4XXeb66u3hJHr4RwMd5oyKFB1GsmzZF7aOhSIb2B" + "t3coNXo/Y+WpEj9fD7/snq7I1lS2+3Jrnna1048O7N4b5S4b5TtEcCBILP1C" + "SRvaHyZhBtJpoH6UyimKfabXi08ksrcHmbs1+HRvn+3pl0bHcdeBIQS/wjk1" + "TVEDtaP+K9zkJxaExtoa45QvqowxtcKtMftNoznF45LvwriXEDV9jCXvKMcO" + "nxG5aQ//fbnn4j4q1wsKXxn61wuLUW5Nrg9fIhX7nTNAAooETO7bMUeOWjig" + "2S1nscmtwaV+Sumyz/XUhvWynwE0AXveLrA8Gxfx"); private static readonly byte[] derExpTest = Base64.Decode( "MIIS6AYJKoZIhvcNAQcDoIIS2TCCEtUCAQAxggG1MIIBsQIBADCBmDCBkDEL" + "MAkGA1UEBhMCVVMxETAPBgNVBAgTCE1pY2hpZ2FuMQ0wCwYDVQQHEwRUcm95" + "MQwwCgYDVQQKEwNFRFMxGTAXBgNVBAsTEEVMSVQgRW5naW5lZXJpbmcxJDAi" + "BgkqhkiG9w0BCQEWFUVsaXQuU2VydmljZXNAZWRzLmNvbTEQMA4GA1UEAxMH" + "RURTRUxJVAIDD6FBMA0GCSqGSIb3DQEBAQUABIIBAGsRYK/jP1YujirddAMl" + "ATysfLCwd0eZhENohVqLiMleH25Dnwf+tBaH4a9hyW+7VrWw/LC6ILPVbKpo" + "oLBAOical40cw6C3zulajc4gM3AlE2KEeAWtI+bgPMXhumqiWDb4byX/APYk" + "53Gk7WXF6Xs4hj3tmrHSJxCUOsTdHKUJYvOqjwKGARPQDjP0EUbVJezeAwBA" + "RMlJ/qBVLBj2UW28n5oJZm3oaSaU93Uc6GPVIk43IWrmEUcWVPiMfUtUCwcX" + "tRNtHuQ9os++rmdNBiuB5p+vtUeA45KWnTUtkwJXvrzE6Sf9AUH/p8uOvvZJ" + "3yt9LhPxcZukGIVvcQnBxLswghEVBgkqhkiG9w0BBwEwFAYIKoZIhvcNAwcE" + "CGObmTycubs2gIIQ8AKUC8ciGPxa3sFJ1EPeX/nRwYGNAarlpVnG+07NITL2" + "pUzqZSgsYh5JiKd8TptQBZNdebzNmCvjrVv5s9PaescGcypL7FNVPEubh0w/" + "8h9rTACqUpF5yRgfcgpAGeK29F1hyZ1WaIH43avUCaDnrZcOKB7wc1ats1aQ" + "TSDLImyFn4KjSo5k0Ec/xSoWnfg391vebp8eOsyHZhFMffFtKQMaayZNHJ7Q" + "BzG3r/ysUbkgI5x+0bX0QfZjEIs7yuV5Wt8DxMTueCm3RQ+HkR4lNdTBkM4V" + "qozCqC1SjcAF5YHB0WFkGouEPGgTlmyvLqR2xerEXVZn9YwSnT48kOde3oGt" + "EAYyg0yHbNbL0sp6LDM7upRmrgWwxf0BR6lP4wyWdv/XSLatEB7twSNiPBJ4" + "PJ+QagK08yQJ84UB7YpMTudKsaUs7zW76eA7KkW3TndfDYGdhbmZ5wxNl+5x" + "yPZc/jcQHW7vplMfWglUVxnzibNW12th0QXSB57Mzk8v1Rvc/HLGvAOJZG/S" + "N12FZOxbUrMIHGi3kXsmfWznVyq92X4P9tuDDD7sxkSGsyUAm/UJIZ3KsXhV" + "QeaRHVTVDxtJtnbYxBupy1FDBO6AhVrp16Blvnip9cPn/aLfxDoFHzmsZmEg" + "IcOFqpT1fW+KN6i/JxLD3mn3gKzzdL1/8F36A2GxhCbefQFp0MfIovlnMLFv" + "mrINwMP8a9VnP8gIV5oW5CxmmMUPHuGkXrfg+69iVACaC2sTq6KGebhtg9OC" + "8vZhmu7+Eescst694pYa3b8Sbr5bTFXV68mMMjuRnhvF2NZgF+O0jzU+sFps" + "o7s1rUloCBk1clJUJ/r+j9vbhVahCeJQw62JAqjZu4R1JYAzON3S7jWU5zJ7" + "pWYPSAQkLYUz3FmRRS2Yv65mXDNHqR9vqkHTIphwA9CLMKC2rIONxSVB57q1" + "Npa/TFkVdXnw+cmYjyFWiWeDP7Mw0Kwy7tO008UrBY0rKQU466RI5ezDqYPc" + "Lm73dUH2EjUYmKUi8zCtXpzgfTYVa/DmkbVUL9ThHMVRq1OpT2nctE7kpXZk" + "OsZjEZHZX4MCrSOlc10ZW7MJIRreWMs70n7JX7MISU+8fK6JKOuaQNG8XcQp" + "5IrCTIH8vmN2rVt4UT8zgm640FtO3jWUxScvxCtUJJ49hGCwK+HwDDpO6fLw" + "LFuybey+6hnAbtaDyqgsgDh2KN8GSkQT9wixqwQPWsMQ4h0xQixf4IMdFOjP" + "ciwp3ul8KAp/q70i0xldWGqcDjUasx6WHKc++rFjVJjoVvijKgEhlod5wJIw" + "BqQVMKRsXle07NS1MOB+CRTVW6mwBEhDDERL+ym2GT2Q4uSDzoolmLq2y5vL" + "+RfDHuh3W0UeC3Q5D2bJclgMsVjgfQUN19iD+lPFp2xvLTaNWi5fYDn4uuJL" + "lgVDXIMmM8I+Z2hlTXTM1Pldz2/UFe3QXTbYnjP6kfd7Bo2Webhhgs/YmSR2" + "XPuA42tWNAAjlK77lETWodxi3UC7XELjZ9xoGPRbxjOklXXvev9v5Vo+vcmN" + "0KrLXhLdkyHRSm81SRsWoadCTSyT8ibv66P00GOt+OlIUOt0YKSUkULQfPvC" + "EgMpeTm1/9l8n9bJ6td5fpJFDqLDm+FpJX6T2sWevV/Tyt6aoDPuET5iHBHW" + "PoHxKl8YPRHBf+nRWoh45QMGQWNSrJRDlO8oYOhdznh4wxLn3DXEfDr0Z7Kd" + "gEg6xr1XCobBn6Gi7wWXp5FDTaRF41t7fH8VxPwwDa8Yfu3vsgB6q426kjAj" + "Q77wx1QFIg8gOYopTOgqze1i4h1U8ehP9btznDD6OR8+hPsVKoXYGp8Ukkc7" + "JBA0o8l9O2DSGh0StsD94UhdYzn+ri7ozkXFy2SHFT2/saC34NHLoIF0v/aw" + "L9G506Dtz6xXOACZ4brCG+NNnPLIcGblXIrYTy4+sm0KSdsl6BGzYh9uc8tu" + "tfCh+iDuhT0n+nfnvdCmPwonONFb53Is1+dz5sisILfjB7OPRW4ngyfjgfHm" + "oxxHDC/N01uoJIdmQRIisLi2nLhG+si8+Puz0SyPaB820VuV2mp77Y2osTAB" + "0hTDv/sU0DQjqcuepYPUMvMs3SlkEmaEzNSiu7xOOBQYB8FoK4PeOXDIW6n2" + "0hv6iS17hcZ+8GdhwC4x2Swkxt99ikRM0AxWrh1lCk5BagVN5xG79c/ZQ1M7" + "a0k3WTzYF1Y4d6QPNOYeOBP9+G7/a2o3hGXDRRXnFpO7gQtlXy9A15RfvsWH" + "O+UuFsOTtuiiZk1qRgWW5nkSCPCl2rP1Z7bwr3VD7o6VYhNCSdjuFfxwgNbW" + "x8t35dBn6xLkc6QcBs2SZaRxvPTSAfjON++Ke0iK5w3mec0Br4QSNB1B0Aza" + "w3t3AleqPyJC6IP1OQl5bi+PA+h3YZthwQmcwgXgW9bWxNDqUjUPZfsnNNDX" + "MU9ANDLjITxvwr3F3ZSfJyeeDdbhr3EJUTtnzzWC6157EL9dt0jdPO35V0w4" + "iUyZIW1FcYlCJp6t6Sy9n3TmxeLbq2xML4hncJBClaDMOp2QfabJ0XEYrD8F" + "jq+aDM0NEUHng+Gt9WNqnjc8GzNlhxTNm3eQ6gyM/9Ip154GhH6c9hsmkMy5" + "DlMjGFpFnsSTNFka2+DOzumWUiXLGbe4M3RePl1N4MLwXrkR2llguQynyoqF" + "Ptat2Ky5yW2q9+IQHY49NJTlsCpunE5HFkAK9rY/4lM4/Q7hVunP6U4a0Kbu" + "beFuOQMKQlBZvcplnYBefXD79uarY/q7ui6nFHlqND5mlXMknMrsQk3papfp" + "OpMS4T07rCTLek0ODtb5KsHdIF76NZXevko4+d/xbv7HLCUYd8xuOuqf+y4I" + "VJiT1FmYtZd9w+ubfHrOfHxY+SBtN6fs02WAccZqBXUYzZEijRbN2YUv1OnG" + "rfYe4EcfOu/Sa+wLbB7msYpLfvUfEO3iseKf4LXZkgtF5P610PBZR8edeSgr" + "YZW+J0K78PRAl5nEi1mvzBxi9DyNf6iQ9mWLyyCmr9p9HGE+aCMKVCn9jfZH" + "WeBDAJNYDcUh5NEckqJtbEc2S1FJM7yZBWLQUt3NCQvj+nvQT45osZ3BJvFg" + "IcGJ0CysoblVz4fCLybrYxby9HP89WMLHqdqsIeVX8IJ3x84SqLPuzrqf9FT" + "ZVYLo0F2oBjAzjT7obt9+NJc/psOMCg+OGQkAfwj3VNvaqkkQsVxSiozgxrC" + "7KaTXuAL6eKKspman96kz4QVk9P0usUPii+LFnW4XYc0RNfgJVO6BgJT7pLX" + "NWwv/izMIMNAqSiWfzHHRVkhq4f1TMSF91auXOSICpJb3QQ4XFh52Mgl8+zs" + "fobsb0geyb49WqFrZhUu+X+8LfQztppGmiUpFL+8EW0aPHbfaf4y9J1/Wthy" + "c28Yqu62j/ljXq4Qa21uaEkoxzH1wPKCoKM9TXJtZJ39Yl9cf119Qy4M6QsB" + "6oMXExlMjqIMCCWaLXLRiqbc2Y7rZHgEr08msibdoYHbSkEl8U+Kii2p6Vdx" + "zyiEIz4CadrFbrAzxmrR/+3u8JuBdq0K3KNR0WWx73BU+G0rgBX56GnP7Ixy" + "fuvkRb4YfJUF4PkDa50BGVhybPrIhoFteT6bSh6LQtBm9c4Kop8Svx3ZbqOT" + "kgQDa0n+O0iR7x3fvNZ0Wz4YJrKGnVOPCqJSlSsnX6v2JScmaNdrSwkMTnUf" + "F9450Hasd88+skC4jVAv3WAB03Gz1MtiGDhdUKFnHnU9HeHUnh38peCFEfnK" + "WihakVQNfc72YoFVZHeJI5fJAW8P7xGTZ95ysyirtirxt2zkRVJa5p7semOw" + "bL/lBC1bp4J6xHF/NHY8NQjvuhqkDyNlh3dRpIBVBu6Z04hRhLFW6IBxcCCv" + "pjfoxJoox9yxKQKpr3J6MiZKBlndZRbSogO/wYwFeh7HhUzMNM1xIy3jWVVC" + "CrzWp+Q1uxnL74SwrMP/EcZh+jZO4CYWk6guUMhTo1kbW03BZfyAqbPM+X+e" + "ZqMZljydH8AWgl0MZd2IAfajDxI03/6XZSgzq24n+J7wKMYWS3WzB98OIwr+" + "oKoQ7aKwaaT/KtR8ggUVYsCLs4ScFY24MnjUvMm+gQcVyeX74UlqR30Aipnf" + "qzDRVcAUMMNcs0fuqePcrZ/yxPo+P135YClPDo9J8bwNpioUY8g+BQxjEQTj" + "py3i2rAoX+Z5fcGjnZQVPMog0niIvLPRJ1Xl7yzPW0SevhlnMo6uDYDjWgQ2" + "TLeTehRCiSd3z7ZunYR3kvJIw1Kzo4YjdO3l3WNf3RQvxPmJcSKzeqKVxWxU" + "QBMIC/dIzmRDcY787qjAlKDZOdDp7qBKIqnfodWolxBA0KhvE61eYabZqUCT" + "G2HJaQE1SvOdL9KM4ORFlxE3/dqv8ttBJ6N1qKk423CJjajZHYTwf1dCfj8T" + "VAE/A3INTc6vg02tfkig+7ebmbeXJRH93KveEo2Wi1xQDsWNA+3DVzsMyTqV" + "+AgfSjjwKouXAznhpgNc5QjmD2I6RyTf+hngftve18ZmVhtlW5+K6qi62M7o" + "aM83KweH1QgCS12/p2tMEAfz//pPbod2NrFDxnmozhp2ZnD04wC+6HGz6bX/" + "h8x2PDaXrpuqnZREFEYzUDKQqxdglXj5oE/chBR8+eBfYSS4JW3TBkW6RfwM" + "KOBBOOv8pe3Sfq/bg7OLq5bn0jKwulqP50bysZJNlQUG/KqJagKRx60fnTqB" + "7gZRebvtqgn3JQU3fRCm8ikmGz9XHruoPlrUQJitWIt4AWFxjyl3oj+suLJn" + "7sK62KwsqAztLV7ztoC9dxldJF34ykok1XQ2cMT+uSrD6ghYZrmrG5QDkiKW" + "tOQCUvVh/CorZNlON2rt67UvueMoW+ua25K4pLKDW316c2hGZRf/jmCpRSdb" + "Xr3RDaRFIK6JpmEiFMMOEnk9yf4rChnS6MHrun7vPkf82w6Q0VxoR8NRdFyW" + "3mETtm2mmG5zPFMMD8uM0BYJ/mlJ2zUcD4P3hWZ8NRiU5y1kazvrC6v7NijV" + "o459AKOasZUj1rDMlXDLPloTHT2ViURHh/8GKqFHi2PDhIjPYUlLR5IrPRAl" + "3m6DLZ7/tvZ1hHEu9lUMMcjrt7EJ3ujS/RRkuxhrM9BFlwzpa2VK8eckuCHm" + "j89UH5Nn7TvH964K67hp3TeV5DKV6WTJmtIoZKCxSi6FFzMlky73gHZM4Vur" + "eccwycFHu+8o+tQqbIAVXaJvdDstHpluUCMtb2SzVmI0bxABXp5XrkOOCg8g" + "EDZz1I7rKLFcyERSifhsnXaC5E99BY0DJ/7v668ZR3bE5cU7Pmo/YmJctK3n" + "m8cThrYDXJNbUi0c5vrAs36ZQECn7BY/bdDDk2NPgi36UfePI8XsbezcyrUR" + "ZZwT+uQ5LOB931NjD5GOMEb96cjmECONcRjB0uD7DoTiVeS3QoWmf7Yz4g0p" + "v9894YWQgOl+CvmTERO4dxd7X5wJsM3Y0acGPwneDF+HtQrIpJlslm2DivEv" + "sikc6DtAQrnVRSNDr67HPPeIpgzThbxH3bm5UjvnP/zcGV1W8Nzk/OBQWi0l" + "fQM9DccS6P/DW3XPSD1+fDtUK5dfH8DFf8wwgnxeVwi/1hCBq9+33XPwiVpz" + "489DnjGhHqq7BdHjTIqAZvNm8UPQfXRpeexbkFZx1mJvS7so54Cs58/hHgQN" + "GHJh4AUCLEt0v7Hc3CMy38ovLr3Q8eZsyNGKO5GvGNa7EffGjzOKxgqtMwT2" + "yv8TOTFCWnZEUTtVA9+2CpwfmuEjD2UQ4vxoM+o="); private static readonly byte[] longTagged = Hex.Decode("9f1f023330"); [Test] public void TestClassCast() { ParseEnveloped(classCastTest); } [Test] public void TestDerExp() { ParseEnveloped(derExpTest); } [Test] public void TestLongTag() { Asn1StreamParser aIn = new Asn1StreamParser(longTagged); Asn1TaggedObjectParser tagged = (Asn1TaggedObjectParser)aIn.ReadObject(); Assert.AreEqual(31, tagged.TagNo); } private void ParseEnveloped( byte[] data) { Asn1StreamParser aIn = new Asn1StreamParser(data); ContentInfoParser cP = new ContentInfoParser((Asn1SequenceParser)aIn.ReadObject()); EnvelopedDataParser eP = new EnvelopedDataParser((Asn1SequenceParser)cP.GetContent(Asn1Tags.Sequence)); eP.GetRecipientInfos().ToAsn1Object(); // Must drain the parser! EncryptedContentInfoParser ecP = eP.GetEncryptedContentInfo(); Asn1OctetStringParser content = (Asn1OctetStringParser)ecP.GetEncryptedContent(Asn1Tags.OctetString); Streams.Drain(content.GetOctetStream()); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Extensions.Options; using Orleans.Configuration; namespace Orleans.Runtime { /* Example of printout in logs: StageAnalysis= Stage: Runtime.IncomingMessageAgent.Application Measured average CPU per request: 0.067 ms Measured average Wall-clock per request: 0.068 ms Measured number of requests: 1777325 requests Estimated wait time: 0.000 ms Suggested thread allocation: 2 threads (rounded up from 1.136) Stage: Scheduler.WorkerPoolThread Measured average CPU per request: 0.153 ms Measured average Wall-clock per request: 0.160 ms Measured number of requests: 4404680 requests Estimated wait time: 0.000 ms Suggested thread allocation: 7 threads (rounded up from 6.386) Stage: Runtime.Messaging.GatewaySender.GatewaySiloSender Measured average CPU per request: 0.152 ms Measured average Wall-clock per request: 0.155 ms Measured number of requests: 92428 requests Estimated wait time: 0.000 ms Suggested thread allocation: 1 threads (rounded up from 0.133) Stage: Runtime.Messaging.SiloMessageSender.AppMsgsSender Measured average CPU per request: 0.034 ms Measured average Wall-clock per request: 0.125 ms Measured number of requests: 1815072 requests Estimated wait time: 0.089 ms Suggested thread allocation: 2 threads (rounded up from 1.765) CPU usage by thread type: 0.415, Untracked 0.359, Scheduler.WorkerPoolThread 0.072, Untracked.ThreadPoolThread 0.064, Runtime.IncomingMessageAgent.Application 0.049, ThreadPoolThread 0.033, Runtime.Messaging.SiloMessageSender.AppMsgsSender 0.008, Runtime.Messaging.GatewaySender.GatewaySiloSender 0.000, Scheduler.WorkerPoolThread.System 0.000, Runtime.Messaging.SiloMessageSender.SystemSender 0.000, Runtime.IncomingMessageAgent.System 0.000, Runtime.Messaging.SiloMessageSender.PingSender 0.000, Runtime.IncomingMessageAgent.Ping EndStageAnalysis */ /// <summary> /// Stage analysis, one instance should exist in each Silo /// </summary> internal class StageAnalysisStatisticsGroup { private readonly double stableReadyTimeProportion; private readonly Dictionary<string, List<ThreadTrackingStatistic>> stageGroups; public StageAnalysisStatisticsGroup(IOptions<StatisticsOptions> statisticsOptions) { // Load test experiments suggested these parameter values stableReadyTimeProportion = 0.3; stageGroups = new Dictionary<string, List<ThreadTrackingStatistic>>(); this.PerformStageAnalysis = statisticsOptions.Value.CollectionLevel.PerformStageAnalysis(); if (this.PerformStageAnalysis) { StringValueStatistic.FindOrCreate(StatisticNames.STAGE_ANALYSIS, StageAnalysisInfo); } } public bool PerformStageAnalysis { get; } public void AddTracking(ThreadTrackingStatistic tts) { lock (stageGroups) { // we trim all thread numbers from thread name, so allow to group them. char[] toTrim = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '/', '_', '.' }; string stageName = tts.Name.Trim(toTrim); List<ThreadTrackingStatistic> stageGroup; if (!stageGroups.TryGetValue(stageName, out stageGroup)) { stageGroup = new List<ThreadTrackingStatistic>(); stageGroups.Add(stageName, stageGroup); } stageGroup.Add(tts); } } // the interesting stages to print in stage analysis private static readonly List<string> stages = new List<string>() { "Runtime.IncomingMessageAgent.Application", "Scheduler.WorkerPoolThread", "Runtime.Messaging.GatewaySender.GatewaySiloSender", "Runtime.Messaging.SiloMessageSender.AppMsgsSender" }; // stages where wait time is expected to be nonzero private static readonly HashSet<string> waitingStages = new HashSet<string>() { //stages[1], // if we know there is no waiting in the WorkerPoolThreads, we can remove it from waitingStages and get more accuarte measurements stages[2], stages[3] }; private static readonly string firstStage = stages[0]; private string StageAnalysisInfo() { try { lock (stageGroups) { double cores = Environment.ProcessorCount; Dictionary<string, double> cpuPerRequest = new Dictionary<string, double>(); // CPU time per request for each stage Dictionary<string, double> wallClockPerRequest = new Dictionary<string, double>(); // Wallclock time per request for each stage Dictionary<string, double> numberOfRequests = new Dictionary<string, double>(); // Number of requests for each stage foreach (var keyVal in stageGroups) { string name = keyVal.Key; if (GetNumberOfRequests(name) > 0) { cpuPerRequest.Add(name, GetCpuPerStagePerRequest(name)); wallClockPerRequest.Add(name, GetWallClockPerStagePerRequest(name)); numberOfRequests.Add(name, GetNumberOfRequests(name)); } } cpuPerRequest.Add("Untracked.ThreadPoolThread", GetCpuPerStagePerRequest("Untracked.ThreadPoolThread")); numberOfRequests.Add("Untracked.ThreadPoolThread", GetNumberOfRequests("Untracked.ThreadPoolThread")); double elapsedWallClock = GetMaxWallClock(); double elapsedCPUClock = GetTotalCPU(); // Idle time estimation double untrackedProportionTime = 1 - elapsedCPUClock / (cores * elapsedWallClock); // Ratio of wall clock per cpu time calculation double sum = 0; double num = 0; foreach (var stage in wallClockPerRequest.Keys) { if (!waitingStages.Contains(stage)) { double ratio = wallClockPerRequest[stage] / cpuPerRequest[stage] - 1; sum += ratio * numberOfRequests[stage]; num += numberOfRequests[stage]; } } double avgRatio = sum / num; // Wait time estimation - implementation of strategy 2 from the "local-throughput.pdf" "Coping with Practical Measurements". var waitTimes = new Dictionary<string, double>(); // Wait time per request for each stage foreach (var stage in wallClockPerRequest.Keys) { waitTimes.Add(stage, waitingStages.Contains(stage) ? Math.Max(wallClockPerRequest[stage] - avgRatio*cpuPerRequest[stage] - cpuPerRequest[stage], 0) : 0); } // CPU sum for denominator of final equation double cpuSum = 0; foreach (var stage in cpuPerRequest.Keys) { cpuSum += cpuPerRequest[stage] * numberOfRequests[stage]; } // beta and lambda values var beta = new Dictionary<string, double>(); var s = new Dictionary<string, double>(); var lambda = new Dictionary<string, double>(); foreach (var stage in wallClockPerRequest.Keys) { beta.Add(stage, cpuPerRequest[stage] / (cpuPerRequest[stage] + waitTimes[stage])); s.Add(stage, 1000.0 / (cpuPerRequest[stage] + waitTimes[stage])); lambda.Add(stage, 1000.0 * numberOfRequests[stage] / elapsedWallClock); } // Final equation thread allocation - implementation of theorem 2 from the "local-throughput.pdf" "Incorporating Ready Time". var throughputThreadAllocation = new Dictionary<string, double>(); // Thread allocation suggestion for each stage foreach (var stage in wallClockPerRequest.Keys) { // cores is p // numberOfRequests is q // cpuPerRequest is x // stableReadyTimeProportion is alpha // waitTimes is w throughputThreadAllocation.Add(stage, cores * numberOfRequests[stage] * (cpuPerRequest[stage] * (1 + stableReadyTimeProportion) + waitTimes[stage]) / cpuSum); } double sum1 = 0; foreach (var stage in s.Keys) sum1 += lambda[stage]*beta[stage]/s[stage]; double sum2 = 0; foreach (var stage in s.Keys) sum2 += Math.Sqrt(lambda[stage]*beta[stage]/s[stage]); var latencyThreadAllocation = new Dictionary<string, double>(); // Latency thread allocation suggestion for each stage foreach (var stage in wallClockPerRequest.Keys) latencyThreadAllocation.Add(stage, lambda[stage]/s[stage] + Math.Sqrt(lambda[stage])*(cores - sum1)/(Math.Sqrt(s[stage]*beta[stage])*sum2)); var latencyPenalizedThreadAllocationConst = new Dictionary<string, double>(); var latencyPenalizedThreadAllocationCoef = new Dictionary<string, double>(); foreach (var stage in wallClockPerRequest.Keys) { latencyPenalizedThreadAllocationConst.Add(stage, lambda[stage] / s[stage]); latencyPenalizedThreadAllocationCoef.Add(stage, Math.Sqrt(lambda[stage] / (lambda[firstStage] * s[stage]))); } double sum3 = 0; foreach (var stage in s.Keys) sum3 += beta[stage]*Math.Sqrt(lambda[stage]/s[stage]); double zeta = Math.Pow(sum3 / (cores - sum1), 2) / lambda[firstStage]; var sb = new StringBuilder(); sb.AppendLine(); sb.AppendLine(); sb.AppendLine("zeta: " + zeta); sb.AppendLine(); foreach (var stage in stages.Intersect(wallClockPerRequest.Keys)) { sb.AppendLine("Stage: " + stage); sb.AppendLine(" Measured average CPU per request: " + cpuPerRequest[stage].ToString("F3") + " ms"); sb.AppendLine(" Measured average Wall-clock per request: " + wallClockPerRequest[stage].ToString("F3") + " ms"); sb.AppendLine(" Measured number of requests: " + numberOfRequests[stage].ToString("F0") + " requests"); sb.AppendLine(" lambda: " + lambda[stage].ToString("F3") + " arrival rate requests/sec"); sb.AppendLine(" s: " + s[stage].ToString("F3") + " per thread service rate requests/sec"); sb.AppendLine(" beta: " + beta[stage].ToString("F3") + " per thread CPU usage"); sb.AppendLine(" Estimated wait time: " + waitTimes[stage].ToString("F3") + " ms"); sb.AppendLine(" Throughput thread allocation: " + Math.Ceiling(throughputThreadAllocation[stage]) + " threads (rounded up from " + throughputThreadAllocation[stage].ToString("F3") + ")"); sb.AppendLine(" Latency thread allocation: " + Math.Ceiling(latencyThreadAllocation[stage]) + " threads (rounded up from " + latencyThreadAllocation[stage].ToString("F3") + ")"); sb.AppendLine(" Regularlized latency thread allocation: " + latencyPenalizedThreadAllocationConst[stage].ToString("F3") + " + " + latencyPenalizedThreadAllocationCoef[stage].ToString("F3") + " / sqrt(eta) threads (rounded this value up)"); } var cpuBreakdown = new Dictionary<string, double>(); foreach (var stage in cpuPerRequest.Keys) { double val = (numberOfRequests[stage] * cpuPerRequest[stage]) / (cores * elapsedWallClock); cpuBreakdown.Add(stage == "ThreadPoolThread" ? "ThreadPoolThread.AsynchronousReceive" : stage, val); } cpuBreakdown.Add("Untracked", untrackedProportionTime); sb.AppendLine(); sb.AppendLine("CPU usage by thread type:"); foreach (var v in cpuBreakdown.OrderByDescending(key => key.Value)) sb.AppendLine(" " + v.Value.ToString("F3") + ", " + v.Key); sb.AppendLine(); sb.Append("EndStageAnalysis"); return sb.ToString(); } } catch (Exception e) { return e + Environment.NewLine + e.StackTrace; } } /// <summary> /// get all cpu used by all types of threads /// </summary> /// <returns> milliseconds of total cpu time </returns> private double GetTotalCPU() { double total = 0; foreach (var keyVal in stageGroups) foreach (var statistics in keyVal.Value) total += statistics.ExecutingCpuCycleTime.Elapsed.TotalMilliseconds; return total; } /// <summary> /// gets total wallclock which is the wallclock of the stage with maximum wallclock time /// </summary> private double GetMaxWallClock() { double maxTime = 0; foreach (var keyVal in stageGroups) foreach (var statistics in keyVal.Value) maxTime = Math.Max(maxTime, statistics.ExecutingWallClockTime.Elapsed.TotalMilliseconds); maxTime -= 60 * 1000; // warmup time for grains needs to be subtracted return maxTime; } /// <summary> /// get number of requests for a stage /// </summary> /// <param name="stageName">name of a stage from thread tracking statistics</param> /// <returns>number of requests</returns> private double GetNumberOfRequests(string stageName) { if (stageName == "Untracked.ThreadPoolThread") return 1; double num = 0; if (!stageGroups.TryGetValue(stageName, out var groups)) return 0; foreach (var tts in groups) num += tts.NumRequests; return num; } /// <summary> /// get wall clock time for a request of a stage /// </summary> /// <param name="stageName">name of a stage from thread tracking statistics</param> /// <returns>average milliseconds of wallclock time per request</returns> private double GetWallClockPerStagePerRequest(string stageName) { double sum = 0; if (!stageGroups.TryGetValue(stageName, out var groups)) return 0; foreach (var statistics in groups) if (stageName == "ThreadPoolThread") { sum += statistics.ProcessingWallClockTime.Elapsed.TotalMilliseconds; } else { sum += statistics.ProcessingWallClockTime.Elapsed.TotalMilliseconds; // We need to add the pure Take time, since in the GetCpuPerStagePerRequest we includes both processingCPUCycleTime and the Take time. TimeSpan takeCPUCycles = statistics.ExecutingCpuCycleTime.Elapsed - statistics.ProcessingCpuCycleTime.Elapsed; sum += takeCPUCycles.TotalMilliseconds; } return sum / GetNumberOfRequests(stageName); } /// <summary> /// get cpu time for a request of a stage /// </summary> /// <param name="stageName">name of a stage from thread tracking statistics</param> /// <returns>average milliseconds of cpu time per request</returns> private double GetCpuPerStagePerRequest(string stageName) { double sum = 0; if (stageName == "Untracked.ThreadPoolThread") { foreach (var statistics in stageGroups["ThreadPoolThread"]) { sum += statistics.ExecutingCpuCycleTime.Elapsed.TotalMilliseconds; sum -= statistics.ProcessingCpuCycleTime.Elapsed.TotalMilliseconds; } return sum; } if (!stageGroups.TryGetValue(stageName, out var groups)) return 0; foreach (var statistics in groups) { if (stageName == "ThreadPoolThread") { sum += statistics.ProcessingCpuCycleTime.Elapsed.TotalMilliseconds; } else { // this includes both processingCPUCycleTime and the Take time. sum += statistics.ExecutingCpuCycleTime.Elapsed.TotalMilliseconds; } } return sum / GetNumberOfRequests(stageName); } } }
// Code generated by Microsoft (R) AutoRest Code Generator 1.1.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace ApplicationGateway { using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// PublicIPAddressesOperations operations. /// </summary> internal partial class PublicIPAddressesOperations : IServiceOperations<NetworkClient>, IPublicIPAddressesOperations { /// <summary> /// Initializes a new instance of the PublicIPAddressesOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal PublicIPAddressesOperations(NetworkClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the NetworkClient /// </summary> public NetworkClient Client { get; private set; } /// <summary> /// Deletes the specified public IP address. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='publicIpAddressName'> /// The name of the subnet. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string publicIpAddressName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send request AzureOperationResponse _response = await BeginDeleteWithHttpMessagesAsync(resourceGroupName, publicIpAddressName, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets the specified public IP address in a specified resource group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='publicIpAddressName'> /// The name of the subnet. /// </param> /// <param name='expand'> /// Expands referenced resources. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<PublicIPAddress>> GetWithHttpMessagesAsync(string resourceGroupName, string publicIpAddressName, string expand = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (publicIpAddressName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "publicIpAddressName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2016-12-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("publicIpAddressName", publicIpAddressName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("expand", expand); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/publicIPAddresses/{publicIpAddressName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{publicIpAddressName}", System.Uri.EscapeDataString(publicIpAddressName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (expand != null) { _queryParameters.Add(string.Format("$expand={0}", System.Uri.EscapeDataString(expand))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<PublicIPAddress>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<PublicIPAddress>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Creates or updates a static or dynamic public IP address. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='publicIpAddressName'> /// The name of the public IP address. /// </param> /// <param name='parameters'> /// Parameters supplied to the create or update public IP address operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<PublicIPAddress>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string publicIpAddressName, PublicIPAddress parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send Request AzureOperationResponse<PublicIPAddress> _response = await BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, publicIpAddressName, parameters, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets all the public IP addresses in a subscription. /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<PublicIPAddress>>> ListAllWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2016-12-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListAll", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.Network/publicIPAddresses").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<PublicIPAddress>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<PublicIPAddress>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets all public IP addresses in a resource group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<PublicIPAddress>>> ListWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2016-12-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/publicIPAddresses").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<PublicIPAddress>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<PublicIPAddress>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Deletes the specified public IP address. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='publicIpAddressName'> /// The name of the subnet. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string publicIpAddressName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (publicIpAddressName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "publicIpAddressName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2016-12-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("publicIpAddressName", publicIpAddressName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginDelete", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/publicIPAddresses/{publicIpAddressName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{publicIpAddressName}", System.Uri.EscapeDataString(publicIpAddressName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("DELETE"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 204 && (int)_statusCode != 202 && (int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Creates or updates a static or dynamic public IP address. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='publicIpAddressName'> /// The name of the public IP address. /// </param> /// <param name='parameters'> /// Parameters supplied to the create or update public IP address operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<PublicIPAddress>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string publicIpAddressName, PublicIPAddress parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (publicIpAddressName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "publicIpAddressName"); } if (parameters == null) { throw new ValidationException(ValidationRules.CannotBeNull, "parameters"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2016-12-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("publicIpAddressName", publicIpAddressName); tracingParameters.Add("parameters", parameters); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginCreateOrUpdate", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/publicIPAddresses/{publicIpAddressName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{publicIpAddressName}", System.Uri.EscapeDataString(publicIpAddressName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(parameters != null) { _requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 201 && (int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<PublicIPAddress>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 201) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<PublicIPAddress>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<PublicIPAddress>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets all the public IP addresses in a subscription. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<PublicIPAddress>>> ListAllNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListAllNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<PublicIPAddress>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<PublicIPAddress>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets all public IP addresses in a resource group. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<PublicIPAddress>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<PublicIPAddress>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<PublicIPAddress>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for details. using System; using System.Drawing; using System.Globalization; using System.Diagnostics; using OpenLiveWriter.Mshtml; using OpenLiveWriter.CoreServices; using OpenLiveWriter.PostEditor.ContentSources; using mshtml ; namespace OpenLiveWriter.PostEditor.Tables { internal sealed class TableHelper { public static IHTMLTable GetContainingTableElement( IHTMLElement element ) { // search up the parent heirarchy while ( element != null ) { if ( element is IHTMLTable ) { return element as IHTMLTable; } // search parent element = element.parentElement ; } // didn't find a table return null ; } public static IHTMLTableRow GetContainingRowElement( IHTMLTableCell cell ) { // search up the parent heirarchy IHTMLElement element = cell as IHTMLElement ; while ( element != null ) { if ( element is IHTMLTableRow ) { return element as IHTMLTableRow; } // search parent element = element.parentElement ; } // didn't find a table row return null ; } public static int GetCellWidth(IHTMLTableCell cell) { if ( cell.width != null ) { try { return int.Parse(cell.width.ToString(), CultureInfo.InvariantCulture) ; } catch { return (cell as IHTMLElement).offsetWidth ; } } else { return (cell as IHTMLElement).offsetWidth ; } } public static int GetParentContainerBlockWidth(MarkupRange markupRange) { IHTMLElement2 parentBlock = markupRange.Start.GetParentElement(ElementFilters.BLOCK_OR_TABLE_CELL_ELEMENTS) as IHTMLElement2 ; if ( parentBlock != null ) { // TODO: we would like to always clientWidth here however for an empty block element this will // be zero. So in this case we use scrollWidth which should be a proxy except in the case where // the parent element has a horizontal scroll bar (in which case we may insert a table which // is worst case too narrow). What we "should" do is insert and remove some bogus content // within the block elemet to force its clientWidth to the right value. int blockWidth = parentBlock.clientWidth ; if ( blockWidth == 0 ) blockWidth = parentBlock.scrollWidth ; return blockWidth ; } else { return 0 ; } } public static int GetTableWidth(IHTMLTable table) { if ( table.width != null ) { try { return int.Parse(table.width.ToString(), CultureInfo.InvariantCulture) ; } catch { return 0 ; } } else { return 0 ; } } public static int GetRowHeight(IHTMLTableRow row) { IHTMLTableRow2 row2 = row as IHTMLTableRow2 ; if ( row2.height != null ) { try { return int.Parse(row2.height.ToString(), CultureInfo.InvariantCulture) ; } catch { return 0 ; } } else { return 0 ; } } public static int GetTableLogicalEditingWidth(IHTMLTable table) { // value to return (default to zero) int logicalWidth = 0 ; // calculate the "logical" width of the table if ( table.rows.length > 0 ) { // save value of cellSpacing int cellSpacing = GetAttributeAsInteger(table.cellSpacing) ; // use the first row as a proxy for the width of the table IHTMLTableRow firstRow = table.rows.item(0,0) as IHTMLTableRow ; foreach (IHTMLTableCell cell in firstRow.cells ) logicalWidth += GetCellWidth(cell) + cellSpacing ; // total width + extra cellspacing @ end + size of borders return logicalWidth + cellSpacing + GetTableBorderEditingOffset(table) ; } // return width return logicalWidth ; } public static void SynchronizeCellWidthsForEditing(IHTMLTable table) { // resize the cells in the table to match their actual width foreach (IHTMLTableCell cell in (table as IHTMLElement2).getElementsByTagName("th")) SynchronizeCellWidthForEditing(cell) ; foreach (IHTMLTableCell cell in (table as IHTMLElement2).getElementsByTagName("td")) SynchronizeCellWidthForEditing(cell) ; } public static void SynchronizeCellWidthForEditing(IHTMLTableCell cell) { if ( GetCellWidth(cell) != ((cell as IHTMLElement).offsetWidth ) ) cell.width = (cell as IHTMLElement).offsetWidth ; } public static void SynchronizeTableWidthForEditing(IHTMLTable table) { int logicalWidth = TableHelper.GetTableLogicalEditingWidth(table) ; if ( logicalWidth > 0 ) table.width = logicalWidth ; else (table as IHTMLElement).removeAttribute("width", 0) ; } public static void SynchronizeCellAndTableWidthsForEditing(IHTMLTable table) { SynchronizeCellWidthsForEditing(table) ; SynchronizeTableWidthForEditing(table) ; } public static Color GetColorForHtmlColor(object color) { if ( color == null ) return Color.Empty ; else return ColorHelper.StringToColor(color.ToString()) ; } public static HorizontalAlignment GetAlignmentForHtmlAlignment(string alignment) { if ( alignment == null ) return HorizontalAlignment.Left ; else if ( alignment == "left" ) return HorizontalAlignment.Left ; else if ( alignment == "center" ) return HorizontalAlignment.Center ; else if ( alignment == "right" ) return HorizontalAlignment.Right ; else return HorizontalAlignment.Left ; } public static string GetHtmlAlignmentForAlignment(HorizontalAlignment alignment) { switch( alignment ) { case HorizontalAlignment.Left: return "left" ; case HorizontalAlignment.Center: return "center"; case HorizontalAlignment.Right: return "right"; default: return String.Empty ; } } public static VerticalAlignment GetVAlignmentForHtmlAlignment(string alignment) { if ( alignment == null ) return VerticalAlignment.Middle ; else if ( alignment == "top" ) return VerticalAlignment.Top ; else if ( alignment == "middle" ) return VerticalAlignment.Middle ; else if ( alignment == "bottom" ) return VerticalAlignment.Bottom ; else return VerticalAlignment.Middle ; } public static string GetHtmlAlignmentForVAlignment(VerticalAlignment alignment) { switch( alignment ) { case VerticalAlignment.Top: return "top" ; case VerticalAlignment.Middle: return "middle"; case VerticalAlignment.Bottom: return "bottom"; default: return String.Empty ; } } public static void UpdateDesignTimeBorders(IHTMLTable table) { // update the table's borders UpdateDesignTimeBorders(table, table as IHTMLElement2) ; // update the contained cell borders foreach (IHTMLTableRow row in table.rows) foreach(IHTMLTableCell cell in row.cells) UpdateDesignTimeBorders(table, cell as IHTMLElement2) ; } public static void UpdateDesignTimeBorders(IHTMLTable table, IHTMLElement2 tableElement) { // don't do anything if there is a css-based border on this element if ( (tableElement as IHTMLElement).style.borderStyle != null ) return ; // don't attach if is there a standard table border if ( table.border != null && table.border.ToString() != "0" ) { RemoveDesignTimeBorder(table, tableElement) ; } else { AttachDesignTimeBorder(table, tableElement) ; } } private static void AttachDesignTimeBorder(IHTMLTable table, IHTMLElement2 tableElement) { // attach design time border tableElement.runtimeStyle.borderWidth = "1" ; tableElement.runtimeStyle.borderColor = "#BCBCBC" ; tableElement.runtimeStyle.borderStyle = "dotted" ; // collapse cells if there is no cellspacing if ( (table.cellSpacing == null) || table.cellSpacing.ToString() != "0" ) (tableElement.runtimeStyle as IHTMLStyle2).borderCollapse = "separate" ; else (tableElement.runtimeStyle as IHTMLStyle2).borderCollapse = "collapse" ; } private static void RemoveDesignTimeBorder(IHTMLTable table, IHTMLElement2 tableElement) { IHTMLElement element = tableElement as IHTMLElement ; tableElement.runtimeStyle.borderWidth = element.style.borderWidth ; tableElement.runtimeStyle.borderColor = element.style.borderColor ; tableElement.runtimeStyle.borderStyle = element.style.borderStyle ; (tableElement.runtimeStyle as IHTMLStyle2).borderCollapse = (element.style as IHTMLStyle2).borderCollapse ; } public static int GetTableBorderEditingOffset(IHTMLTable table) { int borderOffset = GetAttributeAsInteger(table.border)*2 ; if ( borderOffset == 0 ) { // respect css border width IHTMLElement tableElement = table as IHTMLElement ; borderOffset = GetAttributeAsInteger(tableElement.style.borderWidth) * 2 ; // if no css border width, we know the total border width is 2 (b/c we // add a one pixel border for editing) if ( borderOffset == 0 ) borderOffset = 2 ; } // return width return borderOffset ; } public static int GetAttributeAsInteger(object value) { if ( value != null ) { try { return int.Parse(value.ToString(), CultureInfo.InvariantCulture) ; } catch { return 0 ; } } else { return 0 ; } } /// <summary> /// Only edit tables that are not contained within SmartContent blocks and which /// are marked with the "unselectable" attribute. Since this is an attribute which /// applies only to editing scenarios it is almost certain never to enter the editor /// "from the wild" so it is a reasonable way to determine whether we created the /// table (and thus can guarantee that it conforms to our editing capabilities). The /// only other reasonable choice would be to mark the table up with some other /// pseudo-hidden metadata, which seems even more undesirable. /// </summary> public static bool TableElementIsEditable(IHTMLElement element) { return TableElementContainsWriterEditingMark(element) && !ContentSourceManager.IsSmartContent(element); } /// <summary> /// Only edit tables that are not contained within SmartContent blocks and which /// are marked with the "unselectable" attribute. Since this is an attribute which /// applies only to editing scenarios it is almost certain never to enter the editor /// "from the wild" so it is a reasonable way to determine whether we created the /// table (and thus can guarantee that it conforms to our editing capabilities). The /// only other reasonable choice would be to mark the table up with some other /// pseudo-hidden metadata, which seems even more undesirable. /// </summary> public static bool TableElementIsEditable(IHTMLElement element, MarkupRange elementMarkupRange) { return TableElementContainsWriterEditingMark(element) && !TableElementIsContainedInSmartContent(elementMarkupRange) ; } public static bool TableElementContainsWriterEditingMark(IHTMLElement element) { return TableElementIsContainedInUnselectableTable(element) ; } public static void MakeTableWriterEditableIfRectangular(IHTMLTable table) { try { // no-op for null table if ( table == null ) return ; // no-op if we are already unselectable IHTMLElement tableElement = table as IHTMLElement ; if ( TableElementContainsWriterEditingMark(tableElement) ) return ; // check for rectangular structure int tableColumnCount = -1 ; foreach ( IHTMLTableRow row in table.rows ) { int columnCount = row.cells.length ; if ( tableColumnCount == -1 ) { // initilize table column count if this is the first pass tableColumnCount = columnCount ; } else { // compare this rows column count with the table column // count -- if they are not equal then exit function if ( columnCount != tableColumnCount ) return ; } } // if we made it this far then the table is rectangular, so // mark it with our "editable" sentinel tableElement.setAttribute("unselectable", "on", 0); } catch(Exception ex) { Trace.Fail("Unexpected error in MakeTableWriterEditableIfRectangular: " + ex.ToString()); } } private static bool TableElementIsContainedInUnselectableTable(IHTMLElement element) { IHTMLTable table = TableHelper.GetContainingTableElement(element) ; if ( table != null ) { object unselectable = (table as IHTMLElement).getAttribute("unselectable", 0); if ( unselectable != null ) return unselectable.ToString() == "on" ; else return false ; } else { return false ; } } private static bool TableElementIsContainedInSmartContent(MarkupRange elementRange) { // table elements inside smart content regions are not editable IHTMLElement parentSmartContent = elementRange.Start.GetParentElement(ContentSourceManager.CreateSmartContentElementFilter()); return parentSmartContent != null ; } } }
#if (UNITY_WINRT || UNITY_WP_8_1) && !UNITY_EDITOR && !UNITY_WP8 #region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections; using System.Collections.Generic; using System.Reflection; using System.Runtime.Serialization; using Newtonsoft.Json.Linq; using Newtonsoft.Json.Utilities; namespace Newtonsoft.Json.Serialization { internal enum JsonContractType { None, Object, Array, Primitive, String, Dictionary, Dynamic, Linq } /// <summary> /// Handles <see cref="JsonSerializer"/> serialization callback events. /// </summary> /// <param name="o">The object that raised the callback event.</param> /// <param name="context">The streaming context.</param> public delegate void SerializationCallback(object o, StreamingContext context); /// <summary> /// Handles <see cref="JsonSerializer"/> serialization error callback events. /// </summary> /// <param name="o">The object that raised the callback event.</param> /// <param name="context">The streaming context.</param> /// <param name="errorContext">The error context.</param> public delegate void SerializationErrorCallback(object o, StreamingContext context, ErrorContext errorContext); /// <summary> /// Sets extension data for an object during deserialization. /// </summary> /// <param name="o">The object to set extension data on.</param> /// <param name="key">The extension data key.</param> /// <param name="value">The extension data value.</param> public delegate void ExtensionDataSetter(object o, string key, object value); /// <summary> /// Gets extension data for an object during serialization. /// </summary> /// <param name="o">The object to set extension data on.</param> public delegate IEnumerable<KeyValuePair<object, object>> ExtensionDataGetter(object o); /// <summary> /// Contract details for a <see cref="Type"/> used by the <see cref="JsonSerializer"/>. /// </summary> public abstract class JsonContract { internal bool IsNullable; internal bool IsConvertable; internal bool IsSealed; internal bool IsEnum; internal Type NonNullableUnderlyingType; internal ReadType InternalReadType; internal JsonContractType ContractType; internal bool IsReadOnlyOrFixedSize; internal bool IsInstantiable; private List<SerializationCallback> _onDeserializedCallbacks; private IList<SerializationCallback> _onDeserializingCallbacks; private IList<SerializationCallback> _onSerializedCallbacks; private IList<SerializationCallback> _onSerializingCallbacks; private IList<SerializationErrorCallback> _onErrorCallbacks; /// <summary> /// Gets the underlying type for the contract. /// </summary> /// <value>The underlying type for the contract.</value> public Type UnderlyingType { get; private set; } /// <summary> /// Gets or sets the type created during deserialization. /// </summary> /// <value>The type created during deserialization.</value> public Type CreatedType { get; set; } /// <summary> /// Gets or sets whether this type contract is serialized as a reference. /// </summary> /// <value>Whether this type contract is serialized as a reference.</value> public bool? IsReference { get; set; } /// <summary> /// Gets or sets the default <see cref="JsonConverter" /> for this contract. /// </summary> /// <value>The converter.</value> public JsonConverter Converter { get; set; } // internally specified JsonConverter's to override default behavour // checked for after passed in converters and attribute specified converters internal JsonConverter InternalConverter { get; set; } /// <summary> /// Gets or sets all methods called immediately after deserialization of the object. /// </summary> /// <value>The methods called immediately after deserialization of the object.</value> public IList<SerializationCallback> OnDeserializedCallbacks { get { if (_onDeserializedCallbacks == null) _onDeserializedCallbacks = new List<SerializationCallback>(); return _onDeserializedCallbacks; } } /// <summary> /// Gets or sets all methods called during deserialization of the object. /// </summary> /// <value>The methods called during deserialization of the object.</value> public IList<SerializationCallback> OnDeserializingCallbacks { get { if (_onDeserializingCallbacks == null) _onDeserializingCallbacks = new List<SerializationCallback>(); return _onDeserializingCallbacks; } } /// <summary> /// Gets or sets all methods called after serialization of the object graph. /// </summary> /// <value>The methods called after serialization of the object graph.</value> public IList<SerializationCallback> OnSerializedCallbacks { get { if (_onSerializedCallbacks == null) _onSerializedCallbacks = new List<SerializationCallback>(); return _onSerializedCallbacks; } } /// <summary> /// Gets or sets all methods called before serialization of the object. /// </summary> /// <value>The methods called before serialization of the object.</value> public IList<SerializationCallback> OnSerializingCallbacks { get { if (_onSerializingCallbacks == null) _onSerializingCallbacks = new List<SerializationCallback>(); return _onSerializingCallbacks; } } /// <summary> /// Gets or sets all method called when an error is thrown during the serialization of the object. /// </summary> /// <value>The methods called when an error is thrown during the serialization of the object.</value> public IList<SerializationErrorCallback> OnErrorCallbacks { get { if (_onErrorCallbacks == null) _onErrorCallbacks = new List<SerializationErrorCallback>(); return _onErrorCallbacks; } } /// <summary> /// Gets or sets the method called immediately after deserialization of the object. /// </summary> /// <value>The method called immediately after deserialization of the object.</value> [Obsolete("This property is obsolete and has been replaced by the OnDeserializedCallbacks collection.")] public MethodInfo OnDeserialized { get { return (OnDeserializedCallbacks.Count > 0) ? OnDeserializedCallbacks[0].Method() : null; } set { OnDeserializedCallbacks.Clear(); OnDeserializedCallbacks.Add(CreateSerializationCallback(value)); } } /// <summary> /// Gets or sets the method called during deserialization of the object. /// </summary> /// <value>The method called during deserialization of the object.</value> [Obsolete("This property is obsolete and has been replaced by the OnDeserializingCallbacks collection.")] public MethodInfo OnDeserializing { get { return (OnDeserializingCallbacks.Count > 0) ? OnDeserializingCallbacks[0].Method() : null; } set { OnDeserializingCallbacks.Clear(); OnDeserializingCallbacks.Add(CreateSerializationCallback(value)); } } /// <summary> /// Gets or sets the method called after serialization of the object graph. /// </summary> /// <value>The method called after serialization of the object graph.</value> [Obsolete("This property is obsolete and has been replaced by the OnSerializedCallbacks collection.")] public MethodInfo OnSerialized { get { return (OnSerializedCallbacks.Count > 0) ? OnSerializedCallbacks[0].Method() : null; } set { OnSerializedCallbacks.Clear(); OnSerializedCallbacks.Add(CreateSerializationCallback(value)); } } /// <summary> /// Gets or sets the method called before serialization of the object. /// </summary> /// <value>The method called before serialization of the object.</value> [Obsolete("This property is obsolete and has been replaced by the OnSerializingCallbacks collection.")] public MethodInfo OnSerializing { get { return (OnSerializingCallbacks.Count > 0) ? OnSerializingCallbacks[0].Method() : null; } set { OnSerializingCallbacks.Clear(); OnSerializingCallbacks.Add(CreateSerializationCallback(value)); } } /// <summary> /// Gets or sets the method called when an error is thrown during the serialization of the object. /// </summary> /// <value>The method called when an error is thrown during the serialization of the object.</value> [Obsolete("This property is obsolete and has been replaced by the OnErrorCallbacks collection.")] public MethodInfo OnError { get { return (OnErrorCallbacks.Count > 0) ? OnErrorCallbacks[0].Method() : null; } set { OnErrorCallbacks.Clear(); OnErrorCallbacks.Add(CreateSerializationErrorCallback(value)); } } /// <summary> /// Gets or sets the default creator method used to create the object. /// </summary> /// <value>The default creator method used to create the object.</value> public Func<object> DefaultCreator { get; set; } /// <summary> /// Gets or sets a value indicating whether the default creator is non public. /// </summary> /// <value><c>true</c> if the default object creator is non-public; otherwise, <c>false</c>.</value> public bool DefaultCreatorNonPublic { get; set; } internal JsonContract(Type underlyingType) { ValidationUtils.ArgumentNotNull(underlyingType, "underlyingType"); UnderlyingType = underlyingType; IsSealed = underlyingType.IsSealed(); IsInstantiable = !(underlyingType.IsInterface() || underlyingType.IsAbstract()); IsNullable = ReflectionUtils.IsNullable(underlyingType); NonNullableUnderlyingType = (IsNullable && ReflectionUtils.IsNullableType(underlyingType)) ? Nullable.GetUnderlyingType(underlyingType) : underlyingType; CreatedType = NonNullableUnderlyingType; IsConvertable = ConvertUtils.IsConvertible(NonNullableUnderlyingType); IsEnum = NonNullableUnderlyingType.IsEnum(); if (NonNullableUnderlyingType == typeof(byte[])) { InternalReadType = ReadType.ReadAsBytes; } else if (NonNullableUnderlyingType == typeof(int)) { InternalReadType = ReadType.ReadAsInt32; } else if (NonNullableUnderlyingType == typeof(decimal)) { InternalReadType = ReadType.ReadAsDecimal; } else if (NonNullableUnderlyingType == typeof(string)) { InternalReadType = ReadType.ReadAsString; } else if (NonNullableUnderlyingType == typeof(DateTime)) { InternalReadType = ReadType.ReadAsDateTime; } else if (NonNullableUnderlyingType == typeof(DateTimeOffset)) { InternalReadType = ReadType.ReadAsDateTimeOffset; } else { InternalReadType = ReadType.Read; } } internal void InvokeOnSerializing(object o, StreamingContext context) { if (_onSerializingCallbacks != null) { foreach (SerializationCallback callback in _onSerializingCallbacks) { callback(o, context); } } } internal void InvokeOnSerialized(object o, StreamingContext context) { if (_onSerializedCallbacks != null) { foreach (SerializationCallback callback in _onSerializedCallbacks) { callback(o, context); } } } internal void InvokeOnDeserializing(object o, StreamingContext context) { if (_onDeserializingCallbacks != null) { foreach (SerializationCallback callback in _onDeserializingCallbacks) { callback(o, context); } } } internal void InvokeOnDeserialized(object o, StreamingContext context) { if (_onDeserializedCallbacks != null) { foreach (SerializationCallback callback in _onDeserializedCallbacks) { callback(o, context); } } } internal void InvokeOnError(object o, StreamingContext context, ErrorContext errorContext) { if (_onErrorCallbacks != null) { foreach (SerializationErrorCallback callback in _onErrorCallbacks) { callback(o, context, errorContext); } } } internal static SerializationCallback CreateSerializationCallback(MethodInfo callbackMethodInfo) { return (o, context) => callbackMethodInfo.Invoke(o, new object[] { context }); } internal static SerializationErrorCallback CreateSerializationErrorCallback(MethodInfo callbackMethodInfo) { return (o, context, econtext) => callbackMethodInfo.Invoke(o, new object[] { context, econtext }); } } } #endif
/* * Copyright 2021 Google LLC All Rights Reserved. * Use of this source code is governed by a BSD-style * license that can be found in the LICENSE file or at * https://developers.google.com/open-source/licenses/bsd */ // <auto-generated> // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/api/monitored_resource.proto // </auto-generated> #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace Google.Api { /// <summary>Holder for reflection information generated from google/api/monitored_resource.proto</summary> public static partial class MonitoredResourceReflection { #region Descriptor /// <summary>File descriptor for google/api/monitored_resource.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static MonitoredResourceReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "CiNnb29nbGUvYXBpL21vbml0b3JlZF9yZXNvdXJjZS5wcm90bxIKZ29vZ2xl", "LmFwaRoWZ29vZ2xlL2FwaS9sYWJlbC5wcm90bxodZ29vZ2xlL2FwaS9sYXVu", "Y2hfc3RhZ2UucHJvdG8aHGdvb2dsZS9wcm90b2J1Zi9zdHJ1Y3QucHJvdG8i", "wAEKG01vbml0b3JlZFJlc291cmNlRGVzY3JpcHRvchIMCgRuYW1lGAUgASgJ", "EgwKBHR5cGUYASABKAkSFAoMZGlzcGxheV9uYW1lGAIgASgJEhMKC2Rlc2Ny", "aXB0aW9uGAMgASgJEisKBmxhYmVscxgEIAMoCzIbLmdvb2dsZS5hcGkuTGFi", "ZWxEZXNjcmlwdG9yEi0KDGxhdW5jaF9zdGFnZRgHIAEoDjIXLmdvb2dsZS5h", "cGkuTGF1bmNoU3RhZ2UiiwEKEU1vbml0b3JlZFJlc291cmNlEgwKBHR5cGUY", "ASABKAkSOQoGbGFiZWxzGAIgAygLMikuZ29vZ2xlLmFwaS5Nb25pdG9yZWRS", "ZXNvdXJjZS5MYWJlbHNFbnRyeRotCgtMYWJlbHNFbnRyeRILCgNrZXkYASAB", "KAkSDQoFdmFsdWUYAiABKAk6AjgBIsoBChlNb25pdG9yZWRSZXNvdXJjZU1l", "dGFkYXRhEi4KDXN5c3RlbV9sYWJlbHMYASABKAsyFy5nb29nbGUucHJvdG9i", "dWYuU3RydWN0EkoKC3VzZXJfbGFiZWxzGAIgAygLMjUuZ29vZ2xlLmFwaS5N", "b25pdG9yZWRSZXNvdXJjZU1ldGFkYXRhLlVzZXJMYWJlbHNFbnRyeRoxCg9V", "c2VyTGFiZWxzRW50cnkSCwoDa2V5GAEgASgJEg0KBXZhbHVlGAIgASgJOgI4", "AUJ5Cg5jb20uZ29vZ2xlLmFwaUIWTW9uaXRvcmVkUmVzb3VyY2VQcm90b1AB", "WkNnb29nbGUuZ29sYW5nLm9yZy9nZW5wcm90by9nb29nbGVhcGlzL2FwaS9t", "b25pdG9yZWRyZXM7bW9uaXRvcmVkcmVz+AEBogIER0FQSWIGcHJvdG8z")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::Google.Api.LabelReflection.Descriptor, global::Google.Api.LaunchStageReflection.Descriptor, global::Google.Protobuf.WellKnownTypes.StructReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Api.MonitoredResourceDescriptor), global::Google.Api.MonitoredResourceDescriptor.Parser, new[]{ "Name", "Type", "DisplayName", "Description", "Labels", "LaunchStage" }, null, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Api.MonitoredResource), global::Google.Api.MonitoredResource.Parser, new[]{ "Type", "Labels" }, null, null, null, new pbr::GeneratedClrTypeInfo[] { null, }), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Api.MonitoredResourceMetadata), global::Google.Api.MonitoredResourceMetadata.Parser, new[]{ "SystemLabels", "UserLabels" }, null, null, null, new pbr::GeneratedClrTypeInfo[] { null, }) })); } #endregion } #region Messages /// <summary> /// An object that describes the schema of a [MonitoredResource][google.api.MonitoredResource] object using a /// type name and a set of labels. For example, the monitored resource /// descriptor for Google Compute Engine VM instances has a type of /// `"gce_instance"` and specifies the use of the labels `"instance_id"` and /// `"zone"` to identify particular VM instances. /// /// Different APIs can support different monitored resource types. APIs generally /// provide a `list` method that returns the monitored resource descriptors used /// by the API. /// </summary> public sealed partial class MonitoredResourceDescriptor : pb::IMessage<MonitoredResourceDescriptor> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { private static readonly pb::MessageParser<MonitoredResourceDescriptor> _parser = new pb::MessageParser<MonitoredResourceDescriptor>(() => new MonitoredResourceDescriptor()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<MonitoredResourceDescriptor> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Api.MonitoredResourceReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public MonitoredResourceDescriptor() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public MonitoredResourceDescriptor(MonitoredResourceDescriptor other) : this() { name_ = other.name_; type_ = other.type_; displayName_ = other.displayName_; description_ = other.description_; labels_ = other.labels_.Clone(); launchStage_ = other.launchStage_; _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public MonitoredResourceDescriptor Clone() { return new MonitoredResourceDescriptor(this); } /// <summary>Field number for the "name" field.</summary> public const int NameFieldNumber = 5; private string name_ = ""; /// <summary> /// Optional. The resource name of the monitored resource descriptor: /// `"projects/{project_id}/monitoredResourceDescriptors/{type}"` where /// {type} is the value of the `type` field in this object and /// {project_id} is a project ID that provides API-specific context for /// accessing the type. APIs that do not use project information can use the /// resource name format `"monitoredResourceDescriptors/{type}"`. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Name { get { return name_; } set { name_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "type" field.</summary> public const int TypeFieldNumber = 1; private string type_ = ""; /// <summary> /// Required. The monitored resource type. For example, the type /// `"cloudsql_database"` represents databases in Google Cloud SQL. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Type { get { return type_; } set { type_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "display_name" field.</summary> public const int DisplayNameFieldNumber = 2; private string displayName_ = ""; /// <summary> /// Optional. A concise name for the monitored resource type that might be /// displayed in user interfaces. It should be a Title Cased Noun Phrase, /// without any article or other determiners. For example, /// `"Google Cloud SQL Database"`. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string DisplayName { get { return displayName_; } set { displayName_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "description" field.</summary> public const int DescriptionFieldNumber = 3; private string description_ = ""; /// <summary> /// Optional. A detailed description of the monitored resource type that might /// be used in documentation. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Description { get { return description_; } set { description_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "labels" field.</summary> public const int LabelsFieldNumber = 4; private static readonly pb::FieldCodec<global::Google.Api.LabelDescriptor> _repeated_labels_codec = pb::FieldCodec.ForMessage(34, global::Google.Api.LabelDescriptor.Parser); private readonly pbc::RepeatedField<global::Google.Api.LabelDescriptor> labels_ = new pbc::RepeatedField<global::Google.Api.LabelDescriptor>(); /// <summary> /// Required. A set of labels used to describe instances of this monitored /// resource type. For example, an individual Google Cloud SQL database is /// identified by values for the labels `"database_id"` and `"zone"`. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<global::Google.Api.LabelDescriptor> Labels { get { return labels_; } } /// <summary>Field number for the "launch_stage" field.</summary> public const int LaunchStageFieldNumber = 7; private global::Google.Api.LaunchStage launchStage_ = global::Google.Api.LaunchStage.Unspecified; /// <summary> /// Optional. The launch stage of the monitored resource definition. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Api.LaunchStage LaunchStage { get { return launchStage_; } set { launchStage_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as MonitoredResourceDescriptor); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(MonitoredResourceDescriptor other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Name != other.Name) return false; if (Type != other.Type) return false; if (DisplayName != other.DisplayName) return false; if (Description != other.Description) return false; if(!labels_.Equals(other.labels_)) return false; if (LaunchStage != other.LaunchStage) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Name.Length != 0) hash ^= Name.GetHashCode(); if (Type.Length != 0) hash ^= Type.GetHashCode(); if (DisplayName.Length != 0) hash ^= DisplayName.GetHashCode(); if (Description.Length != 0) hash ^= Description.GetHashCode(); hash ^= labels_.GetHashCode(); if (LaunchStage != global::Google.Api.LaunchStage.Unspecified) hash ^= LaunchStage.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE output.WriteRawMessage(this); #else if (Type.Length != 0) { output.WriteRawTag(10); output.WriteString(Type); } if (DisplayName.Length != 0) { output.WriteRawTag(18); output.WriteString(DisplayName); } if (Description.Length != 0) { output.WriteRawTag(26); output.WriteString(Description); } labels_.WriteTo(output, _repeated_labels_codec); if (Name.Length != 0) { output.WriteRawTag(42); output.WriteString(Name); } if (LaunchStage != global::Google.Api.LaunchStage.Unspecified) { output.WriteRawTag(56); output.WriteEnum((int) LaunchStage); } if (_unknownFields != null) { _unknownFields.WriteTo(output); } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { if (Type.Length != 0) { output.WriteRawTag(10); output.WriteString(Type); } if (DisplayName.Length != 0) { output.WriteRawTag(18); output.WriteString(DisplayName); } if (Description.Length != 0) { output.WriteRawTag(26); output.WriteString(Description); } labels_.WriteTo(ref output, _repeated_labels_codec); if (Name.Length != 0) { output.WriteRawTag(42); output.WriteString(Name); } if (LaunchStage != global::Google.Api.LaunchStage.Unspecified) { output.WriteRawTag(56); output.WriteEnum((int) LaunchStage); } if (_unknownFields != null) { _unknownFields.WriteTo(ref output); } } #endif [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Name.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); } if (Type.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Type); } if (DisplayName.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(DisplayName); } if (Description.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Description); } size += labels_.CalculateSize(_repeated_labels_codec); if (LaunchStage != global::Google.Api.LaunchStage.Unspecified) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) LaunchStage); } if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(MonitoredResourceDescriptor other) { if (other == null) { return; } if (other.Name.Length != 0) { Name = other.Name; } if (other.Type.Length != 0) { Type = other.Type; } if (other.DisplayName.Length != 0) { DisplayName = other.DisplayName; } if (other.Description.Length != 0) { Description = other.Description; } labels_.Add(other.labels_); if (other.LaunchStage != global::Google.Api.LaunchStage.Unspecified) { LaunchStage = other.LaunchStage; } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 10: { Type = input.ReadString(); break; } case 18: { DisplayName = input.ReadString(); break; } case 26: { Description = input.ReadString(); break; } case 34: { labels_.AddEntriesFrom(input, _repeated_labels_codec); break; } case 42: { Name = input.ReadString(); break; } case 56: { LaunchStage = (global::Google.Api.LaunchStage) input.ReadEnum(); break; } } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; case 10: { Type = input.ReadString(); break; } case 18: { DisplayName = input.ReadString(); break; } case 26: { Description = input.ReadString(); break; } case 34: { labels_.AddEntriesFrom(ref input, _repeated_labels_codec); break; } case 42: { Name = input.ReadString(); break; } case 56: { LaunchStage = (global::Google.Api.LaunchStage) input.ReadEnum(); break; } } } } #endif } /// <summary> /// An object representing a resource that can be used for monitoring, logging, /// billing, or other purposes. Examples include virtual machine instances, /// databases, and storage devices such as disks. The `type` field identifies a /// [MonitoredResourceDescriptor][google.api.MonitoredResourceDescriptor] object that describes the resource's /// schema. Information in the `labels` field identifies the actual resource and /// its attributes according to the schema. For example, a particular Compute /// Engine VM instance could be represented by the following object, because the /// [MonitoredResourceDescriptor][google.api.MonitoredResourceDescriptor] for `"gce_instance"` has labels /// `"instance_id"` and `"zone"`: /// /// { "type": "gce_instance", /// "labels": { "instance_id": "12345678901234", /// "zone": "us-central1-a" }} /// </summary> public sealed partial class MonitoredResource : pb::IMessage<MonitoredResource> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { private static readonly pb::MessageParser<MonitoredResource> _parser = new pb::MessageParser<MonitoredResource>(() => new MonitoredResource()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<MonitoredResource> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Api.MonitoredResourceReflection.Descriptor.MessageTypes[1]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public MonitoredResource() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public MonitoredResource(MonitoredResource other) : this() { type_ = other.type_; labels_ = other.labels_.Clone(); _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public MonitoredResource Clone() { return new MonitoredResource(this); } /// <summary>Field number for the "type" field.</summary> public const int TypeFieldNumber = 1; private string type_ = ""; /// <summary> /// Required. The monitored resource type. This field must match /// the `type` field of a [MonitoredResourceDescriptor][google.api.MonitoredResourceDescriptor] object. For /// example, the type of a Compute Engine VM instance is `gce_instance`. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Type { get { return type_; } set { type_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "labels" field.</summary> public const int LabelsFieldNumber = 2; private static readonly pbc::MapField<string, string>.Codec _map_labels_codec = new pbc::MapField<string, string>.Codec(pb::FieldCodec.ForString(10, ""), pb::FieldCodec.ForString(18, ""), 18); private readonly pbc::MapField<string, string> labels_ = new pbc::MapField<string, string>(); /// <summary> /// Required. Values for all of the labels listed in the associated monitored /// resource descriptor. For example, Compute Engine VM instances use the /// labels `"project_id"`, `"instance_id"`, and `"zone"`. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::MapField<string, string> Labels { get { return labels_; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as MonitoredResource); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(MonitoredResource other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Type != other.Type) return false; if (!Labels.Equals(other.Labels)) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Type.Length != 0) hash ^= Type.GetHashCode(); hash ^= Labels.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE output.WriteRawMessage(this); #else if (Type.Length != 0) { output.WriteRawTag(10); output.WriteString(Type); } labels_.WriteTo(output, _map_labels_codec); if (_unknownFields != null) { _unknownFields.WriteTo(output); } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { if (Type.Length != 0) { output.WriteRawTag(10); output.WriteString(Type); } labels_.WriteTo(ref output, _map_labels_codec); if (_unknownFields != null) { _unknownFields.WriteTo(ref output); } } #endif [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Type.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Type); } size += labels_.CalculateSize(_map_labels_codec); if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(MonitoredResource other) { if (other == null) { return; } if (other.Type.Length != 0) { Type = other.Type; } labels_.Add(other.labels_); _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 10: { Type = input.ReadString(); break; } case 18: { labels_.AddEntriesFrom(input, _map_labels_codec); break; } } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; case 10: { Type = input.ReadString(); break; } case 18: { labels_.AddEntriesFrom(ref input, _map_labels_codec); break; } } } } #endif } /// <summary> /// Auxiliary metadata for a [MonitoredResource][google.api.MonitoredResource] object. /// [MonitoredResource][google.api.MonitoredResource] objects contain the minimum set of information to /// uniquely identify a monitored resource instance. There is some other useful /// auxiliary metadata. Monitoring and Logging use an ingestion /// pipeline to extract metadata for cloud resources of all types, and store /// the metadata in this message. /// </summary> public sealed partial class MonitoredResourceMetadata : pb::IMessage<MonitoredResourceMetadata> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { private static readonly pb::MessageParser<MonitoredResourceMetadata> _parser = new pb::MessageParser<MonitoredResourceMetadata>(() => new MonitoredResourceMetadata()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<MonitoredResourceMetadata> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Api.MonitoredResourceReflection.Descriptor.MessageTypes[2]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public MonitoredResourceMetadata() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public MonitoredResourceMetadata(MonitoredResourceMetadata other) : this() { systemLabels_ = other.systemLabels_ != null ? other.systemLabels_.Clone() : null; userLabels_ = other.userLabels_.Clone(); _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public MonitoredResourceMetadata Clone() { return new MonitoredResourceMetadata(this); } /// <summary>Field number for the "system_labels" field.</summary> public const int SystemLabelsFieldNumber = 1; private global::Google.Protobuf.WellKnownTypes.Struct systemLabels_; /// <summary> /// Output only. Values for predefined system metadata labels. /// System labels are a kind of metadata extracted by Google, including /// "machine_image", "vpc", "subnet_id", /// "security_group", "name", etc. /// System label values can be only strings, Boolean values, or a list of /// strings. For example: /// /// { "name": "my-test-instance", /// "security_group": ["a", "b", "c"], /// "spot_instance": false } /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Protobuf.WellKnownTypes.Struct SystemLabels { get { return systemLabels_; } set { systemLabels_ = value; } } /// <summary>Field number for the "user_labels" field.</summary> public const int UserLabelsFieldNumber = 2; private static readonly pbc::MapField<string, string>.Codec _map_userLabels_codec = new pbc::MapField<string, string>.Codec(pb::FieldCodec.ForString(10, ""), pb::FieldCodec.ForString(18, ""), 18); private readonly pbc::MapField<string, string> userLabels_ = new pbc::MapField<string, string>(); /// <summary> /// Output only. A map of user-defined metadata labels. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::MapField<string, string> UserLabels { get { return userLabels_; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as MonitoredResourceMetadata); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(MonitoredResourceMetadata other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (!object.Equals(SystemLabels, other.SystemLabels)) return false; if (!UserLabels.Equals(other.UserLabels)) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (systemLabels_ != null) hash ^= SystemLabels.GetHashCode(); hash ^= UserLabels.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE output.WriteRawMessage(this); #else if (systemLabels_ != null) { output.WriteRawTag(10); output.WriteMessage(SystemLabels); } userLabels_.WriteTo(output, _map_userLabels_codec); if (_unknownFields != null) { _unknownFields.WriteTo(output); } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { if (systemLabels_ != null) { output.WriteRawTag(10); output.WriteMessage(SystemLabels); } userLabels_.WriteTo(ref output, _map_userLabels_codec); if (_unknownFields != null) { _unknownFields.WriteTo(ref output); } } #endif [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (systemLabels_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(SystemLabels); } size += userLabels_.CalculateSize(_map_userLabels_codec); if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(MonitoredResourceMetadata other) { if (other == null) { return; } if (other.systemLabels_ != null) { if (systemLabels_ == null) { SystemLabels = new global::Google.Protobuf.WellKnownTypes.Struct(); } SystemLabels.MergeFrom(other.SystemLabels); } userLabels_.Add(other.userLabels_); _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 10: { if (systemLabels_ == null) { SystemLabels = new global::Google.Protobuf.WellKnownTypes.Struct(); } input.ReadMessage(SystemLabels); break; } case 18: { userLabels_.AddEntriesFrom(input, _map_userLabels_codec); break; } } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; case 10: { if (systemLabels_ == null) { SystemLabels = new global::Google.Protobuf.WellKnownTypes.Struct(); } input.ReadMessage(SystemLabels); break; } case 18: { userLabels_.AddEntriesFrom(ref input, _map_userLabels_codec); break; } } } } #endif } #endregion } #endregion Designer generated code
/* * Copyright (c) .NET Foundation and Contributors * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE file for details. * * https://github.com/piranhacms/piranha.core * */ using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; using Piranha.Models; using Piranha.Repositories; namespace Piranha.Services { public class PageService : IPageService { private readonly IPageRepository _repo; private readonly IContentFactory _factory; private readonly ISiteService _siteService; private readonly IParamService _paramService; private readonly IMediaService _mediaService; private readonly ICache _cache; private readonly ISearch _search; /// <summary> /// Default constructor. /// </summary> /// <param name="repo">The main repository</param> /// <param name="factory">The content facory</param> /// <param name="siteService">The site service</param> /// <param name="paramService">The param service</param> /// <param name="mediaService">The media service</param> /// <param name="cache">The optional model cache</param> /// <param name="search">The optional content search</param> public PageService(IPageRepository repo, IContentFactory factory, ISiteService siteService, IParamService paramService, IMediaService mediaService, ICache cache = null, ISearch search = null) { _repo = repo; _factory = factory; _siteService = siteService; _paramService = paramService; _mediaService = mediaService; _search = search; if ((int)App.CacheLevel > 2) { _cache = cache; } } /// <summary> /// Creates and initializes a new page of the specified type. /// </summary> /// <returns>The created page</returns> public async Task<T> CreateAsync<T>(string typeId = null) where T : Models.PageBase { if (string.IsNullOrEmpty(typeId)) { typeId = typeof(T).Name; } var type = App.PageTypes.GetById(typeId); if (type != null) { var model = await _factory.CreateAsync<T>(type).ConfigureAwait(false); using (var config = new Config(_paramService)) { model.EnableComments = config.CommentsEnabledForPages; model.CloseCommentsAfterDays = config.CommentsCloseAfterDays; } return model; } return null; } /// <summary> /// Creates and initializes a copy of the given page. /// </summary> /// <param name="originalPage">The orginal page</param> /// <returns>The created copy</returns> public async Task<T> CopyAsync<T>(T originalPage) where T : Models.PageBase { var model = await GetByIdAsync<T>(originalPage.Id).ConfigureAwait(false); model.Id = Guid.NewGuid(); model.OriginalPageId = originalPage.Id; model.Title = $"Copy of { model.Title }"; model.NavigationTitle = null; model.Slug = null; model.Created = model.LastModified = DateTime.MinValue; model.Published = null; return model; } /// <summary> /// Detaches a copy and initializes it as a standalone page /// </summary> /// <returns>The standalone page</returns> public async Task DetachAsync<T>(T model) where T : Models.PageBase { if (!model.OriginalPageId.HasValue) { throw new ValidationException("Page is not an copy"); } // Get the page and remove the original id var page = await GetByIdAsync<T>(model.Id).ConfigureAwait(false); page.OriginalPageId = null; // Reset blocks so they are recreated foreach (var pageBlock in page.Blocks) { pageBlock.Id = Guid.Empty; if (pageBlock is Extend.BlockGroup) { foreach (var childBlock in ((Extend.BlockGroup)pageBlock).Items) { childBlock.Id = Guid.Empty; } } } await SaveAsync(page).ConfigureAwait(false); } /// <summary> /// Gets all available models. /// </summary> /// <returns>The available models</returns> public Task<IEnumerable<DynamicPage>> GetAllAsync(Guid? siteId = null) { return GetAllAsync<DynamicPage>(siteId); } /// <summary> /// Gets all available models. /// </summary> /// <returns>The available models</returns> public async Task<IEnumerable<T>> GetAllAsync<T>(Guid? siteId = null) where T : PageBase { var models = new List<T>(); var pages = await _repo.GetAll(await EnsureSiteIdAsync(siteId).ConfigureAwait(false)) .ConfigureAwait(false); foreach (var pageId in pages) { var page = await GetByIdAsync<T>(pageId).ConfigureAwait(false); if (page != null) { models.Add(page); } } return models; } /// <summary> /// Gets the available blog pages for the current site. /// </summary> /// <param name="siteId">The optional site id</param> /// <returns>The pages</returns> public Task<IEnumerable<DynamicPage>> GetAllBlogsAsync(Guid? siteId = null) { return GetAllBlogsAsync<DynamicPage>(siteId); } /// <summary> /// Gets the available blog pages for the current site. /// </summary> /// <param name="siteId">The optional site id</param> /// <returns>The pages</returns> public async Task<IEnumerable<T>> GetAllBlogsAsync<T>(Guid? siteId = null) where T : Models.PageBase { var models = new List<T>(); var pages = await _repo.GetAllBlogs(await EnsureSiteIdAsync(siteId).ConfigureAwait(false)) .ConfigureAwait(false); foreach (var pageId in pages) { var page = await GetByIdAsync<T>(pageId).ConfigureAwait(false); if (page != null) { models.Add(page); } } return models; } /// <summary> /// Gets the id of all pages that have a draft for /// the specified site. /// </summary> /// <param name="siteId">The unique site id</param> /// <returns>The pages that have a draft</returns> public async Task<IEnumerable<Guid>> GetAllDraftsAsync(Guid? siteId = null) { return await _repo.GetAllDrafts(await EnsureSiteIdAsync(siteId).ConfigureAwait(false)); } /// <summary> /// Gets the pending comments available for the page with the specified id. If no page id /// is provided all comments are fetched. /// </summary> /// <param name="pageId">The unique page id</param> /// <param name="onlyApproved">If only approved comments should be fetched</param> /// <param name="page">The optional page number</param> /// <param name="pageSize">The optional page size</param> /// <returns>The available comments</returns> public Task<IEnumerable<Comment>> GetAllCommentsAsync(Guid? pageId = null, bool onlyApproved = true, int? page = null, int? pageSize = null) { return GetAllCommentsAsync(pageId, onlyApproved, false, page, pageSize); } /// <summary> /// Gets the pending comments available for the page with the specified id. If no page id /// is provided all comments are fetched. /// </summary> /// <param name="pageId">The unique page id</param> /// <param name="page">The optional page number</param> /// <param name="pageSize">The optional page size</param> /// <returns>The available comments</returns> public Task<IEnumerable<Comment>> GetAllPendingCommentsAsync(Guid? pageId = null, int? page = null, int? pageSize = null) { return GetAllCommentsAsync(pageId, false, true, page, pageSize); } /// <summary> /// Gets the site startpage. /// </summary> /// <param name="siteId">The optional site id</param> /// <returns>The page model</returns> public Task<DynamicPage> GetStartpageAsync(Guid? siteId = null) { return GetStartpageAsync<DynamicPage>(siteId); } /// <summary> /// Gets the site startpage. /// </summary> /// <typeparam name="T">The model type</typeparam> /// <param name="siteId">The optional site id</param> /// <returns>The page model</returns> public async Task<T> GetStartpageAsync<T>(Guid? siteId = null) where T : Models.PageBase { siteId = await EnsureSiteIdAsync(siteId).ConfigureAwait(false); PageBase model = null; if (typeof(T) == typeof(Models.PageInfo)) { model = _cache?.Get<PageInfo>($"PageInfo_{siteId.Value}"); } else if (!typeof(DynamicPage).IsAssignableFrom(typeof(T))) { model = _cache?.Get<PageBase>($"Page_{siteId.Value}"); if (model != null) { await _factory.InitAsync(model, App.PageTypes.GetById(model.TypeId)).ConfigureAwait(false); } } if (model == null) { model = await _repo.GetStartpage<T>(siteId.Value).ConfigureAwait(false); await OnLoadAsync(model).ConfigureAwait(false); } if (model != null && model is T) { return await MapOriginalAsync((T)model).ConfigureAwait(false); } return null; } /// <summary> /// Gets the page model with the specified id. /// </summary> /// <param name="id">The unique id</param> /// <returns>The page model</returns> public Task<DynamicPage> GetByIdAsync(Guid id) { return GetByIdAsync<DynamicPage>(id); } /// <summary> /// Gets the model with the specified id. /// </summary> /// <param name="id">The unique id</param> /// <returns>The model, or null if it doesn't exist</returns> public async Task<T> GetByIdAsync<T>(Guid id) where T : PageBase { return (await GetByIdsAsync<T>(id)).FirstOrDefault(); } /// <summary> /// Gets the page models with the specified id's. /// </summary> /// <param name="ids">The unique id's</param> /// <returns>The page models</returns> public async Task<IEnumerable<T>> GetByIdsAsync<T>(params Guid[] ids) where T : PageBase { var ret = new List<T>(); var notCached = new List<Guid>(); // Try to get the requested models from cache foreach (var id in ids) { PageBase model = null; if (typeof(T) == typeof(Models.PageInfo)) { model = _cache?.Get<PageInfo>($"PageInfo_{id.ToString()}"); } else if (!typeof(DynamicPage).IsAssignableFrom(typeof(T))) { model = _cache?.Get<PageBase>(id.ToString()); if (model != null) { await _factory.InitAsync(model, App.PageTypes.GetById(model.TypeId)).ConfigureAwait(false); } } if (model == null) { notCached.Add(id); } else if (model is T) { ret.Add(await MapOriginalAsync((T)model).ConfigureAwait(false)); } } // Get the models not available in cache from the // repository. if (notCached.Count > 0) { var models = await _repo.GetByIds<T>(notCached.ToArray()).ConfigureAwait(false); foreach (var model in models.Where(m => m is T)) { await OnLoadAsync(model).ConfigureAwait(false); ret.Add(await MapOriginalAsync((T)model).ConfigureAwait(false)); } } // Sort the output in the same order as the input array var sorted = new List<T>(); foreach (var id in ids) { var model = ret.FirstOrDefault(m => m.Id == id); if (model != null) { sorted.Add(model); } } return sorted; } /// <summary> /// Gets the page model with the specified slug. /// </summary> /// <param name="slug">The unique slug</param> /// <param name="siteId">The optional site id</param> /// <returns>The page model</returns> public Task<DynamicPage> GetBySlugAsync(string slug, Guid? siteId = null) { return GetBySlugAsync<DynamicPage>(slug, siteId); } /// <summary> /// Gets the page model with the specified slug. /// </summary> /// <typeparam name="T">The model type</typeparam> /// <param name="slug">The unique slug</param> /// <param name="siteId">The optional site id</param> /// <returns>The page model</returns> public async Task<T> GetBySlugAsync<T>(string slug, Guid? siteId = null) where T : Models.PageBase { siteId = await EnsureSiteIdAsync(siteId).ConfigureAwait(false); PageBase model = null; // Lets see if we can resolve the slug from cache var pageId = _cache?.Get<Guid?>($"PageId_{siteId}_{slug}"); if (pageId.HasValue) { if (typeof(T) == typeof(Models.PageInfo)) { model = _cache?.Get<PageInfo>($"PageInfo_{pageId.ToString()}"); } else if (!typeof(DynamicPage).IsAssignableFrom(typeof(T))) { model = _cache?.Get<PageBase>(pageId.ToString()); if (model != null) { await _factory.InitAsync(model, App.PageTypes.GetById(model.TypeId)).ConfigureAwait(false); } } } if (model == null) { model = await _repo.GetBySlug<T>(slug, siteId.Value).ConfigureAwait(false); await OnLoadAsync(model).ConfigureAwait(false); } if (model != null && model is T) { return await MapOriginalAsync((T)model).ConfigureAwait(false); } return null; } /// <summary> /// Gets the id for the page with the given slug. /// </summary> /// <param name="slug">The unique slug</param> /// <param name="siteId">The optional page id</param> /// <returns>The id</returns> public async Task<Guid?> GetIdBySlugAsync(string slug, Guid? siteId = null) { siteId = await EnsureSiteIdAsync(siteId).ConfigureAwait(false); // Lets see if we can resolve the slug from cache var pageId = _cache?.Get<Guid?>($"PageId_{siteId}_{slug}"); if (!pageId.HasValue) { var info = await _repo.GetBySlug<PageInfo>(slug, siteId.Value).ConfigureAwait(false); if (info != null) { pageId = info.Id; } } return pageId; } /// <summary> /// Gets the draft for the page model with the specified id. /// </summary> /// <param name="id">The unique id</param> /// <returns>The draft, or null if no draft exists</returns> public Task<DynamicPage> GetDraftByIdAsync(Guid id) { return GetDraftByIdAsync<DynamicPage>(id); } /// <summary> /// Gets the draft for the page model with the specified id. /// </summary> /// <typeparam name="T">The model type</typeparam> /// <param name="id">The unique id</param> /// <returns>The draft, or null if no draft exists</returns> public async Task<T> GetDraftByIdAsync<T>(Guid id) where T : PageBase { var draft = await _repo.GetDraftById<T>(id).ConfigureAwait(false); await OnLoadAsync(draft, true).ConfigureAwait(false); return draft; } /// <summary> /// Moves the current page in the structure. /// </summary> /// <typeparam name="T">The model type</typeparam> /// <param name="model">The page to move</param> /// <param name="parentId">The new parent id</param> /// <param name="sortOrder">The new sort order</param> public async Task MoveAsync<T>(T model, Guid? parentId, int sortOrder) where T : Models.PageBase { // Call hooks & save App.Hooks.OnBeforeSave<PageBase>(model); var affected = await _repo.Move(model, parentId, sortOrder).ConfigureAwait(false); App.Hooks.OnAfterSave<PageBase>(model); // Remove the moved page from cache await RemoveFromCache(model).ConfigureAwait(false); // Remove all affected pages from cache if (_cache != null) { foreach (var id in affected) { var page = await GetByIdAsync<PageInfo>(id).ConfigureAwait(false); if (page != null) { await RemoveFromCache(model).ConfigureAwait(false); } } } await _siteService.InvalidateSitemapAsync(model.SiteId).ConfigureAwait(false); } /// <summary> /// Gets the comment with the given id. /// </summary> /// <param name="id">The comment id</param> /// <returns>The model</returns> public Task<Comment> GetCommentByIdAsync(Guid id) { return _repo.GetCommentById(id); } /// <summary> /// Saves the given page model /// </summary> /// <param name="model">The page model</param> public Task SaveAsync<T>(T model) where T : PageBase { return SaveAsync(model, false); } /// <summary> /// Saves the given page model as a draft /// </summary> /// <param name="model">The page model</param> public Task SaveDraftAsync<T>(T model) where T : PageBase { return SaveAsync(model, true); } /// <summary> /// Gets the comments available for the page with the specified id. /// </summary> /// <param name="pageId">The unique page id</param> /// <param name="onlyApproved">If only approved comments should be fetched</param> /// <param name="onlyPending">If only pending comments should be fetched</param> /// <param name="page">The optional page number</param> /// <param name="pageSize">The optional page size</param> /// <returns>The available comments</returns> private async Task<IEnumerable<Comment>> GetAllCommentsAsync(Guid? pageId = null, bool onlyApproved = true, bool onlyPending = false, int? page = null, int? pageSize = null) { // Ensure page number if (!page.HasValue) { page = 0; } // Ensure page size if (!pageSize.HasValue) { using (var config = new Config(_paramService)) { pageSize = config.CommentsPageSize; } } // Get the comments IEnumerable<Comment> comments = null; if (onlyPending) { comments = await _repo.GetAllPendingComments(pageId, page.Value, pageSize.Value).ConfigureAwait(false); } else { comments = await _repo.GetAllComments(pageId, onlyApproved, page.Value, pageSize.Value).ConfigureAwait(false); } // Execute hook foreach (var comment in comments) { App.Hooks.OnLoad<Comment>(comment); } return comments; } /// <summary> /// Saves the given page model /// </summary> /// <param name="model">The page model</param> /// <param name="isDraft">If we're saving as a draft</param> private async Task SaveAsync<T>(T model, bool isDraft) where T : PageBase { // Ensure id if (model.Id == Guid.Empty) { model.Id = Guid.NewGuid(); } // Validate model var context = new ValidationContext(model); Validator.ValidateObject(model, context, true); // Ensure title since this field isn't required in // the Content base class if (string.IsNullOrWhiteSpace(model.Title)) { throw new ValidationException("The Title field is required"); } // Ensure type id since this field isn't required in // the Content base class if (string.IsNullOrWhiteSpace(model.TypeId)) { throw new ValidationException("The TypeId field is required"); } // Ensure slug if (string.IsNullOrWhiteSpace(model.Slug)) { var prefix = ""; // Check if we should generate hierarchical slugs using (var config = new Config(_paramService)) { if (config.HierarchicalPageSlugs && model.ParentId.HasValue) { var parentSlug = (await GetByIdAsync<PageInfo>(model.ParentId.Value).ConfigureAwait(false))?.Slug; if (!string.IsNullOrWhiteSpace(parentSlug)) { prefix = parentSlug + "/"; } } model.Slug = prefix + Utils.GenerateSlug(!string.IsNullOrWhiteSpace(model.NavigationTitle) ? model.NavigationTitle : model.Title); } } else { model.Slug = Utils.GenerateSlug(model.Slug); } // Ensure slug is not null or empty // after removing unwanted characters if (string.IsNullOrWhiteSpace(model.Slug)) { throw new ValidationException("The generated slug is empty as the title only contains special characters, please specify a slug to save the page."); } // Ensure that the slug is unique var duplicate = await GetBySlugAsync(model.Slug, model.SiteId); if (duplicate != null && duplicate.Id != model.Id) { throw new ValidationException("The specified slug already exists, please create a unique slug"); } // Check if we're changing the state var current = await _repo.GetById<PageInfo>(model.Id).ConfigureAwait(false); var changeState = IsPublished(current) != IsPublished(model); IEnumerable<Guid> affected = new Guid[0]; // Call before save hook App.Hooks.OnBeforeSave<PageBase>(model); // Handle revisions and save if ((IsPublished(current) || IsScheduled(current) ) && isDraft) { // We're saving a draft since we have a previously // published version of the page await _repo.SaveDraft(model).ConfigureAwait(false); } else { if (current == null && isDraft) { // If we're saving a draft as a normal page instance, make // sure we remove the published date as this sould effectively // publish the page. model.Published = null; } else if (current != null && !isDraft) { using (var config = new Config(_paramService)) { // Save current as a revision before saving the model // and if a draft revision exists, remove it. await _repo.DeleteDraft(model.Id).ConfigureAwait(false); await _repo.CreateRevision(model.Id, config.PageRevisions).ConfigureAwait(false); } } // Save the main page affected = await _repo.Save(model).ConfigureAwait(false); } // Call after save hook App.Hooks.OnAfterSave<PageBase>(model); // Update search document if (!isDraft && _search != null) { await _search.SavePageAsync(model); } // Remove from cache await RemoveFromCache(model).ConfigureAwait(false); // Remove all affected pages from cache if (_cache != null) { foreach (var id in affected) { var page = await GetByIdAsync<PageInfo>(id).ConfigureAwait(false); if (page != null) { await RemoveFromCache(model).ConfigureAwait(false); } } } // Invalidate sitemap if any other pages were affected if (changeState || affected.Count() > 0) { await _siteService.InvalidateSitemapAsync(model.SiteId).ConfigureAwait(false); } } /// <summary> /// Saves the comment. /// </summary> /// <param name="pageId">The unique page id</param> /// <param name="model">The comment model</param> public Task SaveCommentAsync(Guid pageId, PageComment model) { return SaveCommentAsync(pageId, model, false); } /// <summary> /// Saves the comment and verifies if should be approved or not. /// </summary> /// <param name="pageId">The unique page id</param> /// <param name="model">The comment model</param> public Task SaveCommentAndVerifyAsync(Guid pageId, PageComment model) { return SaveCommentAsync(pageId, model, true); } /// <summary> /// Saves the comment. /// </summary> /// <param name="pageId">The unique page id</param> /// <param name="model">The comment model</param> /// <param name="verify">If comment verification should be applied</param> private async Task SaveCommentAsync(Guid pageId, Comment model, bool verify) { // Make sure we have a post var page = await GetByIdAsync<PageInfo>(pageId).ConfigureAwait(false); if (page != null) { // Ensure id if (model.Id == Guid.Empty) { model.Id = Guid.NewGuid(); } // Ensure created date if (model.Created == DateTime.MinValue) { model.Created = DateTime.Now; } // Ensure content id if (model.ContentId == Guid.Empty) { model.ContentId = pageId; } // Validate model var context = new ValidationContext(model); Validator.ValidateObject(model, context, true); // Set approved according to config if we should verify if (verify) { using (var config = new Config(_paramService)) { model.IsApproved = config.CommentsApprove; } App.Hooks.OnValidate<Comment>(model); } // Call hooks & save App.Hooks.OnBeforeSave<Comment>(model); await _repo.SaveComment(pageId, model).ConfigureAwait(false); App.Hooks.OnAfterSave<Comment>(model); // Invalidate parent post from cache await RemoveFromCache(page).ConfigureAwait(false); } else { throw new ArgumentException($"Could not find page with id { pageId.ToString() }"); } } /// <summary> /// Deletes the model with the specified id. /// </summary> /// <param name="id">The unique id</param> public async Task DeleteAsync(Guid id) { var model = await GetByIdAsync<PageInfo>(id).ConfigureAwait(false); if (model != null) { await DeleteAsync(model).ConfigureAwait(false); } } /// <summary> /// Deletes the given model. /// </summary> /// <param name="model">The model</param> public async Task DeleteAsync<T>(T model) where T : Models.PageBase { // Call hooks & save App.Hooks.OnBeforeDelete<PageBase>(model); await _repo.Delete(model.Id).ConfigureAwait(false); App.Hooks.OnAfterDelete<PageBase>(model); // Delete search document if (_search != null) { await _search.DeletePageAsync(model); } // Remove from cache & invalidate sitemap await RemoveFromCache(model).ConfigureAwait(false); await _siteService.InvalidateSitemapAsync(model.SiteId).ConfigureAwait(false); } /// <summary> /// Deletes the comment with the specified id. /// </summary> /// <param name="id">The unique id</param> public async Task DeleteCommentAsync(Guid id) { var model = await GetCommentByIdAsync(id).ConfigureAwait(false); if (model != null) { await DeleteCommentAsync(model).ConfigureAwait(false); } } /// <summary> /// Deletes the given comment. /// </summary> /// <param name="model">The comment</param> public async Task DeleteCommentAsync(Comment model) { var page = await GetByIdAsync<PageInfo>(model.ContentId).ConfigureAwait(false); if (page != null) { // Call hooks & delete App.Hooks.OnBeforeDelete<Comment>(model); await _repo.DeleteComment(model.Id).ConfigureAwait(false); App.Hooks.OnAfterDelete<Comment>(model); // Remove parent post from cache await RemoveFromCache(page).ConfigureAwait(false); } else { throw new ArgumentException($"Could not find page with id { model.ContentId.ToString() }"); } } /// <summary> /// Merges the given model with the original model and /// returns it as a new instance. /// </summary> /// <param name="model">The model</param> /// <typeparam name="T">The model type</typeparam> /// <returns>The new merged model</returns> private async Task<T> MapOriginalAsync<T>(T model) where T : PageBase { if (model == null || !model.OriginalPageId.HasValue) { return model; } var original = await GetByIdAsync<T>(model.OriginalPageId.Value).ConfigureAwait(false); if (original != null) { T copy = null; if (model is DynamicPage) { // No need to clone as we don't cache dynamic models copy = original; } else { // Clone the original in case we are caching in system // memory, otherwise we'll destroy the original. copy = Utils.DeepClone(original); // Initialize all blocks & regions await _factory.InitAsync(copy, App.PageTypes.GetById(copy.TypeId)).ConfigureAwait(false); } // Now let's move over the fields we want to the // soft copy. copy.Id = model.Id; copy.SiteId = model.SiteId; copy.Title = model.Title; copy.NavigationTitle = model.NavigationTitle; copy.Slug = model.Slug; copy.ParentId = model.ParentId; copy.SortOrder = model.SortOrder; copy.IsHidden = model.IsHidden; copy.Route = model.Route; copy.OriginalPageId = model.OriginalPageId; copy.Published = model.Published; copy.Created = model.Created; copy.LastModified = model.LastModified; return copy; } return null; } /// <summary> /// Checks if the given site id is empty, and if so /// gets the site id of the default site. /// </summary> /// <param name="siteId">The optional site id</param> /// <returns>The site id</returns> private async Task<Guid> EnsureSiteIdAsync(Guid? siteId) { if (!siteId.HasValue) { var site = await _siteService.GetDefaultAsync().ConfigureAwait(false); if (site != null) { return site.Id; } } return siteId.Value; } /// <summary> /// Processes the model on load. /// </summary> /// <param name="model">The model</param> /// <param name="isDraft">If this is a draft</param> private async Task OnLoadAsync(PageBase model, bool isDraft = false) { if (model != null) { // Initialize model if (model is IDynamicContent dynamicModel) { await _factory.InitDynamicAsync(dynamicModel, App.PageTypes.GetById(model.TypeId)).ConfigureAwait(false); } else { await _factory.InitAsync(model, App.PageTypes.GetById(model.TypeId)).ConfigureAwait(false); } // Initialize primary image if (model.PrimaryImage == null) { model.PrimaryImage = new Extend.Fields.ImageField(); } if (model.PrimaryImage.Id.HasValue) { await _factory.InitFieldAsync(model.PrimaryImage).ConfigureAwait(false); } // Initialize og image if (model.OgImage == null) { model.OgImage = new Extend.Fields.ImageField(); } if (model.OgImage.Id.HasValue) { await _factory.InitFieldAsync(model.OgImage).ConfigureAwait(false); } App.Hooks.OnLoad(model); // Never cache drafts, dynamic or simple instances if (!isDraft && _cache != null && !(model is DynamicPage)) { if (model is PageInfo) { _cache.Set($"PageInfo_{model.Id.ToString()}", model); } else { _cache.Set(model.Id.ToString(), model); } _cache.Set($"PageId_{model.SiteId}_{model.Slug}", model.Id); if (!model.ParentId.HasValue && model.SortOrder == 0) { if (model is PageInfo) { _cache.Set($"PageInfo_{model.SiteId}", model); } else { _cache.Set($"Page_{model.SiteId}", model); } } } } } /// <summary> /// Removes the given model from cache. /// </summary> /// <param name="model">The model</param> private async Task RemoveFromCache(PageBase model) { if (_cache != null) { _cache.Remove(model.Id.ToString()); _cache.Remove($"PageInfo_{model.Id.ToString()}"); _cache.Remove($"PageId_{model.SiteId}_{model.Slug}"); if (!model.ParentId.HasValue && model.SortOrder == 0) { _cache.Remove($"Page_{model.SiteId}"); _cache.Remove($"PageInfo_{model.SiteId}"); } // Remove the site & clear the sitemap from cache await _siteService.RemoveSitemapFromCacheAsync(model.SiteId).ConfigureAwait(false); } } /// <summary> /// Checks if the given page is published /// </summary> /// <param name="model">The page model</param> /// <returns>If the page is published</returns> private bool IsPublished(PageBase model) { return model != null && model.Published.HasValue && model.Published.Value <= DateTime.Now; } /// <summary> /// Checks if the given page is scheduled /// </summary> /// <param name="model">The page model</param> /// <returns>If the page is scheduled</returns> private bool IsScheduled(PageBase model) { return model != null && model.Published.HasValue && model.Published.Value > DateTime.Now; } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using LaunchAtlanta.FaceSwap.Web.Areas.HelpPage.ModelDescriptions; using LaunchAtlanta.FaceSwap.Web.Areas.HelpPage.Models; namespace LaunchAtlanta.FaceSwap.Web.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
using System; using System.Text; using HttpServer.Exceptions; namespace HttpServer.Parser { /// <summary> /// Parses a HTTP request directly from a stream /// </summary> public class HttpRequestParser : IHttpRequestParser { private readonly BodyEventArgs _bodyArgs = new BodyEventArgs(); private readonly HeaderEventArgs _headerArgs = new HeaderEventArgs(); private ILogWriter _log; private readonly RequestLineEventArgs _requestLineArgs = new RequestLineEventArgs(); private int _bodyBytesLeft; private string _curHeaderName = string.Empty; private string _curHeaderValue = string.Empty; /// <summary> /// Create a new request parser /// </summary> /// <param name="logWriter">delegate receiving log entries.</param> public HttpRequestParser(ILogWriter logWriter) { _log = logWriter ?? NullLogWriter.Instance; } /// <summary> /// Add a number of bytes to the body /// </summary> /// <param name="buffer">buffer containing more body bytes.</param> /// <param name="offset">starting offset in buffer</param> /// <param name="count">number of bytes, from offset, to read.</param> /// <returns>offset to continue from.</returns> private int AddToBody(byte[] buffer, int offset, int count) { // got all bytes we need, or just a few of them? int bytesUsed = count > _bodyBytesLeft ? _bodyBytesLeft : count; _bodyArgs.Buffer = buffer; _bodyArgs.Offset = offset; _bodyArgs.Count = bytesUsed; BodyBytesReceived(this, _bodyArgs); _bodyBytesLeft -= bytesUsed; if (_bodyBytesLeft == 0) { // got a complete request. _log.Write(this, LogPrio.Trace, "Request parsed successfully."); OnRequestCompleted(); Clear(); } return offset + bytesUsed; } /// <summary> /// Remove all state information for the request. /// </summary> public void Clear() { _bodyBytesLeft = 0; _curHeaderName = string.Empty; _curHeaderValue = string.Empty; CurrentState = RequestParserState.FirstLine; } /// <summary> /// Gets or sets the log writer. /// </summary> public ILogWriter LogWriter { get { return _log; } set { _log = value ?? NullLogWriter.Instance; } } /// <summary> /// Parse request line /// </summary> /// <param name="value"></param> /// <exception cref="BadRequestException">If line is incorrect</exception> /// <remarks>Expects the following format: "Method SP Request-URI SP HTTP-Version CRLF"</remarks> protected void OnFirstLine(string value) { // //todo: In the interest of robustness, servers SHOULD ignore any empty line(s) received where a Request-Line is expected. // In other words, if the server is reading the protocol stream at the beginning of a message and receives a CRLF first, it should ignore the CRLF. // _log.Write(this, LogPrio.Debug, "Got request: " + value); //Request-Line = Method SP Request-URI SP HTTP-Version CRLF int pos = value.IndexOf(' '); if (pos == -1 || pos + 1 >= value.Length) { _log.Write(this, LogPrio.Warning, "Invalid request line, missing Method. Line: " + value); throw new BadRequestException("Invalid request line, missing Method. Line: " + value); } string method = value.Substring(0, pos).ToUpper(); int oldPos = pos + 1; pos = value.IndexOf(' ', oldPos); if (pos == -1) { _log.Write(this, LogPrio.Warning, "Invalid request line, missing URI. Line: " + value); throw new BadRequestException("Invalid request line, missing URI. Line: " + value); } string path = value.Substring(oldPos, pos - oldPos); if (path.Length > 4196) throw new BadRequestException("Too long URI."); if (pos + 1 >= value.Length) { _log.Write(this, LogPrio.Warning, "Invalid request line, missing HTTP-Version. Line: " + value); throw new BadRequestException("Invalid request line, missing HTTP-Version. Line: " + value); } string version = value.Substring(pos + 1); if (version.Length < 4 || string.Compare(version.Substring(0, 4), "HTTP", true) != 0) { _log.Write(this, LogPrio.Warning, "Invalid HTTP version in request line. Line: " + value); throw new BadRequestException("Invalid HTTP version in Request line. Line: " + value); } _requestLineArgs.HttpMethod = method; _requestLineArgs.HttpVersion = version; _requestLineArgs.UriPath = path; RequestLineReceived(this, _requestLineArgs); } /// <summary> /// We've parsed a new header. /// </summary> /// <param name="name">Name in lower case</param> /// <param name="value">Value, unmodified.</param> /// <exception cref="BadRequestException">If content length cannot be parsed.</exception> protected void OnHeader(string name, string value) { _headerArgs.Name = name; _headerArgs.Value = value; if (string.Compare(name, "content-length", true) == 0) { if (!int.TryParse(value, out _bodyBytesLeft)) throw new BadRequestException("Content length is not a number."); } HeaderReceived(this, _headerArgs); } private void OnRequestCompleted() { RequestCompleted(this, EventArgs.Empty); } #region IHttpRequestParser Members /// <summary> /// Current state in parser. /// </summary> public RequestParserState CurrentState { get; private set; } /// <summary> /// Parse a message /// </summary> /// <param name="buffer">bytes to parse.</param> /// <param name="offset">where in buffer that parsing should start</param> /// <param name="count">number of bytes to parse, starting on <paramref name="offset"/>.</param> /// <returns>offset (where to start parsing next).</returns> /// <exception cref="BadRequestException"><c>BadRequestException</c>.</exception> public int Parse(byte[] buffer, int offset, int count) { // add body bytes if (CurrentState == RequestParserState.Body) { // copy all remaining bytes to the beginning of the buffer. //Buffer.BlockCopy(buffer, offset + bytesUsed, buffer, 0, count - bytesUsed); return AddToBody(buffer, 0, count); } #if DEBUG string temp = Encoding.ASCII.GetString(buffer, offset, count); _log.Write(this, LogPrio.Trace, "\r\n\r\n HTTP MESSAGE: " + temp + "\r\n"); #endif int currentLine = 1; int startPos = -1; // set start pos since this is from an partial request if (CurrentState == RequestParserState.HeaderValue) startPos = 0; int endOfBufferPos = offset + count; //<summary> // Handled bytes are used to keep track of the number of bytes processed. // We do this since we can handle partial requests (to be able to check headers and abort // invalid requests directly without having to process the whole header / body). // </summary> int handledBytes = 0; for (int currentPos = offset; currentPos < endOfBufferPos; ++currentPos) { var ch = (char) buffer[currentPos]; char nextCh = endOfBufferPos > currentPos + 1 ? (char) buffer[currentPos + 1] : char.MinValue; if (ch == '\r') ++currentLine; switch (CurrentState) { case RequestParserState.FirstLine: if (currentPos > 4196) { _log.Write(this, LogPrio.Warning, "HTTP Request is too large."); throw new BadRequestException("Too large request line."); } if (char.IsLetterOrDigit(ch) && startPos == -1) startPos = currentPos; if (startPos == -1 && (ch != '\r' || nextCh != '\n')) { _log.Write(this, LogPrio.Warning, "Request line is not found."); throw new BadRequestException("Invalid request line."); } if (startPos != -1 && (ch == '\r' || ch == '\n')) { int size = GetLineBreakSize(buffer, currentPos); OnFirstLine(Encoding.UTF8.GetString(buffer, startPos, currentPos - startPos)); CurrentState = CurrentState + 1; currentPos += size - 1; handledBytes = currentPos + size - 1; startPos = -1; } break; case RequestParserState.HeaderName: if (ch == '\r' || ch == '\n') { currentPos += GetLineBreakSize(buffer, currentPos); if (_bodyBytesLeft == 0) { CurrentState = RequestParserState.FirstLine; _log.Write(this, LogPrio.Trace, "Request parsed successfully (no content)."); OnRequestCompleted(); Clear(); return currentPos; } CurrentState = RequestParserState.Body; if (currentPos + 1 < endOfBufferPos) { _log.Write(this, LogPrio.Trace, "Adding bytes to the body"); return AddToBody(buffer, currentPos, endOfBufferPos - currentPos); } return currentPos; } if (char.IsWhiteSpace(ch) || ch == ':') { if (startPos == -1) { _log.Write(this, LogPrio.Warning, "Expected header name, got colon on line " + currentLine); throw new BadRequestException("Expected header name, got colon on line " + currentLine); } _curHeaderName = Encoding.UTF8.GetString(buffer, startPos, currentPos - startPos); handledBytes = currentPos + 1; startPos = -1; CurrentState = CurrentState + 1; if (ch == ':') CurrentState = CurrentState + 1; } else if (startPos == -1) startPos = currentPos; else if (!char.IsLetterOrDigit(ch) && ch != '-') { _log.Write(this, LogPrio.Warning, "Invalid character in header name on line " + currentLine); throw new BadRequestException("Invalid character in header name on line " + currentLine); } if (startPos != -1 && currentPos - startPos > 200) { _log.Write(this, LogPrio.Warning, "Invalid header name on line " + currentLine); throw new BadRequestException("Invalid header name on line " + currentLine); } break; case RequestParserState.AfterName: if (ch == ':') { handledBytes = currentPos + 1; CurrentState = CurrentState + 1; } break; case RequestParserState.Between: { if (ch == ' ' || ch == '\t') continue; int newLineSize = GetLineBreakSize(buffer, currentPos); if (newLineSize > 0 && currentPos + newLineSize < endOfBufferPos && char.IsWhiteSpace((char) buffer[currentPos + newLineSize])) { ++currentPos; continue; } startPos = currentPos; CurrentState = CurrentState + 1; handledBytes = currentPos; continue; } case RequestParserState.HeaderValue: { if (ch != '\r' && ch != '\n') continue; int newLineSize = GetLineBreakSize(buffer, currentPos); if (startPos == -1) continue; // allow new lines before start of value if (_curHeaderName == string.Empty) throw new BadRequestException("Missing header on line " + currentLine); if (startPos == -1) { _log.Write(this, LogPrio.Warning, "Missing header value for '" + _curHeaderName); throw new BadRequestException("Missing header value for '" + _curHeaderName); } if (currentPos - startPos > 4096) { _log.Write(this, LogPrio.Warning, "Too large header value on line " + currentLine); throw new BadRequestException("Too large header value on line " + currentLine); } // Header fields can be extended over multiple lines by preceding each extra line with at // least one SP or HT. if (endOfBufferPos > currentPos + newLineSize && (buffer[currentPos + newLineSize] == ' ' || buffer[currentPos + newLineSize] == buffer['\t'])) { if (startPos != -1) _curHeaderValue = Encoding.UTF8.GetString(buffer, startPos, currentPos - startPos); _log.Write(this, LogPrio.Trace, "Header value is on multiple lines."); CurrentState = RequestParserState.Between; startPos = -1; currentPos += newLineSize - 1; handledBytes = currentPos + newLineSize - 1; continue; } _curHeaderValue += Encoding.UTF8.GetString(buffer, startPos, currentPos - startPos); _log.Write(this, LogPrio.Trace, "Header [" + _curHeaderName + ": " + _curHeaderValue + "]"); OnHeader(_curHeaderName, _curHeaderValue); startPos = -1; CurrentState = RequestParserState.HeaderName; _curHeaderValue = string.Empty; _curHeaderName = string.Empty; ++currentPos; handledBytes = currentPos + 1; // Check if we got a colon so we can cut header name, or crlf for end of header. bool canContinue = false; for (int j = currentPos; j < endOfBufferPos; ++j) { if (buffer[j] != ':' && buffer[j] != '\r' && buffer[j] != '\n') continue; canContinue = true; break; } if (!canContinue) { _log.Write(this, LogPrio.Trace, "Cant continue, no colon."); return currentPos + 1; } } break; } } return handledBytes; } int GetLineBreakSize(byte[] buffer, int offset) { if (buffer[offset] != '\r' && buffer[offset] != '\n') return 0; // linux line feed if (buffer[offset] == '\n' && (buffer.Length == offset + 1 || buffer[offset + 1] != '\r')) return 1; // win line feed if (buffer[offset] == '\r' && buffer.Length > offset + 1 && buffer[offset + 1] == '\n') return 2; if (buffer[offset] == '\n' && buffer.Length > offset + 1 && buffer[offset + 1] == '\r') return 2; throw new BadRequestException("Got invalid linefeed."); } /// <summary> /// A request have been successfully parsed. /// </summary> public event EventHandler RequestCompleted = delegate { }; /// <summary> /// More body bytes have been received. /// </summary> public event EventHandler<BodyEventArgs> BodyBytesReceived = delegate { }; /// <summary> /// Request line have been received. /// </summary> public event EventHandler<RequestLineEventArgs> RequestLineReceived = delegate { }; /// <summary> /// A header have been received. /// </summary> public event EventHandler<HeaderEventArgs> HeaderReceived = delegate { }; #endregion } }
using System; using System.Collections.Generic; using System.Text; using FlatRedBall.Graphics; //using FlatRedBall.Content; #if FRB_MDX using Texture2D = FlatRedBall.Texture2D; using Microsoft.DirectX; using FlatRedBall.Graphics.Model; #else #if !SILVERLIGHT using FlatRedBall.Input; #endif using FlatRedBall.Gui; using Texture2D = Microsoft.Xna.Framework.Graphics.Texture2D; using Microsoft.Xna.Framework; #endif using FlatRedBall.ManagedSpriteGroups; using FlatRedBall.Math; using FlatRedBall.Utilities; namespace FlatRedBall { public static class SpriteGridListExtensionMethods { public static SpriteGrid FindByName(this List<SpriteGrid> list, string name) { for (int i = 0; i < list.Count; i++) { if (list[i].Name == name) { return list[i]; } } return null; } } public class Scene : IEquatable<Scene> #if FRB_XNA , IMouseOver #endif { #region Fields string mName; SpriteList mSprites; List<SpriteGrid> mSpriteGrids; PositionedObjectList<SpriteFrame> mSpriteFrames; PositionedObjectList<Text> mTexts; #endregion #region Properties public string Name { get { return mName; } set { mName = value; } } public SpriteList Sprites { get { return mSprites; } } public List<SpriteGrid> SpriteGrids { get { return mSpriteGrids; } } public PositionedObjectList<SpriteFrame> SpriteFrames { get { return mSpriteFrames; } set { mSpriteFrames = value; } } public PositionedObjectList<Text> Texts { get { return mTexts; } set { mTexts = value; } } public bool Visible { set { for (int i = 0; i < mSprites.Count; i++) { mSprites[i].Visible = value; } for (int i = 0; i < mSpriteGrids.Count; i++) { SpriteGrid spriteGrid = mSpriteGrids[i]; spriteGrid.Blueprint.Visible = value; for (int j = 0; j < spriteGrid.VisibleSprites.Count; j++) { spriteGrid.VisibleSprites[j].Visible = value; } } for (int i = 0; i < mSpriteFrames.Count; i++) { mSpriteFrames[i].Visible = value; } for (int i = 0; i < mTexts.Count; i++) { mTexts[i].Visible = value; } } } #endregion #region Methods #region Constructor public Scene() { mSprites = new SpriteList(); mSprites.Name = "Scene SpriteList"; mSpriteGrids = new List<SpriteGrid>(); mSpriteFrames = new PositionedObjectList<SpriteFrame>(); mSpriteFrames.Name = "Scene SpriteFrame PositionedObjectList"; mTexts = new PositionedObjectList<Text>(); mTexts.Name = "Scene Text PositionedObjectList"; } #endregion #region Public Methods public void AddToThis(Scene scene) { mSprites.AddRange(scene.mSprites); mSpriteGrids.AddRange(scene.mSpriteGrids); mSpriteFrames.AddRange(scene.mSpriteFrames); mTexts.AddRange(scene.mTexts); } public void AddToManagers() { AddToManagers(null); } public void AddToManagers(Layer layer) { #region Add the Sprites if (layer == null) { for (int i = 0; i < Sprites.Count; i++) { Sprite sprite = Sprites[i]; if (sprite.mOrdered) { SpriteManager.AddSprite(sprite); } else { SpriteManager.AddZBufferedSprite(sprite); } } } else { for (int i = 0; i < Sprites.Count; i++) { Sprite sprite = Sprites[i]; SpriteManager.AddToLayer(sprite, layer); } } #endregion #region Add the SpriteGrids for (int i = 0; i < SpriteGrids.Count; i++) { SpriteGrid spriteGrid = SpriteGrids[i]; spriteGrid.Layer = layer; spriteGrid.PopulateGrid(); spriteGrid.RefreshPaint(); spriteGrid.Manage(); } #endregion #region Add the SpriteFrames for (int i = 0; i < SpriteFrames.Count; i++) { SpriteFrame frame = SpriteFrames[i]; if (frame.CenterSprite != null && frame.CenterSprite.mOrdered == false) { SpriteManager.AddToLayerZBuffered(frame, layer); } else { SpriteManager.AddSpriteFrame(frame); SpriteManager.AddToLayer(frame, layer); } } #endregion #region Add the Texts for (int i = 0; i < Texts.Count; i++) { if (layer == null) { TextManager.AddText(Texts[i]); } else { #if SILVERLIGHT throw new NotImplementedException(); #else TextManager.AddText(Texts[i], layer); #endif } } #endregion } public void AttachAllDetachedTo(PositionedObject newParent, bool changeRelative) { mSprites.AttachAllDetachedTo(newParent, changeRelative); mSpriteFrames.AttachAllDetachedTo(newParent, changeRelative); mTexts.AttachAllDetachedTo(newParent, changeRelative); } public void AttachTo(PositionedObject newParent, bool changeRelative) { mSprites.AttachTo(newParent, changeRelative); mSpriteFrames.AttachTo(newParent, changeRelative); mTexts.AttachTo(newParent, changeRelative); } public void Clear() { mSprites.Clear(); mSpriteGrids.Clear(); mSpriteFrames.Clear(); mTexts.Clear(); } public Scene Clone() { Scene scene = new Scene(); #region Create the Sprites for (int i = 0; i < mSprites.Count; i++) { Sprite sprite = mSprites[i]; scene.mSprites.Add(sprite.Clone()); } for (int i = 0; i < mSprites.Count; i++) { Sprite thisSprite = mSprites[i]; if (thisSprite.Parent != null) { Sprite otherSprite = scene.mSprites[i]; otherSprite.AttachTo( scene.mSprites.FindByName(thisSprite.Parent.Name), false); } } #endregion #region Create the SpriteGrids for (int i = 0; i < mSpriteGrids.Count; i++) { SpriteGrid spriteGrid = mSpriteGrids[i]; scene.mSpriteGrids.Add(spriteGrid.Clone()); } #endregion #region Create and Attach the SpriteFrames for (int i = 0; i < mSpriteFrames.Count; i++) { SpriteFrame spriteFrame = mSpriteFrames[i]; scene.mSpriteFrames.Add(spriteFrame.Clone()); } #endregion #region Create and attach the Texts for (int i = 0; i < mTexts.Count; i++) { Text text = mTexts[i]; scene.mTexts.Add(text.Clone()); } for (int i = 0; i < mTexts.Count; i++) { Text thisText = mTexts[i]; if (thisText.Parent != null) { Text otherText = scene.mTexts[i]; otherText.AttachTo( scene.mTexts.FindByName(thisText.Parent.Name), false); } } #endregion scene.Name = Name; return scene; } public void CopyAbsoluteToRelative() { CopyAbsoluteToRelative(true); } public void CopyAbsoluteToRelative(bool includeItemsWithParent) { mSprites.CopyAbsoluteToRelative(includeItemsWithParent); //mSpriteGrids; mSpriteFrames.CopyAbsoluteToRelative(includeItemsWithParent); mTexts.CopyAbsoluteToRelative(includeItemsWithParent); } public INameable FindByName(string name) { Sprite sprite = mSprites.FindByName(name); { if (sprite != null) return sprite; } foreach (SpriteGrid spriteGrid in mSpriteGrids) { if (spriteGrid.Name == name) { return spriteGrid; } } SpriteFrame spriteFrame = mSpriteFrames.FindByName(name); { if (spriteFrame != null) return spriteFrame; } Text text = mTexts.FindByName(name); { if (text != null) return text; } return null; } public void InvertHandedness() { int count = mSprites.Count; for(int i = 0; i < count; i++) { Sprite s = mSprites[i]; s.InvertHandedness(); } foreach (SpriteGrid sg in mSpriteGrids) { sg.InvertZ(); } count = mSpriteFrames.Count; for(int i = 0; i < count; i++) { SpriteFrame sf = mSpriteFrames[i]; sf.InvertHandedness(); } count = mTexts.Count; for(int i = 0; i < count; i++) { Text text = mTexts[i]; text.InvertHandedness(); } } public void ConvertToManuallyUpdated() { SpriteManager.ConvertToManuallyUpdated(mSprites); for (int i = 0; i < mSpriteFrames.Count; i++) { SpriteManager.ConvertToManuallyUpdated(mSpriteFrames[i]); } for (int i = 0; i < mTexts.Count; i++) { TextManager.ConvertToManuallyUpdated(mTexts[i]); } for (int i = 0; i < mSpriteGrids.Count; i++) { mSpriteGrids[i].CreatesAutomaticallyUpdatedSprites = false; for(int j = 0; j < mSpriteGrids[i].mVisibleSprites.Count; j++) { SpriteManager.ConvertToManuallyUpdated(mSpriteGrids[i].mVisibleSprites[j]); } } } public void ManageAll() { for (int i = 0; i < mSpriteGrids.Count; i++) { SpriteGrid spriteGrid = mSpriteGrids[i]; spriteGrid.Manage(); } // No need to manage SpriteFrames now that they're automatically managed by the SpriteManager. } public void RemoveFromManagers() { // Clearing may remove some references, but // it can cause bugs if people want to reuse // Scenes, which is common for reusing levels // Therefore, let's not clear //RemoveFromManagers(true); RemoveFromManagers(false); } public void RemoveFromManagers(bool clearThis) { if (!clearThis) { MakeOneWay(); } for (int i = mSprites.Count - 1; i > -1; i--) { Sprite sprite = mSprites[i]; PositionedObject oldParent = sprite.Parent; SpriteManager.RemoveSprite(sprite); if (!clearThis && oldParent != null) { sprite.AttachTo(oldParent, false); } } for (int i = mSpriteGrids.Count - 1; i > -1; i--) { //SpriteGrids don't get attached, so there is no code to preserve Parent and re-attach SpriteGrid spriteGrid = mSpriteGrids[i]; spriteGrid.Destroy(); } for(int i = mSpriteFrames.Count -1 ; i > -1; i--) { SpriteFrame spriteFrame = mSpriteFrames[i]; PositionedObject oldParent = spriteFrame.Parent; SpriteManager.RemoveSpriteFrame(spriteFrame); if (!clearThis && oldParent != null) { spriteFrame.AttachTo(oldParent, false); } } for (int i = mTexts.Count - 1; i > -1; i--) { Text text = mTexts[i]; PositionedObject oldParent = text.Parent; TextManager.RemoveText(text); if (!clearThis && oldParent != null) { text.AttachTo(oldParent, false); } } if (clearThis) { Clear(); } else { MakeTwoWay(); } } public void MakeTwoWay() { mSprites.MakeTwoWay(); mSpriteFrames.MakeTwoWay(); mTexts.MakeTwoWay(); // The SpriteGrids is not a two-way list } public void MakeOneWay() { mSprites.MakeOneWay(); mSpriteFrames.MakeOneWay(); mTexts.MakeOneWay(); // The SpriteGrids is not a two-way list } public void ScalePositionsAndScales(float value) { Vector3 amountToShiftBy = new Vector3(value, value, value); for (int i = 0; i < SpriteFrames.Count; i++) { SpriteFrame spriteFrame = SpriteFrames[i]; spriteFrame.X *= amountToShiftBy.X; spriteFrame.Y *= amountToShiftBy.Y; spriteFrame.Z *= amountToShiftBy.Z; spriteFrame.RelativeX *= amountToShiftBy.X; spriteFrame.RelativeY *= amountToShiftBy.Y; spriteFrame.RelativeZ *= amountToShiftBy.Z; spriteFrame.ScaleX *= amountToShiftBy.X; spriteFrame.ScaleY *= amountToShiftBy.Y; } for (int i = 0; i < Sprites.Count; i++) { Sprite sprite = Sprites[i]; Sprites[i].X *= amountToShiftBy.X; Sprites[i].Y *= amountToShiftBy.Y; Sprites[i].Z *= amountToShiftBy.Z; Sprites[i].RelativeX *= amountToShiftBy.X; Sprites[i].RelativeY *= amountToShiftBy.Y; Sprites[i].RelativeZ *= amountToShiftBy.Z; Sprites[i].ScaleX *= amountToShiftBy.X; Sprites[i].ScaleY *= amountToShiftBy.Y; } for (int i = 0; i < Texts.Count; i++) { Texts[i].X *= amountToShiftBy.X; Texts[i].Y *= amountToShiftBy.Y; Texts[i].Z *= amountToShiftBy.Z; Texts[i].RelativeX *= amountToShiftBy.X; Texts[i].RelativeY *= amountToShiftBy.Y; Texts[i].RelativeZ *= amountToShiftBy.Z; Texts[i].Scale *= amountToShiftBy.X; Texts[i].Spacing *= amountToShiftBy.X; Texts[i].NewLineDistance *= amountToShiftBy.X; Texts[i].MaxWidth *= amountToShiftBy.X; } } public void Shift(Vector3 shiftVector) { mSprites.Shift(shiftVector); for (int i = 0; i < mSpriteGrids.Count; i++) { SpriteGrid spriteGrid = mSpriteGrids[i]; spriteGrid.Shift(shiftVector.X, shiftVector.Y, shiftVector.Z); spriteGrid.XLeftBound += shiftVector.X; spriteGrid.XRightBound += shiftVector.X; spriteGrid.YTopBound += shiftVector.Y; spriteGrid.YBottomBound += shiftVector.Y; spriteGrid.ZCloseBound += shiftVector.Z; spriteGrid.ZFarBound += shiftVector.Z; } mSpriteFrames.Shift(shiftVector); mTexts.Shift(shiftVector); } public void ShiftRelative(float x, float y, float z) { ShiftRelative(new Vector3(x, y, z)); } public void ShiftRelative(Vector3 relativeShiftVector) { mSprites.ShiftRelative(relativeShiftVector); // SpriteGrids don't attach //for (int i = 0; i < mSpriteGrids.Count; i++) //{ // SpriteGrid spriteGrid = mSpriteGrids[i]; // spriteGrid.Shift(shiftVector.X, shiftVector.Y, shiftVector.Z); //} mSpriteFrames.ShiftRelative(relativeShiftVector); mTexts.ShiftRelative(relativeShiftVector); } public override string ToString() { return "Scene: " + mName; } public void UpdateDependencies(double currentTime) { for (int i = 0; i < mSprites.Count; i++) { Sprite sprite = mSprites[i]; sprite.UpdateDependencies(currentTime); } for (int i = 0; i < mSpriteFrames.Count; i++) { SpriteFrame spriteFrame = mSpriteFrames[i]; spriteFrame.UpdateDependencies(currentTime); } for (int i = 0; i < mTexts.Count; i++) { Text text = mTexts[i]; text.UpdateDependencies(currentTime); } } #endregion #endregion #region IEquatable<Scene> Members bool IEquatable<Scene>.Equals(Scene other) { return this == other; } #endregion #if FRB_XNA #region IMouseOver bool IMouseOver.IsMouseOver(Cursor cursor) { return cursor.IsOn3D(this, null); } public bool IsMouseOver(Cursor cursor, Layer layer) { return cursor.IsOn3D(this, layer); } #endregion #endif } }
//--------------------------------------------------------------------------- // // Copyright (C) Microsoft Corporation. All rights reserved. // // File: avelementhelper.cs // // Description: Contains the AVElementHelper class. // // History: // 05/04/2004 : [....] - Added // //--------------------------------------------------------------------------- using MS.Internal; using MS.Utility; using System.Diagnostics; using System.Windows.Threading; using System; using System.Windows.Documents; using System.Windows.Media; using System.Windows.Media.Animation; using System.Security; using System.Security.Permissions; namespace System.Windows.Controls { #region SettableState /// <summary> /// Settable State, keeps track of what state was set and whether it has /// been set recently. /// </summary> internal struct SettableState<T> { internal T _value; internal bool _isSet; internal bool _wasSet; internal SettableState( T value ) { _value = value; _isSet = _wasSet = false; } } #endregion #region AVElementHelper /// <summary> /// AVElementHelper /// </summary> internal class AVElementHelper { #region Constructor /// <summary> /// Constructor, point to the corresponding MediaElement. /// </summary> internal AVElementHelper(MediaElement element) { Debug.Assert((element != null), "Element is null"); _element = element; _position = new SettableState<TimeSpan>(new TimeSpan(0)); // // We always start off in a closed state. // _mediaState = new SettableState<MediaState>(MediaState.Close); _source = new SettableState<Uri>(null); _clock = new SettableState<MediaClock>(null); _speedRatio = new SettableState<double>(1.0); _volume = new SettableState<double>(0.5); _isMuted = new SettableState<bool>(false); _balance = new SettableState<double>(0.0); _isScrubbingEnabled = new SettableState<bool>(false); _mediaPlayer = new MediaPlayer(); HookEvents(); } #endregion #region Internal and Private Properties / Methods /// <summary> /// Returns the helper class given a dependency object /// </summary> internal static AVElementHelper GetHelper(DependencyObject d) { MediaElement mediaElement = d as MediaElement; if (mediaElement != null) { return mediaElement.Helper; } else { throw new ArgumentException(SR.Get(SRID.AudioVideo_InvalidDependencyObject)); } } /// <summary> /// MediaPlayer associated with the element. /// </summary> internal MediaPlayer Player { get { return _mediaPlayer; } } /// <summary> /// Base Uri to use when resolving relative Uri's /// </summary> internal Uri BaseUri { get { return _baseUri; } set { // ignore pack URIs for now (see work items 45396 and 41636) if (value.Scheme != System.IO.Packaging.PackUriHelper.UriSchemePack) { _baseUri = value; } else { _baseUri = null; } } } /// <summary> /// Allows the behavior the Media Element should have when it is unloaded /// to be expressed. This is a method because it can have side-effects /// (Media could start playing or pause or perform a number of other /// actions). /// </summary> internal void SetUnloadedBehavior( MediaState unloadedBehavior ) { _unloadedBehavior = unloadedBehavior; HandleStateChange(); } /// <summary> /// Changes the loaded behavior. This is a method because it can cause /// side effects on other properties. (It could cause me to start or /// stop playing, for example). /// </summary> internal void SetLoadedBehavior( MediaState loadedBehavior ) { _loadedBehavior = loadedBehavior; HandleStateChange(); } /// <summary> /// Returns the current position of the media. /// </summary> internal TimeSpan Position { get { // // If we have been closed, position is just a cached value, // return it. // if (_currentState == MediaState.Close) { return _position._value; } else { return _mediaPlayer.Position; } } } /// <summary> /// Sets the current position of the media. This is a method /// and not a property because it has side effects. /// </summary> internal void SetPosition( TimeSpan position ) { _position._isSet = true; _position._value = position; // // If the media isn't closed, then we can actually send // this down to the unmanaged state engine. It gets // snippy if you try to change the position when it // is closed. // HandleStateChange(); } internal MediaClock Clock { get { return _clock._value; } } internal void SetClock( MediaClock clock ) { _clock._value = clock; // // We don't use _wasSet for clocks because our behavior changes dramatically // whether _value is null or not. // _clock._isSet = true; HandleStateChange(); } internal double SpeedRatio { get { return _speedRatio._value; } } internal void SetSpeedRatio( double speedRatio ) { _speedRatio._wasSet = _speedRatio._isSet = true; _speedRatio._value = speedRatio; HandleStateChange(); } internal void SetState( MediaState mediaState ) { // // If the caller hasn't requested any loaded or unloaded behavior to be manual // then calls to Play/Pause/Stop etc. will never take effect. // if (_loadedBehavior != MediaState.Manual && _unloadedBehavior != MediaState.Manual) { throw new NotSupportedException(SR.Get(SRID.AudioVideo_CannotControlMedia)); } _mediaState._value = mediaState; _mediaState._isSet = true; HandleStateChange(); } internal void SetVolume( double volume ) { _volume._wasSet = _volume._isSet = true; _volume._value = volume; HandleStateChange(); } internal void SetBalance( double balance ) { _balance._wasSet = _balance._isSet = true; _balance._value = balance; HandleStateChange(); } internal void SetIsMuted( bool isMuted ) { _isMuted._wasSet = _isMuted._isSet = true; _isMuted._value = isMuted; HandleStateChange(); } internal void SetScrubbingEnabled( bool isScrubbingEnabled ) { _isScrubbingEnabled._wasSet = _isScrubbingEnabled._isSet = true; _isScrubbingEnabled._value = isScrubbingEnabled; HandleStateChange(); } /// <summary> /// Hook Events when clock is created/changed /// </summary> private void HookEvents() { // register the new clock events _mediaPlayer.MediaOpened += new EventHandler(OnMediaOpened); _mediaPlayer.MediaFailed += new EventHandler<ExceptionEventArgs>(OnMediaFailed); _mediaPlayer.BufferingStarted += new EventHandler(OnBufferingStarted); _mediaPlayer.BufferingEnded += new EventHandler(OnBufferingEnded); _mediaPlayer.MediaEnded += new EventHandler(OnMediaEnded); _mediaPlayer.ScriptCommand += new EventHandler<MediaScriptCommandEventArgs>(OnScriptCommand); _element.Loaded += new RoutedEventHandler(this.OnLoaded); _element.Unloaded += new RoutedEventHandler(this.OnUnloaded); } /// <summary> /// All state changes to the media element come through this code, we first /// look at all of the media element properties and the loaded behavior and /// source property to see whether to open or close the media, the we set /// other properties that actually control media and have been cached up. /// </summary> private void HandleStateChange( ) { // // First, just assume that our requested actions are going to be // the same as the media requested actions. // MediaState thisStateRequest = _mediaState._value; bool openClock = false; bool actionRequested = false; // // If the element is loaded // if (_isLoaded) { // // If we have a clock, then our loaded behavior is always manual. // The clock always wins. // if (_clock._value != null) { thisStateRequest = MediaState.Manual; openClock = true; } // // If the loaded behavior was set, it wins over whether the // source was set or not. // else if (_loadedBehavior != MediaState.Manual) { // // If it is manual, it doesn't override the requested state. // thisStateRequest = _loadedBehavior; } else if (_source._wasSet) { if (_loadedBehavior != MediaState.Manual) { thisStateRequest = MediaState.Play; } else { actionRequested = true; } } } else { // // If the unloaded behavior is manual, it doesn't override the // requested state, // if (_unloadedBehavior != MediaState.Manual) { thisStateRequest = _unloadedBehavior; } else { // // For situations in which we don't received loaded and unloaded // events, (like VisualBrush), we need to set our UnloadedBehavior // to Manual in order to allow storyboards to be able to control // the media element. // Invariant.Assert(_unloadedBehavior == MediaState.Manual); if (_clock._value != null) { thisStateRequest = MediaState.Manual; openClock = true; } // // Otherwise, an action was requested, we need to take it. // else { actionRequested = true; } } } bool openedMedia = false; // // If the media state is anything other than close // and the current state is closed, the media needs to be opened. // if ( thisStateRequest != MediaState.Close && thisStateRequest != MediaState.Manual) { // // We shouldn't have a clock to open because this would have a state // request of MediaState.Manual. // Invariant.Assert(openClock == false); // // If we had a clock, get rid of it now. This is to handle the case // where UnloadedBehavior is specified after the timing engine has // been in control. // if (_mediaPlayer.Clock != null) { _mediaPlayer.Clock = null; } // // If we are currently closed, we should open. If the source property // was assigned, we should also open. // if (_currentState == MediaState.Close || _source._isSet) { // // ScrubbingEnabled needs to be set before opening media in // order to get the initial scrub. // if (_isScrubbingEnabled._wasSet) { _mediaPlayer.ScrubbingEnabled = _isScrubbingEnabled._value; _isScrubbingEnabled._isSet = false; } if (_clock._value == null) { _mediaPlayer.Open(UriFromSourceUri(_source._value)); } openedMedia = true; } } else if (openClock) { // // If either we were closed before, or if a clock was re-assigned without // a state transition, then, re-apply the clock. // if (_currentState == MediaState.Close || _clock._isSet) { // // ScrubbingEnabled needs to be set before opening media in // order to get the initial scrub. // if (_isScrubbingEnabled._wasSet) { _mediaPlayer.ScrubbingEnabled = _isScrubbingEnabled._value; _isScrubbingEnabled._isSet = false; } _mediaPlayer.Clock = _clock._value; _clock._isSet = false; openedMedia = true; } } // // Otherwise, if the request is for a Close and and we aren't in a closed state, // we need to close. // else if (thisStateRequest == MediaState.Close) { if (_currentState != MediaState.Close) { // // Dis-associate the clock from the player (if it has one). // (Otherwise, it won't let us close it). // _mediaPlayer.Clock = null; _mediaPlayer.Close(); _currentState = MediaState.Close; } } // // If we either just opened the media, or if we weren't closed in the // first place, we get to perform all of the other actions. // if (_currentState != MediaState.Close || openedMedia) { // // If we have a position request, do it now. // if (_position._isSet) { _mediaPlayer.Position = _position._value; _position._isSet = false; } // // Do volume state changes before a play so that we don't get either // no sound or a loud sound on the play transition. // if (_volume._isSet || openedMedia && _volume._wasSet) { _mediaPlayer.Volume = _volume._value; _volume._isSet = false; } if (_balance._isSet || openedMedia && _balance._wasSet) { _mediaPlayer.Balance = _balance._value; _balance._isSet = false; } if (_isMuted._isSet || openedMedia && _isMuted._wasSet) { _mediaPlayer.IsMuted = _isMuted._value; _isMuted._isSet = false; } // // In the case that openedMedia is true, we will have already // applied the scrubbing enabled property prior to opening the // media. This is necessary for initial scrubbing to work // if (_isScrubbingEnabled._isSet) { _mediaPlayer.ScrubbingEnabled = _isScrubbingEnabled._value; _isScrubbingEnabled._isSet = false; } // // If we are asked to play because the source was reset, // then, start playing the media again. // if (thisStateRequest == MediaState.Play && _source._isSet) { // // We always want to Play() and then set the SpeedRatio to // 1. This ensures that whwn you change the source of a // MediaElement via databinding, we start playing the // media again. // _mediaPlayer.Play(); if (!_speedRatio._wasSet) { _mediaPlayer.SpeedRatio = 1; } // // We have effectively `swallowed the "Play" request, if this is // what finally brought us into this code path. // _source._isSet = false; _mediaState._isSet = false; } // // Might be missing out on a Play, Pause, or a stop. // If the source is changed, we always want to do the // requested action. Also, we want to mirror each call // to Play, Pause and Stop down to the underlying player. // else if ( _currentState != thisStateRequest || (actionRequested && _mediaState._isSet)) { switch(thisStateRequest) { case MediaState.Play: _mediaPlayer.Play(); break; case MediaState.Pause: _mediaPlayer.Pause(); break; case MediaState.Stop: _mediaPlayer.Stop(); break; case MediaState.Manual: break; default: Invariant.Assert(false, "Unexpected state request."); break; } // // If we did this transition because an action was requested, make sure // we don't do it again when we come in. // if (actionRequested) { _mediaState._isSet = false; } } _currentState = thisStateRequest; // // Finally, if the speed ratio has been set, change it. // if (_speedRatio._isSet || openedMedia && _speedRatio._wasSet) { _mediaPlayer.SpeedRatio = _speedRatio._value; _speedRatio._isSet = false; } } } /// <summary> /// Looks at the current uri and the base uri and uses it to determine /// whether we should normalize the uri to the base or not. /// </summary> private Uri UriFromSourceUri( Uri sourceUri ) { if (sourceUri != null) { if (sourceUri.IsAbsoluteUri) { return sourceUri; } else if (BaseUri != null) { return new Uri(BaseUri, sourceUri); } } return sourceUri; } #endregion #region Delegates /// <summary> /// Raised when source is changed /// </summary> /// <SecurityNote> /// Critical: This code calls into PresentationSource.CriticalFromVisual to /// extract presentationsource. /// TreatAsSafe: The value is not exposed and the call simply checks to see /// if the value is null /// </SecurityNote> [SecurityCritical,SecurityTreatAsSafe] internal static void OnSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { if (e.IsASubPropertyChange) { return; } AVElementHelper aveh = AVElementHelper.GetHelper(d); aveh.MemberOnInvalidateSource(e); // call non-static } private void MemberOnInvalidateSource(DependencyPropertyChangedEventArgs e) { if (_clock._value != null) { throw new InvalidOperationException(SR.Get(SRID.MediaElement_CannotSetSourceOnMediaElementDrivenByClock)); } _source._value = (Uri)e.NewValue; _source._wasSet = _source._isSet = true; HandleStateChange(); } /// <summary> /// Raised when there is a error with media playback /// </summary> private void OnMediaFailed( object sender, ExceptionEventArgs args ) { // // Propagate the error to the media element. // _element.OnMediaFailed(sender, args); } /// <summary> /// Raised when media is opened /// </summary> private void OnMediaOpened( object sender, EventArgs args ) { // Whenever a new file is opened the size of the MediaElement may change _element.InvalidateMeasure(); _element.OnMediaOpened(sender, args); } private void OnBufferingStarted( object sender, EventArgs args ) { _element.OnBufferingStarted(sender, args); } private void OnBufferingEnded( object sender, EventArgs args ) { _element.OnBufferingEnded(sender, args); } private void OnMediaEnded( object sender, EventArgs args ) { _element.OnMediaEnded(sender, args); } private void OnScriptCommand( object sender, MediaScriptCommandEventArgs args ) { _element.OnScriptCommand(sender, args); } private void OnLoaded( object sender, RoutedEventArgs args ) { _isLoaded = true; HandleStateChange(); } private void OnUnloaded( object sender, RoutedEventArgs args ) { _isLoaded = false; HandleStateChange(); } #endregion #region Data Members /// <summary> /// MediaPlayer /// </summary> private MediaPlayer _mediaPlayer; /// <summary> /// UIElement that owns this helper /// </summary> private MediaElement _element; private Uri _baseUri; private MediaState _unloadedBehavior = MediaState.Close; private MediaState _loadedBehavior = MediaState.Play; private MediaState _currentState = MediaState.Close; private bool _isLoaded = false; // // The requested state, we need to know for each one whether it // was ever set and for // SettableState<TimeSpan> _position; SettableState<MediaState> _mediaState; SettableState<Uri> _source; SettableState<MediaClock> _clock; SettableState<double> _speedRatio; SettableState<double> _volume; SettableState<bool> _isMuted; SettableState<double> _balance; SettableState<bool> _isScrubbingEnabled; #endregion } #endregion }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #pragma warning disable 1634, 1691 #pragma warning disable 56506 using System.Runtime.Serialization; using System.Diagnostics.CodeAnalysis; using System.Management.Automation.Internal; #pragma warning disable 1634, 1691 // Stops compiler from warning about unknown warnings namespace System.Management.Automation { #region CmdletInvocationException /// <summary> /// Indicates that a cmdlet hit a terminating error. /// </summary> /// <remarks> /// InnerException is the error which the cmdlet hit. /// </remarks> [Serializable] public class CmdletInvocationException : RuntimeException { #region ctor /// <summary> /// Instantiates a new instance of the CmdletInvocationException class. /// </summary> /// <param name="errorRecord"></param> internal CmdletInvocationException(ErrorRecord errorRecord) : base(RetrieveMessage(errorRecord), RetrieveException(errorRecord)) { if (errorRecord == null) { throw new ArgumentNullException(nameof(errorRecord)); } _errorRecord = errorRecord; if (errorRecord.Exception != null) { // 2005/04/13-JonN Can't do this in an unsealed class: HelpLink = errorRecord.Exception.HelpLink; // Exception.Source is set by Throw // Source = errorRecord.Exception.Source; } } /// <summary> /// Instantiates a new instance of the CmdletInvocationException class. /// </summary> /// <param name="innerException">Wrapped exception.</param> /// <param name="invocationInfo"> /// identity of cmdlet, null is unknown /// </param> internal CmdletInvocationException(Exception innerException, InvocationInfo invocationInfo) : base(RetrieveMessage(innerException), innerException) { if (innerException == null) { throw new ArgumentNullException(nameof(innerException)); } // invocationInfo may be null IContainsErrorRecord icer = innerException as IContainsErrorRecord; if (icer != null && icer.ErrorRecord != null) { _errorRecord = new ErrorRecord(icer.ErrorRecord, innerException); } else { // When no ErrorId is specified by a thrown exception, // we use innerException.GetType().FullName. _errorRecord = new ErrorRecord( innerException, innerException.GetType().FullName, ErrorCategory.NotSpecified, null); } _errorRecord.SetInvocationInfo(invocationInfo); // 2005/04/13-JonN Can't do this in an unsealed class: HelpLink = innerException.HelpLink; // Exception.Source is set by Throw // Source = innerException.Source; } /// <summary> /// Instantiates a new instance of the CmdletInvocationException class. /// </summary> public CmdletInvocationException() : base() { } /// <summary> /// Instantiates a new instance of the CmdletInvocationException class. /// </summary> /// <param name="message"></param> /// <returns>Constructed object.</returns> public CmdletInvocationException(string message) : base(message) { } /// <summary> /// Instantiates a new instance of the CmdletInvocationException class. /// </summary> /// <param name="message"></param> /// <param name="innerException"></param> /// <returns>Constructed object.</returns> public CmdletInvocationException(string message, Exception innerException) : base(message, innerException) { } #region Serialization /// <summary> /// Initializes a new instance of the CmdletInvocationException class /// using data serialized via /// <see cref="ISerializable"/> /// </summary> /// <param name="info">Serialization information.</param> /// <param name="context">Streaming context.</param> /// <returns>Constructed object.</returns> protected CmdletInvocationException(SerializationInfo info, StreamingContext context) : base(info, context) { bool hasErrorRecord = info.GetBoolean("HasErrorRecord"); if (hasErrorRecord) _errorRecord = (ErrorRecord)info.GetValue("ErrorRecord", typeof(ErrorRecord)); } /// <summary> /// Serializer for <see cref="ISerializable"/> /// </summary> /// <param name="info">Serialization information.</param> /// <param name="context">Streaming context.</param> public override void GetObjectData(SerializationInfo info, StreamingContext context) { if (info == null) { throw new PSArgumentNullException(nameof(info)); } base.GetObjectData(info, context); bool hasErrorRecord = (_errorRecord != null); info.AddValue("HasErrorRecord", hasErrorRecord); if (hasErrorRecord) info.AddValue("ErrorRecord", _errorRecord); } #endregion Serialization #endregion ctor #region Properties /// <summary> /// The error reported by the cmdlet. /// </summary> /// <value>never null</value> public override ErrorRecord ErrorRecord { get { if (_errorRecord == null) { _errorRecord = new ErrorRecord( new ParentContainsErrorRecordException(this), "CmdletInvocationException", ErrorCategory.NotSpecified, null); } return _errorRecord; } } private ErrorRecord _errorRecord = null; #endregion Properties } #endregion CmdletInvocationException #region CmdletProviderInvocationException /// <summary> /// Indicates that a cmdlet hit a terminating error of type /// <see cref="System.Management.Automation.ProviderInvocationException"/>. /// This is generally reported from the standard provider navigation cmdlets /// such as get-childitem. /// </summary> [Serializable] public class CmdletProviderInvocationException : CmdletInvocationException { #region ctor /// <summary> /// Instantiates a new instance of the CmdletProviderInvocationException class. /// </summary> /// <param name="innerException">Wrapped exception.</param> /// <param name="myInvocation"> /// identity of cmdlet, null is unknown /// </param> /// <returns>Constructed object.</returns> internal CmdletProviderInvocationException( ProviderInvocationException innerException, InvocationInfo myInvocation) : base(GetInnerException(innerException), myInvocation) { if (innerException == null) { throw new ArgumentNullException(nameof(innerException)); } _providerInvocationException = innerException; } /// <summary> /// Instantiates a new instance of the CmdletProviderInvocationException class. /// </summary> /// <returns>Constructed object.</returns> public CmdletProviderInvocationException() : base() { } /// <summary> /// Initializes a new instance of the CmdletProviderInvocationException class /// using data serialized via /// <see cref="ISerializable"/> /// </summary> /// <param name="info">Serialization information.</param> /// <param name="context">Streaming context.</param> /// <returns>Constructed object.</returns> protected CmdletProviderInvocationException(SerializationInfo info, StreamingContext context) : base(info, context) { _providerInvocationException = InnerException as ProviderInvocationException; } /// <summary> /// Instantiates a new instance of the CmdletProviderInvocationException class. /// </summary> /// <param name="message"></param> /// <returns>Constructed object.</returns> public CmdletProviderInvocationException(string message) : base(message) { } /// <summary> /// Instantiates a new instance of the CmdletProviderInvocationException class. /// </summary> /// <param name="message"></param> /// <param name="innerException"></param> /// <returns>Constructed object.</returns> public CmdletProviderInvocationException(string message, Exception innerException) : base(message, innerException) { _providerInvocationException = innerException as ProviderInvocationException; } #endregion ctor #region Properties /// <summary> /// InnerException as ProviderInvocationException. /// </summary> /// <value>ProviderInvocationException</value> public ProviderInvocationException ProviderInvocationException { get { return _providerInvocationException; } } [NonSerialized] private readonly ProviderInvocationException _providerInvocationException; /// <summary> /// This is the ProviderInfo associated with the provider which /// generated the error. /// </summary> /// <value>may be null</value> public ProviderInfo ProviderInfo { get { return _providerInvocationException?.ProviderInfo; } } #endregion Properties #region Internal private static Exception GetInnerException(Exception e) { return e?.InnerException; } #endregion Internal } #endregion CmdletProviderInvocationException #region PipelineStoppedException /// <summary> /// Indicates that the pipeline has already been stopped. /// </summary> /// <remarks> /// When reported as the result of a command, PipelineStoppedException /// indicates that the command was stopped asynchronously, either by the /// user hitting CTRL-C, or by a call to /// <see cref="System.Management.Automation.Runspaces.Pipeline.Stop"/>. /// /// When a cmdlet or provider sees this exception thrown from a Monad API such as /// WriteObject(object) /// this means that the command was already stopped. The cmdlet or provider /// should clean up and return. /// Catching this exception is optional; if the cmdlet or providers chooses not to /// handle PipelineStoppedException and instead allow it to propagate to the /// Monad Engine's call to ProcessRecord, the Monad Engine will handle it properly. /// </remarks> [Serializable] public class PipelineStoppedException : RuntimeException { #region ctor /// <summary> /// Instantiates a new instance of the PipelineStoppedException class. /// </summary> /// <returns>Constructed object.</returns> public PipelineStoppedException() : base(GetErrorText.PipelineStoppedException) { SetErrorId("PipelineStopped"); SetErrorCategory(ErrorCategory.OperationStopped); } /// <summary> /// Initializes a new instance of the PipelineStoppedException class /// using data serialized via /// <see cref="ISerializable"/> /// </summary> /// <param name="info">Serialization information.</param> /// <param name="context">Streaming context.</param> /// <returns>Constructed object.</returns> protected PipelineStoppedException(SerializationInfo info, StreamingContext context) : base(info, context) { // no properties, nothing more to serialize // no need for a GetObjectData implementation } /// <summary> /// Instantiates a new instance of the PipelineStoppedException class. /// </summary> /// <param name="message"></param> /// <returns>Constructed object.</returns> public PipelineStoppedException(string message) : base(message) { } /// <summary> /// Instantiates a new instance of the PipelineStoppedException class. /// </summary> /// <param name="message"></param> /// <param name="innerException"></param> /// <returns>Constructed object.</returns> public PipelineStoppedException(string message, Exception innerException) : base(message, innerException) { } #endregion ctor } #endregion PipelineStoppedException #region PipelineClosedException /// <summary> /// PipelineClosedException occurs when someone tries to write /// to an asynchronous pipeline source and the pipeline has already /// been stopped. /// </summary> /// <seealso cref="System.Management.Automation.Runspaces.Pipeline.Input"/> [Serializable] public class PipelineClosedException : RuntimeException { #region ctor /// <summary> /// Instantiates a new instance of the PipelineClosedException class. /// </summary> /// <returns>Constructed object.</returns> public PipelineClosedException() : base() { } /// <summary> /// Instantiates a new instance of the PipelineClosedException class. /// </summary> /// <param name="message"></param> /// <returns>Constructed object.</returns> public PipelineClosedException(string message) : base(message) { } /// <summary> /// Instantiates a new instance of the PipelineClosedException class. /// </summary> /// <param name="message"></param> /// <param name="innerException"></param> /// <returns>Constructed object.</returns> public PipelineClosedException(string message, Exception innerException) : base(message, innerException) { } #endregion ctor #region Serialization /// <summary> /// Initializes a new instance of the PipelineClosedException class /// using data serialized via /// <see cref="ISerializable"/> /// </summary> /// <param name="info">Serialization information.</param> /// <param name="context">Streaming context.</param> /// <returns>Constructed object.</returns> protected PipelineClosedException(SerializationInfo info, StreamingContext context) : base(info, context) { } #endregion Serialization } #endregion PipelineClosedException #region ActionPreferenceStopException /// <summary> /// ActionPreferenceStopException indicates that the command stopped due /// to the ActionPreference.Stop or Inquire policy. /// </summary> /// <remarks> /// For example, if $WarningPreference is "Stop", the command will fail with /// this error if a cmdlet calls WriteWarning. /// </remarks> [Serializable] public class ActionPreferenceStopException : RuntimeException { #region ctor /// <summary> /// Instantiates a new instance of the ActionPreferenceStopException class. /// </summary> /// <returns>Constructed object.</returns> public ActionPreferenceStopException() : this(GetErrorText.ActionPreferenceStop) { } /// <summary> /// Instantiates a new instance of the ActionPreferenceStopException class. /// </summary> /// <param name="error"> /// Non-terminating error which triggered the Stop /// </param> /// <returns>Constructed object.</returns> internal ActionPreferenceStopException(ErrorRecord error) : this(RetrieveMessage(error)) { if (error == null) { throw new ArgumentNullException(nameof(error)); } _errorRecord = error; } /// <summary> /// Instantiates a new instance of the ActionPreferenceStopException class. /// </summary> /// <param name="invocationInfo"></param> /// <param name="message"></param> /// <returns>Constructed object.</returns> internal ActionPreferenceStopException(InvocationInfo invocationInfo, string message) : this(message) { base.ErrorRecord.SetInvocationInfo(invocationInfo); } /// <summary> /// Instantiates a new instance of the ActionPreferenceStopException class. /// </summary> internal ActionPreferenceStopException(InvocationInfo invocationInfo, ErrorRecord errorRecord, string message) : this(invocationInfo, message) { if (errorRecord == null) { throw new ArgumentNullException(nameof(errorRecord)); } _errorRecord = errorRecord; } #region Serialization /// <summary> /// Initializes a new instance of the ActionPreferenceStopException class /// using data serialized via /// <see cref="ISerializable"/> /// </summary> /// <param name="info">Serialization information.</param> /// <param name="context">Streaming context.</param> /// <returns>Constructed object.</returns> protected ActionPreferenceStopException(SerializationInfo info, StreamingContext context) : base(info, context) { bool hasErrorRecord = info.GetBoolean("HasErrorRecord"); if (hasErrorRecord) _errorRecord = (ErrorRecord)info.GetValue("ErrorRecord", typeof(ErrorRecord)); // fix for BUG: Windows Out Of Band Releases: 906263 and 906264 // The interpreter prompt CommandBaseStrings:InquireHalt // should be suppressed when this flag is set. This will be set // when this prompt has already occurred and Break was chosen, // or for ActionPreferenceStopException in all cases. this.SuppressPromptInInterpreter = true; } /// <summary> /// Serializer for <see cref="ISerializable"/> /// </summary> /// <param name="info">Serialization information.</param> /// <param name="context">Streaming context.</param> public override void GetObjectData(SerializationInfo info, StreamingContext context) { base.GetObjectData(info, context); if (info != null) { bool hasErrorRecord = (_errorRecord != null); info.AddValue("HasErrorRecord", hasErrorRecord); if (hasErrorRecord) { info.AddValue("ErrorRecord", _errorRecord); } } // fix for BUG: Windows Out Of Band Releases: 906263 and 906264 // The interpreter prompt CommandBaseStrings:InquireHalt // should be suppressed when this flag is set. This will be set // when this prompt has already occurred and Break was chosen, // or for ActionPreferenceStopException in all cases. this.SuppressPromptInInterpreter = true; } #endregion Serialization /// <summary> /// Instantiates a new instance of the ActionPreferenceStopException class. /// </summary> /// <param name="message"></param> /// <returns>Constructed object.</returns> public ActionPreferenceStopException(string message) : base(message) { SetErrorCategory(ErrorCategory.OperationStopped); SetErrorId("ActionPreferenceStop"); // fix for BUG: Windows Out Of Band Releases: 906263 and 906264 // The interpreter prompt CommandBaseStrings:InquireHalt // should be suppressed when this flag is set. This will be set // when this prompt has already occurred and Break was chosen, // or for ActionPreferenceStopException in all cases. this.SuppressPromptInInterpreter = true; } /// <summary> /// Instantiates a new instance of the ActionPreferenceStopException class. /// </summary> /// <param name="message"></param> /// <param name="innerException"></param> /// <returns>Constructed object.</returns> public ActionPreferenceStopException(string message, Exception innerException) : base(message, innerException) { SetErrorCategory(ErrorCategory.OperationStopped); SetErrorId("ActionPreferenceStop"); // fix for BUG: Windows Out Of Band Releases: 906263 and 906264 // The interpreter prompt CommandBaseStrings:InquireHalt // should be suppressed when this flag is set. This will be set // when this prompt has already occurred and Break was chosen, // or for ActionPreferenceStopException in all cases. this.SuppressPromptInInterpreter = true; } #endregion ctor #region Properties /// <summary> /// See <see cref="System.Management.Automation.IContainsErrorRecord"/> /// </summary> /// <value>ErrorRecord</value> /// <remarks> /// If this error results from a non-terminating error being promoted to /// terminating due to -ErrorAction or $ErrorActionPreference, this is /// the non-terminating error. /// </remarks> public override ErrorRecord ErrorRecord { get { return _errorRecord ?? base.ErrorRecord; } } private readonly ErrorRecord _errorRecord = null; #endregion Properties } #endregion ActionPreferenceStopException #region ParentContainsErrorRecordException /// <summary> /// ParentContainsErrorRecordException is the exception contained by the ErrorRecord /// which is associated with a Monad engine custom exception through /// the IContainsErrorRecord interface. /// </summary> /// <remarks> /// We use this exception class /// so that there is not a recursive "containment" relationship /// between the Monad engine exception and its ErrorRecord. /// </remarks> [Serializable] public class ParentContainsErrorRecordException : SystemException { #region Constructors /// <summary> /// Instantiates a new instance of the ParentContainsErrorRecordException class. /// Note that this sets the Message and not the InnerException. /// </summary> /// <returns>Constructed object.</returns> /// <remarks> /// I leave this non-standard constructor form public. /// </remarks> #pragma warning disable 56506 // BUGBUG : We should check whether wrapperException is not null. // Please remove the #pragma warning when this is fixed. public ParentContainsErrorRecordException(Exception wrapperException) { _wrapperException = wrapperException; } #pragma warning restore 56506 /// <summary> /// Instantiates a new instance of the ParentContainsErrorRecordException class. /// </summary> /// <param name="message"></param> /// <returns>Constructed object.</returns> public ParentContainsErrorRecordException(string message) { _message = message; } /// <summary> /// Instantiates a new instance of the ParentContainsErrorRecordException class. /// </summary> /// <returns>Constructed object.</returns> public ParentContainsErrorRecordException() : base() { } /// <summary> /// Instantiates a new instance of the ParentContainsErrorRecordException class. /// </summary> /// <param name="message"></param> /// <param name="innerException"></param> /// <returns>Constructed object.</returns> public ParentContainsErrorRecordException(string message, Exception innerException) : base(message, innerException) { _message = message; } #endregion Constructors #region Serialization /// <summary> /// Initializes a new instance of the ParentContainsErrorRecordException class /// using data serialized via /// <see cref="ISerializable"/> /// </summary> /// <param name="info">Serialization information.</param> /// <param name="context">Streaming context.</param> /// <returns>Doesn't return.</returns> /// <exception cref="NotImplementedException">Always.</exception> protected ParentContainsErrorRecordException( SerializationInfo info, StreamingContext context) : base(info, context) { _message = info.GetString("ParentContainsErrorRecordException_Message"); } #endregion Serialization /// <summary> /// Gets the message for the exception. /// </summary> public override string Message { get { return _message ??= (_wrapperException != null) ? _wrapperException.Message : string.Empty; } } /// <summary> /// Serializer for <see cref="ISerializable"/> /// </summary> /// <param name="info">Serialization information.</param> /// <param name="context">Context.</param> public override void GetObjectData(SerializationInfo info, StreamingContext context) { if (info == null) { throw new PSArgumentNullException(nameof(info)); } base.GetObjectData(info, context); info.AddValue("ParentContainsErrorRecordException_Message", this.Message); } #region Private Data private readonly Exception _wrapperException; private string _message; #endregion } #endregion ParentContainsErrorRecordException #region RedirectedException /// <summary> /// Indicates that a success object was written and success-to-error ("1>&amp;2") /// has been specified. /// </summary> /// <remarks> /// The redirected object is available as /// <see cref="System.Management.Automation.ErrorRecord.TargetObject"/> /// in the ErrorRecord which contains this exception. /// </remarks> [Serializable] public class RedirectedException : RuntimeException { #region constructors /// <summary> /// Instantiates a new instance of the RedirectedException class. /// </summary> /// <returns>Constructed object.</returns> public RedirectedException() : base() { SetErrorId("RedirectedException"); SetErrorCategory(ErrorCategory.NotSpecified); } /// <summary> /// Instantiates a new instance of the RedirectedException class. /// </summary> /// <param name="message"></param> /// <returns>Constructed object.</returns> public RedirectedException(string message) : base(message) { SetErrorId("RedirectedException"); SetErrorCategory(ErrorCategory.NotSpecified); } /// <summary> /// Instantiates a new instance of the RedirectedException class. /// </summary> /// <param name="message"></param> /// <param name="innerException"></param> /// <returns>Constructed object.</returns> public RedirectedException(string message, Exception innerException) : base(message, innerException) { SetErrorId("RedirectedException"); SetErrorCategory(ErrorCategory.NotSpecified); } /// <summary> /// Initializes a new instance of the RedirectedException class /// using data serialized via /// <see cref="ISerializable"/> /// </summary> /// <param name="info">Serialization information.</param> /// <param name="context">Streaming context.</param> /// <returns>Constructed object.</returns> protected RedirectedException(SerializationInfo info, StreamingContext context) : base(info, context) { } #endregion constructors } #endregion RedirectedException #region ScriptCallDepthException /// <summary> /// ScriptCallDepthException occurs when the number of /// session state objects of this type in this scope /// exceeds the configured maximum. /// </summary> /// <remarks> /// When one Monad command or script calls another, this creates an additional /// scope. Some script expressions also create a scope. Monad imposes a maximum /// call depth to prevent stack overflows. The maximum call depth is configurable /// but generally high enough that scripts which are not deeply recursive /// should not have a problem. /// </remarks> [Serializable] public class ScriptCallDepthException : SystemException, IContainsErrorRecord { #region ctor /// <summary> /// Instantiates a new instance of the ScriptCallDepthException class. /// </summary> /// <returns>Constructed object.</returns> public ScriptCallDepthException() : base(GetErrorText.ScriptCallDepthException) { } /// <summary> /// Instantiates a new instance of the ScriptCallDepthException class. /// </summary> /// <param name="message"></param> /// <returns>Constructed object.</returns> public ScriptCallDepthException(string message) : base(message) { } /// <summary> /// Instantiates a new instance of the ScriptCallDepthException class. /// </summary> /// <param name="message"></param> /// <param name="innerException"></param> /// <returns>Constructed object.</returns> public ScriptCallDepthException(string message, Exception innerException) : base(message, innerException) { } #endregion ctor #region Serialization /// <summary> /// Initializes a new instance of the ScriptCallDepthException class /// using data serialized via /// <see cref="ISerializable"/> /// </summary> /// <param name="info">Serialization information.</param> /// <param name="context">Streaming context.</param> /// <returns>Constructed object.</returns> protected ScriptCallDepthException(SerializationInfo info, StreamingContext context) : base(info, context) { } /// <summary> /// Serializer for <see cref="ISerializable"/> /// </summary> /// <param name="info">Serialization information.</param> /// <param name="context">Context.</param> public override void GetObjectData(SerializationInfo info, StreamingContext context) { base.GetObjectData(info, context); } #endregion Serialization #region properties /// <summary> /// See <see cref="System.Management.Automation.IContainsErrorRecord"/> /// </summary> /// <value></value> /// <remarks> /// TargetObject is the offending call depth /// </remarks> public ErrorRecord ErrorRecord { get { if (_errorRecord == null) { _errorRecord = new ErrorRecord( new ParentContainsErrorRecordException(this), "CallDepthOverflow", ErrorCategory.InvalidOperation, CallDepth); } return _errorRecord; } } private ErrorRecord _errorRecord = null; /// <summary> /// Always 0 - depth is not tracked as there is no hard coded maximum. /// </summary> public int CallDepth { get { return 0; } } #endregion properties } #endregion ScriptCallDepthException #region PipelineDepthException /// <summary> /// PipelineDepthException occurs when the number of /// commands participating in a pipeline (object streaming) /// exceeds the configured maximum. /// </summary> /// <remarks> /// </remarks> [Serializable] public class PipelineDepthException : SystemException, IContainsErrorRecord { #region ctor /// <summary> /// Instantiates a new instance of the PipelineDepthException class. /// </summary> /// <returns>Constructed object.</returns> public PipelineDepthException() : base(GetErrorText.PipelineDepthException) { } /// <summary> /// Instantiates a new instance of the PipelineDepthException class. /// </summary> /// <param name="message"></param> /// <returns>Constructed object.</returns> public PipelineDepthException(string message) : base(message) { } /// <summary> /// Instantiates a new instance of the PipelineDepthException class. /// </summary> /// <param name="message"></param> /// <param name="innerException"></param> /// <returns>Constructed object.</returns> public PipelineDepthException(string message, Exception innerException) : base(message, innerException) { } #endregion ctor #region Serialization /// <summary> /// Initializes a new instance of the PipelineDepthException class /// using data serialized via /// <see cref="ISerializable"/> /// </summary> /// <param name="info">Serialization information.</param> /// <param name="context">Streaming context.</param> /// <returns>Constructed object.</returns> protected PipelineDepthException(SerializationInfo info, StreamingContext context) : base(info, context) { } /// <summary> /// Serializer for <see cref="ISerializable"/> /// </summary> /// <param name="info">Serialization information.</param> /// <param name="context">Context.</param> public override void GetObjectData(SerializationInfo info, StreamingContext context) { base.GetObjectData(info, context); } #endregion Serialization #region properties /// <summary> /// See <see cref="System.Management.Automation.IContainsErrorRecord"/> /// </summary> /// <value></value> /// <remarks> /// TargetObject is the offending call depth /// </remarks> [SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations")] public ErrorRecord ErrorRecord { get { if (_errorRecord == null) { _errorRecord = new ErrorRecord( new ParentContainsErrorRecordException(this), "CallDepthOverflow", ErrorCategory.InvalidOperation, CallDepth); } return _errorRecord; } } private ErrorRecord _errorRecord = null; /// <summary> /// Always 0 - depth is not tracked as there is no hard coded maximum. /// </summary> /// <value></value> public int CallDepth { get { return 0; } } #endregion properties } #endregion #region HaltCommandException /// <summary> /// A cmdlet/provider should throw HaltCommandException /// when it wants to terminate the running command without /// this being considered an error. /// </summary> /// <remarks> /// For example, "more" will throw HaltCommandException if the user hits "q". /// /// Only throw HaltCommandException from your implementation of ProcessRecord etc. /// /// Note that HaltCommandException does not define IContainsErrorRecord. /// This is because it is not reported to the user. /// </remarks> [Serializable] public class HaltCommandException : SystemException { #region ctor /// <summary> /// Instantiates a new instance of the HaltCommandException class. /// </summary> /// <returns>Constructed object.</returns> public HaltCommandException() : base(StringUtil.Format(AutomationExceptions.HaltCommandException)) { } /// <summary> /// Instantiates a new instance of the HaltCommandException class. /// </summary> /// <param name="message"></param> /// <returns>Constructed object.</returns> public HaltCommandException(string message) : base(message) { } /// <summary> /// Instantiates a new instance of the HaltCommandException class. /// </summary> /// <param name="message"></param> /// <param name="innerException"></param> /// <returns>Constructed object.</returns> public HaltCommandException(string message, Exception innerException) : base(message, innerException) { } #endregion ctor #region Serialization /// <summary> /// Initializes a new instance of the HaltCommandException class /// using data serialized via /// <see cref="ISerializable"/> /// </summary> /// <param name="info">Serialization information.</param> /// <param name="context">Streaming context.</param> /// <returns>Constructed object.</returns> protected HaltCommandException(SerializationInfo info, StreamingContext context) : base(info, context) { } #endregion Serialization } #endregion HaltCommandException } #pragma warning restore 56506
using System; using System.Collections.Generic; using System.Runtime.InteropServices; namespace NAudio.Wave.Compression { /// <summary> /// Represents an installed ACM Driver /// </summary> public class AcmDriver : IDisposable { private static List<AcmDriver> drivers; private readonly IntPtr driverId; private AcmDriverDetails details; private IntPtr driverHandle; private List<AcmFormatTag> formatTags; private List<AcmFormat> tempFormatsList; // used by enumerator /// <summary> /// Creates a new ACM Driver object /// </summary> /// <param name="hAcmDriver">Driver handle</param> private AcmDriver(IntPtr hAcmDriver) { driverId = hAcmDriver; details = new AcmDriverDetails(); details.structureSize = Marshal.SizeOf(details); MmException.Try(AcmInterop.acmDriverDetails(hAcmDriver, ref details, 0), "acmDriverDetails"); } /// <summary> /// Gets the maximum size needed to store a WaveFormat for ACM interop functions /// </summary> public int MaxFormatSize { get { int maxFormatSize = 0; MmException.Try(AcmInterop.acmMetrics(driverHandle, AcmMetrics.MaxSizeFormat, out maxFormatSize), "acmMetrics"); return maxFormatSize; } } /// <summary> /// The short name of this driver /// </summary> public string ShortName { get { return details.shortName; } } /// <summary> /// The full name of this driver /// </summary> public string LongName { get { return details.longName; } } /// <summary> /// The driver ID /// </summary> public IntPtr DriverId { get { return driverId; } } /// <summary> /// The list of FormatTags for this ACM Driver /// </summary> public IEnumerable<AcmFormatTag> FormatTags { get { if (formatTags == null) { if (driverHandle == IntPtr.Zero) { throw new InvalidOperationException("Driver must be opened first"); } formatTags = new List<AcmFormatTag>(); var formatTagDetails = new AcmFormatTagDetails(); formatTagDetails.structureSize = Marshal.SizeOf(formatTagDetails); MmException.Try( AcmInterop.acmFormatTagEnum(driverHandle, ref formatTagDetails, AcmFormatTagEnumCallback, IntPtr.Zero, 0), "acmFormatTagEnum"); } return formatTags; } } /// <summary> /// Helper function to determine whether a particular codec is installed /// </summary> /// <param name="shortName">The short name of the function</param> /// <returns>Whether the codec is installed</returns> public static bool IsCodecInstalled(string shortName) { foreach (AcmDriver driver in EnumerateAcmDrivers()) { if (driver.ShortName == shortName) { return true; } } return false; } /// <summary> /// Show Format Choose Dialog /// </summary> /// <param name="ownerWindowHandle">Owner window handle, can be null</param> /// <param name="windowTitle">Window title</param> /// <param name="enumFlags">Enumeration flags. None to get everything</param> /// <param name="enumFormat">Enumeration format. Only needed with certain enumeration flags</param> /// <param name="selectedFormat">The selected format</param> /// <param name="selectedFormatDescription">Textual description of the selected format</param> /// <param name="selectedFormatTagDescription">Textual description of the selected format tag</param> /// <returns>True if a format was selected</returns> public static bool ShowFormatChooseDialog( IntPtr ownerWindowHandle, string windowTitle, AcmFormatEnumFlags enumFlags, WaveFormat enumFormat, out WaveFormat selectedFormat, out string selectedFormatDescription, out string selectedFormatTagDescription) { var formatChoose = new AcmFormatChoose(); formatChoose.structureSize = Marshal.SizeOf(formatChoose); formatChoose.styleFlags = AcmFormatChooseStyleFlags.None; formatChoose.ownerWindowHandle = ownerWindowHandle; int maxFormatSize = 200; // guess formatChoose.selectedWaveFormatPointer = Marshal.AllocHGlobal(maxFormatSize); formatChoose.selectedWaveFormatByteSize = maxFormatSize; formatChoose.title = windowTitle; formatChoose.name = null; formatChoose.formatEnumFlags = enumFlags; //AcmFormatEnumFlags.None; formatChoose.waveFormatEnumPointer = IntPtr.Zero; if (enumFormat != null) { IntPtr enumPointer = Marshal.AllocHGlobal(Marshal.SizeOf(enumFormat)); Marshal.StructureToPtr(enumFormat, enumPointer, false); formatChoose.waveFormatEnumPointer = enumPointer; } formatChoose.instanceHandle = IntPtr.Zero; formatChoose.templateName = null; MmResult result = AcmInterop.acmFormatChoose(ref formatChoose); selectedFormat = null; selectedFormatDescription = null; selectedFormatTagDescription = null; if (result == MmResult.NoError) { selectedFormat = WaveFormat.MarshalFromPtr(formatChoose.selectedWaveFormatPointer); selectedFormatDescription = formatChoose.formatDescription; selectedFormatTagDescription = formatChoose.formatTagDescription; } Marshal.FreeHGlobal(formatChoose.waveFormatEnumPointer); Marshal.FreeHGlobal(formatChoose.selectedWaveFormatPointer); if (result != MmResult.AcmCancelled && result != MmResult.NoError) { throw new MmException(result, "acmFormatChoose"); } return result == MmResult.NoError; } /// <summary> /// Finds a Driver by its short name /// </summary> /// <param name="shortName">Short Name</param> /// <returns>The driver, or null if not found</returns> public static AcmDriver FindByShortName(string shortName) { foreach (AcmDriver driver in EnumerateAcmDrivers()) { if (driver.ShortName == shortName) { return driver; } } return null; } /// <summary> /// Gets a list of the ACM Drivers installed /// </summary> public static IEnumerable<AcmDriver> EnumerateAcmDrivers() { drivers = new List<AcmDriver>(); MmException.Try(AcmInterop.acmDriverEnum(DriverEnumCallback, IntPtr.Zero, 0), "acmDriverEnum"); return drivers; } /// <summary> /// The callback for acmDriverEnum /// </summary> private static bool DriverEnumCallback(IntPtr hAcmDriver, IntPtr dwInstance, AcmDriverDetailsSupportFlags flags) { drivers.Add(new AcmDriver(hAcmDriver)); return true; } /// <summary> /// ToString /// </summary> public override string ToString() { return LongName; } /// <summary> /// Gets all the supported formats for a given format tag /// </summary> /// <param name="formatTag">Format tag</param> /// <returns>Supported formats</returns> public IEnumerable<AcmFormat> GetFormats(AcmFormatTag formatTag) { if (driverHandle == IntPtr.Zero) { throw new InvalidOperationException("Driver must be opened first"); } tempFormatsList = new List<AcmFormat>(); var formatDetails = new AcmFormatDetails(); formatDetails.structSize = Marshal.SizeOf(formatDetails); formatDetails.waveFormatByteSize = MaxFormatSize; // formatTag.FormatSize doesn't work; formatDetails.waveFormatPointer = Marshal.AllocHGlobal(formatDetails.waveFormatByteSize); formatDetails.formatTag = (int) formatTag.FormatTag; // (int)WaveFormatEncoding.Unknown MmResult result = AcmInterop.acmFormatEnum(driverHandle, ref formatDetails, AcmFormatEnumCallback, IntPtr.Zero, AcmFormatEnumFlags.None); Marshal.FreeHGlobal(formatDetails.waveFormatPointer); MmException.Try(result, "acmFormatEnum"); return tempFormatsList; } /// <summary> /// Opens this driver /// </summary> public void Open() { if (driverHandle == IntPtr.Zero) { MmException.Try(AcmInterop.acmDriverOpen(out driverHandle, DriverId, 0), "acmDriverOpen"); } } /// <summary> /// Closes this driver /// </summary> public void Close() { if (driverHandle != IntPtr.Zero) { MmException.Try(AcmInterop.acmDriverClose(driverHandle, 0), "acmDriverClose"); driverHandle = IntPtr.Zero; } } private bool AcmFormatTagEnumCallback(IntPtr hAcmDriverId, ref AcmFormatTagDetails formatTagDetails, IntPtr dwInstance, AcmDriverDetailsSupportFlags flags) { formatTags.Add(new AcmFormatTag(formatTagDetails)); return true; } private bool AcmFormatEnumCallback(IntPtr hAcmDriverId, ref AcmFormatDetails formatDetails, IntPtr dwInstance, AcmDriverDetailsSupportFlags flags) { tempFormatsList.Add(new AcmFormat(formatDetails)); return true; } #region IDisposable Members /// <summary> /// Dispose /// </summary> public void Dispose() { if (driverHandle != IntPtr.Zero) { Close(); GC.SuppressFinalize(this); } } #endregion } }
/* *************************************************************************** * This file is part of SharpNEAT - Evolution of Neural Networks. * * Copyright 2004-2006, 2009-2010 Colin Green (sharpneat@gmail.com) * * SharpNEAT 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. * * SharpNEAT 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 SharpNEAT. If not, see <http://www.gnu.org/licenses/>. */ using System; using System.Collections; using System.Collections.Generic; using SharpNeat.Network; namespace SharpNeat.Genomes.Neat { // ENHANCEMENT: Consider switching to a SortedList[K,V] - which guarantees item sort order at all times. /// <summary> /// Represents a sorted list of NeuronGene objects. The sorting of the items is done on request /// rather than being strictly enforced at all times (e.g. as part of adding and removing items). This /// approach is currently more convenient for use in some of the routines that work with NEAT genomes. /// /// Because we are not using a strictly sorted list such as the generic class SortedList[K,V] a customised /// BinarySearch() method is provided for fast lookup of items if the list is known to be sorted. If the list is /// not sorted then the BinarySearch method's behaviour is undefined. This is potentially a source of bugs /// and thus this class should probably migrate to SortedList[K,V] or be modified to ensure items are sorted /// prior to a binary search. /// /// Sort order is with respect to connection gene innovation ID. /// </summary> public class NeuronGeneList : List<NeuronGene>, INodeList { #region Constructors /// <summary> /// Construct an empty list. /// </summary> public NeuronGeneList() { } /// <summary> /// Construct an empty list with the specified capacity. /// </summary> public NeuronGeneList(int capacity) : base(capacity) { } /// <summary> /// Copy constructor. The newly allocated list has a capacity 1 larger than copyFrom /// allowing for a single add node mutation to occur without reallocation of memory. /// </summary> public NeuronGeneList(ICollection<NeuronGene> copyFrom) : base(copyFrom.Count+1) { // ENHANCEMENT: List.Foreach() is potentially faster than a foreach loop. // http://diditwith.net/2006/10/05/PerformanceOfForeachVsListForEach.aspx foreach(NeuronGene srcGene in copyFrom) { Add(srcGene.CreateCopy()); } } #endregion #region Public Methods /// <summary> /// Inserts a NeuronGene into its correct (sorted) location within the gene list. /// Normally neuron genes can safely be assumed to have a new Innovation ID higher /// than all existing IDs, and so we can just call Add(). /// This routine handles genes with older IDs that need placing correctly. /// </summary> public void InsertIntoPosition(NeuronGene neuronGene) { // Determine the insert idx with a linear search, starting from the end // since mostly we expect to be adding genes that belong only 1 or 2 genes // from the end at most. int idx=Count-1; for(; idx > -1; idx--) { if(this[idx].InnovationId < neuronGene.InnovationId) { // Insert idx found. break; } } Insert(idx+1, neuronGene); } /// <summary> /// Remove the neuron gene with the specified innovation ID. /// Returns the removed gene. /// </summary> public NeuronGene Remove(uint neuronId) { int idx = BinarySearch(neuronId); if(idx<0) { throw new ApplicationException("Attempt to remove neuron with an unknown neuronId"); } NeuronGene neuronGene = this[idx]; RemoveAt(idx); return neuronGene; } /// <summary> /// Gets the neuron gene with the specified innovation ID using a fast binary search. /// Returns null if no such gene is in the list. /// </summary> public NeuronGene GetNeuronById(uint neuronId) { int idx = BinarySearch(neuronId); if(idx<0) { // Not found. return null; } return this[idx]; } /// <summary> /// Sort neuron gene's into ascending order by their innovation IDs. /// </summary> public void SortByInnovationId() { Sort(delegate(NeuronGene x, NeuronGene y) { // Test the most likely cases first. if(x.InnovationId < y.InnovationId) { return -1; } if(x.InnovationId > y.InnovationId) { return 1; } return 0; }); } /// <summary> /// Obtain the index of the gene with the specified ID by performing a binary search. /// Binary search is fast and can be performed so long as the genes are sorted by ID. /// If the genes are not sorted then the behaviour of this method is undefined. /// </summary> public int BinarySearch(uint id) { int lo = 0; int hi = Count-1; while (lo <= hi) { int i = (lo + hi) >> 1; if(this[i].Id < id) { lo = i + 1; } else if(this[i].Id > id) { hi = i - 1; } else { return i; } } return ~lo; } /// <summary> /// For debug purposes only. Don't call this method in normal circumstances as it is an /// expensive O(n) operation. /// </summary> public bool IsSorted() { int count = this.Count; if(0 == count) { return true; } uint prev = this[0].InnovationId; for(int i=1; i<count; i++) { if(this[i].InnovationId <= prev) { return false; } } return true; } #endregion #region INodeList<INetworkNode> Members INetworkNode INodeList.this[int index] { get { return this[index]; } } int INodeList.Count { get { return this.Count; } } IEnumerator<INetworkNode> IEnumerable<INetworkNode>.GetEnumerator() { foreach(NeuronGene nGene in this) { yield return nGene; } } IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable<INetworkNode>)this).GetEnumerator(); } #endregion } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #if NETFRAMEWORK_4_0 || SILVERLIGHT_4_0 || SILVERLIGHT_5_0 // File System.Linq.Expressions.ExpressionVisitor.cs // Automatically generated contract file. using System.Collections.Generic; using System.IO; using System.Text; using System.Diagnostics.Contracts; using System; // Disable the "this variable is not used" warning as every field would imply it. #pragma warning disable 0414 // Disable the "this variable is never assigned to". #pragma warning disable 0067 // Disable the "this event is never assigned to". #pragma warning disable 0649 // Disable the "this variable is never used". #pragma warning disable 0169 // Disable the "new keyword not required" warning. #pragma warning disable 0109 // Disable the "extern without DllImport" warning. #pragma warning disable 0626 // Disable the "could hide other member" warning, can happen on certain properties. #pragma warning disable 0108 namespace System.Linq.Expressions { abstract public partial class ExpressionVisitor { #region Methods and constructors protected ExpressionVisitor () { } public static System.Collections.ObjectModel.ReadOnlyCollection<T> Visit<T> (System.Collections.ObjectModel.ReadOnlyCollection<T> nodes, Func<T, T> elementVisitor) { return default(System.Collections.ObjectModel.ReadOnlyCollection<T>); } public System.Collections.ObjectModel.ReadOnlyCollection<Expression> Visit (System.Collections.ObjectModel.ReadOnlyCollection<Expression> nodes) { return default(System.Collections.ObjectModel.ReadOnlyCollection<Expression>); } public virtual new Expression Visit (Expression node) { return default(Expression); } public System.Collections.ObjectModel.ReadOnlyCollection<T> VisitAndConvert<T> (System.Collections.ObjectModel.ReadOnlyCollection<T> nodes, string callerName) { return default(System.Collections.ObjectModel.ReadOnlyCollection<T>); } public T VisitAndConvert<T> (T node, string callerName) { return default(T); } protected internal virtual new Expression VisitBinary (BinaryExpression node) { return default(Expression); } protected internal virtual new Expression VisitBlock (BlockExpression node) { return default(Expression); } protected virtual new CatchBlock VisitCatchBlock (CatchBlock node) { return default(CatchBlock); } protected internal virtual new Expression VisitConditional (ConditionalExpression node) { return default(Expression); } protected internal virtual new Expression VisitConstant (ConstantExpression node) { return default(Expression); } protected internal virtual new Expression VisitDebugInfo (DebugInfoExpression node) { return default(Expression); } protected internal virtual new Expression VisitDefault (DefaultExpression node) { return default(Expression); } protected internal virtual new Expression VisitDynamic (DynamicExpression node) { return default(Expression); } protected virtual new ElementInit VisitElementInit (ElementInit node) { return default(ElementInit); } protected internal virtual new Expression VisitExtension (Expression node) { return default(Expression); } protected internal virtual new Expression VisitGoto (GotoExpression node) { return default(Expression); } protected internal virtual new Expression VisitIndex (IndexExpression node) { return default(Expression); } protected internal virtual new Expression VisitInvocation (InvocationExpression node) { return default(Expression); } protected internal virtual new Expression VisitLabel (LabelExpression node) { return default(Expression); } protected virtual new LabelTarget VisitLabelTarget (LabelTarget node) { return default(LabelTarget); } protected internal virtual new Expression VisitLambda<T> (Expression<T> node) { return default(Expression); } protected internal virtual new Expression VisitListInit (ListInitExpression node) { return default(Expression); } protected internal virtual new Expression VisitLoop (LoopExpression node) { return default(Expression); } protected internal virtual new Expression VisitMember (MemberExpression node) { return default(Expression); } protected virtual new MemberAssignment VisitMemberAssignment (MemberAssignment node) { return default(MemberAssignment); } protected virtual new MemberBinding VisitMemberBinding (MemberBinding node) { return default(MemberBinding); } protected internal virtual new Expression VisitMemberInit (MemberInitExpression node) { return default(Expression); } protected virtual new MemberListBinding VisitMemberListBinding (MemberListBinding node) { return default(MemberListBinding); } protected virtual new MemberMemberBinding VisitMemberMemberBinding (MemberMemberBinding node) { return default(MemberMemberBinding); } protected internal virtual new Expression VisitMethodCall (MethodCallExpression node) { return default(Expression); } protected internal virtual new Expression VisitNew (NewExpression node) { return default(Expression); } protected internal virtual new Expression VisitNewArray (NewArrayExpression node) { return default(Expression); } protected internal virtual new Expression VisitParameter (ParameterExpression node) { return default(Expression); } protected internal virtual new Expression VisitRuntimeVariables (RuntimeVariablesExpression node) { return default(Expression); } protected internal virtual new Expression VisitSwitch (SwitchExpression node) { return default(Expression); } protected virtual new SwitchCase VisitSwitchCase (SwitchCase node) { return default(SwitchCase); } protected internal virtual new Expression VisitTry (TryExpression node) { return default(Expression); } protected internal virtual new Expression VisitTypeBinary (TypeBinaryExpression node) { return default(Expression); } protected internal virtual new Expression VisitUnary (UnaryExpression node) { return default(Expression); } #endregion } } #endif
/* $Id$ * * Project: Swicli.Library - Two Way Interface for .NET and MONO to SWI-Prolog * Author: Douglas R. Miles * E-mail: logicmoo@gmail.com * WWW: http://www.logicmoo.org * Copyright (C): 2010-2012 LogicMOO Developement * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * *********************************************************/ #if USE_MUSHDLR using MushDLR223.Utilities; #endif #if USE_IKVM using JavaClass = java.lang.Class; #endif using System; using System.Collections; using System.Collections.Generic; //using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using System.Threading; using SbsSW.SwiPlCs; using PlTerm = SbsSW.SwiPlCs.PlTerm; namespace Swicli.Library { public partial class PrologCLR { protected string ClientPrefix { get; set; } private string _clientModule = null; protected string ClientModule { get { return _clientModule; } set { if (value != "user") _clientModule = value; } } private static PrologCLR _singleInstance; public static PrologCLR SingleInstance { get { if (_singleInstance == null) _singleInstance = new PrologCLR(); return _singleInstance; } } public PrologCLR() { _singleInstance = this; ClientModule = null; ClientPrefix = "cli_"; PrologCLR.SetupProlog(); } public readonly static Type[] ZERO_TYPES = new Type[0]; public readonly static Object[] ZERO_OBJECTS = new Object[0]; public static readonly Type[] ONE_STRING = new[] {typeof (string)}; public static BindingFlags BindingFlagsJustStatic = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.FlattenHierarchy; public static BindingFlags BindingFlagsInstance = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.FlattenHierarchy; public static BindingFlags BindingFlagsALL = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance | BindingFlags.IgnoreCase | BindingFlags.IgnoreReturn | BindingFlags.FlattenHierarchy; public static BindingFlags InstanceFields = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy; public static BindingFlags BindingFlagsALLNC = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance | BindingFlags.IgnoreReturn | BindingFlags.FlattenHierarchy; public static BindingFlags BindingFlagsALL3 = BindingFlags.InvokeMethod | BindingFlags.GetField | BindingFlags.GetProperty | BindingFlags.SetField | BindingFlags.SetProperty; public static BindingFlags ICASE = BindingFlags.IgnoreCase; private static readonly BindingFlags[] BindingFlags_SEARCHIS = new[] { BindingFlagsInstance, BindingFlagsJustStatic, BindingFlagsInstance | ICASE, BindingFlagsJustStatic | ICASE, }; private static readonly BindingFlags[] BindingFlags_SEARCHS = new[] { BindingFlagsALL3 | BindingFlagsJustStatic, BindingFlagsALL3 | BindingFlagsJustStatic | ICASE, }; [PrologVisible] public static bool cliThrow(PlTerm ex) { throw (Exception) CastTerm(ex, typeof (Exception)); } [PrologVisible] public static bool cliBreak(PlTerm ex) { Trace(); return Embedded.WarnMissing(ToString(ex)) || true; } private static void Trace() { //throw new NotImplementedException(); } private static object ToFort(object o) { return ToProlog(o); } public static int PlSucceedOrFail(bool p) { return p ? libpl.PL_succeed : libpl.PL_fail; } public static bool PlSucceedOrFailOrError(int p) { return p != libpl.PL_fail; } private static string ToString(object o) { try { return ToString0(o); } catch (Exception) { return "" + o; } } private static string ToString0(object o) { if (o == null) return "null"; if (o is IConvertible || o is PlTerm || o is ValueType) return o.ToString(); if (o is IEnumerable) { var oc = (IEnumerable)o; int count = 0; string ret = "["; foreach (var o1 in oc) { if (count > 1) ret += ","; count++; ret += ToString0(o1); } return ret + "]"; } return o.ToString(); } /// <summary> /// 1 ?- cliToString(-1,X). /// X = "4294967295". /// </summary> /// <param name="obj"></param> /// <param name="str"></param> /// <returns></returns> [PrologVisible] public static bool cliToStrRaw(PlTerm obj, PlTerm str) { try { if (!str.IsVar) { var plvar = PlTerm.PlVar(); return cliToStrRaw(obj, plvar) && SpecialUnify(str, plvar); } if (obj.IsString) return str.Unify(obj); if (obj.IsVar) return str.Unify((string)obj); object o = GetInstance(obj); if (o == null) return str.FromObject("" + obj); return str.FromObject(ToString(o)); } catch (Exception e) { Embedded.Warn("cliToString: {0}", e); object o = GetInstance(obj); if (o == null) return str.FromObject("" + obj); return str.FromObject(ToString(o)); } } [IKVMBased] [PrologVisible] static public bool cliJavaToString(PlTerm paramIn, PlTerm valueOut) { if (!valueOut.IsVar) { var plvar = PlTerm.PlVar(); return cliJavaToString(paramIn, plvar) && SpecialUnify(valueOut, plvar); } object getInstance = GetInstance(paramIn); if (getInstance == null) return valueOut.Unify(PlTerm.PlString("null")); #if USE_IKVM //object val = getInstance as java.lang.Object; /* if (val == null) { JClass c = ikvm.runtime.Util.getClassFromObject(getInstance); string s = (string)c.getMethod("toString", new JClass[0]).invoke(getInstance, ZERO_OBJECTS); return valueOut.Unify(PlTerm.PlString(s)); }*/ return valueOut.Unify(PlTerm.PlString(ikvm.extensions.ExtensionMethods.instancehelper_toString(getInstance))); #else object val = getInstance; return valueOut.Unify(PlTerm.PlString(val.ToString())); #endif } private static bool CheckBound(params PlTerm[] terms) { foreach (PlTerm term in terms) { if (term.IsVar) { return Embedded.Error("Is var {0}", term); } } return true; } private static bool IsCompatTypes(Type[] supplied, Type[] required) { int len = supplied.Length; if (required.Length != len) return false; int considered = 0; foreach (Type type in required) { Type consider = supplied[considered]; if (!IsCompatType(consider,type)) { return false; } considered++; } return true; } private static bool IsCompatType(Type consider, Type type) { if (consider == null || type == null) return true; if (consider == typeof(object) || type == typeof(object)) return true; if (type.IsAssignableFrom(consider)) return true; if (typeof(IConvertible).IsAssignableFrom(type) && typeof(IConvertible).IsAssignableFrom(consider)) return true; return false; } [PrologVisible] static public bool cliLockEnter(PlTerm lockObj) { object getInstance = GetInstance(lockObj); Monitor.Enter(getInstance); return true; } [PrologVisible] static public bool cliLockExit(PlTerm lockObj) { object getInstance = GetInstance(lockObj); Monitor.Exit(getInstance); return true; } private static bool GetInstanceAndType(PlTerm clazzOrInstance, out object getInstance, out Type c) { if (clazzOrInstance.IsVar) { c = null; getInstance = null; return Embedded.Error("Cant find instance {0}", clazzOrInstance); } getInstance = GetInstance(clazzOrInstance); c = GetTypeFromInstance(getInstance, clazzOrInstance); if (getInstance == null && c == null) { return Embedded.Error("Cant find instance or type {0}", clazzOrInstance); } return true; } } }
using System; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.DataProtection; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Localization; using Microsoft.IdentityModel.Protocols.OpenIdConnect; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; using OrchardCore.DisplayManagement.Entities; using OrchardCore.DisplayManagement.Handlers; using OrchardCore.DisplayManagement.Views; using OrchardCore.Environment.Shell; using OrchardCore.OpenId.Configuration; using OrchardCore.OpenId.Services; using OrchardCore.OpenId.Settings; using OrchardCore.OpenId.ViewModels; using OrchardCore.Settings; namespace OrchardCore.OpenId.Drivers { public class OpenIdClientSettingsDisplayDriver : SectionDisplayDriver<ISite, OpenIdClientSettings> { private const string SettingsGroupId = "OrchardCore.OpenId.Client"; private static readonly JsonSerializerSettings JsonSerializerSettings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }; private readonly IAuthorizationService _authorizationService; private readonly IDataProtectionProvider _dataProtectionProvider; private readonly IHttpContextAccessor _httpContextAccessor; private readonly IOpenIdClientService _clientService; private readonly IShellHost _shellHost; private readonly ShellSettings _shellSettings; private readonly IStringLocalizer S; public OpenIdClientSettingsDisplayDriver( IAuthorizationService authorizationService, IDataProtectionProvider dataProtectionProvider, IOpenIdClientService clientService, IHttpContextAccessor httpContextAccessor, IShellHost shellHost, ShellSettings shellSettings, IStringLocalizer<OpenIdClientSettingsDisplayDriver> stringLocalizer) { _authorizationService = authorizationService; _dataProtectionProvider = dataProtectionProvider; _clientService = clientService; _httpContextAccessor = httpContextAccessor; _shellHost = shellHost; _shellSettings = shellSettings; S = stringLocalizer; } public override async Task<IDisplayResult> EditAsync(OpenIdClientSettings settings, BuildEditorContext context) { var user = _httpContextAccessor.HttpContext?.User; if (!await _authorizationService.AuthorizeAsync(user, Permissions.ManageClientSettings)) { return null; } return Initialize<OpenIdClientSettingsViewModel>("OpenIdClientSettings_Edit", model => { model.DisplayName = settings.DisplayName; model.Scopes = settings.Scopes != null ? string.Join(" ", settings.Scopes) : null; model.Authority = settings.Authority?.AbsoluteUri; model.CallbackPath = settings.CallbackPath; model.ClientId = settings.ClientId; model.ClientSecret = settings.ClientSecret; model.SignedOutCallbackPath = settings.SignedOutCallbackPath; model.SignedOutRedirectUri = settings.SignedOutRedirectUri; model.ResponseMode = settings.ResponseMode; model.StoreExternalTokens = settings.StoreExternalTokens; if (settings.ResponseType == OpenIdConnectResponseType.Code) { model.UseCodeFlow = true; } else if (settings.ResponseType == OpenIdConnectResponseType.CodeIdToken) { model.UseCodeIdTokenFlow = true; } else if (settings.ResponseType == OpenIdConnectResponseType.CodeIdTokenToken) { model.UseCodeIdTokenTokenFlow = true; } else if (settings.ResponseType == OpenIdConnectResponseType.CodeToken) { model.UseCodeTokenFlow = true; } else if (settings.ResponseType == OpenIdConnectResponseType.IdToken) { model.UseIdTokenFlow = true; } else if (settings.ResponseType == OpenIdConnectResponseType.IdTokenToken) { model.UseIdTokenTokenFlow = true; } model.Parameters = JsonConvert.SerializeObject(settings.Parameters, JsonSerializerSettings); }).Location("Content:2").OnGroup(SettingsGroupId); } public override async Task<IDisplayResult> UpdateAsync(OpenIdClientSettings settings, BuildEditorContext context) { var user = _httpContextAccessor.HttpContext?.User; if (!await _authorizationService.AuthorizeAsync(user, Permissions.ManageClientSettings)) { return null; } if (context.GroupId == SettingsGroupId) { var previousClientSecret = settings.ClientSecret; var model = new OpenIdClientSettingsViewModel(); await context.Updater.TryUpdateModelAsync(model, Prefix); model.Scopes = model.Scopes ?? string.Empty; settings.DisplayName = model.DisplayName; settings.Scopes = model.Scopes.Split(new char[] { ' ', ',' }, StringSplitOptions.RemoveEmptyEntries); settings.Authority = !string.IsNullOrEmpty(model.Authority) ? new Uri(model.Authority, UriKind.Absolute) : null; settings.CallbackPath = model.CallbackPath; settings.ClientId = model.ClientId; settings.SignedOutCallbackPath = model.SignedOutCallbackPath; settings.SignedOutRedirectUri = model.SignedOutRedirectUri; settings.ResponseMode = model.ResponseMode; settings.StoreExternalTokens = model.StoreExternalTokens; bool useClientSecret = true; if (model.UseCodeFlow) { settings.ResponseType = OpenIdConnectResponseType.Code; } else if (model.UseCodeIdTokenFlow) { settings.ResponseType = OpenIdConnectResponseType.CodeIdToken; } else if (model.UseCodeIdTokenTokenFlow) { settings.ResponseType = OpenIdConnectResponseType.CodeIdTokenToken; } else if (model.UseCodeTokenFlow) { settings.ResponseType = OpenIdConnectResponseType.CodeToken; } else if (model.UseIdTokenFlow) { settings.ResponseType = OpenIdConnectResponseType.IdToken; useClientSecret = false; } else if (model.UseIdTokenTokenFlow) { settings.ResponseType = OpenIdConnectResponseType.IdTokenToken; useClientSecret = false; } else { settings.ResponseType = OpenIdConnectResponseType.None; useClientSecret = false; } try { settings.Parameters = string.IsNullOrWhiteSpace(model.Parameters) ? Array.Empty<ParameterSetting>() : JsonConvert.DeserializeObject<ParameterSetting[]>(model.Parameters); } catch { context.Updater.ModelState.AddModelError(Prefix, S["The parameters are written in an incorrect format."]); } if (!useClientSecret) { model.ClientSecret = previousClientSecret = null; } // Restore the client secret if the input is empty (i.e if it hasn't been reset). if (string.IsNullOrEmpty(model.ClientSecret)) { settings.ClientSecret = previousClientSecret; } else { var protector = _dataProtectionProvider.CreateProtector(nameof(OpenIdClientConfiguration)); settings.ClientSecret = protector.Protect(model.ClientSecret); } foreach (var result in await _clientService.ValidateSettingsAsync(settings)) { if (result != ValidationResult.Success) { var key = result.MemberNames.FirstOrDefault() ?? string.Empty; context.Updater.ModelState.AddModelError(key, result.ErrorMessage); } } // If the settings are valid, release the current tenant. if (context.Updater.ModelState.IsValid) { await _shellHost.ReleaseShellContextAsync(_shellSettings); } } return await EditAsync(settings, context); } } }
using System.Security; using System; using System.Runtime.InteropServices; // For SafeHandle [SecurityCritical] public class MySafeValidHandle : SafeHandle { [SecurityCritical] public MySafeValidHandle() : base(IntPtr.Zero, true) { } public MySafeValidHandle(IntPtr handleValue) : base(IntPtr.Zero, true) { handle = handleValue; } public override bool IsInvalid { [SecurityCritical] get { return false; } } [SecurityCritical] protected override bool ReleaseHandle() { return true; } } [SecurityCritical] public class MySafeInValidHandle : SafeHandle { [SecurityCritical] public MySafeInValidHandle() : base(IntPtr.Zero, true) { } public MySafeInValidHandle(IntPtr handleValue) : base(IntPtr.Zero, true) { handle = handleValue; } public override bool IsInvalid { [SecurityCritical] get { return true; } } [SecurityCritical] protected override bool ReleaseHandle() { return true; } } /// <summary> /// DangerousGetHandle /// </summary> public class SafeHandleDangerousGetHandle { #region Public Methods [SecuritySafeCritical] public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; return retVal; } #region Positive Test Cases [SecuritySafeCritical] public bool PosTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest1: DangerousGetHandle should return handle value for valid safe handle"); try { SafeHandle handle = new MySafeValidHandle(); IntPtr handleValue = handle.DangerousGetHandle(); if (handleValue != IntPtr.Zero) { TestLibrary.TestFramework.LogError("001.1", "DangerousGetHandle returns wrong handle value for valid safe handle"); TestLibrary.TestFramework.LogInformation("WARNING: [LOCAL VARIABLES] handleValue = " + handleValue.ToString() + ", desiredValue = IntPtr.Zero"); retVal = false; } // Get it twice handleValue = handle.DangerousGetHandle(); if (handleValue != IntPtr.Zero) { TestLibrary.TestFramework.LogError("001.2", "DangerousGetHandle returns wrong handle value for valid safe handle"); TestLibrary.TestFramework.LogInformation("WARNING: [LOCAL VARIABLES] handleValue = " + handleValue.ToString() + ", desiredValue = IntPtr.Zero"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("001.3", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } [SecuritySafeCritical] public bool PosTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest2: DangerousGetHandle should return handle value for valid safe handle"); try { int randValue = TestLibrary.Generator.GetInt32(-55); IntPtr desiredValue = new IntPtr(randValue); SafeHandle handle = new MySafeValidHandle(desiredValue); IntPtr handleValue = handle.DangerousGetHandle(); if (handleValue != desiredValue) { TestLibrary.TestFramework.LogError("002.1", "DangerousGetHandle returns wrong handle value for valid safe handle"); TestLibrary.TestFramework.LogInformation("WARNING: [LOCAL VARIABLES] handleValue = " + handleValue.ToString() + ", desiredValue = " + desiredValue.ToString()); retVal = false; } handleValue = handle.DangerousGetHandle(); if (handleValue != desiredValue) { TestLibrary.TestFramework.LogError("002.2", "DangerousGetHandle returns wrong handle value for valid safe handle"); TestLibrary.TestFramework.LogInformation("WARNING: [LOCAL VARIABLES] handleValue = " + handleValue.ToString() + ", desiredValue = " + desiredValue.ToString()); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002.3", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } [SecuritySafeCritical] public bool PosTest3() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest3: DangerousGetHandle should return handle value for invalid safe handle"); try { SafeHandle handle = new MySafeInValidHandle(); IntPtr handleValue = handle.DangerousGetHandle(); if (handleValue != IntPtr.Zero) { TestLibrary.TestFramework.LogError("003.1", "DangerousGetHandle returns wrong handle value for invalid safe handle"); TestLibrary.TestFramework.LogInformation("WARNING: [LOCAL VARIABLES] handleValue = " + handleValue.ToString() + ", desiredValue = IntPtr.Zero"); retVal = false; } handleValue = handle.DangerousGetHandle(); if (handleValue != IntPtr.Zero) { TestLibrary.TestFramework.LogError("003.2", "DangerousGetHandle returns wrong handle value for invalid safe handle"); TestLibrary.TestFramework.LogInformation("WARNING: [LOCAL VARIABLES] handleValue = " + handleValue.ToString() + ", desiredValue = IntPtr.Zero"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("003.3", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } [SecuritySafeCritical] public bool PosTest4() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest4: DangerousGetHandle should return handle value for valid safe handle"); try { int randValue = TestLibrary.Generator.GetInt32(-55); IntPtr desiredValue = new IntPtr(randValue); SafeHandle handle = new MySafeInValidHandle(desiredValue); IntPtr handleValue = handle.DangerousGetHandle(); if (handleValue != desiredValue) { TestLibrary.TestFramework.LogError("004.1", "DangerousGetHandle returns wrong handle value for valid safe handle"); TestLibrary.TestFramework.LogInformation("WARNING: [LOCAL VARIABLES] handleValue = " + handleValue.ToString() + ", desiredValue = " + desiredValue.ToString()); retVal = false; } handleValue = handle.DangerousGetHandle(); if (handleValue != desiredValue) { TestLibrary.TestFramework.LogError("004.2", "DangerousGetHandle returns wrong handle value for valid safe handle"); TestLibrary.TestFramework.LogInformation("WARNING: [LOCAL VARIABLES] handleValue = " + handleValue.ToString() + ", desiredValue = " + desiredValue.ToString()); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("004.3", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } #endregion #endregion [SecuritySafeCritical] public static int Main() { SafeHandleDangerousGetHandle test = new SafeHandleDangerousGetHandle(); TestLibrary.TestFramework.BeginTestCase("SafeHandleDangerousGetHandle"); if (test.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } }
// // ContextPane.cs // // Authors: // Gabriel Burt <gburt@novell.com> // // Copyright (C) 2009 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Linq; using System.Collections.Generic; using Mono.Unix; using Gtk; using Hyena.Gui; using Hyena.Widgets; using Banshee.Base; using Banshee.Configuration; using Banshee.Collection; using Banshee.ServiceStack; using Banshee.MediaEngine; using Banshee.Gui; namespace Banshee.ContextPane { public class ContextPane : Gtk.HBox { private object tooltip_host = TooltipSetter.CreateHost (); private Gtk.Notebook notebook; private VBox vbox; private bool large = false; private bool initialized = false; private RoundedFrame no_active; private RoundedFrame loading; private RadioButton radio_group = new RadioButton (null, ""); private Dictionary<BaseContextPage, RadioButton> pane_tabs = new Dictionary<BaseContextPage, RadioButton> (); private Dictionary<BaseContextPage, Widget> pane_pages = new Dictionary<BaseContextPage, Widget> (); private List<BaseContextPage> pages = new List<BaseContextPage> (); private BaseContextPage active_page; private Action<bool> expand_handler; public Action<bool> ExpandHandler { set { expand_handler = value; } } public bool Large { get { return large; } } public ContextPane () { HeightRequest = 200; CreateContextNotebook (); CreateTabButtonBox (); new ContextPageManager (this); initialized = true; RestoreLastActivePage (); Enabled = ShowSchema.Get (); ShowAction.Activated += OnShowContextPane; ServiceManager.PlayerEngine.ConnectEvent (OnPlayerEvent, PlayerEvent.StartOfStream | PlayerEvent.TrackInfoUpdated); } private void RestoreLastActivePage () { // TODO restore the last page string last_id = LastContextPageSchema.Get (); if (!String.IsNullOrEmpty (last_id)) { var page = pages.FirstOrDefault (p => p.Id == last_id); if (page != null) { SetActivePage (page); pane_tabs[page].Active = true; } } if (active_page == null) { ActivateFirstPage (); } } private void CreateTabButtonBox () { vbox = new VBox (); HBox hbox = new HBox (); var max = new Button (new Image (IconThemeUtils.LoadIcon ("context-pane-maximize", 7))); max.Clicked += (o, a) => { large = !large; expand_handler (large); }; TooltipSetter.Set (tooltip_host, max, Catalog.GetString ("Make the context pane larger or smaller")); var close = new Button (new Image (IconThemeUtils.LoadIcon ("context-pane-close", 7))); close.Clicked += (o, a) => ShowAction.Activate (); TooltipSetter.Set (tooltip_host, close, Catalog.GetString ("Hide context pane")); max.Relief = close.Relief = ReliefStyle.None; hbox.PackStart (max, false, false, 0); hbox.PackStart (close, false, false, 0); vbox.PackStart (hbox, false, false, 0); PackStart (vbox, false, false, 6); vbox.ShowAll (); } private void CreateContextNotebook () { notebook = new Notebook () { ShowBorder = false, ShowTabs = false }; // 'No active track' and 'Loading' widgets no_active = new RoundedFrame (); no_active.Add (new Label () { Markup = String.Format ("<b>{0}</b>", Catalog.GetString ("Waiting for playback to begin...")) }); no_active.ShowAll (); notebook.Add (no_active); loading = new RoundedFrame (); loading.Add (new Label () { Markup = String.Format ("<b>{0}</b>", Catalog.GetString ("Loading...")) }); loading.ShowAll (); notebook.Add (loading); PackStart (notebook, true, true, 0); notebook.Show (); } private void OnPlayerEvent (PlayerEventArgs args) { if (Enabled) { SetCurrentTrackForActivePage (); } } private void SetCurrentTrackForActivePage () { TrackInfo track = ServiceManager.PlayerEngine.CurrentTrack; if (track != null && active_page != null) { active_page.SetTrack (track); } } private void OnActivePageStateChanged (ContextState state) { if (active_page == null || !pane_pages.ContainsKey (active_page)) { return; } if (state == ContextState.NotLoaded) notebook.CurrentPage = notebook.PageNum (no_active); else if (state == ContextState.Loading) notebook.CurrentPage = notebook.PageNum (loading); else if (state == ContextState.Loaded) notebook.CurrentPage = notebook.PageNum (pane_pages[active_page]); } private Gtk.ToggleAction ShowAction { get { return ServiceManager.Get<InterfaceActionService> ().ViewActions["ShowContextPaneAction"] as ToggleAction; } } private void OnShowContextPane (object o, EventArgs args) { Enabled = ShowAction.Active; } private bool Enabled { get { return ShowSchema.Get (); } set { ShowSchema.Set (value); SetCurrentTrackForActivePage (); UpdateVisibility (); } } private void UpdateVisibility () { int npages = pages.Count; bool enabled = Enabled; ShowAction.Sensitive = npages > 0; if (enabled && npages > 0) { Show (); } else { if (expand_handler != null) { expand_handler (false); } large = false; Hide (); } vbox.Visible = true;//enabled && npages > 1; } private void SetActivePage (BaseContextPage page) { if (page == null || page == active_page) return; if (active_page != null) active_page.StateChanged -= OnActivePageStateChanged; active_page = page; active_page.StateChanged += OnActivePageStateChanged; LastContextPageSchema.Set (page.Id); OnActivePageStateChanged (active_page.State); SetCurrentTrackForActivePage (); } public void AddPage (BaseContextPage page) { Hyena.Log.DebugFormat ("Adding context page {0}", page.Id); // TODO delay adding the page.Widget until the page is first activated, // that way we don't even create those objects unless used var frame = new Hyena.Widgets.RoundedFrame (); frame.Add (page.Widget); frame.Show (); // TODO implement DnD? /*if (page is ITrackContextPage) { Gtk.Drag.DestSet (frame, DestDefaults.Highlight | DestDefaults.Motion, new TargetEntry [] { Banshee.Gui.DragDrop.DragDropTarget.UriList }, Gdk.DragAction.Default); frame.DragDataReceived += delegate(object o, DragDataReceivedArgs args) { }; }*/ page.Widget.Show (); notebook.AppendPage (frame, null); pane_pages[page] = frame; // Setup the tab-like button that switches the notebook to this page var tab_image = new Image (IconThemeUtils.LoadIcon (22, page.IconNames)); var toggle_button = new RadioButton (radio_group) { Child = tab_image, DrawIndicator = false, Relief = ReliefStyle.None }; TooltipSetter.Set (tooltip_host, toggle_button, page.Name); toggle_button.Clicked += (s, e) => { if (pane_pages.ContainsKey (page)) { if (page.State == ContextState.Loaded) { notebook.CurrentPage = notebook.PageNum (pane_pages[page]); } SetActivePage (page); } }; toggle_button.ShowAll (); vbox.PackStart (toggle_button, false, false, 0); pane_tabs[page] = toggle_button; pages.Add (page); if (initialized && pages.Count == 1) { SetActivePage (page); toggle_button.Active = true; } UpdateVisibility (); } public void RemovePage (BaseContextPage page) { Hyena.Log.DebugFormat ("Removing context page {0}", page.Id); // Remove the notebook page notebook.RemovePage (notebook.PageNum (pane_pages[page])); pane_pages.Remove (page); // Remove the tab button bool was_active = pane_tabs[page].Active; vbox.Remove (pane_tabs[page]); pane_tabs.Remove (page); pages.Remove (page); // Set a new page as the default if (was_active) { ActivateFirstPage (); } UpdateVisibility (); } private void ActivateFirstPage () { if (pages.Count > 0) { SetActivePage (pages[0]); pane_tabs[active_page].Active = true; } } internal static readonly SchemaEntry<bool> ShowSchema = new SchemaEntry<bool>( "interface", "show_context_pane", false, "Show context pane", "Show context pane for the currently playing track" ); private static readonly SchemaEntry<string> LastContextPageSchema = new SchemaEntry<string>( "interface", "last_context_page", null, "The id of the last context page", "The string id of the last context page, which will be defaulted to when Banshee starts" ); } }
using NetApp.Tests.Helpers; using Microsoft.Azure.Management.NetApp; using Microsoft.Azure.Management.Resources; using Microsoft.Azure.Test.HttpRecorder; using Microsoft.Rest.ClientRuntime.Azure.TestFramework; using System.IO; using System.Linq; using System.Net; using System.Reflection; using Xunit; using System; using Microsoft.Azure.Management.NetApp.Models; using System.Collections.Generic; using Microsoft.Rest.Azure; namespace NetApp.Tests.ResourceTests { public class AccountTests : TestBase { [Fact] public void CreateDeleteAccount() { HttpMockServer.RecordsDirectory = GetSessionsDirectoryPath(); using (MockContext context = MockContext.Start(this.GetType())) { var netAppMgmtClient = NetAppTestUtilities.GetNetAppManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }); var accountsInitial = netAppMgmtClient.Accounts.List(ResourceUtils.resourceGroup); int initialCount = accountsInitial.Count(); // create the account with only the one required property var netAppAccount = new NetAppAccount() { Location = ResourceUtils.location }; var resource = netAppMgmtClient.Accounts.CreateOrUpdate(netAppAccount, ResourceUtils.resourceGroup, ResourceUtils.accountName1); Assert.Equal(resource.Name, ResourceUtils.accountName1); Assert.Null(resource.Tags); Assert.Null(resource.ActiveDirectories); // get all accounts and check var accountsBefore = netAppMgmtClient.Accounts.List(ResourceUtils.resourceGroup); Assert.Equal(initialCount + 1, accountsBefore.Count()); // remove the account and check netAppMgmtClient.Accounts.Delete(ResourceUtils.resourceGroup, ResourceUtils.accountName1); // get all accounts and check var accountsAfter = netAppMgmtClient.Accounts.List(ResourceUtils.resourceGroup); Assert.Equal(initialCount, accountsAfter.Count()); } } [Fact] public void CreateAccountWithProperties() { HttpMockServer.RecordsDirectory = GetSessionsDirectoryPath(); using (MockContext context = MockContext.Start(this.GetType())) { var netAppMgmtClient = NetAppTestUtilities.GetNetAppManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }); var dict = new Dictionary<string, string>(); dict.Add("Tag1", "Value1"); // create the account var resource = ResourceUtils.CreateAccount(netAppMgmtClient, tags: dict, activeDirectory: ResourceUtils.activeDirectory); Assert.True(resource.Tags.ContainsKey("Tag1")); Assert.Equal("Value1", resource.Tags["Tag1"]); Assert.NotNull(resource.ActiveDirectories); // remove the account netAppMgmtClient.Accounts.Delete(ResourceUtils.resourceGroup, ResourceUtils.accountName1); } } [Fact] public void UpdateAccount() { HttpMockServer.RecordsDirectory = GetSessionsDirectoryPath(); using (MockContext context = MockContext.Start(this.GetType())) { var netAppMgmtClient = NetAppTestUtilities.GetNetAppManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }); // create the account ResourceUtils.CreateAccount(netAppMgmtClient); // perform create/update operation again for same account // this should be treated as an update and accepted // could equally do this with some property fields added var dict = new Dictionary<string, string>(); dict.Add("Tag1", "Value2"); var resource = ResourceUtils.CreateAccount(netAppMgmtClient, tags: dict); Assert.True(resource.Tags.ContainsKey("Tag1")); Assert.Equal("Value2", resource.Tags["Tag1"]); } } [Fact] public void ListAccounts() { HttpMockServer.RecordsDirectory = GetSessionsDirectoryPath(); using (MockContext context = MockContext.Start(this.GetType())) { var netAppMgmtClient = NetAppTestUtilities.GetNetAppManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }); var accountsBefore = netAppMgmtClient.Accounts.List(ResourceUtils.resourceGroup); int count = accountsBefore.Count(); // create two accounts ResourceUtils.CreateAccount(netAppMgmtClient); ResourceUtils.CreateAccount(netAppMgmtClient, ResourceUtils.accountName2); // get the account list and check var accounts = netAppMgmtClient.Accounts.List(ResourceUtils.resourceGroup); Assert.Contains(accounts, item => item.Name == ResourceUtils.accountName1); Assert.Contains(accounts, item => item.Name == ResourceUtils.accountName2); // clean up - delete the two accounts ResourceUtils.DeleteAccount(netAppMgmtClient); ResourceUtils.DeleteAccount(netAppMgmtClient, ResourceUtils.accountName2); } } [Fact] public void ListAccountsBySubscription() { HttpMockServer.RecordsDirectory = GetSessionsDirectoryPath(); using (MockContext context = MockContext.Start(this.GetType())) { var netAppMgmtClient = NetAppTestUtilities.GetNetAppManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }); var accountsBefore = netAppMgmtClient.Accounts.List(ResourceUtils.resourceGroup); int count = accountsBefore.Count(); // create two accounts ResourceUtils.CreateAccount(netAppMgmtClient); ResourceUtils.CreateAccount(netAppMgmtClient, ResourceUtils.accountName2); // get the account list and check var accounts = netAppMgmtClient.Accounts.ListBySubscription(); Assert.Contains(accounts, item => item.Name == ResourceUtils.accountName1); Assert.Contains(accounts, item => item.Name == ResourceUtils.accountName2); // clean up - delete the two accounts ResourceUtils.DeleteAccount(netAppMgmtClient); ResourceUtils.DeleteAccount(netAppMgmtClient, ResourceUtils.accountName2); } } [Fact] public void GetAccountByName() { HttpMockServer.RecordsDirectory = GetSessionsDirectoryPath(); using (MockContext context = MockContext.Start(this.GetType())) { var netAppMgmtClient = NetAppTestUtilities.GetNetAppManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }); // create the account ResourceUtils.CreateAccount(netAppMgmtClient, ResourceUtils.accountName1); // get and check the account var account = netAppMgmtClient.Accounts.Get(ResourceUtils.resourceGroup, ResourceUtils.accountName1); Assert.Equal(account.Name, ResourceUtils.accountName1); // clean up - delete the account ResourceUtils.DeleteAccount(netAppMgmtClient); } } [Fact] public void GetAccountByNameNotFound() { HttpMockServer.RecordsDirectory = GetSessionsDirectoryPath(); string expectedErrorCode = "ResourceNotFound"; using (MockContext context = MockContext.Start(this.GetType())) { var netAppMgmtClient = NetAppTestUtilities.GetNetAppManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }); // get and check the account try { var account = netAppMgmtClient.Accounts.Get(ResourceUtils.resourceGroup, ResourceUtils.accountName1); Assert.True(false); // expecting exception } catch (CloudException cex) { Assert.Equal(cex.Body.Code, expectedErrorCode); } } } [Fact] public void PatchAccount() { HttpMockServer.RecordsDirectory = GetSessionsDirectoryPath(); using (MockContext context = MockContext.Start(this.GetType())) { var netAppMgmtClient = NetAppTestUtilities.GetNetAppManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }); // create the account ResourceUtils.CreateAccount(netAppMgmtClient, activeDirectory: ResourceUtils.activeDirectory); var dict = new Dictionary<string, string>(); dict.Add("Tag2", "Value1"); // Now try and modify it var netAppAccountPatch = new NetAppAccountPatch() { Tags = dict }; // tag changes but active directory still present var resource = netAppMgmtClient.Accounts.Update(netAppAccountPatch, ResourceUtils.resourceGroup, ResourceUtils.accountName1); Assert.True(resource.Tags.ContainsKey("Tag2")); Assert.Equal("Value1", resource.Tags["Tag2"]); Assert.NotNull(resource.ActiveDirectories); Assert.Equal("sdkuser", resource.ActiveDirectories.First().Username); // so deleting the active directory requires the put operation // but changing an active directory can be done but requires the id ResourceUtils.activeDirectory2.ActiveDirectoryId = resource.ActiveDirectories.First().ActiveDirectoryId; var activeDirectories = new List<ActiveDirectory> { ResourceUtils.activeDirectory2 }; dict.Add("Tag3", "Value3"); // Now try and modify it var netAppAccountPatch2 = new NetAppAccountPatch() { ActiveDirectories = activeDirectories, Tags = dict }; var resource2 = netAppMgmtClient.Accounts.Update(netAppAccountPatch2, ResourceUtils.resourceGroup, ResourceUtils.accountName1); Assert.True(resource2.Tags.ContainsKey("Tag2")); Assert.Equal("Value1", resource2.Tags["Tag2"]); Assert.True(resource2.Tags.ContainsKey("Tag3")); Assert.Equal("Value3", resource2.Tags["Tag3"]); Assert.NotNull(resource2.ActiveDirectories); Assert.Equal("sdkuser1", resource2.ActiveDirectories.First().Username); // cleanup - remove the account ResourceUtils.DeleteAccount(netAppMgmtClient); } } private static string GetSessionsDirectoryPath() { string executingAssemblyPath = typeof(NetApp.Tests.ResourceTests.AccountTests).GetTypeInfo().Assembly.Location; return Path.Combine(Path.GetDirectoryName(executingAssemblyPath), "SessionRecords"); } } }
// 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.Globalization; using System.Linq; using Xunit; namespace System.Text.Tests { public class EncodingTest : IClassFixture<CultureSetup> { public EncodingTest(CultureSetup setup) { // Setting up the culture happens externally, and only once, which is what we want. // xUnit will keep track of it, do nothing. } public static IEnumerable<object[]> CodePageInfo() { // The layout is code page, IANA(web) name, and query string. // Query strings may be undocumented, and IANA names will be returned from Encoding objects. // Entries are sorted by code page. yield return new object[] { 37, "ibm037", "ibm037" }; yield return new object[] { 37, "ibm037", "cp037" }; yield return new object[] { 37, "ibm037", "csibm037" }; yield return new object[] { 37, "ibm037", "ebcdic-cp-ca" }; yield return new object[] { 37, "ibm037", "ebcdic-cp-nl" }; yield return new object[] { 37, "ibm037", "ebcdic-cp-us" }; yield return new object[] { 37, "ibm037", "ebcdic-cp-wt" }; yield return new object[] { 437, "ibm437", "ibm437" }; yield return new object[] { 437, "ibm437", "437" }; yield return new object[] { 437, "ibm437", "cp437" }; yield return new object[] { 437, "ibm437", "cspc8codepage437" }; yield return new object[] { 500, "ibm500", "ibm500" }; yield return new object[] { 500, "ibm500", "cp500" }; yield return new object[] { 500, "ibm500", "csibm500" }; yield return new object[] { 500, "ibm500", "ebcdic-cp-be" }; yield return new object[] { 500, "ibm500", "ebcdic-cp-ch" }; yield return new object[] { 708, "asmo-708", "asmo-708" }; yield return new object[] { 720, "dos-720", "dos-720" }; yield return new object[] { 737, "ibm737", "ibm737" }; yield return new object[] { 775, "ibm775", "ibm775" }; yield return new object[] { 850, "ibm850", "ibm850" }; yield return new object[] { 850, "ibm850", "cp850" }; yield return new object[] { 852, "ibm852", "ibm852" }; yield return new object[] { 852, "ibm852", "cp852" }; yield return new object[] { 855, "ibm855", "ibm855" }; yield return new object[] { 855, "ibm855", "cp855" }; yield return new object[] { 857, "ibm857", "ibm857" }; yield return new object[] { 857, "ibm857", "cp857" }; yield return new object[] { 858, "ibm00858", "ibm00858" }; yield return new object[] { 858, "ibm00858", "ccsid00858" }; yield return new object[] { 858, "ibm00858", "cp00858" }; yield return new object[] { 858, "ibm00858", "cp858" }; yield return new object[] { 858, "ibm00858", "pc-multilingual-850+euro" }; yield return new object[] { 860, "ibm860", "ibm860" }; yield return new object[] { 860, "ibm860", "cp860" }; yield return new object[] { 861, "ibm861", "ibm861" }; yield return new object[] { 861, "ibm861", "cp861" }; yield return new object[] { 862, "dos-862", "dos-862" }; yield return new object[] { 862, "dos-862", "cp862" }; yield return new object[] { 862, "dos-862", "ibm862" }; yield return new object[] { 863, "ibm863", "ibm863" }; yield return new object[] { 863, "ibm863", "cp863" }; yield return new object[] { 864, "ibm864", "ibm864" }; yield return new object[] { 864, "ibm864", "cp864" }; yield return new object[] { 865, "ibm865", "ibm865" }; yield return new object[] { 865, "ibm865", "cp865" }; yield return new object[] { 866, "cp866", "cp866" }; yield return new object[] { 866, "cp866", "ibm866" }; yield return new object[] { 869, "ibm869", "ibm869" }; yield return new object[] { 869, "ibm869", "cp869" }; yield return new object[] { 870, "ibm870", "ibm870" }; yield return new object[] { 870, "ibm870", "cp870" }; yield return new object[] { 870, "ibm870", "csibm870" }; yield return new object[] { 870, "ibm870", "ebcdic-cp-roece" }; yield return new object[] { 870, "ibm870", "ebcdic-cp-yu" }; yield return new object[] { 874, "windows-874", "windows-874" }; yield return new object[] { 874, "windows-874", "dos-874" }; yield return new object[] { 874, "windows-874", "iso-8859-11" }; yield return new object[] { 874, "windows-874", "tis-620" }; yield return new object[] { 875, "cp875", "cp875" }; yield return new object[] { 932, "shift_jis", "shift_jis" }; yield return new object[] { 932, "shift_jis", "csshiftjis" }; yield return new object[] { 932, "shift_jis", "cswindows31j" }; yield return new object[] { 932, "shift_jis", "ms_kanji" }; yield return new object[] { 932, "shift_jis", "shift-jis" }; yield return new object[] { 932, "shift_jis", "sjis" }; yield return new object[] { 932, "shift_jis", "x-ms-cp932" }; yield return new object[] { 932, "shift_jis", "x-sjis" }; yield return new object[] { 936, "gb2312", "gb2312" }; yield return new object[] { 936, "gb2312", "chinese" }; yield return new object[] { 936, "gb2312", "cn-gb" }; yield return new object[] { 936, "gb2312", "csgb2312" }; yield return new object[] { 936, "gb2312", "csgb231280" }; yield return new object[] { 936, "gb2312", "csiso58gb231280" }; yield return new object[] { 936, "gb2312", "gb_2312-80" }; yield return new object[] { 936, "gb2312", "gb231280" }; yield return new object[] { 936, "gb2312", "gb2312-80" }; yield return new object[] { 936, "gb2312", "gbk" }; yield return new object[] { 936, "gb2312", "iso-ir-58" }; yield return new object[] { 949, "ks_c_5601-1987", "ks_c_5601-1987" }; yield return new object[] { 949, "ks_c_5601-1987", "csksc56011987" }; yield return new object[] { 949, "ks_c_5601-1987", "iso-ir-149" }; yield return new object[] { 949, "ks_c_5601-1987", "korean" }; yield return new object[] { 949, "ks_c_5601-1987", "ks_c_5601" }; yield return new object[] { 949, "ks_c_5601-1987", "ks_c_5601_1987" }; yield return new object[] { 949, "ks_c_5601-1987", "ks_c_5601-1989" }; yield return new object[] { 949, "ks_c_5601-1987", "ksc_5601" }; yield return new object[] { 949, "ks_c_5601-1987", "ksc5601" }; yield return new object[] { 949, "ks_c_5601-1987", "ks-c5601" }; yield return new object[] { 949, "ks_c_5601-1987", "ks-c-5601" }; yield return new object[] { 950, "big5", "big5" }; yield return new object[] { 950, "big5", "big5-hkscs" }; yield return new object[] { 950, "big5", "cn-big5" }; yield return new object[] { 950, "big5", "csbig5" }; yield return new object[] { 950, "big5", "x-x-big5" }; yield return new object[] { 1026, "ibm1026", "ibm1026" }; yield return new object[] { 1026, "ibm1026", "cp1026" }; yield return new object[] { 1026, "ibm1026", "csibm1026" }; yield return new object[] { 1047, "ibm01047", "ibm01047" }; yield return new object[] { 1140, "ibm01140", "ibm01140" }; yield return new object[] { 1140, "ibm01140", "ccsid01140" }; yield return new object[] { 1140, "ibm01140", "cp01140" }; yield return new object[] { 1140, "ibm01140", "ebcdic-us-37+euro" }; yield return new object[] { 1141, "ibm01141", "ibm01141" }; yield return new object[] { 1141, "ibm01141", "ccsid01141" }; yield return new object[] { 1141, "ibm01141", "cp01141" }; yield return new object[] { 1141, "ibm01141", "ebcdic-de-273+euro" }; yield return new object[] { 1142, "ibm01142", "ibm01142" }; yield return new object[] { 1142, "ibm01142", "ccsid01142" }; yield return new object[] { 1142, "ibm01142", "cp01142" }; yield return new object[] { 1142, "ibm01142", "ebcdic-dk-277+euro" }; yield return new object[] { 1142, "ibm01142", "ebcdic-no-277+euro" }; yield return new object[] { 1143, "ibm01143", "ibm01143" }; yield return new object[] { 1143, "ibm01143", "ccsid01143" }; yield return new object[] { 1143, "ibm01143", "cp01143" }; yield return new object[] { 1143, "ibm01143", "ebcdic-fi-278+euro" }; yield return new object[] { 1143, "ibm01143", "ebcdic-se-278+euro" }; yield return new object[] { 1144, "ibm01144", "ibm01144" }; yield return new object[] { 1144, "ibm01144", "ccsid01144" }; yield return new object[] { 1144, "ibm01144", "cp01144" }; yield return new object[] { 1144, "ibm01144", "ebcdic-it-280+euro" }; yield return new object[] { 1145, "ibm01145", "ibm01145" }; yield return new object[] { 1145, "ibm01145", "ccsid01145" }; yield return new object[] { 1145, "ibm01145", "cp01145" }; yield return new object[] { 1145, "ibm01145", "ebcdic-es-284+euro" }; yield return new object[] { 1146, "ibm01146", "ibm01146" }; yield return new object[] { 1146, "ibm01146", "ccsid01146" }; yield return new object[] { 1146, "ibm01146", "cp01146" }; yield return new object[] { 1146, "ibm01146", "ebcdic-gb-285+euro" }; yield return new object[] { 1147, "ibm01147", "ibm01147" }; yield return new object[] { 1147, "ibm01147", "ccsid01147" }; yield return new object[] { 1147, "ibm01147", "cp01147" }; yield return new object[] { 1147, "ibm01147", "ebcdic-fr-297+euro" }; yield return new object[] { 1148, "ibm01148", "ibm01148" }; yield return new object[] { 1148, "ibm01148", "ccsid01148" }; yield return new object[] { 1148, "ibm01148", "cp01148" }; yield return new object[] { 1148, "ibm01148", "ebcdic-international-500+euro" }; yield return new object[] { 1149, "ibm01149", "ibm01149" }; yield return new object[] { 1149, "ibm01149", "ccsid01149" }; yield return new object[] { 1149, "ibm01149", "cp01149" }; yield return new object[] { 1149, "ibm01149", "ebcdic-is-871+euro" }; yield return new object[] { 1250, "windows-1250", "windows-1250" }; yield return new object[] { 1250, "windows-1250", "x-cp1250" }; yield return new object[] { 1251, "windows-1251", "windows-1251" }; yield return new object[] { 1251, "windows-1251", "x-cp1251" }; yield return new object[] { 1252, "windows-1252", "windows-1252" }; yield return new object[] { 1252, "windows-1252", "x-ansi" }; yield return new object[] { 1253, "windows-1253", "windows-1253" }; yield return new object[] { 1254, "windows-1254", "windows-1254" }; yield return new object[] { 1255, "windows-1255", "windows-1255" }; yield return new object[] { 1256, "windows-1256", "windows-1256" }; yield return new object[] { 1256, "windows-1256", "cp1256" }; yield return new object[] { 1257, "windows-1257", "windows-1257" }; yield return new object[] { 1258, "windows-1258", "windows-1258" }; yield return new object[] { 1361, "johab", "johab" }; yield return new object[] { 10000, "macintosh", "macintosh" }; yield return new object[] { 10001, "x-mac-japanese", "x-mac-japanese" }; yield return new object[] { 10002, "x-mac-chinesetrad", "x-mac-chinesetrad" }; yield return new object[] { 10003, "x-mac-korean", "x-mac-korean" }; yield return new object[] { 10004, "x-mac-arabic", "x-mac-arabic" }; yield return new object[] { 10005, "x-mac-hebrew", "x-mac-hebrew" }; yield return new object[] { 10006, "x-mac-greek", "x-mac-greek" }; yield return new object[] { 10007, "x-mac-cyrillic", "x-mac-cyrillic" }; yield return new object[] { 10008, "x-mac-chinesesimp", "x-mac-chinesesimp" }; yield return new object[] { 10010, "x-mac-romanian", "x-mac-romanian" }; yield return new object[] { 10017, "x-mac-ukrainian", "x-mac-ukrainian" }; yield return new object[] { 10021, "x-mac-thai", "x-mac-thai" }; yield return new object[] { 10029, "x-mac-ce", "x-mac-ce" }; yield return new object[] { 10079, "x-mac-icelandic", "x-mac-icelandic" }; yield return new object[] { 10081, "x-mac-turkish", "x-mac-turkish" }; yield return new object[] { 10082, "x-mac-croatian", "x-mac-croatian" }; yield return new object[] { 20000, "x-chinese-cns", "x-chinese-cns" }; yield return new object[] { 20001, "x-cp20001", "x-cp20001" }; yield return new object[] { 20002, "x-chinese-eten", "x-chinese-eten" }; yield return new object[] { 20003, "x-cp20003", "x-cp20003" }; yield return new object[] { 20004, "x-cp20004", "x-cp20004" }; yield return new object[] { 20005, "x-cp20005", "x-cp20005" }; yield return new object[] { 20105, "x-ia5", "x-ia5" }; yield return new object[] { 20105, "x-ia5", "irv" }; yield return new object[] { 20106, "x-ia5-german", "x-ia5-german" }; yield return new object[] { 20106, "x-ia5-german", "din_66003" }; yield return new object[] { 20106, "x-ia5-german", "german" }; yield return new object[] { 20107, "x-ia5-swedish", "x-ia5-swedish" }; yield return new object[] { 20107, "x-ia5-swedish", "sen_850200_b" }; yield return new object[] { 20107, "x-ia5-swedish", "swedish" }; yield return new object[] { 20108, "x-ia5-norwegian", "x-ia5-norwegian" }; yield return new object[] { 20108, "x-ia5-norwegian", "norwegian" }; yield return new object[] { 20108, "x-ia5-norwegian", "ns_4551-1" }; yield return new object[] { 20261, "x-cp20261", "x-cp20261" }; yield return new object[] { 20269, "x-cp20269", "x-cp20269" }; yield return new object[] { 20273, "ibm273", "ibm273" }; yield return new object[] { 20273, "ibm273", "cp273" }; yield return new object[] { 20273, "ibm273", "csibm273" }; yield return new object[] { 20277, "ibm277", "ibm277" }; yield return new object[] { 20277, "ibm277", "csibm277" }; yield return new object[] { 20277, "ibm277", "ebcdic-cp-dk" }; yield return new object[] { 20277, "ibm277", "ebcdic-cp-no" }; yield return new object[] { 20278, "ibm278", "ibm278" }; yield return new object[] { 20278, "ibm278", "cp278" }; yield return new object[] { 20278, "ibm278", "csibm278" }; yield return new object[] { 20278, "ibm278", "ebcdic-cp-fi" }; yield return new object[] { 20278, "ibm278", "ebcdic-cp-se" }; yield return new object[] { 20280, "ibm280", "ibm280" }; yield return new object[] { 20280, "ibm280", "cp280" }; yield return new object[] { 20280, "ibm280", "csibm280" }; yield return new object[] { 20280, "ibm280", "ebcdic-cp-it" }; yield return new object[] { 20284, "ibm284", "ibm284" }; yield return new object[] { 20284, "ibm284", "cp284" }; yield return new object[] { 20284, "ibm284", "csibm284" }; yield return new object[] { 20284, "ibm284", "ebcdic-cp-es" }; yield return new object[] { 20285, "ibm285", "ibm285" }; yield return new object[] { 20285, "ibm285", "cp285" }; yield return new object[] { 20285, "ibm285", "csibm285" }; yield return new object[] { 20285, "ibm285", "ebcdic-cp-gb" }; yield return new object[] { 20290, "ibm290", "ibm290" }; yield return new object[] { 20290, "ibm290", "cp290" }; yield return new object[] { 20290, "ibm290", "csibm290" }; yield return new object[] { 20290, "ibm290", "ebcdic-jp-kana" }; yield return new object[] { 20297, "ibm297", "ibm297" }; yield return new object[] { 20297, "ibm297", "cp297" }; yield return new object[] { 20297, "ibm297", "csibm297" }; yield return new object[] { 20297, "ibm297", "ebcdic-cp-fr" }; yield return new object[] { 20420, "ibm420", "ibm420" }; yield return new object[] { 20420, "ibm420", "cp420" }; yield return new object[] { 20420, "ibm420", "csibm420" }; yield return new object[] { 20420, "ibm420", "ebcdic-cp-ar1" }; yield return new object[] { 20423, "ibm423", "ibm423" }; yield return new object[] { 20423, "ibm423", "cp423" }; yield return new object[] { 20423, "ibm423", "csibm423" }; yield return new object[] { 20423, "ibm423", "ebcdic-cp-gr" }; yield return new object[] { 20424, "ibm424", "ibm424" }; yield return new object[] { 20424, "ibm424", "cp424" }; yield return new object[] { 20424, "ibm424", "csibm424" }; yield return new object[] { 20424, "ibm424", "ebcdic-cp-he" }; yield return new object[] { 20833, "x-ebcdic-koreanextended", "x-ebcdic-koreanextended" }; yield return new object[] { 20838, "ibm-thai", "ibm-thai" }; yield return new object[] { 20838, "ibm-thai", "csibmthai" }; yield return new object[] { 20866, "koi8-r", "koi8-r" }; yield return new object[] { 20866, "koi8-r", "cskoi8r" }; yield return new object[] { 20866, "koi8-r", "koi" }; yield return new object[] { 20866, "koi8-r", "koi8" }; yield return new object[] { 20866, "koi8-r", "koi8r" }; yield return new object[] { 20871, "ibm871", "ibm871" }; yield return new object[] { 20871, "ibm871", "cp871" }; yield return new object[] { 20871, "ibm871", "csibm871" }; yield return new object[] { 20871, "ibm871", "ebcdic-cp-is" }; yield return new object[] { 20880, "ibm880", "ibm880" }; yield return new object[] { 20880, "ibm880", "cp880" }; yield return new object[] { 20880, "ibm880", "csibm880" }; yield return new object[] { 20880, "ibm880", "ebcdic-cyrillic" }; yield return new object[] { 20905, "ibm905", "ibm905" }; yield return new object[] { 20905, "ibm905", "cp905" }; yield return new object[] { 20905, "ibm905", "csibm905" }; yield return new object[] { 20905, "ibm905", "ebcdic-cp-tr" }; yield return new object[] { 20924, "ibm00924", "ibm00924" }; yield return new object[] { 20924, "ibm00924", "ccsid00924" }; yield return new object[] { 20924, "ibm00924", "cp00924" }; yield return new object[] { 20924, "ibm00924", "ebcdic-latin9--euro" }; yield return new object[] { 20932, "euc-jp", "euc-jp" }; yield return new object[] { 20936, "x-cp20936", "x-cp20936" }; yield return new object[] { 20949, "x-cp20949", "x-cp20949" }; yield return new object[] { 21025, "cp1025", "cp1025" }; yield return new object[] { 21866, "koi8-u", "koi8-u" }; yield return new object[] { 21866, "koi8-u", "koi8-ru" }; yield return new object[] { 28592, "iso-8859-2", "iso-8859-2" }; yield return new object[] { 28592, "iso-8859-2", "csisolatin2" }; yield return new object[] { 28592, "iso-8859-2", "iso_8859-2" }; yield return new object[] { 28592, "iso-8859-2", "iso_8859-2:1987" }; yield return new object[] { 28592, "iso-8859-2", "iso8859-2" }; yield return new object[] { 28592, "iso-8859-2", "iso-ir-101" }; yield return new object[] { 28592, "iso-8859-2", "l2" }; yield return new object[] { 28592, "iso-8859-2", "latin2" }; yield return new object[] { 28593, "iso-8859-3", "iso-8859-3" }; yield return new object[] { 28593, "iso-8859-3", "csisolatin3" }; yield return new object[] { 28593, "iso-8859-3", "iso_8859-3" }; yield return new object[] { 28593, "iso-8859-3", "iso_8859-3:1988" }; yield return new object[] { 28593, "iso-8859-3", "iso-ir-109" }; yield return new object[] { 28593, "iso-8859-3", "l3" }; yield return new object[] { 28593, "iso-8859-3", "latin3" }; yield return new object[] { 28594, "iso-8859-4", "iso-8859-4" }; yield return new object[] { 28594, "iso-8859-4", "csisolatin4" }; yield return new object[] { 28594, "iso-8859-4", "iso_8859-4" }; yield return new object[] { 28594, "iso-8859-4", "iso_8859-4:1988" }; yield return new object[] { 28594, "iso-8859-4", "iso-ir-110" }; yield return new object[] { 28594, "iso-8859-4", "l4" }; yield return new object[] { 28594, "iso-8859-4", "latin4" }; yield return new object[] { 28595, "iso-8859-5", "iso-8859-5" }; yield return new object[] { 28595, "iso-8859-5", "csisolatincyrillic" }; yield return new object[] { 28595, "iso-8859-5", "cyrillic" }; yield return new object[] { 28595, "iso-8859-5", "iso_8859-5" }; yield return new object[] { 28595, "iso-8859-5", "iso_8859-5:1988" }; yield return new object[] { 28595, "iso-8859-5", "iso-ir-144" }; yield return new object[] { 28596, "iso-8859-6", "iso-8859-6" }; yield return new object[] { 28596, "iso-8859-6", "arabic" }; yield return new object[] { 28596, "iso-8859-6", "csisolatinarabic" }; yield return new object[] { 28596, "iso-8859-6", "ecma-114" }; yield return new object[] { 28596, "iso-8859-6", "iso_8859-6" }; yield return new object[] { 28596, "iso-8859-6", "iso_8859-6:1987" }; yield return new object[] { 28596, "iso-8859-6", "iso-ir-127" }; yield return new object[] { 28597, "iso-8859-7", "iso-8859-7" }; yield return new object[] { 28597, "iso-8859-7", "csisolatingreek" }; yield return new object[] { 28597, "iso-8859-7", "ecma-118" }; yield return new object[] { 28597, "iso-8859-7", "elot_928" }; yield return new object[] { 28597, "iso-8859-7", "greek" }; yield return new object[] { 28597, "iso-8859-7", "greek8" }; yield return new object[] { 28597, "iso-8859-7", "iso_8859-7" }; yield return new object[] { 28597, "iso-8859-7", "iso_8859-7:1987" }; yield return new object[] { 28597, "iso-8859-7", "iso-ir-126" }; yield return new object[] { 28598, "iso-8859-8", "iso-8859-8" }; yield return new object[] { 28598, "iso-8859-8", "csisolatinhebrew" }; yield return new object[] { 28598, "iso-8859-8", "hebrew" }; yield return new object[] { 28598, "iso-8859-8", "iso_8859-8" }; yield return new object[] { 28598, "iso-8859-8", "iso_8859-8:1988" }; yield return new object[] { 28598, "iso-8859-8", "iso-8859-8 visual" }; yield return new object[] { 28598, "iso-8859-8", "iso-ir-138" }; yield return new object[] { 28598, "iso-8859-8", "logical" }; yield return new object[] { 28598, "iso-8859-8", "visual" }; yield return new object[] { 28599, "iso-8859-9", "iso-8859-9" }; yield return new object[] { 28599, "iso-8859-9", "csisolatin5" }; yield return new object[] { 28599, "iso-8859-9", "iso_8859-9" }; yield return new object[] { 28599, "iso-8859-9", "iso_8859-9:1989" }; yield return new object[] { 28599, "iso-8859-9", "iso-ir-148" }; yield return new object[] { 28599, "iso-8859-9", "l5" }; yield return new object[] { 28599, "iso-8859-9", "latin5" }; yield return new object[] { 28603, "iso-8859-13", "iso-8859-13" }; yield return new object[] { 28605, "iso-8859-15", "iso-8859-15" }; yield return new object[] { 28605, "iso-8859-15", "csisolatin9" }; yield return new object[] { 28605, "iso-8859-15", "iso_8859-15" }; yield return new object[] { 28605, "iso-8859-15", "l9" }; yield return new object[] { 28605, "iso-8859-15", "latin9" }; yield return new object[] { 29001, "x-europa", "x-europa" }; yield return new object[] { 38598, "iso-8859-8-i", "iso-8859-8-i" }; yield return new object[] { 50220, "iso-2022-jp", "iso-2022-jp" }; yield return new object[] { 50221, "csiso2022jp", "csiso2022jp" }; yield return new object[] { 50222, "iso-2022-jp", "iso-2022-jp" }; yield return new object[] { 50225, "iso-2022-kr", "iso-2022-kr" }; yield return new object[] { 50225, "iso-2022-kr", "csiso2022kr" }; yield return new object[] { 50225, "iso-2022-kr", "iso-2022-kr-7" }; yield return new object[] { 50225, "iso-2022-kr", "iso-2022-kr-7bit" }; yield return new object[] { 50227, "x-cp50227", "x-cp50227" }; yield return new object[] { 50227, "x-cp50227", "cp50227" }; yield return new object[] { 51932, "euc-jp", "euc-jp" }; yield return new object[] { 51932, "euc-jp", "cseucpkdfmtjapanese" }; yield return new object[] { 51932, "euc-jp", "extended_unix_code_packed_format_for_japanese" }; yield return new object[] { 51932, "euc-jp", "iso-2022-jpeuc" }; yield return new object[] { 51932, "euc-jp", "x-euc" }; yield return new object[] { 51932, "euc-jp", "x-euc-jp" }; yield return new object[] { 51936, "euc-cn", "euc-cn" }; yield return new object[] { 51936, "euc-cn", "x-euc-cn" }; yield return new object[] { 51949, "euc-kr", "euc-kr" }; yield return new object[] { 51949, "euc-kr", "cseuckr" }; yield return new object[] { 51949, "euc-kr", "iso-2022-kr-8" }; yield return new object[] { 51949, "euc-kr", "iso-2022-kr-8bit" }; yield return new object[] { 52936, "hz-gb-2312", "hz-gb-2312" }; yield return new object[] { 54936, "gb18030", "gb18030" }; yield return new object[] { 57002, "x-iscii-de", "x-iscii-de" }; yield return new object[] { 57003, "x-iscii-be", "x-iscii-be" }; yield return new object[] { 57004, "x-iscii-ta", "x-iscii-ta" }; yield return new object[] { 57005, "x-iscii-te", "x-iscii-te" }; yield return new object[] { 57006, "x-iscii-as", "x-iscii-as" }; yield return new object[] { 57007, "x-iscii-or", "x-iscii-or" }; yield return new object[] { 57008, "x-iscii-ka", "x-iscii-ka" }; yield return new object[] { 57009, "x-iscii-ma", "x-iscii-ma" }; yield return new object[] { 57010, "x-iscii-gu", "x-iscii-gu" }; yield return new object[] { 57011, "x-iscii-pa", "x-iscii-pa" }; } public static IEnumerable<object[]> SpecificCodepageEncodings() { // Layout is codepage encoding, bytes, and matching unicode string. yield return new object[] { "Windows-1256", new byte[] { 0xC7, 0xE1, 0xE1, 0xE5, 0x20, 0xC7, 0xCD, 0xCF }, "\x0627\x0644\x0644\x0647\x0020\x0627\x062D\x062F" }; yield return new object[] {"Windows-1252", new byte[] { 0xD0, 0xD1, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xD7, 0xD8, 0xD9, 0xDA, 0xDB, 0xDC, 0xDD, 0xDE, 0xDF } , "\x00D0\x00D1\x00D2\x00D3\x00D4\x00D5\x00D6\x00D7\x00D8\x00D9\x00DA\x00DB\x00DC\x00DD\x00DE\x00DF"}; yield return new object[] { "GB2312", new byte[] { 0xCD, 0xE2, 0xCD, 0xE3, 0xCD, 0xE4 }, "\x5916\x8C4C\x5F2F" }; yield return new object[] {"GB18030", new byte[] { 0x81, 0x30, 0x89, 0x37, 0x81, 0x30, 0x89, 0x38, 0xA8, 0xA4, 0xA8, 0xA2, 0x81, 0x30, 0x89, 0x39, 0x81, 0x30, 0x8A, 0x30 } , "\x00DE\x00DF\x00E0\x00E1\x00E2\x00E3"}; } public static IEnumerable<object[]> MultibyteCharacterEncodings() { // Layout is the encoding, bytes, and expected result. yield return new object[] { "iso-2022-jp", new byte[] { 0xA, 0x1B, 0x24, 0x42, 0x25, 0x4A, 0x25, 0x4A, 0x1B, 0x28, 0x42, 0x1B, 0x24, 0x42, 0x25, 0x4A, 0x1B, 0x28, 0x42, 0x1B, 0x24, 0x42, 0x25, 0x4A, 0x1B, 0x28, 0x42, 0x1B, 0x1, 0x2, 0x3, 0x4, 0x1B, 0x24, 0x42, 0x25, 0x4A, 0x0E, 0x25, 0x4A, 0x1B, 0x28, 0x42, 0x41, 0x42, 0x0E, 0x25, 0x0F, 0x43 }, new int[] { 0xA, 0x30CA, 0x30CA, 0x30CA, 0x30CA, 0x1B, 0x1, 0x2, 0x3, 0x4, 0x30CA, 0xFF65, 0xFF8A, 0x41, 0x42, 0xFF65, 0x43} }; yield return new object[] { "GB18030", new byte[] { 0x41, 0x42, 0x43, 0x81, 0x40, 0x82, 0x80, 0x81, 0x30, 0x82, 0x31, 0x81, 0x20 }, new int[] { 0x41, 0x42, 0x43, 0x4E02, 0x500B, 0x8B, 0x3F, 0x20 } }; yield return new object[] { "shift_jis", new byte[] { 0x41, 0x42, 0x43, 0x81, 0x42, 0xE0, 0x43, 0x44, 0x45 }, new int[] { 0x41, 0x42, 0x43, 0x3002, 0x6F86, 0x44, 0x45 } }; yield return new object[] { "iso-2022-kr", new byte[] { 0x0E, 0x21, 0x7E, 0x1B, 0x24, 0x29, 0x43, 0x21, 0x7E, 0x0F, 0x21, 0x7E, 0x1B, 0x24, 0x29, 0x43, 0x21, 0x7E }, new int[] { 0xFFE2, 0xFFE2, 0x21, 0x7E, 0x21, 0x7E } }; yield return new object[] { "hz-gb-2312", new byte[] { 0x7E, 0x42, 0x7E, 0x7E, 0x7E, 0x7B, 0x21, 0x7E, 0x7E, 0x7D, 0x42, 0x42, 0x7E, 0xA, 0x43, 0x43 }, new int[] { 0x7E, 0x42, 0x7E, 0x3013, 0x42, 0x42, 0x43, 0x43, } }; } private static IEnumerable<KeyValuePair<int, string>> CrossplatformDefaultEncodings() { yield return Map(1200, "utf-16"); yield return Map(12000, "utf-32"); yield return Map(20127, "us-ascii"); yield return Map(65000, "utf-7"); yield return Map(65001, "utf-8"); } private static KeyValuePair<int, string> Map(int codePage, string webName) { return new KeyValuePair<int, string>(codePage, webName); } [Fact] public static void TestDefaultEncodings() { ValidateDefaultEncodings(); foreach (object[] mapping in CodePageInfo()) { Assert.Throws<NotSupportedException>(() => Encoding.GetEncoding((int)mapping[0])); Assert.Throws<ArgumentException>(() => Encoding.GetEncoding((string)mapping[2])); } // Currently the class EncodingInfo isn't present in corefx, so this checks none of the code pages are present. // When it is, comment out this line and remove the previous foreach/assert. // Assert.Equal(CrossplatformDefaultEncodings, Encoding.GetEncodings().OrderBy(i => i.CodePage).Select(i => Map(i.CodePage, i.WebName))); // The default encoding should be something from the known list. Encoding defaultEncoding = Encoding.GetEncoding(0); Assert.NotNull(defaultEncoding); KeyValuePair<int, string> mappedEncoding = Map(defaultEncoding.CodePage, defaultEncoding.WebName); Assert.Contains(mappedEncoding, CrossplatformDefaultEncodings()); // Add the code page provider. Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); // Make sure added code pages are identical between the provider and the Encoding class. foreach (object[] mapping in CodePageInfo()) { Encoding encoding = Encoding.GetEncoding((int)mapping[0]); Encoding codePageEncoding = CodePagesEncodingProvider.Instance.GetEncoding((int)mapping[0]); Assert.Equal(encoding, codePageEncoding); Assert.Equal(encoding.CodePage, (int)mapping[0]); Assert.Equal(encoding.WebName, (string)mapping[1]); // Get encoding via query string. Assert.Equal(Encoding.GetEncoding((string)mapping[2]), CodePagesEncodingProvider.Instance.GetEncoding((string)mapping[2])); } // Adding the code page provider should keep the originals, too. ValidateDefaultEncodings(); // Currently the class EncodingInfo isn't present in corefx, so this checks the complete list // When it is, comment out this line and remove the previous foreach/assert. // Assert.Equal(CrossplatformDefaultEncodings().Union(CodePageInfo().Select(i => Map((int)i[0], (string)i[1])).OrderBy(i => i.Key)), // Encoding.GetEncodings().OrderBy(i => i.CodePage).Select(i => Map(i.CodePage, i.WebName))); // Default encoding may have changed, should still be something on the combined list. defaultEncoding = Encoding.GetEncoding(0); Assert.NotNull(defaultEncoding); mappedEncoding = Map(defaultEncoding.CodePage, defaultEncoding.WebName); Assert.Contains(mappedEncoding, CrossplatformDefaultEncodings().Union(CodePageInfo().Select(i => Map((int)i[0], (string)i[1])))); } private static void ValidateDefaultEncodings() { foreach (var mapping in CrossplatformDefaultEncodings()) { Encoding encoding = Encoding.GetEncoding(mapping.Key); Assert.NotNull(encoding); Assert.Equal(encoding, Encoding.GetEncoding(mapping.Value)); Assert.Equal(mapping.Value, encoding.WebName); } } [Theory] [MemberData(nameof(SpecificCodepageEncodings))] public static void TestRoundtrippingSpecificCodepageEncoding(string encodingName, byte[] bytes, string expected) { Encoding encoding = CodePagesEncodingProvider.Instance.GetEncoding(encodingName); string encoded = encoding.GetString(bytes, 0, bytes.Length); Assert.Equal(expected, encoded); Assert.Equal(bytes, encoding.GetBytes(encoded)); byte[] resultBytes = encoding.GetBytes(encoded); } [Theory] [MemberData(nameof(CodePageInfo))] public static void TestCodepageEncoding(int codePage, string webName, string queryString) { Encoding encoding; // There are two names that have duplicate associated CodePages. For those two names, // we have to test with the expectation that querying the name will always return the // same codepage. if (codePage != 20932 && codePage != 50222) { encoding = CodePagesEncodingProvider.Instance.GetEncoding(queryString); Assert.Equal(encoding, CodePagesEncodingProvider.Instance.GetEncoding(codePage)); Assert.Equal(encoding, CodePagesEncodingProvider.Instance.GetEncoding(webName)); } else { encoding = CodePagesEncodingProvider.Instance.GetEncoding(codePage); Assert.NotEqual(encoding, CodePagesEncodingProvider.Instance.GetEncoding(queryString)); Assert.NotEqual(encoding, CodePagesEncodingProvider.Instance.GetEncoding(webName)); } Assert.NotNull(encoding); Assert.Equal(codePage, encoding.CodePage); Assert.Equal(webName, encoding.WebName); // Small round-trip for ASCII alphanumeric range (some code pages use different punctuation!) // Start with space. string asciiPrintable = " 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; char[] traveled = encoding.GetChars(encoding.GetBytes(asciiPrintable)); Assert.Equal(asciiPrintable.ToCharArray(), traveled); } [Theory] [MemberData(nameof(MultibyteCharacterEncodings))] public static void TestSpecificMultibyteCharacterEncodings(string codepageName, byte[] bytes, int[] expected) { Decoder decoder = CodePagesEncodingProvider.Instance.GetEncoding(codepageName).GetDecoder(); char[] buffer = new char[expected.Length]; for (int byteIndex = 0, charIndex = 0, charCount = 0; byteIndex < bytes.Length; byteIndex++, charIndex += charCount) { charCount = decoder.GetChars(bytes, byteIndex, 1, buffer, charIndex); } Assert.Equal(expected, buffer.Select(c => (int)c)); } [Theory] [MemberData(nameof(CodePageInfo))] public static void TestEncodingDisplayNames(int codePage, string webName, string queryString) { var encoding = CodePagesEncodingProvider.Instance.GetEncoding(codePage); string name = encoding.EncodingName; // Names can't be empty, and must be printable characters. Assert.False(string.IsNullOrWhiteSpace(name)); Assert.All(name, c => Assert.True(c >= ' ' && c < '~' + 1, "Name: " + name + " contains character: " + c)); } } public class CultureSetup : IDisposable { private readonly CultureInfo _originalUICulture; public CultureSetup() { _originalUICulture = CultureInfo.CurrentUICulture; CultureInfo.CurrentUICulture = new CultureInfo("en-US"); } public void Dispose() { CultureInfo.CurrentUICulture = _originalUICulture; } } }
/* Generated SBE (Simple Binary Encoding) message codec */ using System; using System.Text; using System.Collections.Generic; using Adaptive.Agrona; namespace Adaptive.Archiver.Codecs { public class DeleteDetachedSegmentsRequestDecoder { public const ushort BLOCK_LENGTH = 24; public const ushort TEMPLATE_ID = 54; public const ushort SCHEMA_ID = 101; public const ushort SCHEMA_VERSION = 6; private DeleteDetachedSegmentsRequestDecoder _parentMessage; private IDirectBuffer _buffer; protected int _offset; protected int _limit; protected int _actingBlockLength; protected int _actingVersion; public DeleteDetachedSegmentsRequestDecoder() { _parentMessage = this; } public ushort SbeBlockLength() { return BLOCK_LENGTH; } public ushort SbeTemplateId() { return TEMPLATE_ID; } public ushort SbeSchemaId() { return SCHEMA_ID; } public ushort SbeSchemaVersion() { return SCHEMA_VERSION; } public string SbeSemanticType() { return ""; } public IDirectBuffer Buffer() { return _buffer; } public int Offset() { return _offset; } public DeleteDetachedSegmentsRequestDecoder Wrap( IDirectBuffer buffer, int offset, int actingBlockLength, int actingVersion) { this._buffer = buffer; this._offset = offset; this._actingBlockLength = actingBlockLength; this._actingVersion = actingVersion; Limit(offset + actingBlockLength); return this; } public int EncodedLength() { return _limit - _offset; } public int Limit() { return _limit; } public void Limit(int limit) { this._limit = limit; } public static int ControlSessionIdId() { return 1; } public static int ControlSessionIdSinceVersion() { return 0; } public static int ControlSessionIdEncodingOffset() { return 0; } public static int ControlSessionIdEncodingLength() { return 8; } public static string ControlSessionIdMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.EPOCH: return "unix"; case MetaAttribute.TIME_UNIT: return "nanosecond"; case MetaAttribute.SEMANTIC_TYPE: return ""; case MetaAttribute.PRESENCE: return "required"; } return ""; } public static long ControlSessionIdNullValue() { return -9223372036854775808L; } public static long ControlSessionIdMinValue() { return -9223372036854775807L; } public static long ControlSessionIdMaxValue() { return 9223372036854775807L; } public long ControlSessionId() { return _buffer.GetLong(_offset + 0, ByteOrder.LittleEndian); } public static int CorrelationIdId() { return 2; } public static int CorrelationIdSinceVersion() { return 0; } public static int CorrelationIdEncodingOffset() { return 8; } public static int CorrelationIdEncodingLength() { return 8; } public static string CorrelationIdMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.EPOCH: return "unix"; case MetaAttribute.TIME_UNIT: return "nanosecond"; case MetaAttribute.SEMANTIC_TYPE: return ""; case MetaAttribute.PRESENCE: return "required"; } return ""; } public static long CorrelationIdNullValue() { return -9223372036854775808L; } public static long CorrelationIdMinValue() { return -9223372036854775807L; } public static long CorrelationIdMaxValue() { return 9223372036854775807L; } public long CorrelationId() { return _buffer.GetLong(_offset + 8, ByteOrder.LittleEndian); } public static int RecordingIdId() { return 3; } public static int RecordingIdSinceVersion() { return 0; } public static int RecordingIdEncodingOffset() { return 16; } public static int RecordingIdEncodingLength() { return 8; } public static string RecordingIdMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.EPOCH: return "unix"; case MetaAttribute.TIME_UNIT: return "nanosecond"; case MetaAttribute.SEMANTIC_TYPE: return ""; case MetaAttribute.PRESENCE: return "required"; } return ""; } public static long RecordingIdNullValue() { return -9223372036854775808L; } public static long RecordingIdMinValue() { return -9223372036854775807L; } public static long RecordingIdMaxValue() { return 9223372036854775807L; } public long RecordingId() { return _buffer.GetLong(_offset + 16, ByteOrder.LittleEndian); } public override string ToString() { return AppendTo(new StringBuilder(100)).ToString(); } public StringBuilder AppendTo(StringBuilder builder) { int originalLimit = Limit(); Limit(_offset + _actingBlockLength); builder.Append("[DeleteDetachedSegmentsRequest](sbeTemplateId="); builder.Append(TEMPLATE_ID); builder.Append("|sbeSchemaId="); builder.Append(SCHEMA_ID); builder.Append("|sbeSchemaVersion="); if (_parentMessage._actingVersion != SCHEMA_VERSION) { builder.Append(_parentMessage._actingVersion); builder.Append('/'); } builder.Append(SCHEMA_VERSION); builder.Append("|sbeBlockLength="); if (_actingBlockLength != BLOCK_LENGTH) { builder.Append(_actingBlockLength); builder.Append('/'); } builder.Append(BLOCK_LENGTH); builder.Append("):"); //Token{signal=BEGIN_FIELD, name='controlSessionId', referencedName='null', description='null', id=1, version=0, deprecated=0, encodedLength=0, offset=0, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} //Token{signal=ENCODING, name='int64', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=8, offset=0, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT64, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} builder.Append("ControlSessionId="); builder.Append(ControlSessionId()); builder.Append('|'); //Token{signal=BEGIN_FIELD, name='correlationId', referencedName='null', description='null', id=2, version=0, deprecated=0, encodedLength=0, offset=8, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} //Token{signal=ENCODING, name='int64', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=8, offset=8, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT64, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} builder.Append("CorrelationId="); builder.Append(CorrelationId()); builder.Append('|'); //Token{signal=BEGIN_FIELD, name='recordingId', referencedName='null', description='null', id=3, version=0, deprecated=0, encodedLength=0, offset=16, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} //Token{signal=ENCODING, name='int64', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=8, offset=16, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT64, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} builder.Append("RecordingId="); builder.Append(RecordingId()); Limit(originalLimit); return builder; } } }
// Copyright (c) The Avalonia Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using System; using System.Collections.Generic; using System.Reactive.Linq; using Moq; using Avalonia.Styling; using Avalonia.UnitTests; using Xunit; namespace Avalonia.Controls.UnitTests { public class ControlTests { [Fact] public void Classes_Should_Initially_Be_Empty() { var target = new Control(); Assert.Equal(0, target.Classes.Count); } [Fact] public void Setting_Parent_Should_Also_Set_InheritanceParent() { var parent = new Decorator(); var target = new TestControl(); parent.Child = target; Assert.Equal(parent, target.Parent); Assert.Equal(parent, target.InheritanceParent); } [Fact] public void Setting_Parent_Should_Not_Set_InheritanceParent_If_Already_Set() { var parent = new Decorator(); var inheritanceParent = new Decorator(); var target = new TestControl(); ((ISetInheritanceParent)target).SetParent(inheritanceParent); parent.Child = target; Assert.Equal(parent, target.Parent); Assert.Equal(inheritanceParent, target.InheritanceParent); } [Fact] public void InheritanceParent_Should_Be_Cleared_When_Removed_From_Parent() { var parent = new Decorator(); var target = new TestControl(); parent.Child = target; parent.Child = null; Assert.Null(target.InheritanceParent); } [Fact] public void InheritanceParent_Should_Be_Cleared_When_Removed_From_Parent_When_Has_Different_InheritanceParent() { var parent = new Decorator(); var inheritanceParent = new Decorator(); var target = new TestControl(); ((ISetInheritanceParent)target).SetParent(inheritanceParent); parent.Child = target; parent.Child = null; Assert.Null(target.InheritanceParent); } [Fact] public void AttachedToLogicalParent_Should_Be_Called_When_Added_To_Tree() { var root = new TestRoot(); var parent = new Border(); var child = new Border(); var grandchild = new Border(); var parentRaised = false; var childRaised = false; var grandchildRaised = false; parent.AttachedToLogicalTree += (s, e) => parentRaised = true; child.AttachedToLogicalTree += (s, e) => childRaised = true; grandchild.AttachedToLogicalTree += (s, e) => grandchildRaised = true; parent.Child = child; child.Child = grandchild; Assert.False(parentRaised); Assert.False(childRaised); Assert.False(grandchildRaised); root.Child = parent; Assert.True(parentRaised); Assert.True(childRaised); Assert.True(grandchildRaised); } [Fact] public void AttachedToLogicalParent_Should_Be_Called_Before_Parent_Change_Signalled() { var root = new TestRoot(); var child = new Border(); var raised = new List<string>(); child.AttachedToLogicalTree += (s, e) => { Assert.Equal(root, child.Parent); raised.Add("attached"); }; child.GetObservable(Control.ParentProperty).Skip(1).Subscribe(_ => raised.Add("parent")); root.Child = child; Assert.Equal(new[] { "attached", "parent" }, raised); } [Fact] public void DetachedToLogicalParent_Should_Be_Called_When_Removed_From_Tree() { var root = new TestRoot(); var parent = new Border(); var child = new Border(); var grandchild = new Border(); var parentRaised = false; var childRaised = false; var grandchildRaised = false; parent.Child = child; child.Child = grandchild; root.Child = parent; parent.DetachedFromLogicalTree += (s, e) => parentRaised = true; child.DetachedFromLogicalTree += (s, e) => childRaised = true; grandchild.DetachedFromLogicalTree += (s, e) => grandchildRaised = true; root.Child = null; Assert.True(parentRaised); Assert.True(childRaised); Assert.True(grandchildRaised); } [Fact] public void Adding_Tree_To_IStyleRoot_Should_Style_Controls() { using (AvaloniaLocator.EnterScope()) { var root = new TestRoot(); var parent = new Border(); var child = new Border(); var grandchild = new Control(); var styler = new Mock<IStyler>(); AvaloniaLocator.CurrentMutable.Bind<IStyler>().ToConstant(styler.Object); parent.Child = child; child.Child = grandchild; styler.Verify(x => x.ApplyStyles(It.IsAny<IStyleable>()), Times.Never()); root.Child = parent; styler.Verify(x => x.ApplyStyles(parent), Times.Once()); styler.Verify(x => x.ApplyStyles(child), Times.Once()); styler.Verify(x => x.ApplyStyles(grandchild), Times.Once()); } } [Fact] public void Styles_Not_Applied_Until_Initialization_Finished() { using (AvaloniaLocator.EnterScope()) { var root = new TestRoot(); var child = new Border(); var styler = new Mock<IStyler>(); AvaloniaLocator.CurrentMutable.Bind<IStyler>().ToConstant(styler.Object); ((ISupportInitialize)child).BeginInit(); root.Child = child; styler.Verify(x => x.ApplyStyles(It.IsAny<IStyleable>()), Times.Never()); ((ISupportInitialize)child).EndInit(); styler.Verify(x => x.ApplyStyles(child), Times.Once()); } } [Fact] public void Adding_To_Logical_Tree_Should_Register_With_NameScope() { using (AvaloniaLocator.EnterScope()) { var root = new TestRoot(); var child = new Border(); child.Name = "foo"; root.Child = child; Assert.Same(root.FindControl<Border>("foo"), child); } } [Fact] public void Name_Cannot_Be_Set_After_Added_To_Logical_Tree() { using (AvaloniaLocator.EnterScope()) { var root = new TestRoot(); var child = new Border(); root.Child = child; Assert.Throws<InvalidOperationException>(() => child.Name = "foo"); } } [Fact] public void Name_Can_Be_Set_While_Initializing() { using (AvaloniaLocator.EnterScope()) { var root = new TestRoot(); var child = new Border(); ((ISupportInitialize)child).BeginInit(); root.Child = child; child.Name = "foo"; Assert.Null(root.FindControl<Border>("foo")); ((ISupportInitialize)child).EndInit(); Assert.Same(root.FindControl<Border>("foo"), child); } } [Fact] public void StyleDetach_Is_Triggered_When_Control_Removed_From_Logical_Tree() { using (AvaloniaLocator.EnterScope()) { var root = new TestRoot(); var child = new Border(); root.Child = child; bool styleDetachTriggered = false; ((IStyleable)child).StyleDetach.Subscribe(_ => styleDetachTriggered = true); root.Child = null; Assert.True(styleDetachTriggered); } } [Fact] public void EndInit_Should_Raise_Initialized() { var root = new TestRoot(); var target = new Border(); var called = false; target.Initialized += (s, e) => called = true; ((ISupportInitialize)target).BeginInit(); root.Child = target; ((ISupportInitialize)target).EndInit(); Assert.True(called); Assert.True(target.IsInitialized); } [Fact] public void Attaching_To_Visual_Tree_Should_Raise_Initialized() { var root = new TestRoot(); var target = new Border(); var called = false; target.Initialized += (s, e) => called = true; root.Child = target; Assert.True(called); Assert.True(target.IsInitialized); } private class TestControl : Control { public new IAvaloniaObject InheritanceParent => base.InheritanceParent; } } }
using System.Globalization; using System.Linq; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; namespace Aardvark.Base { /// <summary> /// A three-dimensional ray with an origin and a direction. /// </summary> [StructLayout(LayoutKind.Sequential)] public struct Ray3d : IValidity, IBoundingBox3d { public V3d Origin; public V3d Direction; #region Constructors /// <summary> /// Creates Ray from origin point and directional vector /// </summary> public Ray3d(V3d origin, V3d direction) { Origin = origin; Direction = direction; } public static Ray3d FromEndPoints(V3d origin, V3d target) => new Ray3d(origin, target - origin); #endregion #region Constants /// <summary> /// An invalid ray has a zero direction. /// </summary> public static readonly Ray3d Invalid = new Ray3d(V3d.NaN, V3d.Zero); #endregion #region Properties /// <summary> /// A ray is valid if its direction is non-zero. /// </summary> public bool IsValid { get { return Direction != V3d.Zero; } } /// <summary> /// A ray is invalid if its direction is zero. /// </summary> public bool IsInvalid { get { return Direction == V3d.Zero; } } /// <summary> /// Returns true if either the origin or the direction contains any NaN value. /// </summary> public bool AnyNaN { get { return Origin.AnyNaN || Direction.AnyNaN; } } /// <summary> /// Line segment from origin to origin + direction. /// </summary> public Line3d Line3d => new Line3d(Origin, Origin + Direction); /// <summary> /// Returns new ray with flipped direction. /// </summary> public Ray3d Reversed => new Ray3d(Origin, -Direction); #endregion #region Ray Arithmetics /// <summary> /// Gets the point on the ray that is t * Direction from Origin. /// </summary> public V3d GetPointOnRay(double t) => Origin + Direction * t; /// <summary> /// Gets the t for a point p on this ray. /// </summary> public double GetT(V3d p) { var v = p - Origin; var d = Direction.Abs(); if (d.X > d.Y) return (d.X > d.Z) ? (v.X / Direction.X) : (v.Z / Direction.Z); else return (d.Y > d.Z) ? (v.Y / Direction.Y) : (v.Z / Direction.Z); } /// <summary> /// Gets the t of the closest point on the ray for any point p. /// </summary> public double GetTOfProjectedPoint(V3d p) { var v = p - Origin; return v.Dot(Direction) / Direction.LengthSquared; } /// <summary> /// Returns true if the ray hits the other ray before the parameter /// value contained in the supplied hit. Detailed information about /// the hit is returned in the supplied hit. /// </summary> public bool Hits(Ray3d ray, ref RayHit3d hit) => HitsRay(ray, double.MinValue, double.MaxValue, ref hit); /// <summary> /// Returns true if the ray hits the other ray before the parameter /// value contained in the supplied hit. Detailed information about /// the hit is returned in the supplied hit. /// </summary> public bool Hits(Ray3d ray, double tmin, double tmax, ref RayHit3d hit) => HitsRay(ray, tmin, tmax, ref hit); /// <summary> /// Returns true if the ray hits the other ray before the parameter /// value contained in the supplied hit. Detailed information about /// the hit is returned in the supplied hit. /// </summary> public bool HitsRay(Ray3d ray, double tmin, double tmax, ref RayHit3d hit) { V3d d = Origin - ray.Origin; V3d u = Direction; V3d v = ray.Direction; V3d n = u.Cross(v); if (Fun.IsTiny(d.Length)) return true; else if (Fun.IsTiny(u.Cross(v).Length)) return false; else { //-t0*u + t1*v + t2*n == d //M = {-u,v,n} //M*{t0,t1,t2}T == d //{t0,t1,t2}T == M^-1 * d M33d M = new M33d { C0 = -u, C1 = v, C2 = n }; if (M.Invertible) { V3d t = M.Inverse * d; if (Fun.IsTiny(t.Z)) { ProcessHits(t.X, double.MaxValue, tmin, tmax, ref hit); return true; } else return false; } else return false; } } /// <summary> /// Returns true if the ray hits the triangle before the parameter /// value contained in the supplied hit. Detailed information about /// the hit is returned in the supplied hit. /// </summary> public bool Hits(Triangle3d triangle, ref RayHit3d hit) => HitsTrianglePointAndEdges( triangle.P0, triangle.Edge01, triangle.Edge02, double.MinValue, double.MaxValue, ref hit); /// <summary> /// Returns true if the ray hits the triangle within the supplied /// parameter interval and before the parameter value contained /// in the supplied hit. Detailed information about the hit is /// returned in the supplied hit. In order to obtain all potential /// hits, the supplied hit can be initialized with RayHit3d.MaxRange. /// </summary> public bool Hits(Triangle3d triangle, double tmin, double tmax, ref RayHit3d hit) => HitsTrianglePointAndEdges( triangle.P0, triangle.Edge01, triangle.Edge02, tmin, tmax, ref hit); /// <summary> /// Returns true if the ray hits the triangle within the supplied /// parameter interval and before the parameter value contained /// in the supplied hit. Detailed information about the hit is /// returned in the supplied hit. In order to obtain all potential /// hits, the supplied hit can be initialized with RayHit3d.MaxRange. /// </summary> public bool HitsTriangle( V3d p0, V3d p1, V3d p2, double tmin, double tmax, ref RayHit3d hit ) { V3d edge01 = p1 - p0; V3d edge02 = p2 - p0; V3d plane = Vec.Cross(Direction, edge02); double det = Vec.Dot(edge01, plane); if (det > -0.0000001 && det < 0.0000001) return false; // ray ~= paralell / Triangle V3d tv = Origin - p0; det = 1.0 / det; // det is now inverse det double u = Vec.Dot(tv, plane) * det; if (u < 0.0 || u > 1.0) return false; plane = Vec.Cross(tv, edge01); // plane is now qv double v = Vec.Dot(Direction, plane) * det; if (v < 0.0 || u + v > 1.0) return false; double t = Vec.Dot(edge02, plane) * det; if (t < tmin || t >= tmax || t >= hit.T) return false; hit.T = t; hit.Point = Origin + t * Direction; hit.Coord.X = u; hit.Coord.Y = v; hit.BackSide = (det < 0.0); return true; } /// <summary> /// Returns true if the ray hits the triangle within the supplied /// parameter interval and before the parameter value contained /// in the supplied hit. Detailed information about the hit is /// returned in the supplied hit. In order to obtain all potential /// hits, the supplied hit can be initialized with RayHit3d.MaxRange. /// </summary> public bool HitsTrianglePointAndEdges( V3d p0, V3d edge01, V3d edge02, double tmin, double tmax, ref RayHit3d hit ) { V3d plane = Vec.Cross(Direction, edge02); double det = Vec.Dot(edge01, plane); if (det > -0.0000001 && det < 0.0000001) return false; // ray ~= paralell / Triangle V3d tv = Origin - p0; det = 1.0 / det; // det is now inverse det double u = Vec.Dot(tv, plane) * det; if (u < 0.0 || u > 1.0) return false; plane = Vec.Cross(tv, edge01); // plane is now qv double v = Vec.Dot(Direction, plane) * det; if (v < 0.0 || u + v > 1.0) return false; double t = Vec.Dot(edge02, plane) * det; if (t < tmin || t >= tmax || t >= hit.T) return false; hit.T = t; hit.Point = Origin + t * Direction; hit.Coord.X = u; hit.Coord.Y = v; hit.BackSide = (det < 0.0); return true; } /// <summary> /// Returns true if the ray hits the quad before the parameter /// value contained in the supplied hit. Detailed information about /// the hit is returned in the supplied hit. In order to obtain all /// potential hits, the supplied hit can be initialized with /// RayHit3d.MaxRange. /// </summary> public bool Hits(Quad3d quad, ref RayHit3d hit) => HitsQuad( quad.P0, quad.P1, quad.P2, quad.P3, double.MinValue, double.MaxValue, ref hit); /// <summary> /// Returns true if the ray hits the quad within the supplied /// parameter interval and before the parameter value contained /// in the supplied hit. Detailed information about the hit is /// returned in the supplied hit. In order to obtain all potential /// hits, the supplied hit can be initialized with RayHit3d.MaxRange. /// </summary> public bool Hits(Quad3d quad, double tmin, double tmax, ref RayHit3d hit) => HitsQuad( quad.P0, quad.P1, quad.P2, quad.P3, tmin, tmax, ref hit); /// <summary> /// Returns true if the ray hits the quad within the supplied /// parameter interval and before the parameter value contained /// in the supplied hit. The quad is considered to consist of the /// two triangles [p0,p1,p2] and [p0,p2,p3]. Detailed information /// about the hit is returned in the supplied hit. In order to obtain /// all potential hits, the supplied hit can be initialized with /// RayHit3d.MaxRange. /// </summary> public bool HitsQuad( V3d p0, V3d p1, V3d p2, V3d p3, double tmin, double tmax, ref RayHit3d hit ) { V3d e02 = p2 - p0; bool result = false; if (HitsTrianglePointAndEdges(p0, p1 - p0, e02, tmin, tmax, ref hit)) { hit.Coord.X += hit.Coord.Y; result = true; } if (HitsTrianglePointAndEdges(p0, e02, p3 - p0, tmin, tmax, ref hit)) { hit.Coord.Y += hit.Coord.X; result = true; } return result; } private bool ComputeHit( double t, double tmin, double tmax, ref RayHit3d hit) { if (t >= tmin) { if (t < tmax && t < hit.T) { hit.T = t; hit.Point = GetPointOnRay(t); hit.Coord = V2d.NaN; hit.BackSide = false; return true; } return false; } return false; } private bool GetClosestHit( double t1, double t2, double tmin, double tmax, ref RayHit3d hit) { return t1 < t2 ? ProcessHits(t1, t2, tmin, tmax, ref hit) : ProcessHits(t2, t1, tmin, tmax, ref hit); } private bool ProcessHits( double t1, double t2, double tmin, double tmax, ref RayHit3d hit) { if (t1 >= tmin) { if (t1 < tmax && t1 < hit.T) { hit.T = t1; hit.Point = GetPointOnRay(t1); hit.Coord = V2d.NaN; hit.BackSide = false; return true; } return false; } if (t2 >= tmin) { if (t2 < tmax && t2 < hit.T) { hit.T = t2; hit.Point = GetPointOnRay(t2); hit.Coord = V2d.NaN; hit.BackSide = true; return true; } } return false; } /// <summary> /// Returns true if the ray hits the sphere given by center and /// radius within the supplied parameter interval and before the /// parameter value contained in the supplied hit. Note that a /// hit is only registered if the front or the backsurface is /// encountered within the interval. /// </summary> public bool HitsSphere( V3d center, double radius, double tmin, double tmax, ref RayHit3d hit) { V3d originSubCenter = Origin - center; double a = Direction.LengthSquared; double b = Direction.Dot(originSubCenter); double c = originSubCenter.LengthSquared - radius * radius; // --------------------- quadric equation : a t^2 + 2b t + c = 0 double d = b * b - a * c; // factor 2 was eliminated if (d < Constant<double>.PositiveTinyValue) // no root ? return false; // then exit if (b > 0.0) // stable way to calculate d = -Fun.Sqrt(d) - b; // the roots of a quadratic else // equation d = Fun.Sqrt(d) - b; double t1 = d / a; double t2 = c / d; // Vieta : t1 * t2 == c/a return t1 < t2 ? ProcessHits(t1, t2, tmin, tmax, ref hit) : ProcessHits(t2, t1, tmin, tmax, ref hit); } /// <summary> /// Returns true if the ray hits the supplied sphere within the /// supplied parameter interval and before the parameter value /// contained in the supplied hit. Note that a hit is only /// registered if the front or the backsurface is encountered /// within the interval. /// </summary> public bool Hits(Sphere3d sphere, double tmin, double tmax, ref RayHit3d hit) => HitsSphere(sphere.Center, sphere.Radius, tmin, tmax, ref hit); public bool HitsPlane(Plane3d plane, double tmin, double tmax, ref RayHit3d hit) { var dc = plane.Normal.Dot(Direction); var dw = plane.Distance - plane.Normal.Dot(Origin); // If parallel to plane if (dc == 0.0) return false; var t = dw / dc; return (ComputeHit(t, tmin, tmax, ref hit)); } public bool HitsCircle(Circle3d circle, double tmin, double tmax, ref RayHit3d hit) { var dc = circle.Normal.Dot(Direction); var dw = circle.Normal.Dot(circle.Center - Origin); // If parallel to plane if (dc == 0.0) return false; var t = dw / dc; if (!ComputeHit(t, tmin, tmax, ref hit)) return false; if (Vec.Distance(hit.Point, circle.Center) > circle.Radius) { hit.Point = V3d.NaN; hit.T = tmax; return false; } return true; } public bool HitsCylinder(Cylinder3d cylinder, double tmin, double tmax, ref RayHit3d hit) { var axisDir = cylinder.Axis.Direction.Normalized; // Vector Cyl.P0 -> Ray.Origin var op = Origin - cylinder.P0; // normal RayDirection - CylinderAxis var normal = Direction.Cross(axisDir); var unitNormal = normal.Normalized; // normal (Vec Cyl.P0 -> Ray.Origin) - CylinderAxis var normal2 = op.Cross(axisDir); var t = -normal2.Dot(unitNormal) / normal.Length; var radius = cylinder.Radius; if (cylinder.DistanceScale != 0) { // cylinder gets bigger, the further away it is var pnt = GetPointOnRay(t); var dis = Vec.Distance(pnt, this.Origin); radius = ((cylinder.Radius / cylinder.DistanceScale) * dis) * 2; } // between enitre rays (caps are ignored) var shortestDistance = Fun.Abs(op.Dot(unitNormal)); if (shortestDistance <= radius) { var s = Fun.Abs(Fun.Sqrt(radius.Square() - shortestDistance.Square()) / Direction.Length); var t1 = t - s; // first hit of Cylinder shell var t2 = t + s; // second hit of Cylinder shell if (t1 > tmin && t1 < tmax) tmin = t1; if (t2 < tmax && t2 > tmin) tmax = t2; hit.T = t1; hit.Point = GetPointOnRay(t1); // check if found point is outside of Cylinder Caps var bottomPlane = new Plane3d(cylinder.Circle0.Normal, cylinder.Circle0.Center); var topPlane = new Plane3d(cylinder.Circle1.Normal, cylinder.Circle1.Center); var heightBottom = bottomPlane.Height(hit.Point); var heightTop = topPlane.Height(hit.Point); // t1 lies outside of caps => find closest cap hit if (heightBottom > 0 || heightTop > 0) { hit.T = tmax; // intersect with bottom Cylinder Cap var bottomHit = HitsPlane(bottomPlane, tmin, tmax, ref hit); // intersect with top Cylinder Cap var topHit = HitsPlane(topPlane, tmin, tmax, ref hit); // hit still close enough to cylinder axis? var distance = cylinder.Axis.Ray3d.GetMinimalDistanceTo(hit.Point); if (distance <= radius && (bottomHit || topHit)) return true; } else return true; } hit.T = tmax; hit.Point = V3d.NaN; return false; } public bool Hits( Cylinder3d cylinder, double tmin, double tmax, ref RayHit3d hit) { var intersects = HitsCylinder(cylinder, tmin, tmax, ref hit); return intersects; } /// <summary> /// Returns the ray transformed with the given matrix. /// </summary> public Ray3d Transformed(M44d mat) => new Ray3d( mat.TransformPos(Origin), mat.TransformDir(Direction) ); /// <summary> /// Returns the angle between this and the given <see cref="Ray3d"/> in radians. /// The direction vectors of the input rays have to be normalized. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public double AngleBetweenFast(Ray3d r) => Direction.AngleBetweenFast(r.Direction); /// <summary> /// Returns the angle between this and the given <see cref="Ray3d"/> in radians using a numerically stable algorithm. /// The direction vectors of the input rays have to be normalized. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public double AngleBetween(Ray3d r) => Direction.AngleBetween(r.Direction); #endregion #region Comparison Operators [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(Ray3d a, Ray3d b) => (a.Origin == b.Origin) && (a.Direction == b.Direction); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator !=(Ray3d a, Ray3d b) => !((a.Origin == b.Origin) && (a.Direction == b.Direction)); [MethodImpl(MethodImplOptions.AggressiveInlining)] public int LexicalCompare(Ray3d other) { var cmp = Origin.LexicalCompare(other.Origin); if (cmp != 0) return cmp; return Direction.LexicalCompare(other.Direction); } #endregion #region Overrides /// <summary> /// Calculates Hash-code of the given ray. /// </summary> /// <returns>Hash-code.</returns> public override int GetHashCode() => HashCode.GetCombined(Origin, Direction); [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool Equals(Ray3d other) => Origin.Equals(other.Origin) && Direction.Equals(other.Direction); public override bool Equals(object other) => (other is Ray3d o) ? Equals(o) : false; public override string ToString() => string.Format(CultureInfo.InvariantCulture, "[{0}, {1}]", Origin, Direction); public static Ray3d Parse(string s) { var x = s.NestedBracketSplitLevelOne().ToArray(); return new Ray3d(V3d.Parse(x[0]), V3d.Parse(x[1])); } #endregion #region IBoundingBox3d public Box3d BoundingBox3d => Box3d.FromPoints(Origin, Direction + Origin); #endregion } public static partial class Fun { /// <summary> /// Returns whether the given <see cref="Ray3d"/> are equal within the given tolerance. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool ApproximateEquals(this Ray3d a, Ray3d b, double tolerance) => ApproximateEquals(a.Origin, b.Origin, tolerance) && ApproximateEquals(a.Direction, b.Direction, tolerance); /// <summary> /// Returns whether the given <see cref="Ray3d"/> are equal within /// Constant&lt;double&gt;.PositiveTinyValue. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool ApproximateEquals(this Ray3d a, Ray3d b) => ApproximateEquals(a, b, Constant<double>.PositiveTinyValue); } /// <summary> /// A ray hit represents the hit of a ray on a primitive object such as /// a triangle. It stores the ray parameter of the hit, the hit point, /// the hit point's coordinates, and a flag indicating if the backside /// of the primitive was hit. Optionally the part field can be used to /// store which part of a multi-part object was hit. If no multi-part /// objects are used, this field remains 0. /// </summary> public struct RayHit3d { public double T; public V3d Point; public V2d Coord; public bool BackSide; public int Part; #region Constructor public RayHit3d(double tMax) { T = tMax; Point = V3d.NaN; Coord = V2d.NaN; BackSide = false; Part = 0; } #endregion #region Constants public static readonly RayHit3d MaxRange = new RayHit3d(double.MaxValue); #endregion } /// <summary> /// A fast ray contains a ray and a number of precomputed flags and /// fields for fast intersection computation with bounding boxes and /// other axis-aligned sturctures such as kd-Trees. /// </summary> public struct FastRay3d { public readonly Ray3d Ray; public readonly DirFlags DirFlags; public readonly V3d InvDir; #region Constructors public FastRay3d(Ray3d ray) { Ray = ray; DirFlags = ray.Direction.DirFlags(); InvDir = 1.0 / ray.Direction; } public FastRay3d(V3d origin, V3d direction) : this(new Ray3d(origin, direction)) { } #endregion #region Ray Arithmetics public bool Intersects( Box3d box, ref double tmin, ref double tmax ) { var dirFlags = DirFlags; if ((dirFlags & DirFlags.PositiveX) != 0) { { double t = (box.Max.X - Ray.Origin.X) * InvDir.X; if (t <= tmin) return false; if (t < tmax) tmax = t; } { double t = (box.Min.X - Ray.Origin.X) * InvDir.X; if (t >= tmax) return false; if (t > tmin) tmin = t; } } else if ((dirFlags & DirFlags.NegativeX) != 0) { { double t = (box.Min.X - Ray.Origin.X) * InvDir.X; if (t <= tmin) return false; if (t < tmax) tmax = t; } { double t = (box.Max.X - Ray.Origin.X) * InvDir.X; if (t >= tmax) return false; if (t > tmin) tmin = t; } } else // ray parallel to X-plane { if (Ray.Origin.X < box.Min.X || Ray.Origin.X > box.Max.X) return false; } if ((dirFlags & DirFlags.PositiveY) != 0) { { double t = (box.Max.Y - Ray.Origin.Y) * InvDir.Y; if (t <= tmin) return false; if (t < tmax) tmax = t; } { double t = (box.Min.Y - Ray.Origin.Y) * InvDir.Y; if (t >= tmax) return false; if (t > tmin) tmin = t; } } else if ((dirFlags & DirFlags.NegativeY) != 0) { { double t = (box.Min.Y - Ray.Origin.Y) * InvDir.Y; if (t <= tmin) return false; if (t < tmax) tmax = t; } { double t = (box.Max.Y - Ray.Origin.Y) * InvDir.Y; if (t >= tmax) return false; if (t > tmin) tmin = t; } } else // ray parallel to Y-plane { if (Ray.Origin.Y < box.Min.Y || Ray.Origin.Y > box.Max.Y) return false; } if ((dirFlags & DirFlags.PositiveZ) != 0) { { double t = (box.Max.Z - Ray.Origin.Z) * InvDir.Z; if (t <= tmin) return false; if (t < tmax) tmax = t; } { double t = (box.Min.Z - Ray.Origin.Z) * InvDir.Z; if (t >= tmax) return false; if (t > tmin) tmin = t; } } else if ((dirFlags & DirFlags.NegativeZ) != 0) { { double t = (box.Min.Z - Ray.Origin.Z) * InvDir.Z; if (t <= tmin) return false; if (t < tmax) tmax = t; } { double t = (box.Max.Z - Ray.Origin.Z) * InvDir.Z; if (t >= tmax) return false; if (t > tmin) tmin = t; } } else // ray parallel to Z-plane { if (Ray.Origin.Z < box.Min.Z || Ray.Origin.Z > box.Max.Z) return false; } if (tmin > tmax) return false; return true; } /// <summary> /// This variant of the intersection method only tests with the /// faces of the box indicated by the supplied boxFlags. /// </summary> public bool Intersects( Box3d box, Box.Flags boxFlags, ref double tmin, ref double tmax ) { var dirFlags = DirFlags; if ((dirFlags & DirFlags.PositiveX) != 0) { if ((boxFlags & Box.Flags.MaxX) != 0) { double t = (box.Max.X - Ray.Origin.X) * InvDir.X; if (t <= tmin) return false; if (t < tmax) tmax = t; } if ((boxFlags & Box.Flags.MinX) != 0) { double t = (box.Min.X - Ray.Origin.X) * InvDir.X; if (t >= tmax) return false; if (t > tmin) tmin = t; } } else if ((dirFlags & DirFlags.NegativeX) != 0) { if ((boxFlags & Box.Flags.MinX) != 0) { double t = (box.Min.X - Ray.Origin.X) * InvDir.X; if (t <= tmin) return false; if (t < tmax) tmax = t; } if ((boxFlags & Box.Flags.MaxX) != 0) { double t = (box.Max.X - Ray.Origin.X) * InvDir.X; if (t >= tmax) return false; if (t > tmin) tmin = t; } } else // ray parallel to X-plane { if ((boxFlags & Box.Flags.MinX) != 0 && (Ray.Origin.X < box.Min.X) || (boxFlags & Box.Flags.MaxX) != 0 && (Ray.Origin.X > box.Max.X)) return false; } if ((dirFlags & DirFlags.PositiveY) != 0) { if ((boxFlags & Box.Flags.MaxY) != 0) { double t = (box.Max.Y - Ray.Origin.Y) * InvDir.Y; if (t <= tmin) return false; if (t < tmax) tmax = t; } if ((boxFlags & Box.Flags.MinY) != 0) { double t = (box.Min.Y - Ray.Origin.Y) * InvDir.Y; if (t >= tmax) return false; if (t > tmin) tmin = t; } } else if ((dirFlags & DirFlags.NegativeY) != 0) { if ((boxFlags & Box.Flags.MinY) != 0) { double t = (box.Min.Y - Ray.Origin.Y) * InvDir.Y; if (t <= tmin) return false; if (t < tmax) tmax = t; } if ((boxFlags & Box.Flags.MaxY) != 0) { double t = (box.Max.Y - Ray.Origin.Y) * InvDir.Y; if (t >= tmax) return false; if (t > tmin) tmin = t; } } else // ray parallel to Y-plane { if ((boxFlags & Box.Flags.MinY) != 0 && (Ray.Origin.Y < box.Min.Y) || (boxFlags & Box.Flags.MaxY) != 0 && (Ray.Origin.Y > box.Max.Y)) return false; } if ((dirFlags & DirFlags.PositiveZ) != 0) { if ((boxFlags & Box.Flags.MaxZ) != 0) { double t = (box.Max.Z - Ray.Origin.Z) * InvDir.Z; if (t <= tmin) return false; if (t < tmax) tmax = t; } if ((boxFlags & Box.Flags.MinZ) != 0) { double t = (box.Min.Z - Ray.Origin.Z) * InvDir.Z; if (t >= tmax) return false; if (t > tmin) tmin = t; } } else if ((dirFlags & DirFlags.NegativeZ) != 0) { if ((boxFlags & Box.Flags.MinZ) != 0) { double t = (box.Min.Z - Ray.Origin.Z) * InvDir.Z; if (t <= tmin) return false; if (t < tmax) tmax = t; } if ((boxFlags & Box.Flags.MaxZ) != 0) { double t = (box.Max.Z - Ray.Origin.Z) * InvDir.Z; if (t >= tmax) return false; if (t > tmin) tmin = t; } } else // ray parallel to Z-plane { if ((boxFlags & Box.Flags.MinZ) != 0 && (Ray.Origin.Z < box.Min.Z) || (boxFlags & Box.Flags.MaxZ) != 0 && (Ray.Origin.Z > box.Max.Z)) return false; } if (tmin > tmax) return false; return true; } /// <summary> /// This variant of the intersection method returns the affected /// planes of the box if the box was hit. /// </summary> public bool Intersects( Box3d box, ref double tmin, ref double tmax, out Box.Flags tminFlags, out Box.Flags tmaxFlags ) { var dirFlags = DirFlags; tminFlags = Box.Flags.None; tmaxFlags = Box.Flags.None; if ((dirFlags & DirFlags.PositiveX) != 0) { { double t = (box.Max.X - Ray.Origin.X) * InvDir.X; if (t <= tmin) return false; if (t < tmax) { tmax = t; tmaxFlags = Box.Flags.MaxX; } } { double t = (box.Min.X - Ray.Origin.X) * InvDir.X; if (t >= tmax) return false; if (t > tmin) { tmin = t; tminFlags = Box.Flags.MinX; } } } else if ((dirFlags & DirFlags.NegativeX) != 0) { { double t = (box.Min.X - Ray.Origin.X) * InvDir.X; if (t <= tmin) return false; if (t < tmax) { tmax = t; tmaxFlags = Box.Flags.MinX; } } { double t = (box.Max.X - Ray.Origin.X) * InvDir.X; if (t >= tmax) return false; if (t > tmin) { tmin = t; tminFlags = Box.Flags.MaxX; } } } else // ray parallel to X-plane { if (Ray.Origin.X < box.Min.X || Ray.Origin.X > box.Max.X) return false; } if ((dirFlags & DirFlags.PositiveY) != 0) { { double t = (box.Max.Y - Ray.Origin.Y) * InvDir.Y; if (t <= tmin) return false; if (t < tmax) { tmax = t; tmaxFlags = Box.Flags.MaxY; } } { double t = (box.Min.Y - Ray.Origin.Y) * InvDir.Y; if (t >= tmax) return false; if (t > tmin) { tmin = t; tminFlags = Box.Flags.MinY; } } } else if ((dirFlags & DirFlags.NegativeY) != 0) { { double t = (box.Min.Y - Ray.Origin.Y) * InvDir.Y; if (t <= tmin) return false; if (t < tmax) { tmax = t; tmaxFlags = Box.Flags.MinY; } } { double t = (box.Max.Y - Ray.Origin.Y) * InvDir.Y; if (t >= tmax) return false; if (t > tmin) { tmin = t; tminFlags = Box.Flags.MaxY; } } } else // ray parallel to Y-plane { if (Ray.Origin.Y < box.Min.Y || Ray.Origin.Y > box.Max.Y) return false; } if ((dirFlags & DirFlags.PositiveZ) != 0) { { double t = (box.Max.Z - Ray.Origin.Z) * InvDir.Z; if (t <= tmin) return false; if (t < tmax) { tmax = t; tmaxFlags = Box.Flags.MaxZ; } } { double t = (box.Min.Z - Ray.Origin.Z) * InvDir.Z; if (t >= tmax) return false; if (t > tmin) { tmin = t; tminFlags = Box.Flags.MinZ; } } } else if ((dirFlags & DirFlags.NegativeZ) != 0) { { double t = (box.Min.Z - Ray.Origin.Z) * InvDir.Z; if (t <= tmin) return false; if (t < tmax) { tmax = t; tmaxFlags = Box.Flags.MinZ; } } { double t = (box.Max.Z - Ray.Origin.Z) * InvDir.Z; if (t >= tmax) return false; if (t > tmin) { tmin = t; tminFlags = Box.Flags.MaxZ; } } } else // ray parallel to Z-plane { if (Ray.Origin.Z < box.Min.Z || Ray.Origin.Z > box.Max.Z) return false; } if (tmin > tmax) return false; return true; } /// <summary> /// This variant of the intersection method only tests with the /// faces of the box indicated by the supplied boxFlags and /// returns the affected planes of the box if the box was hit. /// </summary> public bool Intersects( Box3d box, Box.Flags boxFlags, ref double tmin, ref double tmax, out Box.Flags tminFlags, out Box.Flags tmaxFlags ) { var dirFlags = DirFlags; tminFlags = Box.Flags.None; tmaxFlags = Box.Flags.None; if ((dirFlags & DirFlags.PositiveX) != 0) { if ((boxFlags & Box.Flags.MaxX) != 0) { double t = (box.Max.X - Ray.Origin.X) * InvDir.X; if (t <= tmin) return false; if (t < tmax) { tmax = t; tmaxFlags = Box.Flags.MaxX; } } if ((boxFlags & Box.Flags.MinX) != 0) { double t = (box.Min.X - Ray.Origin.X) * InvDir.X; if (t >= tmax) return false; if (t > tmin) { tmin = t; tminFlags = Box.Flags.MinX; } } } else if ((dirFlags & DirFlags.NegativeX) != 0) { if ((boxFlags & Box.Flags.MinX) != 0) { double t = (box.Min.X - Ray.Origin.X) * InvDir.X; if (t <= tmin) return false; if (t < tmax) { tmax = t; tmaxFlags = Box.Flags.MinX; } } if ((boxFlags & Box.Flags.MaxX) != 0) { double t = (box.Max.X - Ray.Origin.X) * InvDir.X; if (t >= tmax) return false; if (t > tmin) { tmin = t; tminFlags = Box.Flags.MaxX; } } } else // ray parallel to X-plane { if ((boxFlags & Box.Flags.MinX) != 0 && (Ray.Origin.X < box.Min.X) || (boxFlags & Box.Flags.MaxX) != 0 && (Ray.Origin.X > box.Max.X)) return false; } if ((dirFlags & DirFlags.PositiveY) != 0) { if ((boxFlags & Box.Flags.MaxY) != 0) { double t = (box.Max.Y - Ray.Origin.Y) * InvDir.Y; if (t <= tmin) return false; if (t < tmax) { tmax = t; tmaxFlags = Box.Flags.MaxY; } } if ((boxFlags & Box.Flags.MinY) != 0) { double t = (box.Min.Y - Ray.Origin.Y) * InvDir.Y; if (t >= tmax) return false; if (t > tmin) { tmin = t; tminFlags = Box.Flags.MinY; } } } else if ((dirFlags & DirFlags.NegativeY) != 0) { if ((boxFlags & Box.Flags.MinY) != 0) { double t = (box.Min.Y - Ray.Origin.Y) * InvDir.Y; if (t <= tmin) return false; if (t < tmax) { tmax = t; tmaxFlags = Box.Flags.MinY; } } if ((boxFlags & Box.Flags.MaxY) != 0) { double t = (box.Max.Y - Ray.Origin.Y) * InvDir.Y; if (t >= tmax) return false; if (t > tmin) { tmin = t; tminFlags = Box.Flags.MaxY; } } } else // ray parallel to Y-plane { if ((boxFlags & Box.Flags.MinY) != 0 && (Ray.Origin.Y < box.Min.Y) || (boxFlags & Box.Flags.MaxY) != 0 && (Ray.Origin.Y > box.Max.Y)) return false; } if ((dirFlags & DirFlags.PositiveZ) != 0) { if ((boxFlags & Box.Flags.MaxZ) != 0) { double t = (box.Max.Z - Ray.Origin.Z) * InvDir.Z; if (t <= tmin) return false; if (t < tmax) { tmax = t; tmaxFlags = Box.Flags.MaxZ; } } if ((boxFlags & Box.Flags.MinZ) != 0) { double t = (box.Min.Z - Ray.Origin.Z) * InvDir.Z; if (t >= tmax) return false; if (t > tmin) { tmin = t; tminFlags = Box.Flags.MinZ; } } } else if ((dirFlags & DirFlags.NegativeZ) != 0) { if ((boxFlags & Box.Flags.MinZ) != 0) { double t = (box.Min.Z - Ray.Origin.Z) * InvDir.Z; if (t <= tmin) return false; if (t < tmax) { tmax = t; tmaxFlags = Box.Flags.MinZ; } } if ((boxFlags & Box.Flags.MaxZ) != 0) { double t = (box.Max.Z - Ray.Origin.Z) * InvDir.Z; if (t >= tmax) return false; if (t > tmin) { tmin = t; tminFlags = Box.Flags.MaxZ; } } } else // ray parallel to Z-plane { if ((boxFlags & Box.Flags.MinZ) != 0 && (Ray.Origin.Z < box.Min.Z) || (boxFlags & Box.Flags.MaxZ) != 0 && (Ray.Origin.Z > box.Max.Z)) return false; } if (tmin > tmax) return false; return true; } #endregion } }
using System.Collections.Generic; using MicroComGenerator.Ast; namespace MicroComGenerator { public class AstParser { public static AstIdlNode Parse(string source) { var parser = new TokenParser(source); var idl = new AstIdlNode { Attributes = ParseGlobalAttributes(ref parser) }; while (!parser.Eof) { var attrs = ParseLocalAttributes(ref parser); if (parser.TryParseKeyword("enum")) idl.Enums.Add(ParseEnum(attrs, ref parser)); else if (parser.TryParseKeyword("struct")) idl.Structs.Add(ParseStruct(attrs, ref parser)); else if (parser.TryParseKeyword("interface")) idl.Interfaces.Add(ParseInterface(attrs, ref parser)); else throw new ParseException("Unexpected character", ref parser); } return idl; } static AstAttributes ParseGlobalAttributes(ref TokenParser parser) { var rv = new AstAttributes(); while (!parser.Eof) { parser.SkipWhitespace(); if (parser.TryConsume('@')) { var ident = parser.ParseIdentifier("-"); var value = parser.ReadToEol().Trim(); if (value == "@@") { parser.Advance(1); value = ""; while (true) { var l = parser.ReadToEol(); if (l == "@@") break; else value = value.Length == 0 ? l : (value + "\n" + l); parser.Advance(1); } } rv.Add(new AstAttributeNode(ident, value)); } else return rv; } return rv; } static AstAttributes ParseLocalAttributes(ref TokenParser parser) { var rv = new AstAttributes(); if (parser.TryConsume("[")) { while (!parser.TryConsume("]") && !parser.Eof) { if (parser.TryConsume(',')) continue; // Get identifier var ident = parser.ParseIdentifier("-"); // No value, end of attribute list if (parser.TryConsume(']')) { rv.Add(new AstAttributeNode(ident, null)); return rv; } // No value, next attribute else if (parser.TryConsume(',')) rv.Add(new AstAttributeNode(ident, null)); // Has value else if (parser.TryConsume('(')) { var value = parser.ReadTo(')'); parser.Consume(')'); rv.Add(new AstAttributeNode(ident, value)); } else throw new ParseException("Unexpected character", ref parser); } if (parser.Eof) throw new ParseException("Unexpected EOF", ref parser); } return rv; } static void EnsureOpenBracket(ref TokenParser parser) { if (!parser.TryConsume('{')) throw new ParseException("{ expected", ref parser); } static AstEnumNode ParseEnum(AstAttributes attrs, ref TokenParser parser) { var name = parser.ParseIdentifier(); EnsureOpenBracket(ref parser); var rv = new AstEnumNode { Name = name, Attributes = attrs }; while (!parser.TryConsume('}') && !parser.Eof) { if (parser.TryConsume(',')) continue; var ident = parser.ParseIdentifier(); // Automatic value if (parser.TryConsume(',') || parser.Peek == '}') { rv.Add(new AstEnumMemberNode(ident, null)); continue; } if (!parser.TryConsume('=')) throw new ParseException("Unexpected character", ref parser); var value = parser.ReadToAny(",}").Trim(); rv.Add(new AstEnumMemberNode(ident, value)); if (parser.Eof) throw new ParseException("Unexpected EOF", ref parser); } return rv; } static AstTypeNode ParseType(ref TokenParser parser) { var ident = parser.ParseIdentifier(); var t = new AstTypeNode { Name = ident }; while (parser.TryConsume('*')) t.PointerLevel++; if (parser.TryConsume("&")) t.IsLink = true; return t; } static AstStructNode ParseStruct(AstAttributes attrs, ref TokenParser parser) { var name = parser.ParseIdentifier(); EnsureOpenBracket(ref parser); var rv = new AstStructNode { Name = name, Attributes = attrs }; while (!parser.TryConsume('}') && !parser.Eof) { var memberAttrs = ParseLocalAttributes(ref parser); var t = ParseType(ref parser); bool parsedAtLeastOneMember = false; while (!parser.TryConsume(';')) { // Skip any , while (parser.TryConsume(',')) { } var ident = parser.ParseIdentifier(); parsedAtLeastOneMember = true; rv.Add(new AstStructMemberNode { Name = ident, Type = t, Attributes = memberAttrs}); } if (!parsedAtLeastOneMember) throw new ParseException("Expected at least one enum member with declared type " + t, ref parser); } return rv; } static AstInterfaceNode ParseInterface(AstAttributes interfaceAttrs, ref TokenParser parser) { var interfaceName = parser.ParseIdentifier(); string inheritsFrom = null; if (parser.TryConsume(":")) inheritsFrom = parser.ParseIdentifier(); EnsureOpenBracket(ref parser); var rv = new AstInterfaceNode { Name = interfaceName, Attributes = interfaceAttrs, Inherits = inheritsFrom }; while (!parser.TryConsume('}') && !parser.Eof) { var memberAttrs = ParseLocalAttributes(ref parser); var returnType = ParseType(ref parser); var name = parser.ParseIdentifier(); var member = new AstInterfaceMemberNode { Name = name, ReturnType = returnType, Attributes = memberAttrs }; rv.Add(member); parser.Consume('('); while (true) { if (parser.TryConsume(')')) break; var argumentAttrs = ParseLocalAttributes(ref parser); var type = ParseType(ref parser); var argName = parser.ParseIdentifier(); member.Add(new AstInterfaceMemberArgumentNode { Name = argName, Type = type, Attributes = argumentAttrs }); if (parser.TryConsume(')')) break; if (parser.TryConsume(',')) continue; throw new ParseException("Unexpected character", ref parser); } parser.Consume(';'); } return rv; } } }
// 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; using System.ComponentModel.Composition.Factories; using System.ComponentModel.Composition.Hosting; using System.Linq; using System.Reflection; using System.UnitTesting; using Xunit; namespace Tests.Integration { public class LifetimeTests { [Export] public class AnyPartSimple { } [Export] public class AnyPartDisposable : IDisposable { public bool IsDisposed { get; set; } public void Dispose() { Assert.False(IsDisposed); IsDisposed = true; } } [Export] public class AnyPartRecomposable { [Import("Value", AllowRecomposition = true)] public int Value { get; set; } } [Export] public class AnyPartDisposableRecomposable : IDisposable { [Import("Value", AllowRecomposition = true)] public int Value { get; set; } public bool IsDisposed { get; set; } public void Dispose() { Assert.False(IsDisposed); IsDisposed = true; } } [Fact] public void PartAddedViaAddExportedValue_ShouldNotBeDisposedWithContainer() { var container = new CompositionContainer(); var disposablePart = new AnyPartDisposable(); var batch = new CompositionBatch(); batch.AddPart(batch); container.Compose(batch); container.Dispose(); Assert.False(disposablePart.IsDisposed); } [Fact] public void PartAddedTwice_AppearsTwice() { // You probably shouldn't be adding a part to the container twice, but it's not something we're going to check for and throw an exception on var container = new CompositionContainer(); var disposable = new AnyPartDisposable(); var part = AttributedModelServices.CreatePart(disposable); var batch = new CompositionBatch(); batch.AddPart(part); container.Compose(batch); batch = new CompositionBatch(); batch.AddPart(part); container.Compose(batch); var exports = container.GetExports<AnyPartDisposable>(); Assert.Equal(2, exports.Count()); container.Dispose(); } [Fact] public void AnyPart_Simple_ShouldNotBeCollected() { var catalog = new TypeCatalog(typeof(AnyPartSimple)); var container = new CompositionContainer(catalog); var refTracker = new ReferenceTracker(); refTracker.AddReferencesNotExpectedToBeCollected( container.GetExportedValue<AnyPartSimple>()); refTracker.CollectAndAssert(); GC.KeepAlive(container); } [Fact] public void AnyPart_Disposable_ShouldNotBeCollected() { var catalog = new TypeCatalog(typeof(AnyPartDisposable)); var container = new CompositionContainer(catalog); var refTracker = new ReferenceTracker(); refTracker.AddReferencesNotExpectedToBeCollected( container.GetExportedValue<AnyPartDisposable>()); GC.KeepAlive(container); } [Fact] public void AnyPart_Disposable_ShouldBeDisposedWithContainer() { var catalog = new TypeCatalog(typeof(AnyPartDisposable)); var container = new CompositionContainer(catalog); var exportedValue = container.GetExportedValue<AnyPartDisposable>(); Assert.False(exportedValue.IsDisposed); container.Dispose(); Assert.True(exportedValue.IsDisposed, "AnyPart should be disposed with the container!"); } [Fact] public void AnyPart_RecomposabeImport_ShouldNotBeCollected() { var catalog = new TypeCatalog(typeof(AnyPartRecomposable)); var container = new CompositionContainer(catalog); // Setup dependency CompositionBatch batch = new CompositionBatch(); var valueKey = batch.AddExportedValue("Value", 21); container.Compose(batch); batch = null; var refTracker = new ReferenceTracker(); refTracker.AddReferencesNotExpectedToBeCollected( container.GetExportedValue<AnyPartRecomposable>()); refTracker.CollectAndAssert(); // Lets make sure recomposition doesn't blow anything up here. batch = new CompositionBatch(); batch.RemovePart(valueKey); batch.AddExportedValue("Value", 42); container.Compose(batch); batch = null; var exportedValue = (AnyPartRecomposable)refTracker.ReferencesNotExpectedToBeCollected[0].Target; Assert.Equal(42, exportedValue.Value); GC.KeepAlive(container); } [Fact] public void AnyPart_DisposableRecomposabeImport_ShouldNotBeCollected() { var catalog = new TypeCatalog(typeof(AnyPartDisposableRecomposable)); var container = new CompositionContainer(catalog); // Setup dependency CompositionBatch batch = new CompositionBatch(); var valueKey = batch.AddExportedValue("Value", 21); container.Compose(batch); batch = null; var refTracker = new ReferenceTracker(); refTracker.AddReferencesNotExpectedToBeCollected( container.GetExportedValue<AnyPartDisposableRecomposable>()); refTracker.CollectAndAssert(); // Lets make sure recomposition doesn't blow anything up here. batch = new CompositionBatch(); batch.RemovePart(valueKey); batch.AddExportedValue("Value", 42); container.Compose(batch); batch = null; var exportedValue = (AnyPartDisposableRecomposable)refTracker.ReferencesNotExpectedToBeCollected[0].Target; Assert.Equal(42, exportedValue.Value); GC.KeepAlive(container); container.Dispose(); Assert.True(exportedValue.IsDisposed, "Any parts should be disposed with the container!"); } [Export] [PartCreationPolicy(CreationPolicy.Shared)] public class SharedPartSimple { } [Export] [PartCreationPolicy(CreationPolicy.Shared)] public class SharedPartDisposable : IDisposable { public bool IsDisposed { get; set; } public void Dispose() { Assert.False(IsDisposed); IsDisposed = true; } } [Export] [PartCreationPolicy(CreationPolicy.Shared)] public class SharedPartRecomposable { [Import("Value", AllowRecomposition = true)] public int Value { get; set; } } [Export] [PartCreationPolicy(CreationPolicy.Shared)] public class SharedPartDisposableRecomposable : IDisposable { [Import("Value", AllowRecomposition = true)] public int Value { get; set; } public bool IsDisposed { get; set; } public void Dispose() { Assert.False(IsDisposed); IsDisposed = true; } } [Fact] public void SharedPart_Simple_ShouldNotBeCollected() { var catalog = new TypeCatalog(typeof(SharedPartSimple)); var container = new CompositionContainer(catalog); var refTracker = new ReferenceTracker(); refTracker.AddReferencesNotExpectedToBeCollected( container.GetExportedValue<SharedPartSimple>()); refTracker.CollectAndAssert(); GC.KeepAlive(container); } [Fact] public void SharedPart_Disposable_ShouldNotBeCollected() { var catalog = new TypeCatalog(typeof(SharedPartDisposable)); var container = new CompositionContainer(catalog); var refTracker = new ReferenceTracker(); refTracker.AddReferencesNotExpectedToBeCollected( container.GetExportedValue<SharedPartDisposable>()); refTracker.CollectAndAssert(); GC.KeepAlive(container); } [Fact] public void SharedPart_Disposable_ShouldBeDisposedWithContainer() { var catalog = new TypeCatalog(typeof(SharedPartDisposable)); var container = new CompositionContainer(catalog); var export = container.GetExportedValue<SharedPartDisposable>(); Assert.False(export.IsDisposed); container.Dispose(); Assert.True(export.IsDisposed, "SharedPart should be disposed with the container!"); } [Fact] public void SharedPart_RecomposabeImport_ShouldNotBeCollected() { var catalog = new TypeCatalog(typeof(SharedPartRecomposable)); var container = new CompositionContainer(catalog); // Setup dependency CompositionBatch batch = new CompositionBatch(); var valueKey = batch.AddExportedValue("Value", 21); container.Compose(batch); batch = null; var refTracker = new ReferenceTracker(); refTracker.AddReferencesNotExpectedToBeCollected( container.GetExportedValue<SharedPartRecomposable>()); refTracker.CollectAndAssert(); // Lets make sure recomposition doesn't blow anything up here. batch = new CompositionBatch(); batch.RemovePart(valueKey); batch.AddExportedValue("Value", 42); container.Compose(batch); batch = null; var exportedValue = (SharedPartRecomposable)refTracker.ReferencesNotExpectedToBeCollected[0].Target; Assert.Equal(42, exportedValue.Value); GC.KeepAlive(container); } [Fact] public void SharedPart_DisposableRecomposabeImport_ShouldNotBeCollected() { var catalog = new TypeCatalog(typeof(SharedPartDisposableRecomposable)); var container = new CompositionContainer(catalog); // Setup dependency CompositionBatch batch = new CompositionBatch(); var valueKey = batch.AddExportedValue("Value", 21); container.Compose(batch); batch = null; var refTracker = new ReferenceTracker(); refTracker.AddReferencesNotExpectedToBeCollected( container.GetExportedValue<SharedPartDisposableRecomposable>()); refTracker.CollectAndAssert(); // Lets make sure recomposition doesn't blow anything up here. batch = new CompositionBatch(); batch.RemovePart(valueKey); batch.AddExportedValue("Value", 42); container.Compose(batch); batch = null; var exportedValue = (SharedPartDisposableRecomposable)refTracker.ReferencesNotExpectedToBeCollected[0].Target; Assert.Equal(42, exportedValue.Value); container.Dispose(); Assert.True(exportedValue.IsDisposed, "Any parts should be disposed with the container!"); } [Export] [PartCreationPolicy(CreationPolicy.NonShared)] public class NonSharedPartSimple { } [Export] [PartCreationPolicy(CreationPolicy.NonShared)] public class NonSharedPartRecomposable { [Import("Value", AllowRecomposition = true)] public int Value { get; set; } } [Export] [PartCreationPolicy(CreationPolicy.NonShared)] public class NonSharedPartDisposable : IDisposable { public bool IsDisposed { get; set; } public void Dispose() { Assert.False(IsDisposed); IsDisposed = true; } } [Export] [PartCreationPolicy(CreationPolicy.NonShared)] public class NonSharedPartDisposableRecomposable : IDisposable { private int _value; [Import("Value", AllowRecomposition = true)] public int Value { get { if (this.IsDisposed) throw new ObjectDisposedException(this.GetType().Name); return this._value; } set { if (this.IsDisposed) throw new ObjectDisposedException(this.GetType().Name); this._value = value; } } public bool IsDisposed { get; set; } public void Dispose() { Assert.False(IsDisposed); IsDisposed = true; } } [Fact] public void NonSharedPart_Disposable_ShouldNotBeCollected() { var catalog = new TypeCatalog(typeof(NonSharedPartDisposable)); var container = new CompositionContainer(catalog); var refTracker = new ReferenceTracker(); refTracker.AddReferencesNotExpectedToBeCollected( container.GetExportedValue<NonSharedPartDisposable>()); refTracker.CollectAndAssert(); GC.KeepAlive(container); } [Fact] public void NonSharedPart_Disposable_ShouldBeDisposedWithContainer() { var catalog = new TypeCatalog(typeof(NonSharedPartDisposable)); var container = new CompositionContainer(catalog); var export = container.GetExportedValue<NonSharedPartDisposable>(); Assert.False(export.IsDisposed); container.Dispose(); Assert.True(export.IsDisposed, "NonSharedParts should be disposed with the container!"); } [Fact] public void NonSharedPart_RecomposableImport_WithReference_ShouldNotBeCollected() { var catalog = new TypeCatalog(typeof(NonSharedPartRecomposable)); var container = new CompositionContainer(catalog); // Setup dependency CompositionBatch batch = new CompositionBatch(); var valueKey = batch.AddExportedValue("Value", 21); container.Compose(batch); batch = null; var exportedValue = container.GetExportedValue<NonSharedPartRecomposable>(); var refTracker = new ReferenceTracker(); refTracker.AddReferencesNotExpectedToBeCollected(exportedValue); refTracker.CollectAndAssert(); // Recompose should work because we are still holding a reference to the exported value. batch = new CompositionBatch(); batch.RemovePart(valueKey); batch.AddExportedValue("Value", 42); container.Compose(batch); batch = null; Assert.Equal(42, exportedValue.Value); GC.KeepAlive(container); } [Fact] public void NonSharedPart_DisposableRecomposabeImport_NoReference_ShouldNotBeCollected() { var catalog = new TypeCatalog(typeof(NonSharedPartDisposableRecomposable)); var container = new CompositionContainer(catalog); // Setup dependency CompositionBatch batch = new CompositionBatch(); var valueKey = batch.AddExportedValue("Value", 21); container.Compose(batch); batch = null; var refTracker = new ReferenceTracker(); refTracker.AddReferencesNotExpectedToBeCollected( container.GetExportedValue<NonSharedPartDisposableRecomposable>()); refTracker.CollectAndAssert(); // Recompose just to ensure we don't blow up, even though we don't expect anything to happen. batch = new CompositionBatch(); batch.RemovePart(valueKey); batch.AddExportedValue("Value", 42); container.Compose(batch); batch = null; var exportedValue = (NonSharedPartDisposableRecomposable)refTracker.ReferencesNotExpectedToBeCollected[0].Target; Assert.Equal(42, exportedValue.Value); GC.KeepAlive(container); } [Export] public class SharedState { public static int instanceNumber = 0; public SharedState() { MyInstanceNumber = instanceNumber++; } public int MyInstanceNumber { get; private set; } } [PartCreationPolicy(CreationPolicy.NonShared)] public class NonSharedState { [Import(AllowRecomposition = true)] public SharedState State { set { ExportState = value; } } [Export("SharedFromNonShared")] public SharedState ExportState { get; private set; } } [Fact] public void NonSharedPart_TwoRecomposablePartsSameExportedValue() { // This test is primarily used to ensure that we allow for multiple parts to be associated // with the same exported value. var catalog = new TypeCatalog(typeof(SharedState), typeof(NonSharedState)); var container = new CompositionContainer(catalog); var export1 = container.GetExportedValue<SharedState>("SharedFromNonShared"); var export2 = container.GetExportedValue<SharedState>("SharedFromNonShared"); // Same exported value that comes from two different recomposable part instances. Assert.Equal(export1.MyInstanceNumber, export2.MyInstanceNumber); } [Export] [PartCreationPolicy(CreationPolicy.NonShared)] public class SharedImporter { [Import(RequiredCreationPolicy = CreationPolicy.Shared)] public AnyPartSimple AnyPartSimple { get; set; } [Import(RequiredCreationPolicy = CreationPolicy.Shared)] public AnyPartDisposable AnyPartDisposable { get; set; } [Import(RequiredCreationPolicy = CreationPolicy.Shared)] public AnyPartRecomposable AnyPartRecomposable { get; set; } [Import(RequiredCreationPolicy = CreationPolicy.Shared)] public AnyPartDisposableRecomposable AnyPartDisposableRecomposable { get; set; } } [Export] [PartCreationPolicy(CreationPolicy.NonShared)] public class NonSharedImporter { [Import(RequiredCreationPolicy = CreationPolicy.NonShared)] public AnyPartSimple AnyPartSimple { get; set; } [Import(RequiredCreationPolicy = CreationPolicy.NonShared)] public AnyPartDisposable AnyPartDisposable { get; set; } [Import(RequiredCreationPolicy = CreationPolicy.NonShared)] public AnyPartRecomposable AnyPartRecomposable { get; set; } [Import(RequiredCreationPolicy = CreationPolicy.NonShared)] public AnyPartDisposableRecomposable AnyPartDisposableRecomposable { get; set; } } private static CompositionContainer GetContainer() { var container = ContainerFactory.CreateWithAttributedCatalog( typeof(LifetimeTests).GetNestedTypes(BindingFlags.Public)); CompositionBatch batch = new CompositionBatch(); batch.AddExportedValue("Value", 21); container.Compose(batch); return container; } [Fact] public void GetReleaseExport_SharedRoot_ShouldNotDisposeChain() { var container = GetContainer(); var export = container.GetExport<SharedImporter, IDictionary<string, object>>(); var exportedValue = export.Value; container.ReleaseExport(export); Assert.False(exportedValue.AnyPartDisposable.IsDisposed); Assert.False(exportedValue.AnyPartDisposableRecomposable.IsDisposed); } [Fact] public void AddRemovePart_SharedRoot_ShouldNotDisposeChain() { var container = GetContainer(); var exportedValue = new SharedImporter(); CompositionBatch batch = new CompositionBatch(); var part = batch.AddPart(exportedValue); container.Compose(batch); batch = new CompositionBatch(); batch.RemovePart(part); container.Compose(batch); Assert.False(exportedValue.AnyPartDisposable.IsDisposed); Assert.False(exportedValue.AnyPartDisposableRecomposable.IsDisposed); } [Fact] public void ContainerDispose_SharedRoot_ShouldDisposeChain() { var container = GetContainer(); var export = container.GetExport<SharedImporter>(); var exportedValue = export.Value; container.Dispose(); Assert.True(exportedValue.AnyPartDisposable.IsDisposed); Assert.True(exportedValue.AnyPartDisposableRecomposable.IsDisposed); } [Fact] public void GetReleaseExport_NonSharedRoot_ShouldDisposeChain() { var container = GetContainer(); var exports = new List<Lazy<NonSharedImporter>>(); var exportedValues = new List<NonSharedImporter>(); // Executing this 100 times to help uncover any GC bugs for (int i = 0; i < 100; i++) { var export = container.GetExport<NonSharedImporter>(); var exportedValue = export.Value; exports.Add(export); exportedValues.Add(exportedValue); } for (int i = 0; i < 100; i++) { var export = exports[i]; var exportedValue = exportedValues[i]; container.ReleaseExport(export); Assert.True(exportedValue.AnyPartDisposable.IsDisposed); Assert.True(exportedValue.AnyPartDisposableRecomposable.IsDisposed); } } public void GetReleaseExport_NonSharedRoot_ShouldDisposeChain_WithMetadata() { var container = GetContainer(); var exports = new List<Lazy<NonSharedImporter, IDictionary<string, object>>>(); var exportedValues = new List<NonSharedImporter>(); // Executing this 100 times to help uncover any GC bugs for (int i = 0; i < 100; i++) { var export = container.GetExport<NonSharedImporter, IDictionary<string, object>>(); var exportedValue = export.Value; exports.Add(export); exportedValues.Add(exportedValue); } for (int i = 0; i < 100; i++) { var export = exports[i]; var exportedValue = exportedValues[i]; container.ReleaseExport(export); Assert.True(exportedValue.AnyPartDisposable.IsDisposed); Assert.True(exportedValue.AnyPartDisposableRecomposable.IsDisposed); } } [Fact] public void ReleaseExports_ShouldDispose_NonSharedParts() { var container = GetContainer(); var export1 = container.GetExport<NonSharedImporter>(); var exportedValue1 = export1.Value; var export2 = container.GetExport<NonSharedImporter>(); var exportedValue2 = export2.Value; container.ReleaseExports(new[] { export1, export2 }); Assert.True(exportedValue1.AnyPartDisposable.IsDisposed); Assert.True(exportedValue1.AnyPartDisposableRecomposable.IsDisposed); Assert.True(exportedValue2.AnyPartDisposable.IsDisposed); Assert.True(exportedValue2.AnyPartDisposableRecomposable.IsDisposed); } [Fact] public void AddRemovePart_NonSharedRoot_ShouldDisposeChain() { var container = GetContainer(); var exportedValue = new NonSharedImporter(); CompositionBatch batch = new CompositionBatch(); var part = batch.AddPart(exportedValue); container.Compose(batch); batch = new CompositionBatch(); batch.RemovePart(part); container.Compose(batch); Assert.True(exportedValue.AnyPartDisposable.IsDisposed); Assert.True(exportedValue.AnyPartDisposableRecomposable.IsDisposed); } [Fact] public void ContainerDispose_NonSharedRoot_ShouldNotDisposeChain() { var container = GetContainer(); var export = container.GetExport<NonSharedImporter>(); var exportedValue = export.Value; container.Dispose(); Assert.True(exportedValue.AnyPartDisposable.IsDisposed); Assert.True(exportedValue.AnyPartDisposableRecomposable.IsDisposed); } [Fact] public void GetReleaseExport_NonSharedPart_ShouldNotRecomposeAfterRelease() { var catalog = new TypeCatalog(typeof(NonSharedPartRecomposable)); var container = new CompositionContainer(catalog); // Setup dependency CompositionBatch batch = new CompositionBatch(); var valueKey = batch.AddExportedValue("Value", 21); container.Compose(batch); var export = container.GetExport<NonSharedPartRecomposable>(); var exportedValue = export.Value; Assert.Equal(21, exportedValue.Value); container.ReleaseExport(export); // Recompose just to ensure we don't blow up, even though we don't expect anything to happen. batch = new CompositionBatch(); batch.RemovePart(valueKey); batch.AddExportedValue("Value", 42); container.Compose(batch); Assert.Equal(21, exportedValue.Value); } [Fact] public void GetExportManualDisposeThenRecompose_NonSharedDisposableRecomposablePart_ShouldThrowComposition() { var catalog = new TypeCatalog(typeof(NonSharedPartDisposableRecomposable)); var container = new CompositionContainer(catalog); // Setup dependency CompositionBatch batch = new CompositionBatch(); var valueKey = batch.AddExportedValue("Value", 21); container.Compose(batch); var export = container.GetExport<NonSharedPartDisposableRecomposable>(); var exportedValue = export.Value; Assert.Equal(21, exportedValue.Value); exportedValue.Dispose(); // Recompose should cause a ObjectDisposedException. batch = new CompositionBatch(); batch.RemovePart(valueKey); batch.AddExportedValue("Value", 42); CompositionAssert.ThrowsError( ErrorId.ImportEngine_PartCannotActivate, // Cannot activate part because ErrorId.ReflectionModel_ImportThrewException, // Import threw an exception RetryMode.DoNotRetry, () => { container.Compose(batch); }); } [Export] public class MyImporter { [Import(AllowDefault = true, AllowRecomposition = true, RequiredCreationPolicy = CreationPolicy.NonShared)] public AnyPartDisposable AnyPartDisposable { get; set; } } [Fact] public void RecomposeCausesOldImportedValuesToBeDisposed() { var cat = new AggregateCatalog(); var cat1 = new TypeCatalog(typeof(AnyPartDisposable)); cat.Catalogs.Add(new TypeCatalog(typeof(MyImporter))); cat.Catalogs.Add(cat1); var container = new CompositionContainer(cat); var importer = container.GetExportedValue<MyImporter>(); var anyPart = importer.AnyPartDisposable; Assert.False(anyPart.IsDisposed); Assert.IsType<AnyPartDisposable>(anyPart); // Remove the instance of MyClass1 cat.Catalogs.Remove(cat1); Assert.Null(importer.AnyPartDisposable); Assert.True(anyPart.IsDisposed); } private static CompositionContainer CreateParentChildContainerWithNonSharedImporter() { var parentCat = CatalogFactory.CreateAttributed(typeof(AnyPartDisposable), typeof(AnyPartDisposableRecomposable), typeof(AnyPartRecomposable), typeof(AnyPartSimple)); var parent = new CompositionContainer(parentCat); CompositionBatch batch = new CompositionBatch(); batch.AddExportedValue("Value", 21); parent.Compose(batch); var childCat = CatalogFactory.CreateAttributed(typeof(NonSharedImporter)); var child = new CompositionContainer(childCat, parent); return child; } [Fact] public void ChildContainerGetReleaseExport_NonSharedRoot_ShouldDisposeChain() { var child = CreateParentChildContainerWithNonSharedImporter(); var export = child.GetExport<NonSharedImporter>(); var exportedValue = export.Value; child.ReleaseExport(export); Assert.True(exportedValue.AnyPartDisposable.IsDisposed); Assert.True(exportedValue.AnyPartDisposableRecomposable.IsDisposed); } [Fact] public void ChildContainerAddRemovePart_NonSharedRoot_ShouldDisposeChain() { var child = CreateParentChildContainerWithNonSharedImporter(); var exportedValue = new NonSharedImporter(); CompositionBatch batch = new CompositionBatch(); var part = batch.AddPart(exportedValue); child.Compose(batch); batch = new CompositionBatch(); batch.RemovePart(part); child.Compose(batch); Assert.True(exportedValue.AnyPartDisposable.IsDisposed); Assert.True(exportedValue.AnyPartDisposableRecomposable.IsDisposed); } [Fact] public void ChildContainerAddRemovePart_NonSharedRoot_ShouldNotDisposeChain() { var child = CreateParentChildContainerWithNonSharedImporter(); var exportedValue = child.GetExportedValue<NonSharedImporter>(); child.Dispose(); Assert.False(exportedValue.AnyPartDisposable.IsDisposed); Assert.False(exportedValue.AnyPartDisposableRecomposable.IsDisposed); } [Fact] [ActiveIssue(25498)] public void NonSharedPart_Simple_ShouldBeCollected() { var catalog = new TypeCatalog(typeof(NonSharedPartSimple)); var container = new CompositionContainer(catalog); var refTracker = new ReferenceTracker(); refTracker.AddReferencesExpectedToBeCollected( container.GetExportedValue<NonSharedPartSimple>()); refTracker.CollectAndAssert(); GC.KeepAlive(container); } [Fact] [ActiveIssue(25498)] public void ContainerDispose_SharedPart_ShouldCollectWholeObjectChain() { // Test only works properly with while using the real ConditionalWeakTable var container = GetContainer(); var export = container.GetExport<SharedImporter>(); var exportedValue = export.Value; container.Dispose(); var refTracker = new ReferenceTracker(); refTracker.AddReferencesExpectedToBeCollected( exportedValue, exportedValue.AnyPartDisposable, exportedValue.AnyPartDisposableRecomposable, exportedValue.AnyPartRecomposable, exportedValue.AnyPartSimple); export = null; exportedValue = null; refTracker.CollectAndAssert(); GC.KeepAlive(container); } [Fact] [ActiveIssue(25498)] public void AddRemovePart_SharedPart_ShouldCollectOnlyRoot() { var container = GetContainer(); var exportedValue = new SharedImporter(); CompositionBatch batch = new CompositionBatch(); var part = batch.AddPart(exportedValue); container.Compose(batch); batch = null; batch = new CompositionBatch(); batch.RemovePart(part); container.Compose(batch); batch = null; var refTracker = new ReferenceTracker(); refTracker.AddReferencesExpectedToBeCollected( exportedValue); refTracker.AddReferencesNotExpectedToBeCollected( exportedValue.AnyPartDisposable, exportedValue.AnyPartDisposableRecomposable, exportedValue.AnyPartRecomposable, exportedValue.AnyPartSimple); part = null; exportedValue = null; refTracker.CollectAndAssert(); GC.KeepAlive(container); } [Fact] [ActiveIssue(25498)] public void AddRemovePart_NonSharedPart_ShouldCollectWholeObjectChain() { var container = GetContainer(); var exportedValue = new NonSharedImporter(); CompositionBatch batch = new CompositionBatch(); var part = batch.AddPart(exportedValue); container.Compose(batch); batch = null; batch = new CompositionBatch(); batch.RemovePart(part); container.Compose(batch); batch = null; var refTracker = new ReferenceTracker(); refTracker.AddReferencesExpectedToBeCollected( exportedValue, exportedValue.AnyPartDisposable, exportedValue.AnyPartDisposableRecomposable, exportedValue.AnyPartRecomposable, exportedValue.AnyPartSimple); part = null; exportedValue = null; refTracker.CollectAndAssert(); GC.KeepAlive(container); } [Fact] [ActiveIssue(25498)] public void ContainerDispose_NonSharedPart_ShouldCollectWholeObjectChain() { // Test only works properly with while using the real ConditionalWeakTable var container = GetContainer(); var export = container.GetExport<NonSharedImporter>(); var exportedValue = export.Value; container.Dispose(); var refTracker = new ReferenceTracker(); refTracker.AddReferencesExpectedToBeCollected( exportedValue, exportedValue.AnyPartDisposable, exportedValue.AnyPartDisposableRecomposable, exportedValue.AnyPartRecomposable, exportedValue.AnyPartSimple); export = null; exportedValue = null; refTracker.CollectAndAssert(); GC.KeepAlive(container); } [Fact] [ActiveIssue(25498)] public void NonSharedImporter_ReleaseReference_ShouldCollectWholeChain() { var container = GetContainer(); var export = container.GetExport<NonSharedImporter>(); var exportedValue = export.Value; var refTracker = new ReferenceTracker(); // Non-Disposable references in the chain should be GC'ed refTracker.AddReferencesExpectedToBeCollected( exportedValue, exportedValue.AnyPartRecomposable, exportedValue.AnyPartSimple); // Disposable references in the chain should NOT be GC'ed refTracker.AddReferencesNotExpectedToBeCollected( exportedValue.AnyPartDisposable, exportedValue.AnyPartDisposableRecomposable); export = null; exportedValue = null; refTracker.CollectAndAssert(); GC.KeepAlive(container); } [Fact] [ActiveIssue(25498)] public void ChildContainerDispose_NonSharedPart_ShouldOnlyCleanupChildAndSimpleNonShared() { var child = CreateParentChildContainerWithNonSharedImporter(); var exportedValue = child.GetExportedValue<NonSharedImporter>(); child.Dispose(); var refTracker = new ReferenceTracker(); refTracker.AddReferencesExpectedToBeCollected( exportedValue, // object in child exportedValue.AnyPartSimple, // No reference parent so collected. exportedValue.AnyPartRecomposable); // These are in the parent and will not be cleaned out refTracker.AddReferencesNotExpectedToBeCollected( exportedValue.AnyPartDisposable, exportedValue.AnyPartDisposableRecomposable); exportedValue = null; refTracker.CollectAndAssert(); GC.KeepAlive(child); } [Fact] [ActiveIssue(25498)] public void ChildContainerGetReleaseExport_NonSharedPart_ShouldCollectWholeObjectChain() { var child = CreateParentChildContainerWithNonSharedImporter(); var export = child.GetExport<NonSharedImporter>(); var exportedValue = export.Value; child.ReleaseExport(export); var refTracker = new ReferenceTracker(); refTracker.AddReferencesExpectedToBeCollected( exportedValue, exportedValue.AnyPartDisposable, exportedValue.AnyPartDisposableRecomposable, exportedValue.AnyPartRecomposable, exportedValue.AnyPartSimple); export = null; exportedValue = null; refTracker.CollectAndAssert(); GC.KeepAlive(child); } [Fact] [ActiveIssue(25498)] public void NonSharedPart_RecomposableImport_NoReference_ShouldBeCollected() { var catalog = new TypeCatalog(typeof(NonSharedPartRecomposable)); var container = new CompositionContainer(catalog); // Setup dependency CompositionBatch batch = new CompositionBatch(); var valueKey = batch.AddExportedValue("Value", 21); container.Compose(batch); batch = null; var refTracker = new ReferenceTracker(); refTracker.AddReferencesExpectedToBeCollected( container.GetExportedValue<NonSharedPartRecomposable>()); refTracker.CollectAndAssert(); // Recompose just to ensure we don't blow up, even though we don't expect anything to happen. batch = new CompositionBatch(); batch.RemovePart(valueKey); batch.AddExportedValue("Value", 42); container.Compose(batch); batch = null; GC.KeepAlive(container); } [Fact] [ActiveIssue(25498)] public void ChildContainerAddRemovePart_NonSharedPart_ShouldCollectWholeObjectChain() { var child = CreateParentChildContainerWithNonSharedImporter(); var exportedValue = new NonSharedImporter(); CompositionBatch batch = new CompositionBatch(); var part = batch.AddPart(exportedValue); child.Compose(batch); batch = null; batch = new CompositionBatch(); batch.RemovePart(part); child.Compose(batch); batch = null; var refTracker = new ReferenceTracker(); refTracker.AddReferencesExpectedToBeCollected( exportedValue, exportedValue.AnyPartDisposable, exportedValue.AnyPartDisposableRecomposable, exportedValue.AnyPartRecomposable, exportedValue.AnyPartSimple); part = null; exportedValue = null; refTracker.CollectAndAssert(); GC.KeepAlive(child); } [Fact] [ActiveIssue(25498)] public void GetReleaseExport_SharedPart_ShouldCollectOnlyRoot() { var container = GetContainer(); var export = container.GetExport<SharedImporter>(); var exportedValue = export.Value; container.ReleaseExport(export); var refTracker = new ReferenceTracker(); refTracker.AddReferencesExpectedToBeCollected( exportedValue); refTracker.AddReferencesNotExpectedToBeCollected( exportedValue.AnyPartDisposable, exportedValue.AnyPartDisposableRecomposable, exportedValue.AnyPartRecomposable, exportedValue.AnyPartSimple); export = null; exportedValue = null; refTracker.CollectAndAssert(); GC.KeepAlive(container); } [Fact] [ActiveIssue(25498)] public void GetReleaseExport_NonSharedPart_ShouldCollectWholeObjectChain() { var container = GetContainer(); var export = container.GetExport<NonSharedImporter>(); var exportedValue = export.Value; container.ReleaseExport(export); var refTracker = new ReferenceTracker(); refTracker.AddReferencesExpectedToBeCollected( exportedValue, exportedValue.AnyPartDisposable, exportedValue.AnyPartDisposableRecomposable, exportedValue.AnyPartRecomposable, exportedValue.AnyPartSimple); export = null; exportedValue = null; refTracker.CollectAndAssert(); GC.KeepAlive(container); } [Fact] public void ReleaseExports_ShouldWorkWithExportCollection() { var container = GetContainer(); var exports = container.GetExports<NonSharedImporter>(); Assert.True(exports.Count() > 0); var exportedValues = exports.Select(export => export.Value).ToList(); container.ReleaseExports(exports); foreach (var obj in exportedValues) { Assert.True(obj.AnyPartDisposable.IsDisposed); Assert.True(obj.AnyPartDisposableRecomposable.IsDisposed); } } } }
// 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; using System; using System.Collections.Generic; using System.Security; // TPL namespaces using System.Threading; using System.Threading.Tasks; using System.Diagnostics; namespace System.Threading.Tasks.Tests { // // Task scheduler basics. // public static class TaskSchedulerTests { // Just ensure we eventually complete when many blocked tasks are created. [Fact] public static void RunBlockedInjectionTest() { Debug.WriteLine("* RunBlockedInjectionTest() -- if it deadlocks, it failed"); ManualResetEvent mre = new ManualResetEvent(false); // we need to run this test in a local task scheduler, because it needs to to perform // the verification based on a known number of initially available threads. // // // @TODO: When we reach the _planB branch we need to add a trick here using ThreadPool.SetMaxThread // to bring down the TP worker count. This is because previous activity in the test process might have // injected workers. TaskScheduler tm = TaskScheduler.Default; // Create many tasks blocked on the MRE. int processorCount = Environment.ProcessorCount; Task[] tasks = new Task[processorCount]; for (int i = 0; i < tasks.Length; i++) { tasks[i] = Task.Factory.StartNew(delegate { mre.WaitOne(); }, CancellationToken.None, TaskCreationOptions.None, tm); } // Create one task that signals the MRE, and wait for it. Task.Factory.StartNew(delegate { mre.Set(); }, CancellationToken.None, TaskCreationOptions.None, tm).Wait(); // Lastly, wait for the others to complete. Task.WaitAll(tasks); } [Fact] public static void RunBuggySchedulerTests() { Debug.WriteLine("* RunBuggySchedulerTests()"); BuggyTaskScheduler bts = new BuggyTaskScheduler(); Task t1 = new Task(delegate { }); Task t2 = new Task(delegate { }); // // Test Task.Start(buggy scheduler) // Debug.WriteLine(" -- testing Task.Start(buggy scheduler)"); try { t1.Start(bts); Assert.True(false, string.Format(" > FAILED. No exception thrown.")); } catch (TaskSchedulerException) { } catch (Exception e) { Assert.True(false, string.Format(" > FAILED. Wrong exception thrown (expected TaskSchedulerException): {0}", e)); } if (t1.Status != TaskStatus.Faulted) { Assert.True(false, string.Format(" > FAILED. Task ended up in wrong status (expected Faulted): {0}", t1.Status)); } Debug.WriteLine(" -- Waiting on Faulted task (there's a problem if we deadlock)..."); try { t1.Wait(); Assert.True(false, string.Format(" > FAILED. No exception thrown from Wait().")); } catch (AggregateException ae) { if (!(ae.InnerExceptions[0] is TaskSchedulerException)) { Assert.True(false, string.Format(" > FAILED. Wrong inner exception thrown from Wait(): {0}", ae.InnerExceptions[0].GetType().Name)); } } // // Test Task.RunSynchronously(buggy scheduler) // Debug.WriteLine(" -- testing Task.RunSynchronously(buggy scheduler)"); try { t2.RunSynchronously(bts); Assert.True(false, string.Format(" > FAILED. No exception thrown.")); } catch (TaskSchedulerException) { } catch (Exception e) { Assert.True(false, string.Format(" > FAILED. Wrong exception thrown (expected TaskSchedulerException): {0}", e)); } if (t2.Status != TaskStatus.Faulted) { Assert.True(false, string.Format(" > FAILED. Task ended up in wrong status (expected Faulted): {0}", t1.Status)); } Debug.WriteLine(" -- Waiting on Faulted task (there's a problem if we deadlock)..."); try { t2.Wait(); Assert.True(false, string.Format(" > FAILED. No exception thrown from Wait().")); } catch (AggregateException ae) { if (!(ae.InnerExceptions[0] is TaskSchedulerException)) { Assert.True(false, string.Format(" > FAILED. Wrong inner exception thrown from Wait(): {0}", ae.InnerExceptions[0].GetType().Name)); } } // // Test StartNew(buggy scheduler) // Debug.WriteLine(" -- testing Task.Factory.StartNew(buggy scheduler)"); try { Task t3 = Task.Factory.StartNew(delegate { }, CancellationToken.None, TaskCreationOptions.None, bts); Assert.True(false, string.Format(" > FAILED. No exception thrown.")); } catch (TaskSchedulerException) { } catch (Exception e) { Assert.True(false, string.Format(" > FAILED. Wrong exception thrown (expected TaskSchedulerException): {0}", e)); } // // Test continuations // Debug.WriteLine(" -- testing Task.ContinueWith(buggy scheduler)"); Task completedTask = Task.Factory.StartNew(delegate { }); completedTask.Wait(); Task tc1 = completedTask.ContinueWith(delegate { }, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, bts); Debug.WriteLine(" -- Waiting on Faulted task (there's a problem if we deadlock)..."); try { tc1.Wait(); Assert.True(false, string.Format(" > FAILED. No exception thrown (sync).")); } catch (AggregateException ae) { if (!(ae.InnerExceptions[0] is TaskSchedulerException)) { Assert.True(false, string.Format(" > FAILED. Wrong inner exception thrown from Wait() (sync): {0}", ae.InnerExceptions[0].GetType().Name)); } } catch (Exception e) { Assert.True(false, string.Format(" > FAILED. Wrong exception thrown (sync): {0}", e)); } Task tc2 = completedTask.ContinueWith(delegate { }, CancellationToken.None, TaskContinuationOptions.None, bts); Debug.WriteLine(" -- Waiting on Faulted task (there's a problem if we deadlock)..."); try { tc2.Wait(); Assert.True(false, string.Format(" > FAILED. No exception thrown (async).")); } catch (AggregateException ae) { if (!(ae.InnerExceptions[0] is TaskSchedulerException)) { Assert.True(false, string.Format(" > FAILED. Wrong inner exception thrown from Wait() (async): {0}", ae.InnerExceptions[0].GetType().Name)); } } catch (Exception e) { Assert.True(false, string.Format(" > FAILED. Wrong exception thrown (async): {0}", e)); } // Test Wait()/inlining Debug.WriteLine(" -- testing Task.Wait(task started on buggy scheduler)"); BuggyTaskScheduler bts2 = new BuggyTaskScheduler(false); // won't throw on QueueTask Task t4 = new Task(delegate { }); t4.Start(bts2); try { t4.Wait(); Assert.True(false, string.Format(" > FAILED. Expected inlining exception")); } catch (TaskSchedulerException) { } catch (Exception e) { Assert.True(false, string.Format(" > FAILED. Wrong exception thrown: {0}", e)); } } [Fact] [OuterLoop] public static void RunSynchronizationContextTaskSchedulerTests() { // Remember the current SynchronizationContext, so that we can restore it SynchronizationContext previousSC = SynchronizationContext.Current; // Now make up a "real" SynchronizationContext abd install it SimpleSynchronizationContext newSC = new SimpleSynchronizationContext(); SetSynchronizationContext(newSC); // Create a scheduler based on the current SC TaskScheduler scTS = TaskScheduler.FromCurrentSynchronizationContext(); // // Launch a Task on scTS, make sure that it is processed in the expected fashion // bool sideEffect = false; Task task = Task.Factory.StartNew(() => { sideEffect = true; }, CancellationToken.None, TaskCreationOptions.None, scTS); Exception ex = null; try { task.Wait(); } catch (Exception e) { ex = e; } Assert.True(task.IsCompleted, "Expected task to have completed"); Assert.True(ex == null, "Did not expect exception on Wait"); Assert.True(sideEffect, "Task appears not to have run"); Assert.True(newSC.PostCount == 1, "Expected exactly one post to underlying SynchronizationContext"); // // Run a Task synchronously on scTS, make sure that it completes // sideEffect = false; Task syncTask = new Task(() => { sideEffect = true; }); ex = null; try { syncTask.RunSynchronously(scTS); } catch (Exception e) { ex = e; } Assert.True(task.IsCompleted, "Expected task to have completed"); Assert.True(ex == null, "Did not expect exception on RunSynchronously"); Assert.True(sideEffect, "Task appears not to have run"); Assert.True(newSC.PostCount == 1, "Did not expect a new Post to underlying SynchronizationContext"); // // Miscellaneous things to test // Assert.True(scTS.MaximumConcurrencyLevel == 1, "Expected scTS.MaximumConcurrencyLevel to be 1"); // restore original SC SetSynchronizationContext(previousSC); } [Fact] public static void RunSynchronizationContextTaskSchedulerTests_Negative() { // Remember the current SynchronizationContext, so that we can restore it SynchronizationContext previousSC = SynchronizationContext.Current; // // Test exceptions on construction of SCTaskScheduler // SetSynchronizationContext(null); Assert.Throws<InvalidOperationException>( () => { TaskScheduler.FromCurrentSynchronizationContext(); }); } #region Helper Methods / Helper Classes // Buggy task scheduler to make sure that we handle QueueTask()/TryExecuteTaskInline() // exceptions correctly. Used in RunBuggySchedulerTests() below. [SecuritySafeCritical] public class BuggyTaskScheduler : TaskScheduler { private bool _faultQueues; [SecurityCritical] protected override void QueueTask(Task task) { if (_faultQueues) throw new InvalidOperationException("I don't queue tasks!"); // else do nothing -- still a pretty buggy scheduler!! } [SecurityCritical] protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued) { throw new ArgumentException("I am your worst nightmare!"); } [SecurityCritical] protected override IEnumerable<Task> GetScheduledTasks() { return null; } public BuggyTaskScheduler() : this(true) { } public BuggyTaskScheduler(bool faultQueues) { _faultQueues = faultQueues; } } private class SimpleSynchronizationContext : SynchronizationContext { private int _postCount = 0; public override void Post(SendOrPostCallback d, object state) { _postCount++; base.Post(d, state); } public int PostCount { get { return _postCount; } } } private static void SetSynchronizationContext(SynchronizationContext sc) { SynchronizationContext.SetSynchronizationContext(sc); } #endregion } }
#region Apache License // // 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. // #endregion using System; using System.Globalization; using System.Net; using System.Net.Sockets; using System.Text; using log4net.Layout; using log4net.Core; using log4net.Util; namespace log4net.Appender { /// <summary> /// Sends logging events as connectionless UDP datagrams to a remote host or a /// multicast group using an <see cref="UdpClient" />. /// </summary> /// <remarks> /// <para> /// UDP guarantees neither that messages arrive, nor that they arrive in the correct order. /// </para> /// <para> /// To view the logging results, a custom application can be developed that listens for logging /// events. /// </para> /// <para> /// When decoding events send via this appender remember to use the same encoding /// to decode the events as was used to send the events. See the <see cref="Encoding"/> /// property to specify the encoding to use. /// </para> /// </remarks> /// <example> /// This example shows how to log receive logging events that are sent /// on IP address 244.0.0.1 and port 8080 to the console. The event is /// encoded in the packet as a unicode string and it is decoded as such. /// <code lang="C#"> /// IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, 0); /// UdpClient udpClient; /// byte[] buffer; /// string loggingEvent; /// /// try /// { /// udpClient = new UdpClient(8080); /// /// while(true) /// { /// buffer = udpClient.Receive(ref remoteEndPoint); /// loggingEvent = System.Text.Encoding.Unicode.GetString(buffer); /// Console.WriteLine(loggingEvent); /// } /// } /// catch(Exception e) /// { /// Console.WriteLine(e.ToString()); /// } /// </code> /// <code lang="Visual Basic"> /// Dim remoteEndPoint as IPEndPoint /// Dim udpClient as UdpClient /// Dim buffer as Byte() /// Dim loggingEvent as String /// /// Try /// remoteEndPoint = new IPEndPoint(IPAddress.Any, 0) /// udpClient = new UdpClient(8080) /// /// While True /// buffer = udpClient.Receive(ByRef remoteEndPoint) /// loggingEvent = System.Text.Encoding.Unicode.GetString(buffer) /// Console.WriteLine(loggingEvent) /// Wend /// Catch e As Exception /// Console.WriteLine(e.ToString()) /// End Try /// </code> /// <para> /// An example configuration section to log information using this appender to the /// IP 224.0.0.1 on port 8080: /// </para> /// <code lang="XML" escaped="true"> /// <appender name="UdpAppender" type="log4net.Appender.UdpAppender"> /// <remoteAddress value="224.0.0.1" /> /// <remotePort value="8080" /> /// <layout type="log4net.Layout.PatternLayout" value="%-5level %logger [%ndc] - %message%newline" /> /// </appender> /// </code> /// </example> /// <author>Gert Driesen</author> /// <author>Nicko Cadell</author> public class UdpAppender : AppenderSkeleton { #region Public Instance Constructors /// <summary> /// Initializes a new instance of the <see cref="UdpAppender" /> class. /// </summary> /// <remarks> /// The default constructor initializes all fields to their default values. /// </remarks> public UdpAppender() { } #endregion Public Instance Constructors #region Public Instance Properties /// <summary> /// Gets or sets the IP address of the remote host or multicast group to which /// the underlying <see cref="UdpClient" /> should sent the logging event. /// </summary> /// <value> /// The IP address of the remote host or multicast group to which the logging event /// will be sent. /// </value> /// <remarks> /// <para> /// Multicast addresses are identified by IP class <b>D</b> addresses (in the range 224.0.0.0 to /// 239.255.255.255). Multicast packets can pass across different networks through routers, so /// it is possible to use multicasts in an Internet scenario as long as your network provider /// supports multicasting. /// </para> /// <para> /// Hosts that want to receive particular multicast messages must register their interest by joining /// the multicast group. Multicast messages are not sent to networks where no host has joined /// the multicast group. Class <b>D</b> IP addresses are used for multicast groups, to differentiate /// them from normal host addresses, allowing nodes to easily detect if a message is of interest. /// </para> /// <para> /// Static multicast addresses that are needed globally are assigned by IANA. A few examples are listed in the table below: /// </para> /// <para> /// <list type="table"> /// <listheader> /// <term>IP Address</term> /// <description>Description</description> /// </listheader> /// <item> /// <term>224.0.0.1</term> /// <description> /// <para> /// Sends a message to all system on the subnet. /// </para> /// </description> /// </item> /// <item> /// <term>224.0.0.2</term> /// <description> /// <para> /// Sends a message to all routers on the subnet. /// </para> /// </description> /// </item> /// <item> /// <term>224.0.0.12</term> /// <description> /// <para> /// The DHCP server answers messages on the IP address 224.0.0.12, but only on a subnet. /// </para> /// </description> /// </item> /// </list> /// </para> /// <para> /// A complete list of actually reserved multicast addresses and their owners in the ranges /// defined by RFC 3171 can be found at the <A href="http://www.iana.org/assignments/multicast-addresses">IANA web site</A>. /// </para> /// <para> /// The address range 239.0.0.0 to 239.255.255.255 is reserved for administrative scope-relative /// addresses. These addresses can be reused with other local groups. Routers are typically /// configured with filters to prevent multicast traffic in this range from flowing outside /// of the local network. /// </para> /// </remarks> public IPAddress RemoteAddress { get { return m_remoteAddress; } set { m_remoteAddress = value; } } /// <summary> /// Gets or sets the TCP port number of the remote host or multicast group to which /// the underlying <see cref="UdpClient" /> should sent the logging event. /// </summary> /// <value> /// An integer value in the range <see cref="IPEndPoint.MinPort" /> to <see cref="IPEndPoint.MaxPort" /> /// indicating the TCP port number of the remote host or multicast group to which the logging event /// will be sent. /// </value> /// <remarks> /// The underlying <see cref="UdpClient" /> will send messages to this TCP port number /// on the remote host or multicast group. /// </remarks> /// <exception cref="ArgumentOutOfRangeException">The value specified is less than <see cref="IPEndPoint.MinPort" /> or greater than <see cref="IPEndPoint.MaxPort" />.</exception> public int RemotePort { get { return m_remotePort; } set { if (value < IPEndPoint.MinPort || value > IPEndPoint.MaxPort) { throw log4net.Util.SystemInfo.CreateArgumentOutOfRangeException("value", (object)value, "The value specified is less than " + IPEndPoint.MinPort.ToString(NumberFormatInfo.InvariantInfo) + " or greater than " + IPEndPoint.MaxPort.ToString(NumberFormatInfo.InvariantInfo) + "."); } else { m_remotePort = value; } } } /// <summary> /// Gets or sets the TCP port number from which the underlying <see cref="UdpClient" /> will communicate. /// </summary> /// <value> /// An integer value in the range <see cref="IPEndPoint.MinPort" /> to <see cref="IPEndPoint.MaxPort" /> /// indicating the TCP port number from which the underlying <see cref="UdpClient" /> will communicate. /// </value> /// <remarks> /// <para> /// The underlying <see cref="UdpClient" /> will bind to this port for sending messages. /// </para> /// <para> /// Setting the value to 0 (the default) will cause the udp client not to bind to /// a local port. /// </para> /// </remarks> /// <exception cref="ArgumentOutOfRangeException">The value specified is less than <see cref="IPEndPoint.MinPort" /> or greater than <see cref="IPEndPoint.MaxPort" />.</exception> public int LocalPort { get { return m_localPort; } set { if (value != 0 && (value < IPEndPoint.MinPort || value > IPEndPoint.MaxPort)) { throw log4net.Util.SystemInfo.CreateArgumentOutOfRangeException("value", (object)value, "The value specified is less than " + IPEndPoint.MinPort.ToString(NumberFormatInfo.InvariantInfo) + " or greater than " + IPEndPoint.MaxPort.ToString(NumberFormatInfo.InvariantInfo) + "."); } else { m_localPort = value; } } } /// <summary> /// Gets or sets <see cref="Encoding"/> used to write the packets. /// </summary> /// <value> /// The <see cref="Encoding"/> used to write the packets. /// </value> /// <remarks> /// <para> /// The <see cref="Encoding"/> used to write the packets. /// </para> /// </remarks> public Encoding Encoding { get { return m_encoding; } set { m_encoding = value; } } #endregion Public Instance Properties #region Protected Instance Properties /// <summary> /// Gets or sets the underlying <see cref="UdpClient" />. /// </summary> /// <value> /// The underlying <see cref="UdpClient" />. /// </value> /// <remarks> /// <see cref="UdpAppender" /> creates a <see cref="UdpClient" /> to send logging events /// over a network. Classes deriving from <see cref="UdpAppender" /> can use this /// property to get or set this <see cref="UdpClient" />. Use the underlying <see cref="UdpClient" /> /// returned from <see cref="Client" /> if you require access beyond that which /// <see cref="UdpAppender" /> provides. /// </remarks> protected UdpClient Client { get { return this.m_client; } set { this.m_client = value; } } /// <summary> /// Gets or sets the cached remote endpoint to which the logging events should be sent. /// </summary> /// <value> /// The cached remote endpoint to which the logging events will be sent. /// </value> /// <remarks> /// The <see cref="ActivateOptions" /> method will initialize the remote endpoint /// with the values of the <see cref="RemoteAddress" /> and <see cref="RemotePort"/> /// properties. /// </remarks> protected IPEndPoint RemoteEndPoint { get { return this.m_remoteEndPoint; } set { this.m_remoteEndPoint = value; } } #endregion Protected Instance Properties #region Implementation of IOptionHandler /// <summary> /// Initialize the appender based on the options set. /// </summary> /// <remarks> /// <para> /// This is part of the <see cref="IOptionHandler"/> delayed object /// activation scheme. The <see cref="ActivateOptions"/> method must /// be called on this object after the configuration properties have /// been set. Until <see cref="ActivateOptions"/> is called this /// object is in an undefined state and must not be used. /// </para> /// <para> /// If any of the configuration properties are modified then /// <see cref="ActivateOptions"/> must be called again. /// </para> /// <para> /// The appender will be ignored if no <see cref="RemoteAddress" /> was specified or /// an invalid remote or local TCP port number was specified. /// </para> /// </remarks> /// <exception cref="ArgumentNullException">The required property <see cref="RemoteAddress" /> was not specified.</exception> /// <exception cref="ArgumentOutOfRangeException">The TCP port number assigned to <see cref="LocalPort" /> or <see cref="RemotePort" /> is less than <see cref="IPEndPoint.MinPort" /> or greater than <see cref="IPEndPoint.MaxPort" />.</exception> public override void ActivateOptions() { base.ActivateOptions(); if (this.RemoteAddress == null) { throw new ArgumentNullException("The required property 'Address' was not specified."); } else if (this.RemotePort < IPEndPoint.MinPort || this.RemotePort > IPEndPoint.MaxPort) { throw log4net.Util.SystemInfo.CreateArgumentOutOfRangeException("this.RemotePort", (object)this.RemotePort, "The RemotePort is less than " + IPEndPoint.MinPort.ToString(NumberFormatInfo.InvariantInfo) + " or greater than " + IPEndPoint.MaxPort.ToString(NumberFormatInfo.InvariantInfo) + "."); } else if (this.LocalPort != 0 && (this.LocalPort < IPEndPoint.MinPort || this.LocalPort > IPEndPoint.MaxPort)) { throw log4net.Util.SystemInfo.CreateArgumentOutOfRangeException("this.LocalPort", (object)this.LocalPort, "The LocalPort is less than " + IPEndPoint.MinPort.ToString(NumberFormatInfo.InvariantInfo) + " or greater than " + IPEndPoint.MaxPort.ToString(NumberFormatInfo.InvariantInfo) + "."); } else { this.RemoteEndPoint = new IPEndPoint(this.RemoteAddress, this.RemotePort); this.InitializeClientConnection(); } } #endregion #region Override implementation of AppenderSkeleton /// <summary> /// This method is called by the <see cref="M:AppenderSkeleton.DoAppend(LoggingEvent)"/> method. /// </summary> /// <param name="loggingEvent">The event to log.</param> /// <remarks> /// <para> /// Sends the event using an UDP datagram. /// </para> /// <para> /// Exceptions are passed to the <see cref="AppenderSkeleton.ErrorHandler"/>. /// </para> /// </remarks> protected override void Append(LoggingEvent loggingEvent) { try { Byte [] buffer = m_encoding.GetBytes(RenderLoggingEvent(loggingEvent).ToCharArray()); this.Client.Send(buffer, buffer.Length, this.RemoteEndPoint); } catch (Exception ex) { ErrorHandler.Error( "Unable to send logging event to remote host " + this.RemoteAddress.ToString() + " on port " + this.RemotePort + ".", ex, ErrorCode.WriteFailure); } } /// <summary> /// This appender requires a <see cref="Layout"/> to be set. /// </summary> /// <value><c>true</c></value> /// <remarks> /// <para> /// This appender requires a <see cref="Layout"/> to be set. /// </para> /// </remarks> override protected bool RequiresLayout { get { return true; } } /// <summary> /// Closes the UDP connection and releases all resources associated with /// this <see cref="UdpAppender" /> instance. /// </summary> /// <remarks> /// <para> /// Disables the underlying <see cref="UdpClient" /> and releases all managed /// and unmanaged resources associated with the <see cref="UdpAppender" />. /// </para> /// </remarks> override protected void OnClose() { base.OnClose(); if (this.Client != null) { this.Client.Close(); this.Client = null; } } #endregion Override implementation of AppenderSkeleton #region Protected Instance Methods /// <summary> /// Initializes the underlying <see cref="UdpClient" /> connection. /// </summary> /// <remarks> /// <para> /// The underlying <see cref="UdpClient"/> is initialized and binds to the /// port number from which you intend to communicate. /// </para> /// <para> /// Exceptions are passed to the <see cref="AppenderSkeleton.ErrorHandler"/>. /// </para> /// </remarks> protected virtual void InitializeClientConnection() { try { if (this.LocalPort == 0) { #if NETCF || NET_1_0 || SSCLI_1_0 || CLI_1_0 this.Client = new UdpClient(); #else this.Client = new UdpClient(RemoteAddress.AddressFamily); #endif } else { #if NETCF || NET_1_0 || SSCLI_1_0 || CLI_1_0 this.Client = new UdpClient(this.LocalPort); #else this.Client = new UdpClient(this.LocalPort, RemoteAddress.AddressFamily); #endif } } catch (Exception ex) { ErrorHandler.Error( "Could not initialize the UdpClient connection on port " + this.LocalPort.ToString(NumberFormatInfo.InvariantInfo) + ".", ex, ErrorCode.GenericFailure); this.Client = null; } } #endregion Protected Instance Methods #region Private Instance Fields /// <summary> /// The IP address of the remote host or multicast group to which /// the logging event will be sent. /// </summary> private IPAddress m_remoteAddress; /// <summary> /// The TCP port number of the remote host or multicast group to /// which the logging event will be sent. /// </summary> private int m_remotePort; /// <summary> /// The cached remote endpoint to which the logging events will be sent. /// </summary> private IPEndPoint m_remoteEndPoint; /// <summary> /// The TCP port number from which the <see cref="UdpClient" /> will communicate. /// </summary> private int m_localPort; /// <summary> /// The <see cref="UdpClient" /> instance that will be used for sending the /// logging events. /// </summary> private UdpClient m_client; /// <summary> /// The encoding to use for the packet. /// </summary> private Encoding m_encoding = Encoding.Default; #endregion Private Instance Fields } }
// 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 Xunit; namespace System.IO.Tests { public class Directory_GetFileSystemEntries_str : FileSystemTest { #region Utilities public static string[] WindowsInvalidUnixValid = new string[] { " ", " ", "\n", ">", "<", "\t" }; protected virtual bool TestFiles { get { return true; } } // True if the virtual GetEntries mmethod returns files protected virtual bool TestDirectories { get { return true; } } // True if the virtual GetEntries mmethod returns Directories public virtual string[] GetEntries(string dirName) { return Directory.GetFileSystemEntries(dirName); } /// <summary> /// Create a file at the given path or directory if GetEntries doesn't return files /// </summary> protected void CreateItem(string path) { if (TestFiles) File.WriteAllText(path, path); else Directory.CreateDirectory(path); } #endregion #region UniversalTests [Fact] public void NullFileName() { Assert.Throws<ArgumentNullException>(() => GetEntries(null)); } [Fact] public void EmptyFileName() { Assert.Throws<ArgumentException>(() => GetEntries(string.Empty)); } [Fact] public void InvalidFileNames() { Assert.Throws<DirectoryNotFoundException>(() => GetEntries("DoesNotExist")); Assert.Throws<ArgumentException>(() => GetEntries("\0")); } [Fact] public void EmptyDirectory() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); Assert.Empty(GetEntries(testDir.FullName)); } [Fact] public void GetEntriesThenDelete() { string testDirPath = GetTestFilePath(); DirectoryInfo testDirInfo = new DirectoryInfo(testDirPath); testDirInfo.Create(); string testDir1 = GetTestFileName(); string testDir2 = GetTestFileName(); string testFile1 = GetTestFileName(); string testFile2 = GetTestFileName(); string testFile3 = GetTestFileName(); string testFile4 = GetTestFileName(); string testFile5 = GetTestFileName(); testDirInfo.CreateSubdirectory(testDir1); testDirInfo.CreateSubdirectory(testDir2); using (File.Create(Path.Combine(testDirPath, testFile1))) using (File.Create(Path.Combine(testDirPath, testFile2))) using (File.Create(Path.Combine(testDirPath, testFile3))) { string[] results; using (File.Create(Path.Combine(testDirPath, testFile4))) using (File.Create(Path.Combine(testDirPath, testFile5))) { results = GetEntries(testDirPath); Assert.NotNull(results); Assert.NotEmpty(results); if (TestFiles) { Assert.Contains(Path.Combine(testDirPath, testFile1), results); Assert.Contains(Path.Combine(testDirPath, testFile2), results); Assert.Contains(Path.Combine(testDirPath, testFile3), results); Assert.Contains(Path.Combine(testDirPath, testFile4), results); Assert.Contains(Path.Combine(testDirPath, testFile5), results); } if (TestDirectories) { Assert.Contains(Path.Combine(testDirPath, testDir1), results); Assert.Contains(Path.Combine(testDirPath, testDir2), results); } } File.Delete(Path.Combine(testDirPath, testFile4)); File.Delete(Path.Combine(testDirPath, testFile5)); FailSafeDirectoryOperations.DeleteDirectory(testDir1, true); results = GetEntries(testDirPath); Assert.NotNull(results); Assert.NotEmpty(results); if (TestFiles) { Assert.Contains(Path.Combine(testDirPath, testFile1), results); Assert.Contains(Path.Combine(testDirPath, testFile2), results); Assert.Contains(Path.Combine(testDirPath, testFile3), results); } if (TestDirectories) { Assert.Contains(Path.Combine(testDirPath, testDir2), results); } } } [Fact] public virtual void IgnoreSubDirectoryFiles() { string subDir = GetTestFileName(); Directory.CreateDirectory(Path.Combine(TestDirectory, subDir)); string testFile = Path.Combine(TestDirectory, GetTestFileName()); string testFileInSub = Path.Combine(TestDirectory, subDir, GetTestFileName()); string testDir = Path.Combine(TestDirectory, GetTestFileName()); string testDirInSub = Path.Combine(TestDirectory, subDir, GetTestFileName()); Directory.CreateDirectory(testDir); Directory.CreateDirectory(testDirInSub); using (File.Create(testFile)) using (File.Create(testFileInSub)) { string[] results = GetEntries(TestDirectory); if (TestFiles) Assert.Contains(testFile, results); if (TestDirectories) Assert.Contains(testDir, results); Assert.DoesNotContain(testFileInSub, results); Assert.DoesNotContain(testDirInSub, results); } } [Theory, MemberData(nameof(TrailingCharacters))] public void MissingFile_ThrowsDirectoryNotFound(char trailingChar) { string path = GetTestFilePath() + trailingChar; Assert.Throws<DirectoryNotFoundException>(() => GetEntries(path)); } [Theory, MemberData(nameof(TrailingCharacters))] public void MissingDirectory_ThrowsDirectoryNotFound(char trailingChar) { string path = Path.Combine(GetTestFilePath(), "file" + trailingChar); Assert.Throws<DirectoryNotFoundException>(() => GetEntries(path)); } [Fact] public void TrailingSlashes() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); Directory.CreateDirectory(Path.Combine(testDir.FullName, GetTestFileName())); using (File.Create(Path.Combine(testDir.FullName, GetTestFileName()))) { string[] strArr = GetEntries(testDir.FullName + new string(Path.DirectorySeparatorChar, 5)); Assert.NotNull(strArr); Assert.NotEmpty(strArr); } } #endregion #region PlatformSpecific [Fact] public void InvalidPath() { foreach (char invalid in Path.GetInvalidFileNameChars()) { if (invalid == '/' || invalid == '\\') { Assert.Throws<DirectoryNotFoundException>(() => GetEntries(Path.Combine(TestDirectory, string.Format("te{0}st", invalid.ToString())))); } else if (invalid == ':') { if (FileSystemDebugInfo.IsCurrentDriveNTFS()) Assert.Throws<NotSupportedException>(() => GetEntries(Path.Combine(TestDirectory, string.Format("te{0}st", invalid.ToString())))); } else { Assert.Throws<ArgumentException>(() => GetEntries(Path.Combine(TestDirectory, string.Format("te{0}st", invalid.ToString())))); } } } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // Windows-only Invalid chars in path public void WindowsInvalidCharsPath() { Assert.All(WindowsInvalidUnixValid, invalid => Assert.Throws<ArgumentException>(() => GetEntries(invalid))); } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] // Unix-only valid chars in file path public void UnixValidCharsFilePath() { if (TestFiles) { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); foreach (string valid in WindowsInvalidUnixValid) File.Create(Path.Combine(testDir.FullName, valid)).Dispose(); string[] results = GetEntries(testDir.FullName); Assert.All(WindowsInvalidUnixValid, valid => Assert.Contains(Path.Combine(testDir.FullName, valid), results)); } } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] // Windows-only invalid chars in directory path public void UnixValidCharsDirectoryPath() { if (TestDirectories) { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); foreach (string valid in WindowsInvalidUnixValid) testDir.CreateSubdirectory(valid); string[] results = GetEntries(testDir.FullName); Assert.All(WindowsInvalidUnixValid, valid => Assert.Contains(Path.Combine(testDir.FullName, valid), results)); } } #endregion } public sealed class Directory_GetEntries_CurrentDirectory : RemoteExecutorTestBase { [Fact] public void CurrentDirectory() { string testDir = GetTestFilePath(); Directory.CreateDirectory(testDir); File.WriteAllText(Path.Combine(testDir, GetTestFileName()), "cat"); Directory.CreateDirectory(Path.Combine(testDir, GetTestFileName())); RemoteInvoke((testDirectory) => { Directory.SetCurrentDirectory(testDirectory); Assert.NotEmpty(Directory.GetFileSystemEntries(Directory.GetCurrentDirectory())); Assert.NotEmpty(Directory.GetFileSystemEntries(Directory.GetCurrentDirectory(), "*")); Assert.NotEmpty(Directory.GetFileSystemEntries(Directory.GetCurrentDirectory(), "*", SearchOption.AllDirectories)); Assert.NotEmpty(Directory.GetFileSystemEntries(Directory.GetCurrentDirectory(), "*", SearchOption.TopDirectoryOnly)); Assert.NotEmpty(Directory.GetDirectories(Directory.GetCurrentDirectory())); Assert.NotEmpty(Directory.GetDirectories(Directory.GetCurrentDirectory(), "*")); Assert.NotEmpty(Directory.GetDirectories(Directory.GetCurrentDirectory(), "*", SearchOption.AllDirectories)); Assert.NotEmpty(Directory.GetDirectories(Directory.GetCurrentDirectory(), "*", SearchOption.TopDirectoryOnly)); Assert.NotEmpty(Directory.GetFiles(Directory.GetCurrentDirectory())); Assert.NotEmpty(Directory.GetFiles(Directory.GetCurrentDirectory(), "*")); Assert.NotEmpty(Directory.GetFiles(Directory.GetCurrentDirectory(), "*", SearchOption.AllDirectories)); Assert.NotEmpty(Directory.GetFiles(Directory.GetCurrentDirectory(), "*", SearchOption.TopDirectoryOnly)); Assert.NotEmpty(Directory.EnumerateFileSystemEntries(Directory.GetCurrentDirectory())); Assert.NotEmpty(Directory.EnumerateFileSystemEntries(Directory.GetCurrentDirectory(), "*")); Assert.NotEmpty(Directory.EnumerateFileSystemEntries(Directory.GetCurrentDirectory(), "*", SearchOption.AllDirectories)); Assert.NotEmpty(Directory.EnumerateFileSystemEntries(Directory.GetCurrentDirectory(), "*", SearchOption.TopDirectoryOnly)); Assert.NotEmpty(Directory.EnumerateDirectories(Directory.GetCurrentDirectory())); Assert.NotEmpty(Directory.EnumerateDirectories(Directory.GetCurrentDirectory(), "*")); Assert.NotEmpty(Directory.EnumerateDirectories(Directory.GetCurrentDirectory(), "*", SearchOption.AllDirectories)); Assert.NotEmpty(Directory.EnumerateDirectories(Directory.GetCurrentDirectory(), "*", SearchOption.TopDirectoryOnly)); Assert.NotEmpty(Directory.EnumerateFiles(Directory.GetCurrentDirectory())); Assert.NotEmpty(Directory.EnumerateFiles(Directory.GetCurrentDirectory(), "*")); Assert.NotEmpty(Directory.EnumerateFiles(Directory.GetCurrentDirectory(), "*", SearchOption.AllDirectories)); Assert.NotEmpty(Directory.EnumerateFiles(Directory.GetCurrentDirectory(), "*", SearchOption.TopDirectoryOnly)); return SuccessExitCode; }, testDir).Dispose(); } } }
#if !NOT_UNITY3D using System; using System.Collections.Generic; using System.IO; using System.Linq; using UnityEditor; using UnityEditor.SceneManagement; using UnityEngine; using ModestTree; using UnityEngine.SceneManagement; namespace Zenject { public static class ZenUnityEditorUtil { // Don't use this public static void ValidateCurrentSceneSetup() { bool encounteredError = false; Application.LogCallback logCallback = (condition, stackTrace, type) => { if (type == LogType.Error || type == LogType.Assert || type == LogType.Exception) { encounteredError = true; } }; Application.logMessageReceived += logCallback; try { Assert.That(!ProjectContext.HasInstance); ProjectContext.ValidateOnNextRun = true; foreach (var sceneContext in GetAllSceneContexts()) { sceneContext.Validate(); } } catch (Exception e) { ModestTree.Log.ErrorException(e); encounteredError = true; } finally { Application.logMessageReceived -= logCallback; } if (encounteredError) { throw new ZenjectException("Zenject Validation Failed! See errors below for details."); } } // Don't use this public static int ValidateAllActiveScenes() { var activeScenePaths = UnityEditor.EditorBuildSettings.scenes.Where(x => x.enabled) .Select(x => x.path).ToList(); foreach (var scenePath in activeScenePaths) { EditorSceneManager.OpenScene(scenePath, OpenSceneMode.Single); ValidateCurrentSceneSetup(); } return activeScenePaths.Count; } // Don't use this public static void RunCurrentSceneSetup() { Assert.That(!ProjectContext.HasInstance); foreach (var sceneContext in GetAllSceneContexts()) { try { sceneContext.Run(); } catch (Exception e) { // Add a bit more context throw new ZenjectException( "Scene '{0}' Failed To Start!".Fmt(sceneContext.gameObject.scene.name), e); } } } static IEnumerable<SceneContext> GetAllSceneContexts() { var decoratedSceneNames = new List<string>(); for (int i = 0; i < EditorSceneManager.sceneCount; i++) { var scene = EditorSceneManager.GetSceneAt(i); var sceneContexts = scene.GetRootGameObjects() .SelectMany(x => x.GetComponentsInChildren<SceneContext>()).ToList(); var decoratorContexts = scene.GetRootGameObjects() .SelectMany(x => x.GetComponentsInChildren<SceneDecoratorContext>()).ToList(); if (!sceneContexts.IsEmpty()) { Assert.That(decoratorContexts.IsEmpty(), "Found both SceneDecoratorContext and SceneContext in the same scene '{0}'. This is not allowed", scene.name); Assert.That(sceneContexts.IsLength(1), "Found multiple SceneContexts in scene '{0}'. Expected a maximum of one.", scene.name); var context = sceneContexts[0]; decoratedSceneNames.RemoveAll(x => context.ContractNames.Contains(x)); yield return context; } else if (!decoratorContexts.IsEmpty()) { Assert.That(decoratorContexts.IsLength(1), "Found multiple SceneDecoratorContexts in scene '{0}'. Expected a maximum of one.", scene.name); var context = decoratorContexts[0]; Assert.That(!string.IsNullOrEmpty(context.DecoratedContractName), "Missing Decorated Contract Name on SceneDecoratorContext in scene '{0}'", scene.name); decoratedSceneNames.Add(context.DecoratedContractName); } } Assert.That(decoratedSceneNames.IsEmpty(), "Found decorator scenes without a corresponding scene to decorator. Missing scene contracts: {0}", decoratedSceneNames.Join(", ")); } public static string ConvertFullAbsolutePathToAssetPath(string fullPath) { fullPath = Path.GetFullPath(fullPath); var assetFolderFullPath = Path.GetFullPath(Application.dataPath); if (fullPath.Length == assetFolderFullPath.Length) { Assert.IsEqual(fullPath, assetFolderFullPath); return "Assets"; } var assetPath = fullPath.Remove(0, assetFolderFullPath.Length + 1).Replace("\\", "/"); return "Assets/" + assetPath; } public static string GetCurrentDirectoryAssetPathFromSelection() { return ZenUnityEditorUtil.ConvertFullAbsolutePathToAssetPath( GetCurrentDirectoryAbsolutePathFromSelection()); } public static string GetCurrentDirectoryAbsolutePathFromSelection() { var folderPath = ZenUnityEditorUtil.TryGetSelectedFolderPathInProjectsTab(); if (folderPath != null) { return folderPath; } var filePath = ZenUnityEditorUtil.TryGetSelectedFilePathInProjectsTab(); if (filePath != null) { return Path.GetDirectoryName(filePath); } return Application.dataPath; } public static string TryGetSelectedFilePathInProjectsTab() { return GetSelectedFilePathsInProjectsTab().OnlyOrDefault(); } public static List<string> GetSelectedFilePathsInProjectsTab() { return GetSelectedPathsInProjectsTab() .Where(x => File.Exists(x)).ToList(); } public static List<string> GetSelectedPathsInProjectsTab() { var paths = new List<string>(); UnityEngine.Object[] selectedAssets = Selection.GetFiltered( typeof(UnityEngine.Object), SelectionMode.Assets); foreach (var item in selectedAssets) { var relativePath = AssetDatabase.GetAssetPath(item); if (!string.IsNullOrEmpty(relativePath)) { var fullPath = Path.GetFullPath(Path.Combine( Application.dataPath, Path.Combine("..", relativePath))); paths.Add(fullPath); } } return paths; } // Note that the path is relative to the Assets folder public static List<string> GetSelectedFolderPathsInProjectsTab() { return GetSelectedPathsInProjectsTab() .Where(x => Directory.Exists(x)).ToList(); } // Returns the best guess directory in projects pane // Useful when adding to Assets -> Create context menu // Returns null if it can't find one // Note that the path is relative to the Assets folder for use in AssetDatabase.GenerateUniqueAssetPath etc. public static string TryGetSelectedFolderPathInProjectsTab() { return GetSelectedFolderPathsInProjectsTab().OnlyOrDefault(); } } } #endif
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect 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. * */ using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Threading; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using NodaTime; using QuantConnect.Data; using QuantConnect.Data.Market; using QuantConnect.Packets; using RestSharp; namespace QuantConnect.Brokerages.Tradier { /// <summary> /// Tradier Class: IDataQueueHandler implementation /// </summary> public partial class TradierBrokerage { #region IDataQueueHandler implementation private const string WebSocketUrl = "wss://ws.tradier.com/v1/markets/events"; private const int ConnectionTimeout = 30000; private readonly WebSocketClientWrapper _webSocketClient = new WebSocketClientWrapper(); private bool _isDataQueueHandlerInitialized; private TradierStreamSession _streamSession; private readonly ConcurrentDictionary<string, Symbol> _subscribedTickers = new ConcurrentDictionary<string, Symbol>(); /// <summary> /// Sets the job we're subscribing for /// </summary> /// <param name="job">Job we're subscribing for</param> public void SetJob(LiveNodePacket job) { } /// <summary> /// Subscribe to the specified configuration /// </summary> /// <param name="dataConfig">defines the parameters to subscribe to a data feed</param> /// <param name="newDataAvailableHandler">handler to be fired on new data available</param> /// <returns>The new enumerator for this subscription request</returns> public IEnumerator<BaseData> Subscribe(SubscriptionDataConfig dataConfig, EventHandler newDataAvailableHandler) { // streaming is not supported by sandbox if (_useSandbox) { throw new NotSupportedException( "TradierBrokerage.DataQueueHandler.Subscribe(): The sandbox does not support data streaming."); } // initialize data queue handler on-demand if (!_isDataQueueHandlerInitialized) { _isDataQueueHandlerInitialized = true; _streamSession = CreateStreamSession(); using (var resetEvent = new ManualResetEvent(false)) { EventHandler triggerEvent = (o, args) => resetEvent.Set(); _webSocketClient.Open += triggerEvent; _webSocketClient.Connect(); if (!resetEvent.WaitOne(ConnectionTimeout)) { throw new TimeoutException("Websockets connection timeout."); } _webSocketClient.Open -= triggerEvent; } } if (!CanSubscribe(dataConfig.Symbol)) { return Enumerable.Empty<BaseData>().GetEnumerator(); } var enumerator = _aggregator.Add(dataConfig, newDataAvailableHandler); _subscriptionManager.Subscribe(dataConfig); return enumerator; } private bool CanSubscribe(Symbol symbol) { return (symbol.ID.SecurityType == SecurityType.Equity || symbol.ID.SecurityType == SecurityType.Option) && !symbol.Value.Contains("-UNIVERSE-"); } /// <summary> /// Removes the specified configuration /// </summary> /// <param name="dataConfig">Subscription config to be removed</param> public void Unsubscribe(SubscriptionDataConfig dataConfig) { _subscriptionManager.Unsubscribe(dataConfig); _aggregator.Remove(dataConfig); } private bool Subscribe(IEnumerable<Symbol> symbols, TickType tickType) { var symbolsAdded = false; foreach (var symbol in symbols) { if (!symbol.IsCanonical()) { var ticker = _symbolMapper.GetBrokerageSymbol(symbol); if (!_subscribedTickers.ContainsKey(ticker)) { _subscribedTickers.TryAdd(ticker, symbol); symbolsAdded = true; } } } if (symbolsAdded) { SendSubscribeMessage(_subscribedTickers.Keys.ToList()); } return true; } private bool Unsubscribe(IEnumerable<Symbol> symbols, TickType tickType) { var symbolsRemoved = false; foreach (var symbol in symbols) { if (!symbol.IsCanonical()) { var ticker = _symbolMapper.GetBrokerageSymbol(symbol); if (_subscribedTickers.ContainsKey(ticker)) { Symbol removedSymbol; _subscribedTickers.TryRemove(ticker, out removedSymbol); symbolsRemoved = true; } } } if (symbolsRemoved) { var tickers = _subscribedTickers.Keys.ToList(); // Tradier expects at least one symbol SendSubscribeMessage(tickers.Count > 0 ? tickers : new List<string> { "$empty$" }); } return true; } private void SendSubscribeMessage(List<string> tickers) { var obj = new { sessionid = _streamSession.SessionId, symbols = tickers, filter = new[] { "trade", "quote" }, linebreak = true }; var json = JsonConvert.SerializeObject(obj); _webSocketClient.Send(json); } private void OnMessage(object sender, WebSocketMessage webSocketMessage) { var e = (WebSocketClientWrapper.TextMessage)webSocketMessage.Data; var obj = JObject.Parse(e.Message); JToken error; if (obj.TryGetValue("error", out error)) { OnMessage(new BrokerageMessageEvent(BrokerageMessageType.Error, -1, error.Value<string>())); return; } var tsd = obj.ToObject<TradierStreamData>(); if (tsd?.Type == "trade" || tsd?.Type == "quote") { var tick = CreateTick(tsd); if (tick != null) { _aggregator.Update(tick); } } } /// <summary> /// Create a tick from the tradier stream data /// </summary> /// <param name="tsd">Tradier stream data object</param> /// <returns>LEAN Tick object</returns> private Tick CreateTick(TradierStreamData tsd) { Symbol symbol; if (!_subscribedTickers.TryGetValue(tsd.Symbol, out symbol)) { // Not subscribed to this symbol. return null; } if (tsd.Type == "trade") { // Occasionally Tradier sends trades with 0 volume? if (tsd.TradeSize == 0) return null; } // Tradier trades are US NY time only. Convert local server time to NY Time: var utc = tsd.GetTickTimestamp(); // Occasionally Tradier sends old ticks every 20sec-ish if no trading? if (DateTime.UtcNow - utc > TimeSpan.FromSeconds(10)) return null; // Convert the timestamp to exchange timezone and pass into algorithm var time = utc.ConvertTo(DateTimeZone.Utc, TimeZones.NewYork); switch (tsd.Type) { case "trade": return new Tick(time, symbol, "", tsd.TradeExchange, (int) tsd.TradeSize, tsd.TradePrice); case "quote": return new Tick(time, symbol, "", "", tsd.BidSize, tsd.BidPrice, tsd.AskSize, tsd.AskPrice); } return null; } /// <summary> /// Get the current market status /// </summary> private TradierStreamSession CreateStreamSession() { var request = new RestRequest("markets/events/session", Method.POST); return Execute<TradierStreamSession>(request, TradierApiRequestType.Data, "stream"); } #endregion } }
#region Facebook's boilerplate notice /* * Copyright 2010 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ #endregion // THIS FILE IS MODIFIED SINCE FORKING FROM http://github.com/facebook/csharp-sdk/commit/52cf2493349494b783e321e0ea22335481b1c058 // #region Boris Byk's boilerplate notice /* * Copyright 2010 Boris Byk. * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ #endregion using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Text; using System.Globalization; using System.Web.Script.Serialization; namespace Facebook { /// <summary> /// Represents an object encoded in JSON. Can be either a dictionary /// mapping strings to other objects, an array of objects, or a single /// object, which represents a scalar. /// </summary> [Serializable] public class JsonObject { [NonSerialized] long? _int; [NonSerialized] bool? _bool; [NonSerialized] DateTime? _datetime; CultureInfo _ci; /// <summary> /// Creates a <see cref="JsonObject"/> by parsing a string. This is the only correct way to create a JSONObject. /// </summary> /// <param name="input">The JSON string to be deserialized.</param> /// <param name="culture"></param> /// <returns>The deserialized <see cref="JsonObject"/>.</returns> /// <exception cref="ArgumentNullException">input is null.</exception> /// <exception cref="FacebookApiException">invalid json input.</exception> [NotNull] public static JsonObject CreateFromString([NotNull] string input, CultureInfo culture) { if (input == null) throw FacebookApi.Nre("input"); object o; try { o = new JavaScriptSerializer().DeserializeObject(input); } catch (ArgumentException ex) { throw new FacebookApiException("JSONException", "Not a valid JSON string: " + input, ex); } return Create(o, culture); } ///<summary> /// Current locale. Facebook graph is locale sensitive. The data in json can be localized. If not provided, <see cref="CultureInfo.CurrentCulture"/> is used ///</summary> public CultureInfo Culture { [NotNull] get { return _ci ?? CultureInfo.CurrentCulture; } set { _ci = value; } } /// <summary> /// Returns true if this <see cref="JsonObject"/> represents a dictionary. /// </summary> public bool IsDictionary { get { return _dictData != null; } } /// <summary> /// Returns true if this <see cref="JsonObject"/> represents an array. /// </summary> public bool IsArray { get { return _arrayData != null; } } /// <summary> /// Returns true if this <see cref="JsonObject"/> represents a string value. /// </summary> public bool IsString { get { return _stringData != null; } } /// <summary> /// Returns true if this <see cref="JsonObject"/> represents an integer value. /// </summary> public bool IsInteger { get { long tmp; if (Int64.TryParse(_stringData, NumberStyles.Integer, Culture, out tmp)) { _int = tmp; return true; } return false; } } /// <summary> /// Returns true if this <see cref="JsonObject"/> represents a boolean value. /// </summary> public bool IsBoolean { get { bool tmp; if (bool.TryParse(ExtractQuoted(), out tmp)) { _bool = tmp; return true; } return false; } } ///<summary> /// Returns true if this <see cref="JsonObject"/> represents a <see cref="DateTime"/> value. ///</summary> public bool IsDateTime { get { DateTime tmp; if (DateTime.TryParse(_stringData, Culture, DateTimeStyles.None, out tmp)) { _datetime = tmp; return true; } return false; } } /// <summary> /// Returns this <see cref="JsonObject"/> as a dictionary /// </summary> public Dictionary<string, JsonObject> Dictionary { get { return _dictData; } } /// <summary> /// Returns this <see cref="JsonObject"/> as an array /// </summary> public JsonObject[] Array { get { return _arrayData; } } /// <summary> /// Returns this <see cref="JsonObject"/> as a string /// </summary> public string String { get { return _stringData; } } /// <summary> /// Returns this <see cref="JsonObject"/> as an integer /// </summary> public Int64 Integer { get { return _int.HasValue ? _int.Value : Convert.ToInt64(_stringData, Culture); } } /// <summary> /// Returns this <see cref="JsonObject"/> as a boolean /// </summary> public bool Boolean { get { return _bool.HasValue ? _bool.Value : Convert.ToBoolean(ExtractQuoted(), Culture); } } /// <summary> /// Returns this <see cref="JsonObject"/> as a <see cref="DateTime" />. /// </summary> public DateTime DateTime { get { return _datetime.HasValue ? _datetime.Value : Convert.ToDateTime(_stringData, Culture); } } /// <summary> /// Prints the JSONObject as a formatted string, suitable for viewing. /// </summary> public override string ToString() { var sb = new StringBuilder(); RecursiveObjectToString(this, sb, 0); return sb.ToString(); } #region Private Members private string _stringData; private JsonObject[] _arrayData; private Dictionary<string, JsonObject> _dictData; private JsonObject(CultureInfo ci) { _ci = ci ?? CultureInfo.CurrentCulture; } /// <summary> /// Recursively constructs this JSONObject /// </summary> internal static JsonObject Create(object o, CultureInfo ci) { var obj = new JsonObject(ci); object[] objArray; Dictionary<string, object> dict; Dictionary<string, string> sdict; NameValueCollection nvc; if ((objArray = o as object[]) != null) { obj._arrayData = new JsonObject[objArray.Length]; for (int i = 0; i < obj._arrayData.Length; ++i) { obj._arrayData[i] = Create(objArray[i], ci); } } else if ((dict = o as Dictionary<string, object>) != null) { obj._dictData = new Dictionary<string, JsonObject>(dict.Count); foreach (string key in dict.Keys) { obj._dictData[key] = Create(dict[key], ci); } } else if ((sdict = o as Dictionary<string, string>) != null) { obj._dictData = new Dictionary<string, JsonObject>(sdict.Count); foreach (string key in sdict.Keys) { obj._dictData[key] = new JsonObject(ci) { _stringData = sdict[key] }; } } else if ((nvc = o as NameValueCollection) != null) { obj._dictData = new Dictionary<string, JsonObject>(nvc.Count); foreach (string key in nvc) { obj._dictData[key] = new JsonObject(ci) { _stringData = nvc[key] }; } } else if (o != null) // o is a scalar { obj._stringData = o.ToString(); } return obj; } private static void RecursiveObjectToString(JsonObject obj, StringBuilder sb, int level) { if (obj.IsDictionary) { sb.AppendLine(); RecursiveDictionaryToString(obj, sb, level + 1); } else if (obj.IsArray) { foreach (JsonObject o in obj.Array) { RecursiveObjectToString(o, sb, level); sb.AppendLine(); } } else // some sort of scalar value { sb.Append(obj.String); } } private static void RecursiveDictionaryToString(JsonObject obj, StringBuilder sb, int level) { foreach (KeyValuePair<string, JsonObject> kvp in obj.Dictionary) { sb.Append(' ', level * 2); sb.Append(kvp.Key); sb.Append(" => "); RecursiveObjectToString(kvp.Value, sb, level); sb.AppendLine(); } } string ExtractQuoted() { return _stringData != null && ((_stringData[0] == '\'' && _stringData[_stringData.Length - 1] == '\'') || (_stringData[0] == '"' && _stringData[_stringData.Length - 1] == '"')) ? _stringData.Substring(1, Math.Max(0, _stringData.Length - 2)) : _stringData; } #endregion } }
namespace System.Windows.Forms { using System; using System.Windows.Forms; using System.Windows.Forms.VisualStyles; using Microsoft.Win32; using System.Drawing; using System.Collections; using System.Diagnostics; public sealed class ProfessionalColors { [ThreadStatic] private static ProfessionalColorTable professionalColorTable = null; [ThreadStatic] private static string colorScheme = null; [ThreadStatic] private static object colorFreshnessKey = null; internal static ProfessionalColorTable ColorTable { get { if (professionalColorTable == null) { professionalColorTable = new ProfessionalColorTable(); } return professionalColorTable; } } static ProfessionalColors() { SystemEvents.UserPreferenceChanged += new UserPreferenceChangedEventHandler(OnUserPreferenceChanged); SetScheme(); } private ProfessionalColors() { } internal static string ColorScheme { get { return colorScheme; } } // internal object used between professional color tables // to identify when a userpreferencechanged has occurred internal static object ColorFreshnessKey { get { return colorFreshnessKey; } } #region Colors [SRDescription(SR.ProfessionalColorsButtonSelectedHighlightDescr)] public static Color ButtonSelectedHighlight { get { return ColorTable.ButtonSelectedHighlight; } } [SRDescription(SR.ProfessionalColorsButtonSelectedHighlightBorderDescr)] public static Color ButtonSelectedHighlightBorder { get { return ColorTable.ButtonSelectedHighlightBorder; } } [SRDescription(SR.ProfessionalColorsButtonPressedHighlightDescr)] public static Color ButtonPressedHighlight { get { return ColorTable.ButtonPressedHighlight; } } [SRDescription(SR.ProfessionalColorsButtonPressedHighlightBorderDescr)] public static Color ButtonPressedHighlightBorder { get { return ColorTable.ButtonPressedHighlightBorder; } } [SRDescription(SR.ProfessionalColorsButtonCheckedHighlightDescr)] public static Color ButtonCheckedHighlight { get { return ColorTable.ButtonCheckedHighlight; } } [SRDescription(SR.ProfessionalColorsButtonCheckedHighlightBorderDescr)] public static Color ButtonCheckedHighlightBorder { get { return ColorTable.ButtonCheckedHighlightBorder; } } [SRDescription(SR.ProfessionalColorsButtonPressedBorderDescr)] public static Color ButtonPressedBorder { get { return ColorTable.ButtonPressedBorder; } } [SRDescription(SR.ProfessionalColorsButtonSelectedBorderDescr)] public static Color ButtonSelectedBorder { get { return ColorTable.ButtonSelectedBorder; } } [SRDescription(SR.ProfessionalColorsButtonCheckedGradientBeginDescr)] public static Color ButtonCheckedGradientBegin { get { return ColorTable.ButtonCheckedGradientBegin; } } [SRDescription(SR.ProfessionalColorsButtonCheckedGradientMiddleDescr)] public static Color ButtonCheckedGradientMiddle { get { return ColorTable.ButtonCheckedGradientMiddle; } } [SRDescription(SR.ProfessionalColorsButtonCheckedGradientEndDescr)] public static Color ButtonCheckedGradientEnd { get { return ColorTable.ButtonCheckedGradientEnd; } } [SRDescription(SR.ProfessionalColorsButtonSelectedGradientBeginDescr)] public static Color ButtonSelectedGradientBegin { get { return ColorTable.ButtonSelectedGradientBegin; } } [SRDescription(SR.ProfessionalColorsButtonSelectedGradientMiddleDescr)] public static Color ButtonSelectedGradientMiddle { get { return ColorTable.ButtonSelectedGradientMiddle; } } [SRDescription(SR.ProfessionalColorsButtonSelectedGradientEndDescr)] public static Color ButtonSelectedGradientEnd { get { return ColorTable.ButtonSelectedGradientEnd; } } [SRDescription(SR.ProfessionalColorsButtonPressedGradientBeginDescr)] public static Color ButtonPressedGradientBegin { get { return ColorTable.ButtonPressedGradientBegin; } } [SRDescription(SR.ProfessionalColorsButtonPressedGradientMiddleDescr)] public static Color ButtonPressedGradientMiddle { get { return ColorTable.ButtonPressedGradientMiddle; } } [SRDescription(SR.ProfessionalColorsButtonPressedGradientEndDescr)] public static Color ButtonPressedGradientEnd { get { return ColorTable.ButtonPressedGradientEnd; } } [SRDescription(SR.ProfessionalColorsCheckBackgroundDescr)] public static Color CheckBackground { get { return ColorTable.CheckBackground; } } [SRDescription(SR.ProfessionalColorsCheckSelectedBackgroundDescr)] public static Color CheckSelectedBackground { get { return ColorTable.CheckSelectedBackground; } } [SRDescription(SR.ProfessionalColorsCheckPressedBackgroundDescr)] public static Color CheckPressedBackground { get { return ColorTable.CheckPressedBackground; } } [SRDescription(SR.ProfessionalColorsGripDarkDescr)] public static Color GripDark { get { return ColorTable.GripDark; } } [SRDescription(SR.ProfessionalColorsGripLightDescr)] public static Color GripLight { get { return ColorTable.GripLight; } } [SRDescription(SR.ProfessionalColorsImageMarginGradientBeginDescr)] public static Color ImageMarginGradientBegin { get { return ColorTable.ImageMarginGradientBegin; } } [SRDescription(SR.ProfessionalColorsImageMarginGradientMiddleDescr)] public static Color ImageMarginGradientMiddle { get { return ColorTable.ImageMarginGradientMiddle; } } [SRDescription(SR.ProfessionalColorsImageMarginGradientEndDescr)] public static Color ImageMarginGradientEnd { get { return ColorTable.ImageMarginGradientEnd; } } [SRDescription(SR.ProfessionalColorsImageMarginRevealedGradientBeginDescr)] public static Color ImageMarginRevealedGradientBegin { get { return ColorTable.ImageMarginRevealedGradientBegin; } } [SRDescription(SR.ProfessionalColorsImageMarginRevealedGradientMiddleDescr)] public static Color ImageMarginRevealedGradientMiddle { get { return ColorTable.ImageMarginRevealedGradientMiddle; } } [SRDescription(SR.ProfessionalColorsImageMarginRevealedGradientEndDescr)] public static Color ImageMarginRevealedGradientEnd { get { return ColorTable.ImageMarginRevealedGradientEnd; } } [SRDescription(SR.ProfessionalColorsMenuStripGradientBeginDescr)] public static Color MenuStripGradientBegin { get { return ColorTable.MenuStripGradientBegin; } } [SRDescription(SR.ProfessionalColorsMenuStripGradientEndDescr)] public static Color MenuStripGradientEnd{ get { return ColorTable.MenuStripGradientEnd; } } [SRDescription(SR.ProfessionalColorsMenuBorderDescr)] public static Color MenuBorder { get { return ColorTable.MenuBorder; } } [SRDescription(SR.ProfessionalColorsMenuItemSelectedDescr)] public static Color MenuItemSelected { get { return ColorTable.MenuItemSelected; } } [SRDescription(SR.ProfessionalColorsMenuItemBorderDescr)] public static Color MenuItemBorder { get { return ColorTable.MenuItemBorder; } } [SRDescription(SR.ProfessionalColorsMenuItemSelectedGradientBeginDescr)] public static Color MenuItemSelectedGradientBegin { get { return ColorTable.MenuItemSelectedGradientBegin; } } [SRDescription(SR.ProfessionalColorsMenuItemSelectedGradientEndDescr)] public static Color MenuItemSelectedGradientEnd { get { return ColorTable.MenuItemSelectedGradientEnd; } } [SRDescription(SR.ProfessionalColorsMenuItemPressedGradientBeginDescr)] public static Color MenuItemPressedGradientBegin { get { return ColorTable.MenuItemPressedGradientBegin; } } [SRDescription(SR.ProfessionalColorsMenuItemPressedGradientMiddleDescr)] public static Color MenuItemPressedGradientMiddle { get { return ColorTable.MenuItemPressedGradientMiddle; } } [SRDescription(SR.ProfessionalColorsMenuItemPressedGradientEndDescr)] public static Color MenuItemPressedGradientEnd { get { return ColorTable.MenuItemPressedGradientEnd; } } [SRDescription(SR.ProfessionalColorsRaftingContainerGradientBeginDescr)] public static Color RaftingContainerGradientBegin { get { return ColorTable.RaftingContainerGradientBegin; } } [SRDescription(SR.ProfessionalColorsRaftingContainerGradientEndDescr)] public static Color RaftingContainerGradientEnd { get { return ColorTable.RaftingContainerGradientEnd; } } [SRDescription(SR.ProfessionalColorsSeparatorDarkDescr)] public static Color SeparatorDark { get { return ColorTable.SeparatorDark; } } [SRDescription(SR.ProfessionalColorsSeparatorLightDescr)] public static Color SeparatorLight { get { return ColorTable.SeparatorLight; } } [SRDescription(SR.ProfessionalColorsStatusStripGradientBeginDescr)] public static Color StatusStripGradientBegin { get { return ColorTable.StatusStripGradientBegin; } } [SRDescription(SR.ProfessionalColorsStatusStripGradientEndDescr)] public static Color StatusStripGradientEnd { get { return ColorTable.StatusStripGradientEnd; } } [SRDescription(SR.ProfessionalColorsToolStripBorderDescr)] public static Color ToolStripBorder { get { return ColorTable.ToolStripBorder; } } [SRDescription(SR.ProfessionalColorsToolStripDropDownBackgroundDescr)] public static Color ToolStripDropDownBackground { get { return ColorTable.ToolStripDropDownBackground; } } [SRDescription(SR.ProfessionalColorsToolStripGradientBeginDescr)] public static Color ToolStripGradientBegin { get { return ColorTable.ToolStripGradientBegin; } } [SRDescription(SR.ProfessionalColorsToolStripGradientMiddleDescr)] public static Color ToolStripGradientMiddle { get { return ColorTable.ToolStripGradientMiddle; } } [SRDescription(SR.ProfessionalColorsToolStripGradientEndDescr)] public static Color ToolStripGradientEnd { get { return ColorTable.ToolStripGradientEnd; } } [SRDescription(SR.ProfessionalColorsToolStripContentPanelGradientBeginDescr)] public static Color ToolStripContentPanelGradientBegin { get { return ColorTable.ToolStripContentPanelGradientBegin; } } [SRDescription(SR.ProfessionalColorsToolStripContentPanelGradientEndDescr)] public static Color ToolStripContentPanelGradientEnd { get { return ColorTable.ToolStripContentPanelGradientEnd; } } [SRDescription(SR.ProfessionalColorsToolStripPanelGradientBeginDescr)] public static Color ToolStripPanelGradientBegin { get { return ColorTable.ToolStripPanelGradientBegin; } } [SRDescription(SR.ProfessionalColorsToolStripPanelGradientEndDescr)] public static Color ToolStripPanelGradientEnd { get { return ColorTable.ToolStripPanelGradientEnd; } } [SRDescription(SR.ProfessionalColorsOverflowButtonGradientBeginDescr)] public static Color OverflowButtonGradientBegin { get { return ColorTable.OverflowButtonGradientBegin; } } [SRDescription(SR.ProfessionalColorsOverflowButtonGradientMiddleDescr)] public static Color OverflowButtonGradientMiddle { get { return ColorTable.OverflowButtonGradientMiddle; } } [SRDescription(SR.ProfessionalColorsOverflowButtonGradientEndDescr)] public static Color OverflowButtonGradientEnd { get { return ColorTable.OverflowButtonGradientEnd; } } #endregion Colors /* public static Color ControlLight { get { return FromKnownColor(KnownColors.msocbvcrCBCtlBkgdLight); } } */ private static void OnUserPreferenceChanged(object sender, UserPreferenceChangedEventArgs e) { SetScheme(); if (e.Category == UserPreferenceCategory.Color) { colorFreshnessKey = new object(); } } private static void SetScheme() { if (VisualStyleRenderer.IsSupported) { colorScheme = VisualStyleInformation.ColorScheme; } else { colorScheme = null; } } } }
using System; using System.Collections; using System.Collections.Generic; namespace ClosedXML.Excel { using System.Linq; internal class XLCells : XLStylizedBase, IXLCells, IXLStylized, IEnumerable<XLCell> { #region Fields private readonly List<XLRangeAddress> _rangeAddresses = new List<XLRangeAddress>(); private readonly bool _usedCellsOnly; private readonly Func<IXLCell, Boolean> _predicate; private readonly XLCellsUsedOptions _options; private bool _styleInitialized = false; #endregion Fields #region Constructor public XLCells(bool usedCellsOnly, XLCellsUsedOptions options, Func<IXLCell, Boolean> predicate = null) : base(XLStyle.Default.Value) { _usedCellsOnly = usedCellsOnly; _options = options; _predicate = predicate ?? (_ => true); } #endregion Constructor #region IEnumerable<XLCell> Members private IEnumerable<XLCell> GetAllCells() { var grouppedAddresses = _rangeAddresses.GroupBy(addr => addr.Worksheet); foreach (var worksheetGroup in grouppedAddresses) { var ws = worksheetGroup.Key; var sheetPoints = worksheetGroup.SelectMany(addr => GetAllCellsInRange(addr)) .Distinct(); foreach (var sheetPoint in sheetPoints) { var c = ws.Cell(sheetPoint.Row, sheetPoint.Column); if (_predicate(c)) yield return c; } } } private IEnumerable<XLSheetPoint> GetAllCellsInRange(IXLRangeAddress rangeAddress) { if (!rangeAddress.IsValid) yield break; var normalizedAddress = ((XLRangeAddress)rangeAddress).Normalize(); var minRow = normalizedAddress.FirstAddress.RowNumber; var maxRow = normalizedAddress.LastAddress.RowNumber; var minColumn = normalizedAddress.FirstAddress.ColumnNumber; var maxColumn = normalizedAddress.LastAddress.ColumnNumber; for (var ro = minRow; ro <= maxRow; ro++) { for (var co = minColumn; co <= maxColumn; co++) { yield return new XLSheetPoint(ro, co); } } } private IEnumerable<XLCell> GetUsedCells() { var grouppedAddresses = _rangeAddresses.GroupBy(addr => addr.Worksheet); foreach (var worksheetGroup in grouppedAddresses) { var ws = worksheetGroup.Key; var usedCellsCandidates = GetUsedCellsCandidates(ws); var cells = worksheetGroup.SelectMany(addr => GetUsedCellsInRange(addr, ws, usedCellsCandidates)) .OrderBy(cell => cell.Address.RowNumber) .ThenBy(cell => cell.Address.ColumnNumber); var visitedCells = new HashSet<XLAddress>(); foreach (var cell in cells) { if (visitedCells.Contains(cell.Address)) continue; visitedCells.Add(cell.Address); yield return cell; } } } private IEnumerable<XLCell> GetUsedCellsInRange(XLRangeAddress rangeAddress, XLWorksheet worksheet, IEnumerable<XLSheetPoint> usedCellsCandidates) { if (!rangeAddress.IsValid) yield break; var normalizedAddress = rangeAddress.Normalize(); var minRow = normalizedAddress.FirstAddress.RowNumber; var maxRow = normalizedAddress.LastAddress.RowNumber; var minColumn = normalizedAddress.FirstAddress.ColumnNumber; var maxColumn = normalizedAddress.LastAddress.ColumnNumber; var cellRange = worksheet.Internals.CellsCollection .GetCells(minRow, minColumn, maxRow, maxColumn, _predicate) .Where(c => !c.IsEmpty(_options)); foreach (var cell in cellRange) { if (_predicate(cell)) yield return cell; } foreach (var sheetPoint in usedCellsCandidates) { if (sheetPoint.Row.Between(minRow, maxRow) && sheetPoint.Column.Between(minColumn, maxColumn)) { var cell = worksheet.Cell(sheetPoint.Row, sheetPoint.Column); if (_predicate(cell)) yield return cell; } } } private IEnumerable<XLSheetPoint> GetUsedCellsCandidates(XLWorksheet worksheet) { var candidates = Enumerable.Empty<XLSheetPoint>(); if (_options.HasFlag(XLCellsUsedOptions.MergedRanges)) candidates = candidates.Union( worksheet.Internals.MergedRanges.SelectMany(r => GetAllCellsInRange(r.RangeAddress))); if (_options.HasFlag(XLCellsUsedOptions.ConditionalFormats)) candidates = candidates.Union( worksheet.ConditionalFormats.SelectMany(cf => cf.Ranges.SelectMany(r => GetAllCellsInRange(r.RangeAddress)))); if (_options.HasFlag(XLCellsUsedOptions.DataValidation)) candidates = candidates.Union( worksheet.DataValidations.SelectMany(dv => dv.Ranges.SelectMany(r => GetAllCellsInRange(r.RangeAddress)))); return candidates.Distinct(); } public IEnumerator<XLCell> GetEnumerator() { var cells = (_usedCellsOnly) ? GetUsedCells() : GetAllCells(); foreach (var cell in cells) { yield return cell; } } #endregion IEnumerable<XLCell> Members #region IXLCells Members IEnumerator<IXLCell> IEnumerable<IXLCell>.GetEnumerator() { foreach (XLCell cell in this) yield return cell; } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public Object Value { set { this.ForEach<XLCell>(c => c.Value = value); } } public IXLCells SetDataType(XLDataType dataType) { this.ForEach<XLCell>(c => c.DataType = dataType); return this; } public XLDataType DataType { set { this.ForEach<XLCell>(c => c.DataType = value); } } public IXLCells Clear(XLClearOptions clearOptions = XLClearOptions.All) { this.ForEach<XLCell>(c => c.Clear(clearOptions)); return this; } public void DeleteComments() { this.ForEach<XLCell>(c => c.DeleteComment()); } public void DeleteSparklines() { this.ForEach<XLCell>(c => c.DeleteSparkline()); } public String FormulaA1 { set { this.ForEach<XLCell>(c => c.FormulaA1 = value); } } public String FormulaR1C1 { set { this.ForEach<XLCell>(c => c.FormulaR1C1 = value); } } #endregion IXLCells Members #region IXLStylized Members public override IEnumerable<IXLStyle> Styles { get { yield return Style; foreach (XLCell c in this) yield return c.Style; } } protected override IEnumerable<XLStylizedBase> Children { get { foreach (XLCell c in this) yield return c; } } public override IXLRanges RangesUsed { get { var retVal = new XLRanges(); this.ForEach<XLCell>(c => retVal.Add(c.AsRange())); return retVal; } } #endregion IXLStylized Members public void Add(XLRangeAddress rangeAddress) { _rangeAddresses.Add(rangeAddress); if (_styleInitialized) return; var worksheetStyle = rangeAddress.Worksheet?.Style; if (worksheetStyle == null) return; InnerStyle = worksheetStyle; _styleInitialized = true; } public void Add(XLCell cell) { Add(new XLRangeAddress(cell.Address, cell.Address)); } public void Select() { foreach (var cell in this) cell.Select(); } } }
namespace Ioke.Lang { using System.Collections; using System.Collections.Generic; using Ioke.Lang.Util; public class LexicalMacro : IokeData, AssociatedCode, Named, Inspectable { internal string name; IokeObject context; IokeObject code; public LexicalMacro(IokeObject context, IokeObject code) : base(IokeData.TYPE_LEXICAL_MACRO) { this.context = context; this.code = code; } public LexicalMacro(string name) : base(IokeData.TYPE_LEXICAL_MACRO) { this.name = name; } public override void Init(IokeObject obj) { obj.Kind = "LexicalMacro"; obj.SetActivatable(true); obj.RegisterMethod(obj.runtime.NewNativeMethod("returns the name of the lecro", new NativeMethod.WithNoArguments("name", (method, _context, message, on, outer) => { outer.ArgumentsDefinition.GetEvaluatedArguments(_context, message, on, new SaneArrayList(), new SaneDictionary<string, object>()); return _context.runtime.NewText(((LexicalMacro)IokeObject.dataOf(on)).name); }))); obj.RegisterMethod(obj.runtime.NewNativeMethod("activates this lecro with the arguments given to call", new NativeMethod("call", DefaultArgumentsDefinition.builder() .WithRestUnevaluated("arguments") .Arguments, (method, _context, message, on, outer) => { return Interpreter.Activate(IokeObject.As(on, _context), _context, message, _context.RealContext); }))); obj.RegisterMethod(obj.runtime.NewNativeMethod("returns the message chain for this lecro", new NativeMethod.WithNoArguments("message", (method, _context, message, on, outer) => { outer.ArgumentsDefinition.GetEvaluatedArguments(_context, message, on, new SaneArrayList(), new SaneDictionary<string, object>()); return ((AssociatedCode)IokeObject.dataOf(on)).Code; }))); obj.RegisterMethod(obj.runtime.NewNativeMethod("returns the code for the argument definition", new NativeMethod.WithNoArguments("argumentsCode", (method, _context, message, on, outer) => { outer.ArgumentsDefinition.GetEvaluatedArguments(_context, message, on, new SaneArrayList(), new SaneDictionary<string, object>()); return _context.runtime.NewText(((AssociatedCode)IokeObject.dataOf(on)).ArgumentsCode); }))); obj.RegisterMethod(obj.runtime.NewNativeMethod("Returns a text inspection of the object", new NativeMethod.WithNoArguments("inspect", (method, _context, message, on, outer) => { outer.ArgumentsDefinition.GetEvaluatedArguments(_context, message, on, new SaneArrayList(), new SaneDictionary<string, object>()); return _context.runtime.NewText(LexicalMacro.GetInspect(on)); }))); obj.RegisterMethod(obj.runtime.NewNativeMethod("Returns a brief text inspection of the object", new NativeMethod.WithNoArguments("notice", (method, _context, message, on, outer) => { outer.ArgumentsDefinition.GetEvaluatedArguments(_context, message, on, new SaneArrayList(), new SaneDictionary<string, object>()); return _context.runtime.NewText(LexicalMacro.GetNotice(on)); }))); obj.RegisterMethod(obj.runtime.NewNativeMethod("returns the full code of this lecro, as a Text", new NativeMethod.WithNoArguments("code", (method, _context, message, on, outer) => { outer.ArgumentsDefinition.GetEvaluatedArguments(_context, message, on, new SaneArrayList(), new SaneDictionary<string, object>()); IokeData data = IokeObject.dataOf(on); if(data is LexicalMacro) { return _context.runtime.NewText(((LexicalMacro)data).CodeString(on)); } else { return _context.runtime.NewText(((AliasMethod)data).CodeString); } }))); obj.RegisterMethod(obj.runtime.NewNativeMethod("returns idiomatically formatted code for this lecro", new NativeMethod.WithNoArguments("formattedCode", (method, _context, message, on, outer) => { outer.ArgumentsDefinition.GetEvaluatedArguments(_context, message, on, new SaneArrayList(), new SaneDictionary<string, object>()); return _context.runtime.NewText(((AssociatedCode)IokeObject.dataOf(on)).FormattedCode(method)); }))); } public IokeObject Code { get { return code; } } public string CodeString(object self) { if(IokeObject.As(self, null).IsActivatable) { return "lecro(" + Message.Code(code) + ")"; } else { return "lecrox(" + Message.Code(code) + ")"; } } public string FormattedCode(object self) { if(IokeObject.As(self, (IokeObject)self).IsActivatable) { return "lecro(\n " + Message.FormattedCode(code, 2, (IokeObject)self) + ")"; } else { return "lecrox(\n " + Message.FormattedCode(code, 2, (IokeObject)self) + ")"; } } public string ArgumentsCode { get { return "..."; } } public string Name { get { return name; } set { this.name = value; } } public static string GetInspect(object on) { return ((Inspectable)(IokeObject.dataOf(on))).Inspect(on); } public static string GetNotice(object on) { return ((Inspectable)(IokeObject.dataOf(on))).Notice(on); } public string Inspect(object self) { string type = "lecro"; if(!IokeObject.As(self, null).IsActivatable) { type = "lecrox"; } if(name == null) { return type + "(" + Message.Code(code) + ")"; } else { return name + ":" + type + "(" + Message.Code(code) + ")"; } } public string Notice(object self) { string type = "lecro"; if(!IokeObject.As(self, null).IsActivatable) { type = "lecrox"; } if(name == null) { return type + "(...)"; } else { return name + ":" + type + "(...)"; } } public static object ActivateWithCallAndDataFixed(IokeObject self, IokeObject dynamicContext, IokeObject message, object on, object call, IDictionary<string, object> data) { LexicalMacro lm = (LexicalMacro)self.data; if(lm.code == null) { IokeObject condition = IokeObject.As(IokeObject.GetCellChain(dynamicContext.runtime.Condition, message, dynamicContext, "Error", "Invocation", "NotActivatable"), dynamicContext).Mimic(message, dynamicContext); condition.SetCell("message", message); condition.SetCell("context", dynamicContext); condition.SetCell("receiver", on); condition.SetCell("method", self); condition.SetCell("report", dynamicContext.runtime.NewText("You tried to activate a method without any code - did you by any chance activate the LexicalMacro kind by referring to it without wrapping it inside a call to cell?")); dynamicContext.runtime.ErrorCondition(condition); return null; } IokeObject c = self.runtime.NewLexicalContext(on, "Lexical macro activation context", lm.context); c.SetCell("outerScope", lm.context); c.SetCell("call", call); foreach(var d in data) { string s = d.Key; c.SetCell(s.Substring(0, s.Length-1), d.Value); } return self.runtime.interpreter.Evaluate(lm.code, c, on, c); } public new static object ActivateFixed(IokeObject self, IokeObject dynamicContext, IokeObject message, object on) { LexicalMacro lm = (LexicalMacro)self.data; if(lm.code == null) { IokeObject condition = IokeObject.As(IokeObject.GetCellChain(dynamicContext.runtime.Condition, message, dynamicContext, "Error", "Invocation", "NotActivatable"), dynamicContext).Mimic(message, dynamicContext); condition.SetCell("message", message); condition.SetCell("context", dynamicContext); condition.SetCell("receiver", on); condition.SetCell("method", self); condition.SetCell("report", dynamicContext.runtime.NewText("You tried to activate a method without any code - did you by any chance activate the LexicalMacro kind by referring to it without wrapping it inside a call to cell?")); dynamicContext.runtime.ErrorCondition(condition); return null; } IokeObject c = self.runtime.NewLexicalContext(on, "Lexical macro activation context", lm.context); c.SetCell("outerScope", lm.context); c.SetCell("call", dynamicContext.runtime.NewCallFrom(c, message, dynamicContext, IokeObject.As(on, dynamicContext))); return self.runtime.interpreter.Evaluate(lm.code, c, on, c); } public static object ActivateWithDataFixed(IokeObject self, IokeObject dynamicContext, IokeObject message, object on, IDictionary<string, object> data) { LexicalMacro lm = (LexicalMacro)self.data; if(lm.code == null) { IokeObject condition = IokeObject.As(IokeObject.GetCellChain(dynamicContext.runtime.Condition, message, dynamicContext, "Error", "Invocation", "NotActivatable"), dynamicContext).Mimic(message, dynamicContext); condition.SetCell("message", message); condition.SetCell("context", dynamicContext); condition.SetCell("receiver", on); condition.SetCell("method", self); condition.SetCell("report", dynamicContext.runtime.NewText("You tried to activate a method without any code - did you by any chance activate the LexicalMacro kind by referring to it without wrapping it inside a call to cell?")); dynamicContext.runtime.ErrorCondition(condition); return null; } IokeObject c = self.runtime.NewLexicalContext(on, "Lexical macro activation context", lm.context); c.SetCell("outerScope", lm.context); c.SetCell("call", dynamicContext.runtime.NewCallFrom(c, message, dynamicContext, IokeObject.As(on, dynamicContext))); foreach(var d in data) { string s = d.Key; c.SetCell(s.Substring(0, s.Length-1), d.Value); } return self.runtime.interpreter.Evaluate(lm.code, c, on, c); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; namespace System.IO.Tests { public class Directory_Delete_str : FileSystemTest { #region Utilities public virtual void Delete(string path) { Directory.Delete(path); } #endregion #region UniversalTests [Fact] public void NullParameters() { Assert.Throws<ArgumentNullException>(() => Delete(null)); } [Fact] public void InvalidParameters() { Assert.Throws<ArgumentException>(() => Delete(string.Empty)); } [Fact] public void ShouldThrowIOExceptionIfContainedFileInUse() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); using (File.Create(Path.Combine(testDir.FullName, GetTestFileName()))) { Assert.Throws<IOException>(() => Delete(testDir.FullName)); } Assert.True(testDir.Exists); } [Fact] public void ShouldThrowIOExceptionForDirectoryWithFiles() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); File.Create(Path.Combine(testDir.FullName, GetTestFileName())).Dispose(); Assert.Throws<IOException>(() => Delete(testDir.FullName)); Assert.True(testDir.Exists); } [Fact] public void DirectoryWithSubdirectories() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); testDir.CreateSubdirectory(GetTestFileName()); Assert.Throws<IOException>(() => Delete(testDir.FullName)); Assert.True(testDir.Exists); } [Fact] [OuterLoop] public void DeleteRoot() { Assert.Throws<IOException>(() => Delete(Path.GetPathRoot(Directory.GetCurrentDirectory()))); } [Fact] public void PositiveTest() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); Delete(testDir.FullName); Assert.False(testDir.Exists); } [Fact] public void ShouldThrowDirectoryNotFoundExceptionForNonexistentDirectory() { Assert.Throws<DirectoryNotFoundException>(() => Delete(GetTestFilePath())); } [Fact] public void ShouldThrowIOExceptionDeletingCurrentDirectory() { Assert.Throws<IOException>(() => Delete(Directory.GetCurrentDirectory())); } [ConditionalFact(nameof(CanCreateSymbolicLinks))] public void DeletingSymLinkDoesntDeleteTarget() { var path = GetTestFilePath(); var linkPath = GetTestFilePath(); Directory.CreateDirectory(path); Assert.True(MountHelper.CreateSymbolicLink(linkPath, path, isDirectory: true)); // Both the symlink and the target exist Assert.True(Directory.Exists(path), "path should exist"); Assert.True(Directory.Exists(linkPath), "linkPath should exist"); // Delete the symlink Directory.Delete(linkPath); // Target should still exist Assert.True(Directory.Exists(path), "path should still exist"); Assert.False(Directory.Exists(linkPath), "linkPath should no longer exist"); } #endregion #region PlatformSpecific [Fact] [PlatformSpecific(PlatformID.Windows)] public void WindowsExtendedDirectoryWithSubdirectories() { DirectoryInfo testDir = Directory.CreateDirectory(IOInputs.ExtendedPrefix + GetTestFilePath()); testDir.CreateSubdirectory(GetTestFileName()); Assert.Throws<IOException>(() => Delete(testDir.FullName)); Assert.True(testDir.Exists); } [Fact] [PlatformSpecific(PlatformID.Windows)] public void WindowsLongPathExtendedDirectory() { DirectoryInfo testDir = Directory.CreateDirectory(IOServices.GetPath(IOInputs.ExtendedPrefix + TestDirectory, characterCount: 500).FullPath); Delete(testDir.FullName); Assert.False(testDir.Exists); } [Fact] [PlatformSpecific(PlatformID.Windows)] public void WindowsDeleteReadOnlyDirectory() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); testDir.Attributes = FileAttributes.ReadOnly; Assert.Throws<IOException>(() => Delete(testDir.FullName)); Assert.True(testDir.Exists); testDir.Attributes = FileAttributes.Normal; } [Fact] [PlatformSpecific(PlatformID.Windows)] public void WindowsDeleteExtendedReadOnlyDirectory() { DirectoryInfo testDir = Directory.CreateDirectory(IOInputs.ExtendedPrefix + GetTestFilePath()); testDir.Attributes = FileAttributes.ReadOnly; Assert.Throws<IOException>(() => Delete(testDir.FullName)); Assert.True(testDir.Exists); testDir.Attributes = FileAttributes.Normal; } [Fact] [PlatformSpecific(PlatformID.AnyUnix)] public void UnixDeleteReadOnlyDirectory() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); testDir.Attributes = FileAttributes.ReadOnly; Delete(testDir.FullName); Assert.False(testDir.Exists); } [Fact] [PlatformSpecific(PlatformID.Windows)] public void WindowsShouldBeAbleToDeleteHiddenDirectory() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); testDir.Attributes = FileAttributes.Hidden; Delete(testDir.FullName); Assert.False(testDir.Exists); } [Fact] [PlatformSpecific(PlatformID.Windows)] public void WindowsShouldBeAbleToDeleteExtendedHiddenDirectory() { DirectoryInfo testDir = Directory.CreateDirectory(IOInputs.ExtendedPrefix + GetTestFilePath()); testDir.Attributes = FileAttributes.Hidden; Delete(testDir.FullName); Assert.False(testDir.Exists); } [Fact] [PlatformSpecific(PlatformID.AnyUnix)] public void UnixShouldBeAbleToDeleteHiddenDirectory() { string testDir = "." + GetTestFileName(); Directory.CreateDirectory(Path.Combine(TestDirectory, testDir)); Assert.True(0 != (new DirectoryInfo(Path.Combine(TestDirectory, testDir)).Attributes & FileAttributes.Hidden)); Delete(Path.Combine(TestDirectory, testDir)); Assert.False(Directory.Exists(testDir)); } #endregion } public class Directory_Delete_str_bool : Directory_Delete_str { #region Utilities public override void Delete(string path) { Directory.Delete(path, false); } public virtual void Delete(string path, bool recursive) { Directory.Delete(path, recursive); } #endregion [Fact] public void RecursiveDelete() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); File.Create(Path.Combine(testDir.FullName, GetTestFileName())).Dispose(); testDir.CreateSubdirectory(GetTestFileName()); Delete(testDir.FullName, true); Assert.False(testDir.Exists); } [Fact] public void RecursiveDeleteWithTrailingSlash() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); Delete(testDir.FullName + Path.DirectorySeparatorChar, true); Assert.False(testDir.Exists); } [Fact] [PlatformSpecific(PlatformID.Windows)] public void RecursiveDelete_ShouldThrowIOExceptionIfContainedFileInUse() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); using (File.Create(Path.Combine(testDir.FullName, GetTestFileName()))) { Assert.Throws<IOException>(() => Delete(testDir.FullName, true)); } Assert.True(testDir.Exists); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Text; using System.Xml; using System.Xml.Schema; using System.IO; using System.Reflection; using System.Diagnostics; using System.Runtime.Serialization; using System.Security.Permissions; using System.Globalization; //using System.Workflow.Activities; using System.Workflow.ComponentModel; using System.Workflow.Runtime; using System.Workflow.Runtime.Hosting; using Hosting = System.Workflow.Runtime.Hosting; namespace System.Workflow.Runtime.Tracking { [Obsolete("The System.Workflow.* types are deprecated. Instead, please use the new types from System.Activities.*")] public sealed class ActivityTrackPoint { #region Private Data Members private ActivityTrackingLocationCollection _match = new ActivityTrackingLocationCollection(); private ActivityTrackingLocationCollection _exclude = new ActivityTrackingLocationCollection(); private TrackingAnnotationCollection _annotations = new TrackingAnnotationCollection(); private ExtractCollection _extracts = new ExtractCollection(); #endregion #region Public Properties public ActivityTrackingLocationCollection MatchingLocations { get { return _match; } } public ActivityTrackingLocationCollection ExcludedLocations { get { return _exclude; } } public TrackingAnnotationCollection Annotations { get { return _annotations; } } public ExtractCollection Extracts { get { return _extracts; } } #endregion #region Internal Matching Methods internal bool IsMatch(Activity activity, out List<ActivityExecutionStatus> status, out bool hasCondition) { hasCondition = false; // // Check if we have any conditions on this track point. // If we do signal that we need to recheck this item for each activity event (can't cache) foreach (ActivityTrackingLocation location in _exclude) { if ((null != location.Conditions) && (location.Conditions.Count > 0)) { hasCondition = true; break; } } foreach (ActivityTrackingLocation location in _match) { if ((null != location.Conditions) && (location.Conditions.Count > 0)) { hasCondition = true; break; } } status = new List<ActivityExecutionStatus>(9); // // Do matches first foreach (ActivityTrackingLocation location in _match) { if (location.Match(activity, true)) { // // Insert all status values for this location foreach (ActivityExecutionStatus s in location.ExecutionStatusEvents) { if (!status.Contains(s)) status.Add(s); } } } // // If no includes matched // this trackpoint isn't relevant to this activity if (0 == status.Count) return false; // // Check the excludes but only if there aren't any conditions if (!hasCondition) { foreach (ActivityTrackingLocation location in _exclude) { if (location.Match(activity, true)) { // // Remove all status values for this location foreach (ActivityExecutionStatus s in location.ExecutionStatusEvents) status.Remove(s); } } } return (status.Count > 0); } internal bool IsMatch(Activity activity, ActivityExecutionStatus status) { // // Do matches first bool included = false; foreach (ActivityTrackingLocation location in _match) { if (location.Match(activity, false)) { if (location.ExecutionStatusEvents.Contains(status)) { included = true; break; } } } // // If no includes matched this trackpoint // doesn't match this activity if (!included) return false; // // Check the excludes foreach (ActivityTrackingLocation location in _exclude) { // // If any exclude matches this trackpoint // doesn't match this activity if (location.Match(activity, false)) { if (location.ExecutionStatusEvents.Contains(status)) return false; } } return included; } internal void Track(Activity activity, IServiceProvider provider, IList<TrackingDataItem> items) { foreach (TrackingExtract e in _extracts) e.GetData(activity, provider, items); } #endregion } [Obsolete("The System.Workflow.* types are deprecated. Instead, please use the new types from System.Activities.*")] public sealed class UserTrackPoint { #region Private Data Members private UserTrackingLocationCollection _match = new UserTrackingLocationCollection(); private UserTrackingLocationCollection _exclude = new UserTrackingLocationCollection(); private TrackingAnnotationCollection _annotations = new TrackingAnnotationCollection(); private ExtractCollection _extracts = new ExtractCollection(); #endregion #region Public Properties public UserTrackingLocationCollection MatchingLocations { get { return _match; } } public UserTrackingLocationCollection ExcludedLocations { get { return _exclude; } } public TrackingAnnotationCollection Annotations { get { return _annotations; } } public ExtractCollection Extracts { get { return _extracts; } } #endregion #region Internal Matching Methods internal bool IsMatch(Activity activity) { // // Check include, excludes checked at event time foreach (UserTrackingLocation location in _match) if (location.Match(activity)) return true; return false; } internal bool IsMatch(Activity activity, string keyName, object argument) { // // We need to check runtime values here // // Check the excludes - if any exclude matches based on activity, key and arg type we're not a match foreach (UserTrackingLocation location in _exclude) if (location.Match(activity, keyName, argument)) return false; // // No excludes match, check includes foreach (UserTrackingLocation location in _match) if (location.Match(activity, keyName, argument)) return true; return false; } internal void Track(Activity activity, object arg, IServiceProvider provider, IList<TrackingDataItem> items) { foreach (TrackingExtract e in _extracts) e.GetData(activity, provider, items); } #endregion } [Obsolete("The System.Workflow.* types are deprecated. Instead, please use the new types from System.Activities.*")] public sealed class WorkflowTrackPoint { #region Private Data Members private WorkflowTrackingLocation _location = new WorkflowTrackingLocation(); private TrackingAnnotationCollection _annotations = new TrackingAnnotationCollection(); #endregion #region Public Properties public WorkflowTrackingLocation MatchingLocation { get { return _location; } set { _location = value; } } public TrackingAnnotationCollection Annotations { get { return _annotations; } } #endregion #region Internal Matching Methods internal bool IsMatch(TrackingWorkflowEvent status) { return _location.Match(status); } #endregion } }
using System.Collections.Generic; using Loon.Utils; using Loon.Java.Collections; using Loon.Core.Timer; namespace Loon.Action.Sprite.Painting { public sealed class GameComponentCollection { public sealed class GameComponent_0 : IComparer<IGameComponent> { public int Compare(IGameComponent one, IGameComponent two) { if (one is DrawableGameComponent && two is DrawableGameComponent) { return ((DrawableGameComponent) one).GetDrawOrder() - ((DrawableGameComponent) two).GetDrawOrder(); } return 0; } } public sealed class GameComponent_1 : IComparer<IGameComponent> { public int Compare(IGameComponent one, IGameComponent two) { if (one is GameComponent && two is GameComponent) { return ((GameComponent) one).GetUpdateOrder() - ((GameComponent) two).GetUpdateOrder(); } return 0; } } private List<IGameComponent> collections; private List<IGameComponent> collectionsToUpdate; private List<IGameComponent> collectionsToDraw; private IComparer<IGameComponent> igameDrawComparator = new GameComponentCollection.GameComponent_0(); private IComparer<IGameComponent> igameUpdateComparator = new GameComponentCollection.GameComponent_1(); public GameComponentCollection() { this.collections = new List<IGameComponent>(); this.collectionsToUpdate = new List<IGameComponent>(); this.collectionsToDraw = new List<IGameComponent>(); } public int Size() { return collections.Count; } public void SortDraw() { Arrays.Sort(collections,igameDrawComparator); } public void SortUpdate() { Arrays.Sort(collections, igameUpdateComparator); } public List<IGameComponent> List() { return new List<IGameComponent>(collections); } public IGameComponent Get(int idx) { return collections[idx]; } internal void Draw(SpriteBatch batch, GameTime gameTime) { if (isClear) { return; } if (collectionsToDraw.Count > 0) { CollectionUtils.Clear(collectionsToDraw); } foreach (IGameComponent drawable in collections) { CollectionUtils.Add(collectionsToDraw,drawable); } foreach (IGameComponent drawable in collectionsToDraw) { if (drawable is IDrawable) { IDrawable comp = (IDrawable) drawable; comp.Draw(batch, gameTime); } } } internal void Load() { isClear = false; foreach (IGameComponent comp in collections) { comp.Initialize(); } } internal void Update(GameTime gameTime) { if (isClear) { return; } if (collectionsToUpdate.Count > 0) { CollectionUtils.Clear(collectionsToUpdate); } foreach (IGameComponent drawable in collections) { CollectionUtils.Add(collectionsToUpdate,drawable); } IGameComponent _drawable; int screenIndex; for (; collectionsToUpdate.Count > 0;) { screenIndex = collectionsToUpdate.Count - 1; _drawable = collectionsToUpdate[screenIndex]; CollectionUtils.RemoveAt(collectionsToUpdate,screenIndex); if (_drawable is IUpdateable) { IUpdateable comp = (IUpdateable)_drawable; comp.Update(gameTime); } } } private bool isClear; public void Clear() { if (!isClear) { lock (typeof(GameComponentCollection)) { CollectionUtils.Clear(collections); CollectionUtils.Clear(collectionsToUpdate); CollectionUtils.Clear(collectionsToDraw); isClear = true; } } } public bool Add(IGameComponent gc) { if (isClear) { return false; } gc.Initialize(); bool result = CollectionUtils.Add(collections,gc); if (gc != null && Added != null) { Added.Invoke(gc); } if (gc is DrawableGameComponent) { if (((DrawableGameComponent) gc).GetDrawOrder() != 0) { SortDraw(); } } return result; } public bool Add(IGameComponent gc, int index) { if (isClear) { return false; } gc.Initialize(); bool result = CollectionUtils.Add(collections,gc); for (int i = 0; i < collections.Count; i++) { if (collections[i] is DrawableGameComponent) { if (i == index) { ((DrawableGameComponent) collections[i]) .SetEnabled(true); } else { ((DrawableGameComponent) collections[i]) .SetEnabled(false); } } } if (gc != null && Added != null) { Added.Invoke(gc); } if (gc is DrawableGameComponent) { if (((DrawableGameComponent) gc).GetDrawOrder() != 0) { SortDraw(); } } return result; } public bool Remove(IGameComponent gc) { if (isClear) { return false; } bool result = false; if (gc != null && gc is DrawableGameComponent) { DrawableGameComponent comp = (DrawableGameComponent) gc; comp.UnloadContent(); result = CollectionUtils.Remove(collections,gc); CollectionUtils.Remove(collectionsToUpdate,gc); if (Removed != null) { Removed.Invoke(gc); } } return result; } public bool RemoveAt(int idx) { if (isClear) { return false; } IGameComponent comp = (IGameComponent)CollectionUtils.RemoveAt(collections, idx); bool result = (comp != null); if (result) { if (comp is DrawableGameComponent) { ((DrawableGameComponent) comp).UnloadContent(); } CollectionUtils.Remove(collectionsToUpdate,comp); if (Removed != null) { Removed.Invoke(comp); } } return result; } private ComponentEvent Added; private ComponentEvent Removed; public ComponentEvent GetAdded() { return Added; } public void SetAdded(ComponentEvent added) { Added = added; } public ComponentEvent GetRemoved() { return Removed; } public void SetRemoved(ComponentEvent removed) { Removed = removed; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Web; using NUnit.Framework; using Umbraco.Core; using Umbraco.Core.Dynamics; using Umbraco.Tests.TestHelpers; namespace Umbraco.Tests.PublishedContent { [TestFixture] public abstract class DynamicDocumentTestsBase<TDocument, TDocumentList> : PublishedContentTestBase { protected override DatabaseBehavior DatabaseTestBehavior { get { return DatabaseBehavior.NoDatabasePerFixture; } } protected override string GetXmlContent(int templateId) { return @"<?xml version=""1.0"" encoding=""utf-8""?> <!DOCTYPE root[ <!ELEMENT Home ANY> <!ATTLIST Home id ID #REQUIRED> <!ELEMENT CustomDocument ANY> <!ATTLIST CustomDocument id ID #REQUIRED> ]> <root id=""-1""> <Home id=""1046"" parentID=""-1"" level=""1"" writerID=""0"" creatorID=""0"" nodeType=""1044"" template=""" + templateId + @""" sortOrder=""1"" createDate=""2012-06-12T14:13:17"" updateDate=""2012-07-20T18:50:43"" nodeName=""Home"" urlName=""home"" writerName=""admin"" creatorName=""admin"" path=""-1,1046"" isDoc=""""> <content><![CDATA[]]></content> <umbracoUrlAlias><![CDATA[this/is/my/alias, anotheralias]]></umbracoUrlAlias> <umbracoNaviHide>1</umbracoNaviHide> <siteTitle><![CDATA[This is my site]]></siteTitle> <Home id=""1173"" parentID=""1046"" level=""2"" writerID=""0"" creatorID=""0"" nodeType=""1044"" template=""" + templateId + @""" sortOrder=""2"" createDate=""2012-07-20T18:06:45"" updateDate=""2012-07-20T19:07:31"" nodeName=""Sub1"" urlName=""sub1"" writerName=""admin"" creatorName=""admin"" path=""-1,1046,1173"" isDoc=""""> <content><![CDATA[<div>This is some content</div>]]></content> <umbracoUrlAlias><![CDATA[page2/alias, 2ndpagealias]]></umbracoUrlAlias> <Home id=""1174"" parentID=""1173"" level=""3"" writerID=""0"" creatorID=""0"" nodeType=""1044"" template=""" + templateId + @""" sortOrder=""1"" createDate=""2012-07-20T18:07:54"" updateDate=""2012-07-20T19:10:27"" nodeName=""Sub2"" urlName=""sub2"" writerName=""admin"" creatorName=""admin"" path=""-1,1046,1173,1174"" isDoc=""""> <content><![CDATA[]]></content> <umbracoUrlAlias><![CDATA[only/one/alias]]></umbracoUrlAlias> <creatorName><![CDATA[Custom data with same property name as the member name]]></creatorName> </Home> <CustomDocument id=""1177"" parentID=""1173"" level=""3"" writerID=""0"" creatorID=""0"" nodeType=""1234"" template=""" + templateId + @""" sortOrder=""2"" createDate=""2012-07-16T15:26:59"" updateDate=""2012-07-18T14:23:35"" nodeName=""custom sub 1"" urlName=""custom-sub-1"" writerName=""admin"" creatorName=""admin"" path=""-1,1046,1173,1177"" isDoc="""" /> <CustomDocument id=""1178"" parentID=""1173"" level=""3"" writerID=""0"" creatorID=""0"" nodeType=""1234"" template=""" + templateId + @""" sortOrder=""3"" createDate=""2012-07-16T15:26:59"" updateDate=""2012-07-16T14:23:35"" nodeName=""custom sub 2"" urlName=""custom-sub-2"" writerName=""admin"" creatorName=""admin"" path=""-1,1046,1173,1178"" isDoc="""" /> <Home id=""1176"" parentID=""1173"" level=""3"" writerID=""0"" creatorID=""0"" nodeType=""1044"" template=""" + templateId + @""" sortOrder=""4"" createDate=""2012-07-20T18:08:08"" updateDate=""2012-07-20T19:10:52"" nodeName=""Sub 3"" urlName=""sub-3"" writerName=""admin"" creatorName=""admin"" path=""-1,1046,1173,1176"" isDoc=""""> <content><![CDATA[some content]]></content> <blah><![CDATA[some content]]></blah> <umbracoNaviHide>1</umbracoNaviHide> </Home> </Home> <Home id=""1175"" parentID=""1046"" level=""2"" writerID=""0"" creatorID=""0"" nodeType=""1044"" template=""" + templateId + @""" sortOrder=""3"" createDate=""2012-07-20T18:08:01"" updateDate=""2012-07-20T18:49:32"" nodeName=""Sub 2"" urlName=""sub-2"" writerName=""admin"" creatorName=""admin"" path=""-1,1046,1175"" isDoc=""""><content><![CDATA[]]></content> </Home> <CustomDocument id=""4444"" parentID=""1046"" level=""2"" writerID=""0"" creatorID=""0"" nodeType=""1234"" template=""" + templateId + @""" sortOrder=""4"" createDate=""2012-07-16T15:26:59"" updateDate=""2012-07-18T14:23:35"" nodeName=""Test"" urlName=""test-page"" writerName=""admin"" creatorName=""admin"" path=""-1,1046,4444"" isDoc=""""> <selectedNodes><![CDATA[1172,1176,1173]]></selectedNodes> <CustomDocument id=""5555"" parentID=""1046"" level=""3"" writerID=""0"" creatorID=""0"" nodeType=""1234"" template=""" + templateId + @""" sortOrder=""0"" createDate=""2012-07-16T15:26:59"" updateDate=""2012-07-18T14:23:35"" nodeName=""Test"" urlName=""test-page"" writerName=""admin"" creatorName=""admin"" path=""-1,1046,4444,5555"" isDoc=""""> </CustomDocument> </CustomDocument> </Home> <CustomDocument id=""1172"" parentID=""-1"" level=""1"" writerID=""0"" creatorID=""0"" nodeType=""1234"" template=""" + templateId + @""" sortOrder=""2"" createDate=""2012-07-16T15:26:59"" updateDate=""2012-07-18T14:23:35"" nodeName=""Test"" urlName=""test-page"" writerName=""admin"" creatorName=""admin"" path=""-1,1172"" isDoc="""" /> </root>"; } /// <summary> /// Returns the dynamic node/document to run tests against /// </summary> /// <param name="id"></param> /// <returns></returns> protected abstract dynamic GetDynamicNode(int id); [Test] public void Recursive_Property() { var doc = GetDynamicNode(1174); var prop = doc.GetProperty("siteTitle", true); Assert.IsNotNull(prop); Assert.AreEqual("This is my site", prop.Value); prop = doc.GetProperty("_siteTitle"); //test with underscore prefix Assert.IsNotNull(prop); Assert.AreEqual("This is my site", prop.Value); Assert.AreEqual("This is my site", doc._siteTitle); } /// <summary> /// Tests the internal instance level caching of returning properties /// </summary> /// <remarks> /// http://issues.umbraco.org/issue/U4-1824 /// http://issues.umbraco.org/issue/U4-1825 /// </remarks> [Test] public void Can_Return_Property_And_Value() { var doc = GetDynamicNode(1173); Assert.IsTrue(doc.HasProperty(Constants.Conventions.Content.UrlAlias)); var prop = doc.GetProperty(Constants.Conventions.Content.UrlAlias); Assert.IsNotNull(prop); Assert.AreEqual("page2/alias, 2ndpagealias", prop.Value); Assert.AreEqual("page2/alias, 2ndpagealias", doc.umbracoUrlAlias); } /// <summary> /// Tests the IsLast method with the result set from a Where statement /// </summary> [Test] public void Is_Last_From_Where_Filter() { var doc = GetDynamicNode(1173); foreach (var d in doc.Children.Where("Visible")) { if (d.Id != 1178) { Assert.IsFalse(d.IsLast()); } else { Assert.IsTrue(d.IsLast()); } } } [Test] public void Single() { var doc = GetDynamicNode(4444); var result = doc.Children().Single(); Assert.IsNotNull(result); Assert.AreEqual(5555, result.Id); } [Test] public void Single_With_Query() { var doc = GetDynamicNode(1046); var result = doc.Children().Single("id==1175"); Assert.IsNotNull(result); Assert.AreEqual(1175, result.Id); } [Test] public void First() { var doc = GetDynamicNode(1173); var result = doc.Children().First(); Assert.IsNotNull(result); Assert.AreEqual(1174, result.Id); } [Test] public void First_With_Query() { var doc = GetDynamicNode(1173); var result = doc.Children().First("blah==\"some content\""); Assert.IsNotNull(result); Assert.AreEqual(1176, result.Id); } [Test] public void Where_User_Property_Value() { var doc = GetDynamicNode(1173); var result = (IEnumerable<dynamic>)doc.Children().Where("blah==\"some content\""); Assert.IsNotNull(result); Assert.AreEqual(1, result.Count()); Assert.AreEqual(1176, result.Single().Id); } [Test] public void String_ContainsValue_Extension_Method() { var doc = GetDynamicNode(1046); var paramVals = new Dictionary<string, object> { { "searchId", 1173 } }; //this is an integer value var result = doc.Children() .Where("selectedNodes.ContainsValue(searchId)", paramVals) //call an extension method .FirstOrDefault(); Assert.IsNotNull(result); Assert.AreEqual(4444, result.Id); //don't find! paramVals = new Dictionary<string, object> { { "searchId", 1111777 } }; result = doc.Children() .Where("selectedNodes.ContainsValue(searchId)", paramVals) .FirstOrDefault(); Assert.IsNotNull(result); Assert.IsTrue(result.GetType() == typeof(DynamicNull) || result.GetType() == typeof(umbraco.MacroEngines.DynamicNull)); //Assert.AreEqual(typeof(DynamicNull), result.GetType()); } [Test] public void String_Contains_Method() { var doc = GetDynamicNode(1046); var paramVals = new Dictionary<string, object> { { "searchId", "1173" } }; var result = doc.Children() .Where("selectedNodes.Contains(searchId)", paramVals) .FirstOrDefault(); Assert.IsNotNull(result); Assert.AreEqual(4444, result.Id); //don't find! paramVals = new Dictionary<string, object> { { "searchId", "1aaa173" } }; result = doc.Children() .Where("selectedNodes.Contains(searchId)", paramVals) .FirstOrDefault(); Assert.IsNotNull(result); Assert.IsTrue(result.GetType() == typeof (DynamicNull) || result.GetType() == typeof (umbraco.MacroEngines.DynamicNull)); //Assert.AreEqual(typeof (DynamicNull), result.GetType()); } [Test] public void String_Split_Method() { var doc = GetDynamicNode(1046); var paramVals = new Dictionary<string, object> { { "splitTerm", new char[] { ',' } }, { "splitOptions", StringSplitOptions.RemoveEmptyEntries } }; var result = doc.Children() .Where("selectedNodes.Split(splitTerm, splitOptions).Length == 3", paramVals) .FirstOrDefault(); Assert.IsNotNull(result); Assert.AreEqual(4444, result.Id); } [Ignore("We are ignoring this test because currently our ExpressionParser class cannot deal with this... it needs some serious TLC but it is very complex.")] [Test] public void Complex_Linq() { var doc = GetDynamicNode(1173); var paramVals = new Dictionary<string, object> {{"splitTerm", new char[] {','}}, {"searchId", "1173"}}; var result = doc.Ancestors().OrderBy("level") .Single() .Descendants() .Where("selectedNodes != null && selectedNodes != String.Empty && selectedNodes.Split(splitTerm).Contains(searchId)", paramVals) .FirstOrDefault(); Assert.IsNotNull(result); Assert.AreEqual(4444, result.Id); } [Test] public void Index() { var doc = GetDynamicNode(1173); Assert.AreEqual(0, doc.Index()); doc = GetDynamicNode(1176); Assert.AreEqual(3, doc.Index()); doc = GetDynamicNode(1177); Assert.AreEqual(1, doc.Index()); doc = GetDynamicNode(1178); Assert.AreEqual(2, doc.Index()); } [Test] public virtual void Is_First_Root_Nodes() { var doc = GetDynamicNode(1046); //test root nodes Assert.IsTrue(doc.IsFirst()); doc = GetDynamicNode(1172); Assert.IsFalse(doc.IsFirst()); } [Test] public void Is_First() { var doc = GetDynamicNode(1173); //test normal nodes Assert.IsTrue(doc.IsFirst()); doc = GetDynamicNode(1175); Assert.IsFalse(doc.IsFirst()); } [Test] public virtual void Is_Not_First_Root_Nodes() { var doc = GetDynamicNode(1046); //test root nodes Assert.IsFalse(doc.IsNotFirst()); doc = GetDynamicNode(1172); Assert.IsTrue(doc.IsNotFirst()); } [Test] public void Is_Not_First() { var doc = GetDynamicNode(1173); //test normal nodes Assert.IsFalse(doc.IsNotFirst()); doc = GetDynamicNode(1175); Assert.IsTrue(doc.IsNotFirst()); } [Test] public virtual void Is_Position_Root_Nodes() { var doc = GetDynamicNode(1046); //test root nodes Assert.IsTrue(doc.IsPosition(0)); doc = GetDynamicNode(1172); Assert.IsTrue(doc.IsPosition(1)); } [Test] public void Is_Position() { var doc = GetDynamicNode(1173); //test normal nodes Assert.IsTrue(doc.IsPosition(0)); doc = GetDynamicNode(1175); Assert.IsTrue(doc.IsPosition(1)); } [Test] public void Children_GroupBy_DocumentTypeAlias() { var doc = GetDynamicNode(1046); var found1 = doc.Children.GroupBy("DocumentTypeAlias"); var casted = (IEnumerable<IGrouping<object, dynamic>>)(found1); Assert.AreEqual(2, casted.Count()); Assert.AreEqual(2, casted.Single(x => x.Key.ToString() == "Home").Count()); Assert.AreEqual(1, casted.Single(x => x.Key.ToString() == "CustomDocument").Count()); } [Test] public void Children_Where_DocumentTypeAlias() { var doc = GetDynamicNode(1046); var found1 = doc.Children.Where("DocumentTypeAlias == \"CustomDocument\""); var found2 = doc.Children.Where("DocumentTypeAlias == \"Home\""); Assert.AreEqual(1, found1.Count()); Assert.AreEqual(2, found2.Count()); } [Test] public void Children_Where_NodeTypeAlias() { var doc = GetDynamicNode(1046); var found1 = doc.Children.Where("NodeTypeAlias == \"CustomDocument\""); var found2 = doc.Children.Where("NodeTypeAlias == \"Home\""); Assert.AreEqual(1, found1.Count()); Assert.AreEqual(2, found2.Count()); } [Test] public void Children_Order_By_Update_Date() { var asDynamic = GetDynamicNode(1173); var ordered = asDynamic.Children.OrderBy("UpdateDate"); var casted = (IEnumerable<TDocument>)ordered; var correctOrder = new[] { 1178, 1177, 1174, 1176 }; for (var i = 0; i < correctOrder.Length ;i++) { Assert.AreEqual(correctOrder[i], ((dynamic)casted.ElementAt(i)).Id); } } [Test] public void Children_Order_By_Update_Date_Descending() { var asDynamic = GetDynamicNode(1173); var ordered = asDynamic.Children.OrderBy("UpdateDate desc"); var casted = (IEnumerable<TDocument>)ordered; var correctOrder = new[] { 1176, 1174, 1177, 1178 }; for (var i = 0; i < correctOrder.Length; i++) { Assert.AreEqual(correctOrder[i], ((dynamic)casted.ElementAt(i)).Id); } } [Test] public void HasProperty() { var asDynamic = GetDynamicNode(1173); var hasProp = asDynamic.HasProperty(Constants.Conventions.Content.UrlAlias); Assert.AreEqual(true, (bool)hasProp); } [Test] public void Skip() { var asDynamic = GetDynamicNode(1173); var skip = asDynamic.Children.Skip(2); var casted = (IEnumerable<TDocument>)skip; Assert.AreEqual(2, casted.Count()); Assert.IsTrue(casted.Select(x => ((dynamic) x).Id).ContainsAll(new dynamic[] {1178, 1176})); } [Test] public void HasValue() { var asDynamic = GetDynamicNode(1173); var hasValue = asDynamic.HasValue(Constants.Conventions.Content.UrlAlias); var noValue = asDynamic.HasValue("blahblahblah"); Assert.IsTrue(hasValue); Assert.IsFalse(noValue); } [Test] public void Take() { var asDynamic = GetDynamicNode(1173); var take = asDynamic.Children.Take(2); var casted = (IEnumerable<TDocument>)take; Assert.AreEqual(2, casted.Count()); Assert.IsTrue(casted.Select(x => ((dynamic)x).Id).ContainsAll(new dynamic[] { 1174, 1177 })); } [Test] public void Ancestors_Where_Visible() { var asDynamic = GetDynamicNode(1174); var whereVisible = asDynamic.Ancestors().Where("Visible"); var casted = (IEnumerable<TDocument>)whereVisible; Assert.AreEqual(1, casted.Count()); } [Test] public void Visible() { var asDynamicHidden = GetDynamicNode(1046); var asDynamicVisible = GetDynamicNode(1173); Assert.IsFalse(asDynamicHidden.Visible); Assert.IsTrue(asDynamicVisible.Visible); } [Test] public void Ensure_TinyMCE_Converted_Type_User_Property() { var asDynamic = GetDynamicNode(1173); Assert.IsTrue(TypeHelper.IsTypeAssignableFrom<IHtmlString>(asDynamic.Content.GetType())); Assert.AreEqual("<div>This is some content</div>", asDynamic.Content.ToString()); } [Test] public void Get_Children_With_Pluralized_Alias() { var asDynamic = GetDynamicNode(1173); Action<object> doAssert = d => { Assert.IsTrue(TypeHelper.IsTypeAssignableFrom<IEnumerable>(d)); var casted = (IEnumerable<TDocument>)d; Assert.AreEqual(2, casted.Count()); }; doAssert(asDynamic.Homes); //pluralized alias doAssert(asDynamic.homes); //pluralized alias doAssert(asDynamic.CustomDocuments); //pluralized alias doAssert(asDynamic.customDocuments); //pluralized alias } [Test] public void GetPropertyValue_Non_Reflected() { var asDynamic = GetDynamicNode(1174); Assert.AreEqual("Custom data with same property name as the member name", asDynamic.GetPropertyValue("creatorName")); Assert.AreEqual("Custom data with same property name as the member name", asDynamic.GetPropertyValue("CreatorName")); } [Test] public void GetPropertyValue_Reflected() { var asDynamic = GetDynamicNode(1174); Assert.AreEqual("admin", asDynamic.GetPropertyValue("@creatorName")); Assert.AreEqual("admin", asDynamic.GetPropertyValue("@CreatorName")); } [Test] public void Get_User_Property_With_Same_Name_As_Member_Property() { var asDynamic = GetDynamicNode(1174); Assert.AreEqual("Custom data with same property name as the member name", asDynamic.creatorName); //because CreatorName is defined on DynamicNode, it will not return the user defined property Assert.AreEqual("admin", asDynamic.CreatorName); } [Test] public void Get_Member_Property() { var asDynamic = GetDynamicNode(1173); Assert.AreEqual((int) 2, (int) asDynamic.Level); Assert.AreEqual((int) 2, (int) asDynamic.level); Assert.AreEqual((int) 1046, (int) asDynamic.ParentId); Assert.AreEqual((int) 1046, (int) asDynamic.parentId); } [Test] public void Get_Children() { var asDynamic = GetDynamicNode(1173); var children = asDynamic.Children; Assert.IsTrue(TypeHelper.IsTypeAssignableFrom<IEnumerable>(children)); var childrenAsList = asDynamic.ChildrenAsList; //test ChildrenAsList too Assert.IsTrue(TypeHelper.IsTypeAssignableFrom<IEnumerable>(childrenAsList)); var castChildren = (IEnumerable<TDocument>)children; Assert.AreEqual(4, castChildren.Count()); var castChildrenAsList = (IEnumerable<TDocument>)childrenAsList; Assert.AreEqual(4, castChildrenAsList.Count()); } [Test] public void Ancestor_Or_Self() { var asDynamic = GetDynamicNode(1173); var result = asDynamic.AncestorOrSelf(); Assert.IsNotNull(result); Assert.AreEqual((int) 1046, (int) result.Id); } [Test] public void Ancestors_Or_Self() { var asDynamic = GetDynamicNode(1174); var result = asDynamic.AncestorsOrSelf(); Assert.IsNotNull(result); var list = (IEnumerable<TDocument>)result; Assert.AreEqual(3, list.Count()); Assert.IsTrue(list.Select(x => ((dynamic)x).Id).ContainsAll(new dynamic[] { 1174, 1173, 1046 })); } [Test] public void Ancestors() { var asDynamic = GetDynamicNode(1174); var result = asDynamic.Ancestors(); Assert.IsNotNull(result); var list = (IEnumerable<TDocument>)result; Assert.AreEqual(2, list.Count()); Assert.IsTrue(list.Select(x => ((dynamic)x).Id).ContainsAll(new dynamic[] { 1173, 1046 })); } [Test] public void Descendants_Or_Self() { var asDynamic = GetDynamicNode(1046); var result = asDynamic.DescendantsOrSelf(); Assert.IsNotNull(result); var list = (IEnumerable<TDocument>)result; Assert.AreEqual(9, list.Count()); Assert.IsTrue(list.Select(x => ((dynamic)x).Id).ContainsAll(new dynamic[] { 1046, 1173, 1174, 1176, 1175, 4444 })); } [Test] public void Descendants() { var asDynamic = GetDynamicNode(1046); var result = asDynamic.Descendants(); Assert.IsNotNull(result); var list = (IEnumerable<TDocument>)result; Assert.AreEqual(8, list.Count()); Assert.IsTrue(list.Select(x => ((dynamic)x).Id).ContainsAll(new dynamic[] { 1173, 1174, 1176, 1175, 4444 })); } [Test] public void Up() { var asDynamic = GetDynamicNode(1173); var result = asDynamic.Up(); Assert.IsNotNull(result); Assert.AreEqual((int) 1046, (int) result.Id); } [Test] public void Down() { var asDynamic = GetDynamicNode(1173); var result = asDynamic.Down(); Assert.IsNotNull(result); Assert.AreEqual((int) 1174, (int) result.Id); } [Test] public void Next() { var asDynamic = GetDynamicNode(1173); var result = asDynamic.Next(); Assert.IsNotNull(result); Assert.AreEqual((int) 1175, (int) result.Id); } [Test] public void Next_Without_Sibling() { var asDynamic = GetDynamicNode(1176); Assert.IsNull(asDynamic.Next()); } [Test] public void Previous_Without_Sibling() { var asDynamic = GetDynamicNode(1173); Assert.IsNull(asDynamic.Previous()); } [Test] public void Previous() { var asDynamic = GetDynamicNode(1176); var result = asDynamic.Previous(); Assert.IsNotNull(result); Assert.AreEqual((int)1178, (int)result.Id); } } /// <summary> /// Extension methods used in tests /// </summary> public static class TestExtensionMethods { public static bool ContainsValue(this string s, int val) { return s.Contains(val.ToString()); } } }
/* * 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.Net; using System.Reflection; using Nini.Config; using log4net; using OpenSim.Framework; using OpenSim.Framework.Console; using OpenSim.Data; using OpenSim.Server.Base; using OpenSim.Services.Interfaces; using GridRegion = OpenSim.Services.Interfaces.GridRegion; using OpenMetaverse; namespace OpenSim.Services.GridService { public class GridService : GridServiceBase, IGridService { private static readonly ILog m_log = LogManager.GetLogger( MethodBase.GetCurrentMethod().DeclaringType); private bool m_DeleteOnUnregister = true; private static GridService m_RootInstance = null; protected IConfigSource m_config; protected HypergridLinker m_HypergridLinker; protected IAuthenticationService m_AuthenticationService = null; protected bool m_AllowDuplicateNames = false; protected bool m_AllowHypergridMapSearch = false; public GridService(IConfigSource config) : base(config) { m_log.DebugFormat("[GRID SERVICE]: Starting..."); m_config = config; IConfig gridConfig = config.Configs["GridService"]; if (gridConfig != null) { m_DeleteOnUnregister = gridConfig.GetBoolean("DeleteOnUnregister", true); string authService = gridConfig.GetString("AuthenticationService", String.Empty); if (authService != String.Empty) { Object[] args = new Object[] { config }; m_AuthenticationService = ServerUtils.LoadPlugin<IAuthenticationService>(authService, args); } m_AllowDuplicateNames = gridConfig.GetBoolean("AllowDuplicateNames", m_AllowDuplicateNames); m_AllowHypergridMapSearch = gridConfig.GetBoolean("AllowHypergridMapSearch", m_AllowHypergridMapSearch); } if (m_RootInstance == null) { m_RootInstance = this; if (MainConsole.Instance != null) { MainConsole.Instance.Commands.AddCommand("grid", true, "show region", "show region <Region name>", "Show details on a region", String.Empty, HandleShowRegion); MainConsole.Instance.Commands.AddCommand("grid", true, "set region flags", "set region flags <Region name> <flags>", "Set database flags for region", String.Empty, HandleSetFlags); } m_HypergridLinker = new HypergridLinker(m_config, this, m_Database); } } #region IGridService public string RegisterRegion(UUID scopeID, GridRegion regionInfos) { IConfig gridConfig = m_config.Configs["GridService"]; // This needs better sanity testing. What if regionInfo is registering in // overlapping coords? RegionData region = m_Database.Get(regionInfos.RegionLocX, regionInfos.RegionLocY, scopeID); if (region != null) { // There is a preexisting record // // Get it's flags // OpenSim.Data.RegionFlags rflags = (OpenSim.Data.RegionFlags)Convert.ToInt32(region.Data["flags"]); // Is this a reservation? // if ((rflags & OpenSim.Data.RegionFlags.Reservation) != 0) { // Regions reserved for the null key cannot be taken. if ((string)region.Data["PrincipalID"] == UUID.Zero.ToString()) return "Region location us reserved"; // Treat it as an auth request // // NOTE: Fudging the flags value here, so these flags // should not be used elsewhere. Don't optimize // this with the later retrieval of the same flags! rflags |= OpenSim.Data.RegionFlags.Authenticate; } if ((rflags & OpenSim.Data.RegionFlags.Authenticate) != 0) { // Can we authenticate at all? // if (m_AuthenticationService == null) return "No authentication possible"; if (!m_AuthenticationService.Verify(new UUID(region.Data["PrincipalID"].ToString()), regionInfos.Token, 30)) return "Bad authentication"; } } if ((region != null) && (region.RegionID != regionInfos.RegionID)) { m_log.WarnFormat("[GRID SERVICE]: Region {0} tried to register in coordinates {1}, {2} which are already in use in scope {3}.", regionInfos.RegionID, regionInfos.RegionLocX, regionInfos.RegionLocY, scopeID); return "Region overlaps another region"; } if ((region != null) && (region.RegionID == regionInfos.RegionID) && ((region.posX != regionInfos.RegionLocX) || (region.posY != regionInfos.RegionLocY))) { if ((Convert.ToInt32(region.Data["flags"]) & (int)OpenSim.Data.RegionFlags.NoMove) != 0) return "Can't move this region"; // Region reregistering in other coordinates. Delete the old entry m_log.DebugFormat("[GRID SERVICE]: Region {0} ({1}) was previously registered at {2}-{3}. Deleting old entry.", regionInfos.RegionName, regionInfos.RegionID, regionInfos.RegionLocX, regionInfos.RegionLocY); try { m_Database.Delete(regionInfos.RegionID); } catch (Exception e) { m_log.DebugFormat("[GRID SERVICE]: Database exception: {0}", e); } } if (!m_AllowDuplicateNames) { List<RegionData> dupe = m_Database.Get(regionInfos.RegionName, scopeID); if (dupe != null && dupe.Count > 0) { foreach (RegionData d in dupe) { if (d.RegionID != regionInfos.RegionID) { m_log.WarnFormat("[GRID SERVICE]: Region {0} tried to register duplicate name with ID {1}.", regionInfos.RegionName, regionInfos.RegionID); return "Duplicate region name"; } } } } // Everything is ok, let's register RegionData rdata = RegionInfo2RegionData(regionInfos); rdata.ScopeID = scopeID; if (region != null) { int oldFlags = Convert.ToInt32(region.Data["flags"]); if ((oldFlags & (int)OpenSim.Data.RegionFlags.LockedOut) != 0) return "Region locked out"; oldFlags &= ~(int)OpenSim.Data.RegionFlags.Reservation; rdata.Data["flags"] = oldFlags.ToString(); // Preserve flags } else { rdata.Data["flags"] = "0"; if ((gridConfig != null) && rdata.RegionName != string.Empty) { int newFlags = 0; string regionName = rdata.RegionName.Trim().Replace(' ', '_'); newFlags = ParseFlags(newFlags, gridConfig.GetString("Region_" + regionName, String.Empty)); newFlags = ParseFlags(newFlags, gridConfig.GetString("Region_" + rdata.RegionID.ToString(), String.Empty)); rdata.Data["flags"] = newFlags.ToString(); } } int flags = Convert.ToInt32(rdata.Data["flags"]); flags |= (int)OpenSim.Data.RegionFlags.RegionOnline; rdata.Data["flags"] = flags.ToString(); try { rdata.Data["last_seen"] = Util.UnixTimeSinceEpoch(); m_Database.Store(rdata); } catch (Exception e) { m_log.DebugFormat("[GRID SERVICE]: Database exception: {0}", e); } m_log.DebugFormat("[GRID SERVICE]: Region {0} ({1}) registered successfully at {2}-{3}", regionInfos.RegionName, regionInfos.RegionID, regionInfos.RegionLocX, regionInfos.RegionLocY); return String.Empty; } public bool DeregisterRegion(UUID regionID) { m_log.DebugFormat("[GRID SERVICE]: Region {0} deregistered", regionID); RegionData region = m_Database.Get(regionID, UUID.Zero); if (region == null) return false; int flags = Convert.ToInt32(region.Data["flags"]); if (!m_DeleteOnUnregister || (flags & (int)OpenSim.Data.RegionFlags.Persistent) != 0) { flags &= ~(int)OpenSim.Data.RegionFlags.RegionOnline; region.Data["flags"] = flags.ToString(); region.Data["last_seen"] = Util.UnixTimeSinceEpoch(); try { m_Database.Store(region); } catch (Exception e) { m_log.DebugFormat("[GRID SERVICE]: Database exception: {0}", e); } return true; } return m_Database.Delete(regionID); } public List<GridRegion> GetNeighbours(UUID scopeID, UUID regionID) { List<GridRegion> rinfos = new List<GridRegion>(); RegionData region = m_Database.Get(regionID, scopeID); if (region != null) { // Not really? Maybe? List<RegionData> rdatas = m_Database.Get(region.posX - (int)Constants.RegionSize, region.posY - (int)Constants.RegionSize, region.posX + (int)Constants.RegionSize, region.posY + (int)Constants.RegionSize, scopeID); foreach (RegionData rdata in rdatas) if (rdata.RegionID != regionID) rinfos.Add(RegionData2RegionInfo(rdata)); } return rinfos; } public GridRegion GetRegionByUUID(UUID scopeID, UUID regionID) { RegionData rdata = m_Database.Get(regionID, scopeID); if (rdata != null) return RegionData2RegionInfo(rdata); return null; } public GridRegion GetRegionByPosition(UUID scopeID, int x, int y) { int snapX = (int)(x / Constants.RegionSize) * (int)Constants.RegionSize; int snapY = (int)(y / Constants.RegionSize) * (int)Constants.RegionSize; RegionData rdata = m_Database.Get(snapX, snapY, scopeID); if (rdata != null) return RegionData2RegionInfo(rdata); return null; } public GridRegion GetRegionByName(UUID scopeID, string regionName) { List<RegionData> rdatas = m_Database.Get(regionName + "%", scopeID); if ((rdatas != null) && (rdatas.Count > 0)) return RegionData2RegionInfo(rdatas[0]); // get the first return null; } public List<GridRegion> GetRegionsByName(UUID scopeID, string name, int maxNumber) { m_log.DebugFormat("[GRID SERVICE]: GetRegionsByName {0}", name); List<RegionData> rdatas = m_Database.Get("%" + name + "%", scopeID); int count = 0; List<GridRegion> rinfos = new List<GridRegion>(); if (rdatas != null) { m_log.DebugFormat("[GRID SERVICE]: Found {0} regions", rdatas.Count); foreach (RegionData rdata in rdatas) { if (count++ < maxNumber) rinfos.Add(RegionData2RegionInfo(rdata)); } } if (m_AllowHypergridMapSearch && (rdatas == null || (rdatas != null && rdatas.Count == 0)) && name.Contains(".")) { GridRegion r = m_HypergridLinker.LinkRegion(scopeID, name); if (r != null) rinfos.Add(r); } return rinfos; } public List<GridRegion> GetRegionRange(UUID scopeID, int xmin, int xmax, int ymin, int ymax) { int xminSnap = (int)(xmin / Constants.RegionSize) * (int)Constants.RegionSize; int xmaxSnap = (int)(xmax / Constants.RegionSize) * (int)Constants.RegionSize; int yminSnap = (int)(ymin / Constants.RegionSize) * (int)Constants.RegionSize; int ymaxSnap = (int)(ymax / Constants.RegionSize) * (int)Constants.RegionSize; List<RegionData> rdatas = m_Database.Get(xminSnap, yminSnap, xmaxSnap, ymaxSnap, scopeID); List<GridRegion> rinfos = new List<GridRegion>(); foreach (RegionData rdata in rdatas) rinfos.Add(RegionData2RegionInfo(rdata)); return rinfos; } #endregion #region Data structure conversions public RegionData RegionInfo2RegionData(GridRegion rinfo) { RegionData rdata = new RegionData(); rdata.posX = (int)rinfo.RegionLocX; rdata.posY = (int)rinfo.RegionLocY; rdata.RegionID = rinfo.RegionID; rdata.RegionName = rinfo.RegionName; rdata.Data = rinfo.ToKeyValuePairs(); rdata.Data["regionHandle"] = Utils.UIntsToLong((uint)rdata.posX, (uint)rdata.posY); rdata.Data["owner_uuid"] = rinfo.EstateOwner.ToString(); return rdata; } public GridRegion RegionData2RegionInfo(RegionData rdata) { GridRegion rinfo = new GridRegion(rdata.Data); rinfo.RegionLocX = rdata.posX; rinfo.RegionLocY = rdata.posY; rinfo.RegionID = rdata.RegionID; rinfo.RegionName = rdata.RegionName; rinfo.ScopeID = rdata.ScopeID; return rinfo; } #endregion public List<GridRegion> GetDefaultRegions(UUID scopeID) { List<GridRegion> ret = new List<GridRegion>(); List<RegionData> regions = m_Database.GetDefaultRegions(scopeID); foreach (RegionData r in regions) { if ((Convert.ToInt32(r.Data["flags"]) & (int)OpenSim.Data.RegionFlags.RegionOnline) != 0) ret.Add(RegionData2RegionInfo(r)); } m_log.DebugFormat("[GRID SERVICE]: GetDefaultRegions returning {0} regions", ret.Count); return ret; } public List<GridRegion> GetFallbackRegions(UUID scopeID, int x, int y) { List<GridRegion> ret = new List<GridRegion>(); List<RegionData> regions = m_Database.GetFallbackRegions(scopeID, x, y); foreach (RegionData r in regions) { if ((Convert.ToInt32(r.Data["flags"]) & (int)OpenSim.Data.RegionFlags.RegionOnline) != 0) ret.Add(RegionData2RegionInfo(r)); } m_log.DebugFormat("[GRID SERVICE]: Fallback returned {0} regions", ret.Count); return ret; } public int GetRegionFlags(UUID scopeID, UUID regionID) { RegionData region = m_Database.Get(regionID, scopeID); if (region != null) { int flags = Convert.ToInt32(region.Data["flags"]); //m_log.DebugFormat("[GRID SERVICE]: Request for flags of {0}: {1}", regionID, flags); return flags; } else return -1; } private void HandleShowRegion(string module, string[] cmd) { if (cmd.Length != 3) { MainConsole.Instance.Output("Syntax: show region <region name>"); return; } List<RegionData> regions = m_Database.Get(cmd[2], UUID.Zero); if (regions == null || regions.Count < 1) { MainConsole.Instance.Output("Region not found"); return; } MainConsole.Instance.Output("Region Name Region UUID"); MainConsole.Instance.Output("Location URI"); MainConsole.Instance.Output("Owner ID Flags"); MainConsole.Instance.Output("-------------------------------------------------------------------------------"); foreach (RegionData r in regions) { OpenSim.Data.RegionFlags flags = (OpenSim.Data.RegionFlags)Convert.ToInt32(r.Data["flags"]); MainConsole.Instance.Output(String.Format("{0,-20} {1}\n{2,-20} {3}\n{4,-39} {5}\n\n", r.RegionName, r.RegionID, String.Format("{0},{1}", r.posX, r.posY), "http://" + r.Data["serverIP"].ToString() + ":" + r.Data["serverPort"].ToString(), r.Data["owner_uuid"].ToString(), flags.ToString())); } return; } private int ParseFlags(int prev, string flags) { OpenSim.Data.RegionFlags f = (OpenSim.Data.RegionFlags)prev; string[] parts = flags.Split(new char[] {',', ' '}, StringSplitOptions.RemoveEmptyEntries); foreach (string p in parts) { int val; try { if (p.StartsWith("+")) { val = (int)Enum.Parse(typeof(OpenSim.Data.RegionFlags), p.Substring(1)); f |= (OpenSim.Data.RegionFlags)val; } else if (p.StartsWith("-")) { val = (int)Enum.Parse(typeof(OpenSim.Data.RegionFlags), p.Substring(1)); f &= ~(OpenSim.Data.RegionFlags)val; } else { val = (int)Enum.Parse(typeof(OpenSim.Data.RegionFlags), p); f |= (OpenSim.Data.RegionFlags)val; } } catch (Exception) { MainConsole.Instance.Output("Error in flag specification: " + p); } } return (int)f; } private void HandleSetFlags(string module, string[] cmd) { if (cmd.Length < 5) { MainConsole.Instance.Output("Syntax: set region flags <region name> <flags>"); return; } List<RegionData> regions = m_Database.Get(cmd[3], UUID.Zero); if (regions == null || regions.Count < 1) { MainConsole.Instance.Output("Region not found"); return; } foreach (RegionData r in regions) { int flags = Convert.ToInt32(r.Data["flags"]); flags = ParseFlags(flags, cmd[4]); r.Data["flags"] = flags.ToString(); OpenSim.Data.RegionFlags f = (OpenSim.Data.RegionFlags)flags; MainConsole.Instance.Output(String.Format("Set region {0} to {1}", r.RegionName, f)); m_Database.Store(r); } } } }
using CrystalDecisions.CrystalReports.Engine; using CrystalDecisions.Windows.Forms; using DpSdkEngLib; using DPSDKOPSLib; using Microsoft.VisualBasic; using System; using System.Collections; using System.Collections.Generic; using System.Drawing; using System.Diagnostics; using System.Windows.Forms; using System.Linq; using System.Xml.Linq; namespace _4PosBackOffice.NET { [Microsoft.VisualBasic.CompilerServices.DesignerGenerated()] partial class frmStockGroupListNotes { #region "Windows Form Designer generated code " [System.Diagnostics.DebuggerNonUserCode()] public frmStockGroupListNotes() : base() { FormClosed += frmStockGroupListNotes_FormClosed; KeyPress += frmStockGroupListNotes_KeyPress; KeyDown += frmStockGroupListNotes_KeyDown; //This call is required by the Windows Form Designer. InitializeComponent(); } //Form overrides dispose to clean up the component list. [System.Diagnostics.DebuggerNonUserCode()] protected override void Dispose(bool Disposing) { if (Disposing) { if ((components != null)) { components.Dispose(); } } base.Dispose(Disposing); } //Required by the Windows Form Designer private System.ComponentModel.IContainer components; public System.Windows.Forms.ToolTip ToolTip1; private System.Windows.Forms.ToolStripMenuItem withEventsField_mnuDel; public System.Windows.Forms.ToolStripMenuItem mnuDel { get { return withEventsField_mnuDel; } set { if (withEventsField_mnuDel != null) { withEventsField_mnuDel.Click -= mnuDel_Click; } withEventsField_mnuDel = value; if (withEventsField_mnuDel != null) { withEventsField_mnuDel.Click += mnuDel_Click; } } } public System.Windows.Forms.ToolStripMenuItem mnuHand; public System.Windows.Forms.MenuStrip MainMenu1; private System.Windows.Forms.Button withEventsField_cmdNew; public System.Windows.Forms.Button cmdNew { get { return withEventsField_cmdNew; } set { if (withEventsField_cmdNew != null) { withEventsField_cmdNew.Click -= cmdNew_Click; } withEventsField_cmdNew = value; if (withEventsField_cmdNew != null) { withEventsField_cmdNew.Click += cmdNew_Click; } } } private myDataGridView withEventsField_DataList1; public myDataGridView DataList1 { get { return withEventsField_DataList1; } set { if (withEventsField_DataList1 != null) { withEventsField_DataList1.DoubleClick -= DataList1_DblClick; withEventsField_DataList1.KeyPress -= DataList1_KeyPress; withEventsField_DataList1.MouseDown -= DataList1_MouseDown; } withEventsField_DataList1 = value; if (withEventsField_DataList1 != null) { withEventsField_DataList1.DoubleClick += DataList1_DblClick; withEventsField_DataList1.KeyPress += DataList1_KeyPress; withEventsField_DataList1.MouseDown += DataList1_MouseDown; } } } private System.Windows.Forms.TextBox withEventsField_txtSearch; public System.Windows.Forms.TextBox txtSearch { get { return withEventsField_txtSearch; } set { if (withEventsField_txtSearch != null) { withEventsField_txtSearch.Enter -= txtSearch_Enter; withEventsField_txtSearch.KeyDown -= txtSearch_KeyDown; withEventsField_txtSearch.KeyPress -= txtSearch_KeyPress; } withEventsField_txtSearch = value; if (withEventsField_txtSearch != null) { withEventsField_txtSearch.Enter += txtSearch_Enter; withEventsField_txtSearch.KeyDown += txtSearch_KeyDown; withEventsField_txtSearch.KeyPress += txtSearch_KeyPress; } } } private System.Windows.Forms.Button withEventsField_cmdExit; public System.Windows.Forms.Button cmdExit { get { return withEventsField_cmdExit; } set { if (withEventsField_cmdExit != null) { withEventsField_cmdExit.Click -= cmdExit_Click; } withEventsField_cmdExit = value; if (withEventsField_cmdExit != null) { withEventsField_cmdExit.Click += cmdExit_Click; } } } public System.Windows.Forms.Label lbl; //NOTE: The following procedure is required by the Windows Form Designer //It can be modified using the Windows Form Designer. //Do not modify it using the code editor. [System.Diagnostics.DebuggerStepThrough()] private void InitializeComponent() { System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(frmStockGroupListNotes)); this.components = new System.ComponentModel.Container(); this.ToolTip1 = new System.Windows.Forms.ToolTip(components); this.MainMenu1 = new System.Windows.Forms.MenuStrip(); this.mnuHand = new System.Windows.Forms.ToolStripMenuItem(); this.mnuDel = new System.Windows.Forms.ToolStripMenuItem(); this.cmdNew = new System.Windows.Forms.Button(); this.DataList1 = new myDataGridView(); this.txtSearch = new System.Windows.Forms.TextBox(); this.cmdExit = new System.Windows.Forms.Button(); this.lbl = new System.Windows.Forms.Label(); this.MainMenu1.SuspendLayout(); this.SuspendLayout(); this.ToolTip1.Active = true; ((System.ComponentModel.ISupportInitialize)this.DataList1).BeginInit(); this.BackColor = System.Drawing.Color.FromArgb(224, 224, 224); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.Text = "Select a Stock Group"; this.ClientSize = new System.Drawing.Size(259, 457); this.Location = new System.Drawing.Point(3, 22); this.ControlBox = false; this.KeyPreview = true; this.MaximizeBox = false; this.MinimizeBox = false; this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Enabled = true; this.Cursor = System.Windows.Forms.Cursors.Default; this.RightToLeft = System.Windows.Forms.RightToLeft.No; this.HelpButton = false; this.WindowState = System.Windows.Forms.FormWindowState.Normal; this.Name = "frmStockGroupListNotes"; this.mnuHand.Name = "mnuHand"; this.mnuHand.Text = "HandHeld"; this.mnuHand.Visible = false; this.mnuHand.Checked = false; this.mnuHand.Enabled = true; this.mnuDel.Name = "mnuDel"; this.mnuDel.Text = "Delete Group"; this.mnuDel.Checked = false; this.mnuDel.Enabled = true; this.mnuDel.Visible = true; this.cmdNew.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.cmdNew.Text = "&New"; this.cmdNew.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178)); this.cmdNew.Size = new System.Drawing.Size(97, 52); this.cmdNew.Location = new System.Drawing.Point(6, 399); this.cmdNew.TabIndex = 4; this.cmdNew.TabStop = false; this.cmdNew.BackColor = System.Drawing.SystemColors.Control; this.cmdNew.CausesValidation = true; this.cmdNew.Enabled = true; this.cmdNew.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdNew.Cursor = System.Windows.Forms.Cursors.Default; this.cmdNew.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdNew.Name = "cmdNew"; //DataList1.OcxState = CType(resources.GetObject("'DataList1.OcxState"), System.Windows.Forms.AxHost.State) this.DataList1.Size = new System.Drawing.Size(244, 342); this.DataList1.Location = new System.Drawing.Point(6, 51); this.DataList1.TabIndex = 2; this.DataList1.Name = "DataList1"; this.txtSearch.AutoSize = false; this.txtSearch.Size = new System.Drawing.Size(199, 19); this.txtSearch.Location = new System.Drawing.Point(51, 27); this.txtSearch.TabIndex = 1; this.txtSearch.AcceptsReturn = true; this.txtSearch.TextAlign = System.Windows.Forms.HorizontalAlignment.Left; this.txtSearch.BackColor = System.Drawing.SystemColors.Window; this.txtSearch.CausesValidation = true; this.txtSearch.Enabled = true; this.txtSearch.ForeColor = System.Drawing.SystemColors.WindowText; this.txtSearch.HideSelection = true; this.txtSearch.ReadOnly = false; this.txtSearch.MaxLength = 0; this.txtSearch.Cursor = System.Windows.Forms.Cursors.IBeam; this.txtSearch.Multiline = false; this.txtSearch.RightToLeft = System.Windows.Forms.RightToLeft.No; this.txtSearch.ScrollBars = System.Windows.Forms.ScrollBars.None; this.txtSearch.TabStop = true; this.txtSearch.Visible = true; this.txtSearch.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.txtSearch.Name = "txtSearch"; this.cmdExit.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.cmdExit.Text = "E&xit"; this.cmdExit.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178)); this.cmdExit.Size = new System.Drawing.Size(97, 52); this.cmdExit.Location = new System.Drawing.Point(153, 399); this.cmdExit.TabIndex = 3; this.cmdExit.TabStop = false; this.cmdExit.BackColor = System.Drawing.SystemColors.Control; this.cmdExit.CausesValidation = true; this.cmdExit.Enabled = true; this.cmdExit.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdExit.Cursor = System.Windows.Forms.Cursors.Default; this.cmdExit.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdExit.Name = "cmdExit"; this.lbl.TextAlign = System.Drawing.ContentAlignment.TopRight; this.lbl.Text = "&Search :"; this.lbl.Size = new System.Drawing.Size(40, 13); this.lbl.Location = new System.Drawing.Point(8, 30); this.lbl.TabIndex = 0; this.lbl.BackColor = System.Drawing.Color.Transparent; this.lbl.Enabled = true; this.lbl.ForeColor = System.Drawing.SystemColors.ControlText; this.lbl.Cursor = System.Windows.Forms.Cursors.Default; this.lbl.RightToLeft = System.Windows.Forms.RightToLeft.No; this.lbl.UseMnemonic = true; this.lbl.Visible = true; this.lbl.AutoSize = true; this.lbl.BorderStyle = System.Windows.Forms.BorderStyle.None; this.lbl.Name = "lbl"; this.Controls.Add(cmdNew); this.Controls.Add(DataList1); this.Controls.Add(txtSearch); this.Controls.Add(cmdExit); this.Controls.Add(lbl); ((System.ComponentModel.ISupportInitialize)this.DataList1).EndInit(); MainMenu1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.mnuHand }); mnuHand.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.mnuDel }); this.Controls.Add(MainMenu1); this.MainMenu1.ResumeLayout(false); this.ResumeLayout(false); this.PerformLayout(); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Net; using System.Security.Authentication.ExtendedProtection; using System.ServiceModel; using System.ServiceModel.Channels; using System.ServiceModel.Tests.Common; using System.Text; using System.Xml; using Infrastructure.Common; using Xunit; public static class BasicHttpBindingTest { [WcfFact] public static void Default_Ctor_Initializes_Properties() { var binding = new BasicHttpBinding(); Assert.Equal("BasicHttpBinding", binding.Name); Assert.Equal("http://tempuri.org/", binding.Namespace); Assert.Equal("http", binding.Scheme); Assert.Equal<Encoding>(Encoding.GetEncoding("utf-8"), binding.TextEncoding); Assert.Equal(Encoding.GetEncoding("utf-8").WebName, binding.TextEncoding.WebName); Assert.False(binding.AllowCookies); Assert.Equal<TimeSpan>(TimeSpan.FromMinutes(1), binding.CloseTimeout); Assert.Equal<TimeSpan>(TimeSpan.FromMinutes(1), binding.OpenTimeout); Assert.Equal<TimeSpan>(TimeSpan.FromMinutes(10), binding.ReceiveTimeout); Assert.Equal<TimeSpan>(TimeSpan.FromMinutes(1), binding.SendTimeout); Assert.Equal<EnvelopeVersion>(EnvelopeVersion.Soap11, binding.EnvelopeVersion); Assert.Equal<MessageVersion>(MessageVersion.Soap11, binding.MessageVersion); Assert.Equal<long>(524288, binding.MaxBufferPoolSize); Assert.Equal<long>(65536, binding.MaxBufferSize); Assert.Equal<long>(65536, binding.MaxReceivedMessageSize); Assert.Equal<TransferMode>(TransferMode.Buffered, binding.TransferMode); Assert.True(TestHelpers.XmlDictionaryReaderQuotasAreEqual(binding.ReaderQuotas, new XmlDictionaryReaderQuotas()), "XmlDictionaryReaderQuotas"); } [WcfFact] public static void Ctor_With_BasicHttpSecurityMode_Transport_Initializes_Properties() { var binding = new BasicHttpBinding(BasicHttpSecurityMode.Transport); Assert.Equal("BasicHttpBinding", binding.Name); Assert.Equal("http://tempuri.org/", binding.Namespace); Assert.Equal("https", binding.Scheme); Assert.Equal<Encoding>(Encoding.GetEncoding("utf-8"), binding.TextEncoding); Assert.Equal(Encoding.GetEncoding("utf-8").WebName, binding.TextEncoding.WebName); Assert.False(binding.AllowCookies); Assert.Equal<TimeSpan>(TimeSpan.FromMinutes(1), binding.CloseTimeout); Assert.Equal<TimeSpan>(TimeSpan.FromMinutes(1), binding.OpenTimeout); Assert.Equal<TimeSpan>(TimeSpan.FromMinutes(10), binding.ReceiveTimeout); Assert.Equal<TimeSpan>(TimeSpan.FromMinutes(1), binding.SendTimeout); Assert.Equal<EnvelopeVersion>(EnvelopeVersion.Soap11, binding.EnvelopeVersion); Assert.Equal<MessageVersion>(MessageVersion.Soap11, binding.MessageVersion); Assert.Equal<long>(524288, binding.MaxBufferPoolSize); Assert.Equal<long>(65536, binding.MaxBufferSize); Assert.Equal<long>(65536, binding.MaxReceivedMessageSize); Assert.Equal<TransferMode>(TransferMode.Buffered, binding.TransferMode); Assert.True(TestHelpers.XmlDictionaryReaderQuotasAreEqual(binding.ReaderQuotas, new XmlDictionaryReaderQuotas()), "XmlDictionaryReaderQuotas"); } [WcfFact] public static void Ctor_With_BasicHttpSecurityMode_TransportCredentialOnly_Initializes_Properties() { var binding = new BasicHttpBinding(BasicHttpSecurityMode.TransportCredentialOnly); Assert.Equal("BasicHttpBinding", binding.Name); Assert.Equal("http://tempuri.org/", binding.Namespace); Assert.Equal("http", binding.Scheme); Assert.Equal<Encoding>(Encoding.GetEncoding("utf-8"), binding.TextEncoding); Assert.Equal(Encoding.GetEncoding("utf-8").WebName, binding.TextEncoding.WebName); Assert.False(binding.AllowCookies); Assert.Equal<TimeSpan>(TimeSpan.FromMinutes(1), binding.CloseTimeout); Assert.Equal<TimeSpan>(TimeSpan.FromMinutes(1), binding.OpenTimeout); Assert.Equal<TimeSpan>(TimeSpan.FromMinutes(10), binding.ReceiveTimeout); Assert.Equal<TimeSpan>(TimeSpan.FromMinutes(1), binding.SendTimeout); Assert.Equal<EnvelopeVersion>(EnvelopeVersion.Soap11, binding.EnvelopeVersion); Assert.Equal<MessageVersion>(MessageVersion.Soap11, binding.MessageVersion); Assert.Equal<long>(524288, binding.MaxBufferPoolSize); Assert.Equal<long>(65536, binding.MaxBufferSize); Assert.Equal<long>(65536, binding.MaxReceivedMessageSize); Assert.Equal<TransferMode>(TransferMode.Buffered, binding.TransferMode); Assert.True(TestHelpers.XmlDictionaryReaderQuotasAreEqual(binding.ReaderQuotas, new XmlDictionaryReaderQuotas()), "XmlDictionaryReaderQuotas"); } [WcfTheory] [InlineData(true)] [InlineData(false)] public static void AllowCookies_Property_Sets(bool value) { var binding = new BasicHttpBinding(); binding.AllowCookies = value; Assert.Equal<bool>(value, binding.AllowCookies); } [WcfTheory] [InlineData(0)] [InlineData(1)] [InlineData(int.MaxValue)] public static void MaxBufferPoolSize_Property_Sets(long value) { var binding = new BasicHttpBinding(); binding.MaxBufferPoolSize = value; Assert.Equal<long>(value, binding.MaxBufferPoolSize); } [WcfTheory] [InlineData(-1)] [InlineData(int.MinValue)] public static void MaxBufferPoolSize_Property_Set_Invalid_Value_Throws(long value) { var binding = new BasicHttpBinding(); Assert.Throws<ArgumentOutOfRangeException>(() => binding.MaxBufferPoolSize = value); } [WcfTheory] [InlineData(1)] [InlineData(int.MaxValue)] public static void MaxBufferSize_Property_Sets(int value) { var binding = new BasicHttpBinding(); binding.MaxBufferSize = value; Assert.Equal<long>(value, binding.MaxBufferSize); } [WcfTheory] [InlineData(0)] [InlineData(-1)] [InlineData(int.MinValue)] public static void MaxBufferSize_Property_Set_Invalid_Value_Throws(int value) { var binding = new BasicHttpBinding(); Assert.Throws<ArgumentOutOfRangeException>(() => binding.MaxBufferSize = value); } [WcfTheory] [InlineData(1)] [InlineData(int.MaxValue)] public static void MaxReceivedMessageSize_Property_Sets(long value) { var binding = new BasicHttpBinding(); binding.MaxReceivedMessageSize = value; Assert.Equal<long>(value, binding.MaxReceivedMessageSize); } [WcfTheory] [InlineData(0)] [InlineData(-1)] [InlineData(int.MinValue)] public static void MaxReceivedMessageSize_Property_Set_Invalid_Value_Throws(int value) { var binding = new BasicHttpBinding(); Assert.Throws<ArgumentOutOfRangeException>(() => binding.MaxReceivedMessageSize = value); } [WcfTheory] [InlineData("testName")] public static void Name_Property_Sets(string value) { var binding = new BasicHttpBinding(); binding.Name = value; Assert.Equal(value, binding.Name); } [WcfTheory] [InlineData(new object[] { null } )] [InlineData("")] public static void Name_Property_Set_Invalid_Value_Throws(string value) { var binding = new BasicHttpBinding(); Assert.Throws<ArgumentException>(() => binding.Name = value); } [WcfTheory] [InlineData("")] [InlineData("http://hello")] [InlineData("testNamespace")] public static void Namespace_Property_Sets(string value) { var binding = new BasicHttpBinding(); binding.Namespace = value; Assert.Equal(value, binding.Namespace); } [WcfTheory] [InlineData(new object[] { null } )] public static void Namespace_Property_Set_Invalid_Value_Throws(string value) { var binding = new BasicHttpBinding(); Assert.Throws<ArgumentNullException>(() => binding.Namespace = value); } [WcfFact] public static void ReaderQuotas_Property_Sets() { var binding = new BasicHttpBinding(); XmlDictionaryReaderQuotas maxQuota = XmlDictionaryReaderQuotas.Max; XmlDictionaryReaderQuotas defaultQuota = new XmlDictionaryReaderQuotas(); Assert.True(TestHelpers.XmlDictionaryReaderQuotasAreEqual(binding.ReaderQuotas, defaultQuota)); maxQuota.CopyTo(binding.ReaderQuotas); Assert.True(TestHelpers.XmlDictionaryReaderQuotasAreEqual(binding.ReaderQuotas, maxQuota), "Setting Max ReaderQuota failed"); } [WcfFact] public static void ReaderQuotas_Property_Set_Null_Throws() { var binding = new BasicHttpBinding(); Assert.Throws<ArgumentNullException>(() => binding.ReaderQuotas = null); } [WcfTheory] [MemberData(nameof(TestData.ValidTimeOuts), MemberType = typeof(TestData))] public static void CloseTimeout_Property_Sets(TimeSpan timeSpan) { BasicHttpBinding binding = new BasicHttpBinding(); binding.CloseTimeout = timeSpan; Assert.Equal<TimeSpan>(timeSpan, binding.CloseTimeout); } [WcfTheory] [MemberData(nameof(TestData.InvalidTimeOuts), MemberType = typeof(TestData))] public static void CloseTimeout_Property_Set_Invalid_Value_Throws(TimeSpan timeSpan) { BasicHttpBinding binding = new BasicHttpBinding(); Assert.Throws<ArgumentOutOfRangeException>(() => binding.CloseTimeout = timeSpan); } [WcfTheory] [MemberData(nameof(TestData.ValidTimeOuts), MemberType = typeof(TestData))] public static void OpenTimeout_Property_Sets(TimeSpan timeSpan) { BasicHttpBinding binding = new BasicHttpBinding(); binding.OpenTimeout = timeSpan; Assert.Equal<TimeSpan>(timeSpan, binding.OpenTimeout); } [WcfTheory] [MemberData(nameof(TestData.InvalidTimeOuts), MemberType = typeof(TestData))] public static void OpenTimeout_Property_Set_Invalid_Value_Throws(TimeSpan timeSpan) { BasicHttpBinding binding = new BasicHttpBinding(); Assert.Throws<ArgumentOutOfRangeException>(() => binding.OpenTimeout = timeSpan); } [WcfTheory] [MemberData(nameof(TestData.ValidTimeOuts), MemberType = typeof(TestData))] public static void SendTimeout_Property_Sets(TimeSpan timeSpan) { BasicHttpBinding binding = new BasicHttpBinding(); binding.SendTimeout = timeSpan; Assert.Equal<TimeSpan>(timeSpan, binding.SendTimeout); } [WcfTheory] [MemberData(nameof(TestData.InvalidTimeOuts), MemberType = typeof(TestData))] public static void SendTimeout_Property_Set_Invalid_Value_Throws(TimeSpan timeSpan) { BasicHttpBinding binding = new BasicHttpBinding(); Assert.Throws<ArgumentOutOfRangeException>(() => binding.SendTimeout = timeSpan); } [WcfTheory] [MemberData(nameof(TestData.ValidTimeOuts), MemberType = typeof(TestData))] public static void ReceiveTimeout_Property_Sets(TimeSpan timeSpan) { BasicHttpBinding binding = new BasicHttpBinding(); binding.ReceiveTimeout = timeSpan; Assert.Equal<TimeSpan>(timeSpan, binding.ReceiveTimeout); } [WcfTheory] [MemberData(nameof(TestData.InvalidTimeOuts), MemberType = typeof(TestData))] public static void ReceiveTimeout_Property_Set_Invalid_Value_Throws(TimeSpan timeSpan) { BasicHttpBinding binding = new BasicHttpBinding(); Assert.Throws<ArgumentOutOfRangeException>(() => binding.SendTimeout = timeSpan); } [WcfTheory] [MemberData(nameof(TestData.ValidEncodings), MemberType = typeof(TestData))] public static void TextEncoding_Property_Sets(Encoding encoding) { var binding = new BasicHttpBinding(); binding.TextEncoding = encoding; Assert.Equal<Encoding>(encoding, binding.TextEncoding); } [WcfTheory] [MemberData(nameof(TestData.InvalidEncodings), MemberType = typeof(TestData))] public static void TextEncoding_Property_Set_Invalid_Value_Throws(Encoding encoding) { var binding = new BasicHttpBinding(); Assert.Throws<ArgumentException>(() => binding.TextEncoding = encoding); } [WcfTheory] [InlineData(TransferMode.Buffered)] [InlineData(TransferMode.Streamed)] [InlineData(TransferMode.StreamedRequest)] [InlineData(TransferMode.StreamedResponse)] public static void TransferMode_Property_Sets(TransferMode transferMode) { var binding = new BasicHttpBinding(); binding.TransferMode = transferMode; Assert.Equal<TransferMode>(transferMode, binding.TransferMode); } [WcfTheory] [InlineData(HttpProxyCredentialType.Basic, AuthenticationSchemes.Basic)] [InlineData(HttpProxyCredentialType.Digest, AuthenticationSchemes.Digest)] [InlineData(HttpProxyCredentialType.None, AuthenticationSchemes.Anonymous)] [InlineData(HttpProxyCredentialType.Ntlm, AuthenticationSchemes.Ntlm)] [InlineData(HttpProxyCredentialType.Windows, AuthenticationSchemes.Negotiate)] public static void ProxyCredentialType_Propagates_To_TransportBindingElement(HttpProxyCredentialType credentialType, AuthenticationSchemes mappedAuthScheme) { var binding = new BasicHttpBinding(BasicHttpSecurityMode.Transport); binding.Security.Transport.ProxyCredentialType = credentialType; var be = binding.CreateBindingElements(); var htbe = be.Find<HttpTransportBindingElement>(); Assert.Equal(mappedAuthScheme, htbe.ProxyAuthenticationScheme); } [WcfFact] public static void ExtendedProtectionPolicy_Propagates_To_TransportBindingElement() { var binding = new BasicHttpBinding(BasicHttpSecurityMode.Transport); var epp = new ExtendedProtectionPolicy(PolicyEnforcement.Always); binding.Security.Transport.ExtendedProtectionPolicy = epp; var be = binding.CreateBindingElements(); var htbe = be.Find<HttpTransportBindingElement>(); Assert.Equal(epp, htbe.ExtendedProtectionPolicy); } }
/* ==================================================================== Copyright (C) 2004-2008 fyiReporting Software, LLC This file is part of the fyiReporting RDL project. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. For additional information, email info@fyireporting.com or visit the website www.fyiReporting.com. */ using System; using fyiReporting.RDL; using System.IO; using System.Collections; using System.Text; namespace fyiReporting.RDL { ///<summary> ///The primary class to "run" a report to XML ///</summary> internal class RenderCsv : IPresent { Report report; // report DelimitedTextWriter tw; // where the output is going public RenderCsv(Report report, IStreamGen sg) { this.report = report; tw = new DelimitedTextWriter(sg.GetTextWriter(), ","); } public Report Report() { return report; } public bool IsPagingNeeded() { return false; } public void Start() { } public void End() { } public void RunPages(Pages pgs) { } public void BodyStart(Body b) { } public void BodyEnd(Body b) { } public void PageHeaderStart(PageHeader ph) { } public void PageHeaderEnd(PageHeader ph) { if (ph.PrintOnFirstPage||ph.PrintOnLastPage) {tw.WriteLine();} } public void PageFooterStart(PageFooter pf) { } public void PageFooterEnd(PageFooter pf) { if (pf.PrintOnLastPage || pf.PrintOnFirstPage) {tw.WriteLine();} } public void Textbox(Textbox tb, string t, Row r) { object value = tb.Evaluate(report, r); tw.Write(value); } public void DataRegionNoRows(DataRegion d, string noRowsMsg) { } public bool ListStart(List l, Row r) { return true; } public void ListEnd(List l, Row r) { tw.WriteLine(); } public void ListEntryBegin(List l, Row r) { } public void ListEntryEnd(List l, Row r) { tw.WriteLine(); } public bool TableStart(Table t, Row r) { return true; } public void TableEnd(Table t, Row r) { } public void TableBodyStart(Table t, Row r) { } public void TableBodyEnd(Table t, Row r) { } public void TableFooterStart(Footer f, Row r) { } public void TableFooterEnd(Footer f, Row r) { } public void TableHeaderStart(Header h, Row r) { } public void TableHeaderEnd(Header h, Row r) { } public void TableRowStart(TableRow tr, Row r) { } public void TableRowEnd(TableRow tr, Row r) { tw.WriteLine(); } public void TableCellStart(TableCell t, Row r) { } public void TableCellEnd(TableCell t, Row r) { } public bool MatrixStart(Matrix m, MatrixCellEntry[,] matrix, Row r, int headerRows, int maxRows, int maxCols) { return true; } public void MatrixColumns(Matrix m, MatrixColumns mc) { } public void MatrixRowStart(Matrix m, int row, Row r) { } public void MatrixRowEnd(Matrix m, int row, Row r) { tw.WriteLine(); } public void MatrixCellStart(Matrix m, ReportItem ri, int row, int column, Row r, float h, float w, int colSpan) { } public void MatrixCellEnd(Matrix m, ReportItem ri, int row, int column, Row r) { } public void MatrixEnd(Matrix m, Row r) { } public void Chart(Chart c, Row r, ChartBase cb) { } public void Image(Image i, Row r, string mimeType, Stream io) { } public void Line(Line l, Row r) { } public bool RectangleStart(Rectangle rect, Row r) { return true; } public void RectangleEnd(Rectangle rect, Row r) { } public void Subreport(Subreport s, Row r) { } public void GroupingStart(Grouping g) { } public void GroupingInstanceStart(Grouping g) { } public void GroupingInstanceEnd(Grouping g) { } public void GroupingEnd(Grouping g) { } } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; #if UNITY_WSA using Windows.System.Threading; #elif !UNITY_WEBGL using System.Threading; #endif namespace Foundation.Tasks { /// <summary> /// Describes the Tasks State /// </summary> public enum TaskStatus { /// <summary> /// Ready to run /// </summary> Created, /// <summary> /// Working /// </summary> Running, /// <summary> /// Exception as thrown or otherwise stopped early /// </summary> Faulted, /// <summary> /// Complete without error /// </summary> Success, /// <summary> /// Dispose has been called /// </summary> Disposed, } /// <summary> /// Execution strategy for the Task /// </summary> public enum TaskStrategy { #if !UNITY_WEBGL /// <summary> /// Dispatches the task to a background thread /// </summary> BackgroundThread, #endif /// <summary> /// Dispatches the task to the main thread /// </summary> MainThread, /// <summary> /// Dispatches the task to the current thread /// </summary> CurrentThread, /// <summary> /// Runs the task as a coroutine /// </summary> Coroutine, /// <summary> /// Does nothing. For custom tasks. /// </summary> Custom, } /// <summary> /// A task encapsulates future work that may be waited on. /// - Support running actions in background threads /// - Supports running coroutines with return results /// - Use the WaitForRoutine method to wait for the task in a coroutine /// </summary> /// <example> /// <code> /// var task = Task.Run(() => /// { /// //Debug.Log does not work in /// Debug.Log("Sleeping..."); /// Task.Delay(2000); /// Debug.Log("Slept"); /// }); /// // wait for it /// yield return StartCoroutine(task.WaitRoutine()); /// /// // check exceptions /// if(task.IsFaulted) /// Debug.LogException(task.Exception) ///</code> ///</example> public partial class UnityTask : IDisposable { #region options /// <summary> /// Forces use of a single thread for debugging /// </summary> public static bool DisableMultiThread = false; /// <summary> /// Logs Exceptions /// </summary> public static bool LogErrors = false; #endregion #region fields // ReSharper disable InconsistentNaming /// <summary> /// Input Parameter /// </summary> public object Paramater { get; set; } /// <summary> /// Execution option /// </summary> public TaskStrategy Strategy; Action _action; Delegate _action2; protected IEnumerator _routine; protected List<Delegate> CompleteList = new List<Delegate>(); protected List<Delegate> SuccessList = new List<Delegate>(); #endregion #region properties private TaskStatus _status; public TaskStatus Status { get { return _status; } set { if (_status == value) return; _status = value; if (IsCompleted) OnTaskComplete(); } } public Exception Exception { get; set; } #endregion #region computed properties public bool IsRunning { get { return Status == TaskStatus.Running; } } public bool IsCompleted { get { return Status == TaskStatus.Success || Status == TaskStatus.Faulted; } } public bool IsFaulted { get { return Status == TaskStatus.Faulted; } } public bool IsSuccess { get { return Status == TaskStatus.Success; } } #endregion #region constructor static UnityTask() { TaskManager.ConfirmInit(); } /// <summary> /// Creates a new task /// </summary> protected UnityTask() { Status = TaskStatus.Created; } /// <summary> /// Creates a new task /// </summary> public UnityTask(TaskStrategy mode) : this() { Strategy = mode; } /// <summary> /// Creates a new Task in a Faulted state /// </summary> /// <param name="ex"></param> public UnityTask(Exception ex) { Exception = ex; Strategy = TaskStrategy.Custom; Status = TaskStatus.Faulted; } /// <summary> /// Creates a new background task /// </summary> /// <param name="action"></param> public UnityTask(Action action) : this() { _action = action; #if UNITY_WEBGL Strategy = TaskStrategy.MainThread; #else Strategy = TaskStrategy.BackgroundThread; #endif } /// <summary> /// Creates a new Task /// </summary> /// <param name="action"></param> /// <param name="mode"></param> public UnityTask(Action action, TaskStrategy mode) : this() { if (mode == TaskStrategy.Coroutine) throw new ArgumentException("Action tasks may not be coroutines"); _action = action; Strategy = mode; } /// <summary> /// Creates a new Coroutine Task /// </summary> /// <param name="action"></param> public UnityTask(IEnumerator action) : this() { if (action == null) throw new ArgumentNullException("action"); _routine = action; Strategy = TaskStrategy.Coroutine; } /// <summary> /// Creates a new Coroutine Task /// </summary> /// <param name="action"></param> /// <param name="param"></param> public UnityTask(IEnumerator action, object param) : this() { if (action == null) throw new ArgumentNullException("action"); _routine = action; Strategy = TaskStrategy.Coroutine; Paramater = param; } /// <summary> /// Creates a new background task with a parameter /// </summary> /// <param name="action"></param> /// <param name="paramater"></param> public UnityTask(Delegate action, object paramater) : this() { _action2 = action; #if UNITY_WEBGL Strategy = TaskStrategy.MainThread; #else Strategy = TaskStrategy.BackgroundThread; #endif Paramater = paramater; } /// <summary> /// Creates a new Task with a parameter /// </summary> /// <param name="action"></param> /// <param name="paramater"></param> /// <param name="mode"></param> public UnityTask(Delegate action, object paramater, TaskStrategy mode) : this() { if (mode == TaskStrategy.Coroutine) throw new ArgumentException("Action tasks may not be coroutines"); _action2 = action; Strategy = mode; Paramater = paramater; } #endregion #region Private protected virtual void Execute() { try { if (_action2 != null) { _action2.DynamicInvoke(Paramater); } else if (_action != null) { _action(); } Status = TaskStatus.Success; } catch (Exception ex) { Exception = ex; Status = TaskStatus.Faulted; if (LogErrors) Debug.LogException(ex); } } #if !UNITY_WEBGL /// <summary> /// Executes the task in background thread /// </summary> #if UNITY_WSA protected async void RunOnBackgroundThread() { Status = TaskStatus.Running; await ThreadPool.RunAsync(o => Execute()); #else protected void RunOnBackgroundThread() { Status = TaskStatus.Running; ThreadPool.QueueUserWorkItem(state => Execute()); #endif } #endif /// <summary> /// Executes the task in background thread /// </summary> protected void RunOnCurrentThread() { Status = TaskStatus.Running; Execute(); } /// <summary> /// Executes the task on the main thread /// </summary> protected void RunOnMainThread() { Status = TaskStatus.Running; #if UNITY_WEBGL Execute(); #else TaskManager.RunOnMainThread(Execute); #endif } /// <summary> /// Executes the task in a coroutine /// </summary> protected void RunAsCoroutine() { Status = TaskStatus.Running; TaskManager.StartRoutine(new TaskManager.CoroutineCommand { Coroutine = _routine, OnComplete = OnRoutineComplete }); } protected virtual void OnTaskComplete() { foreach (var d in CompleteList) { if (d != null) d.DynamicInvoke(this); } CompleteList.Clear(); if (IsSuccess) { foreach (var d in SuccessList) { if (d != null) d.DynamicInvoke(); } } SuccessList.Clear(); } protected void OnRoutineComplete() { if (Status == TaskStatus.Running || Status == TaskStatus.Created) Status = TaskStatus.Success; } #endregion #region public methods /// <summary> /// Executes the task /// </summary> public void Start() { if (IsCompleted) { return; } switch (Strategy) { case TaskStrategy.Coroutine: RunAsCoroutine(); break; #if UNITY_WEBGL default: RunOnCurrentThread(); break; #else case TaskStrategy.BackgroundThread: if (DisableMultiThread) RunOnCurrentThread(); else RunOnBackgroundThread(); break; case TaskStrategy.CurrentThread: RunOnCurrentThread(); break; case TaskStrategy.MainThread: RunOnMainThread(); break; #endif } } /// <summary> /// will throw if faulted /// </summary> /// <returns></returns> public UnityTask ThrowIfFaulted() { if (IsFaulted) throw Exception; return this; } /// <summary> /// Thread.Sleep /// </summary> /// <param name="millisecondTimeout"></param> #if UNITY_WSA public async static System.Threading.Tasks.Task Delay(int millisecondTimeout) { await System.Threading.Tasks.Task.Delay(TimeSpan.FromMilliseconds(millisecondTimeout)); } #elif UNITY_WEBGL public static void Delay(int millisecondTimeout) { Debug.LogError("Delay not supported on WebGL"); } #else public static void Delay(int millisecondTimeout) { Thread.Sleep(millisecondTimeout); } #endif public virtual void Dispose() { Status = TaskStatus.Created; Paramater = null; Exception = null; _action = null; _action2 = null; _routine = null; CompleteList.Clear(); SuccessList.Clear(); } #endregion #region wait /// <summary> /// Wait for the task to complete in an iterator coroutine /// </summary> /// <returns></returns> public IEnumerator WaitRoutine() { while (IsRunning || CompleteList.Count > 0) { yield return 1; } } /// <summary> /// Waits for the task to complete /// </summary> public UnityTask Wait() { if (TaskManager.IsMainThread && !DisableMultiThread) { Debug.LogWarning("Use WaitRoutine in coroutine to wait in main thread"); } Delay(10); while (IsRunning || CompleteList.Count > 0) { Delay(10); } return this; } #endregion #region continue with /// <summary> /// Called after the task is complete /// </summary> /// <param name="action"></param> /// <returns></returns> public UnityTask ContinueWith(Action<UnityTask> action) { if (IsCompleted) { action(this); } else { CompleteList.Add(action); } return this; } /// <summary> /// Called after the task is complete /// </summary> /// <param name="action"></param> /// <returns></returns> public K ContinueWith<K>(Action<K> action) where K : UnityTask { if (IsCompleted) { action((K)this); } else { CompleteList.Add(action); } return (K)this; } /// <summary> /// Called after a successful task execution /// </summary> /// <param name="action"></param> /// <returns></returns> public UnityTask OnSuccess(Action action) { if (IsCompleted && IsSuccess) { action(); } else { SuccessList.Add(action); } return this; } #endregion } }
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; using Abp.Application.Features; using Abp.Authorization.Roles; using Abp.Configuration; using Abp.Configuration.Startup; using Abp.Domain.Repositories; using Abp.Domain.Services; using Abp.Domain.Uow; using Abp.IdentityFramework; using Abp.Localization; using Abp.MultiTenancy; using Abp.Organizations; using Abp.Runtime.Caching; using Abp.Runtime.Security; using Abp.Runtime.Session; using Abp.Zero; using Abp.Zero.Configuration; using Microsoft.AspNet.Identity; namespace Abp.Authorization.Users { /// <summary> /// Extends <see cref="UserManager{TUser,TKey}"/> of ASP.NET Identity Framework. /// </summary> public abstract class AbpUserManager<TRole, TUser> : UserManager<TUser, long>, IDomainService where TRole : AbpRole<TUser>, new() where TUser : AbpUser<TUser> { protected IUserPermissionStore<TUser> UserPermissionStore { get { if (!(Store is IUserPermissionStore<TUser>)) { throw new AbpException("Store is not IUserPermissionStore"); } return Store as IUserPermissionStore<TUser>; } } public ILocalizationManager LocalizationManager { get; } protected string LocalizationSourceName { get; set; } public IAbpSession AbpSession { get; set; } public FeatureDependencyContext FeatureDependencyContext { get; set; } protected AbpRoleManager<TRole, TUser> RoleManager { get; } public AbpUserStore<TRole, TUser> AbpStore { get; } public IMultiTenancyConfig MultiTenancy { get; set; } private readonly IPermissionManager _permissionManager; private readonly IUnitOfWorkManager _unitOfWorkManager; private readonly ICacheManager _cacheManager; private readonly IRepository<OrganizationUnit, long> _organizationUnitRepository; private readonly IRepository<UserOrganizationUnit, long> _userOrganizationUnitRepository; private readonly IOrganizationUnitSettings _organizationUnitSettings; private readonly ISettingManager _settingManager; protected AbpUserManager( AbpUserStore<TRole, TUser> userStore, AbpRoleManager<TRole, TUser> roleManager, IPermissionManager permissionManager, IUnitOfWorkManager unitOfWorkManager, ICacheManager cacheManager, IRepository<OrganizationUnit, long> organizationUnitRepository, IRepository<UserOrganizationUnit, long> userOrganizationUnitRepository, IOrganizationUnitSettings organizationUnitSettings, ILocalizationManager localizationManager, IdentityEmailMessageService emailService, ISettingManager settingManager, IUserTokenProviderAccessor userTokenProviderAccessor) : base(userStore) { AbpStore = userStore; RoleManager = roleManager; LocalizationManager = localizationManager; LocalizationSourceName = AbpZeroConsts.LocalizationSourceName; _settingManager = settingManager; _permissionManager = permissionManager; _unitOfWorkManager = unitOfWorkManager; _cacheManager = cacheManager; _organizationUnitRepository = organizationUnitRepository; _userOrganizationUnitRepository = userOrganizationUnitRepository; _organizationUnitSettings = organizationUnitSettings; AbpSession = NullAbpSession.Instance; UserLockoutEnabledByDefault = true; DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5); MaxFailedAccessAttemptsBeforeLockout = 5; EmailService = emailService; UserTokenProvider = userTokenProviderAccessor.GetUserTokenProviderOrNull<TUser>(); } public override async Task<IdentityResult> CreateAsync(TUser user) { var result = await CheckDuplicateUsernameOrEmailAddressAsync(user.Id, user.UserName, user.EmailAddress); if (!result.Succeeded) { return result; } var tenantId = GetCurrentTenantId(); if (tenantId.HasValue && !user.TenantId.HasValue) { user.TenantId = tenantId.Value; } InitializeLockoutSettings(user.TenantId); return await base.CreateAsync(user); } /// <summary> /// Check whether a user is granted for a permission. /// </summary> /// <param name="userId">User id</param> /// <param name="permissionName">Permission name</param> public virtual async Task<bool> IsGrantedAsync(long userId, string permissionName) { return await IsGrantedAsync( userId, _permissionManager.GetPermission(permissionName) ); } /// <summary> /// Check whether a user is granted for a permission. /// </summary> /// <param name="user">User</param> /// <param name="permission">Permission</param> public virtual Task<bool> IsGrantedAsync(TUser user, Permission permission) { return IsGrantedAsync(user.Id, permission); } /// <summary> /// Check whether a user is granted for a permission. /// </summary> /// <param name="userId">User id</param> /// <param name="permission">Permission</param> public virtual async Task<bool> IsGrantedAsync(long userId, Permission permission) { //Check for multi-tenancy side if (!permission.MultiTenancySides.HasFlag(GetCurrentMultiTenancySide())) { return false; } //Check for depended features if (permission.FeatureDependency != null && GetCurrentMultiTenancySide() == MultiTenancySides.Tenant) { FeatureDependencyContext.TenantId = GetCurrentTenantId(); if (!await permission.FeatureDependency.IsSatisfiedAsync(FeatureDependencyContext)) { return false; } } //Get cached user permissions var cacheItem = await GetUserPermissionCacheItemAsync(userId); if (cacheItem == null) { return false; } //Check for user-specific value if (cacheItem.GrantedPermissions.Contains(permission.Name)) { return true; } if (cacheItem.ProhibitedPermissions.Contains(permission.Name)) { return false; } //Check for roles foreach (var roleId in cacheItem.RoleIds) { if (await RoleManager.IsGrantedAsync(roleId, permission)) { return true; } } return false; } /// <summary> /// Gets granted permissions for a user. /// </summary> /// <param name="user">Role</param> /// <returns>List of granted permissions</returns> public virtual async Task<IReadOnlyList<Permission>> GetGrantedPermissionsAsync(TUser user) { var permissionList = new List<Permission>(); foreach (var permission in _permissionManager.GetAllPermissions()) { if (await IsGrantedAsync(user.Id, permission)) { permissionList.Add(permission); } } return permissionList; } /// <summary> /// Sets all granted permissions of a user at once. /// Prohibits all other permissions. /// </summary> /// <param name="user">The user</param> /// <param name="permissions">Permissions</param> public virtual async Task SetGrantedPermissionsAsync(TUser user, IEnumerable<Permission> permissions) { var oldPermissions = await GetGrantedPermissionsAsync(user); var newPermissions = permissions.ToArray(); foreach (var permission in oldPermissions.Where(p => !newPermissions.Contains(p))) { await ProhibitPermissionAsync(user, permission); } foreach (var permission in newPermissions.Where(p => !oldPermissions.Contains(p))) { await GrantPermissionAsync(user, permission); } } /// <summary> /// Prohibits all permissions for a user. /// </summary> /// <param name="user">User</param> public async Task ProhibitAllPermissionsAsync(TUser user) { foreach (var permission in _permissionManager.GetAllPermissions()) { await ProhibitPermissionAsync(user, permission); } } /// <summary> /// Resets all permission settings for a user. /// It removes all permission settings for the user. /// User will have permissions according to his roles. /// This method does not prohibit all permissions. /// For that, use <see cref="ProhibitAllPermissionsAsync"/>. /// </summary> /// <param name="user">User</param> public async Task ResetAllPermissionsAsync(TUser user) { await UserPermissionStore.RemoveAllPermissionSettingsAsync(user); } /// <summary> /// Grants a permission for a user if not already granted. /// </summary> /// <param name="user">User</param> /// <param name="permission">Permission</param> public virtual async Task GrantPermissionAsync(TUser user, Permission permission) { await UserPermissionStore.RemovePermissionAsync(user, new PermissionGrantInfo(permission.Name, false)); if (await IsGrantedAsync(user.Id, permission)) { return; } await UserPermissionStore.AddPermissionAsync(user, new PermissionGrantInfo(permission.Name, true)); } /// <summary> /// Prohibits a permission for a user if it's granted. /// </summary> /// <param name="user">User</param> /// <param name="permission">Permission</param> public virtual async Task ProhibitPermissionAsync(TUser user, Permission permission) { await UserPermissionStore.RemovePermissionAsync(user, new PermissionGrantInfo(permission.Name, true)); if (!await IsGrantedAsync(user.Id, permission)) { return; } await UserPermissionStore.AddPermissionAsync(user, new PermissionGrantInfo(permission.Name, false)); } public virtual async Task<TUser> FindByNameOrEmailAsync(string userNameOrEmailAddress) { return await AbpStore.FindByNameOrEmailAsync(userNameOrEmailAddress); } public virtual Task<List<TUser>> FindAllAsync(UserLoginInfo login) { return AbpStore.FindAllAsync(login); } /// <summary> /// Gets a user by given id. /// Throws exception if no user found with given id. /// </summary> /// <param name="userId">User id</param> /// <returns>User</returns> /// <exception cref="AbpException">Throws exception if no user found with given id</exception> public virtual async Task<TUser> GetUserByIdAsync(long userId) { var user = await FindByIdAsync(userId); if (user == null) { throw new AbpException("There is no user with id: " + userId); } return user; } public async override Task<ClaimsIdentity> CreateIdentityAsync(TUser user, string authenticationType) { var identity = await base.CreateIdentityAsync(user, authenticationType); if (user.TenantId.HasValue) { identity.AddClaim(new Claim(AbpClaimTypes.TenantId, user.TenantId.Value.ToString(CultureInfo.InvariantCulture))); } return identity; } public async override Task<IdentityResult> UpdateAsync(TUser user) { var result = await CheckDuplicateUsernameOrEmailAddressAsync(user.Id, user.UserName, user.EmailAddress); if (!result.Succeeded) { return result; } //Admin user's username can not be changed! if (user.UserName != AbpUser<TUser>.AdminUserName) { if ((await GetOldUserNameAsync(user.Id)) == AbpUser<TUser>.AdminUserName) { return AbpIdentityResult.Failed(string.Format(L("CanNotRenameAdminUser"), AbpUser<TUser>.AdminUserName)); } } return await base.UpdateAsync(user); } public async override Task<IdentityResult> DeleteAsync(TUser user) { if (user.UserName == AbpUser<TUser>.AdminUserName) { return AbpIdentityResult.Failed(string.Format(L("CanNotDeleteAdminUser"), AbpUser<TUser>.AdminUserName)); } return await base.DeleteAsync(user); } public virtual async Task<IdentityResult> ChangePasswordAsync(TUser user, string newPassword) { var result = await PasswordValidator.ValidateAsync(newPassword); if (!result.Succeeded) { return result; } await AbpStore.SetPasswordHashAsync(user, PasswordHasher.HashPassword(newPassword)); return IdentityResult.Success; } public virtual async Task<IdentityResult> CheckDuplicateUsernameOrEmailAddressAsync(long? expectedUserId, string userName, string emailAddress) { var user = (await FindByNameAsync(userName)); if (user != null && user.Id != expectedUserId) { return AbpIdentityResult.Failed(string.Format(L("Identity.DuplicateUserName"), userName)); } user = (await FindByEmailAsync(emailAddress)); if (user != null && user.Id != expectedUserId) { return AbpIdentityResult.Failed(string.Format(L("Identity.DuplicateEmail"), emailAddress)); } return IdentityResult.Success; } public virtual async Task<IdentityResult> SetRoles(TUser user, string[] roleNames) { //Remove from removed roles foreach (var userRole in user.Roles.ToList()) { var role = await RoleManager.FindByIdAsync(userRole.RoleId); if (roleNames.All(roleName => role.Name != roleName)) { var result = await RemoveFromRoleAsync(user.Id, role.Name); if (!result.Succeeded) { return result; } } } //Add to added roles foreach (var roleName in roleNames) { var role = await RoleManager.GetRoleByNameAsync(roleName); if (user.Roles.All(ur => ur.RoleId != role.Id)) { var result = await AddToRoleAsync(user.Id, roleName); if (!result.Succeeded) { return result; } } } return IdentityResult.Success; } public virtual async Task<bool> IsInOrganizationUnitAsync(long userId, long ouId) { return await IsInOrganizationUnitAsync( await GetUserByIdAsync(userId), await _organizationUnitRepository.GetAsync(ouId) ); } public virtual async Task<bool> IsInOrganizationUnitAsync(TUser user, OrganizationUnit ou) { return await _userOrganizationUnitRepository.CountAsync(uou => uou.UserId == user.Id && uou.OrganizationUnitId == ou.Id ) > 0; } public virtual async Task AddToOrganizationUnitAsync(long userId, long ouId) { await AddToOrganizationUnitAsync( await GetUserByIdAsync(userId), await _organizationUnitRepository.GetAsync(ouId) ); } public virtual async Task AddToOrganizationUnitAsync(TUser user, OrganizationUnit ou) { var currentOus = await GetOrganizationUnitsAsync(user); if (currentOus.Any(cou => cou.Id == ou.Id)) { return; } await CheckMaxUserOrganizationUnitMembershipCountAsync(user.TenantId, currentOus.Count + 1); await _userOrganizationUnitRepository.InsertAsync(new UserOrganizationUnit(user.TenantId, user.Id, ou.Id)); } public virtual async Task RemoveFromOrganizationUnitAsync(long userId, long ouId) { await RemoveFromOrganizationUnitAsync( await GetUserByIdAsync(userId), await _organizationUnitRepository.GetAsync(ouId) ); } public virtual async Task RemoveFromOrganizationUnitAsync(TUser user, OrganizationUnit ou) { await _userOrganizationUnitRepository.DeleteAsync(uou => uou.UserId == user.Id && uou.OrganizationUnitId == ou.Id); } public virtual async Task SetOrganizationUnitsAsync(long userId, params long[] organizationUnitIds) { await SetOrganizationUnitsAsync( await GetUserByIdAsync(userId), organizationUnitIds ); } private async Task CheckMaxUserOrganizationUnitMembershipCountAsync(int? tenantId, int requestedCount) { var maxCount = await _organizationUnitSettings.GetMaxUserMembershipCountAsync(tenantId); if (requestedCount > maxCount) { throw new AbpException(string.Format("Can not set more than {0} organization unit for a user!", maxCount)); } } public virtual async Task SetOrganizationUnitsAsync(TUser user, params long[] organizationUnitIds) { if (organizationUnitIds == null) { organizationUnitIds = new long[0]; } await CheckMaxUserOrganizationUnitMembershipCountAsync(user.TenantId, organizationUnitIds.Length); var currentOus = await GetOrganizationUnitsAsync(user); //Remove from removed OUs foreach (var currentOu in currentOus) { if (!organizationUnitIds.Contains(currentOu.Id)) { await RemoveFromOrganizationUnitAsync(user, currentOu); } } //Add to added OUs foreach (var organizationUnitId in organizationUnitIds) { if (currentOus.All(ou => ou.Id != organizationUnitId)) { await AddToOrganizationUnitAsync( user, await _organizationUnitRepository.GetAsync(organizationUnitId) ); } } } [UnitOfWork] public virtual Task<List<OrganizationUnit>> GetOrganizationUnitsAsync(TUser user) { var query = from uou in _userOrganizationUnitRepository.GetAll() join ou in _organizationUnitRepository.GetAll() on uou.OrganizationUnitId equals ou.Id where uou.UserId == user.Id select ou; return Task.FromResult(query.ToList()); } [UnitOfWork] public virtual Task<List<TUser>> GetUsersInOrganizationUnit(OrganizationUnit organizationUnit, bool includeChildren = false) { if (!includeChildren) { var query = from uou in _userOrganizationUnitRepository.GetAll() join user in AbpStore.Users on uou.UserId equals user.Id where uou.OrganizationUnitId == organizationUnit.Id select user; return Task.FromResult(query.ToList()); } else { var query = from uou in _userOrganizationUnitRepository.GetAll() join user in AbpStore.Users on uou.UserId equals user.Id join ou in _organizationUnitRepository.GetAll() on uou.OrganizationUnitId equals ou.Id where ou.Code.StartsWith(organizationUnit.Code) select user; return Task.FromResult(query.ToList()); } } public virtual void RegisterTwoFactorProviders(int? tenantId) { TwoFactorProviders.Clear(); if (!IsTrue(AbpZeroSettingNames.UserManagement.TwoFactorLogin.IsEnabled, tenantId)) { return; } if (EmailService != null && IsTrue(AbpZeroSettingNames.UserManagement.TwoFactorLogin.IsEmailProviderEnabled, tenantId)) { RegisterTwoFactorProvider( L("Email"), new EmailTokenProvider<TUser, long> { Subject = L("EmailSecurityCodeSubject"), BodyFormat = L("EmailSecurityCodeBody") } ); } if (SmsService != null && IsTrue(AbpZeroSettingNames.UserManagement.TwoFactorLogin.IsSmsProviderEnabled, tenantId)) { RegisterTwoFactorProvider( L("Sms"), new PhoneNumberTokenProvider<TUser, long> { MessageFormat = L("SmsSecurityCodeMessage") } ); } } public virtual void InitializeLockoutSettings(int? tenantId) { UserLockoutEnabledByDefault = IsTrue(AbpZeroSettingNames.UserManagement.UserLockOut.IsEnabled, tenantId); DefaultAccountLockoutTimeSpan = TimeSpan.FromSeconds(GetSettingValue<int>(AbpZeroSettingNames.UserManagement.UserLockOut.DefaultAccountLockoutSeconds, tenantId)); MaxFailedAccessAttemptsBeforeLockout = GetSettingValue<int>(AbpZeroSettingNames.UserManagement.UserLockOut.MaxFailedAccessAttemptsBeforeLockout, tenantId); } public override async Task<IList<string>> GetValidTwoFactorProvidersAsync(long userId) { var user = await GetUserByIdAsync(userId); RegisterTwoFactorProviders(user.TenantId); return await base.GetValidTwoFactorProvidersAsync(userId); } public override async Task<IdentityResult> NotifyTwoFactorTokenAsync(long userId, string twoFactorProvider, string token) { var user = await GetUserByIdAsync(userId); RegisterTwoFactorProviders(user.TenantId); return await base.NotifyTwoFactorTokenAsync(userId, twoFactorProvider, token); } public override async Task<string> GenerateTwoFactorTokenAsync(long userId, string twoFactorProvider) { var user = await GetUserByIdAsync(userId); RegisterTwoFactorProviders(user.TenantId); return await base.GenerateTwoFactorTokenAsync(userId, twoFactorProvider); } public override async Task<bool> VerifyTwoFactorTokenAsync(long userId, string twoFactorProvider, string token) { var user = await GetUserByIdAsync(userId); RegisterTwoFactorProviders(user.TenantId); return await base.VerifyTwoFactorTokenAsync(userId, twoFactorProvider, token); } protected virtual Task<string> GetOldUserNameAsync(long userId) { return AbpStore.GetUserNameFromDatabaseAsync(userId); } private async Task<UserPermissionCacheItem> GetUserPermissionCacheItemAsync(long userId) { var cacheKey = userId + "@" + (GetCurrentTenantId() ?? 0); return await _cacheManager.GetUserPermissionCache().GetAsync(cacheKey, async () => { var user = await FindByIdAsync(userId); if (user == null) { return null; } var newCacheItem = new UserPermissionCacheItem(userId); foreach (var roleName in await GetRolesAsync(userId)) { newCacheItem.RoleIds.Add((await RoleManager.GetRoleByNameAsync(roleName)).Id); } foreach (var permissionInfo in await UserPermissionStore.GetPermissionsAsync(userId)) { if (permissionInfo.IsGranted) { newCacheItem.GrantedPermissions.Add(permissionInfo.Name); } else { newCacheItem.ProhibitedPermissions.Add(permissionInfo.Name); } } return newCacheItem; }); } private bool IsTrue(string settingName, int? tenantId) { return GetSettingValue<bool>(settingName, tenantId); } private T GetSettingValue<T>(string settingName, int? tenantId) where T : struct { return tenantId == null ? _settingManager.GetSettingValueForApplication<T>(settingName) : _settingManager.GetSettingValueForTenant<T>(settingName, tenantId.Value); } protected virtual string L(string name) { return LocalizationManager.GetString(LocalizationSourceName, name); } protected virtual string L(string name, CultureInfo cultureInfo) { return LocalizationManager.GetString(LocalizationSourceName, name, cultureInfo); } private int? GetCurrentTenantId() { if (_unitOfWorkManager.Current != null) { return _unitOfWorkManager.Current.GetTenantId(); } return AbpSession.TenantId; } private MultiTenancySides GetCurrentMultiTenancySide() { if (_unitOfWorkManager.Current != null) { return MultiTenancy.IsEnabled && !_unitOfWorkManager.Current.GetTenantId().HasValue ? MultiTenancySides.Host : MultiTenancySides.Tenant; } return AbpSession.MultiTenancySide; } } }
// Copyright (c) 2013 SIL International // This software is licensed under the MIT license (http://opensource.org/licenses/MIT) using System; using System.Collections.Generic; using System.Linq; using NUnit.Framework; namespace Icu.Tests { [TestFixture] [Category("Full ICU")] public class BreakIteratorTests { [TestCase(BreakIterator.UBreakIteratorType.CHARACTER, "abc", ExpectedResult = new[] { "a", "b", "c"})] [TestCase(BreakIterator.UBreakIteratorType.WORD, "Aa Bb. Cc", ExpectedResult = new[] { "Aa", "Bb", "Cc"})] [TestCase(BreakIterator.UBreakIteratorType.LINE, "Aa Bb. Cc", ExpectedResult = new[] { "Aa ", "Bb. ", "Cc"})] [TestCase(BreakIterator.UBreakIteratorType.SENTENCE, "Aa bb. Cc 3.5 x? Y?x! Z", ExpectedResult = new[] { "Aa bb. ", "Cc 3.5 x? ", "Y?", "x! ", "Z"})] public IEnumerable<string> Split(BreakIterator.UBreakIteratorType type, string text) { return BreakIterator.Split(type, "en-US", text); } [Test] public void GetBoundaries_Character() { var text = "abc? 1"; var expected = new[] { new Boundary(0, 1), new Boundary(1, 2), new Boundary(2, 3), new Boundary(3, 4), new Boundary(4, 5), new Boundary(5, 6) }; var parts = BreakIterator.GetBoundaries(BreakIterator.UBreakIteratorType.CHARACTER, new Locale("en-US"), text); Assert.That(parts.Count(), Is.EqualTo(expected.Length)); Assert.That(parts.ToArray(), Is.EquivalentTo(expected)); } [Test] public void GetBoundaries_Word() { var parts = BreakIterator.GetBoundaries(BreakIterator.UBreakIteratorType.WORD, new Locale("en-US"), WordBoundaryTestData.Text); Assert.That(parts.Count(), Is.EqualTo(WordBoundaryTestData.ExpectedOnlyWords.Length)); Assert.That(parts.ToArray(), Is.EquivalentTo(WordBoundaryTestData.ExpectedOnlyWords)); } [Test] public void GetBoundaries_Line() { var text = "Aa bb. Ccdef 3.5 x? Y?x! Z"; var expected = new[] { new Boundary(0, 3), new Boundary(3, 7), new Boundary(7, 13), new Boundary(13, 17), new Boundary(17, 20), new Boundary(20, 22), new Boundary(22, 25), new Boundary(25, 26) }; var parts = BreakIterator.GetBoundaries(BreakIterator.UBreakIteratorType.LINE, new Locale("en-US"), text); Assert.That(parts.Count(), Is.EqualTo(expected.Length)); Assert.That(parts.ToArray(), Is.EquivalentTo(expected)); } [Test] public void GetBoundaries_Sentence() { var text = "Aa bb. Ccdef 3.5 x? Y?x! Z"; var expected = new[] { new Boundary(0, 7), new Boundary(7, 20), new Boundary(20, 22), new Boundary(22, 25), new Boundary(25, 26) }; var parts = BreakIterator.GetBoundaries(BreakIterator.UBreakIteratorType.SENTENCE, new Locale("en-US"), text); Assert.That(parts.Count(), Is.EqualTo(expected.Length)); Assert.That(parts.ToArray(), Is.EquivalentTo(expected)); } [Test] public void GetWordBoundaries_IgnoreSpacesAndPunctuation() { var onlyWords = BreakIterator.GetWordBoundaries(new Locale("en-US"), WordBoundaryTestData.Text, false); Assert.That(onlyWords.Count(), Is.EqualTo(WordBoundaryTestData.ExpectedOnlyWords.Length)); Assert.That(onlyWords.ToArray(), Is.EquivalentTo(WordBoundaryTestData.ExpectedOnlyWords)); } [Test] public void GetWordBoundaries_IncludeSpacesAndPunctuation() { var allBoundaries = BreakIterator.GetWordBoundaries(new Locale("en-US"), WordBoundaryTestData.Text, true); Assert.That(allBoundaries.Count(), Is.EqualTo(WordBoundaryTestData.ExpectedAllBoundaries.Length)); Assert.That(allBoundaries.ToArray(), Is.EquivalentTo(WordBoundaryTestData.ExpectedAllBoundaries)); } /// <summary> /// The hypenated text case tests the difference between Word and Line /// breaks described in: /// http://userguide.icu-project.org/boundaryanalysis#TOC-Line-break-Boundary /// </summary> [Test] public void GetWordAndLineBoundariesWithHyphenatedText() { var text = "Good-day, kind sir !"; var expectedWords = new[] { new Boundary(0, 4), new Boundary(5, 8), new Boundary(10, 14), new Boundary(15, 18) }; var expectedLines = new[] { new Boundary(0, 5), new Boundary(5, 10), new Boundary(10, 15), new Boundary(15, 20) }; var wordBoundaries = BreakIterator.GetBoundaries(BreakIterator.UBreakIteratorType.WORD, new Locale("en-US"), text); var lineBoundaries = BreakIterator.GetBoundaries(BreakIterator.UBreakIteratorType.LINE, new Locale("en-US"), text); Assert.That(wordBoundaries.Count(), Is.EqualTo(expectedWords.Length)); Assert.That(wordBoundaries.ToArray(), Is.EquivalentTo(expectedWords)); Assert.That(lineBoundaries.Count(), Is.EqualTo(expectedLines.Length)); Assert.That(lineBoundaries.ToArray(), Is.EquivalentTo(expectedLines)); } [Test] public void CreateChracterInstanceTest() { var locale = new Locale("de-DE"); var text = "Good-bye, dear!"; var expected = new[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }; using (var bi = BreakIterator.CreateCharacterInstance(locale)) { bi.SetText(text); Assert.That(bi.Locale, Is.EqualTo(locale)); Assert.That(bi.Text, Is.EqualTo(text)); Assert.That(bi.Boundaries, Is.EquivalentTo(expected)); // Verify each boundary and rule status. for (int i = 0; i < expected.Length; i++) { int current = bi.Current; int status = bi.GetRuleStatus(); Assert.AreEqual(expected[i], current); Assert.That(status, Is.EqualTo(0)); int moveNext = bi.MoveNext(); int next = i + 1; if (next < expected.Length) { Assert.AreEqual(expected[next], moveNext); } else { // Verify that the BreakIterator is exhausted because we've // moved past every item. Assert.AreEqual(BreakIterator.DONE, moveNext); } } // Verify that the BreakIterator is exhausted because we've // moved past every item, so current should be the last offset. int lastIndex = expected.Length - 1; Assert.AreEqual(expected[lastIndex], bi.Current); } } /// <summary> /// Checking that when a break iterator is created with "", that it /// returns the correct properties. /// </summary> [Test] public void BreakIteratorThatIsEmpty() { var locale = new Locale("de-DE"); string text = string.Empty; using (var bi = BreakIterator.CreateCharacterInstance(locale)) { bi.SetText(text); Assert.That(bi.Locale, Is.EqualTo(locale)); Assert.That(bi.Text, Is.EqualTo(text)); Assert.That(bi.Boundaries.Length, Is.EqualTo(0)); Assert.That(bi.Current, Is.EqualTo(0)); Assert.AreEqual(BreakIterator.DONE, bi.MoveNext()); Assert.That(bi.MoveFirst(), Is.EqualTo(0)); Assert.That(bi.MoveLast(), Is.EqualTo(0)); Assert.AreEqual(BreakIterator.DONE, bi.MovePrevious()); // Default value is 0 when there was no rule applied. Assert.That(bi.GetRuleStatus(), Is.EqualTo(0)); // When iterator is at DONE, it returns the default rule status vector. Assert.That(bi.GetRuleStatusVector(), Is.EquivalentTo(new[] { 0 })); } } /// <summary> /// Checking that when a break iterator is created with null that it /// throws an ArgumentNullException. /// </summary> [Test] public void BreakIteratorThatIsNull() { var locale = new Locale("de-DE"); using (var bi = BreakIterator.CreateCharacterInstance(locale)) { Assert.Throws<ArgumentNullException>(() => { bi.SetText(null); }); } } [Test] public void CanIterateForwards() { var locale = new Locale("de-DE"); var text = "Good-day, kind sir !"; var expected = new int[] { 0, 4, 5, 8, 9, 10, 14, 15, 18, 19, 20 }; var none = BreakIterator.UWordBreak.NONE; var letter = BreakIterator.UWordBreak.LETTER; var ruleStatus = new[] { none, letter, none, letter, none, none, letter, none, letter, none, none }; using (var bi = BreakIterator.CreateWordInstance(locale)) { bi.SetText(text); Assert.That(bi.Boundaries, Is.EquivalentTo(expected)); // Verify each boundary and rule status. for (int i = 0; i < expected.Length; i++) { int current = bi.Current; int status = bi.GetRuleStatus(); int[] ruleStatusVector = bi.GetRuleStatusVector(); Assert.AreEqual(expected[i], current); Assert.AreEqual((int)ruleStatus[i], status); // There should only be one rule that parsed these. Assert.That(ruleStatusVector.Length, Is.EqualTo(1)); Assert.AreEqual((int)ruleStatus[i], ruleStatusVector[0]); int moveNext = bi.MoveNext(); int next = i + 1; if (next < expected.Length) { Assert.AreEqual(expected[next], moveNext); } else { // Verify that the BreakIterator is exhausted because we've // moved past every item. Assert.AreEqual(BreakIterator.DONE, moveNext); } } // Verify that the BreakIterator is exhausted because we've // moved past every item. It should return the last offset found. int lastIndex = expected.Length - 1; Assert.AreEqual(expected[lastIndex], bi.Current); // We've moved past the last word, it should return the last offset. Assert.AreEqual(BreakIterator.DONE, bi.MoveNext()); Assert.AreEqual(expected[lastIndex], bi.Current); // Verify that the first element is correct now that we've moved to the end. Assert.AreEqual(expected[0], bi.MoveFirst()); Assert.AreEqual(expected[0], bi.Current); } } [Test] public void CanIterateBackwards() { var locale = new Locale("de-DE"); var text = "Good-day, kind sir !"; var expected = new[] { 0, 5, 10, 15, 20 }; // RuleStatus only applies to BreakIterator.UBreakIteratorType.WORD. var expectedStatusRuleVector = new[] { 0 }; var expectedEmptyRuleStatusVector = new[] { 0 }; using (var bi = BreakIterator.CreateLineInstance(locale)) { bi.SetText(text); Assert.That(bi.Boundaries, Is.EquivalentTo(expected)); int current = 0; var currentBoundary = expected[current]; Assert.That(bi.Current, Is.EqualTo(currentBoundary)); Assert.That(bi.GetRuleStatus(), Is.EqualTo(0)); Assert.That(bi.GetRuleStatusVector(), Is.EquivalentTo(expectedStatusRuleVector)); // Increment the index and verify that the next Boundary is correct. current++; currentBoundary = expected[current]; Assert.That(bi.MoveNext(), Is.EqualTo(currentBoundary)); Assert.That(bi.Current, Is.EqualTo(currentBoundary)); Assert.That(bi.GetRuleStatus(), Is.EqualTo(0)); Assert.That(bi.GetRuleStatusVector(), Is.EquivalentTo(expectedStatusRuleVector)); current++; currentBoundary = expected[current]; Assert.That(bi.MoveNext(), Is.EqualTo(currentBoundary)); Assert.That(bi.Current, Is.EqualTo(currentBoundary)); Assert.That(bi.GetRuleStatus(), Is.EqualTo(0)); Assert.That(bi.GetRuleStatusVector(), Is.EquivalentTo(expectedStatusRuleVector)); current--; currentBoundary = expected[current]; Assert.That(bi.MovePrevious(), Is.EqualTo(currentBoundary)); Assert.That(bi.Current, Is.EqualTo(currentBoundary)); Assert.That(bi.GetRuleStatusVector(), Is.EquivalentTo(expectedStatusRuleVector)); current--; currentBoundary = expected[current]; Assert.That(bi.MovePrevious(), Is.EqualTo(currentBoundary)); Assert.That(bi.Current, Is.EqualTo(currentBoundary)); Assert.That(bi.GetRuleStatus(), Is.EqualTo(0)); Assert.That(bi.GetRuleStatusVector(), Is.EquivalentTo(expectedStatusRuleVector)); // We've moved past the first word, it should return 0. Assert.AreEqual(BreakIterator.DONE, bi.MovePrevious()); Assert.That(bi.Current, Is.EqualTo(0)); Assert.That(bi.GetRuleStatus(), Is.EqualTo(0)); Assert.That(bi.GetRuleStatusVector(), Is.EquivalentTo(expectedEmptyRuleStatusVector)); // Verify that the element is correct now that we've moved to the end. var last = expected.Last(); Assert.That(bi.MoveLast(), Is.EqualTo(last)); Assert.That(bi.Current, Is.EqualTo(last)); Assert.That(bi.GetRuleStatus(), Is.EqualTo(0)); Assert.That(bi.GetRuleStatusVector(), Is.EquivalentTo(expectedStatusRuleVector)); } } [Test] public void CanSetNewText() { var locale = new Locale("en-US"); var text = "Good-day, kind sir ! Can I have a glass of water? I am very parched."; var expected = new[] { 0, 22, 52, 70 }; // RuleStatus only applies to BreakIterator.UBreakIteratorType.WORD. var expectedRuleStatusVector = new[] { 0 }; var secondText = "It is my birthday! I hope something exciting happens."; var secondExpected = new[] { 0, 20, 54 }; using (var bi = BreakIterator.CreateSentenceInstance(locale)) { bi.SetText(text); Assert.That(bi.Text, Is.EqualTo(text)); Assert.That(bi.Boundaries, Is.EquivalentTo(expected)); // Move the iterator to the next boundary Assert.AreEqual(expected[1], bi.MoveNext()); Assert.AreEqual(expected[1], bi.Current); Assert.That(bi.GetRuleStatus(), Is.EqualTo(0)); Assert.That(bi.GetRuleStatusVector(), Is.EquivalentTo(expectedRuleStatusVector)); // Assert that the new set of boundaries were found. bi.SetText(secondText); Assert.That(bi.Text, Is.EqualTo(secondText)); // Assert that the iterator was reset back to the first element // when we set new text. Assert.AreEqual(secondExpected[0], bi.Current); Assert.That(bi.GetRuleStatus(), Is.EqualTo(0)); Assert.That(bi.GetRuleStatusVector(), Is.EquivalentTo(expectedRuleStatusVector)); Assert.That(bi.Boundaries, Is.EquivalentTo(secondExpected)); } } /// <summary> /// Assert that when we set the text to empty that it will reset all the values. /// </summary> [Test] public void CanSetNewText_Empty() { var locale = new Locale("en-US"); var text = "Good-day, kind sir ! Can I have a glass of water? I am very parched."; string secondText = string.Empty; var expected = new[] { 0, 22, 52, 70 }; // RuleStatus only applies to BreakIterator.UBreakIteratorType.WORD. var expectedRuleStatusVector = new[] { 0 }; using (var bi = BreakIterator.CreateSentenceInstance(locale)) { bi.SetText(text); Assert.That(bi.Text, Is.EqualTo(text)); Assert.That(bi.Boundaries, Is.EquivalentTo(expected)); // Move the iterator to the next boundary Assert.AreEqual(expected[1], bi.MoveNext()); Assert.AreEqual(expected[1], bi.Current); Assert.That(bi.GetRuleStatus(), Is.EqualTo(0)); Assert.That(bi.GetRuleStatusVector(), Is.EquivalentTo(expectedRuleStatusVector)); // Assert that the new set of boundaries were found. bi.SetText(secondText); Assert.That(bi.Text, Is.EqualTo(secondText)); // Assert that the iterator was reset back to the first element // and is now null. Assert.That(bi.Current, Is.EqualTo(0)); Assert.AreEqual(BreakIterator.DONE, bi.MoveNext()); Assert.That(bi.MoveFirst(), Is.EqualTo(0)); Assert.That(bi.MoveLast(), Is.EqualTo(0)); Assert.AreEqual(BreakIterator.DONE, bi.MovePrevious()); Assert.That(bi.GetRuleStatus(), Is.EqualTo(0)); Assert.AreEqual(new[] { 0 }, bi.GetRuleStatusVector()); Assert.That(bi.Boundaries, Is.Empty); } } /// <summary> /// Assert that when we set the text to null, an ArgumentNullException is thrown. /// </summary> [Test] public void CanSetNewText_Null() { var locale = new Locale("en-US"); var text = "Good-day, kind sir ! Can I have a glass of water? I am very parched."; string secondText = null; using (var bi = BreakIterator.CreateCharacterInstance(locale)) { bi.SetText(text); Assert.Throws<ArgumentNullException>(() => bi.SetText(secondText)); } } [Test] public void CreateSentenceInstanceTest() { var locale = new Locale("de-DE"); var text = "Good-bye, dear! That was a delicious dinner."; var expected = new[] { 0, 16, 44 }; using (var bi = BreakIterator.CreateSentenceInstance(locale)) { bi.SetText(text); Assert.That(bi.Locale, Is.EqualTo(locale)); Assert.That(bi.Text, Is.EqualTo(text)); Assert.That(bi.Boundaries, Is.EquivalentTo(expected)); } } [Test] public void CreateWordInstanceTest() { var locale = new Locale("de-DE"); var text = "Good-day, kind sir !"; var expected = new int[] { 0, 4, 5, 8, 9, 10, 14, 15, 18, 19, 20 }; using (var bi = BreakIterator.CreateWordInstance(locale)) { bi.SetText(text); Assert.That(bi.Locale, Is.EqualTo(locale)); Assert.That(bi.Text, Is.EqualTo(text)); Assert.That(bi.Boundaries, Is.EquivalentTo(expected)); } } [Test] public void CreateLineInstanceTest() { var locale = new Locale("de-DE"); var text = "Good-day, kind sir !"; var expected = new[] { 0, 5, 10, 15, 20 }; using (var bi = BreakIterator.CreateLineInstance(locale)) { bi.SetText(text); Assert.That(bi.Locale, Is.EqualTo(locale)); Assert.That(bi.Text, Is.EqualTo(text)); Assert.That(bi.Boundaries, Is.EquivalentTo(expected)); } } [Test] public void IsBoundaryTest_Empty() { string text = string.Empty; var offsetsToTest = new[] { 0, -1, 100 }; var locale = new Locale("de-DE"); using (var bi = BreakIterator.CreateWordInstance(locale)) { bi.SetText(text); for (int i = 0; i < offsetsToTest.Length; i++) { var isBoundary = bi.IsBoundary(offsetsToTest[i]); Assert.IsFalse(isBoundary); Assert.That(bi.Current, Is.EqualTo(0)); } } } [TestCase(-1, false, 0)] [TestCase(21, false, 20)] [TestCase(11, false, 14)] [TestCase(5, true, 5)] [TestCase(0, true, 0)] [TestCase(20, true, 20)] public void IsBoundaryTest(int offset, bool expectedIsBoundary, int expectedOffset) { var locale = new Locale("de-DE"); var text = "Good-day, kind sir !"; using (var bi = BreakIterator.CreateWordInstance(locale)) { bi.SetText(text); var isBoundary = bi.IsBoundary(offset); Assert.That(isBoundary, Is.EqualTo(expectedIsBoundary)); Assert.That(bi.Current, Is.EqualTo(expectedOffset)); } } [TestCase(-10, 0, 0)] // Offset < 0 returns the first offset. [TestCase(0, 22, 22)] // Offset equals to the first offset should give the 2nd offset. [TestCase(75, BreakIterator.DONE, 70)] [TestCase(70, BreakIterator.DONE, 70)] // Expect that if we give it an exact offset, it will return us one previous. [TestCase(30, 52, 52)] [TestCase(52, 70, 70)] public void MoveFollowingTest(int offset, int expectedOffset, int expectedCurrent) { var locale = new Locale("de-DE"); var text = "Good-day, kind sir ! Can I have a glass of water? I am very parched."; using (var bi = BreakIterator.CreateSentenceInstance(locale)) { bi.SetText(text); int actualOffset = bi.MoveFollowing(offset); Assert.That(actualOffset, Is.EqualTo(expectedOffset)); Assert.That(bi.Current, Is.EqualTo(expectedCurrent)); } } [TestCase(-10, 0, 0)] [TestCase(0, BreakIterator.DONE, 0)] [TestCase(10, BreakIterator.DONE, 0)] public void MoveFollowingTest_Empty(int offset, int expectedOffset, int expectedCurrent) { var locale = new Locale("de-DE"); using (var bi = BreakIterator.CreateSentenceInstance(locale)) { bi.SetText(string.Empty); int actualOffset = bi.MoveFollowing(offset); Assert.That(actualOffset, Is.EqualTo(expectedOffset)); Assert.That(bi.Current, Is.EqualTo(expectedCurrent)); } } [TestCase(-1, 0, 0)] // Offset < 0 returns the first offset. [TestCase(0, BreakIterator.DONE, 0)] [TestCase(25, 20, 20)] // Offset > length of text should return last offset. [TestCase(20, 19, 19)] // Expect that if we give it an exact offset, it will return us one previous. [TestCase(7, 5, 5)] [TestCase(14, 10, 10)] public void MovePrecedingTest(int offset, int expectedOffset, int expectedCurrent) { var text = "Good-day, kind sir !"; var locale = new Locale("de-DE"); using (var bi = BreakIterator.CreateWordInstance(locale)) { bi.SetText(text); int actualOffset = bi.MovePreceding(offset); Assert.That(actualOffset, Is.EqualTo(expectedOffset)); Assert.That(bi.Current, Is.EqualTo(expectedCurrent)); } } [TestCase(0, BreakIterator.DONE, 0)] [TestCase(-5, 0, 0)] [TestCase(10, 0, 0)] public void MovePrecedingTest_Empty(int offset, int expectedOffset, int expectedCurrent) { var locale = new Locale("de-DE"); using (var bi = BreakIterator.CreateWordInstance(locale)) { bi.SetText(string.Empty); int actualOffset = bi.MovePreceding(offset); Assert.That(actualOffset, Is.EqualTo(expectedOffset)); Assert.That(bi.Current, Is.EqualTo(expectedCurrent)); } } [Test] public void Clone() { var locale = new Locale("de-DE"); using (var bi = BreakIterator.CreateWordInstance(locale)) { const string text = "Hello World!"; bi.SetText(text); bi.MoveFollowing(5); using (var clone = bi.Clone()) { Assert.That(clone.Text, Is.EqualTo(bi.Text)); Assert.That(clone.Current, Is.EqualTo(bi.Current)); Assert.That(clone.Boundaries, Is.EquivalentTo(bi.Boundaries)); Assert.That(clone.Locale, Is.EqualTo(bi.Locale)); bi.SetText("Good afternoon"); Assert.That(clone.Text, Is.EqualTo(text)); Assert.That(clone.Boundaries, Is.Not.EquivalentTo(bi.Boundaries)); } } } [TestCase(BreakIterator.UBreakIteratorType.CHARACTER, ExpectedResult = new[] { "A","a"," ","b","b","."," ","C","c"," ","3",".","5"," ","x","?"," ","Y","?","x","!"," ","Z"})] [TestCase(BreakIterator.UBreakIteratorType.WORD, ExpectedResult = new[] { "Aa"," ","bb","."," ","Cc"," ","3.5"," ","x","?"," ","Y","?","x","!"," ","Z"})] [TestCase(BreakIterator.UBreakIteratorType.LINE, ExpectedResult = new[] { "Aa ", "bb. ", "Cc ", "3.5 ", "x? ", "Y?", "x! ", "Z"})] [TestCase(BreakIterator.UBreakIteratorType.SENTENCE, ExpectedResult = new[] { "Aa bb. ", "Cc 3.5 x? ", "Y?", "x! ", "Z"})] public List<string> GetEnumerator(BreakIterator.UBreakIteratorType type) { using (var breakIterator = new RuleBasedBreakIterator(type, "en-US")) { breakIterator.SetText("Aa bb. Cc 3.5 x? Y?x! Z"); var result = new List<string>(); foreach (var s in breakIterator) { result.Add(s); } return result; } } /// <summary> /// Test data for GetBoundaries_Word and GetWordBoundaries tests /// </summary> private static class WordBoundaryTestData { public const string Text = "Aa bb. Ccdef 3.5 x? Y?x! Z"; public static readonly Boundary[] ExpectedOnlyWords = new[] { new Boundary(0, 2), new Boundary(3, 5), new Boundary(7, 12), new Boundary(13, 16), new Boundary(17, 18), new Boundary(20, 21), new Boundary(22, 23), new Boundary(25, 26) }; public static readonly Boundary[] ExpectedAllBoundaries = new[] { new Boundary(0, 2), new Boundary(2, 3), new Boundary(3, 5), new Boundary(5, 6), new Boundary(6, 7), new Boundary(7, 12), new Boundary(12, 13), new Boundary(13, 16), new Boundary(16, 17), new Boundary(17, 18), new Boundary(18, 19), new Boundary(19, 20), new Boundary(20, 21), new Boundary(21, 22), new Boundary(22, 23), new Boundary(23, 24), new Boundary(24, 25), new Boundary(25, 26) }; } } }
// 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 grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using xunit = Xunit; namespace Google.Cloud.Compute.V1.Tests { /// <summary>Generated unit tests.</summary> public sealed class GeneratedServiceAttachmentsClientTest { [xunit::FactAttribute] public void GetRequestObject() { moq::Mock<ServiceAttachments.ServiceAttachmentsClient> mockGrpcClient = new moq::Mock<ServiceAttachments.ServiceAttachmentsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetServiceAttachmentRequest request = new GetServiceAttachmentRequest { Region = "regionedb20d96", Project = "projectaa6ff846", ServiceAttachment = "service_attachment592c837a", }; ServiceAttachment expectedResponse = new ServiceAttachment { Id = 11672635353343658936UL, TargetService = "target_service3f6f9a5a", Kind = "kindf7aa39d9", Name = "name1c9368b0", CreationTimestamp = "creation_timestamp235e59a1", ConnectedEndpoints = { new ServiceAttachmentConnectedEndpoint(), }, Region = "regionedb20d96", ConsumerRejectLists = { "consumer_reject_lists640993ba", }, Fingerprint = "fingerprint009e6052", ProducerForwardingRule = "producer_forwarding_rule8732a25d", ConnectionPreference = ServiceAttachment.Types.ConnectionPreference.AcceptAutomatic, EnableProxyProtocol = true, NatSubnets = { "nat_subnets59063249", }, ConsumerAcceptLists = { new ServiceAttachmentConsumerProjectLimit(), }, Description = "description2cf9da67", SelfLink = "self_link7e87f12d", PscServiceAttachmentId = new Uint128(), }; mockGrpcClient.Setup(x => x.Get(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ServiceAttachmentsClient client = new ServiceAttachmentsClientImpl(mockGrpcClient.Object, null); ServiceAttachment response = client.Get(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetRequestObjectAsync() { moq::Mock<ServiceAttachments.ServiceAttachmentsClient> mockGrpcClient = new moq::Mock<ServiceAttachments.ServiceAttachmentsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetServiceAttachmentRequest request = new GetServiceAttachmentRequest { Region = "regionedb20d96", Project = "projectaa6ff846", ServiceAttachment = "service_attachment592c837a", }; ServiceAttachment expectedResponse = new ServiceAttachment { Id = 11672635353343658936UL, TargetService = "target_service3f6f9a5a", Kind = "kindf7aa39d9", Name = "name1c9368b0", CreationTimestamp = "creation_timestamp235e59a1", ConnectedEndpoints = { new ServiceAttachmentConnectedEndpoint(), }, Region = "regionedb20d96", ConsumerRejectLists = { "consumer_reject_lists640993ba", }, Fingerprint = "fingerprint009e6052", ProducerForwardingRule = "producer_forwarding_rule8732a25d", ConnectionPreference = ServiceAttachment.Types.ConnectionPreference.AcceptAutomatic, EnableProxyProtocol = true, NatSubnets = { "nat_subnets59063249", }, ConsumerAcceptLists = { new ServiceAttachmentConsumerProjectLimit(), }, Description = "description2cf9da67", SelfLink = "self_link7e87f12d", PscServiceAttachmentId = new Uint128(), }; mockGrpcClient.Setup(x => x.GetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ServiceAttachment>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ServiceAttachmentsClient client = new ServiceAttachmentsClientImpl(mockGrpcClient.Object, null); ServiceAttachment responseCallSettings = await client.GetAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); ServiceAttachment responseCancellationToken = await client.GetAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void Get() { moq::Mock<ServiceAttachments.ServiceAttachmentsClient> mockGrpcClient = new moq::Mock<ServiceAttachments.ServiceAttachmentsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetServiceAttachmentRequest request = new GetServiceAttachmentRequest { Region = "regionedb20d96", Project = "projectaa6ff846", ServiceAttachment = "service_attachment592c837a", }; ServiceAttachment expectedResponse = new ServiceAttachment { Id = 11672635353343658936UL, TargetService = "target_service3f6f9a5a", Kind = "kindf7aa39d9", Name = "name1c9368b0", CreationTimestamp = "creation_timestamp235e59a1", ConnectedEndpoints = { new ServiceAttachmentConnectedEndpoint(), }, Region = "regionedb20d96", ConsumerRejectLists = { "consumer_reject_lists640993ba", }, Fingerprint = "fingerprint009e6052", ProducerForwardingRule = "producer_forwarding_rule8732a25d", ConnectionPreference = ServiceAttachment.Types.ConnectionPreference.AcceptAutomatic, EnableProxyProtocol = true, NatSubnets = { "nat_subnets59063249", }, ConsumerAcceptLists = { new ServiceAttachmentConsumerProjectLimit(), }, Description = "description2cf9da67", SelfLink = "self_link7e87f12d", PscServiceAttachmentId = new Uint128(), }; mockGrpcClient.Setup(x => x.Get(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ServiceAttachmentsClient client = new ServiceAttachmentsClientImpl(mockGrpcClient.Object, null); ServiceAttachment response = client.Get(request.Project, request.Region, request.ServiceAttachment); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetAsync() { moq::Mock<ServiceAttachments.ServiceAttachmentsClient> mockGrpcClient = new moq::Mock<ServiceAttachments.ServiceAttachmentsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetServiceAttachmentRequest request = new GetServiceAttachmentRequest { Region = "regionedb20d96", Project = "projectaa6ff846", ServiceAttachment = "service_attachment592c837a", }; ServiceAttachment expectedResponse = new ServiceAttachment { Id = 11672635353343658936UL, TargetService = "target_service3f6f9a5a", Kind = "kindf7aa39d9", Name = "name1c9368b0", CreationTimestamp = "creation_timestamp235e59a1", ConnectedEndpoints = { new ServiceAttachmentConnectedEndpoint(), }, Region = "regionedb20d96", ConsumerRejectLists = { "consumer_reject_lists640993ba", }, Fingerprint = "fingerprint009e6052", ProducerForwardingRule = "producer_forwarding_rule8732a25d", ConnectionPreference = ServiceAttachment.Types.ConnectionPreference.AcceptAutomatic, EnableProxyProtocol = true, NatSubnets = { "nat_subnets59063249", }, ConsumerAcceptLists = { new ServiceAttachmentConsumerProjectLimit(), }, Description = "description2cf9da67", SelfLink = "self_link7e87f12d", PscServiceAttachmentId = new Uint128(), }; mockGrpcClient.Setup(x => x.GetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ServiceAttachment>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ServiceAttachmentsClient client = new ServiceAttachmentsClientImpl(mockGrpcClient.Object, null); ServiceAttachment responseCallSettings = await client.GetAsync(request.Project, request.Region, request.ServiceAttachment, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); ServiceAttachment responseCancellationToken = await client.GetAsync(request.Project, request.Region, request.ServiceAttachment, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetIamPolicyRequestObject() { moq::Mock<ServiceAttachments.ServiceAttachmentsClient> mockGrpcClient = new moq::Mock<ServiceAttachments.ServiceAttachmentsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetIamPolicyServiceAttachmentRequest request = new GetIamPolicyServiceAttachmentRequest { Region = "regionedb20d96", Resource = "resource164eab96", Project = "projectaa6ff846", OptionsRequestedPolicyVersion = -1471234741, }; Policy expectedResponse = new Policy { Etag = "etage8ad7218", Rules = { new Rule(), }, AuditConfigs = { new AuditConfig(), }, Version = 271578922, Bindings = { new Binding(), }, IamOwned = false, }; mockGrpcClient.Setup(x => x.GetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ServiceAttachmentsClient client = new ServiceAttachmentsClientImpl(mockGrpcClient.Object, null); Policy response = client.GetIamPolicy(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetIamPolicyRequestObjectAsync() { moq::Mock<ServiceAttachments.ServiceAttachmentsClient> mockGrpcClient = new moq::Mock<ServiceAttachments.ServiceAttachmentsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetIamPolicyServiceAttachmentRequest request = new GetIamPolicyServiceAttachmentRequest { Region = "regionedb20d96", Resource = "resource164eab96", Project = "projectaa6ff846", OptionsRequestedPolicyVersion = -1471234741, }; Policy expectedResponse = new Policy { Etag = "etage8ad7218", Rules = { new Rule(), }, AuditConfigs = { new AuditConfig(), }, Version = 271578922, Bindings = { new Binding(), }, IamOwned = false, }; mockGrpcClient.Setup(x => x.GetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ServiceAttachmentsClient client = new ServiceAttachmentsClientImpl(mockGrpcClient.Object, null); Policy responseCallSettings = await client.GetIamPolicyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Policy responseCancellationToken = await client.GetIamPolicyAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetIamPolicy() { moq::Mock<ServiceAttachments.ServiceAttachmentsClient> mockGrpcClient = new moq::Mock<ServiceAttachments.ServiceAttachmentsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetIamPolicyServiceAttachmentRequest request = new GetIamPolicyServiceAttachmentRequest { Region = "regionedb20d96", Resource = "resource164eab96", Project = "projectaa6ff846", }; Policy expectedResponse = new Policy { Etag = "etage8ad7218", Rules = { new Rule(), }, AuditConfigs = { new AuditConfig(), }, Version = 271578922, Bindings = { new Binding(), }, IamOwned = false, }; mockGrpcClient.Setup(x => x.GetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ServiceAttachmentsClient client = new ServiceAttachmentsClientImpl(mockGrpcClient.Object, null); Policy response = client.GetIamPolicy(request.Project, request.Region, request.Resource); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetIamPolicyAsync() { moq::Mock<ServiceAttachments.ServiceAttachmentsClient> mockGrpcClient = new moq::Mock<ServiceAttachments.ServiceAttachmentsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetIamPolicyServiceAttachmentRequest request = new GetIamPolicyServiceAttachmentRequest { Region = "regionedb20d96", Resource = "resource164eab96", Project = "projectaa6ff846", }; Policy expectedResponse = new Policy { Etag = "etage8ad7218", Rules = { new Rule(), }, AuditConfigs = { new AuditConfig(), }, Version = 271578922, Bindings = { new Binding(), }, IamOwned = false, }; mockGrpcClient.Setup(x => x.GetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ServiceAttachmentsClient client = new ServiceAttachmentsClientImpl(mockGrpcClient.Object, null); Policy responseCallSettings = await client.GetIamPolicyAsync(request.Project, request.Region, request.Resource, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Policy responseCancellationToken = await client.GetIamPolicyAsync(request.Project, request.Region, request.Resource, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void SetIamPolicyRequestObject() { moq::Mock<ServiceAttachments.ServiceAttachmentsClient> mockGrpcClient = new moq::Mock<ServiceAttachments.ServiceAttachmentsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); SetIamPolicyServiceAttachmentRequest request = new SetIamPolicyServiceAttachmentRequest { Region = "regionedb20d96", Resource = "resource164eab96", Project = "projectaa6ff846", RegionSetPolicyRequestResource = new RegionSetPolicyRequest(), }; Policy expectedResponse = new Policy { Etag = "etage8ad7218", Rules = { new Rule(), }, AuditConfigs = { new AuditConfig(), }, Version = 271578922, Bindings = { new Binding(), }, IamOwned = false, }; mockGrpcClient.Setup(x => x.SetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ServiceAttachmentsClient client = new ServiceAttachmentsClientImpl(mockGrpcClient.Object, null); Policy response = client.SetIamPolicy(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task SetIamPolicyRequestObjectAsync() { moq::Mock<ServiceAttachments.ServiceAttachmentsClient> mockGrpcClient = new moq::Mock<ServiceAttachments.ServiceAttachmentsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); SetIamPolicyServiceAttachmentRequest request = new SetIamPolicyServiceAttachmentRequest { Region = "regionedb20d96", Resource = "resource164eab96", Project = "projectaa6ff846", RegionSetPolicyRequestResource = new RegionSetPolicyRequest(), }; Policy expectedResponse = new Policy { Etag = "etage8ad7218", Rules = { new Rule(), }, AuditConfigs = { new AuditConfig(), }, Version = 271578922, Bindings = { new Binding(), }, IamOwned = false, }; mockGrpcClient.Setup(x => x.SetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ServiceAttachmentsClient client = new ServiceAttachmentsClientImpl(mockGrpcClient.Object, null); Policy responseCallSettings = await client.SetIamPolicyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Policy responseCancellationToken = await client.SetIamPolicyAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void SetIamPolicy() { moq::Mock<ServiceAttachments.ServiceAttachmentsClient> mockGrpcClient = new moq::Mock<ServiceAttachments.ServiceAttachmentsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); SetIamPolicyServiceAttachmentRequest request = new SetIamPolicyServiceAttachmentRequest { Region = "regionedb20d96", Resource = "resource164eab96", Project = "projectaa6ff846", RegionSetPolicyRequestResource = new RegionSetPolicyRequest(), }; Policy expectedResponse = new Policy { Etag = "etage8ad7218", Rules = { new Rule(), }, AuditConfigs = { new AuditConfig(), }, Version = 271578922, Bindings = { new Binding(), }, IamOwned = false, }; mockGrpcClient.Setup(x => x.SetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ServiceAttachmentsClient client = new ServiceAttachmentsClientImpl(mockGrpcClient.Object, null); Policy response = client.SetIamPolicy(request.Project, request.Region, request.Resource, request.RegionSetPolicyRequestResource); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task SetIamPolicyAsync() { moq::Mock<ServiceAttachments.ServiceAttachmentsClient> mockGrpcClient = new moq::Mock<ServiceAttachments.ServiceAttachmentsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); SetIamPolicyServiceAttachmentRequest request = new SetIamPolicyServiceAttachmentRequest { Region = "regionedb20d96", Resource = "resource164eab96", Project = "projectaa6ff846", RegionSetPolicyRequestResource = new RegionSetPolicyRequest(), }; Policy expectedResponse = new Policy { Etag = "etage8ad7218", Rules = { new Rule(), }, AuditConfigs = { new AuditConfig(), }, Version = 271578922, Bindings = { new Binding(), }, IamOwned = false, }; mockGrpcClient.Setup(x => x.SetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ServiceAttachmentsClient client = new ServiceAttachmentsClientImpl(mockGrpcClient.Object, null); Policy responseCallSettings = await client.SetIamPolicyAsync(request.Project, request.Region, request.Resource, request.RegionSetPolicyRequestResource, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Policy responseCancellationToken = await client.SetIamPolicyAsync(request.Project, request.Region, request.Resource, request.RegionSetPolicyRequestResource, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void TestIamPermissionsRequestObject() { moq::Mock<ServiceAttachments.ServiceAttachmentsClient> mockGrpcClient = new moq::Mock<ServiceAttachments.ServiceAttachmentsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); TestIamPermissionsServiceAttachmentRequest request = new TestIamPermissionsServiceAttachmentRequest { Region = "regionedb20d96", Resource = "resource164eab96", Project = "projectaa6ff846", TestPermissionsRequestResource = new TestPermissionsRequest(), }; TestPermissionsResponse expectedResponse = new TestPermissionsResponse { Permissions = { "permissions535a2741", }, }; mockGrpcClient.Setup(x => x.TestIamPermissions(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ServiceAttachmentsClient client = new ServiceAttachmentsClientImpl(mockGrpcClient.Object, null); TestPermissionsResponse response = client.TestIamPermissions(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task TestIamPermissionsRequestObjectAsync() { moq::Mock<ServiceAttachments.ServiceAttachmentsClient> mockGrpcClient = new moq::Mock<ServiceAttachments.ServiceAttachmentsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); TestIamPermissionsServiceAttachmentRequest request = new TestIamPermissionsServiceAttachmentRequest { Region = "regionedb20d96", Resource = "resource164eab96", Project = "projectaa6ff846", TestPermissionsRequestResource = new TestPermissionsRequest(), }; TestPermissionsResponse expectedResponse = new TestPermissionsResponse { Permissions = { "permissions535a2741", }, }; mockGrpcClient.Setup(x => x.TestIamPermissionsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<TestPermissionsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ServiceAttachmentsClient client = new ServiceAttachmentsClientImpl(mockGrpcClient.Object, null); TestPermissionsResponse responseCallSettings = await client.TestIamPermissionsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); TestPermissionsResponse responseCancellationToken = await client.TestIamPermissionsAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void TestIamPermissions() { moq::Mock<ServiceAttachments.ServiceAttachmentsClient> mockGrpcClient = new moq::Mock<ServiceAttachments.ServiceAttachmentsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); TestIamPermissionsServiceAttachmentRequest request = new TestIamPermissionsServiceAttachmentRequest { Region = "regionedb20d96", Resource = "resource164eab96", Project = "projectaa6ff846", TestPermissionsRequestResource = new TestPermissionsRequest(), }; TestPermissionsResponse expectedResponse = new TestPermissionsResponse { Permissions = { "permissions535a2741", }, }; mockGrpcClient.Setup(x => x.TestIamPermissions(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ServiceAttachmentsClient client = new ServiceAttachmentsClientImpl(mockGrpcClient.Object, null); TestPermissionsResponse response = client.TestIamPermissions(request.Project, request.Region, request.Resource, request.TestPermissionsRequestResource); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task TestIamPermissionsAsync() { moq::Mock<ServiceAttachments.ServiceAttachmentsClient> mockGrpcClient = new moq::Mock<ServiceAttachments.ServiceAttachmentsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); TestIamPermissionsServiceAttachmentRequest request = new TestIamPermissionsServiceAttachmentRequest { Region = "regionedb20d96", Resource = "resource164eab96", Project = "projectaa6ff846", TestPermissionsRequestResource = new TestPermissionsRequest(), }; TestPermissionsResponse expectedResponse = new TestPermissionsResponse { Permissions = { "permissions535a2741", }, }; mockGrpcClient.Setup(x => x.TestIamPermissionsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<TestPermissionsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ServiceAttachmentsClient client = new ServiceAttachmentsClientImpl(mockGrpcClient.Object, null); TestPermissionsResponse responseCallSettings = await client.TestIamPermissionsAsync(request.Project, request.Region, request.Resource, request.TestPermissionsRequestResource, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); TestPermissionsResponse responseCancellationToken = await client.TestIamPermissionsAsync(request.Project, request.Region, request.Resource, request.TestPermissionsRequestResource, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } } }
/************************************************************************************ Copyright : Copyright 2014 Oculus VR, LLC. All Rights reserved. Licensed under the Oculus VR Rift SDK License Version 3.3 (the "License"); you may not use the Oculus VR Rift SDK except in compliance with the License, which is provided at the time of installation or download, or which otherwise accompanies this software in either electronic or hard copy form. You may obtain a copy of the License at http://www.oculus.com/licenses/LICENSE-3.3 Unless required by applicable law or agreed to in writing, the Oculus VR SDK 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 UnityEngine; using System.Collections; using UnityEngine.UI; using VR = UnityEngine.VR; //------------------------------------------------------------------------------------- /// <summary> /// Shows debug information on a heads-up display. /// </summary> public class OVRDebugInfo : MonoBehaviour { #region GameObjects for Debug Information UIs GameObject debugUIManager; GameObject debugUIObject; GameObject riftPresent; GameObject fps; GameObject ipd; GameObject fov; GameObject height; GameObject depth; GameObject resolutionEyeTexture; GameObject latencies; GameObject texts; #endregion #region Debug strings string strRiftPresent = null; // "VR DISABLED" string strFPS = null; // "FPS: 0"; string strIPD = null; // "IPD: 0.000"; string strFOV = null; // "FOV: 0.0f"; string strHeight = null; // "Height: 0.0f"; string strDepth = null; // "Depth: 0.0f"; string strResolutionEyeTexture = null; // "Resolution : {0} x {1}" string strLatencies = null; // "R: {0:F3} TW: {1:F3} PP: {2:F3} RE: {3:F3} TWE: {4:F3}" #endregion /// <summary> /// Variables for FPS /// </summary> float updateInterval = 0.5f; float accum = 0.0f; int frames = 0; float timeLeft = 0.0f; /// <summary> /// Managing for UI initialization /// </summary> bool initUIComponent = false; bool isInited = false; /// <summary> /// UIs Y offset /// </summary> float offsetY = 55.0f; /// <summary> /// Managing for rift detection UI /// </summary> float riftPresentTimeout = 0.0f; /// <summary> /// Turn on / off VR variables /// </summary> bool showVRVars = false; #region MonoBehaviour handler /// <summary> /// Initialization /// </summary> void Awake() { // Create canvas for using new GUI debugUIManager = new GameObject(); debugUIManager.name = "DebugUIManager"; debugUIManager.transform.parent = GameObject.Find("LeftEyeAnchor").transform; RectTransform rectTransform = debugUIManager.AddComponent<RectTransform>(); rectTransform.sizeDelta = new Vector2(100f, 100f); rectTransform.localScale = new Vector3(0.001f, 0.001f, 0.001f); rectTransform.localPosition = new Vector3(0.01f, 0.17f, 0.53f); rectTransform.localEulerAngles = Vector3.zero; Canvas canvas = debugUIManager.AddComponent<Canvas>(); canvas.renderMode = RenderMode.WorldSpace; canvas.pixelPerfect = false; } /// <summary> /// Updating VR variables and managing UI present /// </summary> void Update() { if (initUIComponent && !isInited) { InitUIComponents(); } if (Input.GetKeyDown(KeyCode.Space) && riftPresentTimeout < 0.0f) { initUIComponent = true; showVRVars ^= true; } UpdateDeviceDetection(); // Presenting VR variables if (showVRVars) { debugUIManager.SetActive(true); UpdateVariable(); UpdateStrings(); } else { debugUIManager.SetActive(false); } } /// <summary> /// Initialize isInited value on OnDestroy /// </summary> void OnDestroy() { isInited = false; } #endregion #region Private Functions /// <summary> /// Initialize UI GameObjects /// </summary> void InitUIComponents() { float posY = 0.0f; int fontSize = 20; debugUIObject = new GameObject(); debugUIObject.name = "DebugInfo"; debugUIObject.transform.parent = GameObject.Find("DebugUIManager").transform; debugUIObject.transform.localPosition = new Vector3(0.0f, 100.0f, 0.0f); debugUIObject.transform.localEulerAngles = Vector3.zero; debugUIObject.transform.localScale = new Vector3(1.0f, 1.0f, 1.0f); // Print out for FPS if (!string.IsNullOrEmpty(strFPS)) { fps = VariableObjectManager(fps, "FPS", posY -= offsetY, strFPS, fontSize); } // Print out for IPD if (!string.IsNullOrEmpty(strIPD)) { ipd = VariableObjectManager(ipd, "IPD", posY -= offsetY, strIPD, fontSize); } // Print out for FOV if (!string.IsNullOrEmpty(strFOV)) { fov = VariableObjectManager(fov, "FOV", posY -= offsetY, strFOV, fontSize); } // Print out for Height if (!string.IsNullOrEmpty(strHeight)) { height = VariableObjectManager(height, "Height", posY -= offsetY, strHeight, fontSize); } // Print out for Depth if (!string.IsNullOrEmpty(strDepth)) { depth = VariableObjectManager(depth, "Depth", posY -= offsetY, strDepth, fontSize); } // Print out for Resoulution of Eye Texture if (!string.IsNullOrEmpty(strResolutionEyeTexture)) { resolutionEyeTexture = VariableObjectManager(resolutionEyeTexture, "Resolution", posY -= offsetY, strResolutionEyeTexture, fontSize); } // Print out for Latency if (!string.IsNullOrEmpty(strLatencies)) { latencies = VariableObjectManager(latencies, "Latency", posY -= offsetY, strLatencies, 17); posY = 0.0f; } initUIComponent = false; isInited = true; } /// <summary> /// Update VR Variables /// </summary> void UpdateVariable() { UpdateIPD(); UpdateEyeHeightOffset(); UpdateEyeDepthOffset(); UpdateFOV(); UpdateResolutionEyeTexture(); UpdateLatencyValues(); UpdateFPS(); } /// <summary> /// Update Strings /// </summary> void UpdateStrings() { if (debugUIObject == null) return; if (!string.IsNullOrEmpty(strFPS)) fps.GetComponentInChildren<Text>().text = strFPS; if (!string.IsNullOrEmpty(strIPD)) ipd.GetComponentInChildren<Text>().text = strIPD; if (!string.IsNullOrEmpty(strFOV)) fov.GetComponentInChildren<Text>().text = strFOV; if (!string.IsNullOrEmpty(strResolutionEyeTexture)) resolutionEyeTexture.GetComponentInChildren<Text>().text = strResolutionEyeTexture; if (!string.IsNullOrEmpty(strLatencies)) { latencies.GetComponentInChildren<Text>().text = strLatencies; latencies.GetComponentInChildren<Text>().fontSize = 14; } if (!string.IsNullOrEmpty(strHeight)) height.GetComponentInChildren<Text>().text = strHeight; if (!string.IsNullOrEmpty(strDepth)) depth.GetComponentInChildren<Text>().text = strDepth; } /// <summary> /// It's for rift present GUI /// </summary> void RiftPresentGUI(GameObject guiMainOBj) { riftPresent = ComponentComposition(riftPresent); riftPresent.transform.SetParent(guiMainOBj.transform); riftPresent.name = "RiftPresent"; RectTransform rectTransform = riftPresent.GetComponent<RectTransform>(); rectTransform.localPosition = new Vector3(0.0f, 0.0f, 0.0f); rectTransform.localScale = new Vector3(1.0f, 1.0f, 1.0f); rectTransform.localEulerAngles = Vector3.zero; Text text = riftPresent.GetComponentInChildren<Text>(); text.text = strRiftPresent; text.fontSize = 20; } /// <summary> /// Updates the device detection. /// </summary> void UpdateDeviceDetection() { if (riftPresentTimeout >= 0.0f) { riftPresentTimeout -= Time.deltaTime; } } /// <summary> /// Object Manager for Variables /// </summary> /// <returns> gameobject for each Variable </returns> GameObject VariableObjectManager(GameObject gameObject, string name, float posY, string str, int fontSize) { gameObject = ComponentComposition(gameObject); gameObject.name = name; gameObject.transform.SetParent(debugUIObject.transform); RectTransform rectTransform = gameObject.GetComponent<RectTransform>(); rectTransform.localPosition = new Vector3(0.0f, posY -= offsetY, 0.0f); Text text = gameObject.GetComponentInChildren<Text>(); text.text = str; text.fontSize = fontSize; gameObject.transform.localEulerAngles = Vector3.zero; rectTransform.localScale = new Vector3(1.0f, 1.0f, 1.0f); return gameObject; } /// <summary> /// Component composition /// </summary> /// <returns> Composed gameobject. </returns> GameObject ComponentComposition(GameObject GO) { GO = new GameObject(); GO.AddComponent<RectTransform>(); GO.AddComponent<CanvasRenderer>(); GO.AddComponent<Image>(); GO.GetComponent<RectTransform>().sizeDelta = new Vector2(350f, 50f); GO.GetComponent<Image>().color = new Color(7f / 255f, 45f / 255f, 71f / 255f, 200f / 255f); texts = new GameObject(); texts.AddComponent<RectTransform>(); texts.AddComponent<CanvasRenderer>(); texts.AddComponent<Text>(); texts.GetComponent<RectTransform>().sizeDelta = new Vector2(350f, 50f); texts.GetComponent<Text>().font = Resources.GetBuiltinResource(typeof(Font), "Arial.ttf") as Font; texts.GetComponent<Text>().alignment = TextAnchor.MiddleCenter; texts.transform.SetParent(GO.transform); texts.name = "TextBox"; return GO; } #endregion #region Debugging variables handler /// <summary> /// Updates the IPD. /// </summary> void UpdateIPD() { strIPD = System.String.Format("IPD (mm): {0:F4}", OVRManager.profile.ipd * 1000.0f); } /// <summary> /// Updates the eye height offset. /// </summary> void UpdateEyeHeightOffset() { float eyeHeight = OVRManager.profile.eyeHeight; strHeight = System.String.Format("Eye Height (m): {0:F3}", eyeHeight); } /// <summary> /// Updates the eye depth offset. /// </summary> void UpdateEyeDepthOffset() { float eyeDepth = OVRManager.profile.eyeDepth; strDepth = System.String.Format("Eye Depth (m): {0:F3}", eyeDepth); } /// <summary> /// Updates the FOV. /// </summary> void UpdateFOV() { OVRDisplay.EyeRenderDesc eyeDesc = OVRManager.display.GetEyeRenderDesc(VR.VRNode.LeftEye); strFOV = System.String.Format("FOV (deg): {0:F3}", eyeDesc.fov.y); } /// <summary> /// Updates resolution of eye texture /// </summary> void UpdateResolutionEyeTexture() { OVRDisplay.EyeRenderDesc leftEyeDesc = OVRManager.display.GetEyeRenderDesc(VR.VRNode.LeftEye); OVRDisplay.EyeRenderDesc rightEyeDesc = OVRManager.display.GetEyeRenderDesc(VR.VRNode.RightEye); float scale = VR.VRSettings.renderViewportScale; float w = (int)(scale * (float)(leftEyeDesc.resolution.x + rightEyeDesc.resolution.x)); float h = (int)(scale * (float)Mathf.Max(leftEyeDesc.resolution.y, rightEyeDesc.resolution.y)); strResolutionEyeTexture = System.String.Format("Resolution : {0} x {1}", w, h); } /// <summary> /// Updates latency values /// </summary> void UpdateLatencyValues() { #if !UNITY_ANDROID || UNITY_EDITOR OVRDisplay.LatencyData latency = OVRManager.display.latency; if (latency.render < 0.000001f && latency.timeWarp < 0.000001f && latency.postPresent < 0.000001f) strLatencies = System.String.Format("Latency values are not available."); else strLatencies = System.String.Format("Render: {0:F3} TimeWarp: {1:F3} Post-Present: {2:F3}\nRender Error: {3:F3} TimeWarp Error: {4:F3}", latency.render, latency.timeWarp, latency.postPresent, latency.renderError, latency.timeWarpError); #endif } /// <summary> /// Updates the FPS. /// </summary> void UpdateFPS() { timeLeft -= Time.unscaledDeltaTime; accum += Time.unscaledDeltaTime; ++frames; // Interval ended - update GUI text and start new interval if (timeLeft <= 0.0) { // display two fractional digits (f2 format) float fps = frames / accum; strFPS = System.String.Format("FPS: {0:F2}", fps); timeLeft += updateInterval; accum = 0.0f; frames = 0; } } #endregion }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading; using System.Threading.Tasks; using Hyak.Common; using Microsoft.Azure; using Microsoft.Azure.Management.Sql; using Microsoft.Azure.Management.Sql.Models; using Newtonsoft.Json.Linq; namespace Microsoft.Azure.Management.Sql { /// <summary> /// Represents all the operations for operating on Azure SQL Server /// disaster recovery configurations. Contains operations to: Create, /// Retrieve, Update, Failover, and Delete. /// </summary> internal partial class ServerDisasterRecoveryConfigurationOperations : IServiceOperations<SqlManagementClient>, IServerDisasterRecoveryConfigurationOperations { /// <summary> /// Initializes a new instance of the /// ServerDisasterRecoveryConfigurationOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal ServerDisasterRecoveryConfigurationOperations(SqlManagementClient client) { this._client = client; } private SqlManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.Azure.Management.Sql.SqlManagementClient. /// </summary> public SqlManagementClient Client { get { return this._client; } } /// <summary> /// Begins creating a new or updating an existing Azure SQL Server /// disaster recovery configuration. To determine the status of the /// operation call /// GetServerDisasterRecoveryConfigurationOperationStatus. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the Azure SQL /// Server belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Server. /// </param> /// <param name='serverDisasterRecoveryConfigurationName'> /// Required. The name of the Azure SQL Server disaster recovery /// configuration to be operated on (Updated or created). /// </param> /// <param name='parameters'> /// Required. The required parameters for creating or updating a Server /// disaster recovery configuration. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Response for long running Azure Sql server disaster recovery /// configuration operation. /// </returns> public async Task<ServerDisasterRecoveryConfigurationCreateOrUpdateResponse> BeginCreateOrUpdateAsync(string resourceGroupName, string serverName, string serverDisasterRecoveryConfigurationName, ServerDisasterRecoveryConfigurationCreateOrUpdateParameters parameters, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (serverName == null) { throw new ArgumentNullException("serverName"); } if (serverDisasterRecoveryConfigurationName == null) { throw new ArgumentNullException("serverDisasterRecoveryConfigurationName"); } if (parameters == null) { throw new ArgumentNullException("parameters"); } if (parameters.Location == null) { throw new ArgumentNullException("parameters.Location"); } if (parameters.Properties == null) { throw new ArgumentNullException("parameters.Properties"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("serverName", serverName); tracingParameters.Add("serverDisasterRecoveryConfigurationName", serverDisasterRecoveryConfigurationName); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "BeginCreateOrUpdateAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; url = url + "Microsoft.Sql"; url = url + "/servers/"; url = url + Uri.EscapeDataString(serverName); url = url + "/disasterRecoveryConfiguration/"; url = url + Uri.EscapeDataString(serverDisasterRecoveryConfigurationName); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2014-04-01"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Put; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; JToken requestDoc = null; JObject serverDisasterRecoveryConfigurationCreateOrUpdateParametersValue = new JObject(); requestDoc = serverDisasterRecoveryConfigurationCreateOrUpdateParametersValue; JObject propertiesValue = new JObject(); serverDisasterRecoveryConfigurationCreateOrUpdateParametersValue["properties"] = propertiesValue; if (parameters.Properties.AutoFailover != null) { propertiesValue["autoFailover"] = parameters.Properties.AutoFailover; } if (parameters.Properties.FailoverPolicy != null) { propertiesValue["failoverPolicy"] = parameters.Properties.FailoverPolicy; } if (parameters.Properties.PartnerLogicalServerName != null) { propertiesValue["partnerLogicalServerName"] = parameters.Properties.PartnerLogicalServerName; } if (parameters.Properties.PartnerServerId != null) { propertiesValue["partnerServerId"] = parameters.Properties.PartnerServerId; } if (parameters.Properties.Role != null) { propertiesValue["role"] = parameters.Properties.Role; } if (parameters.Properties.Type != null) { propertiesValue["type"] = parameters.Properties.Type; } serverDisasterRecoveryConfigurationCreateOrUpdateParametersValue["location"] = parameters.Location; if (parameters.Tags != null) { JObject tagsDictionary = new JObject(); foreach (KeyValuePair<string, string> pair in parameters.Tags) { string tagsKey = pair.Key; string tagsValue = pair.Value; tagsDictionary[tagsKey] = tagsValue; } serverDisasterRecoveryConfigurationCreateOrUpdateParametersValue["tags"] = tagsDictionary; } requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Created && statusCode != HttpStatusCode.Accepted) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result ServerDisasterRecoveryConfigurationCreateOrUpdateResponse result = null; // Deserialize Response result = new ServerDisasterRecoveryConfigurationCreateOrUpdateResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("Location")) { result.OperationStatusLink = httpResponse.Headers.GetValues("Location").FirstOrDefault(); } if (httpResponse.Headers.Contains("Retry-After")) { result.RetryAfter = int.Parse(httpResponse.Headers.GetValues("Retry-After").FirstOrDefault(), CultureInfo.InvariantCulture); } if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (statusCode == HttpStatusCode.Created) { result.Status = OperationStatus.Succeeded; } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Creates a new or updates an existing Azure SQL Server disaster /// recovery configuration. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the Azure SQL /// Database Server belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Server. /// </param> /// <param name='serverDisasterRecoveryConfigurationName'> /// Required. The name of the Azure SQL Server disaster recovery /// configuration to be operated on (Updated or created). /// </param> /// <param name='parameters'> /// Required. The required parameters for creating or updating a Server /// disaster recovery configuration. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Response for long running Azure Sql server disaster recovery /// configuration operation. /// </returns> public async Task<ServerDisasterRecoveryConfigurationCreateOrUpdateResponse> CreateOrUpdateAsync(string resourceGroupName, string serverName, string serverDisasterRecoveryConfigurationName, ServerDisasterRecoveryConfigurationCreateOrUpdateParameters parameters, CancellationToken cancellationToken) { SqlManagementClient client = this.Client; bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("serverName", serverName); tracingParameters.Add("serverDisasterRecoveryConfigurationName", serverDisasterRecoveryConfigurationName); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "CreateOrUpdateAsync", tracingParameters); } cancellationToken.ThrowIfCancellationRequested(); ServerDisasterRecoveryConfigurationCreateOrUpdateResponse response = await client.ServerDisasterRecoveryConfigurations.BeginCreateOrUpdateAsync(resourceGroupName, serverName, serverDisasterRecoveryConfigurationName, parameters, cancellationToken).ConfigureAwait(false); if (response.Status == OperationStatus.Succeeded) { return response; } cancellationToken.ThrowIfCancellationRequested(); ServerDisasterRecoveryConfigurationCreateOrUpdateResponse result = await client.ServerDisasterRecoveryConfigurations.GetServerDisasterRecoveryConfigurationOperationStatusAsync(response.OperationStatusLink, cancellationToken).ConfigureAwait(false); int delayInSeconds = response.RetryAfter; if (delayInSeconds == 0) { delayInSeconds = 30; } if (client.LongRunningOperationInitialTimeout >= 0) { delayInSeconds = client.LongRunningOperationInitialTimeout; } while (result.Status == OperationStatus.InProgress) { cancellationToken.ThrowIfCancellationRequested(); await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); result = await client.ServerDisasterRecoveryConfigurations.GetServerDisasterRecoveryConfigurationOperationStatusAsync(response.OperationStatusLink, cancellationToken).ConfigureAwait(false); delayInSeconds = result.RetryAfter; if (delayInSeconds == 0) { delayInSeconds = 15; } if (client.LongRunningOperationRetryTimeout >= 0) { delayInSeconds = client.LongRunningOperationRetryTimeout; } } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } /// <summary> /// Deletes the Azure SQL server disaster recovery configuration with /// the given name. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the Azure SQL /// Server belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Server. /// </param> /// <param name='serverDisasterRecoveryConfigurationName'> /// Required. The name of the Azure SQL server disaster recovery /// configuration to be deleted. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public async Task<AzureOperationResponse> DeleteAsync(string resourceGroupName, string serverName, string serverDisasterRecoveryConfigurationName, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (serverName == null) { throw new ArgumentNullException("serverName"); } if (serverDisasterRecoveryConfigurationName == null) { throw new ArgumentNullException("serverDisasterRecoveryConfigurationName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("serverName", serverName); tracingParameters.Add("serverDisasterRecoveryConfigurationName", serverDisasterRecoveryConfigurationName); TracingAdapter.Enter(invocationId, this, "DeleteAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; url = url + "Microsoft.Sql"; url = url + "/servers/"; url = url + Uri.EscapeDataString(serverName); url = url + "/disasterRecoveryConfiguration/"; url = url + Uri.EscapeDataString(serverDisasterRecoveryConfigurationName); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2014-04-01"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Delete; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.NoContent) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result AzureOperationResponse result = null; // Deserialize Response result = new AzureOperationResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Begins failover for the Azure SQL server disaster recovery /// configuration with the given name. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the Azure SQL /// Server belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Server. /// </param> /// <param name='serverDisasterRecoveryConfigurationName'> /// Required. The name of the Azure SQL server disaster recovery /// configuration to start failover. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public async Task<AzureOperationResponse> FailoverAsync(string resourceGroupName, string serverName, string serverDisasterRecoveryConfigurationName, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (serverName == null) { throw new ArgumentNullException("serverName"); } if (serverDisasterRecoveryConfigurationName == null) { throw new ArgumentNullException("serverDisasterRecoveryConfigurationName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("serverName", serverName); tracingParameters.Add("serverDisasterRecoveryConfigurationName", serverDisasterRecoveryConfigurationName); TracingAdapter.Enter(invocationId, this, "FailoverAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; url = url + "Microsoft.Sql"; url = url + "/servers/"; url = url + Uri.EscapeDataString(serverName); url = url + "/disasterRecoveryConfiguration/"; url = url + Uri.EscapeDataString(serverDisasterRecoveryConfigurationName); url = url + "/failover"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2014-04-01"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Post; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.NoContent) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result AzureOperationResponse result = null; // Deserialize Response result = new AzureOperationResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Begins failover for the Azure SQL server disaster recovery /// configuration with the given name. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the Azure SQL /// Server belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Server. /// </param> /// <param name='serverDisasterRecoveryConfigurationName'> /// Required. The name of the Azure SQL server disaster recovery /// configuration to start failover. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public async Task<AzureOperationResponse> FailoverAllowDataLossAsync(string resourceGroupName, string serverName, string serverDisasterRecoveryConfigurationName, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (serverName == null) { throw new ArgumentNullException("serverName"); } if (serverDisasterRecoveryConfigurationName == null) { throw new ArgumentNullException("serverDisasterRecoveryConfigurationName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("serverName", serverName); tracingParameters.Add("serverDisasterRecoveryConfigurationName", serverDisasterRecoveryConfigurationName); TracingAdapter.Enter(invocationId, this, "FailoverAllowDataLossAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; url = url + "Microsoft.Sql"; url = url + "/servers/"; url = url + Uri.EscapeDataString(serverName); url = url + "/disasterRecoveryConfiguration/"; url = url + Uri.EscapeDataString(serverDisasterRecoveryConfigurationName); url = url + "/forceFailoverAllowDataLoss"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2014-04-01"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Post; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.NoContent) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result AzureOperationResponse result = null; // Deserialize Response result = new AzureOperationResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Returns information about an Azure SQL Server disaster recovery /// configurations. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the server /// belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Server. /// </param> /// <param name='serverDisasterRecoveryConfigurationName'> /// Required. The name of the Azure SQL server disaster recovery /// configuration to be retrieved. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Represents the response to a get server disaster recovery /// configuration request. /// </returns> public async Task<ServerDisasterRecoveryConfigurationGetResponse> GetAsync(string resourceGroupName, string serverName, string serverDisasterRecoveryConfigurationName, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (serverName == null) { throw new ArgumentNullException("serverName"); } if (serverDisasterRecoveryConfigurationName == null) { throw new ArgumentNullException("serverDisasterRecoveryConfigurationName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("serverName", serverName); tracingParameters.Add("serverDisasterRecoveryConfigurationName", serverDisasterRecoveryConfigurationName); TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; url = url + "Microsoft.Sql"; url = url + "/servers/"; url = url + Uri.EscapeDataString(serverName); url = url + "/disasterRecoveryConfiguration/"; url = url + Uri.EscapeDataString(serverDisasterRecoveryConfigurationName); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2014-04-01"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result ServerDisasterRecoveryConfigurationGetResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ServerDisasterRecoveryConfigurationGetResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { ServerDisasterRecoveryConfiguration serverDisasterRecoveryConfigurationInstance = new ServerDisasterRecoveryConfiguration(); result.ServerDisasterRecoveryConfiguration = serverDisasterRecoveryConfigurationInstance; JToken propertiesValue = responseDoc["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { ServerDisasterRecoveryConfigurationProperties propertiesInstance = new ServerDisasterRecoveryConfigurationProperties(); serverDisasterRecoveryConfigurationInstance.Properties = propertiesInstance; JToken autoFailoverValue = propertiesValue["autoFailover"]; if (autoFailoverValue != null && autoFailoverValue.Type != JTokenType.Null) { string autoFailoverInstance = ((string)autoFailoverValue); propertiesInstance.AutoFailover = autoFailoverInstance; } JToken failoverPolicyValue = propertiesValue["failoverPolicy"]; if (failoverPolicyValue != null && failoverPolicyValue.Type != JTokenType.Null) { string failoverPolicyInstance = ((string)failoverPolicyValue); propertiesInstance.FailoverPolicy = failoverPolicyInstance; } JToken partnerLogicalServerNameValue = propertiesValue["partnerLogicalServerName"]; if (partnerLogicalServerNameValue != null && partnerLogicalServerNameValue.Type != JTokenType.Null) { string partnerLogicalServerNameInstance = ((string)partnerLogicalServerNameValue); propertiesInstance.PartnerLogicalServerName = partnerLogicalServerNameInstance; } JToken partnerServerIdValue = propertiesValue["partnerServerId"]; if (partnerServerIdValue != null && partnerServerIdValue.Type != JTokenType.Null) { string partnerServerIdInstance = ((string)partnerServerIdValue); propertiesInstance.PartnerServerId = partnerServerIdInstance; } JToken roleValue = propertiesValue["role"]; if (roleValue != null && roleValue.Type != JTokenType.Null) { string roleInstance = ((string)roleValue); propertiesInstance.Role = roleInstance; } JToken typeValue = propertiesValue["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); propertiesInstance.Type = typeInstance; } } JToken idValue = responseDoc["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); serverDisasterRecoveryConfigurationInstance.Id = idInstance; } JToken nameValue = responseDoc["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); serverDisasterRecoveryConfigurationInstance.Name = nameInstance; } JToken typeValue2 = responseDoc["type"]; if (typeValue2 != null && typeValue2.Type != JTokenType.Null) { string typeInstance2 = ((string)typeValue2); serverDisasterRecoveryConfigurationInstance.Type = typeInstance2; } JToken locationValue = responseDoc["location"]; if (locationValue != null && locationValue.Type != JTokenType.Null) { string locationInstance = ((string)locationValue); serverDisasterRecoveryConfigurationInstance.Location = locationInstance; } JToken tagsSequenceElement = ((JToken)responseDoc["tags"]); if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in tagsSequenceElement) { string tagsKey = ((string)property.Name); string tagsValue = ((string)property.Value); serverDisasterRecoveryConfigurationInstance.Tags.Add(tagsKey, tagsValue); } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Gets the status of an Azure Sql Server disaster recovery /// configuration create or update operation. /// </summary> /// <param name='operationStatusLink'> /// Required. Location value returned by the Begin operation /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Response for long running Azure Sql server disaster recovery /// configuration operation. /// </returns> public async Task<ServerDisasterRecoveryConfigurationCreateOrUpdateResponse> GetServerDisasterRecoveryConfigurationOperationStatusAsync(string operationStatusLink, CancellationToken cancellationToken) { // Validate if (operationStatusLink == null) { throw new ArgumentNullException("operationStatusLink"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("operationStatusLink", operationStatusLink); TracingAdapter.Enter(invocationId, this, "GetServerDisasterRecoveryConfigurationOperationStatusAsync", tracingParameters); } // Construct URL string url = ""; url = url + operationStatusLink; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Created && statusCode != HttpStatusCode.Accepted) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result ServerDisasterRecoveryConfigurationCreateOrUpdateResponse result = null; // Deserialize Response result = new ServerDisasterRecoveryConfigurationCreateOrUpdateResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (statusCode == HttpStatusCode.OK) { result.Status = OperationStatus.Succeeded; } if (statusCode == HttpStatusCode.Created) { result.Status = OperationStatus.Succeeded; } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Returns information about Azure SQL Server disaster recovery /// configurations. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the Azure SQL /// Server belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Server. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Represents the response to a List Azure Sql Server disaster /// recovery configuration request. /// </returns> public async Task<ServerDisasterRecoveryConfigurationListResponse> ListAsync(string resourceGroupName, string serverName, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (serverName == null) { throw new ArgumentNullException("serverName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("serverName", serverName); TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; url = url + "Microsoft.Sql"; url = url + "/servers/"; url = url + Uri.EscapeDataString(serverName); url = url + "/disasterRecoveryConfiguration"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2014-04-01"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result ServerDisasterRecoveryConfigurationListResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ServerDisasterRecoveryConfigurationListResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { ServerDisasterRecoveryConfiguration serverDisasterRecoveryConfigurationInstance = new ServerDisasterRecoveryConfiguration(); result.ServerDisasterRecoveryConfigurations.Add(serverDisasterRecoveryConfigurationInstance); JToken propertiesValue = valueValue["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { ServerDisasterRecoveryConfigurationProperties propertiesInstance = new ServerDisasterRecoveryConfigurationProperties(); serverDisasterRecoveryConfigurationInstance.Properties = propertiesInstance; JToken autoFailoverValue = propertiesValue["autoFailover"]; if (autoFailoverValue != null && autoFailoverValue.Type != JTokenType.Null) { string autoFailoverInstance = ((string)autoFailoverValue); propertiesInstance.AutoFailover = autoFailoverInstance; } JToken failoverPolicyValue = propertiesValue["failoverPolicy"]; if (failoverPolicyValue != null && failoverPolicyValue.Type != JTokenType.Null) { string failoverPolicyInstance = ((string)failoverPolicyValue); propertiesInstance.FailoverPolicy = failoverPolicyInstance; } JToken partnerLogicalServerNameValue = propertiesValue["partnerLogicalServerName"]; if (partnerLogicalServerNameValue != null && partnerLogicalServerNameValue.Type != JTokenType.Null) { string partnerLogicalServerNameInstance = ((string)partnerLogicalServerNameValue); propertiesInstance.PartnerLogicalServerName = partnerLogicalServerNameInstance; } JToken partnerServerIdValue = propertiesValue["partnerServerId"]; if (partnerServerIdValue != null && partnerServerIdValue.Type != JTokenType.Null) { string partnerServerIdInstance = ((string)partnerServerIdValue); propertiesInstance.PartnerServerId = partnerServerIdInstance; } JToken roleValue = propertiesValue["role"]; if (roleValue != null && roleValue.Type != JTokenType.Null) { string roleInstance = ((string)roleValue); propertiesInstance.Role = roleInstance; } JToken typeValue = propertiesValue["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); propertiesInstance.Type = typeInstance; } } JToken idValue = valueValue["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); serverDisasterRecoveryConfigurationInstance.Id = idInstance; } JToken nameValue = valueValue["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); serverDisasterRecoveryConfigurationInstance.Name = nameInstance; } JToken typeValue2 = valueValue["type"]; if (typeValue2 != null && typeValue2.Type != JTokenType.Null) { string typeInstance2 = ((string)typeValue2); serverDisasterRecoveryConfigurationInstance.Type = typeInstance2; } JToken locationValue = valueValue["location"]; if (locationValue != null && locationValue.Type != JTokenType.Null) { string locationInstance = ((string)locationValue); serverDisasterRecoveryConfigurationInstance.Location = locationInstance; } JToken tagsSequenceElement = ((JToken)valueValue["tags"]); if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in tagsSequenceElement) { string tagsKey = ((string)property.Name); string tagsValue = ((string)property.Value); serverDisasterRecoveryConfigurationInstance.Tags.Add(tagsKey, tagsValue); } } } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. using System.Diagnostics.Contracts; using System; namespace System.Globalization { public class Calendar { protected Calendar() { } public virtual Int32[] Eras { get { Contract.Ensures(Contract.Result<Int32[]>() != null); return default(Int32[]); } } #if false public int TwoDigitYearMax { get; set; } #endif [Pure] public virtual int ToFourDigitYear(int year) { Contract.Requires(year >= 0); return default(int); } #if false public DateTime ToDateTime(int arg0, int arg1, int arg2, int arg3, int arg4, int arg5, int arg6, int arg7) { return default(DateTime); } public DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond) { return default(DateTime); } #endif [Pure] public virtual bool IsLeapYear(int arg0, int arg1) { return default(bool); } [Pure] public virtual bool IsLeapYear(int year) { return default(bool); } [Pure] public virtual bool IsLeapMonth(int arg0, int arg1, int arg2) { return default(bool); } [Pure] public virtual bool IsLeapMonth(int year, int month) { return default(bool); } [Pure] public virtual bool IsLeapDay(int arg0, int arg1, int arg2, int arg3) { return default(bool); } [Pure] public virtual bool IsLeapDay(int year, int month, int day) { return default(bool); } [Pure] public virtual int GetYear(DateTime arg0) { return default(int); } #if false [Pure] public int GetWeekOfYear(DateTime time, CalendarWeekRule rule, DayOfWeek firstDayOfWeek) { Contract.Requires((int)firstDayOfWeek >= 0); Contract.Requires((int)firstDayOfWeek <= 6); return default(int); } [Pure] public int GetSecond(DateTime time) { return default(int); } #endif [Pure] public virtual int GetMonthsInYear(int arg0, int arg1) { return default(int); } [Pure] public virtual int GetMonthsInYear(int year) { return default(int); } [Pure] public virtual int GetMonth(DateTime arg0) { return default(int); } [Pure] public virtual int GetMinute(DateTime time) { return default(int); } [Pure] public virtual double GetMilliseconds(DateTime time) { return default(double); } [Pure] public virtual int GetHour(DateTime time) { return default(int); } [Pure] public virtual int GetEra(DateTime arg0) { return default(int); } [Pure] public virtual int GetDaysInYear(int arg0, int arg1) { return default(int); } [Pure] public virtual int GetDaysInYear(int year) { return default(int); } [Pure] public virtual int GetDaysInMonth(int arg0, int arg1, int arg2) { return default(int); } [Pure] public virtual int GetDaysInMonth(int year, int month) { return default(int); } [Pure] public virtual int GetDayOfYear(DateTime arg0) { return default(int); } [Pure] public virtual DayOfWeek GetDayOfWeek(DateTime arg0) { return default(DayOfWeek); } [Pure] public virtual int GetDayOfMonth(DateTime arg0) { return default(int); } #if false public DateTime AddYears(DateTime arg0, int arg1) { return default(DateTime); } public DateTime AddWeeks(DateTime time, int weeks) { return default(DateTime); } public DateTime AddSeconds(DateTime time, int seconds) { return default(DateTime); } public DateTime AddMonths(DateTime arg0, int arg1) { return default(DateTime); } public DateTime AddMinutes(DateTime time, int minutes) { return default(DateTime); } public DateTime AddMilliseconds(DateTime time, double milliseconds) { return default(DateTime); } public DateTime AddHours(DateTime time, int hours) { return default(DateTime); } public DateTime AddDays(DateTime time, int days) { return default(DateTime); } #endif } }
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ namespace Microsoft.Graph.Core.Test.Serialization { using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using Microsoft.VisualStudio.TestTools.UnitTesting; using TestModels; using Newtonsoft.Json; using Newtonsoft.Json.Linq; [TestClass] public class SerializerTests { private Serializer serializer; [TestInitialize] public void Setup() { this.serializer = new Serializer(); } [TestMethod] [ExpectedException(typeof(ServiceException))] public void AbstractClassDeserializationFailure() { var stringToDeserialize = "{\"jsonKey\":\"jsonValue\"}"; try { this.serializer.DeserializeObject<AbstractClass>(stringToDeserialize); } catch (ServiceException exception) { Assert.IsTrue(exception.IsMatch(ErrorConstants.Codes.GeneralException), "Unexpected error code thrown."); Assert.AreEqual( string.Format(ErrorConstants.Messages.UnableToCreateInstanceOfTypeFormatString, typeof(AbstractClass).FullName), exception.Error.Message, "Unexpected error message thrown."); throw; } } [TestMethod] public void DeserializeDerivedType() { var id = "id"; var name = "name"; var stringToDeserialize = string.Format( "{{\"id\":\"{0}\", \"@odata.type\":\"#microsoft.graph.core.test.testModels.derivedTypeClass\", \"name\":\"{1}\"}}", id, name); var derivedType = this.serializer.DeserializeObject<AbstractEntityType>(stringToDeserialize) as DerivedTypeClass; Assert.IsNotNull(derivedType, "Object not correctly deserialized."); Assert.AreEqual(id, derivedType.Id, "Unexpected ID initialized."); Assert.AreEqual(name, derivedType.Name, "Unexpected name initialized."); } [TestMethod] public void DeserializeInvalidODataType() { var id = "id"; var givenName = "name"; var stringToDeserialize = string.Format( "{{\"id\":\"{0}\", \"@odata.type\":\"invalid\", \"givenName\":\"{1}\"}}", id, givenName); var instance = this.serializer.DeserializeObject<DerivedTypeClass>(stringToDeserialize); Assert.IsNotNull(instance, "Object not correctly deserialized."); Assert.AreEqual(id, instance.Id, "Unexpected ID initialized."); Assert.IsNotNull(instance.AdditionalData, "Additional data not initialized."); Assert.AreEqual(givenName, instance.AdditionalData["givenName"] as string, "Unexpected additional data initialized."); } [TestMethod] public void DeserializeStream() { var id = "id"; var stringToDeserialize = string.Format("{{\"id\":\"{0}\"}}", id); using (var serializedStream = new MemoryStream(Encoding.UTF8.GetBytes(stringToDeserialize))) { var instance = this.serializer.DeserializeObject<DerivedTypeClass>(serializedStream); Assert.IsNotNull(instance, "Object not correctly deserialized."); Assert.AreEqual(id, instance.Id, "Unexpected ID initialized."); Assert.IsNull(instance.AdditionalData, "Unexpected additional data initialized."); } } [TestMethod] public void DeserializeUnknownEnumValue() { var enumValue = "newValue"; var id = "id"; var stringToDeserialize = string.Format( "{{\"enumType\":\"{0}\",\"id\":\"{1}\"}}", enumValue, id); var instance = this.serializer.DeserializeObject<DerivedTypeClass>(stringToDeserialize); Assert.IsNotNull(instance, "Object not correctly deserialized."); Assert.AreEqual(id, instance.Id, "Unexpected ID initialized."); Assert.IsNull(instance.EnumType, "Unexpected EnumType initialized."); Assert.IsNotNull(instance.AdditionalData, "Additional data not initialized."); Assert.AreEqual(enumValue, instance.AdditionalData["enumType"] as string, "EnumType not set in additional data."); } [TestMethod] [ExpectedException(typeof(ServiceException))] public void DerivedTypeWithoutDefaultConstructor() { var stringToDeserialize = "{\"jsonKey\":\"jsonValue\"}"; try { this.serializer.DeserializeObject<NoDefaultConstructor>(stringToDeserialize); } catch (ServiceException exception) { Assert.IsTrue(exception.IsMatch(ErrorConstants.Codes.GeneralException), "Unexpected error code thrown."); Assert.AreEqual( string.Format( ErrorConstants.Messages.UnableToCreateInstanceOfTypeFormatString, typeof(NoDefaultConstructor).AssemblyQualifiedName), exception.Error.Message, "Unexpected error message thrown."); throw; } } [TestMethod] public void DeserializeDateEnumerableValue() { var now = DateTimeOffset.UtcNow; var tomorrow = now.AddDays(1); var stringToDeserialize = string.Format("{{\"dateCollection\":[\"{0}\",\"{1}\"]}}", now.ToString("yyyy-MM-dd"), tomorrow.ToString("yyyy-MM-dd")); var deserializedObject = this.serializer.DeserializeObject<DateTestClass>(stringToDeserialize); Assert.AreEqual(2, deserializedObject.DateCollection.Count(), "Unexpected number of dates deserialized."); Assert.IsTrue(deserializedObject.DateCollection.Any( date => date.Year == now.Year && date.Month == now.Month && date.Day == now.Day), "Now date not found."); Assert.IsTrue(deserializedObject.DateCollection.Any( date => date.Year == tomorrow.Year && date.Month == tomorrow.Month && date.Day == tomorrow.Day), "Tomorrow date not found."); } [TestMethod] public void DeserializeDateValue() { var now = DateTimeOffset.UtcNow; var stringToDeserialize = string.Format("{{\"nullableDate\":\"{0}\"}}", now.ToString("yyyy-MM-dd")); var dateClass = this.serializer.DeserializeObject<DateTestClass>(stringToDeserialize); Assert.AreEqual(now.Year, dateClass.NullableDate.Year, "Unexpected nullableDate year deserialized."); Assert.AreEqual(now.Month, dateClass.NullableDate.Month, "Unexpected nullableDate month deserialized."); Assert.AreEqual(now.Day, dateClass.NullableDate.Day, "Unexpected nullableDate day deserialized."); } [TestMethod] public void DeserializeInterface() { var collectionPage = new CollectionPageInstance { new DerivedTypeClass { Id = "id" } }; var serializedString = this.serializer.SerializeObject(collectionPage); var deserializedPage = this.serializer.DeserializeObject<ICollectionPageInstance>(serializedString); Assert.IsInstanceOfType(deserializedPage, typeof(CollectionPageInstance), "Unexpected object deserialized."); Assert.AreEqual(1, deserializedPage.Count, "Unexpected page deserialized."); Assert.AreEqual("id", deserializedPage[0].Id, "Unexpected page item deserialized."); } [TestMethod] [ExpectedException(typeof(ServiceException))] public void DeserializeInvalidTypeForDateConverter() { var stringToDeserialize = "{\"invalidType\":1}"; try { var date = this.serializer.DeserializeObject<DateTestClass>(stringToDeserialize); } catch (ServiceException serviceException) { Assert.IsTrue(serviceException.IsMatch(ErrorConstants.Codes.GeneralException), "Unexpected error code thrown."); Assert.AreEqual(ErrorConstants.Messages.UnableToDeserializeDate, serviceException.Error.Message, "Unexpected error message thrown."); Assert.IsInstanceOfType(serviceException.InnerException, typeof(JsonSerializationException), "Unexpected inner exception thrown."); throw; } } [TestMethod] public void NewAbstractDerivedClassInstance() { var entityId = "entityId"; var additionalKey = "key"; var additionalValue = "value"; var stringToDeserialize = string.Format( "{{\"id\":\"{0}\", \"@odata.type\":\"newtype\", \"{1}\":\"{2}\"}}", entityId, additionalKey, additionalValue); var instance = this.serializer.DeserializeObject<AbstractEntityType>(stringToDeserialize); Assert.IsNotNull(instance, "Object not correctly deserialized."); Assert.AreEqual(entityId, instance.Id, "Unexpected ID initialized."); Assert.IsNotNull(instance.AdditionalData, "Additional data not initialized."); Assert.AreEqual(additionalValue, instance.AdditionalData[additionalKey] as string, "Unexpected additional data initialized."); } [TestMethod] public void SerializeAndDeserializeKnownEnumValue() { var instance = new DerivedTypeClass { Id = "id", EnumType = EnumType.Value, }; var expectedSerializedStream = string.Format( "{{\"enumType\":\"{0}\",\"id\":\"{1}\"}}", "value", instance.Id); var serializedValue = this.serializer.SerializeObject(instance); Assert.AreEqual(expectedSerializedStream, serializedValue, "Unexpected value serialized."); var newInstance = this.serializer.DeserializeObject<DerivedTypeClass>(serializedValue); Assert.IsNotNull(newInstance, "Object not correctly deserialized."); Assert.AreEqual(instance.Id, instance.Id, "Unexpected ID initialized."); Assert.AreEqual(EnumType.Value, instance.EnumType, "Unexpected EnumType initialized."); Assert.IsNull(instance.AdditionalData, "Additional data initialized."); } [TestMethod] public void SerializeDateEnumerableValue() { var now = DateTimeOffset.UtcNow; var tomorrow = now.AddDays(1); var expectedSerializedString = string.Format("{{\"nullableDate\":null,\"dateCollection\":[\"{0}\",\"{1}\"]}}", now.ToString("yyyy-MM-dd"), tomorrow.ToString("yyyy-MM-dd")); var recurrence = new DateTestClass { DateCollection = new List<Date> { new Date(now.Year, now.Month, now.Day), new Date(tomorrow.Year, tomorrow.Month, tomorrow.Day) }, }; var serializedString = this.serializer.SerializeObject(recurrence); Assert.AreEqual(expectedSerializedString, serializedString, "Unexpected value serialized."); } [TestMethod] public void SerializeDateNullValue() { var now = DateTimeOffset.UtcNow; var expectedSerializedString = "{\"nullableDate\":null}"; var recurrence = new DateTestClass(); var serializedString = this.serializer.SerializeObject(recurrence); Assert.AreEqual(expectedSerializedString, serializedString, "Unexpected value serialized."); } [TestMethod] public void SerializeDateValue() { var now = DateTimeOffset.UtcNow; var expectedSerializedString = string.Format("{{\"nullableDate\":\"{0}\"}}", now.ToString("yyyy-MM-dd")); var date = new DateTestClass { NullableDate = new Date(now.Year, now.Month, now.Day), }; var serializedString = this.serializer.SerializeObject(date); Assert.AreEqual(expectedSerializedString, serializedString, "Unexpected value serialized."); } [TestMethod] [ExpectedException(typeof(ServiceException))] public void SerializeInvalidTypeForDateConverter() { var dateToSerialize = new DateTestClass { InvalidType = 1, }; try { var serializedString = this.serializer.SerializeObject(dateToSerialize); } catch (ServiceException serviceException) { Assert.IsTrue(serviceException.IsMatch(ErrorConstants.Codes.GeneralException), "Unexpected error code thrown."); Assert.AreEqual( ErrorConstants.Messages.InvalidTypeForDateConverter, serviceException.Error.Message, "Unexpected error message thrown."); throw; } } [TestMethod] public void VerifyTypeMappingCache() { // Clear the cache so it won't have mappings from previous tests. DerivedTypeConverter.TypeMappingCache.Clear(); var id = "id"; var derivedTypeClassTypeString = "microsoft.graph.core.test.testModels.derivedTypeClass"; var dateTestClassTypeString = "microsoft.graph.core.test.testModels.dateTestClass"; var deserializeExistingTypeString = string.Format( "{{\"id\":\"{0}\", \"@odata.type\":\"#{1}\"}}", id, derivedTypeClassTypeString); var derivedType = this.serializer.DeserializeObject<AbstractEntityType>(deserializeExistingTypeString) as DerivedTypeClass; var derivedType2 = this.serializer.DeserializeObject<DerivedTypeClass>(deserializeExistingTypeString) as DerivedTypeClass; var deserializeUnknownTypeString = string.Format( "{{\"id\":\"{0}\", \"@odata.type\":\"#unknown\"}}", id); var upcastType = this.serializer.DeserializeObject<DerivedTypeClass>(deserializeUnknownTypeString) as DerivedTypeClass; var dateTestTypeString = string.Format( "{{\"@odata.type\":\"#{1}\"}}", id, dateTestClassTypeString); var dateTestType = this.serializer.DeserializeObject<DateTestClass>(dateTestTypeString) as DateTestClass; Assert.IsNotNull(derivedType, "Unexpected instance returned for derived type instance."); Assert.IsNotNull(derivedType2, "Unexpected instance returned for derived type instance 2."); Assert.IsNotNull(upcastType, "Unexpected instance returned for up cast type."); Assert.IsNotNull(dateTestType, "Unexpected instance returned for date test type."); Assert.AreEqual(3, DerivedTypeConverter.TypeMappingCache.Count, "Unexpected number of entries in type mapping cache."); Assert.AreEqual( typeof(DerivedTypeClass), DerivedTypeConverter.TypeMappingCache[derivedTypeClassTypeString], "Unexpected type cached for {0}", derivedTypeClassTypeString); Assert.AreEqual( typeof(DerivedTypeClass), DerivedTypeConverter.TypeMappingCache["unknown"], "Unexpected type cached for {0}", derivedTypeClassTypeString); Assert.AreEqual( typeof(DateTestClass), DerivedTypeConverter.TypeMappingCache[dateTestClassTypeString], "Unexpected type cached for {0}", dateTestClassTypeString); } [TestMethod] public void SerializeDeserializeJson() { var expectedSerializedString = "{\"data\":{\"int\":42,\"float\":3.14,\"str\":\"dude\",\"bool\":true,\"null\":null,\"arr\":[\"sweet\",2.82,43,false]}}"; JArray arr = new JArray(); arr.Add("sweet"); arr.Add(2.82); arr.Add(43); arr.Add(false); JObject obj = new JObject(); obj["int"] = 42; obj["float"] = 3.14; obj["str"] = "dude"; obj["bool"] = true; obj["null"] = null; obj["arr"] = arr; ClassWithJson jsCls = new ClassWithJson(); jsCls.Data = obj; var s = this.serializer.SerializeObject(jsCls); Assert.AreEqual(s, expectedSerializedString); var parsedObj = this.serializer.DeserializeObject<ClassWithJson>(s); var jsObj = parsedObj.Data; Assert.AreEqual(jsObj.Type, JTokenType.Object); Assert.AreEqual(jsObj["int"].Type, JTokenType.Integer); Assert.AreEqual(jsObj["float"].Type, JTokenType.Float); Assert.AreEqual(jsObj["str"].Type, JTokenType.String); Assert.AreEqual(jsObj["bool"].Type, JTokenType.Boolean); Assert.AreEqual(jsObj["null"].Type, JTokenType.Null); Assert.AreEqual(jsObj["arr"].Type, JTokenType.Array); Assert.AreEqual(jsObj["int"], 42); Assert.AreEqual(jsObj["float"], 3.14); Assert.AreEqual(jsObj["str"], "dude"); Assert.AreEqual(jsObj["bool"], true); Assert.AreEqual((jsObj["null"] as JValue).Value, null); var jsArr = jsObj["arr"] as JArray; Assert.IsNotNull(jsArr); Assert.AreEqual(jsArr.Count, 4); Assert.AreEqual(jsArr[0].Type, JTokenType.String); Assert.AreEqual(jsArr[1].Type, JTokenType.Float); Assert.AreEqual(jsArr[2].Type, JTokenType.Integer); Assert.AreEqual(jsArr[3].Type, JTokenType.Boolean); Assert.AreEqual(jsArr[0], "sweet"); Assert.AreEqual(jsArr[1], 2.82); Assert.AreEqual(jsArr[2], 43); Assert.AreEqual(jsArr[3], false); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Media; namespace MahApps.Metro.Controls { public class DataGridNumericUpDownColumn : DataGridBoundColumn { private static Style _defaultEditingElementStyle; private static Style _defaultElementStyle; static DataGridNumericUpDownColumn() { ElementStyleProperty.OverrideMetadata(typeof(DataGridNumericUpDownColumn), new FrameworkPropertyMetadata(DefaultElementStyle)); EditingElementStyleProperty.OverrideMetadata(typeof(DataGridNumericUpDownColumn), new FrameworkPropertyMetadata(DefaultEditingElementStyle)); } public static Style DefaultEditingElementStyle { get { if (_defaultEditingElementStyle == null) { var style = new Style(typeof(NumericUpDown)); style.Setters.Add(new Setter(ScrollViewer.HorizontalScrollBarVisibilityProperty, ScrollBarVisibility.Disabled)); style.Setters.Add(new Setter(ScrollViewer.VerticalScrollBarVisibilityProperty, ScrollBarVisibility.Disabled)); style.Setters.Add(new Setter(ControlsHelper.DisabledVisualElementVisibilityProperty, Visibility.Collapsed)); style.Setters.Add(new Setter(Control.BorderThicknessProperty, new Thickness(0))); style.Setters.Add(new Setter(NumericUpDown.HideUpDownButtonsProperty, false)); style.Setters.Add(new Setter(FrameworkElement.MinHeightProperty, 0d)); style.Setters.Add(new Setter(FrameworkElement.VerticalAlignmentProperty, VerticalAlignment.Top)); style.Setters.Add(new Setter(Control.VerticalContentAlignmentProperty, VerticalAlignment.Center)); style.Setters.Add(new Setter(ControlsHelper.CornerRadiusProperty, new CornerRadius(0))); style.Seal(); _defaultEditingElementStyle = style; } return _defaultEditingElementStyle; } } public static Style DefaultElementStyle { get { if (_defaultElementStyle == null) { var style = new Style(typeof(NumericUpDown)); style.Setters.Add(new Setter(ScrollViewer.HorizontalScrollBarVisibilityProperty, ScrollBarVisibility.Disabled)); style.Setters.Add(new Setter(ScrollViewer.VerticalScrollBarVisibilityProperty, ScrollBarVisibility.Disabled)); style.Setters.Add(new Setter(ControlsHelper.DisabledVisualElementVisibilityProperty, Visibility.Collapsed)); style.Setters.Add(new Setter(UIElement.IsHitTestVisibleProperty, false)); style.Setters.Add(new Setter(UIElement.FocusableProperty, false)); style.Setters.Add(new Setter(Control.BackgroundProperty, Brushes.Transparent)); style.Setters.Add(new Setter(Control.BorderThicknessProperty, new Thickness(0))); style.Setters.Add(new Setter(NumericUpDown.HideUpDownButtonsProperty, true)); style.Setters.Add(new Setter(FrameworkElement.MinHeightProperty, 0d)); style.Setters.Add(new Setter(FrameworkElement.VerticalAlignmentProperty, VerticalAlignment.Top)); style.Setters.Add(new Setter(Control.VerticalContentAlignmentProperty, VerticalAlignment.Center)); style.Setters.Add(new Setter(ControlsHelper.CornerRadiusProperty, new CornerRadius(0))); style.Seal(); _defaultElementStyle = style; } return _defaultElementStyle; } } private static void ApplyBinding(BindingBase binding, DependencyObject target, DependencyProperty property) { if (binding != null) { BindingOperations.SetBinding(target, property, binding); } else { BindingOperations.ClearBinding(target, property); } } private void ApplyStyle(bool isEditing, bool defaultToElementStyle, FrameworkElement element) { Style style = this.PickStyle(isEditing, defaultToElementStyle); if (style != null) { element.Style = style; } } protected override FrameworkElement GenerateEditingElement(DataGridCell cell, object dataItem) { return this.GenerateNumericUpDown(true, cell); } protected override FrameworkElement GenerateElement(DataGridCell cell, object dataItem) { return this.GenerateNumericUpDown(false, cell); } private NumericUpDown GenerateNumericUpDown(bool isEditing, DataGridCell cell) { var numericUpDown = cell?.Content as NumericUpDown ?? new NumericUpDown(); SyncColumnProperty(this, numericUpDown, FontFamilyProperty, TextElement.FontFamilyProperty); SyncColumnProperty(this, numericUpDown, FontSizeProperty, TextElement.FontSizeProperty); SyncColumnProperty(this, numericUpDown, FontStyleProperty, TextElement.FontStyleProperty); SyncColumnProperty(this, numericUpDown, FontWeightProperty, TextElement.FontWeightProperty); SyncColumnProperty(this, numericUpDown, TextAlignmentProperty, NumericUpDown.TextAlignmentProperty); SyncColumnProperty(this, numericUpDown, StringFormatProperty, NumericUpDown.StringFormatProperty); SyncColumnProperty(this, numericUpDown, CultureProperty, NumericUpDown.CultureProperty); SyncColumnProperty(this, numericUpDown, MinimumProperty, NumericUpDown.MinimumProperty); SyncColumnProperty(this, numericUpDown, MaximumProperty, NumericUpDown.MaximumProperty); SyncColumnProperty(this, numericUpDown, NumericInputModeProperty, NumericUpDown.NumericInputModeProperty); SyncColumnProperty(this, numericUpDown, DecimalPointCorrectionProperty, NumericUpDown.DecimalPointCorrectionProperty); SyncColumnProperty(this, numericUpDown, IntervalProperty, NumericUpDown.IntervalProperty); SyncColumnProperty(this, numericUpDown, DelayProperty, NumericUpDown.DelayProperty); SyncColumnProperty(this, numericUpDown, SpeedupProperty, NumericUpDown.SpeedupProperty); SyncColumnProperty(this, numericUpDown, SnapToMultipleOfIntervalProperty, NumericUpDown.SnapToMultipleOfIntervalProperty); SyncColumnProperty(this, numericUpDown, InterceptArrowKeysProperty, NumericUpDown.InterceptArrowKeysProperty); SyncColumnProperty(this, numericUpDown, InterceptManualEnterProperty, NumericUpDown.InterceptManualEnterProperty); SyncColumnProperty(this, numericUpDown, InterceptMouseWheelProperty, NumericUpDown.InterceptMouseWheelProperty); SyncColumnProperty(this, numericUpDown, TrackMouseWheelWhenMouseOverProperty, NumericUpDown.TrackMouseWheelWhenMouseOverProperty); SyncColumnProperty(this, numericUpDown, HideUpDownButtonsProperty, NumericUpDown.HideUpDownButtonsProperty); SyncColumnProperty(this, numericUpDown, SwitchUpDownButtonsProperty, NumericUpDown.SwitchUpDownButtonsProperty); SyncColumnProperty(this, numericUpDown, ButtonsAlignmentProperty, NumericUpDown.ButtonsAlignmentProperty); SyncColumnProperty(this, numericUpDown, UpDownButtonsWidthProperty, NumericUpDown.UpDownButtonsWidthProperty); if (isEditing) { SyncColumnProperty(this, numericUpDown, ForegroundProperty, TextElement.ForegroundProperty); } else { if (!SyncColumnProperty(this, numericUpDown, ForegroundProperty, TextElement.ForegroundProperty)) { ApplyBinding(new Binding(Control.ForegroundProperty.Name) { Source = cell, Mode = BindingMode.OneWay }, numericUpDown, TextElement.ForegroundProperty); } } this.ApplyStyle(isEditing, true, numericUpDown); ApplyBinding(this.Binding, numericUpDown, NumericUpDown.ValueProperty); numericUpDown.Focusable = isEditing; numericUpDown.IsHitTestVisible = isEditing; return numericUpDown; } /// <summary> /// Called when a cell has just switched to edit mode. /// </summary> /// <param name="editingElement">A reference to element returned by GenerateEditingElement.</param> /// <param name="editingEventArgs">The event args of the input event that caused the cell to go into edit mode. May be null.</param> /// <returns>The unedited value of the cell.</returns> protected override object PrepareCellForEdit(FrameworkElement editingElement, RoutedEventArgs editingEventArgs) { if (editingElement is NumericUpDown numericUpDown) { numericUpDown.Focus(); numericUpDown.SelectAll(); return numericUpDown.Value; } return null; } /// <summary> /// Synchronizes the column property. Taken from Helper code for DataGrid. /// </summary> internal static bool SyncColumnProperty(DependencyObject column, DependencyObject content, DependencyProperty columnProperty, DependencyProperty contentProperty) { if (IsDefaultValue(column, columnProperty)) { content.ClearValue(contentProperty); return false; } else { content.SetValue(contentProperty, column.GetValue(columnProperty)); return true; } } /// <summary> /// Taken from Helper code for DataGrid. /// </summary> private static bool IsDefaultValue(DependencyObject d, DependencyProperty dp) { return DependencyPropertyHelper.GetValueSource(d, dp).BaseValueSource == BaseValueSource.Default; } private Style PickStyle(bool isEditing, bool defaultToElementStyle) { Style style = isEditing ? this.EditingElementStyle : this.ElementStyle; if (isEditing && defaultToElementStyle && (style == null)) { style = this.ElementStyle; } return style; } /// <summary>Identifies the <see cref="StringFormat"/> dependency property.</summary> public static readonly DependencyProperty StringFormatProperty = NumericUpDown.StringFormatProperty.AddOwner( typeof(DataGridNumericUpDownColumn), new FrameworkPropertyMetadata((string)NumericUpDown.StringFormatProperty.DefaultMetadata.DefaultValue, FrameworkPropertyMetadataOptions.Inherits, NotifyPropertyChangeForRefreshContent)); /// <summary> /// Gets or sets the formatting for the displaying value. /// </summary> /// <remarks> /// <see href="http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx"></see> /// </remarks> public string StringFormat { get { return (string)this.GetValue(StringFormatProperty); } set { this.SetValue(StringFormatProperty, value); } } /// <summary>Identifies the <see cref="Culture"/> dependency property.</summary> public static readonly DependencyProperty CultureProperty = NumericUpDown.CultureProperty.AddOwner( typeof(DataGridNumericUpDownColumn), new FrameworkPropertyMetadata((CultureInfo)NumericUpDown.CultureProperty.DefaultMetadata.DefaultValue, FrameworkPropertyMetadataOptions.Inherits, NotifyPropertyChangeForRefreshContent)); public CultureInfo Culture { get { return (CultureInfo)this.GetValue(CultureProperty); } set { this.SetValue(CultureProperty, value); } } public static readonly DependencyProperty TextAlignmentProperty = NumericUpDown.TextAlignmentProperty.AddOwner( typeof(DataGridNumericUpDownColumn), new FrameworkPropertyMetadata((TextAlignment)NumericUpDown.TextAlignmentProperty.DefaultMetadata.DefaultValue, FrameworkPropertyMetadataOptions.Inherits, NotifyPropertyChangeForRefreshContent)); public TextAlignment TextAlignment { get { return (TextAlignment)this.GetValue(TextAlignmentProperty); } set { this.SetValue(TextAlignmentProperty, value); } } /// <summary>Identifies the <see cref="Minimum"/> dependency property.</summary> public static readonly DependencyProperty MinimumProperty = NumericUpDown.MinimumProperty.AddOwner( typeof(DataGridNumericUpDownColumn), new FrameworkPropertyMetadata((double)NumericUpDown.MinimumProperty.DefaultMetadata.DefaultValue, FrameworkPropertyMetadataOptions.Inherits, NotifyPropertyChangeForRefreshContent)); public double Minimum { get { return (double)this.GetValue(MinimumProperty); } set { this.SetValue(MinimumProperty, value); } } /// <summary>Identifies the <see cref="Maximum"/> dependency property.</summary> public static readonly DependencyProperty MaximumProperty = NumericUpDown.MaximumProperty.AddOwner( typeof(DataGridNumericUpDownColumn), new FrameworkPropertyMetadata((double)NumericUpDown.MaximumProperty.DefaultMetadata.DefaultValue, FrameworkPropertyMetadataOptions.Inherits, NotifyPropertyChangeForRefreshContent)); public double Maximum { get { return (double)this.GetValue(MaximumProperty); } set { this.SetValue(MaximumProperty, value); } } /// <summary>Identifies the <see cref="NumericInputMode"/> dependency property.</summary> public static readonly DependencyProperty NumericInputModeProperty = NumericUpDown.NumericInputModeProperty.AddOwner( typeof(DataGridNumericUpDownColumn), new FrameworkPropertyMetadata((NumericInput)NumericUpDown.NumericInputModeProperty.DefaultMetadata.DefaultValue, FrameworkPropertyMetadataOptions.Inherits, NotifyPropertyChangeForRefreshContent)); public NumericInput NumericInputMode { get { return (NumericInput)this.GetValue(NumericInputModeProperty); } set { this.SetValue(NumericInputModeProperty, value); } } /// <summary>Identifies the <see cref="DecimalPointCorrection"/> dependency property.</summary> public static readonly DependencyProperty DecimalPointCorrectionProperty = DependencyProperty.Register(nameof(DecimalPointCorrection), typeof(DecimalPointCorrectionMode), typeof(DataGridNumericUpDownColumn), new PropertyMetadata(default(DecimalPointCorrectionMode))); /// <summary> /// Gets or sets the decimal-point correction mode. The default is <see cref="DecimalPointCorrectionMode.Inherits"/> /// </summary> public DecimalPointCorrectionMode DecimalPointCorrection { get => (DecimalPointCorrectionMode)this.GetValue(DecimalPointCorrectionProperty); set => this.SetValue(DecimalPointCorrectionProperty, value); } /// <summary>Identifies the <see cref="Interval"/> dependency property.</summary> public static readonly DependencyProperty IntervalProperty = NumericUpDown.IntervalProperty.AddOwner( typeof(DataGridNumericUpDownColumn), new FrameworkPropertyMetadata((double)NumericUpDown.IntervalProperty.DefaultMetadata.DefaultValue, FrameworkPropertyMetadataOptions.Inherits, NotifyPropertyChangeForRefreshContent)); public double Interval { get { return (double)this.GetValue(IntervalProperty); } set { this.SetValue(IntervalProperty, value); } } /// <summary>Identifies the <see cref="Delay"/> dependency property.</summary> public static readonly DependencyProperty DelayProperty = NumericUpDown.DelayProperty.AddOwner( typeof(DataGridNumericUpDownColumn), new FrameworkPropertyMetadata((int)NumericUpDown.DelayProperty.DefaultMetadata.DefaultValue, FrameworkPropertyMetadataOptions.Inherits, NotifyPropertyChangeForRefreshContent)); public int Delay { get { return (int)this.GetValue(DelayProperty); } set { this.SetValue(DelayProperty, value); } } /// <summary>Identifies the <see cref="Speedup"/> dependency property.</summary> public static readonly DependencyProperty SpeedupProperty = NumericUpDown.SpeedupProperty.AddOwner( typeof(DataGridNumericUpDownColumn), new FrameworkPropertyMetadata((bool)NumericUpDown.SpeedupProperty.DefaultMetadata.DefaultValue, FrameworkPropertyMetadataOptions.Inherits, NotifyPropertyChangeForRefreshContent)); public bool Speedup { get { return (bool)this.GetValue(SpeedupProperty); } set { this.SetValue(SpeedupProperty, value); } } /// <summary>Identifies the <see cref="SnapToMultipleOfInterval"/> dependency property.</summary> public static readonly DependencyProperty SnapToMultipleOfIntervalProperty = NumericUpDown.SnapToMultipleOfIntervalProperty.AddOwner( typeof(DataGridNumericUpDownColumn), new FrameworkPropertyMetadata((bool)NumericUpDown.SnapToMultipleOfIntervalProperty.DefaultMetadata.DefaultValue, FrameworkPropertyMetadataOptions.Inherits, NotifyPropertyChangeForRefreshContent)); public bool SnapToMultipleOfInterval { get { return (bool)this.GetValue(SnapToMultipleOfIntervalProperty); } set { this.SetValue(SnapToMultipleOfIntervalProperty, value); } } /// <summary>Identifies the <see cref="InterceptArrowKeys"/> dependency property.</summary> public static readonly DependencyProperty InterceptArrowKeysProperty = NumericUpDown.InterceptArrowKeysProperty.AddOwner( typeof(DataGridNumericUpDownColumn), new FrameworkPropertyMetadata((bool)NumericUpDown.InterceptArrowKeysProperty.DefaultMetadata.DefaultValue, FrameworkPropertyMetadataOptions.Inherits, NotifyPropertyChangeForRefreshContent)); public bool InterceptArrowKeys { get { return (bool)this.GetValue(InterceptArrowKeysProperty); } set { this.SetValue(InterceptArrowKeysProperty, value); } } /// <summary>Identifies the <see cref="InterceptManualEnter"/> dependency property.</summary> public static readonly DependencyProperty InterceptManualEnterProperty = NumericUpDown.InterceptManualEnterProperty.AddOwner( typeof(DataGridNumericUpDownColumn), new FrameworkPropertyMetadata((bool)NumericUpDown.InterceptManualEnterProperty.DefaultMetadata.DefaultValue, FrameworkPropertyMetadataOptions.Inherits, NotifyPropertyChangeForRefreshContent)); public bool InterceptManualEnter { get { return (bool)this.GetValue(InterceptManualEnterProperty); } set { this.SetValue(InterceptManualEnterProperty, value); } } /// <summary>Identifies the <see cref="InterceptMouseWheel"/> dependency property.</summary> public static readonly DependencyProperty InterceptMouseWheelProperty = NumericUpDown.InterceptMouseWheelProperty.AddOwner( typeof(DataGridNumericUpDownColumn), new FrameworkPropertyMetadata((bool)NumericUpDown.InterceptMouseWheelProperty.DefaultMetadata.DefaultValue, FrameworkPropertyMetadataOptions.Inherits, NotifyPropertyChangeForRefreshContent)); public bool InterceptMouseWheel { get { return (bool)this.GetValue(InterceptMouseWheelProperty); } set { this.SetValue(InterceptMouseWheelProperty, value); } } /// <summary>Identifies the <see cref="TrackMouseWheelWhenMouseOver"/> dependency property.</summary> public static readonly DependencyProperty TrackMouseWheelWhenMouseOverProperty = NumericUpDown.TrackMouseWheelWhenMouseOverProperty.AddOwner( typeof(DataGridNumericUpDownColumn), new FrameworkPropertyMetadata((bool)NumericUpDown.TrackMouseWheelWhenMouseOverProperty.DefaultMetadata.DefaultValue, FrameworkPropertyMetadataOptions.Inherits, NotifyPropertyChangeForRefreshContent)); public bool TrackMouseWheelWhenMouseOver { get { return (bool)this.GetValue(TrackMouseWheelWhenMouseOverProperty); } set { this.SetValue(TrackMouseWheelWhenMouseOverProperty, value); } } /// <summary>Identifies the <see cref="HideUpDownButtons"/> dependency property.</summary> public static readonly DependencyProperty HideUpDownButtonsProperty = NumericUpDown.HideUpDownButtonsProperty.AddOwner( typeof(DataGridNumericUpDownColumn), new FrameworkPropertyMetadata((bool)NumericUpDown.HideUpDownButtonsProperty.DefaultMetadata.DefaultValue, FrameworkPropertyMetadataOptions.Inherits, NotifyPropertyChangeForRefreshContent)); public bool HideUpDownButtons { get { return (bool)this.GetValue(HideUpDownButtonsProperty); } set { this.SetValue(HideUpDownButtonsProperty, value); } } /// <summary>Identifies the <see cref="SwitchUpDownButtons"/> dependency property.</summary> public static readonly DependencyProperty SwitchUpDownButtonsProperty = NumericUpDown.SwitchUpDownButtonsProperty.AddOwner( typeof(DataGridNumericUpDownColumn), new FrameworkPropertyMetadata((bool)NumericUpDown.SwitchUpDownButtonsProperty.DefaultMetadata.DefaultValue, FrameworkPropertyMetadataOptions.Inherits, NotifyPropertyChangeForRefreshContent)); public bool SwitchUpDownButtons { get { return (bool)this.GetValue(SwitchUpDownButtonsProperty); } set { this.SetValue(SwitchUpDownButtonsProperty, value); } } /// <summary>Identifies the <see cref="ButtonsAlignment"/> dependency property.</summary> public static readonly DependencyProperty ButtonsAlignmentProperty = NumericUpDown.ButtonsAlignmentProperty.AddOwner( typeof(DataGridNumericUpDownColumn), new FrameworkPropertyMetadata((ButtonsAlignment)NumericUpDown.ButtonsAlignmentProperty.DefaultMetadata.DefaultValue, FrameworkPropertyMetadataOptions.Inherits, NotifyPropertyChangeForRefreshContent)); public ButtonsAlignment ButtonsAlignment { get { return (ButtonsAlignment)this.GetValue(ButtonsAlignmentProperty); } set { this.SetValue(ButtonsAlignmentProperty, value); } } /// <summary>Identifies the <see cref="UpDownButtonsWidth"/> dependency property.</summary> public static readonly DependencyProperty UpDownButtonsWidthProperty = NumericUpDown.UpDownButtonsWidthProperty.AddOwner( typeof(DataGridNumericUpDownColumn), new FrameworkPropertyMetadata((double)NumericUpDown.UpDownButtonsWidthProperty.DefaultMetadata.DefaultValue, FrameworkPropertyMetadataOptions.Inherits, NotifyPropertyChangeForRefreshContent)); public double UpDownButtonsWidth { get { return (double)this.GetValue(UpDownButtonsWidthProperty); } set { this.SetValue(UpDownButtonsWidthProperty, value); } } /// <summary>Identifies the <see cref="FontFamily"/> dependency property.</summary> public static readonly DependencyProperty FontFamilyProperty = TextElement.FontFamilyProperty.AddOwner( typeof(DataGridNumericUpDownColumn), new FrameworkPropertyMetadata(SystemFonts.MessageFontFamily, FrameworkPropertyMetadataOptions.Inherits, NotifyPropertyChangeForRefreshContent)); /// <summary> /// The font family of the desired font. /// </summary> public FontFamily FontFamily { get { return (FontFamily)this.GetValue(FontFamilyProperty); } set { this.SetValue(FontFamilyProperty, value); } } /// <summary>Identifies the <see cref="FontSize"/> dependency property.</summary> public static readonly DependencyProperty FontSizeProperty = TextElement.FontSizeProperty.AddOwner( typeof(DataGridNumericUpDownColumn), new FrameworkPropertyMetadata(SystemFonts.MessageFontSize, FrameworkPropertyMetadataOptions.Inherits, NotifyPropertyChangeForRefreshContent)); /// <summary> /// The size of the desired font. /// </summary> [TypeConverter(typeof(FontSizeConverter))] [Localizability(LocalizationCategory.None)] public double FontSize { get { return (double)this.GetValue(FontSizeProperty); } set { this.SetValue(FontSizeProperty, value); } } /// <summary>Identifies the <see cref="FontStyle"/> dependency property.</summary> public static readonly DependencyProperty FontStyleProperty = TextElement.FontStyleProperty.AddOwner( typeof(DataGridNumericUpDownColumn), new FrameworkPropertyMetadata(SystemFonts.MessageFontStyle, FrameworkPropertyMetadataOptions.Inherits, NotifyPropertyChangeForRefreshContent)); /// <summary> /// The style of the desired font. /// </summary> public FontStyle FontStyle { get { return (FontStyle)this.GetValue(FontStyleProperty); } set { this.SetValue(FontStyleProperty, value); } } /// <summary>Identifies the <see cref="FontWeight"/> dependency property.</summary> public static readonly DependencyProperty FontWeightProperty = TextElement.FontWeightProperty.AddOwner( typeof(DataGridNumericUpDownColumn), new FrameworkPropertyMetadata(SystemFonts.MessageFontWeight, FrameworkPropertyMetadataOptions.Inherits, NotifyPropertyChangeForRefreshContent)); /// <summary> /// The weight or thickness of the desired font. /// </summary> public FontWeight FontWeight { get { return (FontWeight)this.GetValue(FontWeightProperty); } set { this.SetValue(FontWeightProperty, value); } } /// <summary>Identifies the <see cref="Foreground"/> dependency property.</summary> public static readonly DependencyProperty ForegroundProperty = TextElement.ForegroundProperty.AddOwner( typeof(DataGridNumericUpDownColumn), new FrameworkPropertyMetadata(SystemColors.ControlTextBrush, FrameworkPropertyMetadataOptions.Inherits, NotifyPropertyChangeForRefreshContent)); /// <summary> /// An brush that describes the foreground color. This overrides the cell foreground inherited color. /// </summary> public Brush Foreground { get { return (Brush)this.GetValue(ForegroundProperty); } set { this.SetValue(ForegroundProperty, value); } } /// <summary> /// Method used as property changed callback for properties which need RefreshCellContent to be called /// </summary> private static void NotifyPropertyChangeForRefreshContent(DependencyObject d, DependencyPropertyChangedEventArgs e) { Debug.Assert(d is DataGridNumericUpDownColumn, "d should be a DataGridNumericUpDownColumn"); ((DataGridNumericUpDownColumn)d).NotifyPropertyChanged(e.Property.Name); } /// <summary> /// Rebuilds the contents of a cell in the column in response to a binding change. /// </summary> /// <param name="element">The cell to update.</param> /// <param name="propertyName">The name of the column property that has changed.</param> protected override void RefreshCellContent(FrameworkElement element, string propertyName) { var cell = element as DataGridCell; var numericUpDown = cell?.Content as NumericUpDown; if (numericUpDown != null) { switch (propertyName) { case nameof(this.FontFamily): SyncColumnProperty(this, numericUpDown, FontFamilyProperty, TextElement.FontFamilyProperty); break; case nameof(this.FontSize): SyncColumnProperty(this, numericUpDown, FontSizeProperty, TextElement.FontSizeProperty); break; case nameof(this.FontStyle): SyncColumnProperty(this, numericUpDown, FontStyleProperty, TextElement.FontStyleProperty); break; case nameof(this.FontWeight): SyncColumnProperty(this, numericUpDown, FontWeightProperty, TextElement.FontWeightProperty); break; case nameof(this.TextAlignment): SyncColumnProperty(this, numericUpDown, TextAlignmentProperty, NumericUpDown.TextAlignmentProperty); break; case nameof(this.StringFormat): SyncColumnProperty(this, numericUpDown, StringFormatProperty, NumericUpDown.StringFormatProperty); break; case nameof(this.Culture): SyncColumnProperty(this, numericUpDown, CultureProperty, NumericUpDown.CultureProperty); break; case nameof(this.Minimum): SyncColumnProperty(this, numericUpDown, MinimumProperty, NumericUpDown.MinimumProperty); break; case nameof(this.Maximum): SyncColumnProperty(this, numericUpDown, MaximumProperty, NumericUpDown.MaximumProperty); break; case nameof(this.NumericInputMode): SyncColumnProperty(this, numericUpDown, NumericInputModeProperty, NumericUpDown.NumericInputModeProperty); break; case nameof(this.DecimalPointCorrection): SyncColumnProperty(this, numericUpDown, DecimalPointCorrectionProperty, NumericUpDown.DecimalPointCorrectionProperty); break; case nameof(this.Interval): SyncColumnProperty(this, numericUpDown, IntervalProperty, NumericUpDown.IntervalProperty); break; case nameof(this.Delay): SyncColumnProperty(this, numericUpDown, DelayProperty, NumericUpDown.DelayProperty); break; case nameof(this.Speedup): SyncColumnProperty(this, numericUpDown, SpeedupProperty, NumericUpDown.SpeedupProperty); break; case nameof(this.SnapToMultipleOfInterval): SyncColumnProperty(this, numericUpDown, SnapToMultipleOfIntervalProperty, NumericUpDown.SnapToMultipleOfIntervalProperty); break; case nameof(this.InterceptArrowKeys): SyncColumnProperty(this, numericUpDown, InterceptArrowKeysProperty, NumericUpDown.InterceptArrowKeysProperty); break; case nameof(this.InterceptManualEnter): SyncColumnProperty(this, numericUpDown, InterceptManualEnterProperty, NumericUpDown.InterceptManualEnterProperty); break; case nameof(this.InterceptMouseWheel): SyncColumnProperty(this, numericUpDown, InterceptMouseWheelProperty, NumericUpDown.InterceptMouseWheelProperty); break; case nameof(this.TrackMouseWheelWhenMouseOver): SyncColumnProperty(this, numericUpDown, TrackMouseWheelWhenMouseOverProperty, NumericUpDown.TrackMouseWheelWhenMouseOverProperty); break; case nameof(this.HideUpDownButtons): SyncColumnProperty(this, numericUpDown, HideUpDownButtonsProperty, NumericUpDown.HideUpDownButtonsProperty); break; case nameof(this.SwitchUpDownButtons): SyncColumnProperty(this, numericUpDown, SwitchUpDownButtonsProperty, NumericUpDown.SwitchUpDownButtonsProperty); break; case nameof(this.ButtonsAlignment): SyncColumnProperty(this, numericUpDown, ButtonsAlignmentProperty, NumericUpDown.ButtonsAlignmentProperty); break; case nameof(this.UpDownButtonsWidth): SyncColumnProperty(this, numericUpDown, UpDownButtonsWidthProperty, NumericUpDown.UpDownButtonsWidthProperty); break; } } base.RefreshCellContent(element, propertyName); } } }
/* * AssemblyBuilder.cs - Implementation of the * "System.Reflection.Emit.AssemblyBuilder" class. * * Copyright (C) 2001, 2002 Southern Storm Software, Pty Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ namespace System.Reflection.Emit { #if CONFIG_REFLECTION_EMIT using System; using System.IO; using System.Collections; using System.Resources; using System.Reflection; using System.Security; using System.Security.Policy; using System.Security.Permissions; using System.Runtime.CompilerServices; using System.Threading; public sealed class AssemblyBuilder : Assembly { // Internal state. private AssemblyBuilderAccess access; private String directory; private bool isSynchronized; private bool saved; private MethodInfo entryPoint; private IntPtr writer; private ModuleBuilder module; private ArrayList detachList; private PEFileKinds fileKind; // Constructor. Called from AppDomain.DefineDynamicAssembly. internal AssemblyBuilder(AssemblyName name, AssemblyBuilderAccess access, String directory, bool isSynchronized) { this.access = access; this.directory = (directory == null) ? "." : directory; this.isSynchronized = isSynchronized; this.saved = false; this.entryPoint = null; this.detachList = new ArrayList(); fileKind = PEFileKinds.Dll; Version version = name.Version; lock(typeof(AssemblyBuilder)) { if(version != null) { this.privateData = ClrAssemblyCreate (name.Name, version.Major, version.Minor, version.Build, version.Revision, access, out writer); } else { this.privateData = ClrAssemblyCreate (name.Name, 0, 0, 0, 0, access, out writer); } } if(this.privateData == IntPtr.Zero) { // The runtime engine disallowed dynamic assemblies. throw new SecurityException (_("Emit_NoDynamicAssemblies")); } } // Start a synchronized operation on this assembly builder. internal void StartSync() { if(isSynchronized) { Monitor.Enter(this); } } // End a synchronized operation on this assembly builder. internal void EndSync() { if(isSynchronized) { Monitor.Exit(this); } } // Get the code base for this assembly builder. public override String CodeBase { get { throw new NotSupportedException(_("NotSupp_Builder")); } } // Get the location of the assembly manifest file. public override String Location { get { throw new NotSupportedException(_("NotSupp_Builder")); } } // Get the entry point for this assembly builder. public override MethodInfo EntryPoint { get { return entryPoint; } } // Get the runtime image version that will be embedded in the assembly. public override String ImageRuntimeVersion { get { // Our runtime engine versions are different from // Microsoft's, but we want to match things up. // Use a version number from one of Microsoft's // public release versions. return "v1.1.4322"; } } [TODO] public void AddResourceFile(String name, String fileName) { throw new NotImplementedException("AddResourceFile"); } [TODO] public void AddResourceFile(String name, String fileName, ResourceAttributes attribute) { throw new NotImplementedException("AddResourceFile"); } // Define a dynamic module that is attached to this assembly. public ModuleBuilder DefineDynamicModule(String name) { return DefineDynamicModule(name, false); } public ModuleBuilder DefineDynamicModule(String name, bool emitSymbolInfo) { try { StartSync(); if(saved) { throw new InvalidOperationException (_("Emit_AlreadySaved")); } if(name == null) { throw new ArgumentNullException("name"); } if(name == String.Empty) { throw new ArgumentException (_("Emit_ModuleNameInvalid")); } if(Char.IsWhiteSpace(name[0]) || name.IndexOf('/') != -1 || name.IndexOf('\\') != -1) { throw new ArgumentException (_("Emit_ModuleNameInvalid")); } if(module != null) { // We don't support assemblies with multiple modules. throw new NotSupportedException (_("Emit_SingleModuleOnly")); } module = new ModuleBuilder (this, name, true, emitSymbolInfo); return module; } finally { EndSync(); } } public ModuleBuilder DefineDynamicModule(String name, String fileName) { return DefineDynamicModule(name, fileName, false); } public ModuleBuilder DefineDynamicModule(String name, String fileName, bool emitSymbolInfo) { // We don't support modules in external files. return DefineDynamicModule(name, emitSymbolInfo); throw new NotSupportedException(_("Emit_ExternalModule")); } [TODO] public IResourceWriter DefineResource(String name, String description, String fileName) { throw new NotImplementedException("DefineResource"); } [TODO] public IResourceWriter DefineResource(String name, String description, String fileName, ResourceAttributes attribute) { throw new NotImplementedException("DefineResource"); } [TODO] public void DefineUnmanagedResource(byte[] resource) { throw new NotImplementedException("DefineUnmanagedResource"); } [TODO] public void DefineUnmanagedResource(String resourceFileName) { throw new NotImplementedException("DefineUnmanagedResource"); } [TODO] public void DefineVersionInfoResource() { // We already added a 0.0.0.0 version info resource //throw new NotImplementedException("DefineVersionInfoResource"); } [TODO] public void DefineVersionInfoResource(String product, String productVersion ,String company, String copyright, String trademark) { throw new NotImplementedException("DefineVersionInfoResource"); } // Get a particular module within this assembly. public ModuleBuilder GetDynamicModule(String name) { if(name == null) { throw new ArgumentNullException("name"); } else if(name == String.Empty) { throw new ArgumentException (_("Emit_ModuleNameInvalid")); } if(module != null && module.Name == name) { return module; } else { return null; } } [TODO] public override Type[] GetExportedTypes() { throw new NotImplementedException("GetExportedTypes"); } [TODO] public override FileStream GetFile(String name) { throw new NotImplementedException("GetFile"); } [TODO] public override FileStream[] GetFiles(bool getResourceModules) { throw new NotImplementedException("GetFiles"); } // Get information about a particular manifest resource. [TODO] public override ManifestResourceInfo GetManifestResourceInfo(String resourceName) { throw new NotImplementedException("GetManifestResourceInfo"); } // Get the names of all manifest resources in this assembly. public override String[] GetManifestResourceNames() { throw new NotImplementedException("GetManifestResourceNames"); } // Get a stream for a particular manifest resource. [TODO] public override Stream GetManifestResourceStream(String name) { throw new NotImplementedException("GetManifestResourceNames"); } // Get a stream for a particular manifest resource, scoped by a type. [TODO] public override Stream GetManifestResourceStream(Type type, String name) { throw new NotImplementedException("GetManifestResourceStream"); } [TODO] public void Save(String assemblyFileName) { if (assemblyFileName == null) { throw new ArgumentNullException(/* TODO */); } if (assemblyFileName.Length == 0) { throw new ArgumentException(/* TODO */); } if (saved || (access & AssemblyBuilderAccess.Save) == 0) { throw new InvalidOperationException(/* TODO */); } directory = Path.GetFullPath(directory); if (!Directory.Exists(directory)) { throw new ArgumentException(/* TODO */); } String path = Path.Combine(directory, assemblyFileName); /* TODO: the rest of the exception throwing checks */ IntPtr entry = IntPtr.Zero; if (entryPoint != null) { entry = ((IClrProgramItem)entryPoint).ClrHandle; } if (!(ClrSave(base.privateData, writer, path, entry, fileKind))) { throw new IOException(/* TODO */); } saved = true; } // Set a custom attribute on this assembly. public void SetCustomAttribute(CustomAttributeBuilder customBuilder) { try { StartSync(); if(saved) { throw new InvalidOperationException (_("Emit_AlreadySaved")); } SetCustomAttribute(this, customBuilder); } finally { EndSync(); } } public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute) { try { StartSync(); if(saved) { throw new InvalidOperationException (_("Emit_AlreadySaved")); } SetCustomAttribute(this, con, binaryAttribute); } finally { EndSync(); } } // Set the entry point for this assembly builder. public void SetEntryPoint(MethodInfo entryMethod) { SetEntryPoint(entryMethod, PEFileKinds.ConsoleApplication); } public void SetEntryPoint(MethodInfo entryMethod, PEFileKinds fileKind) { if(entryMethod == null) { throw new ArgumentNullException("entryMethod"); } if(entryMethod.DeclaringType.Assembly != this) { throw new InvalidOperationException (_("Invalid_EntryNotInAssembly")); } entryPoint = entryMethod; this.fileKind = fileKind; } // SetCustomAttribute(): // All other XXXBuilder classes invoke call the public method // AssemblyBuilder.SetCustomAttribute(), which invokes one of the // internal SetCustomAttribute() methods that follow. // Set custom attributes on a program item in this assembly. internal void SetCustomAttribute (IClrProgramItem item, CustomAttributeBuilder customBuilder) { byte[] blob = customBuilder.ToBytes(); IntPtr attribute = ClrAttributeCreate (base.privateData, ((IClrProgramItem)(customBuilder.con)).ClrHandle, blob); ClrAttributeAddToItem(item.ClrHandle, attribute); } [TODO] internal void SetCustomAttribute (IClrProgramItem item, ConstructorInfo con, byte[] binaryAttribute) { throw new NotImplementedException("SetCustomAttribute"); } // Add declarative security to a program item in this assembly. [TODO] internal void AddDeclarativeSecurity(IClrProgramItem item, SecurityAction action, PermissionSet pset) { throw new NotImplementedException("AddDeclarativeSecurity"); } // Add an item to this assembly's detach list. internal void AddDetach(IDetachItem item) { lock(typeof(AssemblyBuilder)) { detachList.Add(item); } } // Detach everything used by this assembly, which ensures that // all pointers to native structures are invalidated. private void Detach() { lock(typeof(AssemblyBuilder)) { foreach(IDetachItem item in detachList) { item.Detach(); } privateData = IntPtr.Zero; } } // Write the method IL to the output. internal int WriteMethod(byte[] header, byte[] code, IntPtr[] codeFixupPtrs, int[] codeFixupOffsets, byte[][] exceptionBlocks, IntPtr[] exceptionBlockFixupPtrs, int[] exceptionBlockFixupOffsets) { return ClrWriteMethod(privateData, writer, header, code, codeFixupPtrs, codeFixupOffsets, exceptionBlocks, exceptionBlockFixupPtrs, exceptionBlockFixupOffsets); } // Create a new assembly. [MethodImpl(MethodImplOptions.InternalCall)] extern private static IntPtr ClrAssemblyCreate (String name, int v1, int v2, int v3, int v4, AssemblyBuilderAccess access, out IntPtr writer); // Save the assembly to a file. [MethodImpl(MethodImplOptions.InternalCall)] extern private static bool ClrSave(IntPtr assembly, IntPtr writer, String path, IntPtr entryMethod, PEFileKinds fileKind /*, TODO */); // Get the token associated with a particular program item. [MethodImpl(MethodImplOptions.InternalCall)] extern internal static int ClrGetItemToken(IntPtr item); // Get the program item associated with a particular token. [MethodImpl(MethodImplOptions.InternalCall)] extern internal static IntPtr ClrGetItemFromToken (IntPtr assembly, int token); // Write the body of a method to the code section and return the RVA // that corresponds to it. [MethodImpl(MethodImplOptions.InternalCall)] extern private static int ClrWriteMethod(IntPtr assembly, IntPtr writer, byte[] header, byte[] code, IntPtr[] codeFixupPtrs, int[] codeFixupOffsets, byte[][] exceptionBlocks, IntPtr[] exceptionBlockFixupPtrs, int[] exceptionBlockFixupOffsets); // Add a new attribute to an assembly image. [MethodImpl(MethodImplOptions.InternalCall)] extern private static IntPtr ClrAttributeCreate (IntPtr assembly, IntPtr ctor, byte[] blob); // Add an attribute to a program item and convert special attributes. [MethodImpl(MethodImplOptions.InternalCall)] extern private static void ClrAttributeAddToItem (IntPtr item, IntPtr attribute); }; // class AssemblyBuilder #endif // CONFIG_REFLECTION_EMIT }; // namespace System.Reflection.Emit
//Tic-Tac-Toe //Coded By: Kristina Powell (circa May 2015) //Warning: The code is disgustingly ugly and not optimized...but the game works... //...as long as you follow the directions...uhhh....awkward using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Mystery { class Program { static void Main(string[] args) { #region Variable Declaration char topLeft = ' ' ,topCenter = ' ', topRight = ' ', left = ' ', center = ' ', right = ' ', bottomLeft = ' ', bottomCenter = ' ', bottomRight = ' '; char responseChar; int escape = 0; string ticTacToeBoard; #endregion #region Tic-Tac-Toe Board ticTacToeBoard = "\n | | \n "+ topLeft +" | "+ topCenter +" | "+ topRight +" \n _____|_____|_____\n | | \n "+ left +" | "+ center +" | "+ right +" \n _____|_____|_____\n | | \n "+ bottomLeft +" | "+ bottomCenter +" | "+ bottomRight +" \n | |\n"; #endregion #region Beginning Sequence (Key or Start Game) Console.WriteLine("\n Tic-Tac-Toe!\n (2 Player)\n" + ticTacToeBoard); Console.Write("Would you like to display the key? (y or n) "); responseChar = char.ToLower(Convert.ToChar(Console.ReadLine()[0])); if (responseChar == 'y') PositionKey(ref topLeft, ref topCenter, ref topRight, ref left, ref center, ref right, ref bottomLeft, ref bottomCenter, ref bottomRight, ref escape, ref responseChar); else Game(ref topLeft, ref topCenter, ref topRight, ref left, ref center, ref right, ref bottomLeft, ref bottomCenter, ref bottomRight, ref escape, ref responseChar); #endregion } #region Position Key static void PositionKey(ref char topLeft, ref char topCenter, ref char topRight, ref char left, ref char center, ref char right, ref char bottomLeft, ref char bottomCenter, ref char bottomRight, ref int escape, ref char responseChar) { Console.WriteLine("\nNote: These will be the keywords when entering a move.\nType the word help when prompted during move selection to see the key."); Console.WriteLine("\nIn order (L to R): topLeft, topCenter, topRight,\n left, center, right,\n bottomLeft, bottomCenter, bottomRight."); Game(ref topLeft, ref topCenter, ref topRight, ref left, ref center, ref right, ref bottomLeft, ref bottomCenter, ref bottomRight, ref escape, ref responseChar); } #endregion #region Check Sequence static void CheckSequence(ref char topLeft, ref char topCenter, ref char topRight, ref char left, ref char center, ref char right, ref char bottomLeft, ref char bottomCenter, ref char bottomRight, ref char player1Char, ref char player2Char, ref string player1Name, ref string player2Name, ref int escape, ref int round, ref string ticTacToeBoard, ref char responseChar, ref string moveSelection) { int player1Win = 0, player2Win = 0; if (round == 9) { if (player1Win != 1 && player2Win != 1) { Console.WriteLine("This game was a tie."); escape = 1; player1Win = 0; player2Win = 0; } } if (round > 4) { if (((topLeft == topCenter && topCenter == topRight) || (left == center && center == right) || (bottomLeft == bottomCenter && bottomCenter == topCenter) || (topLeft == left && left == bottomLeft) || (topCenter == center && center == bottomCenter) || (topRight == right && right == bottomRight) || (topLeft == center && center == bottomRight) || (topRight == center && center == bottomLeft))) { ticTacToeBoard = "\n | | \n " + topLeft + " | " + topCenter + " | " + topRight + " \n _____|_____|_____\n | | \n " + left + " | " + center + " | " + right + " \n _____|_____|_____\n | | \n " + bottomLeft + " | " + bottomCenter + " | " + bottomRight + " \n | |\n"; #region Player 1 Win Conditions if ((topLeft == player1Char && topCenter == player1Char && topRight == player1Char) || (left == player1Char && center == player1Char && right == player1Char) || (bottomLeft == player1Char && bottomCenter == player1Char && topCenter == player1Char) || (topLeft == player1Char && left == player1Char && bottomLeft == player1Char) || (topCenter == player1Char && center == player1Char && bottomCenter == player1Char) || (topRight == player1Char && right == player1Char && bottomRight == player1Char) || (topLeft == player1Char && center == player1Char && bottomRight == player1Char) || (topRight == player1Char && center == player1Char && bottomLeft == player1Char)) { Console.WriteLine("{0} has won this round.", player1Name); player1Win = 1; escape = 1; } #endregion #region Player 2 Win Conditions if ((topLeft == player2Char && topCenter == player2Char && topRight == player2Char) || (left == player2Char && center == player2Char && right == player2Char) || (bottomLeft == player2Char && bottomCenter == player2Char && topCenter == player2Char) || (topLeft == player2Char && left == player2Char && bottomLeft == player2Char) || (topCenter == player2Char && center == player2Char && bottomCenter == player2Char) || (topRight == player2Char && right == player2Char && bottomRight == player2Char) || (topLeft == player2Char && center == player2Char && bottomRight == player2Char) || (topRight == player2Char && center == player2Char && bottomLeft == player2Char)) { Console.WriteLine("{0} has won this round.", player2Name); player2Win = 1; escape = 1; } #endregion } } } #endregion #region Game Loop static void Game(ref char topLeft, ref char topCenter, ref char topRight, ref char left, ref char center, ref char right, ref char bottomLeft, ref char bottomCenter, ref char bottomRight, ref int escape, ref char responseChar) { #region Variable Declaration string player1Name, player2Name, moveSelection = " "; int round = 1, game = 1; char player1Char, player2Char; string ticTacToeBoard; #endregion #region Tic-Tac-Toe Board ticTacToeBoard = "\n | | \n " + topLeft + " | " + topCenter + " | " + topRight + " \n _____|_____|_____\n | | \n " + left + " | " + center + " | " + right + " \n _____|_____|_____\n | | \n " + bottomLeft + " | " + bottomCenter + " | " + bottomRight + " \n | |\n"; #endregion #region Player Setup Console.Write("\nPlease type a name for Player 1: "); player1Name = Console.ReadLine(); Console.Write("\nPlease type a character piece for {0} (ex: X, O, etc.) ", player1Name); player1Char = Convert.ToChar(Console.ReadLine()[0]); Console.Write("\nPlease type a name for Player 2: "); player2Name = Console.ReadLine(); Console.Write("\nPlease type a character piece for {0} (ex: X, O, etc.) ", player2Name); player2Char = Convert.ToChar(Console.ReadLine()[0]); #endregion #region Main Loop: False Escape while (escape == 0 || topLeft != ' ' && topCenter != ' ' && topRight != ' ' && left != ' ' && center != ' ' && right != ' ' && bottomLeft != ' ' && bottomCenter != ' ' && bottomRight != ' ' || round < 9) { #region Round 1 if (round == 1) { ticTacToeBoard = "\n | | \n | | \n _____|_____|_____\n | | \n | | \n _____|_____|_____\n | | \n | | \n | |\n"; Console.WriteLine(ticTacToeBoard); } #endregion #region If Player 1's Turn... if ((round+2)%2 == 1) { #region Move Selection Console.WriteLine("{0}, please select a move.", player1Name); moveSelection = Console.ReadLine(); moveSelection = moveSelection.ToLower(); #endregion #region Help Screen if (moveSelection == "help") { PositionKey(ref topLeft, ref topCenter, ref topRight, ref left, ref center, ref right, ref bottomLeft, ref bottomCenter, ref bottomRight, ref escape, ref responseChar); Console.WriteLine("{0}, please select a move.", player1Name); moveSelection = Console.ReadLine(); moveSelection = moveSelection.ToLower(); #endregion #region Space Check if (((moveSelection == "topleft" || moveSelection == "top left" || moveSelection == "tl" || moveSelection == "t l") && topLeft != ' ') || ((moveSelection == "topcenter" || moveSelection == "top center" || moveSelection == "tc" || moveSelection == "t c") && topCenter != ' ') || ((moveSelection == "topright" || moveSelection == "top right" || moveSelection == "tr" || moveSelection == "t r") && topRight != ' ') || ((moveSelection == "left" || moveSelection == "l") && left != ' ') || ((moveSelection == "center" || moveSelection == "c")&& center != ' ') || ((moveSelection == "right" || moveSelection == "r")&& right != ' ') || ((moveSelection == "bottomleft" || moveSelection == "bottom left" || moveSelection == "bl" || moveSelection == "b l") && bottomLeft != ' ') || ((moveSelection == "bottomcenter" || moveSelection == "bottom center" || moveSelection == "bc" || moveSelection == "b c") && bottomCenter != ' ') || ((moveSelection == "bottomright" || moveSelection == "bottom right" || moveSelection == "br" || moveSelection == "b r") && bottomRight != ' ')) { Console.WriteLine("This space has already been played on"); moveSelection = Console.ReadLine(); moveSelection = moveSelection.ToLower(); } #endregion } #region Move Declaration if (moveSelection == "topleft" || moveSelection == "top left" || moveSelection == "tl" || moveSelection == "t l") topLeft = player1Char; if (moveSelection == "topcenter" || moveSelection == "top center" || moveSelection == "tc" || moveSelection == "t c") topCenter = player1Char; if (moveSelection == "topright" || moveSelection == "top right" || moveSelection == "tr" || moveSelection == "t r") topRight = player1Char; if (moveSelection == "left" || moveSelection == "l") left = player1Char; if (moveSelection == "center" || moveSelection == "c") center = player1Char; if (moveSelection == "right" || moveSelection == "r") right = player1Char; if (moveSelection == "bottomleft" || moveSelection == "bottom left" || moveSelection == "bl" || moveSelection == "b l") bottomLeft = player1Char; if (moveSelection == "bottomcenter" || moveSelection == "bottom center" || moveSelection == "bc" || moveSelection == "b c") bottomCenter = player1Char; if (moveSelection == "bottomright" || moveSelection == "bottom right" || moveSelection == "br" || moveSelection == "b r") bottomRight = player1Char; #endregion } #endregion #region If Player 2's Turn... if ((round + 2) % 2 == 0) { #region Move Selection Console.WriteLine("{0}, please select a move.", player2Name); moveSelection = Console.ReadLine(); moveSelection = moveSelection.ToLower(); #endregion #region Help Screen if (moveSelection == "help") { PositionKey(ref topLeft, ref topCenter, ref topRight, ref left, ref center, ref right, ref bottomLeft, ref bottomCenter, ref bottomRight, ref escape, ref responseChar); Console.WriteLine("{0}, please select a move.", player2Name); moveSelection = Console.ReadLine(); moveSelection = moveSelection.ToLower(); #endregion #region Space Check if (((moveSelection == "topleft" || moveSelection == "top left" || moveSelection == "tl" || moveSelection == "t l") && topLeft != ' ') || ((moveSelection == "topcenter" || moveSelection == "top center" || moveSelection == "tc" || moveSelection == "t c") && topCenter != ' ') || ((moveSelection == "topright" || moveSelection == "top right" || moveSelection == "tr" || moveSelection == "t r") && topRight != ' ') || ((moveSelection == "left" || moveSelection == "l") && left != ' ') || ((moveSelection == "center" || moveSelection == "c") && center != ' ') || ((moveSelection == "right" || moveSelection == "r") && right != ' ') || ((moveSelection == "bottomleft" || moveSelection == "bottom left" || moveSelection == "bl" || moveSelection == "b l") && bottomLeft != ' ') || ((moveSelection == "bottomcenter" || moveSelection == "bottom center" || moveSelection == "bc" || moveSelection == "b c") && bottomCenter != ' ') || ((moveSelection == "bottomright" || moveSelection == "bottom right" || moveSelection == "br" || moveSelection == "b r") && bottomRight != ' ')) { Console.WriteLine("This space has already been played on"); moveSelection = Console.ReadLine(); moveSelection = moveSelection.ToLower(); } #endregion } #region Move Declaration if (moveSelection == "topleft" || moveSelection == "top left" || moveSelection == "tl" || moveSelection == "t l") topLeft = player2Char; if (moveSelection == "topcenter" || moveSelection == "top center" || moveSelection == "tc" || moveSelection == "t c") topCenter = player2Char; if (moveSelection == "topright" || moveSelection == "top right" || moveSelection == "tr" || moveSelection == "t r") topRight = player2Char; if (moveSelection == "left" || moveSelection == "l") left = player2Char; if (moveSelection == "center" || moveSelection == "c") center = player2Char; if (moveSelection == "right" || moveSelection == "r") right = player2Char; if (moveSelection == "bottomleft" || moveSelection == "bottom left" || moveSelection == "bl" || moveSelection == "b l") bottomLeft = player2Char; if (moveSelection == "bottomcenter" || moveSelection == "bottom center" || moveSelection == "bc" || moveSelection == "b c") bottomCenter = player2Char; if (moveSelection == "bottomright" || moveSelection == "bottom right" || moveSelection == "br" || moveSelection == "b r") bottomRight = player2Char; #endregion } #endregion #region Updated Tic-Tac-Toe Board ticTacToeBoard = "\n | | \n " + topLeft + " | " + topCenter + " | " + topRight + " \n _____|_____|_____\n | | \n " + left + " | " + center + " | " + right + " \n _____|_____|_____\n | | \n " + bottomLeft + " | " + bottomCenter + " | " + bottomRight + " \n | |\n"; Console.WriteLine(ticTacToeBoard); #endregion #region Run Check Sequence CheckSequence(ref topLeft, ref topCenter, ref topRight, ref left, ref center, ref right, ref bottomLeft, ref bottomCenter, ref bottomRight, ref player1Char, ref player2Char, ref player1Name, ref player2Name, ref escape, ref round, ref ticTacToeBoard, ref responseChar, ref moveSelection); round++; #endregion #region Sub-Loop: True Escape while (escape == 1) { Console.Write("Would you like to play again? (y or n) "); responseChar = char.ToLower(Convert.ToChar(Console.ReadLine())); if (responseChar == 'y') { Reset(ref round, ref topLeft, ref topCenter, ref topRight, ref left, ref center, ref right, ref bottomLeft, ref bottomCenter, ref bottomRight, ref escape, ref responseChar, ref moveSelection, ref player1Name, ref player2Name, ref player1Char, ref player2Char); round = 1; game++; } else { escape = 2; } } #endregion } #endregion } #endregion #region Reset Sequence static void Reset(ref int round, ref char topLeft, ref char topCenter, ref char topRight, ref char left, ref char center, ref char right, ref char bottomLeft, ref char bottomCenter, ref char bottomRight, ref int escape, ref char responseChar, ref string moveSelection, ref string player1Name, ref string player2Name, ref char player1Char, ref char player2Char) { #region Reset round = 1; topLeft = ' '; topCenter = ' '; topRight = ' '; left = ' '; center = ' '; right = ' '; bottomLeft = ' '; bottomCenter = ' '; bottomRight = ' '; moveSelection = player1Name; player1Name = player2Name; player2Name = moveSelection; responseChar = player1Char; player1Char = player2Char; player2Char = responseChar; Console.WriteLine("Player 1 is now {0} and Player 2 is now {1}. The turn order has changed.", player1Name, player2Name); escape = 0; #endregion } #endregion } }
using Jose; using NUnit.Framework; namespace UnitTests { [TestFixture] public class AesKeyWrapTest { [Test] public void Wrap_128Key_128Kek() { //given (Section 4.1) //000102030405060708090A0B0C0D0E0F byte[] kek = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15}; //00112233445566778899AABBCCDDEEFF byte[] key = {0,17,34,51,68,85,102,119,136,153,170,187,204,221,238,255}; //1FA68B0A8112B447AEF34BD8FB5A7B829D3E862371D2CFE5 byte[] expected = { 31, 166, 139, 10, 129, 18, 180, 71, 174, 243, 75, 216, 251, 90, 123, 130, 157, 62, 134,35, 113, 210, 207, 229}; //when byte[] test = AesKeyWrap.Wrap(key, kek); //then Assert.That(test,Is.EqualTo(expected)); } [Test] public void Unwrap_128key_128kek() { //given (Section 4.1) //000102030405060708090A0B0C0D0E0F byte[] kek = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }; //00112233445566778899AABBCCDDEEFF byte[] expected = { 0, 17, 34, 51, 68, 85, 102, 119, 136, 153, 170, 187, 204, 221, 238, 255 }; //1FA68B0A8112B447AEF34BD8FB5A7B829D3E862371D2CFE5 byte[] key = { 31, 166, 139, 10, 129, 18, 180, 71, 174, 243, 75, 216, 251, 90, 123, 130, 157, 62, 134, 35, 113, 210, 207, 229 }; //when byte[] test = AesKeyWrap.Unwrap(key, kek); //then Assert.That(test, Is.EqualTo(expected)); } [Test] public void Wrap_128Key_192Kek() { //given (Section 4.2) //000102030405060708090A0B0C0D0E0F1011121314151617 byte[] kek = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23 }; //00112233445566778899AABBCCDDEEFF byte[] key = { 0, 17, 34, 51, 68, 85, 102, 119, 136, 153, 170, 187, 204, 221, 238, 255 }; //96778B25AE6CA435F92B5B97C050AED2468AB8A17AD84E5D byte[] expected = { 150, 119, 139, 37, 174, 108, 164, 53, 249, 43, 91, 151, 192, 80, 174, 210, 70, 138, 184, 161, 122, 216, 78, 93 }; //when byte[] test = AesKeyWrap.Wrap(key, kek); //then Assert.That(test,Is.EqualTo(expected)); } [Test] public void Unwrap_128Key_192Kek() { //given (Section 4.2) //000102030405060708090A0B0C0D0E0F1011121314151617 byte[] kek = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23 }; //00112233445566778899AABBCCDDEEFF byte[] expected = { 0, 17, 34, 51, 68, 85, 102, 119, 136, 153, 170, 187, 204, 221, 238, 255 }; //96778B25AE6CA435F92B5B97C050AED2468AB8A17AD84E5D byte[] key = { 150, 119, 139, 37, 174, 108, 164, 53, 249, 43, 91, 151, 192, 80, 174, 210, 70, 138, 184, 161, 122, 216, 78, 93 }; //when byte[] test = AesKeyWrap.Unwrap(key, kek); //then Assert.That(test,Is.EqualTo(expected)); } [Test] public void Wrap_128Key_256Kek() { //given (Section 4.3) //000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F byte[] kek = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31 }; //00112233445566778899AABBCCDDEEFF byte[] key = { 0, 17, 34, 51, 68, 85, 102, 119, 136, 153, 170, 187, 204, 221, 238, 255 }; //64E8C3F9CE0F5BA263E9777905818A2A93C8191E7D6E8AE7 byte[] expected = { 100, 232, 195, 249, 206, 15, 91, 162, 99, 233, 119, 121, 5, 129, 138, 42, 147, 200, 25, 30, 125, 110, 138, 231 }; //when byte[] test = AesKeyWrap.Wrap(key, kek); //then Assert.That(test,Is.EqualTo(expected)); } [Test] public void Unwrap_128Key_256Kek() { //given (Section 4.3) //000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F byte[] kek = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31 }; //00112233445566778899AABBCCDDEEFF byte[] expected = { 0, 17, 34, 51, 68, 85, 102, 119, 136, 153, 170, 187, 204, 221, 238, 255 }; //64E8C3F9CE0F5BA263E9777905818A2A93C8191E7D6E8AE7 byte[] key = { 100, 232, 195, 249, 206, 15, 91, 162, 99, 233, 119, 121, 5, 129, 138, 42, 147, 200, 25, 30, 125, 110, 138, 231 }; //when byte[] test = AesKeyWrap.Unwrap(key, kek); //then Assert.That(test,Is.EqualTo(expected)); } [Test] public void Wrap_192Key_192Kek() { //given (Section 4.4) //000102030405060708090A0B0C0D0E0F1011121314151617 byte[] kek = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23 }; //00112233445566778899AABBCCDDEEFF0001020304050607 byte[] key = { 0, 17, 34, 51, 68, 85, 102, 119, 136, 153, 170, 187, 204, 221, 238, 255, 0, 1, 2, 3, 4, 5, 6, 7 }; //031D33264E15D33268F24EC260743EDCE1C6C7DDEE725A936BA814915C6762D2 byte[] expected = { 3, 29, 51, 38, 78, 21, 211, 50, 104, 242, 78, 194, 96, 116, 62, 220, 225, 198, 199, 221, 238, 114, 90, 147, 107, 168, 20, 145, 92, 103, 98, 210 }; //when byte[] test = AesKeyWrap.Wrap(key, kek); //then Assert.That(test,Is.EqualTo(expected)); } [Test] public void UnWwrap_192Key_192Kek() { //given (Section 4.4) //000102030405060708090A0B0C0D0E0F1011121314151617 byte[] kek = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23 }; //00112233445566778899AABBCCDDEEFF0001020304050607 byte[] expected = { 0, 17, 34, 51, 68, 85, 102, 119, 136, 153, 170, 187, 204, 221, 238, 255, 0, 1, 2, 3, 4, 5, 6, 7 }; //031D33264E15D33268F24EC260743EDCE1C6C7DDEE725A936BA814915C6762D2 byte[] key = { 3, 29, 51, 38, 78, 21, 211, 50, 104, 242, 78, 194, 96, 116, 62, 220, 225, 198, 199, 221, 238, 114, 90, 147, 107, 168, 20, 145, 92, 103, 98, 210 }; //when byte[] test = AesKeyWrap.Unwrap(key, kek); //then Assert.That(test,Is.EqualTo(expected)); } [Test] public void Wrap_192Key_256Kek() { //given (Section 4.5) //000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F byte[] kek = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31 }; //00112233445566778899AABBCCDDEEFF0001020304050607 byte[] key = { 0, 17, 34, 51, 68, 85, 102, 119, 136, 153, 170, 187, 204, 221, 238, 255, 0, 1, 2, 3, 4, 5, 6, 7 }; //A8F9BC1612C68B3FF6E6F4FBE30E71E4769C8B80A32CB8958CD5D17D6B254DA1 byte[] expected = { 168, 249, 188, 22, 18, 198, 139, 63, 246, 230, 244, 251, 227, 14, 113, 228, 118, 156, 139, 128, 163, 44, 184, 149, 140, 213, 209, 125, 107, 37, 77, 161 }; //when byte[] test = AesKeyWrap.Wrap(key, kek); //then Assert.That(test,Is.EqualTo(expected)); } [Test] public void Unwrap_192Key_256Kek() { //given (Section 4.5) //000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F byte[] kek = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31 }; //00112233445566778899AABBCCDDEEFF0001020304050607 byte[] expected = { 0, 17, 34, 51, 68, 85, 102, 119, 136, 153, 170, 187, 204, 221, 238, 255, 0, 1, 2, 3, 4, 5, 6, 7 }; //A8F9BC1612C68B3FF6E6F4FBE30E71E4769C8B80A32CB8958CD5D17D6B254DA1 byte[] key = { 168, 249, 188, 22, 18, 198, 139, 63, 246, 230, 244, 251, 227, 14, 113, 228, 118, 156, 139, 128, 163, 44, 184, 149, 140, 213, 209, 125, 107, 37, 77, 161 }; //when byte[] test = AesKeyWrap.Unwrap(key, kek); //then Assert.That(test,Is.EqualTo(expected)); } [Test] public void Wrap_256Key_256Kek() { //given (Section 4.6) //000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F byte[] kek = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31 }; //00112233445566778899AABBCCDDEEFF000102030405060708090A0B0C0D0E0F byte[] key = { 0, 17, 34, 51, 68, 85, 102, 119, 136, 153, 170, 187, 204, 221, 238, 255, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }; //28C9F404C4B810F4CBCCB35CFB87F8263F5786E2D80ED326CBC7F0E71A99F43BFB988B9B7A02DD21 byte[] expected = { 40, 201, 244, 4, 196, 184, 16, 244, 203, 204, 179, 92, 251, 135, 248, 38, 63, 87, 134, 226, 216, 14, 211, 38, 203, 199, 240, 231, 26, 153, 244, 59, 251, 152, 139, 155, 122, 2, 221, 33 }; //when byte[] test = AesKeyWrap.Wrap(key, kek); //then Assert.That(test,Is.EqualTo(expected)); } [Test] public void Unwrap_256Key_256Kek() { //given (Section 4.6) //000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F byte[] kek = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31 }; //00112233445566778899AABBCCDDEEFF000102030405060708090A0B0C0D0E0F byte[] expected = { 0, 17, 34, 51, 68, 85, 102, 119, 136, 153, 170, 187, 204, 221, 238, 255, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }; //28C9F404C4B810F4CBCCB35CFB87F8263F5786E2D80ED326CBC7F0E71A99F43BFB988B9B7A02DD21 byte[] key = { 40, 201, 244, 4, 196, 184, 16, 244, 203, 204, 179, 92, 251, 135, 248, 38, 63, 87, 134, 226, 216, 14, 211, 38, 203, 199, 240, 231, 26, 153, 244, 59, 251, 152, 139, 155, 122, 2, 221, 33 }; //when byte[] test = AesKeyWrap.Unwrap(key, kek); //then Assert.That(test,Is.EqualTo(expected)); } } }
/* * Copyright (c) InWorldz Halcyon Developers * Copyright (c) Contributors, http://opensimulator.org/ * * 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 OpenSim 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.IO.Compression; using System.Reflection; using System.Xml; using log4net; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Serialization; using OpenSim.Framework.Serialization.External; using OpenSim.Framework.Communications; using OpenSim.Framework.Communications.Cache; using OpenSim.Framework.Communications.Osp; using OpenSim.Region.CoreModules.World.Archiver; using OpenSim.Region.Framework.Scenes; namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver { public class InventoryArchiveWriteRequest { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); /// <value> /// Used to select all inventory nodes in a folder but not the folder itself /// </value> private const string STAR_WILDCARD = "*"; private InventoryArchiverModule m_module; private CachedUserInfo m_userInfo; private string m_invPath; protected TarArchiveWriter m_archiveWriter; protected UuidGatherer m_assetGatherer; /// <value> /// Used to collect the uuids of the assets that we need to save into the archive /// </value> protected Dictionary<UUID, int> m_assetUuids = new Dictionary<UUID, int>(); /// <value> /// Used to collect the uuids of the users that we need to save into the archive /// </value> protected Dictionary<UUID, int> m_userUuids = new Dictionary<UUID, int>(); /// <value> /// The stream to which the inventory archive will be saved. /// </value> private Stream m_saveStream; /// <summary> /// Constructor /// </summary> public InventoryArchiveWriteRequest( InventoryArchiverModule module, CachedUserInfo userInfo, string invPath, string savePath) : this( module, userInfo, invPath, new GZipStream(new FileStream(savePath, FileMode.Create), CompressionMode.Compress)) { } /// <summary> /// Constructor /// </summary> public InventoryArchiveWriteRequest( InventoryArchiverModule module, CachedUserInfo userInfo, string invPath, Stream saveStream) { m_module = module; m_userInfo = userInfo; m_invPath = invPath; m_saveStream = saveStream; m_assetGatherer = new UuidGatherer(m_module.CommsManager.AssetCache); } protected void ReceivedAllAssets(ICollection<UUID> assetsFoundUuids, ICollection<UUID> assetsNotFoundUuids) { Exception reportedException = null; bool succeeded = true; try { m_archiveWriter.Close(); } catch (IOException e) { m_saveStream.Close(); reportedException = e; succeeded = false; } m_module.TriggerInventoryArchiveSaved(succeeded, m_userInfo, m_invPath, m_saveStream, reportedException); } protected void SaveInvItem(InventoryItemBase inventoryItem, string path) { string filename = string.Format("{0}{1}_{2}.xml", path, inventoryItem.Name, inventoryItem.ID); // Record the creator of this item for user record purposes (which might go away soon) m_userUuids[inventoryItem.CreatorIdAsUuid] = 1; InventoryItemBase saveItem = (InventoryItemBase)inventoryItem.Clone(); saveItem.CreatorId = OspResolver.MakeOspa(saveItem.CreatorIdAsUuid, m_module.CommsManager); string serialization = UserInventoryItemSerializer.Serialize(saveItem); m_archiveWriter.WriteFile(filename, serialization); m_assetGatherer.GatherAssetUuids(saveItem.AssetID, (AssetType)saveItem.AssetType, m_assetUuids); } /// <summary> /// Save an inventory folder /// </summary> /// <param name="inventoryFolder">The inventory folder to save</param> /// <param name="path">The path to which the folder should be saved</param> /// <param name="saveThisFolderItself">If true, save this folder itself. If false, only saves contents</param> protected void SaveInvFolder(InventoryFolderImpl inventoryFolder, string path, bool saveThisFolderItself) { if (saveThisFolderItself) { path += string.Format( "{0}{1}{2}/", inventoryFolder.Name, ArchiveConstants.INVENTORY_NODE_NAME_COMPONENT_SEPARATOR, inventoryFolder.ID); // We need to make sure that we record empty folders m_archiveWriter.WriteDir(path); } List<InventoryFolderImpl> childFolders = inventoryFolder.RequestListOfFolderImpls(); List<InventoryItemBase> items = inventoryFolder.RequestListOfItems(); /* Dictionary identicalFolderNames = new Dictionary<string, int>(); foreach (InventoryFolderImpl folder in inventories) { if (!identicalFolderNames.ContainsKey(folder.Name)) identicalFolderNames[folder.Name] = 0; else identicalFolderNames[folder.Name] = identicalFolderNames[folder.Name]++; int folderNameNumber = identicalFolderName[folder.Name]; SaveInvDir( folder, string.Format( "{0}{1}{2}/", path, ArchiveConstants.INVENTORY_NODE_NAME_COMPONENT_SEPARATOR, folderNameNumber)); } */ foreach (InventoryFolderImpl childFolder in childFolders) { SaveInvFolder(childFolder, path, true); } foreach (InventoryItemBase item in items) { SaveInvItem(item, path); } } /// <summary> /// Execute the inventory write request /// </summary> public void Execute() { /*InventoryFolderImpl inventoryFolder = null; InventoryItemBase inventoryItem = null; if (!m_userInfo.HasReceivedInventory) { // If the region server has access to the user admin service (by which users are created), // then we'll assume that it's okay to fiddle with the user's inventory even if they are not on the // server. // // FIXME: FetchInventory should probably be assumed to by async anyway, since even standalones might // use a remote inventory service, though this is vanishingly rare at the moment. if (null == m_module.CommsManager.UserAdminService) { m_log.ErrorFormat( "[INVENTORY ARCHIVER]: Have not yet received inventory info for user {0} {1}", m_userInfo.UserProfile.Name, m_userInfo.UserProfile.ID); return; } else { m_userInfo.FetchInventory(); } } bool foundStar = false; // Eliminate double slashes and any leading / on the path. This might be better done within InventoryFolderImpl // itself (possibly at a small loss in efficiency). string[] components = m_invPath.Split(new string[] { InventoryFolderImpl.PATH_DELIMITER }, StringSplitOptions.RemoveEmptyEntries); int maxComponentIndex = components.Length - 1; // If the path terminates with a STAR then later on we want to archive all nodes in the folder but not the // folder itself. This may get more sophisicated later on if (maxComponentIndex >= 0 && components[maxComponentIndex] == STAR_WILDCARD) { foundStar = true; maxComponentIndex--; } m_invPath = String.Empty; for (int i = 0; i <= maxComponentIndex; i++) { m_invPath += components[i] + InventoryFolderImpl.PATH_DELIMITER; } // Annoyingly Split actually returns the original string if the input string consists only of delimiters // Therefore if we still start with a / after the split, then we need the root folder if (m_invPath.Length == 0) { inventoryFolder = m_userInfo.RootFolder; } else { m_invPath = m_invPath.Remove(m_invPath.LastIndexOf(InventoryFolderImpl.PATH_DELIMITER)); inventoryFolder = m_userInfo.RootFolder.FindFolderByPath(m_invPath); } // The path may point to an item instead if (inventoryFolder == null) { inventoryItem = m_userInfo.RootFolder.FindItemByPath(m_invPath); } m_archiveWriter = new TarArchiveWriter(m_saveStream); if (null == inventoryFolder) { if (null == inventoryItem) { // We couldn't find the path indicated m_saveStream.Close(); m_module.TriggerInventoryArchiveSaved( false, m_userInfo, m_invPath, m_saveStream, new Exception(string.Format("Could not find inventory entry at path {0}", m_invPath))); return; } else { m_log.DebugFormat( "[INVENTORY ARCHIVER]: Found item {0} {1} at {2}", inventoryItem.Name, inventoryItem.ID, m_invPath); SaveInvItem(inventoryItem, ArchiveConstants.INVENTORY_PATH); } } else { m_log.DebugFormat( "[INVENTORY ARCHIVER]: Found folder {0} {1} at {2}", inventoryFolder.Name, inventoryFolder.ID, m_invPath); //recurse through all dirs getting dirs and files SaveInvFolder(inventoryFolder, ArchiveConstants.INVENTORY_PATH, !foundStar); } SaveUsers(); new AssetsRequest( new AssetsArchiver(m_archiveWriter), m_assetUuids.Keys, m_module.CommsManager.AssetCache, ReceivedAllAssets).Execute();*/ throw new NotImplementedException(); } /// <summary> /// Save information for the users that we've collected. /// </summary> protected void SaveUsers() { m_log.InfoFormat("[INVENTORY ARCHIVER]: Saving user information for {0} users", m_userUuids.Count); foreach (UUID creatorId in m_userUuids.Keys) { // Record the creator of this item CachedUserInfo creator = m_module.CommsManager.UserProfileCacheService.GetUserDetails(creatorId); if (creator != null) { m_archiveWriter.WriteFile( ArchiveConstants.USERS_PATH + creator.UserProfile.Name + ".xml", UserProfileSerializer.Serialize(creator.UserProfile)); } else { m_log.WarnFormat("[INVENTORY ARCHIVER]: Failed to get creator profile for {0}", creatorId); } } } } }
// 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.IO.PortsTests; using System.Text; using System.Threading; using Legacy.Support; using Xunit; namespace System.IO.Ports.Tests { public class SerialStream_Read_byte_int_int_Generic : PortsTest { // Set bounds fore random timeout values. // If the min is to low read will not timeout accurately and the testcase will fail private const int minRandomTimeout = 250; // If the max is to large then the testcase will take forever to run private const int maxRandomTimeout = 2000; // If the percentage difference between the expected timeout and the actual timeout // found through Stopwatch is greater then 10% then the timeout value was not correctly // to the read method and the testcase fails. private const double maxPercentageDifference = .15; // The number of random bytes to receive for parity testing private const int numRndBytesPairty = 8; // The number of characters to read at a time for parity testing private const int numBytesReadPairty = 2; // The number of random bytes to receive for BytesToRead testing private const int numRndBytesToRead = 16; // When we test Read and do not care about actually reading anything we must still // create an byte array to pass into the method the following is the size of the // byte array used in this situation private const int defaultByteArraySize = 1; private const int NUM_TRYS = 5; #region Test Cases [ConditionalFact(nameof(HasOneSerialPort))] public void ReadAfterClose() { using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { Debug.WriteLine("Verifying read method throws exception after a call to Cloes()"); com.Open(); Stream serialStream = com.BaseStream; com.Close(); VerifyReadException(serialStream, typeof(ObjectDisposedException)); } } [ConditionalFact(nameof(HasOneSerialPort))] public void ReadAfterBaseStreamClose() { using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { Debug.WriteLine("Verifying read method throws exception after a call to BaseStream.Close()"); com.Open(); Stream serialStream = com.BaseStream; com.BaseStream.Close(); VerifyReadException(serialStream, typeof(ObjectDisposedException)); } } [OuterLoop("Slow test")] [ConditionalFact(nameof(HasOneSerialPort))] public void Timeout() { using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { var rndGen = new Random(-55); com.ReadTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout); Debug.WriteLine("Verifying ReadTimeout={0}", com.ReadTimeout); com.Open(); VerifyTimeout(com); } } [OuterLoop("Slow Test")] [ConditionalFact(nameof(HasOneSerialPort))] public void SuccessiveReadTimeoutNoData() { using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { var rndGen = new Random(-55); com.ReadTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout); com.Encoding = Encoding.Unicode; Debug.WriteLine("Verifying ReadTimeout={0} with successive call to read method and no data", com.ReadTimeout); com.Open(); Assert.Throws<TimeoutException>(() => com.BaseStream.Read(new byte[defaultByteArraySize], 0, defaultByteArraySize)); VerifyTimeout(com); } } [ConditionalFact(nameof(HasNullModem))] public void SuccessiveReadTimeoutSomeData() { using (var com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { var rndGen = new Random(-55); var t = new Thread(WriteToCom1); com1.ReadTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout); com1.Encoding = new UTF8Encoding(); Debug.WriteLine( "Verifying ReadTimeout={0} with successive call to read method and some data being received in the first call", com1.ReadTimeout); com1.Open(); // Call WriteToCom1 asynchronously this will write to com1 some time before the following call // to a read method times out t.Start(); try { com1.BaseStream.Read(new byte[defaultByteArraySize], 0, defaultByteArraySize); } catch (TimeoutException) { } // Wait for the thread to finish while (t.IsAlive) Thread.Sleep(50); // Make sure there is no bytes in the buffer so the next call to read will timeout com1.DiscardInBuffer(); VerifyTimeout(com1); } } private void WriteToCom1() { using (var com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { var rndGen = new Random(-55); var xmitBuffer = new byte[1]; int sleepPeriod = rndGen.Next(minRandomTimeout, maxRandomTimeout / 2); // Sleep some random period with of a maximum duration of half the largest possible timeout value for a read method on COM1 Thread.Sleep(sleepPeriod); com2.Open(); com2.Write(xmitBuffer, 0, xmitBuffer.Length); } } [ConditionalFact(nameof(HasNullModem))] public void DefaultParityReplaceByte() { VerifyParityReplaceByte(-1, numRndBytesPairty - 2); } [ConditionalFact(nameof(HasNullModem))] public void NoParityReplaceByte() { var rndGen = new Random(-55); VerifyParityReplaceByte('\0', rndGen.Next(0, numRndBytesPairty - 1), Encoding.UTF32); } [ConditionalFact(nameof(HasNullModem))] public void RNDParityReplaceByte() { var rndGen = new Random(-55); VerifyParityReplaceByte(rndGen.Next(0, 128), 0, new UTF8Encoding()); } [ConditionalFact(nameof(HasNullModem))] public void ParityErrorOnLastByte() { using (var com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) using (var com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { var rndGen = new Random(15); var bytesToWrite = new byte[numRndBytesPairty]; var expectedBytes = new byte[numRndBytesPairty]; var actualBytes = new byte[numRndBytesPairty + 1]; /* 1 Additional character gets added to the input buffer when the parity error occurs on the last byte of a stream We are verifying that besides this everything gets read in correctly. See NDP Whidbey: 24216 for more info on this */ Debug.WriteLine("Verifying default ParityReplace byte with a parity errro on the last byte"); // Generate random characters without an parity error for (var i = 0; i < bytesToWrite.Length; i++) { var randByte = (byte)rndGen.Next(0, 128); bytesToWrite[i] = randByte; expectedBytes[i] = randByte; } bytesToWrite[bytesToWrite.Length - 1] = (byte)(bytesToWrite[bytesToWrite.Length - 1] | 0x80); // Create a parity error on the last byte expectedBytes[expectedBytes.Length - 1] = com1.ParityReplace; // Set the last expected byte to be the ParityReplace Byte com1.Parity = Parity.Space; com1.DataBits = 7; com1.ReadTimeout = 250; com1.Open(); com2.Open(); com2.Write(bytesToWrite, 0, bytesToWrite.Length); TCSupport.WaitForReadBufferToLoad(com1, bytesToWrite.Length + 1); com1.BaseStream.Read(actualBytes, 0, actualBytes.Length); // Compare the chars that were written with the ones we expected to read for (var i = 0; i < expectedBytes.Length; i++) { if (expectedBytes[i] != actualBytes[i]) { Fail("ERROR!!!: Expected to read {0} actual read {1}", (int)expectedBytes[i], (int)actualBytes[i]); } } if (1 < com1.BytesToRead) { Fail("ERROR!!!: Expected BytesToRead=0 actual={0}", com1.BytesToRead); Fail("ByteRead={0}, {1}", com1.ReadByte(), bytesToWrite[bytesToWrite.Length - 1]); } bytesToWrite[bytesToWrite.Length - 1] = (byte)(bytesToWrite[bytesToWrite.Length - 1] & 0x7F); // Clear the parity error on the last byte expectedBytes[expectedBytes.Length - 1] = bytesToWrite[bytesToWrite.Length - 1]; VerifyRead(com1, com2, bytesToWrite, expectedBytes, expectedBytes.Length / 2); } } [ConditionalFact(nameof(HasNullModem))] public void BytesToRead_RND_Buffer_Size() { var rndGen = new Random(-55); VerifyBytesToRead(rndGen.Next(1, 2 * numRndBytesToRead)); } [ConditionalFact(nameof(HasNullModem))] public void BytesToRead_1_Buffer_Size() { VerifyBytesToRead(1, Encoding.Unicode); } [ConditionalFact(nameof(HasNullModem))] public void BytesToRead_Equal_Buffer_Size() { VerifyBytesToRead(numRndBytesToRead, new UTF8Encoding()); } #endregion #region Verification for Test Cases private void VerifyTimeout(SerialPort com) { var timer = new Stopwatch(); int expectedTime = com.ReadTimeout; var actualTime = 0; double percentageDifference; try { com.BaseStream.Read(new byte[defaultByteArraySize], 0, defaultByteArraySize); // Warm up read method Fail("Err_6941814ahbpa!!!: Read did not throw Timeout Exception when it timed out for the first time"); } catch (TimeoutException) { } Thread.CurrentThread.Priority = ThreadPriority.Highest; for (var i = 0; i < NUM_TRYS; i++) { timer.Start(); try { com.BaseStream.Read(new byte[defaultByteArraySize], 0, defaultByteArraySize); Fail("Err_17087ahps!!!: Read did not reuturn 0 when it timed out"); } catch (TimeoutException) { } timer.Stop(); actualTime += (int)timer.ElapsedMilliseconds; timer.Reset(); } Thread.CurrentThread.Priority = ThreadPriority.Normal; actualTime /= NUM_TRYS; percentageDifference = Math.Abs((expectedTime - actualTime) / (double)expectedTime); // Verify that the percentage difference between the expected and actual timeout is less then maxPercentageDifference if (maxPercentageDifference < percentageDifference) { Fail("ERROR!!!: The read method timedout in {0} expected {1} percentage difference: {2}", actualTime, expectedTime, percentageDifference); } if (com.IsOpen) com.Close(); } private void VerifyReadException(Stream serialStream, Type expectedException) { Assert.Throws(expectedException, () => serialStream.Read(new byte[defaultByteArraySize], 0, defaultByteArraySize)); } private void VerifyParityReplaceByte(int parityReplace, int parityErrorIndex) { VerifyParityReplaceByte(parityReplace, parityErrorIndex, new ASCIIEncoding()); } private void VerifyParityReplaceByte(int parityReplace, int parityErrorIndex, Encoding encoding) { using (var com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) using (var com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { var rndGen = new Random(-55); var bytesToWrite = new byte[numRndBytesPairty]; var expectedBytes = new byte[numRndBytesPairty]; byte expectedByte; // Generate random characters without an parity error for (var i = 0; i < bytesToWrite.Length; i++) { var randByte = (byte)rndGen.Next(0, 128); bytesToWrite[i] = randByte; expectedBytes[i] = randByte; } if (-1 == parityReplace) { // If parityReplace is -1 and we should just use the default value expectedByte = com1.ParityReplace; } else if ('\0' == parityReplace) { // If parityReplace is the null charachater and parity replacement should not occur com1.ParityReplace = (byte)parityReplace; expectedByte = bytesToWrite[parityErrorIndex]; } else { // Else parityReplace was set to a value and we should expect this value to be returned on a parity error com1.ParityReplace = (byte)parityReplace; expectedByte = (byte)parityReplace; } // Create an parity error by setting the highest order bit to true bytesToWrite[parityErrorIndex] = (byte)(bytesToWrite[parityErrorIndex] | 0x80); expectedBytes[parityErrorIndex] = expectedByte; Debug.WriteLine("Verifying ParityReplace={0} with an ParityError at: {1} ", com1.ParityReplace, parityErrorIndex); com1.Parity = Parity.Space; com1.DataBits = 7; com1.Encoding = encoding; com1.Open(); com2.Open(); VerifyRead(com1, com2, bytesToWrite, expectedBytes, numBytesReadPairty); } } private void VerifyBytesToRead(int numBytesRead) { VerifyBytesToRead(numBytesRead, new ASCIIEncoding()); } private void VerifyBytesToRead(int numBytesRead, Encoding encoding) { using (var com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) using (var com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { var rndGen = new Random(-55); var bytesToWrite = new byte[numRndBytesToRead]; // Generate random characters for (var i = 0; i < bytesToWrite.Length; i++) { var randByte = (byte)rndGen.Next(0, 256); bytesToWrite[i] = randByte; } Debug.WriteLine("Verifying BytesToRead with a buffer of: {0} ", numBytesRead); com1.Encoding = encoding; com1.Open(); com2.Open(); VerifyRead(com1, com2, bytesToWrite, bytesToWrite, numBytesRead); } } private void VerifyRead(SerialPort com1, SerialPort com2, byte[] bytesToWrite, byte[] expectedBytes, int rcvBufferSize) { var rcvBuffer = new byte[rcvBufferSize]; var buffer = new byte[bytesToWrite.Length]; int totalBytesRead; int bytesToRead; com2.Write(bytesToWrite, 0, bytesToWrite.Length); com1.ReadTimeout = 250; TCSupport.WaitForReadBufferToLoad(com1, bytesToWrite.Length); totalBytesRead = 0; bytesToRead = com1.BytesToRead; while (true) { int bytesRead; try { bytesRead = com1.BaseStream.Read(rcvBuffer, 0, rcvBufferSize); } catch (TimeoutException) { break; } // While their are more characters to be read if ((bytesToRead > bytesRead && rcvBufferSize != bytesRead) || (bytesToRead <= bytesRead && bytesRead != bytesToRead)) { // If we have not read all of the characters that we should have Fail("ERROR!!!: Read did not return all of the characters that were in SerialPort buffer"); } if (bytesToWrite.Length < totalBytesRead + bytesRead) { // If we have read in more characters then we expect Fail("ERROR!!!: We have received more characters then were sent"); break; } Array.Copy(rcvBuffer, 0, buffer, totalBytesRead, bytesRead); totalBytesRead += bytesRead; if (bytesToWrite.Length - totalBytesRead != com1.BytesToRead) { Fail("ERROR!!!: Expected BytesToRead={0} actual={1}", bytesToWrite.Length - totalBytesRead, com1.BytesToRead); } bytesToRead = com1.BytesToRead; } // Compare the bytes that were written with the ones we expected to read for (var i = 0; i < bytesToWrite.Length; i++) { if (expectedBytes[i] != buffer[i]) { Fail("ERROR!!!: Expected to read {0} actual read {1}", expectedBytes[i], buffer[i]); } } } #endregion } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.ApiManagement.Models { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Azure.Management.ApiManagement; using Newtonsoft.Json; using System.Linq; /// <summary> /// Request Report data. /// </summary> public partial class RequestReportRecordContract { /// <summary> /// Initializes a new instance of the RequestReportRecordContract /// class. /// </summary> public RequestReportRecordContract() { CustomInit(); } /// <summary> /// Initializes a new instance of the RequestReportRecordContract /// class. /// </summary> /// <param name="apiId">API identifier path. /apis/{apiId}</param> /// <param name="operationId">Operation identifier path. /// /apis/{apiId}/operations/{operationId}</param> /// <param name="productId">Product identifier path. /// /products/{productId}</param> /// <param name="userId">User identifier path. /users/{userId}</param> /// <param name="method">The HTTP method associated with this /// request..</param> /// <param name="url">The full URL associated with this /// request.</param> /// <param name="ipAddress">The client IP address associated with this /// request.</param> /// <param name="backendResponseCode">The HTTP status code received by /// the gateway as a result of forwarding this request to the /// backend.</param> /// <param name="responseCode">The HTTP status code returned by the /// gateway.</param> /// <param name="responseSize">The size of the response returned by the /// gateway.</param> /// <param name="timestamp">The date and time when this request was /// received by the gateway in ISO 8601 format.</param> /// <param name="cache">Specifies if response cache was involved in /// generating the response. If the value is none, the cache was not /// used. If the value is hit, cached response was returned. If the /// value is miss, the cache was used but lookup resulted in a miss and /// request was fullfilled by the backend.</param> /// <param name="apiTime">The total time it took to process this /// request.</param> /// <param name="serviceTime">he time it took to forward this request /// to the backend and get the response back.</param> /// <param name="apiRegion">Azure region where the gateway that /// processed this request is located.</param> /// <param name="subscriptionId">Subscription identifier path. /// /subscriptions/{subscriptionId}</param> /// <param name="requestId">Request Identifier.</param> /// <param name="requestSize">The size of this request..</param> public RequestReportRecordContract(string apiId = default(string), string operationId = default(string), string productId = default(string), string userId = default(string), string method = default(string), string url = default(string), string ipAddress = default(string), string backendResponseCode = default(string), int? responseCode = default(int?), int? responseSize = default(int?), System.DateTime? timestamp = default(System.DateTime?), string cache = default(string), double? apiTime = default(double?), double? serviceTime = default(double?), string apiRegion = default(string), string subscriptionId = default(string), string requestId = default(string), int? requestSize = default(int?)) { ApiId = apiId; OperationId = operationId; ProductId = productId; UserId = userId; Method = method; Url = url; IpAddress = ipAddress; BackendResponseCode = backendResponseCode; ResponseCode = responseCode; ResponseSize = responseSize; Timestamp = timestamp; Cache = cache; ApiTime = apiTime; ServiceTime = serviceTime; ApiRegion = apiRegion; SubscriptionId = subscriptionId; RequestId = requestId; RequestSize = requestSize; CustomInit(); } /// <summary> /// An initialization method that performs custom operations like setting defaults /// </summary> partial void CustomInit(); /// <summary> /// Gets or sets API identifier path. /apis/{apiId} /// </summary> [JsonProperty(PropertyName = "apiId")] public string ApiId { get; set; } /// <summary> /// Gets or sets operation identifier path. /// /apis/{apiId}/operations/{operationId} /// </summary> [JsonProperty(PropertyName = "operationId")] public string OperationId { get; set; } /// <summary> /// Gets product identifier path. /products/{productId} /// </summary> [JsonProperty(PropertyName = "productId")] public string ProductId { get; private set; } /// <summary> /// Gets user identifier path. /users/{userId} /// </summary> [JsonProperty(PropertyName = "userId")] public string UserId { get; private set; } /// <summary> /// Gets or sets the HTTP method associated with this request.. /// </summary> [JsonProperty(PropertyName = "method")] public string Method { get; set; } /// <summary> /// Gets or sets the full URL associated with this request. /// </summary> [JsonProperty(PropertyName = "url")] public string Url { get; set; } /// <summary> /// Gets or sets the client IP address associated with this request. /// </summary> [JsonProperty(PropertyName = "ipAddress")] public string IpAddress { get; set; } /// <summary> /// Gets or sets the HTTP status code received by the gateway as a /// result of forwarding this request to the backend. /// </summary> [JsonProperty(PropertyName = "backendResponseCode")] public string BackendResponseCode { get; set; } /// <summary> /// Gets or sets the HTTP status code returned by the gateway. /// </summary> [JsonProperty(PropertyName = "responseCode")] public int? ResponseCode { get; set; } /// <summary> /// Gets or sets the size of the response returned by the gateway. /// </summary> [JsonProperty(PropertyName = "responseSize")] public int? ResponseSize { get; set; } /// <summary> /// Gets or sets the date and time when this request was received by /// the gateway in ISO 8601 format. /// </summary> [JsonProperty(PropertyName = "timestamp")] public System.DateTime? Timestamp { get; set; } /// <summary> /// Gets or sets specifies if response cache was involved in generating /// the response. If the value is none, the cache was not used. If the /// value is hit, cached response was returned. If the value is miss, /// the cache was used but lookup resulted in a miss and request was /// fullfilled by the backend. /// </summary> [JsonProperty(PropertyName = "cache")] public string Cache { get; set; } /// <summary> /// Gets or sets the total time it took to process this request. /// </summary> [JsonProperty(PropertyName = "apiTime")] public double? ApiTime { get; set; } /// <summary> /// Gets or sets he time it took to forward this request to the backend /// and get the response back. /// </summary> [JsonProperty(PropertyName = "serviceTime")] public double? ServiceTime { get; set; } /// <summary> /// Gets or sets azure region where the gateway that processed this /// request is located. /// </summary> [JsonProperty(PropertyName = "apiRegion")] public string ApiRegion { get; set; } /// <summary> /// Gets or sets subscription identifier path. /// /subscriptions/{subscriptionId} /// </summary> [JsonProperty(PropertyName = "subscriptionId")] public string SubscriptionId { get; set; } /// <summary> /// Gets or sets request Identifier. /// </summary> [JsonProperty(PropertyName = "requestId")] public string RequestId { get; set; } /// <summary> /// Gets or sets the size of this request.. /// </summary> [JsonProperty(PropertyName = "requestSize")] public int? RequestSize { get; set; } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using log4net; using Nini.Config; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Servers.HttpServer; using OpenSim.Server.Base; using OpenSim.Services.Interfaces; using OpenSim.Services.UserAccountService; using System; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Xml; using OpenSim.Framework.ServiceAuth; namespace OpenSim.Server.Handlers.UserAccounts { public class UserAccountServerPostHandler : BaseStreamHandler { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private IUserAccountService m_UserAccountService; private bool m_AllowCreateUser = false; private bool m_AllowSetAccount = false; public UserAccountServerPostHandler(IUserAccountService service) : this(service, null, null) {} public UserAccountServerPostHandler(IUserAccountService service, IConfig config, IServiceAuth auth) : base("POST", "/accounts", auth) { m_UserAccountService = service; if (config != null) { m_AllowCreateUser = config.GetBoolean("AllowCreateUser", m_AllowCreateUser); m_AllowSetAccount = config.GetBoolean("AllowSetAccount", m_AllowSetAccount); } } protected override byte[] ProcessRequest(string path, Stream requestData, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { StreamReader sr = new StreamReader(requestData); string body = sr.ReadToEnd(); sr.Close(); body = body.Trim(); // We need to check the authorization header //httpRequest.Headers["authorization"] ... //m_log.DebugFormat("[XXX]: query String: {0}", body); string method = string.Empty; try { Dictionary<string, object> request = ServerUtils.ParseQueryString(body); if (!request.ContainsKey("METHOD")) return FailureResult(); method = request["METHOD"].ToString(); switch (method) { case "createuser": if (m_AllowCreateUser) return CreateUser(request); else break; case "getaccount": return GetAccount(request); case "getaccounts": return GetAccounts(request); case "setaccount": if (m_AllowSetAccount) return StoreAccount(request); else break; } m_log.DebugFormat("[USER SERVICE HANDLER]: unknown method request: {0}", method); } catch (Exception e) { m_log.DebugFormat("[USER SERVICE HANDLER]: Exception in method {0}: {1}", method, e); } return FailureResult(); } byte[] GetAccount(Dictionary<string, object> request) { UserAccount account = null; UUID scopeID = UUID.Zero; Dictionary<string, object> result = new Dictionary<string, object>(); if (request.ContainsKey("ScopeID") && !UUID.TryParse(request["ScopeID"].ToString(), out scopeID)) { result["result"] = "null"; return ResultToBytes(result); } if (request.ContainsKey("UserID") && request["UserID"] != null) { UUID userID; if (UUID.TryParse(request["UserID"].ToString(), out userID)) account = m_UserAccountService.GetUserAccount(scopeID, userID); } else if (request.ContainsKey("PrincipalID") && request["PrincipalID"] != null) { UUID userID; if (UUID.TryParse(request["PrincipalID"].ToString(), out userID)) account = m_UserAccountService.GetUserAccount(scopeID, userID); } else if (request.ContainsKey("Email") && request["Email"] != null) { account = m_UserAccountService.GetUserAccount(scopeID, request["Email"].ToString()); } else if (request.ContainsKey("FirstName") && request.ContainsKey("LastName") && request["FirstName"] != null && request["LastName"] != null) { account = m_UserAccountService.GetUserAccount(scopeID, request["FirstName"].ToString(), request["LastName"].ToString()); } if (account == null) { result["result"] = "null"; } else { result["result"] = account.ToKeyValuePairs(); } return ResultToBytes(result); } byte[] GetAccounts(Dictionary<string, object> request) { if (!request.ContainsKey("query")) return FailureResult(); UUID scopeID = UUID.Zero; if (request.ContainsKey("ScopeID") && !UUID.TryParse(request["ScopeID"].ToString(), out scopeID)) return FailureResult(); string query = request["query"].ToString(); List<UserAccount> accounts = m_UserAccountService.GetUserAccounts(scopeID, query); Dictionary<string, object> result = new Dictionary<string, object>(); if ((accounts == null) || ((accounts != null) && (accounts.Count == 0))) { result["result"] = "null"; } else { int i = 0; foreach (UserAccount acc in accounts) { Dictionary<string, object> rinfoDict = acc.ToKeyValuePairs(); result["account" + i] = rinfoDict; i++; } } string xmlString = ServerUtils.BuildXmlResponse(result); //m_log.DebugFormat("[GRID HANDLER]: resp string: {0}", xmlString); return Util.UTF8NoBomEncoding.GetBytes(xmlString); } byte[] StoreAccount(Dictionary<string, object> request) { UUID principalID = UUID.Zero; if (request.ContainsKey("PrincipalID") && !UUID.TryParse(request["PrincipalID"].ToString(), out principalID)) return FailureResult(); UUID scopeID = UUID.Zero; if (request.ContainsKey("ScopeID") && !UUID.TryParse(request["ScopeID"].ToString(), out scopeID)) return FailureResult(); UserAccount existingAccount = m_UserAccountService.GetUserAccount(scopeID, principalID); if (existingAccount == null) return FailureResult(); Dictionary<string, object> result = new Dictionary<string, object>(); if (request.ContainsKey("FirstName")) existingAccount.FirstName = request["FirstName"].ToString(); if (request.ContainsKey("LastName")) existingAccount.LastName = request["LastName"].ToString(); if (request.ContainsKey("Email")) existingAccount.Email = request["Email"].ToString(); int created = 0; if (request.ContainsKey("Created") && int.TryParse(request["Created"].ToString(), out created)) existingAccount.Created = created; int userLevel = 0; if (request.ContainsKey("UserLevel") && int.TryParse(request["UserLevel"].ToString(), out userLevel)) existingAccount.UserLevel = userLevel; int userFlags = 0; if (request.ContainsKey("UserFlags") && int.TryParse(request["UserFlags"].ToString(), out userFlags)) existingAccount.UserFlags = userFlags; if (request.ContainsKey("UserTitle")) existingAccount.UserTitle = request["UserTitle"].ToString(); if (!m_UserAccountService.StoreUserAccount(existingAccount)) { m_log.ErrorFormat( "[USER ACCOUNT SERVER POST HANDLER]: Account store failed for account {0} {1} {2}", existingAccount.FirstName, existingAccount.LastName, existingAccount.PrincipalID); return FailureResult(); } result["result"] = existingAccount.ToKeyValuePairs(); return ResultToBytes(result); } byte[] CreateUser(Dictionary<string, object> request) { if (! request.ContainsKey("FirstName") && request.ContainsKey("LastName") && request.ContainsKey("Password")) return FailureResult(); Dictionary<string, object> result = new Dictionary<string, object>(); UUID scopeID = UUID.Zero; if (request.ContainsKey("ScopeID") && !UUID.TryParse(request["ScopeID"].ToString(), out scopeID)) return FailureResult(); UUID principalID = UUID.Random(); if (request.ContainsKey("PrincipalID") && !UUID.TryParse(request["PrincipalID"].ToString(), out principalID)) return FailureResult(); string firstName = request["FirstName"].ToString(); string lastName = request["LastName"].ToString(); string password = request["Password"].ToString(); string email = ""; if (request.ContainsKey("Email")) email = request["Email"].ToString(); UserAccount createdUserAccount = null; if (m_UserAccountService is UserAccountService) createdUserAccount = ((UserAccountService)m_UserAccountService).CreateUser( scopeID, principalID, firstName, lastName, password, email); if (createdUserAccount == null) return FailureResult(); result["result"] = createdUserAccount.ToKeyValuePairs(); return ResultToBytes(result); } private byte[] SuccessResult() { XmlDocument doc = new XmlDocument(); XmlNode xmlnode = doc.CreateNode(XmlNodeType.XmlDeclaration, "", ""); doc.AppendChild(xmlnode); XmlElement rootElement = doc.CreateElement("", "ServerResponse", ""); doc.AppendChild(rootElement); XmlElement result = doc.CreateElement("", "result", ""); result.AppendChild(doc.CreateTextNode("Success")); rootElement.AppendChild(result); return Util.DocToBytes(doc); } private byte[] FailureResult() { XmlDocument doc = new XmlDocument(); XmlNode xmlnode = doc.CreateNode(XmlNodeType.XmlDeclaration, "", ""); doc.AppendChild(xmlnode); XmlElement rootElement = doc.CreateElement("", "ServerResponse", ""); doc.AppendChild(rootElement); XmlElement result = doc.CreateElement("", "result", ""); result.AppendChild(doc.CreateTextNode("Failure")); rootElement.AppendChild(result); return Util.DocToBytes(doc); } private byte[] ResultToBytes(Dictionary<string, object> result) { string xmlString = ServerUtils.BuildXmlResponse(result); return Util.UTF8NoBomEncoding.GetBytes(xmlString); } } }
// 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.Net.NetworkInformation.Tests { public class StatisticsParsingTests { [Fact] public static void Icmpv4Parsing() { FileUtil.NormalizeLineEndings("snmp", "snmp_normalized1"); Icmpv4StatisticsTable table = StringParsingHelpers.ParseIcmpv4FromSnmpFile("snmp_normalized1"); Assert.Equal(1, table.InMsgs); Assert.Equal(2, table.InErrors); Assert.Equal(3, table.InCsumErrors); Assert.Equal(4, table.InDestUnreachs); Assert.Equal(5, table.InTimeExcds); Assert.Equal(6, table.InParmProbs); Assert.Equal(7, table.InSrcQuenchs); Assert.Equal(8, table.InRedirects); Assert.Equal(9, table.InEchos); Assert.Equal(10, table.InEchoReps); Assert.Equal(20, table.InTimestamps); Assert.Equal(30, table.InTimeStampReps); Assert.Equal(40, table.InAddrMasks); Assert.Equal(50, table.InAddrMaskReps); Assert.Equal(60, table.OutMsgs); Assert.Equal(70, table.OutErrors); Assert.Equal(80, table.OutDestUnreachs); Assert.Equal(90, table.OutTimeExcds); Assert.Equal(100, table.OutParmProbs); Assert.Equal(255, table.OutSrcQuenchs); Assert.Equal(1024, table.OutRedirects); Assert.Equal(256, table.OutEchos); Assert.Equal(9001, table.OutEchoReps); Assert.Equal(42, table.OutTimestamps); Assert.Equal(4100414, table.OutTimestampReps); Assert.Equal(2147483647, table.OutAddrMasks); Assert.Equal(0, table.OutAddrMaskReps); } [Fact] public static void Icmpv6Parsing() { FileUtil.NormalizeLineEndings("snmp6", "snmp6_normalized0"); Icmpv6StatisticsTable table = StringParsingHelpers.ParseIcmpv6FromSnmp6File("snmp6_normalized0"); Assert.Equal(1, table.InMsgs); Assert.Equal(2, table.InErrors); Assert.Equal(3, table.OutMsgs); Assert.Equal(4, table.OutErrors); Assert.Equal(6, table.InDestUnreachs); Assert.Equal(7, table.InPktTooBigs); Assert.Equal(8, table.InTimeExcds); Assert.Equal(9, table.InParmProblems); Assert.Equal(10, table.InEchos); Assert.Equal(11, table.InEchoReplies); Assert.Equal(12, table.InGroupMembQueries); Assert.Equal(13, table.InGroupMembResponses); Assert.Equal(14, table.InGroupMembReductions); Assert.Equal(15, table.InRouterSolicits); Assert.Equal(16, table.InRouterAdvertisements); Assert.Equal(17, table.InNeighborSolicits); Assert.Equal(18, table.InNeighborAdvertisements); Assert.Equal(19, table.InRedirects); Assert.Equal(21, table.OutDestUnreachs); Assert.Equal(22, table.OutPktTooBigs); Assert.Equal(23, table.OutTimeExcds); Assert.Equal(24, table.OutParmProblems); Assert.Equal(25, table.OutEchos); Assert.Equal(26, table.OutEchoReplies); Assert.Equal(27, table.OutInGroupMembQueries); Assert.Equal(28, table.OutGroupMembResponses); Assert.Equal(29, table.OutGroupMembReductions); Assert.Equal(30, table.OutRouterSolicits); Assert.Equal(31, table.OutRouterAdvertisements); Assert.Equal(32, table.OutNeighborSolicits); Assert.Equal(33, table.OutNeighborAdvertisements); Assert.Equal(34, table.OutRedirects); } [Fact] public static void TcpGlobalStatisticsParsing() { FileUtil.NormalizeLineEndings("snmp", "snmp_normalized2"); TcpGlobalStatisticsTable table = StringParsingHelpers.ParseTcpGlobalStatisticsFromSnmpFile("snmp_normalized2"); Assert.Equal(1, table.RtoAlgorithm); Assert.Equal(200, table.RtoMin); Assert.Equal(120000, table.RtoMax); Assert.Equal(-1, table.MaxConn); Assert.Equal(359, table.ActiveOpens); Assert.Equal(28, table.PassiveOpens); Assert.Equal(2, table.AttemptFails); Assert.Equal(53, table.EstabResets); Assert.Equal(4, table.CurrEstab); Assert.Equal(21368, table.InSegs); Assert.Equal(20642, table.OutSegs); Assert.Equal(19, table.RetransSegs); Assert.Equal(0, table.InErrs); Assert.Equal(111, table.OutRsts); Assert.Equal(0, table.InCsumErrors); } [Fact] public static void Udpv4GlobalStatisticsParsing() { FileUtil.NormalizeLineEndings("snmp", "snmp_normalized3"); UdpGlobalStatisticsTable table = StringParsingHelpers.ParseUdpv4GlobalStatisticsFromSnmpFile("snmp_normalized3"); Assert.Equal(7181, table.InDatagrams); Assert.Equal(150, table.NoPorts); Assert.Equal(0, table.InErrors); Assert.Equal(4386, table.OutDatagrams); Assert.Equal(0, table.RcvbufErrors); Assert.Equal(0, table.SndbufErrors); Assert.Equal(1, table.InCsumErrors); } [Fact] public static void Udpv6GlobalStatisticsParsing() { FileUtil.NormalizeLineEndings("snmp6", "snmp6_normalized1"); UdpGlobalStatisticsTable table = StringParsingHelpers.ParseUdpv6GlobalStatisticsFromSnmp6File("snmp6_normalized1"); Assert.Equal(19, table.InDatagrams); Assert.Equal(0, table.NoPorts); Assert.Equal(0, table.InErrors); Assert.Equal(21, table.OutDatagrams); Assert.Equal(99999, table.RcvbufErrors); Assert.Equal(11011011, table.SndbufErrors); Assert.Equal(0, table.InCsumErrors); } [Fact] public static void Ipv4GlobalStatisticsParsing() { FileUtil.NormalizeLineEndings("snmp", "snmp_normalized4"); IPGlobalStatisticsTable table = StringParsingHelpers.ParseIPv4GlobalStatisticsFromSnmpFile("snmp_normalized4"); Assert.Equal(false, table.Forwarding); Assert.Equal(64, table.DefaultTtl); Assert.Equal(28121, table.InReceives); Assert.Equal(0, table.InHeaderErrors); Assert.Equal(2, table.InAddressErrors); Assert.Equal(0, table.ForwardedDatagrams); Assert.Equal(0, table.InUnknownProtocols); Assert.Equal(0, table.InDiscards); Assert.Equal(28117, table.InDelivers); Assert.Equal(24616, table.OutRequests); Assert.Equal(48, table.OutDiscards); Assert.Equal(0, table.OutNoRoutes); Assert.Equal(0, table.ReassemblyTimeout); Assert.Equal(0, table.ReassemblyRequireds); Assert.Equal(1, table.ReassemblyOKs); Assert.Equal(2, table.ReassemblyFails); Assert.Equal(14, table.FragmentOKs); Assert.Equal(0, table.FragmentFails); Assert.Equal(92, table.FragmentCreates); } [Fact] public static void Ipv6GlobalStatisticsParsing() { FileUtil.NormalizeLineEndings("snmp6", "snmp6_normalized2"); IPGlobalStatisticsTable table = StringParsingHelpers.ParseIPv6GlobalStatisticsFromSnmp6File("snmp6_normalized2"); Assert.Equal(189, table.InReceives); Assert.Equal(0, table.InHeaderErrors); Assert.Equal(2000, table.InAddressErrors); Assert.Equal(42, table.InUnknownProtocols); Assert.Equal(0, table.InDiscards); Assert.Equal(189, table.InDelivers); Assert.Equal(55, table.ForwardedDatagrams); Assert.Equal(199, table.OutRequests); Assert.Equal(0, table.OutDiscards); Assert.Equal(53, table.OutNoRoutes); Assert.Equal(2121, table.ReassemblyTimeout); Assert.Equal(1, table.ReassemblyRequireds); Assert.Equal(2, table.ReassemblyOKs); Assert.Equal(4, table.ReassemblyFails); Assert.Equal(8, table.FragmentOKs); Assert.Equal(16, table.FragmentFails); Assert.Equal(32, table.FragmentCreates); } [Fact] public static void IpInterfaceStatisticsParsingFirst() { FileUtil.NormalizeLineEndings("dev", "dev_normalized0"); IPInterfaceStatisticsTable table = StringParsingHelpers.ParseInterfaceStatisticsTableFromFile("dev_normalized0", "wlan0"); Assert.Equal(26622u, table.BytesReceived); Assert.Equal(394u, table.PacketsReceived); Assert.Equal(2u, table.ErrorsReceived); Assert.Equal(4u, table.IncomingPacketsDropped); Assert.Equal(6u, table.FifoBufferErrorsReceived); Assert.Equal(8u, table.PacketFramingErrorsReceived); Assert.Equal(10u, table.CompressedPacketsReceived); Assert.Equal(12u, table.MulticastFramesReceived); Assert.Equal(27465u, table.BytesTransmitted); Assert.Equal(208u, table.PacketsTransmitted); Assert.Equal(1u, table.ErrorsTransmitted); Assert.Equal(2u, table.OutgoingPacketsDropped); Assert.Equal(3u, table.FifoBufferErrorsTransmitted); Assert.Equal(4u, table.CollisionsDetected); Assert.Equal(5u, table.CarrierLosses); Assert.Equal(6u, table.CompressedPacketsTransmitted); } [Fact] public static void IpInterfaceStatisticsParsingLast() { FileUtil.NormalizeLineEndings("dev", "dev_normalized1"); IPInterfaceStatisticsTable table = StringParsingHelpers.ParseInterfaceStatisticsTableFromFile("dev_normalized1", "lo"); Assert.Equal(uint.MaxValue, table.BytesReceived); Assert.Equal(302u, table.PacketsReceived); Assert.Equal(0u, table.ErrorsReceived); Assert.Equal(0u, table.IncomingPacketsDropped); Assert.Equal(0u, table.FifoBufferErrorsReceived); Assert.Equal(0u, table.PacketFramingErrorsReceived); Assert.Equal(0u, table.CompressedPacketsReceived); Assert.Equal(0u, table.MulticastFramesReceived); Assert.Equal(30008u, table.BytesTransmitted); Assert.Equal(302u, table.PacketsTransmitted); Assert.Equal(0u, table.ErrorsTransmitted); Assert.Equal(0u, table.OutgoingPacketsDropped); Assert.Equal(0u, table.FifoBufferErrorsTransmitted); Assert.Equal(0u, table.CollisionsDetected); Assert.Equal(0u, table.CarrierLosses); Assert.Equal(0u, table.CompressedPacketsTransmitted); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.IO; using System.Xml; using System.Collections.Generic; using NUnit.Framework; using Microsoft.Build.BuildEngine; using Microsoft.Build.Framework; using Microsoft.Build.UnitTests; namespace Microsoft.Build.UnitTests.OM.OrcasCompatibility { /// <summary> /// Test Fixture Class for the v9 Object Model Public Interface Compatibility Tests for the UsingTask Class. /// </summary> [TestFixture] public class UsingTask_Tests { #region AssemblyName /// <summary> /// AssemblyName test, set AssemblyName to a simple value in ctor then get. /// </summary> [Test] public void GetAssemblyName() { Project p = new Project(new Engine()); p.AddNewUsingTaskFromAssemblyName("TaskName", "AssemblyName"); object o = p.EvaluatedItems; Assertion.AssertEquals("AssemblyName", CompatibilityTestHelpers.FindUsingTaskByName("TaskName", p.UsingTasks).AssemblyName); } /// <summary> /// AssemblyName test, set AssemblyName to special escaped characters in ctor then get. /// </summary> [Test] public void GetAssemblyNameSpecialCharsEscaped() { Project p = new Project(new Engine()); p.AddNewUsingTaskFromAssemblyName("TaskName", @"%25%2a%3f%40%24%28%29%3b\"); object o = p.EvaluatedItems; Assertion.AssertEquals(@"%25%2a%3f%40%24%28%29%3b\", CompatibilityTestHelpers.FindUsingTaskByName("TaskName", p.UsingTasks).AssemblyName); } /// <summary> /// AssemblyName test, set AssemblyName to special non-escaped characters in ctor then get. /// </summary> [Test] public void GetAssemblyNameSpecialChars() { Project p = new Project(); p.AddNewUsingTaskFromAssemblyName("TaskName", @"%*?@$();\"); object o = p.EvaluatedItems; Assertion.AssertEquals(@"%*?@$();\", CompatibilityTestHelpers.FindUsingTaskByName("TaskName", p.UsingTasks).AssemblyName); } /// <summary> /// AssemblyName test,, set AssemblyName to a scalar that has no property defined in the project, then get. /// </summary> [Test] [ExpectedException(typeof(InvalidProjectFileException))] public void GetAssemblyNameScalarThatIsNotSet() { Project p = new Project(new Engine()); p.AddNewUsingTaskFromAssemblyName("TaskName", @"$(assemblyName)"); object o = p.EvaluatedItems; Assertion.AssertEquals(@"$(assemblyName)", CompatibilityTestHelpers.FindUsingTaskByName("TaskName", p.UsingTasks).AssemblyName); } /// <summary> /// AssemblyName test, set AssemblyName to scalar that is defined in the project, then get. Does not evaluate /// </summary> [Test] public void GetAssemblyNameScalarEvaluation() { string assemblyName = "$(assemblyName)"; Project p = new Project(); p.SetProperty("assemblyName", "aName"); object o = p.EvaluatedItems; p.AddNewUsingTaskFromAssemblyName("TaskName", assemblyName); o = p.EvaluatedItems; Assertion.AssertEquals(assemblyName, CompatibilityTestHelpers.FindUsingTaskByName("TaskName", p.UsingTasks).AssemblyName); } #endregion #region AssemblyFile /// <summary> /// AssemblyFile test, simple set in ctor then get. /// </summary> [Test] public void GetAssemblyFileName() { string assemblyFileName = "FileName.dll"; Assertion.AssertNotNull(SetandGetAssemblyFileName(assemblyFileName)); } /// <summary> /// AssemblyFile test, set special escaped characters in ctor then get. /// </summary> [Test] public void GetAssemblyFileNameSpecialCharsEscaped() { string assemblyFileName = @"%25%2a%3f%40%24%28%29%3b\"; Assertion.AssertNotNull(SetandGetAssemblyFileName(assemblyFileName)); } /// <summary> /// AssemblyFile test, set special non-escaped characters in ctor then get. /// </summary> [Test] public void GetAssemblyFileNameSpecialChars() { string assemblyFileName = @"%*?@$();\"; Assertion.AssertNotNull(SetandGetAssemblyFileName(assemblyFileName)); } /// <summary> /// AssemblyFile test, set to a scalar that has no property defined in the project, then get. /// </summary> [Test] [ExpectedException(typeof(InvalidProjectFileException))] public void GetAssemblyFileNameScalarThatIsNotSet() { string assemblyFileName = "$(fileName)"; Assertion.AssertNotNull(SetandGetAssemblyFileName(assemblyFileName)); } /// <summary> /// AssemblyFile test, set to scalar that is defined in the project, then get. Does Not Evaluate /// </summary> [Test] public void GetAssemblyFileNameScalarEvaluation() { string assemblyFileName = "$(fileName)"; Project p = new Project(new Engine()); p.SetProperty("fileName", "aFileName"); object o = p.EvaluatedItems; p.AddNewUsingTaskFromAssemblyFile("TaskName", assemblyFileName); o = p.EvaluatedItems; Assertion.AssertEquals(assemblyFileName, CompatibilityTestHelpers.FindUsingTaskByName("TaskName", p.UsingTasks).AssemblyFile); } /// <summary> /// AssemblyFile Test, get assembly file name, where the path is is over windows max path /// </summary> [Test] public void GetAssemblyFileNamePathTooLong() { string assemblyFileName = Path.Combine(CompatibilityTestHelpers.GenerateLongPath(255), "assemblyFileName.dll"); Assertion.AssertEquals(assemblyFileName, SetandGetAssemblyFileName(assemblyFileName)); } /// <summary> /// Condition Test, get the usingtask conidtion when set in the xml /// </summary> [Test] public void GetUsingTaskAssemblyFile_SetInXml() { Project p = new Project(new Engine()); p.LoadXml(TestData.ContentUsingTaskFile); object o = p.EvaluatedItems; Assertion.AssertEquals("AssemblyName.dll", CompatibilityTestHelpers.FindUsingTaskByName("TaskName", p.UsingTasks).AssemblyFile); } #endregion #region TaskName /// <summary> /// TaskName Test, simple get /// </summary> [Test] public void GetTaskName_SetInXml() { Project p = new Project(); p.LoadXml(TestData.ContentUsingTaskFile); object o = p.EvaluatedItems; Assertion.AssertNotNull(CompatibilityTestHelpers.FindUsingTaskByName("TaskName", p.UsingTasks)); } /// <summary> /// TaskName Test, scalars are not evaluated /// </summary> [Test] public void GetTaskNameScalar() { Project p = new Project(new Engine()); p.AddNewUsingTaskFromAssemblyName("$(name)", "assemblyName"); p.SetProperty("name", "TaskName"); object o = p.EvaluatedItems; Assertion.AssertNotNull(CompatibilityTestHelpers.FindUsingTaskByName("$(name)", p.UsingTasks)); } /// <summary> /// TaskName Test, scalars are not evaluated /// </summary> [Test] public void GetTaskNameSpeicalChars() { Project p = new Project(); p.AddNewUsingTaskFromAssemblyName(@"%*?@$();\", "assemblyName"); object o = p.EvaluatedItems; Assertion.AssertNotNull(CompatibilityTestHelpers.FindUsingTaskByName(@"%*?@$();\", p.UsingTasks)); } /// <summary> /// TaskName Test, scalars are not evaluated /// </summary> [Test] public void GetTaskNameSpeicalCharsEscaped() { Project p = new Project(new Engine()); p.AddNewUsingTaskFromAssemblyName(@"%25%2a%3f%40%24%28%29%3b\", "assemblyName"); object o = p.EvaluatedItems; Assertion.AssertNotNull(CompatibilityTestHelpers.FindUsingTaskByName(@"%25%2a%3f%40%24%28%29%3b\", p.UsingTasks)); } #endregion #region IsImported /// <summary> /// IsImported Test, assert true for an improted file. /// </summary> [Test] public void IsImported_true() { string importPath = String.Empty; try { importPath = ObjectModelHelpers.CreateFileInTempProjectDirectory("import.proj", TestData.ContentUsingTaskName); Project p = new Project(new Engine()); p.AddNewImport(importPath, "true"); Object o = p.EvaluatedProperties; Import import = CompatibilityTestHelpers.FindFirstMatchingImportByPath(p.Imports, importPath); import.Condition = null; Assertion.AssertEquals(true, CompatibilityTestHelpers.FindUsingTaskByName("TaskName", p.UsingTasks).IsImported); } finally { CompatibilityTestHelpers.RemoveFile(importPath); } } /// <summary> /// IsImported Test, assert true for an imported file. /// </summary> [Test] public void IsImported_false() { Project p = new Project(new Engine()); p.LoadXml(TestData.ContentUsingTaskFile); object o = p.EvaluatedProperties; Assertion.AssertEquals(false, CompatibilityTestHelpers.FindUsingTaskByName("TaskName", p.UsingTasks).IsImported); } #endregion #region Condition /// <summary> /// Condition Test, get condition when set in xml /// </summary> [Test] public void GetConditionSimple() { Project p = new Project(); p.LoadXml(TestData.ContentUsingTaskName); object o = p.EvaluatedProperties; Assertion.AssertEquals("true", CompatibilityTestHelpers.FindUsingTaskByName("TaskName", p.UsingTasks).Condition); } /// <summary> /// Condition Test, get when conditionis an expression /// </summary> [Test] public void GetConditionExpression() { Project p = new Project(); p.LoadXml(TestData.ContentUsingTaskFile); Assertion.AssertEquals("$(value)==true", CompatibilityTestHelpers.FindUsingTaskByName("TaskName", p.UsingTasks).Condition); } /// <summary> /// Condition Test, get condition in OM when set in xml /// </summary> [Test] public void GetUsingTaskCondition_SetInXml() { Project p = new Project(); p.LoadXml(TestData.ContentUsingTaskName); Assertion.AssertEquals("true", CompatibilityTestHelpers.FindUsingTaskByName("TaskName", p.UsingTasks).Condition); } #endregion /// <summary> /// Set an assembly file name, then retrieve it. /// </summary> private string SetandGetAssemblyFileName(string assemblyFileName) { Project p = new Project(); p.AddNewUsingTaskFromAssemblyFile("TaskName", assemblyFileName); object o = p.EvaluatedItems; UsingTask usingTask = CompatibilityTestHelpers.FindUsingTaskByName("TaskName", p.UsingTasks); return usingTask.AssemblyFile; } } }
using UnityEngine; namespace UnityStandardAssets.ImageEffects { [ExecuteInEditMode] [RequireComponent (typeof(Camera))] [AddComponentMenu("Image Effects/Rendering/Screen Space Ambient Occlusion")] public class ScreenSpaceAmbientOcclusion : MonoBehaviour { public enum SSAOSamples { Low = 0, Medium = 1, High = 2, } [Range(0.05f, 1.0f)] public float m_Radius = 0.4f; public SSAOSamples m_SampleCount = SSAOSamples.Medium; [Range(0.5f, 4.0f)] public float m_OcclusionIntensity = 1.5f; [Range(0, 4)] public int m_Blur = 2; [Range(1,6)] public int m_Downsampling = 2; [Range(0.2f, 2.0f)] public float m_OcclusionAttenuation = 1.0f; [Range(0.00001f, 0.5f)] public float m_MinZ = 0.01f; public Shader m_SSAOShader; private Material m_SSAOMaterial; public Texture2D m_RandomTexture; private bool m_Supported; private static Material CreateMaterial (Shader shader) { if (!shader) return null; Material m = new Material (shader); m.hideFlags = HideFlags.HideAndDontSave; return m; } private static void DestroyMaterial (Material mat) { if (mat) { DestroyImmediate (mat); mat = null; } } void OnDisable() { DestroyMaterial (m_SSAOMaterial); } void Start() { if (!SystemInfo.supportsImageEffects || !SystemInfo.SupportsRenderTextureFormat (RenderTextureFormat.Depth)) { m_Supported = false; enabled = false; return; } CreateMaterials (); if (!m_SSAOMaterial || m_SSAOMaterial.passCount != 5) { m_Supported = false; enabled = false; return; } //CreateRandomTable (26, 0.2f); m_Supported = true; } void OnEnable () { GetComponent<Camera>().depthTextureMode |= DepthTextureMode.DepthNormals; } private void CreateMaterials () { if (!m_SSAOMaterial && m_SSAOShader.isSupported) { m_SSAOMaterial = CreateMaterial (m_SSAOShader); m_SSAOMaterial.SetTexture ("_RandomTexture", m_RandomTexture); } } [ImageEffectOpaque] void OnRenderImage (RenderTexture source, RenderTexture destination) { if (!m_Supported || !m_SSAOShader.isSupported) { enabled = false; return; } CreateMaterials (); m_Downsampling = Mathf.Clamp (m_Downsampling, 1, 6); m_Radius = Mathf.Clamp (m_Radius, 0.05f, 1.0f); m_MinZ = Mathf.Clamp (m_MinZ, 0.00001f, 0.5f); m_OcclusionIntensity = Mathf.Clamp (m_OcclusionIntensity, 0.5f, 4.0f); m_OcclusionAttenuation = Mathf.Clamp (m_OcclusionAttenuation, 0.2f, 2.0f); m_Blur = Mathf.Clamp (m_Blur, 0, 4); // Render SSAO term into a smaller texture RenderTexture rtAO = RenderTexture.GetTemporary (source.width / m_Downsampling, source.height / m_Downsampling, 0); float fovY = GetComponent<Camera>().fieldOfView; float far = GetComponent<Camera>().farClipPlane; float y = Mathf.Tan (fovY * Mathf.Deg2Rad * 0.5f) * far; float x = y * GetComponent<Camera>().aspect; m_SSAOMaterial.SetVector ("_FarCorner", new Vector3(x,y,far)); int noiseWidth, noiseHeight; if (m_RandomTexture) { noiseWidth = m_RandomTexture.width; noiseHeight = m_RandomTexture.height; } else { noiseWidth = 1; noiseHeight = 1; } m_SSAOMaterial.SetVector ("_NoiseScale", new Vector3 ((float)rtAO.width / noiseWidth, (float)rtAO.height / noiseHeight, 0.0f)); m_SSAOMaterial.SetVector ("_Params", new Vector4( m_Radius, m_MinZ, 1.0f / m_OcclusionAttenuation, m_OcclusionIntensity)); bool doBlur = m_Blur > 0; Graphics.Blit (doBlur ? null : source, rtAO, m_SSAOMaterial, (int)m_SampleCount); if (doBlur) { // Blur SSAO horizontally RenderTexture rtBlurX = RenderTexture.GetTemporary (source.width, source.height, 0); m_SSAOMaterial.SetVector ("_TexelOffsetScale", new Vector4 ((float)m_Blur / source.width, 0,0,0)); m_SSAOMaterial.SetTexture ("_SSAO", rtAO); Graphics.Blit (null, rtBlurX, m_SSAOMaterial, 3); RenderTexture.ReleaseTemporary (rtAO); // original rtAO not needed anymore // Blur SSAO vertically RenderTexture rtBlurY = RenderTexture.GetTemporary (source.width, source.height, 0); m_SSAOMaterial.SetVector ("_TexelOffsetScale", new Vector4 (0, (float)m_Blur/source.height, 0,0)); m_SSAOMaterial.SetTexture ("_SSAO", rtBlurX); Graphics.Blit (source, rtBlurY, m_SSAOMaterial, 3); RenderTexture.ReleaseTemporary (rtBlurX); // blurX RT not needed anymore rtAO = rtBlurY; // AO is the blurred one now } // Modulate scene rendering with SSAO m_SSAOMaterial.SetTexture ("_SSAO", rtAO); Graphics.Blit (source, destination, m_SSAOMaterial, 4); RenderTexture.ReleaseTemporary (rtAO); } /* private void CreateRandomTable (int count, float minLength) { Random.seed = 1337; Vector3[] samples = new Vector3[count]; // initial samples for (int i = 0; i < count; ++i) samples[i] = Random.onUnitSphere; // energy minimization: push samples away from others int iterations = 100; while (iterations-- > 0) { for (int i = 0; i < count; ++i) { Vector3 vec = samples[i]; Vector3 res = Vector3.zero; // minimize with other samples for (int j = 0; j < count; ++j) { Vector3 force = vec - samples[j]; float fac = Vector3.Dot (force, force); if (fac > 0.00001f) res += force * (1.0f / fac); } samples[i] = (samples[i] + res * 0.5f).normalized; } } // now scale samples between minLength and 1.0 for (int i = 0; i < count; ++i) { samples[i] = samples[i] * Random.Range (minLength, 1.0f); } string table = string.Format ("#define SAMPLE_COUNT {0}\n", count); table += "const float3 RAND_SAMPLES[SAMPLE_COUNT] = {\n"; for (int i = 0; i < count; ++i) { Vector3 v = samples[i]; table += string.Format("\tfloat3({0},{1},{2}),\n", v.x, v.y, v.z); } table += "};\n"; Debug.Log (table); } */ } }
using System; using System.IO; using System.Collections; using System.Collections.Generic; using System.Text; using System.Runtime.Serialization.Formatters.Binary; using System.IO.Compression; using System.Threading; using Volte.Data.Json; namespace Volte.Data.Dapper { public class ZZCache { const string ZFILE_NAME = "ZZCache"; private readonly StringBuilder sb = new StringBuilder(); private static ZZCache _Cache; private static Queue<JSONTable> _que = new Queue<JSONTable>(); private static LRU<string, string> _cache = new LRU<string, string>(5000); private static LRU<string, JSONTable> _cache_Cell = new LRU<string, JSONTable>(5000); private static LRU<string, JSONArray> _JSONObject = new LRU<string, JSONArray>(10); private static object _PENDING = new object(); private static string _Cache_Location = ""; private bool _Running = false; private Thread _worker; public static ZZCache getInstance() { if (_Cache == null) { _que = new Queue<JSONTable>(); _Cache = new ZZCache(); _Cache.Running(); Initialize(); } return _Cache; } internal void Running() { _worker = new Thread(new ThreadStart(_Do_Worker)); _worker.IsBackground = true; _worker.Start(); } public static void Initialize() { if (_Cache_Location == "") { try { string rootPath = AppDomain.CurrentDomain.BaseDirectory; string separator = Path.DirectorySeparatorChar.ToString(); rootPath = rootPath.Replace("/", separator); _Cache_Location = rootPath + "temp" + separator + "cache" + separator; ZZLogger.Debug(ZFILE_NAME , _Cache_Location); if (!Directory.Exists(_Cache_Location)) { Directory.CreateDirectory(_Cache_Location); } } catch (Exception ex) { ZZLogger.Debug(ZFILE_NAME, ex); } } ZZCache.getInstance().Running(); } public static string Type(string fileName) { if (_JSONObject.GetValue(fileName) != null) { return "N"; } else if (_cache_Cell.GetValue(fileName) != null) { return "T"; } else { Initialize(); string _fileName = _Cache_Location + fileName + "T"; if (File.Exists(_fileName)) { return "T"; } else { return ""; } } } public static void WriteJSONArray(string fileName, JSONArray _Values) { _JSONObject.SetValue(fileName, _Values); } public static JSONArray ReadJSONArray(string fileName) { JSONArray _Values = _JSONObject.GetValue(fileName); if (_Values == null) { _Values = new JSONArray(); } return _Values; } public static void WriteJSONTable(string fileName, JSONTable _JSONTable) { Initialize(); _cache_Cell.SetValue(fileName, _JSONTable); _que.Enqueue(_JSONTable); ZZLogger.Debug(ZFILE_NAME , _JSONTable.ToString()); } internal void _Do_Worker() { if (_Running) { return; } _Running = true; while (true) { try { ZZLogger.Debug(ZFILE_NAME , _Cache_Location); if (_que.Count > 0) { lock (_PENDING) { Initialize(); JSONTable _JSONTable= _que.Dequeue(); try { string _fileName = _Cache_Location + _JSONTable.Variable.GetValue("lnk_DataUrl")+ "T"; ZZLogger.Debug(ZFILE_NAME , _fileName); using(FileStream fs = new FileStream(_fileName , FileMode.Create)) { BinaryFormatter formatter = new BinaryFormatter(); GZipStream Compress = new GZipStream(fs, CompressionMode.Compress); formatter.Serialize(Compress, _JSONTable); Compress.Close(); } } catch (Exception ex) { ZZLogger.Debug(ZFILE_NAME, ex); } } } } catch (Exception e) { } Thread.Sleep(10000); } } public static JSONTable ReadJSONTable(string fileName) { JSONTable _JSONTable = _cache_Cell.GetValue(fileName); if (_JSONTable == null) { ZZLogger.Debug(ZFILE_NAME , "load from " + fileName); Initialize(); string _fileName = _Cache_Location + fileName + "T"; if (File.Exists(_fileName)) { using(FileStream fs = new FileStream(_fileName , FileMode.Open)) { GZipStream dStream = new GZipStream(fs, CompressionMode.Decompress, true); BinaryFormatter formatter = new BinaryFormatter(); _JSONTable = (JSONTable)formatter.Deserialize(dStream); if (_JSONTable.RecordCount<2000){ _cache_Cell.SetValue(fileName, _JSONTable); } } } else { _JSONTable = new JSONTable(); } } else { ZZLogger.Debug(ZFILE_NAME , "load memory"); } return _JSONTable; } public static object Read(string fileName) { Initialize(); fileName = _Cache_Location + fileName; string data = ""; if (File.Exists(fileName)) { using(StreamReader sr = new StreamReader(fileName)) { data = sr.ReadToEnd(); } } return data; } public static void Write(string fileName, object Data) { string id = Path.GetFileNameWithoutExtension(fileName); string _path = Path.GetDirectoryName(fileName); if (_path == "") { Initialize(); fileName = _Cache_Location + fileName; } else if (!Directory.Exists(_path)) { Directory.CreateDirectory(_path); } StreamWriter swer = new StreamWriter(fileName, false); swer.Write(Data); swer.Flush(); swer.Close(); } } }
//! \file ImagePRS.cs //! \date Sat Mar 28 00:15:43 2015 //! \brief Marble engine image format. // // Copyright (C) 2015 by morkt // // 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.ComponentModel.Composition; using System.IO; using System.Text; using System.Windows; using System.Windows.Media; using System.Windows.Media.Imaging; using GameRes.Utility; namespace GameRes.Formats.Marble { internal class PrsMetaData : ImageMetaData { public byte Flag; public uint PackedSize; } [Export(typeof(ImageFormat))] public class PrsFormat : ImageFormat { public override string Tag { get { return "PRS"; } } public override string Description { get { return "Marble engine image format"; } } public override uint Signature { get { return 0; } } public override void Write (Stream file, ImageData image) { throw new NotImplementedException ("PrsFormat.Write not implemented"); } public override ImageMetaData ReadMetaData (IBinaryStream stream) { var header = stream.ReadHeader (0x10); if (header[0] != 'Y' || header[1] != 'B') return null; int bpp = header[3]; if (bpp != 3 && bpp != 4) return null; return new PrsMetaData { Width = header.ToUInt16 (12), Height = header.ToUInt16 (14), BPP = 8 * bpp, Flag = header[2], PackedSize = header.ToUInt32 (4), }; } public override ImageData Read (IBinaryStream stream, ImageMetaData info) { using (var reader = new Reader (stream, (PrsMetaData)info)) { reader.Unpack(); return ImageData.Create (info, reader.Format, null, reader.Data, reader.Stride); } } internal class Reader : IDisposable { IBinaryStream m_input; byte[] m_output; uint m_size; byte m_flag; int m_depth; public byte[] Data { get { return m_output; } } public PixelFormat Format { get; private set; } public int Stride { get; private set; } public Reader (IBinaryStream file, PrsMetaData info) { m_input = file; m_size = info.PackedSize; m_flag = info.Flag; m_depth = info.BPP / 8; if (3 == m_depth) Format = PixelFormats.Bgr24; else Format = PixelFormats.Bgra32; Stride = (int)info.Width * m_depth; m_output = new byte[Stride * (int)info.Height]; } static readonly int[] LengthTable = InitLengthTable(); private static int[] InitLengthTable () { var length_table = new int[256]; for (int i = 0; i < 0xfe; ++i) length_table[i] = i + 3; length_table[0xfe] = 0x400; length_table[0xff] = 0x1000; return length_table; } public void Unpack () { m_input.Position = 0x10; int dst = 0; int remaining = (int)m_size; int bit = 0; int ctl = 0; while (remaining > 0 && dst < m_output.Length) { bit >>= 1; if (0 == bit) { ctl = m_input.ReadUInt8(); --remaining; bit = 0x80; } if (remaining <= 0) break; if (0 == (ctl & bit)) { m_output[dst++] = m_input.ReadUInt8(); --remaining; continue; } int b = m_input.ReadUInt8(); --remaining; int length = 0; int shift = 0; if (0 != (b & 0x80)) { if (remaining <= 0) break; shift = m_input.ReadUInt8(); --remaining; shift |= (b & 0x3f) << 8; if (0 != (b & 0x40)) { if (remaining <= 0) break; int offset = m_input.ReadUInt8(); --remaining; length = LengthTable[offset]; } else { length = (shift & 0xf) + 3; shift >>= 4; } } else { length = b >> 2; b &= 3; if (3 == b) { length += 9; int read = m_input.Read (m_output, dst, length); if (read < length) break; remaining -= length; dst += length; continue; } shift = length; length = b + 2; } ++shift; if (dst < shift) throw new InvalidFormatException ("Invalid offset value"); length = Math.Min (length, m_output.Length - dst); Binary.CopyOverlapped (m_output, dst-shift, dst, length); dst += length; } if ((m_flag & 0x80) != 0) { for (int i = m_depth; i < m_output.Length; ++i) m_output[i] += m_output[i-m_depth]; } if (4 == m_depth && IsDummyAlphaChannel()) Format = PixelFormats.Bgr32; } bool IsDummyAlphaChannel () { byte alpha = m_output[3]; if (0xFF == alpha) return false; for (int i = 7; i < m_output.Length; i += 4) if (m_output[i] != alpha) return false; return true; } #region IDisposable Members bool disposed = false; public void Dispose () { Dispose (true); GC.SuppressFinalize (this); } protected virtual void Dispose (bool disposing) { if (!disposed) { if (disposing) { m_input.Dispose(); } disposed = true; } } #endregion } } }
// <copyright file="DefaultCompressedStorage.cs" company="Microsoft Open Technologies, Inc."> // Copyright 2011-2013 Microsoft Open Technologies, Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Threading; namespace Microsoft.Owin.Compression.Storage { public sealed class DefaultCompressedStorage : ICompressedStorage { private readonly IDictionary<CompressedKey, ItemHandle> _items = new Dictionary<CompressedKey, ItemHandle>(CompressedKey.CompressedKeyComparer); private readonly object _itemsLock = new object(); private string _storagePath; private FileStream _lockFile; public void Initialize() { // TODO: guard against many things, including re-execution or string basePath = Path.Combine(Path.GetTempPath(), "MsOwinCompression"); _storagePath = Path.Combine(basePath, Guid.NewGuid().ToString("n")); string lockPath = Path.Combine(_storagePath, "_lock"); Directory.CreateDirectory(_storagePath); _lockFile = new FileStream(lockPath, FileMode.Create, FileAccess.Write, FileShare.None); ThreadPool.QueueUserWorkItem(_ => CleanupReleasedStorage(basePath)); } public void Dispose() { // TODO: implement ~finalizer, etc ItemHandle[] items; lock (_itemsLock) { items = _items.Values.ToArray(); _items.Clear(); } var exceptions = new List<Exception>(); foreach (var item in items) { try { item.Dispose(); } catch (Exception ex) { exceptions.Add(ex); } } try { _lockFile.Close(); _lockFile = null; } catch (Exception ex) { exceptions.Add(ex); } try { Directory.Delete(_storagePath, true); } catch (Exception ex) { exceptions.Add(ex); } if (exceptions.Count != 0) { // TODO: Log, don't throw from dispose. Debug.Fail("Cleanup exceptions: " + exceptions.Select(ex => ex.ToString()).Aggregate((s1, s2) => s1 + "\r\n" + s2)); // throw new AggregateException(exceptions); } } private void CleanupReleasedStorage(string basePath) { foreach (var directory in Directory.GetDirectories(basePath)) { string directoryPath = Path.Combine(basePath, Path.GetFileName(directory)); if (string.Equals(directoryPath, _storagePath, StringComparison.OrdinalIgnoreCase)) { // don't try to cleanup ourselves continue; } string lockPath = Path.Combine(directoryPath, "_lock"); if (File.Exists(lockPath)) { var lockInfo = new FileInfo(lockPath); if (lockInfo.LastAccessTimeUtc > DateTime.UtcNow.Subtract(TimeSpan.FromHours(36))) { // less than a day and a half - don't try cleanup yet to avoid causing // an exception if it's still in use continue; } bool stillInUse = false; try { File.Delete(lockPath); } catch { stillInUse = true; } if (stillInUse) { // can't delete - lock file still in use continue; } } Directory.Delete(directoryPath, true); } } public ICompressedItemHandle Open(CompressedKey key) { lock (_itemsLock) { ItemHandle handle; if (_items.TryGetValue(key, out handle)) { return handle.Clone(); } return null; } } public ICompressedItemBuilder Create(CompressedKey key) { // TODO: break down into buckets to avoid files-per-folder limits string physicalPath = Path.Combine(_storagePath, Guid.NewGuid().ToString("n")); return new ItemBuilder(key, physicalPath); } [SuppressMessage("Microsoft.Reliability", "CA2000:DisposeObjectsBeforeLosingScope", Justification = "False positive")] public ICompressedItemHandle Commit(ICompressedItemBuilder builder) { var itemBuilder = (ItemBuilder)builder; CompressedKey key = itemBuilder.Key; var item = new Item { PhysicalPath = itemBuilder.PhysicalPath, CompressedLength = itemBuilder.Stream.Length }; itemBuilder.Stream.Close(); var handle = new ItemHandle(item); AddHandleInDictionary(key, handle); return handle; } private void AddHandleInDictionary(CompressedKey key, ItemHandle handle) { lock (_itemsLock) { ItemHandle addingHandle = handle.Clone(); ItemHandle existingHandle; if (_items.TryGetValue(key, out existingHandle)) { existingHandle.Dispose(); } _items[key] = addingHandle; } } private class ItemBuilder : ICompressedItemBuilder { public ItemBuilder(CompressedKey key, string physicalPath) { Key = key; PhysicalPath = physicalPath; Stream = new FileStream(PhysicalPath, FileMode.Create, FileAccess.Write, FileShare.None); } public CompressedKey Key { get; private set; } public string PhysicalPath { get; private set; } public Stream Stream { get; private set; } } private class Item { private int _references; public string PhysicalPath { get; set; } public long CompressedLength { get; set; } public void AddReference() { Interlocked.Increment(ref _references); } public void Release() { if (Interlocked.Decrement(ref _references) == 0) { if (File.Exists(PhysicalPath)) { File.Delete(PhysicalPath); } } } } private class ItemHandle : ICompressedItemHandle { private Item _item; private bool _disposed; public ItemHandle(Item item) { item.AddReference(); _item = item; } ~ItemHandle() { Dispose(false); } public string PhysicalPath { get { return _item.PhysicalPath; } } public long CompressedLength { get { return _item.CompressedLength; } } public ItemHandle Clone() { return new ItemHandle(_item); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } private void Dispose(bool disposing) { if (!_disposed) { Item item = Interlocked.Exchange(ref _item, null); if (item != null) { item.Release(); } _disposed = true; } } } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using NLogReader.WebAPI.Areas.HelpPage.ModelDescriptions; using NLogReader.WebAPI.Areas.HelpPage.Models; namespace NLogReader.WebAPI.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
/************************************************************************************ Copyright : Copyright 2014 Oculus VR, LLC. All Rights reserved. Licensed under the Oculus VR Rift SDK License Version 3.2 (the "License"); you may not use the Oculus VR Rift SDK except in compliance with the License, which is provided at the time of installation or download, or which otherwise accompanies this software in either electronic or hard copy form. You may obtain a copy of the License at http://www.oculusvr.com/licenses/LICENSE-3.2 Unless required by applicable law or agreed to in writing, the Oculus VR SDK 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.Runtime.InteropServices; using UnityEngine; /// <summary> /// OVRGamepadController is an interface class to a gamepad controller. /// </summary> public class OVRGamepadController : MonoBehaviour { /// <summary> An axis on the gamepad. </summary> public enum Axis { None = -1, LeftXAxis = 0, LeftYAxis, RightXAxis, RightYAxis, LeftTrigger, RightTrigger, Max, }; /// <summary> A button on the gamepad. </summary> public enum Button { None = -1, A = 0, B, X, Y, Up, Down, Left, Right, Start, Back, LStick, RStick, LeftShoulder, RightShoulder, Max }; /// <summary> /// The default Android Unity input name for each gamepad Axis. /// </summary> public static string[] AndroidAxisNames = new string[(int)Axis.Max] { "Left_X_Axis", "Left_Y_Axis", "Right_X_Axis", "Right_Y_Axis", "LeftTrigger", "RightTrigger", }; /// <summary> /// The default Android Unity input name for each gamepad Button. /// </summary> public static string[] AndroidButtonNames = new string[(int)Button.Max] { "Button A", "Button B", "Button X", "Button Y", "Up", "Down", "Left", "Right", "Start", "Back", "LStick", "RStick", "LeftShoulder", "RightShoulder", }; /// <summary> /// The default Unity input name for each gamepad Axis. /// </summary> public static string[] DesktopAxisNames = new string[(int)Axis.Max] { "Desktop_Left_X_Axis", "Desktop_Left_Y_Axis", "Desktop_Right_X_Axis", "Desktop_Right_Y_Axis", "Desktop_LeftTrigger", "Desktop_RightTrigger", }; /// <summary> /// The default Unity input name for each gamepad Button. /// </summary> public static string[] DesktopButtonNames = new string[(int)Button.Max] { "Desktop_Button A", "Desktop_Button B", "Desktop_Button X", "Desktop_Button Y", "Desktop_Up", "Desktop_Down", "Desktop_Left", "Desktop_Right", "Desktop_Start", "Desktop_Back", "Desktop_LStick", "Desktop_RStick", "Desktop_LeftShoulder", "Desktop_RightShoulder", }; public static int[] DefaultButtonIds = new int[(int)Button.Max] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 }; /// <summary> /// The current Unity input names for all gamepad axes. /// </summary> public static string[] AxisNames = null; /// <summary> /// The current Unity input names for all gamepad buttons. /// </summary> public static string[] ButtonNames = null; static OVRGamepadController() { #if UNITY_ANDROID && !UNITY_EDITOR SetAxisNames(AndroidAxisNames); SetButtonNames(AndroidButtonNames); #else SetAxisNames(DesktopAxisNames); SetButtonNames(DesktopButtonNames); #endif } /// <summary> /// Sets the current names for all gamepad axes. /// </summary> public static void SetAxisNames(string[] axisNames) { AxisNames = axisNames; } /// <summary> /// Sets the current Unity input names for all gamepad buttons. /// </summary> /// <param name="buttonNames">Button names.</param> public static void SetButtonNames(string[] buttonNames) { ButtonNames = buttonNames; } /// <summary> Handles an axis read event. </summary> public delegate float ReadAxisDelegate(Axis axis); /// <summary> Handles an button read event. </summary> public delegate bool ReadButtonDelegate(Button button); /// <summary> Occurs when an axis has been read. </summary> public static ReadAxisDelegate ReadAxis = DefaultReadAxis; /// <summary> Occurs when a button has been read. </summary> public static ReadButtonDelegate ReadButton = DefaultReadButton; #if (!UNITY_ANDROID || UNITY_EDITOR) private static bool GPC_Available = false; //------------------------- // Public access to plugin functions /// <summary> /// GPC_Initialize. /// </summary> /// <returns><c>true</c>, if c_ initialize was GPed, <c>false</c> otherwise.</returns> public static bool GPC_Initialize() { if (!OVRManager.instance.isSupportedPlatform) return false; return OVR_GamepadController_Initialize(); } /// <summary> /// GPC_Destroy /// </summary> /// <returns><c>true</c>, if c_ destroy was GPed, <c>false</c> otherwise.</returns> public static bool GPC_Destroy() { if (!OVRManager.instance.isSupportedPlatform) return false; return OVR_GamepadController_Destroy(); } /// <summary> /// GPC_Update /// </summary> /// <returns><c>true</c>, if c_ update was GPed, <c>false</c> otherwise.</returns> public static bool GPC_Update() { if (!OVRManager.instance.isSupportedPlatform) return false; return OVR_GamepadController_Update(); } #endif /// <summary> /// GPC_GetAxis /// The default delegate for retrieving axis info. /// </summary> /// <returns>The current value of the axis.</returns> /// <param name="axis">Axis.</param> public static float DefaultReadAxis(Axis axis) { #if UNITY_ANDROID && !UNITY_EDITOR return Input.GetAxis(AxisNames[(int)axis]); #else return OVR_GamepadController_GetAxis((int)axis); #endif } /// <summary> /// Returns the current value of the given Axis. /// </summary> public static float GPC_GetAxis(Axis axis) { if (ReadAxis == null) return 0f; return ReadAxis(axis); } public static void SetReadAxisDelegate(ReadAxisDelegate del) { ReadAxis = del; } /// <summary> /// Uses XInput to check if the given Button is down. /// </summary> public static bool DefaultReadButton(Button button) { #if UNITY_ANDROID && !UNITY_EDITOR return Input.GetButton(ButtonNames[(int)button]); #else return OVR_GamepadController_GetButton((int)button); #endif } /// <summary> /// Returns true if the given Button is down. /// </summary> public static bool GPC_GetButton(Button button) { if (ReadButton == null) return false; return ReadButton(button); } public static void SetReadButtonDelegate(ReadButtonDelegate del) { ReadButton = del; } /// <summary> /// Returns true if the gamepad controller is available. /// </summary> public static bool GPC_IsAvailable() { #if !UNITY_ANDROID || UNITY_EDITOR return GPC_Available; #else return true; #endif } void GPC_Test() { // Axis test Debug.Log(string.Format("LT:{0:F3} RT:{1:F3} LX:{2:F3} LY:{3:F3} RX:{4:F3} RY:{5:F3}", GPC_GetAxis(Axis.LeftTrigger), GPC_GetAxis(Axis.RightTrigger), GPC_GetAxis(Axis.LeftXAxis), GPC_GetAxis(Axis.LeftYAxis), GPC_GetAxis(Axis.RightXAxis), GPC_GetAxis(Axis.RightYAxis))); // Button test Debug.Log(string.Format("A:{0} B:{1} X:{2} Y:{3} U:{4} D:{5} L:{6} R:{7} SRT:{8} BK:{9} LS:{10} RS:{11} L1:{12} R1:{13}", GPC_GetButton(Button.A), GPC_GetButton(Button.B), GPC_GetButton(Button.X), GPC_GetButton(Button.Y), GPC_GetButton(Button.Up), GPC_GetButton(Button.Down), GPC_GetButton(Button.Left), GPC_GetButton(Button.Right), GPC_GetButton(Button.Start), GPC_GetButton(Button.Back), GPC_GetButton(Button.LStick), GPC_GetButton(Button.RStick), GPC_GetButton(Button.LeftShoulder), GPC_GetButton(Button.RightShoulder))); } #if !UNITY_ANDROID || UNITY_EDITOR void Start() { GPC_Available = GPC_Initialize(); } void Update() { GPC_Available = GPC_Update(); } void OnDestroy() { GPC_Destroy(); GPC_Available = false; } public const string LibOVR = "OculusPlugin"; [DllImport(LibOVR, CallingConvention = CallingConvention.Cdecl)] public static extern bool OVR_GamepadController_Initialize(); [DllImport(LibOVR, CallingConvention = CallingConvention.Cdecl)] public static extern bool OVR_GamepadController_Destroy(); [DllImport(LibOVR, CallingConvention = CallingConvention.Cdecl)] public static extern bool OVR_GamepadController_Update(); [DllImport(LibOVR, CallingConvention = CallingConvention.Cdecl)] public static extern float OVR_GamepadController_GetAxis(int axis); [DllImport(LibOVR, CallingConvention = CallingConvention.Cdecl)] public static extern bool OVR_GamepadController_GetButton(int button); #endif }
// // Parser.cs // // Author: // Aaron Bockover <abockover@novell.com> // // Copyright (C) 2007-2008 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Globalization; namespace Hyena.SExpEngine { public class ParserException : ApplicationException { public ParserException(string token, int line, int col, Exception inner) : base(String.Format( "Parser exception at token `{0}' [{1},{2}]: {3}", token, line, col, inner == null ? "Unknown error" : inner.Message), inner) { } } public class Parser { private static Regex number_regex = new Regex(@"^[-+]?(0x[\dA-Fa-f]+)?[\d]*\.?[\d]*([eE][-+]?[\d]+)?$"); private static System.Globalization.CultureInfo culture_info = new System.Globalization.CultureInfo("en-US"); private StreamReader reader; private bool debug; private StringBuilder current_token; private TreeNode root_node ; private TreeNode current_parent; private int scope; private int line; private int column; public Parser() { } public TreeNode Parse(string input) { return Parse(new MemoryStream(Encoding.UTF8.GetBytes(input))); } public TreeNode Parse(Stream stream) { return Parse(new StreamReader(stream)); } public TreeNode Parse(StreamReader reader) { this.reader = reader; current_token = new StringBuilder(); root_node = new TreeNode(); current_parent = root_node; scope = 0; line = 1; column = 0; try { Tokenize(); if(scope != 0) { throw new ApplicationException("Scope does pop back to zero"); } } catch(Exception e) { throw new ParserException(current_token.ToString(), line, column, e); } return root_node; } private void Tokenize() { bool in_string = false; bool in_comment = false; while(true) { int ich = reader.Read(); char ch = (char)ich; if(ich < 0) { break; } if(ch == '\n') { line++; column = 0; } else { column++; } if(in_comment) { if(ch == '\r' || ch == '\n') { in_comment = false; } continue; } switch(ch) { case '(': case ')': if(!in_string) { TokenPush(false); if(ch == '(') { ScopePush(); } else { ScopePop(); } } else { current_token.Append(ch); } break; case '"': if(in_string) { in_string = false; TokenPush(true); } else { in_string = true; } break; case '\\': if((char)reader.Peek() == '"') { current_token.Append((char)reader.Read()); } break; case ';': if(in_string) { current_token.Append(ch); } else { TokenPush(false); in_comment = true; } break; default: if(Char.IsWhiteSpace(ch)) { if(in_string) { current_token.Append(ch); } else { TokenPush(false); } } else { current_token.Append(ch); } break; } } TokenPush(false); reader.Close(); } private void ScopePush() { current_parent = new TreeNode(current_parent); scope++; } private void ScopePop() { current_parent = current_parent.Parent; scope--; } private void TokenPush(bool as_string) { if(current_token.Length == 0 && !as_string) { return; } TreeNode node = null; string token = current_token.ToString(); if(Debug) { Console.Write("{3}[{0}] TOKEN({4},{5}): [{2}{1}{2}]", scope, token, as_string ? "\"" : String.Empty, String.Empty.PadLeft(scope - 1, ' '), line, column - current_token.Length); } if(as_string) { node = new StringLiteral(token); } else if(token == "#t") { node = new BooleanLiteral(true); } else if(token == "#f") { node = new BooleanLiteral(false); } else if(token.Length > 0 && token != "." && token != "-" && token != "+" && number_regex.IsMatch(token)) { try { if(token.StartsWith("0x") || token.StartsWith("-0x")) { int offset = token[0] == '-' ? 3 : 2; int value = Int32.Parse(token.Substring(offset), NumberStyles.HexNumber, culture_info.NumberFormat); node = new IntLiteral(value * (offset == 3 ? -1 : 1)); } else if(token.Contains(".")) { node = new DoubleLiteral(Double.Parse(token, NumberStyles.Float, culture_info.NumberFormat)); } else { node = new IntLiteral(Int32.Parse(token, NumberStyles.Integer, culture_info.NumberFormat)); } } catch { throw new FormatException("Invalid number format: " + token); } } else { node = new FunctionNode(token); } if(Debug) { Console.WriteLine(" => [{0}]", node); } node.Line = line; node.Column = column; current_parent.AddChild(node); current_token.Remove(0, current_token.Length); } public bool Debug { get { return debug; } set { debug = value; } } } }
// DeflaterOutputStream.cs // // Copyright (C) 2001 Mike Krueger // // This file was translated from java, it was part of the GNU Classpath // Copyright (C) 2001 Free Software Foundation, Inc. // // 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. // // Linking this library statically or dynamically with other modules is // making a combined work based on this library. Thus, the terms and // conditions of the GNU General Public License cover the whole // combination. // // As a special exception, the copyright holders of this library give you // permission to link this library with independent modules to produce an // executable, regardless of the license terms of these independent // modules, and to copy and distribute the resulting executable under // terms of your choice, provided that you also meet, for each linked // independent module, the terms and conditions of the license of that // module. An independent module is a module which is not derived from // or based on this library. If you modify this library, you may extend // this exception to your version of the library, but you are not // obligated to do so. If you do not wish to do so, delete this // exception statement from your version. using System; using System.IO; using ICSharpCode.SharpZipLib.Checksums; namespace ICSharpCode.SharpZipLib.Zip.Compression.Streams { /// <summary> /// A special stream deflating or compressing the bytes that are /// written to it. It uses a Deflater to perform actual deflating.<br/> /// Authors of the original java version : Tom Tromey, Jochen Hoenicke /// </summary> public class InteractiveDeflaterOutputStream : Stream { /// <summary> /// Generate a table for a byte-wise 32-bit CRC calculation on the polynomial: /// x^32+x^26+x^23+x^22+x^16+x^12+x^11+x^10+x^8+x^7+x^5+x^4+x^2+x+1. /// /// Polynomials over GF(2) are represented in binary, one bit per coefficient, /// with the lowest powers in the most significant bit. Then adding polynomials /// is just exclusive-or, and multiplying a polynomial by x is a right shift by /// one. If we call the above polynomial p, and represent a byte as the /// polynomial q, also with the lowest power in the most significant bit (so the /// byte 0xb1 is the polynomial x^7+x^3+x+1), then the CRC is (q*x^32) mod p, /// where a mod b means the remainder after dividing a by b. /// /// This calculation is done using the shift-register method of multiplying and /// taking the remainder. The register is initialized to zero, and for each /// incoming bit, x^32 is added mod p to the register if the bit is a one (where /// x^32 mod p is p+x^32 = x^26+...+1), and the register is multiplied mod p by /// x (which is shifting right by one and adding x^32 mod p if the bit shifted /// out is a one). We start with the highest power (least significant bit) of /// q and repeat for all eight bits of q. /// /// The table is simply the CRC of all possible eight bit values. This is all /// the information needed to generate CRC's on data a byte at a time for all /// combinations of CRC register values and incoming bytes. /// </summary> public sealed class Crc32 : IChecksum { readonly static uint CrcSeed = 0xFFFFFFFF; readonly static uint[] CrcTable = new uint[] { 0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3, 0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988, 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91, 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE, 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, 0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5, 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172, 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B, 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940, 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59, 0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F, 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924, 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D, 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433, 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818, 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01, 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457, 0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65, 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2, 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB, 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0, 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9, 0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F, 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD, 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A, 0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683, 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8, 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1, 0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE, 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7, 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC, 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5, 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B, 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79, 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236, 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F, 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D, 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A, 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713, 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, 0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777, 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C, 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45, 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2, 0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB, 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9, 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF, 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94, 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D }; internal static uint ComputeCrc32(uint oldCrc, byte bval) { return (uint)(Crc32.CrcTable[(oldCrc ^ bval) & 0xFF] ^ (oldCrc >> 8)); } /// <summary> /// The crc data checksum so far. /// </summary> uint crc = 0; /// <summary> /// Returns the CRC32 data checksum computed so far. /// </summary> public long Value { get { return (long)crc; } set { crc = (uint)value; } } /// <summary> /// Resets the CRC32 data checksum as if no update was ever called. /// </summary> public void Reset() { crc = 0; } /// <summary> /// Updates the checksum with the int bval. /// </summary> /// <param name = "bval"> /// the byte is taken as the lower 8 bits of bval /// </param> public void Update(int bval) { crc ^= CrcSeed; crc = CrcTable[(crc ^ bval) & 0xFF] ^ (crc >> 8); crc ^= CrcSeed; } /// <summary> /// Updates the checksum with the bytes taken from the array. /// </summary> /// <param name="buffer"> /// buffer an array of bytes /// </param> public void Update(byte[] buffer) { Update(buffer, 0, buffer.Length); } /// <summary> /// Adds the byte array to the data checksum. /// </summary> /// <param name = "buf"> /// the buffer which contains the data /// </param> /// <param name = "off"> /// the offset in the buffer where the data starts /// </param> /// <param name = "len"> /// the length of the data /// </param> public void Update(byte[] buf, int off, int len) { if (buf == null) { throw new ArgumentNullException("buf"); } if (off < 0 || len < 0 || off + len > buf.Length) { throw new ArgumentOutOfRangeException(); } crc ^= CrcSeed; while (--len >= 0) { crc = CrcTable[(crc ^ buf[off++]) & 0xFF] ^ (crc >> 8); } crc ^= CrcSeed; } } /// <summary> /// This buffer is used temporarily to retrieve the bytes from the /// deflater and write them to the underlying output stream. /// </summary> protected byte[] buf; /// <summary> /// The deflater which is used to deflate the stream. /// </summary> protected Deflater def; /// <summary> /// Base stream the deflater depends on. /// </summary> protected Stream baseOutputStream; bool isClosed = false; bool isStreamOwner = true; /// <summary> /// Get/set flag indicating ownership of underlying stream. /// When the flag is true <see cref="Close"></see> will close the underlying stream also. /// </summary> public bool IsStreamOwner { get { return isStreamOwner; } set { isStreamOwner = value; } } /// <summary> /// Allows client to determine if an entry can be patched after its added /// </summary> public bool CanPatchEntries { get { return baseOutputStream.CanSeek; } } /// <summary> /// Gets value indicating stream can be read from /// </summary> public override bool CanRead { get { return baseOutputStream.CanRead; } } /// <summary> /// Gets a value indicating if seeking is supported for this stream /// This property always returns false /// </summary> public override bool CanSeek { get { return false; } } /// <summary> /// Get value indicating if this stream supports writing /// </summary> public override bool CanWrite { get { return baseOutputStream.CanWrite; } } /// <summary> /// Get current length of stream /// </summary> public override long Length { get { return baseOutputStream.Length; } } /// <summary> /// The current position within the stream. /// Always throws a NotSupportedExceptionNotSupportedException /// </summary> /// <exception cref="NotSupportedException">Any attempt to set position</exception> public override long Position { get { return baseOutputStream.Position; } set { throw new NotSupportedException("DefalterOutputStream Position not supported"); } } /// <summary> /// Sets the current position of this stream to the given value. Not supported by this class! /// </summary> /// <exception cref="NotSupportedException">Any access</exception> public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException("DeflaterOutputStream Seek not supported"); } /// <summary> /// Sets the length of this stream to the given value. Not supported by this class! /// </summary> /// <exception cref="NotSupportedException">Any access</exception> public override void SetLength(long val) { throw new NotSupportedException("DeflaterOutputStream SetLength not supported"); } /// <summary> /// Read a byte from stream advancing position by one /// </summary> /// <exception cref="NotSupportedException">Any access</exception> public override int ReadByte() { throw new NotSupportedException("DeflaterOutputStream ReadByte not supported"); } /// <summary> /// Read a block of bytes from stream /// </summary> /// <exception cref="NotSupportedException">Any access</exception> public override int Read(byte[] b, int off, int len) { throw new NotSupportedException("DeflaterOutputStream Read not supported"); } /// <summary> /// Asynchronous reads are not supported a NotSupportedException is always thrown /// </summary> /// <param name="buffer"></param> /// <param name="offset"></param> /// <param name="count"></param> /// <param name="callback"></param> /// <param name="state"></param> /// <returns></returns> /// <exception cref="NotSupportedException">Any access</exception> public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state) { throw new NotSupportedException("DeflaterOutputStream BeginRead not currently supported"); } /// <summary> /// Asynchronous writes arent supported, a NotSupportedException is always thrown /// </summary> /// <param name="buffer"></param> /// <param name="offset"></param> /// <param name="count"></param> /// <param name="callback"></param> /// <param name="state"></param> /// <returns></returns> /// <exception cref="NotSupportedException">Any access</exception> public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state) { throw new NotSupportedException("DeflaterOutputStream BeginWrite not currently supported"); } /// <summary> /// Deflates everything in the input buffers. This will call /// <code>def.deflate()</code> until all bytes from the input buffers /// are processed. /// </summary> protected void Deflate() { for (; ; ) { int len = def.Deflate(buf, 0, buf.Length); if (len <= 0) { break; } if (this.keys != null) { this.EncryptBlock(buf, 0, len); } baseOutputStream.Write(buf, 0, len); } if (!def.IsNeedingInput) { throw new SharpZipBaseException("DeflaterOutputStream can't deflate all input?"); } } /// <summary> /// Creates a new DeflaterOutputStream with a default Deflater and default buffer size. /// </summary> /// <param name="baseOutputStream"> /// the output stream where deflated output should be written. /// </param> public InteractiveDeflaterOutputStream(Stream baseOutputStream) : this(baseOutputStream, new Deflater(), 512) { } /// <summary> /// Creates a new DeflaterOutputStream with the given Deflater and /// default buffer size. /// </summary> /// <param name="baseOutputStream"> /// the output stream where deflated output should be written. /// </param> /// <param name="defl"> /// the underlying deflater. /// </param> public InteractiveDeflaterOutputStream(Stream baseOutputStream, Deflater defl) : this(baseOutputStream, defl, 512) { } /// <summary> /// Creates a new DeflaterOutputStream with the given Deflater and /// buffer size. /// </summary> /// <param name="baseOutputStream"> /// The output stream where deflated output is written. /// </param> /// <param name="deflater"> /// The underlying deflater to use /// </param> /// <param name="bufsize"> /// The buffer size to use when deflating /// </param> /// <exception cref="ArgumentOutOfRangeException"> /// bufsize is less than or equal to zero. /// </exception> /// <exception cref="ArgumentException"> /// baseOutputStream does not support writing /// </exception> /// <exception cref="ArgumentNullException"> /// deflater instance is null /// </exception> public InteractiveDeflaterOutputStream(Stream baseOutputStream, Deflater deflater, int bufsize) { if (baseOutputStream.CanWrite == false) { throw new ArgumentException("baseOutputStream", "must support writing"); } if (deflater == null) { throw new ArgumentNullException("deflater"); } if (bufsize <= 0) { throw new ArgumentOutOfRangeException("bufsize"); } this.baseOutputStream = baseOutputStream; buf = new byte[bufsize]; def = deflater; } /// <summary> /// Flushes the stream by calling flush() on the deflater and then /// on the underlying stream. This ensures that all bytes are /// flushed. /// </summary> public override void Flush() { if (m_PossibleBytesPending) { def.SetInput(new byte[0]); def.Flush(); Deflate(); m_PossibleBytesPending = false; } baseOutputStream.Flush(); } /// <summary> /// Finishes the stream by calling finish() on the deflater. /// </summary> /// <exception cref="SharpZipBaseException"> /// Not all input is deflated /// </exception> public virtual void Finish() { def.Finish(); while (!def.IsFinished) { int len = def.Deflate(buf, 0, buf.Length); if (len <= 0) { break; } if (this.keys != null) { this.EncryptBlock(buf, 0, len); } baseOutputStream.Write(buf, 0, len); } if (!def.IsFinished) { throw new SharpZipBaseException("Can't deflate all input?"); } baseOutputStream.Flush(); keys = null; } /// <summary> /// Calls finish() and closes the underlying /// stream when <see cref="IsStreamOwner"></see> is true. /// </summary> public override void Close() { if (!isClosed) { isClosed = true; Finish(); if (isStreamOwner) { baseOutputStream.Close(); } } } /// <summary> /// Writes a single byte to the compressed output stream. /// </summary> /// <param name="bval"> /// The byte value. /// </param> public override void WriteByte(byte bval) { byte[] b = new byte[1]; b[0] = bval; Write(b, 0, 1); } private bool m_PossibleBytesPending = false; /// <summary> /// Writes bytes from an array to the compressed stream. /// </summary> /// <param name="buf"> /// The byte array /// </param> /// <param name="off"> /// The offset into the byte array where to start. /// </param> /// <param name="len"> /// The number of bytes to write. /// </param> public override void Write(byte[] buf, int off, int len) { def.SetInput(buf, off, len); Deflate(); m_PossibleBytesPending = true; } #region Encryption // TODO: Refactor this code. The presence of Zip specific code in this low level class is wrong string password = null; uint[] keys = null; /// <summary> /// Get/set the password used for encryption. When null no encryption is performed /// </summary> public string Password { get { return password; } set { if (value != null && value.Length == 0) { password = null; } else { password = value; } } } /// <summary> /// Encrypt a single byte /// </summary> /// <returns> /// The encrypted value /// </returns> protected byte EncryptByte() { uint temp = ((keys[2] & 0xFFFF) | 2); return (byte)((temp * (temp ^ 1)) >> 8); } /// <summary> /// Encrypt a block of data /// </summary> /// <param name="buffer"> /// Data to encrypt. NOTE the original contents of the buffer are lost /// </param> /// <param name="offset"> /// Offset of first byte in buffer to encrypt /// </param> /// <param name="length"> /// Number of bytes in buffer to encrypt /// </param> protected void EncryptBlock(byte[] buffer, int offset, int length) { // TODO: refactor to use crypto transform for (int i = offset; i < offset + length; ++i) { byte oldbyte = buffer[i]; buffer[i] ^= EncryptByte(); UpdateKeys(oldbyte); } } /// <summary> /// Initializes encryption keys based on given password /// </summary> protected void InitializePassword(string password) { keys = new uint[] { 0x12345678, 0x23456789, 0x34567890 }; for (int i = 0; i < password.Length; ++i) { UpdateKeys((byte)password[i]); } } /// <summary> /// Update encryption keys /// </summary> protected void UpdateKeys(byte ch) { keys[0] = Crc32.ComputeCrc32(keys[0], ch); keys[1] = keys[1] + (byte)keys[0]; keys[1] = keys[1] * 134775813 + 1; keys[2] = Crc32.ComputeCrc32(keys[2], (byte)(keys[1] >> 24)); } #endregion } }
/* Copyright 2006 - 2010 Intel 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. */ using System; using OpenSource.UPnP.AV.CdsMetadata; namespace OpenSource.UPnP.AV.MediaServer.DV { /// <summary> /// Thrown when attempting to set the URI of a resource that maps to /// a local file intended for serving with http-get from the internal /// webserver of a /// <see cref="MediaServerDevice"/> /// object. /// <see cref="DvMediaResource"/> uses this exception. /// </summary> public class Error_CannotSetImportUri : UPnPCustomException { /// <summary> /// Indicates vendor specific UPNP error code of 875. /// </summary> /// <param name="contentUri">The contentUri value of the MediaResource when the importUri modification was attempted.</param> /// <param name="importUri">The value of the intended importUri.</param> public Error_CannotSetImportUri(string contentUri, string importUri) : base(875, "Cannot set the importUri value for a resource that maps to ("+contentUri+"). Set the ContentUri instead.") { ContentUri = contentUri; ImportUri = importUri; } /// <summary> /// The contentUri value of the MediaResource when the importUri was attempted for modification. /// </summary> public string ContentUri; /// <summary> /// The value of the intended importUri. /// </summary> public string ImportUri; } /// <summary> /// Thrown when attempting to set the ProtocolInfo string of a resource /// if the protocolInfo string is not "http-get", when the contentUri /// starts with /// <see cref="OpenSource.UPnP.AV.CdsMetadata.MediaResource.AUTOMAPFILE"/>. /// <see cref="DvMediaResource"/> uses this exception. /// </summary> public class Error_CannotSetProtocolInfo : UPnPCustomException { /// <summary> /// Indicates vendor specific UPNP error code of 876. /// </summary> /// <param name="contentUri">The contentUri value of the MediaResource when the protocolInfo modification was attempted.</param> /// <param name="protocolInfo">The value of the intended protocolInfo string.</param> public Error_CannotSetProtocolInfo(string contentUri, ProtocolInfoString protocolInfo) : base (876, "Cannot set the protocolInfo string (" +protocolInfo.ToString()+ ") to something other than \"http-get\", if the contentUri value starts with (" +MediaResource.AUTOMAPFILE+").") { this.ContentUri = contentUri; this.ProtocolInfo = protocolInfo; } /// <summary> /// The contentUri value of the MediaResource when the protocolInfo modification was attempted. /// </summary> public readonly string ContentUri; /// <summary> /// The value of the intended protocolInfo string. /// </summary> public readonly ProtocolInfoString ProtocolInfo; } /// <summary> /// Thrown when attempting to set the contentUri of a resource if the newUri string begins with /// <see cref="OpenSource.UPnP.AV.CdsMetadata.MediaResource.AUTOMAPFILE"/> /// and the /// protocol is not "http-get". /// <see cref="DvMediaResource"/> uses this exception. /// </summary> public class Error_CannotSetContentUri : UPnPCustomException { /// <summary> /// Indicates vendor specific UPNP error code of 877. /// </summary> public Error_CannotSetContentUri(ProtocolInfoString protocolInfo, string contentUri) : base (877, "Cannot set the contentUri ("+contentUri+") to a string beginning with ("+MediaResource.AUTOMAPFILE+") if the protocolInfo ("+protocolInfo.ToString()+") does not indicate a protocol of \"http-get\"") { this.ContentUri = contentUri; this.ProtocolInfo = protocolInfo; } /// <summary> /// The value of the intended contentUri. /// </summary> public readonly string ContentUri; /// <summary> /// The protocolInfo value of the MediaResource when the contentUri modification was attempted. /// </summary> public readonly ProtocolInfoString ProtocolInfo; } /// <summary> /// Thrown when attempting to create a reference to an item that is queued for /// deletion from the content hierarchy. /// <see cref="DvMediaItem"/> uses this exception. /// </summary> public class Error_PendingDeleteException : UPnPCustomException { /// <summary> /// Indicates vendor specific UPNP error code of 878. /// </summary> /// <param name="item">The item that cannot have a reference created to it.</param> public Error_PendingDeleteException(IMediaItem item) : base(878, "The item (@id=\""+item.ID+"\") has been deleted or is about to be deleted.") { Item = item; } /// <summary> /// The item that cannot have a reference created to it. /// </summary> public readonly IMediaItem Item; } /// <summary> /// Thrown when the MediaServer has not been configured correctly /// <see cref="MediaServerDevice"/> uses this exception. /// </summary> public class Error_InvalidServerConfiguration : UPnPCustomException { /// <summary> /// Indicates UPNP-AV action-specific error code 879. /// </summary> /// <param name="info">Message with additional info.</param> public Error_InvalidServerConfiguration (string info) : base (879, "Invalid server configuration. " + info) {} } /// <summary> /// Thrown when a general error occurs during the import resource process. /// </summary> public class Error_ImportError : UPnPCustomException { /// <summary> /// Indicates vendor-specific error code of 880. /// </summary> /// <param name="info"></param> public Error_ImportError (string info) : base(880, info) { } } /// <summary> /// Thrown when a general error occurred when connecting. /// </summary> public class Error_ConnectionProblem : UPnPCustomException { /// <summary> /// Indicates vendor-specific error code of 881. /// </summary> /// <param name="info"></param> public Error_ConnectionProblem (string info) : base (881, "Connection error. "+info) { } } /// <summary> /// Thrown when ImportResource destination Uri is not HTTP based. /// </summary> public class Error_NonHttpImport : UPnPCustomException { public Error_NonHttpImport (string info) : base (881, "Cannot import from a URI that is not HTTP based. " + info) { Info = info; } public string Info; } /// <summary> /// Thrown when a general error occurred when doing an http-get. /// </summary> public class Error_GetRequestError : UPnPCustomException { /// <summary> /// Indicates vendor-specific error code of 881. /// </summary> /// <param name="directiveObj"></param> /// <param name="res"></param> public Error_GetRequestError (string directiveObj, IMediaResource res) : base (881, "Error fulfilling request for " + directiveObj) { Resource = res; DirectiveObj = directiveObj; } /// <summary> /// The resource that was requested /// </summary> public IMediaResource Resource; public string DirectiveObj; } /// <summary> /// Thrown when an error occurred when transfering binaries. /// </summary> public class Error_TransferProblem : UPnPCustomException { /// <summary> /// Indicates vendor-specific error code of 881. /// </summary> /// <param name="id"></param> /// <param name="transferInfo"></param> public Error_TransferProblem (UInt32 id, MediaServerDevice.HttpTransfer transferInfo) : base(881, "Error with transfer " + id.ToString()) { TransferId = id; TransferInfo = transferInfo; } /// <summary> /// the transfer id that was specified /// </summary> UInt32 TransferId; /// <summary> /// The object representing the transfer in question. /// </summary> MediaServerDevice.HttpTransfer TransferInfo; } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect 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. */ using System; using System.Collections.Generic; using System.Linq; using Moq; using NodaTime; using NUnit.Framework; using Python.Runtime; using QuantConnect.Algorithm; using QuantConnect.Algorithm.Framework.Execution; using QuantConnect.Algorithm.Framework.Portfolio; using QuantConnect.Data; using QuantConnect.Data.Market; using QuantConnect.Data.UniverseSelection; using QuantConnect.Interfaces; using QuantConnect.Orders; using QuantConnect.Securities; using QuantConnect.Tests.Common.Data.UniverseSelection; using QuantConnect.Tests.Engine.DataFeeds; namespace QuantConnect.Tests.Algorithm.Framework.Execution { [TestFixture] public class StandardDeviationExecutionModelTests { [TestCase(Language.CSharp)] [TestCase(Language.Python)] public void OrdersAreNotSubmittedWhenNoTargetsToExecute(Language language) { var actualOrdersSubmitted = new List<SubmitOrderRequest>(); var orderProcessor = new Mock<IOrderProcessor>(); orderProcessor.Setup(m => m.Process(It.IsAny<SubmitOrderRequest>())) .Returns((OrderTicket)null) .Callback((OrderRequest request) => actualOrdersSubmitted.Add((SubmitOrderRequest)request)); var algorithm = new QCAlgorithm(); algorithm.SetPandasConverter(); algorithm.SubscriptionManager.SetDataManager(new DataManagerStub(algorithm)); algorithm.Transactions.SetOrderProcessor(orderProcessor.Object); var model = GetExecutionModel(language); algorithm.SetExecution(model); var changes = SecurityChangesTests.CreateNonInternal(Enumerable.Empty<Security>(), Enumerable.Empty<Security>()); model.OnSecuritiesChanged(algorithm, changes); model.Execute(algorithm, new IPortfolioTarget[0]); Assert.AreEqual(0, actualOrdersSubmitted.Count); } [TestCase(Language.CSharp, new[] { 270d, 260d, 250d }, 240, 1, 10)] [TestCase(Language.CSharp, new[] { 250d, 250d, 250d }, 250, 0, 0)] [TestCase(Language.Python, new[] { 270d, 260d, 250d }, 240, 1, 10)] [TestCase(Language.Python, new[] { 250d, 250d, 250d }, 250, 0, 0)] public void OrdersAreSubmittedWhenRequiredForTargetsToExecute( Language language, double[] historicalPrices, decimal currentPrice, int expectedOrdersSubmitted, decimal expectedTotalQuantity) { var actualOrdersSubmitted = new List<SubmitOrderRequest>(); var time = new DateTime(2018, 8, 2, 16, 0, 0); var historyProvider = new Mock<IHistoryProvider>(); historyProvider.Setup(m => m.GetHistory(It.IsAny<IEnumerable<HistoryRequest>>(), It.IsAny<DateTimeZone>())) .Returns(historicalPrices.Select((x,i) => new Slice(time.AddMinutes(i), new List<BaseData> { new TradeBar { Time = time.AddMinutes(i), Symbol = Symbols.AAPL, Open = Convert.ToDecimal(x), High = Convert.ToDecimal(x), Low = Convert.ToDecimal(x), Close = Convert.ToDecimal(x), Volume = 100m } }, time.AddMinutes(i)))); var algorithm = new QCAlgorithm(); algorithm.SetPandasConverter(); algorithm.SetHistoryProvider(historyProvider.Object); algorithm.SubscriptionManager.SetDataManager(new DataManagerStub(algorithm)); algorithm.SetDateTime(time.AddMinutes(5)); var security = algorithm.AddEquity(Symbols.AAPL.Value); security.SetMarketPrice(new TradeBar { Value = currentPrice }); algorithm.SetFinishedWarmingUp(); var orderProcessor = new Mock<IOrderProcessor>(); orderProcessor.Setup(m => m.Process(It.IsAny<SubmitOrderRequest>())) .Returns((SubmitOrderRequest request) => new OrderTicket(algorithm.Transactions, request)) .Callback((OrderRequest request) => actualOrdersSubmitted.Add((SubmitOrderRequest)request)); orderProcessor.Setup(m => m.GetOpenOrders(It.IsAny<Func<Order, bool>>())) .Returns(new List<Order>()); algorithm.Transactions.SetOrderProcessor(orderProcessor.Object); var model = GetExecutionModel(language); algorithm.SetExecution(model); var changes = SecurityChangesTests.CreateNonInternal(new[] { security }, Enumerable.Empty<Security>()); model.OnSecuritiesChanged(algorithm, changes); var targets = new IPortfolioTarget[] { new PortfolioTarget(Symbols.AAPL, 10) }; model.Execute(algorithm, targets); Assert.AreEqual(expectedOrdersSubmitted, actualOrdersSubmitted.Count); Assert.AreEqual(expectedTotalQuantity, actualOrdersSubmitted.Sum(x => x.Quantity)); if (actualOrdersSubmitted.Count == 1) { var request = actualOrdersSubmitted[0]; Assert.AreEqual(expectedTotalQuantity, request.Quantity); Assert.AreEqual(algorithm.UtcTime, request.Time); } } [TestCase(Language.CSharp, new[] { 270d, 260d, 250d }, MarketDataType.TradeBar)] [TestCase(Language.Python, new[] { 250d, 250d, 250d }, MarketDataType.TradeBar)] [TestCase(Language.CSharp, new[] { 270d, 260d, 250d }, MarketDataType.QuoteBar)] [TestCase(Language.Python, new[] { 250d, 250d, 250d }, MarketDataType.QuoteBar)] public void OnSecuritiesChangeDoesNotThrow( Language language, double[] historicalPrices, MarketDataType marketDataType) { var time = new DateTime(2018, 8, 2, 16, 0, 0); Func<double, int, BaseData> func = (x, i) => { var price = Convert.ToDecimal(x); switch (marketDataType) { case MarketDataType.TradeBar: return new TradeBar(time.AddMinutes(i), Symbols.AAPL, price, price, price, price, 100m); case MarketDataType.QuoteBar: var bar = new Bar(price, price, price, price); return new QuoteBar(time.AddMinutes(i), Symbols.AAPL, bar, 10m, bar, 10m); default: throw new ArgumentException($"Invalid MarketDataType: {marketDataType}"); } }; var historyProvider = new Mock<IHistoryProvider>(); historyProvider.Setup(m => m.GetHistory(It.IsAny<IEnumerable<HistoryRequest>>(), It.IsAny<DateTimeZone>())) .Returns(historicalPrices.Select((x, i) => new Slice(time.AddMinutes(i), new List<BaseData> { func(x, i) }, time.AddMinutes(i)))); var algorithm = new QCAlgorithm(); algorithm.SetPandasConverter(); algorithm.SetHistoryProvider(historyProvider.Object); algorithm.SubscriptionManager.SetDataManager(new DataManagerStub(algorithm)); algorithm.SetDateTime(time.AddMinutes(5)); var security = algorithm.AddEquity(Symbols.AAPL.Value); security.SetMarketPrice(new TradeBar { Value = 250 }); algorithm.SetFinishedWarmingUp(); var model = GetExecutionModel(language); algorithm.SetExecution(model); var changes = SecurityChangesTests.CreateNonInternal(new[] { security }, Enumerable.Empty<Security>()); Assert.DoesNotThrow(() => model.OnSecuritiesChanged(algorithm, changes)); } private static IExecutionModel GetExecutionModel(Language language) { const int period = 2; const decimal deviations = 1.5m; if (language == Language.Python) { using (Py.GIL()) { const string name = nameof(StandardDeviationExecutionModel); var instance = Py.Import(name).GetAttr(name).Invoke(period.ToPython(), deviations.ToPython()); return new ExecutionModelPythonWrapper(instance); } } return new StandardDeviationExecutionModel(period, deviations); } } }
using System.Collections.Immutable; using FluentAssertions; using JetBrains.Annotations; using JsonApiDotNetCore.Configuration; using JsonApiDotNetCore.Errors; using JsonApiDotNetCore.Middleware; using JsonApiDotNetCore.Queries; using JsonApiDotNetCore.Queries.Expressions; using JsonApiDotNetCore.Repositories; using JsonApiDotNetCore.Resources; using JsonApiDotNetCore.Resources.Annotations; using JsonApiDotNetCore.Services; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using Xunit; namespace UnitTests.Extensions; public sealed class ServiceCollectionExtensionsTests { [Fact] public void RegisterResource_DeviatingDbContextPropertyName_RegistersCorrectly() { // Arrange var services = new ServiceCollection(); services.AddLogging(); services.AddDbContext<TestDbContext>(options => options.UseInMemoryDatabase("UnitTestDb")); // Act services.AddJsonApi<TestDbContext>(); // Assert ServiceProvider provider = services.BuildServiceProvider(); var resourceGraph = provider.GetRequiredService<IResourceGraph>(); ResourceType personType = resourceGraph.GetResourceType<Person>(); personType.PublicName.Should().Be("people"); } [Fact] public void AddResourceService_Registers_Service_Interfaces_Of_Int32() { // Arrange var services = new ServiceCollection(); // Act services.AddResourceService<ResourceServiceOfInt32>(); // Assert ServiceProvider provider = services.BuildServiceProvider(); provider.GetRequiredService(typeof(IResourceService<ResourceOfInt32, int>)).Should().BeOfType<ResourceServiceOfInt32>(); provider.GetRequiredService(typeof(IResourceCommandService<ResourceOfInt32, int>)).Should().BeOfType<ResourceServiceOfInt32>(); provider.GetRequiredService(typeof(IResourceQueryService<ResourceOfInt32, int>)).Should().BeOfType<ResourceServiceOfInt32>(); provider.GetRequiredService(typeof(IGetAllService<ResourceOfInt32, int>)).Should().BeOfType<ResourceServiceOfInt32>(); provider.GetRequiredService(typeof(IGetByIdService<ResourceOfInt32, int>)).Should().BeOfType<ResourceServiceOfInt32>(); provider.GetRequiredService(typeof(IGetSecondaryService<ResourceOfInt32, int>)).Should().BeOfType<ResourceServiceOfInt32>(); provider.GetRequiredService(typeof(IGetRelationshipService<ResourceOfInt32, int>)).Should().BeOfType<ResourceServiceOfInt32>(); provider.GetRequiredService(typeof(ICreateService<ResourceOfInt32, int>)).Should().BeOfType<ResourceServiceOfInt32>(); provider.GetRequiredService(typeof(IUpdateService<ResourceOfInt32, int>)).Should().BeOfType<ResourceServiceOfInt32>(); provider.GetRequiredService(typeof(IDeleteService<ResourceOfInt32, int>)).Should().BeOfType<ResourceServiceOfInt32>(); } [Fact] public void AddResourceService_Registers_Service_Interfaces_Of_Guid() { // Arrange var services = new ServiceCollection(); // Act services.AddResourceService<ResourceServiceOfGuid>(); // Assert ServiceProvider provider = services.BuildServiceProvider(); provider.GetRequiredService(typeof(IResourceService<ResourceOfGuid, Guid>)).Should().BeOfType<ResourceServiceOfGuid>(); provider.GetRequiredService(typeof(IResourceCommandService<ResourceOfGuid, Guid>)).Should().BeOfType<ResourceServiceOfGuid>(); provider.GetRequiredService(typeof(IResourceQueryService<ResourceOfGuid, Guid>)).Should().BeOfType<ResourceServiceOfGuid>(); provider.GetRequiredService(typeof(IGetAllService<ResourceOfGuid, Guid>)).Should().BeOfType<ResourceServiceOfGuid>(); provider.GetRequiredService(typeof(IGetByIdService<ResourceOfGuid, Guid>)).Should().BeOfType<ResourceServiceOfGuid>(); provider.GetRequiredService(typeof(IGetSecondaryService<ResourceOfGuid, Guid>)).Should().BeOfType<ResourceServiceOfGuid>(); provider.GetRequiredService(typeof(IGetRelationshipService<ResourceOfGuid, Guid>)).Should().BeOfType<ResourceServiceOfGuid>(); provider.GetRequiredService(typeof(ICreateService<ResourceOfGuid, Guid>)).Should().BeOfType<ResourceServiceOfGuid>(); provider.GetRequiredService(typeof(IUpdateService<ResourceOfGuid, Guid>)).Should().BeOfType<ResourceServiceOfGuid>(); provider.GetRequiredService(typeof(IDeleteService<ResourceOfGuid, Guid>)).Should().BeOfType<ResourceServiceOfGuid>(); } [Fact] public void AddResourceService_Throws_If_Type_Does_Not_Implement_Any_Interfaces() { // Arrange var services = new ServiceCollection(); // Act Action action = () => services.AddResourceService<int>(); // Assert action.Should().ThrowExactly<InvalidConfigurationException>(); } [Fact] public void AddResourceRepository_Registers_Repository_Interfaces_Of_Int32() { // Arrange var services = new ServiceCollection(); // Act services.AddResourceRepository<ResourceRepositoryOfInt32>(); // Assert ServiceProvider provider = services.BuildServiceProvider(); provider.GetRequiredService(typeof(IResourceRepository<ResourceOfInt32, int>)).Should().BeOfType<ResourceRepositoryOfInt32>(); provider.GetRequiredService(typeof(IResourceReadRepository<ResourceOfInt32, int>)).Should().BeOfType<ResourceRepositoryOfInt32>(); provider.GetRequiredService(typeof(IResourceWriteRepository<ResourceOfInt32, int>)).Should().BeOfType<ResourceRepositoryOfInt32>(); } [Fact] public void AddResourceRepository_Registers_Repository_Interfaces_Of_Guid() { // Arrange var services = new ServiceCollection(); // Act services.AddResourceRepository<ResourceRepositoryOfGuid>(); // Assert ServiceProvider provider = services.BuildServiceProvider(); provider.GetRequiredService(typeof(IResourceRepository<ResourceOfGuid, Guid>)).Should().BeOfType<ResourceRepositoryOfGuid>(); provider.GetRequiredService(typeof(IResourceReadRepository<ResourceOfGuid, Guid>)).Should().BeOfType<ResourceRepositoryOfGuid>(); provider.GetRequiredService(typeof(IResourceWriteRepository<ResourceOfGuid, Guid>)).Should().BeOfType<ResourceRepositoryOfGuid>(); } [Fact] public void AddResourceDefinition_Registers_Definition_Interface_Of_Int32() { // Arrange var services = new ServiceCollection(); // Act services.AddResourceDefinition<ResourceDefinitionOfInt32>(); // Assert ServiceProvider provider = services.BuildServiceProvider(); provider.GetRequiredService(typeof(IResourceDefinition<ResourceOfInt32, int>)).Should().BeOfType<ResourceDefinitionOfInt32>(); } [Fact] public void AddResourceDefinition_Registers_Definition_Interface_Of_Guid() { // Arrange var services = new ServiceCollection(); // Act services.AddResourceDefinition<ResourceDefinitionOfGuid>(); // Assert ServiceProvider provider = services.BuildServiceProvider(); provider.GetRequiredService(typeof(IResourceDefinition<ResourceOfGuid, Guid>)).Should().BeOfType<ResourceDefinitionOfGuid>(); } [Fact] public void AddJsonApi_With_Context_Uses_Resource_Type_Name_If_NoOtherSpecified() { // Arrange var services = new ServiceCollection(); services.AddLogging(); services.AddDbContext<TestDbContext>(options => options.UseInMemoryDatabase(Guid.NewGuid().ToString())); // Act services.AddJsonApi<TestDbContext>(); // Assert ServiceProvider provider = services.BuildServiceProvider(); var resourceGraph = provider.GetRequiredService<IResourceGraph>(); ResourceType resourceType = resourceGraph.GetResourceType(typeof(ResourceOfInt32)); resourceType.PublicName.Should().Be("resourceOfInt32s"); } private sealed class ResourceOfInt32 : Identifiable<int> { } [UsedImplicitly(ImplicitUseKindFlags.InstantiatedNoFixedConstructorSignature)] private sealed class ResourceOfGuid : Identifiable<Guid> { } [UsedImplicitly(ImplicitUseKindFlags.InstantiatedNoFixedConstructorSignature)] private sealed class ResourceServiceOfInt32 : IResourceService<ResourceOfInt32, int> { public Task<IReadOnlyCollection<ResourceOfInt32>> GetAsync(CancellationToken cancellationToken) { throw new NotImplementedException(); } public Task<ResourceOfInt32> GetAsync(int id, CancellationToken cancellationToken) { throw new NotImplementedException(); } public Task<object?> GetSecondaryAsync(int id, string relationshipName, CancellationToken cancellationToken) { throw new NotImplementedException(); } public Task<object?> GetRelationshipAsync(int id, string relationshipName, CancellationToken cancellationToken) { throw new NotImplementedException(); } public Task<ResourceOfInt32?> CreateAsync(ResourceOfInt32 resource, CancellationToken cancellationToken) { throw new NotImplementedException(); } public Task AddToToManyRelationshipAsync(int leftId, string relationshipName, ISet<IIdentifiable> rightResourceIds, CancellationToken cancellationToken) { throw new NotImplementedException(); } public Task<ResourceOfInt32?> UpdateAsync(int id, ResourceOfInt32 resource, CancellationToken cancellationToken) { throw new NotImplementedException(); } public Task SetRelationshipAsync(int leftId, string relationshipName, object? rightValue, CancellationToken cancellationToken) { throw new NotImplementedException(); } public Task DeleteAsync(int id, CancellationToken cancellationToken) { throw new NotImplementedException(); } public Task RemoveFromToManyRelationshipAsync(int leftId, string relationshipName, ISet<IIdentifiable> rightResourceIds, CancellationToken cancellationToken) { throw new NotImplementedException(); } } [UsedImplicitly(ImplicitUseKindFlags.InstantiatedNoFixedConstructorSignature)] private sealed class ResourceServiceOfGuid : IResourceService<ResourceOfGuid, Guid> { public Task<IReadOnlyCollection<ResourceOfGuid>> GetAsync(CancellationToken cancellationToken) { throw new NotImplementedException(); } public Task<ResourceOfGuid> GetAsync(Guid id, CancellationToken cancellationToken) { throw new NotImplementedException(); } public Task<object?> GetSecondaryAsync(Guid id, string relationshipName, CancellationToken cancellationToken) { throw new NotImplementedException(); } public Task<object?> GetRelationshipAsync(Guid id, string relationshipName, CancellationToken cancellationToken) { throw new NotImplementedException(); } public Task<ResourceOfGuid?> CreateAsync(ResourceOfGuid resource, CancellationToken cancellationToken) { throw new NotImplementedException(); } public Task AddToToManyRelationshipAsync(Guid leftId, string relationshipName, ISet<IIdentifiable> rightResourceIds, CancellationToken cancellationToken) { throw new NotImplementedException(); } public Task<ResourceOfGuid?> UpdateAsync(Guid id, ResourceOfGuid resource, CancellationToken cancellationToken) { throw new NotImplementedException(); } public Task SetRelationshipAsync(Guid leftId, string relationshipName, object? rightValue, CancellationToken cancellationToken) { throw new NotImplementedException(); } public Task DeleteAsync(Guid id, CancellationToken cancellationToken) { throw new NotImplementedException(); } public Task RemoveFromToManyRelationshipAsync(Guid leftId, string relationshipName, ISet<IIdentifiable> rightResourceIds, CancellationToken cancellationToken) { throw new NotImplementedException(); } } [UsedImplicitly(ImplicitUseKindFlags.InstantiatedNoFixedConstructorSignature)] private sealed class ResourceRepositoryOfInt32 : IResourceRepository<ResourceOfInt32, int> { public Task<IReadOnlyCollection<ResourceOfInt32>> GetAsync(QueryLayer queryLayer, CancellationToken cancellationToken) { throw new NotImplementedException(); } public Task<int> CountAsync(FilterExpression? filter, CancellationToken cancellationToken) { throw new NotImplementedException(); } public Task<ResourceOfInt32> GetForCreateAsync(int id, CancellationToken cancellationToken) { throw new NotImplementedException(); } public Task CreateAsync(ResourceOfInt32 resourceFromRequest, ResourceOfInt32 resourceForDatabase, CancellationToken cancellationToken) { throw new NotImplementedException(); } public Task<ResourceOfInt32?> GetForUpdateAsync(QueryLayer queryLayer, CancellationToken cancellationToken) { throw new NotImplementedException(); } public Task UpdateAsync(ResourceOfInt32 resourceFromRequest, ResourceOfInt32 resourceFromDatabase, CancellationToken cancellationToken) { throw new NotImplementedException(); } public Task DeleteAsync(int id, CancellationToken cancellationToken) { throw new NotImplementedException(); } public Task SetRelationshipAsync(ResourceOfInt32 leftResource, object? rightValue, CancellationToken cancellationToken) { throw new NotImplementedException(); } public Task AddToToManyRelationshipAsync(int leftId, ISet<IIdentifiable> rightResourceIds, CancellationToken cancellationToken) { throw new NotImplementedException(); } public Task RemoveFromToManyRelationshipAsync(ResourceOfInt32 leftResource, ISet<IIdentifiable> rightResourceIds, CancellationToken cancellationToken) { throw new NotImplementedException(); } } [UsedImplicitly(ImplicitUseKindFlags.InstantiatedNoFixedConstructorSignature)] private sealed class ResourceRepositoryOfGuid : IResourceRepository<ResourceOfGuid, Guid> { public Task<IReadOnlyCollection<ResourceOfGuid>> GetAsync(QueryLayer queryLayer, CancellationToken cancellationToken) { throw new NotImplementedException(); } public Task<int> CountAsync(FilterExpression? filter, CancellationToken cancellationToken) { throw new NotImplementedException(); } public Task<ResourceOfGuid> GetForCreateAsync(Guid id, CancellationToken cancellationToken) { throw new NotImplementedException(); } public Task CreateAsync(ResourceOfGuid resourceFromRequest, ResourceOfGuid resourceForDatabase, CancellationToken cancellationToken) { throw new NotImplementedException(); } public Task<ResourceOfGuid?> GetForUpdateAsync(QueryLayer queryLayer, CancellationToken cancellationToken) { throw new NotImplementedException(); } public Task UpdateAsync(ResourceOfGuid resourceFromRequest, ResourceOfGuid resourceFromDatabase, CancellationToken cancellationToken) { throw new NotImplementedException(); } public Task DeleteAsync(Guid id, CancellationToken cancellationToken) { throw new NotImplementedException(); } public Task SetRelationshipAsync(ResourceOfGuid leftResource, object? rightValue, CancellationToken cancellationToken) { throw new NotImplementedException(); } public Task AddToToManyRelationshipAsync(Guid leftId, ISet<IIdentifiable> rightResourceIds, CancellationToken cancellationToken) { throw new NotImplementedException(); } public Task RemoveFromToManyRelationshipAsync(ResourceOfGuid leftResource, ISet<IIdentifiable> rightResourceIds, CancellationToken cancellationToken) { throw new NotImplementedException(); } } [UsedImplicitly(ImplicitUseKindFlags.InstantiatedNoFixedConstructorSignature)] private sealed class ResourceDefinitionOfInt32 : IResourceDefinition<ResourceOfInt32, int> { public IImmutableSet<IncludeElementExpression> OnApplyIncludes(IImmutableSet<IncludeElementExpression> existingIncludes) { throw new NotImplementedException(); } public FilterExpression OnApplyFilter(FilterExpression? existingFilter) { throw new NotImplementedException(); } public SortExpression OnApplySort(SortExpression? existingSort) { throw new NotImplementedException(); } public PaginationExpression OnApplyPagination(PaginationExpression? existingPagination) { throw new NotImplementedException(); } public SparseFieldSetExpression OnApplySparseFieldSet(SparseFieldSetExpression? existingSparseFieldSet) { throw new NotImplementedException(); } public QueryStringParameterHandlers<ResourceOfInt32> OnRegisterQueryableHandlersForQueryStringParameters() { throw new NotImplementedException(); } public IDictionary<string, object?> GetMeta(ResourceOfInt32 resource) { throw new NotImplementedException(); } public Task OnPrepareWriteAsync(ResourceOfInt32 resource, WriteOperationKind writeOperation, CancellationToken cancellationToken) { throw new NotImplementedException(); } public Task<IIdentifiable?> OnSetToOneRelationshipAsync(ResourceOfInt32 leftResource, HasOneAttribute hasOneRelationship, IIdentifiable? rightResourceId, WriteOperationKind writeOperation, CancellationToken cancellationToken) { throw new NotImplementedException(); } public Task OnSetToManyRelationshipAsync(ResourceOfInt32 leftResource, HasManyAttribute hasManyRelationship, ISet<IIdentifiable> rightResourceIds, WriteOperationKind writeOperation, CancellationToken cancellationToken) { throw new NotImplementedException(); } public Task OnAddToRelationshipAsync(int leftResourceId, HasManyAttribute hasManyRelationship, ISet<IIdentifiable> rightResourceIds, CancellationToken cancellationToken) { throw new NotImplementedException(); } public Task OnRemoveFromRelationshipAsync(ResourceOfInt32 leftResource, HasManyAttribute hasManyRelationship, ISet<IIdentifiable> rightResourceIds, CancellationToken cancellationToken) { throw new NotImplementedException(); } public Task OnWritingAsync(ResourceOfInt32 resource, WriteOperationKind writeOperation, CancellationToken cancellationToken) { throw new NotImplementedException(); } public Task OnWriteSucceededAsync(ResourceOfInt32 resource, WriteOperationKind writeOperation, CancellationToken cancellationToken) { throw new NotImplementedException(); } public void OnDeserialize(ResourceOfInt32 resource) { throw new NotImplementedException(); } public void OnSerialize(ResourceOfInt32 resource) { throw new NotImplementedException(); } } [UsedImplicitly(ImplicitUseKindFlags.InstantiatedNoFixedConstructorSignature)] private sealed class ResourceDefinitionOfGuid : IResourceDefinition<ResourceOfGuid, Guid> { public IImmutableSet<IncludeElementExpression> OnApplyIncludes(IImmutableSet<IncludeElementExpression> existingIncludes) { throw new NotImplementedException(); } public FilterExpression OnApplyFilter(FilterExpression? existingFilter) { throw new NotImplementedException(); } public SortExpression OnApplySort(SortExpression? existingSort) { throw new NotImplementedException(); } public PaginationExpression OnApplyPagination(PaginationExpression? existingPagination) { throw new NotImplementedException(); } public SparseFieldSetExpression OnApplySparseFieldSet(SparseFieldSetExpression? existingSparseFieldSet) { throw new NotImplementedException(); } public QueryStringParameterHandlers<ResourceOfGuid> OnRegisterQueryableHandlersForQueryStringParameters() { throw new NotImplementedException(); } public IDictionary<string, object?> GetMeta(ResourceOfGuid resource) { throw new NotImplementedException(); } public Task OnPrepareWriteAsync(ResourceOfGuid resource, WriteOperationKind writeOperation, CancellationToken cancellationToken) { throw new NotImplementedException(); } public Task<IIdentifiable?> OnSetToOneRelationshipAsync(ResourceOfGuid leftResource, HasOneAttribute hasOneRelationship, IIdentifiable? rightResourceId, WriteOperationKind writeOperation, CancellationToken cancellationToken) { throw new NotImplementedException(); } public Task OnSetToManyRelationshipAsync(ResourceOfGuid leftResource, HasManyAttribute hasManyRelationship, ISet<IIdentifiable> rightResourceIds, WriteOperationKind writeOperation, CancellationToken cancellationToken) { throw new NotImplementedException(); } public Task OnAddToRelationshipAsync(Guid leftResourceId, HasManyAttribute hasManyRelationship, ISet<IIdentifiable> rightResourceIds, CancellationToken cancellationToken) { throw new NotImplementedException(); } public Task OnRemoveFromRelationshipAsync(ResourceOfGuid leftResource, HasManyAttribute hasManyRelationship, ISet<IIdentifiable> rightResourceIds, CancellationToken cancellationToken) { throw new NotImplementedException(); } public Task OnWritingAsync(ResourceOfGuid resource, WriteOperationKind writeOperation, CancellationToken cancellationToken) { throw new NotImplementedException(); } public Task OnWriteSucceededAsync(ResourceOfGuid resource, WriteOperationKind writeOperation, CancellationToken cancellationToken) { throw new NotImplementedException(); } public void OnDeserialize(ResourceOfGuid resource) { throw new NotImplementedException(); } public void OnSerialize(ResourceOfGuid resource) { throw new NotImplementedException(); } } [UsedImplicitly(ImplicitUseTargetFlags.Members)] private sealed class TestDbContext : DbContext { public DbSet<ResourceOfInt32> ResourcesOfInt32 => Set<ResourceOfInt32>(); public DbSet<ResourceOfGuid> ResourcesOfGuid => Set<ResourceOfGuid>(); public DbSet<Person> People => Set<Person>(); public TestDbContext(DbContextOptions<TestDbContext> options) : base(options) { } } [UsedImplicitly(ImplicitUseKindFlags.Access)] private sealed class Person : Identifiable<int> { } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace App.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
using System; using System.Collections.Generic; using System.Text; using XecMe.Core.Tasks; using System.Threading; using XecMe.Core.Utils; using System.Collections.Specialized; using System.Diagnostics; namespace XecMe.Core.Tasks { /// <summary> /// Timer task runner /// </summary> /// <seealso cref="XecMe.Core.Tasks.TaskRunner" /> public class TimerTaskRunner : TaskRunner { /// <summary> /// The interval /// </summary> private long _interval; /// <summary> /// The recurrence/ /// </summary> private long _recurrence; /// <summary> /// The start date time /// </summary> private DateTime _startDateTime = DateTime.MinValue; /// <summary> /// The end date time /// </summary> private DateTime _endDateTime = DateTime.MaxValue; /// <summary> /// The day start time /// </summary> private TimeSpan _dayStartTime = TimeSpan.FromSeconds(0); /// <summary> /// The day end time /// </summary> private TimeSpan _dayEndTime = TimeSpan.FromSeconds(86399); /// <summary> /// The weekdays /// </summary> private Weekdays _weekdays = Weekdays.All; /// <summary> /// The timer /// </summary> private Timer _timer; /// <summary> /// The task /// </summary> private TaskWrapper _task; /// <summary> /// The time zone information /// </summary> private TimeZoneInfo _timeZoneInfo; /// <summary> /// Initializes a new instance of the <see cref="TimerTaskRunner"/> class. /// </summary> /// <param name="name">The name.</param> /// <param name="taskType">Type of the task.</param> /// <param name="parameters">The parameters.</param> /// <param name="interval">The interval.</param> /// <param name="recurrence">The recurrence.</param> /// <param name="weekdays">The weekdays.</param> /// <param name="startDateTime">The start date time.</param> /// <param name="endDateTime">The end date time.</param> /// <param name="dayStartTime">The day start time.</param> /// <param name="dayEndTime">The day end time.</param> /// <param name="timeZoneInfo">The time zone information.</param> /// <param name="traceType">Type of the trace.</param> /// <exception cref="ArgumentOutOfRangeException"> /// Interval cannot be less than 1 /// or /// Recurrence has to be greater than 0 or euqal to -1 /// or /// Start date time should be less than End date time /// or /// Start time cannot be negative /// or /// End time cannot be negative /// or /// Start time should be less than 23:59:59 /// or /// End time should be less than 23:59:59 /// or /// No weekday is selected to run the task /// </exception> public TimerTaskRunner(string name, Type taskType, Dictionary<string, object> parameters, long interval, long recurrence, Weekdays weekdays, DateTime startDateTime, DateTime endDateTime, TimeSpan dayStartTime, TimeSpan dayEndTime, TimeZoneInfo timeZoneInfo, LogType traceType) : base(name, taskType, parameters, traceType) { /*} public TimerTaskRunner(string name, Type taskType, StringDictionary parameters, long interval, long recurrence, DateTime startDateTime, DateTime endDateTime, TimeSpan dayStartTime, TimeSpan dayEndTime, TimeZoneInfo timeZoneInfo) : base(name, taskType, parameters) {*/ if (interval < 1) throw new ArgumentOutOfRangeException(nameof(interval), "Interval cannot be less than 1"); if (recurrence != -1 && recurrence < 1) throw new ArgumentOutOfRangeException(nameof(recurrence), "Recurrence has to be greater than 0 or euqal to -1"); if (endDateTime < startDateTime) throw new ArgumentOutOfRangeException(nameof(startDateTime), "Start date time should be less than End date time"); if (dayStartTime < Time.DayMinTime) throw new ArgumentOutOfRangeException(nameof(dayStartTime), "Start time cannot be negative"); if (dayEndTime < Time.DayMinTime) throw new ArgumentOutOfRangeException(nameof(dayEndTime), "End time cannot be negative"); if (dayStartTime > Time.DayMaxTime) throw new ArgumentOutOfRangeException(nameof(dayStartTime), "Start time should be less than 23:59:59"); if (dayEndTime > Time.DayMaxTime) throw new ArgumentOutOfRangeException(nameof(dayEndTime), "End time should be less than 23:59:59"); if (weekdays == Weekdays.None) throw new ArgumentOutOfRangeException(nameof(weekdays), "No weekday is selected to run the task"); _weekdays = weekdays; _timeZoneInfo = timeZoneInfo ?? TimeZoneInfo.Local; _interval = interval; _recurrence = recurrence; _startDateTime = startDateTime; _endDateTime = endDateTime; _dayStartTime = dayStartTime; _dayEndTime = dayEndTime; } /// <summary> /// Gets the interval. /// </summary> /// <value> /// The interval. /// </value> public long Interval { get { return _interval; } } /// <summary> /// Gets the recurrence. /// </summary> /// <value> /// The recurrence. /// </value> public long Recurrence { get { return _recurrence; } } /// <summary> /// Gets the start date time. /// </summary> /// <value> /// The start date time. /// </value> public DateTime StartDateTime { get { return _startDateTime; } } /// <summary> /// Gets the end date time. /// </summary> /// <value> /// The end date time. /// </value> public DateTime EndDateTime { get { return _endDateTime; } } /// <summary> /// Gets the day start time. /// </summary> /// <value> /// The day start time. /// </value> public TimeSpan DayStartTime { get { return _dayStartTime; } } /// <summary> /// Gets the day end time. /// </summary> /// <value> /// The day end time. /// </value> public TimeSpan DayEndTime { get { return _dayEndTime; } } /// <summary> /// Gets the time zone. /// </summary> /// <value> /// The time zone. /// </value> public TimeZoneInfo TimeZone { get { return _timeZoneInfo; } } #region TaskRunner Members /// <summary> /// Starts this instance. /// </summary> public override void Start() { lock (this) { if (_timer == null) { _task = new TaskWrapper(this.TaskType, new ExecutionContext(Parameters, this)); _timer = new Timer(new TimerCallback(RunTask), null, Interval, Interval); base.Start(); TraceInformation("Started"); } } } /// <summary> /// Stops this instance. /// </summary> public override void Stop() { lock (this) { if (_timer != null) { using (_timer) ; _timer = null; _task.Release(); _task = null; base.Stop(); TraceInformation("Stopped"); } } } #endregion /// <summary> /// Gets the now. /// </summary> /// <value> /// The now. /// </value> private DateTime Now { get { DateTime now; if (_timeZoneInfo == null || _timeZoneInfo == TimeZoneInfo.Local) now = DateTime.Now; else now = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, _timeZoneInfo); TraceInformation("Now: {0}", now); return now; } } /// <summary> /// Runs the task. /// </summary> /// <param name="state">The state.</param> private void RunTask(object state) { ///Task not started, call should never come here if (_timer == null) return; DateTime today = Now; ///Not in the limit of the date time range if (today > _endDateTime) { Stop(); return; } ///Sleep until the interval duration before start time if (today < _startDateTime) { TimeSpan wait = TimeZoneInfo.ConvertTimeToUtc(_startDateTime, _timeZoneInfo).Subtract(TimeZoneInfo.ConvertTimeToUtc(today, _timeZoneInfo)); TraceInformation("will wait for {0} before it starts", wait); _timer.Change((long)wait.TotalMilliseconds, _interval); return; } ///Not in the range of time of the day or avalid weekday if (Time.Disallow(today, _dayStartTime, _dayEndTime, _weekdays)) { DateTime st = new DateTime(today.Year, today.Month, today.Day, _dayStartTime.Hours, _dayStartTime.Minutes, _dayStartTime.Seconds, DateTimeKind.Unspecified); ///If its not an allowed weekday, wait until next start of day if (!Utils.HasWeekday(_weekdays, Utils.GetWeekday(today.DayOfWeek)) || today > st) st = st.AddDays(1).Date; ///Find the differene by converting to UTC time to make sure daylight cutover are accounted TimeSpan wait = TimeZoneInfo.ConvertTimeToUtc(st, _timeZoneInfo) - TimeZoneInfo.ConvertTimeToUtc(today, _timeZoneInfo); //TimeSpan wait = st.Subtract(now); TraceInformation("will wait for {0} before it starts", wait); _timer.Change((long)wait.TotalMilliseconds, _interval); return; } if (_recurrence > 0 || _recurrence == -1) { ///Stop the timer _timer.Change(Timeout.Infinite, _interval); ExecutionState executionState = _task.RunTask(); switch (executionState) { case ExecutionState.Executed: RaiseComplete(_task.Context); break; case ExecutionState.Stop: _task.Release(); Stop(); return; case ExecutionState.Recycle: _task.Release(); _task = new TaskWrapper(this.TaskType, new ExecutionContext(Parameters, this)); break; } if (_recurrence != -1) _recurrence--; ///Resume the timer _timer.Change(Interval, _interval); } else { Stop(); TraceInformation("stopped because the reccurence is 0 "); } } } }
/* * OANDA v20 REST API * * The full OANDA v20 REST API Specification. This specification defines how to interact with v20 Accounts, Trades, Orders, Pricing and more. * * OpenAPI spec version: 3.0.15 * Contact: api@oanda.com * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; namespace Oanda.RestV20.Model { /// <summary> /// An AccountChanges Object is used to represent the changes to an Account&#39;s Orders, Trades and Positions since a specified Account TransactionID in the past. /// </summary> [DataContract] public partial class AccountChanges : IEquatable<AccountChanges>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="AccountChanges" /> class. /// </summary> /// <param name="OrdersCreated">The Orders created. These Orders may have been filled, cancelled or triggered in the same period..</param> /// <param name="OrdersCancelled">The Orders cancelled..</param> /// <param name="OrdersFilled">The Orders filled..</param> /// <param name="OrdersTriggered">The Orders triggered..</param> /// <param name="TradesOpened">The Trades opened..</param> /// <param name="TradesReduced">The Trades reduced..</param> /// <param name="TradesClosed">The Trades closed..</param> /// <param name="Positions">The Positions changed..</param> /// <param name="Transactions">The Transactions that have been generated..</param> public AccountChanges(List<Order> OrdersCreated = default(List<Order>), List<Order> OrdersCancelled = default(List<Order>), List<Order> OrdersFilled = default(List<Order>), List<Order> OrdersTriggered = default(List<Order>), List<TradeSummary> TradesOpened = default(List<TradeSummary>), List<TradeSummary> TradesReduced = default(List<TradeSummary>), List<TradeSummary> TradesClosed = default(List<TradeSummary>), List<Position> Positions = default(List<Position>), List<Transaction> Transactions = default(List<Transaction>)) { this.OrdersCreated = OrdersCreated; this.OrdersCancelled = OrdersCancelled; this.OrdersFilled = OrdersFilled; this.OrdersTriggered = OrdersTriggered; this.TradesOpened = TradesOpened; this.TradesReduced = TradesReduced; this.TradesClosed = TradesClosed; this.Positions = Positions; this.Transactions = Transactions; } /// <summary> /// The Orders created. These Orders may have been filled, cancelled or triggered in the same period. /// </summary> /// <value>The Orders created. These Orders may have been filled, cancelled or triggered in the same period.</value> [DataMember(Name="ordersCreated", EmitDefaultValue=false)] public List<Order> OrdersCreated { get; set; } /// <summary> /// The Orders cancelled. /// </summary> /// <value>The Orders cancelled.</value> [DataMember(Name="ordersCancelled", EmitDefaultValue=false)] public List<Order> OrdersCancelled { get; set; } /// <summary> /// The Orders filled. /// </summary> /// <value>The Orders filled.</value> [DataMember(Name="ordersFilled", EmitDefaultValue=false)] public List<Order> OrdersFilled { get; set; } /// <summary> /// The Orders triggered. /// </summary> /// <value>The Orders triggered.</value> [DataMember(Name="ordersTriggered", EmitDefaultValue=false)] public List<Order> OrdersTriggered { get; set; } /// <summary> /// The Trades opened. /// </summary> /// <value>The Trades opened.</value> [DataMember(Name="tradesOpened", EmitDefaultValue=false)] public List<TradeSummary> TradesOpened { get; set; } /// <summary> /// The Trades reduced. /// </summary> /// <value>The Trades reduced.</value> [DataMember(Name="tradesReduced", EmitDefaultValue=false)] public List<TradeSummary> TradesReduced { get; set; } /// <summary> /// The Trades closed. /// </summary> /// <value>The Trades closed.</value> [DataMember(Name="tradesClosed", EmitDefaultValue=false)] public List<TradeSummary> TradesClosed { get; set; } /// <summary> /// The Positions changed. /// </summary> /// <value>The Positions changed.</value> [DataMember(Name="positions", EmitDefaultValue=false)] public List<Position> Positions { get; set; } /// <summary> /// The Transactions that have been generated. /// </summary> /// <value>The Transactions that have been generated.</value> [DataMember(Name="transactions", EmitDefaultValue=false)] public List<Transaction> Transactions { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class AccountChanges {\n"); sb.Append(" OrdersCreated: ").Append(OrdersCreated).Append("\n"); sb.Append(" OrdersCancelled: ").Append(OrdersCancelled).Append("\n"); sb.Append(" OrdersFilled: ").Append(OrdersFilled).Append("\n"); sb.Append(" OrdersTriggered: ").Append(OrdersTriggered).Append("\n"); sb.Append(" TradesOpened: ").Append(TradesOpened).Append("\n"); sb.Append(" TradesReduced: ").Append(TradesReduced).Append("\n"); sb.Append(" TradesClosed: ").Append(TradesClosed).Append("\n"); sb.Append(" Positions: ").Append(Positions).Append("\n"); sb.Append(" Transactions: ").Append(Transactions).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { // credit: http://stackoverflow.com/a/10454552/677735 return this.Equals(obj as AccountChanges); } /// <summary> /// Returns true if AccountChanges instances are equal /// </summary> /// <param name="other">Instance of AccountChanges to be compared</param> /// <returns>Boolean</returns> public bool Equals(AccountChanges other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.OrdersCreated == other.OrdersCreated || this.OrdersCreated != null && this.OrdersCreated.SequenceEqual(other.OrdersCreated) ) && ( this.OrdersCancelled == other.OrdersCancelled || this.OrdersCancelled != null && this.OrdersCancelled.SequenceEqual(other.OrdersCancelled) ) && ( this.OrdersFilled == other.OrdersFilled || this.OrdersFilled != null && this.OrdersFilled.SequenceEqual(other.OrdersFilled) ) && ( this.OrdersTriggered == other.OrdersTriggered || this.OrdersTriggered != null && this.OrdersTriggered.SequenceEqual(other.OrdersTriggered) ) && ( this.TradesOpened == other.TradesOpened || this.TradesOpened != null && this.TradesOpened.SequenceEqual(other.TradesOpened) ) && ( this.TradesReduced == other.TradesReduced || this.TradesReduced != null && this.TradesReduced.SequenceEqual(other.TradesReduced) ) && ( this.TradesClosed == other.TradesClosed || this.TradesClosed != null && this.TradesClosed.SequenceEqual(other.TradesClosed) ) && ( this.Positions == other.Positions || this.Positions != null && this.Positions.SequenceEqual(other.Positions) ) && ( this.Transactions == other.Transactions || this.Transactions != null && this.Transactions.SequenceEqual(other.Transactions) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks etc, of course :) if (this.OrdersCreated != null) hash = hash * 59 + this.OrdersCreated.GetHashCode(); if (this.OrdersCancelled != null) hash = hash * 59 + this.OrdersCancelled.GetHashCode(); if (this.OrdersFilled != null) hash = hash * 59 + this.OrdersFilled.GetHashCode(); if (this.OrdersTriggered != null) hash = hash * 59 + this.OrdersTriggered.GetHashCode(); if (this.TradesOpened != null) hash = hash * 59 + this.TradesOpened.GetHashCode(); if (this.TradesReduced != null) hash = hash * 59 + this.TradesReduced.GetHashCode(); if (this.TradesClosed != null) hash = hash * 59 + this.TradesClosed.GetHashCode(); if (this.Positions != null) hash = hash * 59 + this.Positions.GetHashCode(); if (this.Transactions != null) hash = hash * 59 + this.Transactions.GetHashCode(); return hash; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext) { yield break; } } }
using SIL.Windows.Forms.Widgets; namespace SIL.Windows.Forms.WritingSystems { partial class WSFontControl { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (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.components = new System.ComponentModel.Container(); this._fontComboBox = new System.Windows.Forms.ComboBox(); this._fontSizeComboBox = new System.Windows.Forms.ComboBox(); this._fontLabel = new System.Windows.Forms.Label(); this._sizeLabel = new System.Windows.Forms.Label(); this._rightToLeftCheckBox = new System.Windows.Forms.CheckBox(); this._tableLayoutPanelMain = new System.Windows.Forms.TableLayoutPanel(); this.tableLayoutPanelTestArea = new System.Windows.Forms.TableLayoutPanel(); this._testArea = new System.Windows.Forms.TextBox(); this._testAreaLabel = new System.Windows.Forms.Label(); this._fontNotAvailableLabel = new System.Windows.Forms.Label(); this._promptForFontTestArea = new SIL.Windows.Forms.Widgets.Prompt(); this._l10NSharpExtender = new L10NSharp.UI.L10NSharpExtender(this.components); this._tableLayoutPanelMain.SuspendLayout(); this.tableLayoutPanelTestArea.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this._l10NSharpExtender)).BeginInit(); this.SuspendLayout(); // // _fontComboBox // this._fontComboBox.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this._fontComboBox.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.Append; this._fontComboBox.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.ListItems; this._fontComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.Simple; this._fontComboBox.FormattingEnabled = true; this._fontComboBox.IntegralHeight = false; this._l10NSharpExtender.SetLocalizableToolTip(this._fontComboBox, null); this._l10NSharpExtender.SetLocalizationComment(this._fontComboBox, null); this._l10NSharpExtender.SetLocalizationPriority(this._fontComboBox, L10NSharp.LocalizationPriority.NotLocalizable); this._l10NSharpExtender.SetLocalizingId(this._fontComboBox, "WSFontControl._fontComboBox"); this._fontComboBox.Location = new System.Drawing.Point(3, 19); this._fontComboBox.Name = "_fontComboBox"; this._fontComboBox.Size = new System.Drawing.Size(292, 143); this._fontComboBox.TabIndex = 1; this._fontComboBox.TextChanged += new System.EventHandler(this.FontComboBox_TextChanged); // // _fontSizeComboBox // this._fontSizeComboBox.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this._fontSizeComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.Simple; this._fontSizeComboBox.FormatString = "N2"; this._fontSizeComboBox.FormattingEnabled = true; this._fontSizeComboBox.IntegralHeight = false; this._fontSizeComboBox.Items.AddRange(new object[] { "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24"}); this._l10NSharpExtender.SetLocalizableToolTip(this._fontSizeComboBox, null); this._l10NSharpExtender.SetLocalizationComment(this._fontSizeComboBox, null); this._l10NSharpExtender.SetLocalizationPriority(this._fontSizeComboBox, L10NSharp.LocalizationPriority.NotLocalizable); this._l10NSharpExtender.SetLocalizingId(this._fontSizeComboBox, "WSFontControl._fontSizeComboBox"); this._fontSizeComboBox.Location = new System.Drawing.Point(301, 19); this._fontSizeComboBox.Name = "_fontSizeComboBox"; this._fontSizeComboBox.Size = new System.Drawing.Size(174, 143); this._fontSizeComboBox.TabIndex = 3; this._fontSizeComboBox.TextChanged += new System.EventHandler(this.FontSizeComboBox_TextChanged); // // _fontLabel // this._fontLabel.Font = new System.Drawing.Font("Segoe UI", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this._l10NSharpExtender.SetLocalizableToolTip(this._fontLabel, null); this._l10NSharpExtender.SetLocalizationComment(this._fontLabel, null); this._l10NSharpExtender.SetLocalizingId(this._fontLabel, "WSFontControl.Font"); this._fontLabel.Location = new System.Drawing.Point(3, 0); this._fontLabel.Name = "_fontLabel"; this._fontLabel.Size = new System.Drawing.Size(292, 16); this._fontLabel.TabIndex = 0; this._fontLabel.Text = "&Font:"; // // _sizeLabel // this._sizeLabel.Font = new System.Drawing.Font("Segoe UI", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this._l10NSharpExtender.SetLocalizableToolTip(this._sizeLabel, null); this._l10NSharpExtender.SetLocalizationComment(this._sizeLabel, null); this._l10NSharpExtender.SetLocalizingId(this._sizeLabel, "WSFontControl.Size"); this._sizeLabel.Location = new System.Drawing.Point(301, 0); this._sizeLabel.Name = "_sizeLabel"; this._sizeLabel.Size = new System.Drawing.Size(170, 14); this._sizeLabel.TabIndex = 2; this._sizeLabel.Text = "&Size:"; // // _rightToLeftCheckBox // this._tableLayoutPanelMain.SetColumnSpan(this._rightToLeftCheckBox, 2); this._l10NSharpExtender.SetLocalizableToolTip(this._rightToLeftCheckBox, null); this._l10NSharpExtender.SetLocalizationComment(this._rightToLeftCheckBox, null); this._l10NSharpExtender.SetLocalizingId(this._rightToLeftCheckBox, "WSFontControl.RightToLeftWS"); this._rightToLeftCheckBox.Location = new System.Drawing.Point(3, 168); this._rightToLeftCheckBox.Name = "_rightToLeftCheckBox"; this._rightToLeftCheckBox.Size = new System.Drawing.Size(472, 24); this._rightToLeftCheckBox.TabIndex = 3; this._rightToLeftCheckBox.Text = "This is a &right to left writing system."; this._rightToLeftCheckBox.UseVisualStyleBackColor = false; this._rightToLeftCheckBox.CheckedChanged += new System.EventHandler(this.RightToLeftCheckBox_CheckedChanged); // // _tableLayoutPanelMain // this._tableLayoutPanelMain.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this._tableLayoutPanelMain.ColumnCount = 2; this._tableLayoutPanelMain.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 298F)); this._tableLayoutPanelMain.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F)); this._tableLayoutPanelMain.Controls.Add(this._rightToLeftCheckBox, 0, 2); this._tableLayoutPanelMain.Controls.Add(this._fontSizeComboBox, 1, 1); this._tableLayoutPanelMain.Controls.Add(this._fontComboBox, 0, 1); this._tableLayoutPanelMain.Controls.Add(this._fontLabel, 0, 0); this._tableLayoutPanelMain.Controls.Add(this._sizeLabel, 1, 0); this._tableLayoutPanelMain.Controls.Add(this.tableLayoutPanelTestArea, 0, 3); this._tableLayoutPanelMain.Location = new System.Drawing.Point(0, 0); this._tableLayoutPanelMain.Name = "_tableLayoutPanelMain"; this._tableLayoutPanelMain.RowCount = 4; this._tableLayoutPanelMain.RowStyles.Add(new System.Windows.Forms.RowStyle()); this._tableLayoutPanelMain.RowStyles.Add(new System.Windows.Forms.RowStyle()); this._tableLayoutPanelMain.RowStyles.Add(new System.Windows.Forms.RowStyle()); this._tableLayoutPanelMain.RowStyles.Add(new System.Windows.Forms.RowStyle()); this._tableLayoutPanelMain.Size = new System.Drawing.Size(478, 303); this._tableLayoutPanelMain.TabIndex = 0; // // tableLayoutPanelTestArea // this.tableLayoutPanelTestArea.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.tableLayoutPanelTestArea.AutoSize = true; this.tableLayoutPanelTestArea.ColumnCount = 2; this._tableLayoutPanelMain.SetColumnSpan(this.tableLayoutPanelTestArea, 2); this.tableLayoutPanelTestArea.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle()); this.tableLayoutPanelTestArea.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F)); this.tableLayoutPanelTestArea.Controls.Add(this._testAreaLabel, 0, 0); this.tableLayoutPanelTestArea.Controls.Add(this._fontNotAvailableLabel, 1, 0); this.tableLayoutPanelTestArea.Controls.Add(this._testArea, 0, 1); this.tableLayoutPanelTestArea.Location = new System.Drawing.Point(3, 198); this.tableLayoutPanelTestArea.Name = "tableLayoutPanelTestArea"; this.tableLayoutPanelTestArea.RowCount = 2; this.tableLayoutPanelTestArea.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.tableLayoutPanelTestArea.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F)); this.tableLayoutPanelTestArea.Size = new System.Drawing.Size(472, 102); this.tableLayoutPanelTestArea.TabIndex = 4; // // _testArea // this._testArea.AcceptsReturn = true; this._testArea.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.tableLayoutPanelTestArea.SetColumnSpan(this._testArea, 2); this._l10NSharpExtender.SetLocalizableToolTip(this._testArea, null); this._l10NSharpExtender.SetLocalizationComment(this._testArea, null); this._l10NSharpExtender.SetLocalizationPriority(this._testArea, L10NSharp.LocalizationPriority.NotLocalizable); this._l10NSharpExtender.SetLocalizingId(this._testArea, "WSFontControl._testArea"); this._testArea.Location = new System.Drawing.Point(3, 16); this._testArea.Multiline = true; this._testArea.Name = "_testArea"; this._testArea.Size = new System.Drawing.Size(466, 83); this._testArea.TabIndex = 5; this._testArea.Enter += new System.EventHandler(this._testArea_Enter); this._testArea.Leave += new System.EventHandler(this._testArea_Leave); // // _testAreaLabel // this._testAreaLabel.AutoSize = true; this._l10NSharpExtender.SetLocalizableToolTip(this._testAreaLabel, null); this._l10NSharpExtender.SetLocalizationComment(this._testAreaLabel, null); this._l10NSharpExtender.SetLocalizingId(this._testAreaLabel, "WSFontControl.TestArea"); this._testAreaLabel.Location = new System.Drawing.Point(3, 0); this._testAreaLabel.Name = "_testAreaLabel"; this._testAreaLabel.Size = new System.Drawing.Size(56, 13); this._testAreaLabel.TabIndex = 0; this._testAreaLabel.Text = "&Test Area:"; // // _fontNotAvailableLabel // this._fontNotAvailableLabel.AutoSize = true; this._fontNotAvailableLabel.ForeColor = System.Drawing.Color.Red; this._l10NSharpExtender.SetLocalizableToolTip(this._fontNotAvailableLabel, null); this._l10NSharpExtender.SetLocalizationComment(this._fontNotAvailableLabel, null); this._l10NSharpExtender.SetLocalizingId(this._fontNotAvailableLabel, "WSFontControl.FontNotAvailable"); this._fontNotAvailableLabel.Location = new System.Drawing.Point(65, 0); this._fontNotAvailableLabel.Name = "_fontNotAvailableLabel"; this._fontNotAvailableLabel.Size = new System.Drawing.Size(317, 13); this._fontNotAvailableLabel.TabIndex = 1; this._fontNotAvailableLabel.Text = "(The selected font is not available on this machine. Using default.)"; this._fontNotAvailableLabel.Visible = false; // // _l10NSharpExtender // this._l10NSharpExtender.LocalizationManagerId = "Palaso"; this._l10NSharpExtender.PrefixForNewItems = "WSFontControl"; // // WSFontControl // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Controls.Add(this._tableLayoutPanelMain); this._l10NSharpExtender.SetLocalizableToolTip(this, null); this._l10NSharpExtender.SetLocalizationComment(this, null); this._l10NSharpExtender.SetLocalizationPriority(this, L10NSharp.LocalizationPriority.NotLocalizable); this._l10NSharpExtender.SetLocalizingId(this, "WSFontControl.WSFontControl"); this.Name = "WSFontControl"; this.Size = new System.Drawing.Size(478, 303); this._tableLayoutPanelMain.ResumeLayout(false); this._tableLayoutPanelMain.PerformLayout(); this.tableLayoutPanelTestArea.ResumeLayout(false); this.tableLayoutPanelTestArea.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this._l10NSharpExtender)).EndInit(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.ComboBox _fontComboBox; private System.Windows.Forms.ComboBox _fontSizeComboBox; private System.Windows.Forms.Label _fontLabel; private System.Windows.Forms.Label _sizeLabel; private System.Windows.Forms.CheckBox _rightToLeftCheckBox; private Prompt _promptForFontTestArea; private System.Windows.Forms.TableLayoutPanel _tableLayoutPanelMain; private L10NSharp.UI.L10NSharpExtender _l10NSharpExtender; private System.Windows.Forms.TableLayoutPanel tableLayoutPanelTestArea; private System.Windows.Forms.Label _testAreaLabel; private System.Windows.Forms.Label _fontNotAvailableLabel; private System.Windows.Forms.TextBox _testArea; } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Xml.XPath; using FT = MS.Internal.Xml.XPath.Function.FunctionType; namespace MS.Internal.Xml.XPath { internal sealed class QueryBuilder { // Note: Up->Doun, Down->Up: // For operators order is normal: 1 + 2 --> Operator+(1, 2) // For pathes order is reversed: a/b -> ChildQuery_B(input: ChildQuery_A(input: ContextQuery())) // Input flags. We pass them Up->Down. // Using them upper query set states wich controls how inner query will be built. enum Flags { None = 0x00, SmartDesc = 0x01, PosFilter = 0x02, // Node has this flag set when it has position predicate applied to it Filter = 0x04, // Subtree we compiling will be filtered. i.e. Flag not set on rightmost filter. } // Output props. We return them Down->Up. // These are properties of Query tree we have built already. // These properties are closely related to QueryProps exposed by Query node itself. // They have the following difference: // QueryProps describe property of node they are (belong like Reverse) // these Props describe acumulated properties of the tree (like nonFlat) enum Props { None = 0x00, PosFilter = 0x01, // This filter or inner filter was positional: foo[1] or foo[1][true()] HasPosition = 0x02, // Expression may ask position() of the context HasLast = 0x04, // Expression may ask last() of the context NonFlat = 0x08, // Some nodes may be descendent of otheres } // comment are aproximate. This is my best understanding: private string query; private bool allowVar; private bool allowKey; private bool allowCurrent; private bool needContext; private BaseAxisQuery firstInput; // Input of the leftmost predicate. Set by leftmost predicate, used in rightmost one private void Reset() { parseDepth = 0; needContext = false; } private Query ProcessAxis(Axis root, Flags flags, out Props props) { Query result = null; if (root.Prefix.Length > 0) { needContext = true; } firstInput = null; Query qyInput; { if (root.Input != null) { Flags inputFlags = Flags.None; if ((flags & Flags.PosFilter) == 0) { Axis input = root.Input as Axis; if (input != null) { if ( root.TypeOfAxis == Axis.AxisType.Child && input.TypeOfAxis == Axis.AxisType.DescendantOrSelf && input.NodeType == XPathNodeType.All ) { Query qyGrandInput; if (input.Input != null) { qyGrandInput = ProcessNode(input.Input, Flags.SmartDesc, out props); } else { qyGrandInput = new ContextQuery(); props = Props.None; } result = new DescendantQuery(qyGrandInput, root.Name, root.Prefix, root.NodeType, false, input.AbbrAxis); if ((props & Props.NonFlat) != 0) { result = new DocumentOrderQuery(result); } props |= Props.NonFlat; return result; } } if (root.TypeOfAxis == Axis.AxisType.Descendant || root.TypeOfAxis == Axis.AxisType.DescendantOrSelf) { inputFlags |= Flags.SmartDesc; } } qyInput = ProcessNode(root.Input, inputFlags, out props); } else { qyInput = new ContextQuery(); props = Props.None; } } switch (root.TypeOfAxis) { case Axis.AxisType.Ancestor: result = new XPathAncestorQuery(qyInput, root.Name, root.Prefix, root.NodeType, false); props |= Props.NonFlat; break; case Axis.AxisType.AncestorOrSelf: result = new XPathAncestorQuery(qyInput, root.Name, root.Prefix, root.NodeType, true); props |= Props.NonFlat; break; case Axis.AxisType.Child: if ((props & Props.NonFlat) != 0) { result = new CacheChildrenQuery(qyInput, root.Name, root.Prefix, root.NodeType); } else { result = new ChildrenQuery(qyInput, root.Name, root.Prefix, root.NodeType); } break; case Axis.AxisType.Parent: result = new ParentQuery(qyInput, root.Name, root.Prefix, root.NodeType); break; case Axis.AxisType.Descendant: if ((flags & Flags.SmartDesc) != 0) { result = new DescendantOverDescendantQuery(qyInput, false, root.Name, root.Prefix, root.NodeType, /*abbrAxis:*/false); } else { result = new DescendantQuery(qyInput, root.Name, root.Prefix, root.NodeType, false, /*abbrAxis:*/false); if ((props & Props.NonFlat) != 0) { result = new DocumentOrderQuery(result); } } props |= Props.NonFlat; break; case Axis.AxisType.DescendantOrSelf: if ((flags & Flags.SmartDesc) != 0) { result = new DescendantOverDescendantQuery(qyInput, true, root.Name, root.Prefix, root.NodeType, root.AbbrAxis); } else { result = new DescendantQuery(qyInput, root.Name, root.Prefix, root.NodeType, true, root.AbbrAxis); if ((props & Props.NonFlat) != 0) { result = new DocumentOrderQuery(result); } } props |= Props.NonFlat; break; case Axis.AxisType.Preceding: result = new PrecedingQuery(qyInput, root.Name, root.Prefix, root.NodeType); props |= Props.NonFlat; break; case Axis.AxisType.Following: result = new FollowingQuery(qyInput, root.Name, root.Prefix, root.NodeType); props |= Props.NonFlat; break; case Axis.AxisType.FollowingSibling: result = new FollSiblingQuery(qyInput, root.Name, root.Prefix, root.NodeType); if ((props & Props.NonFlat) != 0) { result = new DocumentOrderQuery(result); } break; case Axis.AxisType.PrecedingSibling: result = new PreSiblingQuery(qyInput, root.Name, root.Prefix, root.NodeType); break; case Axis.AxisType.Attribute: result = new AttributeQuery(qyInput, root.Name, root.Prefix, root.NodeType); break; case Axis.AxisType.Self: result = new XPathSelfQuery(qyInput, root.Name, root.Prefix, root.NodeType); break; case Axis.AxisType.Namespace: if ((root.NodeType == XPathNodeType.All || root.NodeType == XPathNodeType.Element || root.NodeType == XPathNodeType.Attribute) && root.Prefix.Length == 0) { result = new NamespaceQuery(qyInput, root.Name, root.Prefix, root.NodeType); } else { result = new EmptyQuery(); } break; default: throw XPathException.Create(SR.Xp_NotSupported, query); } return result; } private static bool CanBeNumber(Query q) { return ( q.StaticType == XPathResultType.Any || q.StaticType == XPathResultType.Number ); } private Query ProcessFilter(Filter root, Flags flags, out Props props) { bool first = ((flags & Flags.Filter) == 0); Props propsCond; Query cond = ProcessNode(root.Condition, Flags.None, out propsCond); if ( CanBeNumber(cond) || (propsCond & (Props.HasPosition | Props.HasLast)) != 0 ) { propsCond |= Props.HasPosition; flags |= Flags.PosFilter; } // We don't want DescendantOverDescendant pattern to be recognized here (in case descendent::foo[expr]/descendant::bar) // So we clean this flag here: flags &= ~Flags.SmartDesc; // ToDo: Instead it would be nice to wrap descendent::foo[expr] into special query that will flatten it -- i.e. // remove all nodes that are descendant of other nodes. This is very easy becuase for sorted nodesets all children // follow its parent. One step caching. This can be easyly done by rightmost DescendantQuery itsef. // Interesting note! Can we garatee that DescendantOverDescendant returns flat nodeset? This defenetely true if it's input is flat. Query qyInput = ProcessNode(root.Input, flags | Flags.Filter, out props); if (root.Input.Type != AstNode.AstType.Filter) { // Props.PosFilter is for nested filters only. // We clean it here to avoid cleaning it in all other ast nodes. props &= ~Props.PosFilter; } if ((propsCond & Props.HasPosition) != 0) { // this condition is positional rightmost filter should be avare of this. props |= Props.PosFilter; } /*merging predicates*/ { FilterQuery qyFilter = qyInput as FilterQuery; if (qyFilter != null && (propsCond & Props.HasPosition) == 0 && qyFilter.Condition.StaticType != XPathResultType.Any) { Query prevCond = qyFilter.Condition; if (prevCond.StaticType == XPathResultType.Number) { prevCond = new LogicalExpr(Operator.Op.EQ, new NodeFunctions(FT.FuncPosition, null), prevCond); } cond = new BooleanExpr(Operator.Op.AND, prevCond, cond); qyInput = qyFilter.qyInput; } } if ((props & Props.PosFilter) != 0 && qyInput is DocumentOrderQuery) { qyInput = ((DocumentOrderQuery)qyInput).input; } if (firstInput == null) { firstInput = qyInput as BaseAxisQuery; } bool merge = (qyInput.Properties & QueryProps.Merge) != 0; bool reverse = (qyInput.Properties & QueryProps.Reverse) != 0; if ((propsCond & Props.HasPosition) != 0) { if (reverse) { qyInput = new ReversePositionQuery(qyInput); } else if ((propsCond & Props.HasLast) != 0) { qyInput = new ForwardPositionQuery(qyInput); } } if (first && firstInput != null) { if (merge && (props & Props.PosFilter) != 0) { qyInput = new FilterQuery(qyInput, cond, /*noPosition:*/false); Query parent = firstInput.qyInput; if (!(parent is ContextQuery)) { // we don't need to wrap filter with MergeFilterQuery when cardinality is parent <: ? firstInput.qyInput = new ContextQuery(); firstInput = null; return new MergeFilterQuery(parent, qyInput); } firstInput = null; return qyInput; } firstInput = null; } return new FilterQuery(qyInput, cond, /*noPosition:*/(propsCond & Props.HasPosition) == 0); } private Query ProcessOperator(Operator root, out Props props) { Props props1, props2; Query op1 = ProcessNode(root.Operand1, Flags.None, out props1); Query op2 = ProcessNode(root.Operand2, Flags.None, out props2); props = props1 | props2; switch (root.OperatorType) { case Operator.Op.PLUS: case Operator.Op.MINUS: case Operator.Op.MUL: case Operator.Op.MOD: case Operator.Op.DIV: return new NumericExpr(root.OperatorType, op1, op2); case Operator.Op.LT: case Operator.Op.GT: case Operator.Op.LE: case Operator.Op.GE: case Operator.Op.EQ: case Operator.Op.NE: return new LogicalExpr(root.OperatorType, op1, op2); case Operator.Op.OR: case Operator.Op.AND: return new BooleanExpr(root.OperatorType, op1, op2); case Operator.Op.UNION: props |= Props.NonFlat; return new UnionExpr(op1, op2); default: return null; } } private Query ProcessVariable(Variable root) { needContext = true; if (!allowVar) { throw XPathException.Create(SR.Xp_InvalidKeyPattern, query); } return new VariableQuery(root.Localname, root.Prefix); } private Query ProcessFunction(Function root, out Props props) { props = Props.None; Query qy = null; switch (root.TypeOfFunction) { case FT.FuncLast: qy = new NodeFunctions(root.TypeOfFunction, null); props |= Props.HasLast; return qy; case FT.FuncPosition: qy = new NodeFunctions(root.TypeOfFunction, null); props |= Props.HasPosition; return qy; case FT.FuncCount: return new NodeFunctions(FT.FuncCount, ProcessNode((AstNode)(root.ArgumentList[0]), Flags.None, out props) ); case FT.FuncID: qy = new IDQuery(ProcessNode((AstNode)(root.ArgumentList[0]), Flags.None, out props)); props |= Props.NonFlat; return qy; case FT.FuncLocalName: case FT.FuncNameSpaceUri: case FT.FuncName: if (root.ArgumentList != null && root.ArgumentList.Count > 0) { return new NodeFunctions(root.TypeOfFunction, ProcessNode((AstNode)(root.ArgumentList[0]), Flags.None, out props) ); } else { return new NodeFunctions(root.TypeOfFunction, null); } case FT.FuncString: case FT.FuncConcat: case FT.FuncStartsWith: case FT.FuncContains: case FT.FuncSubstringBefore: case FT.FuncSubstringAfter: case FT.FuncSubstring: case FT.FuncStringLength: case FT.FuncNormalize: case FT.FuncTranslate: return new StringFunctions(root.TypeOfFunction, ProcessArguments(root.ArgumentList, out props)); case FT.FuncNumber: case FT.FuncSum: case FT.FuncFloor: case FT.FuncCeiling: case FT.FuncRound: if (root.ArgumentList != null && root.ArgumentList.Count > 0) { return new NumberFunctions(root.TypeOfFunction, ProcessNode((AstNode)root.ArgumentList[0], Flags.None, out props) ); } else { return new NumberFunctions(Function.FunctionType.FuncNumber, null); } case FT.FuncTrue: case FT.FuncFalse: return new BooleanFunctions(root.TypeOfFunction, null); case FT.FuncNot: case FT.FuncLang: case FT.FuncBoolean: return new BooleanFunctions(root.TypeOfFunction, ProcessNode((AstNode)root.ArgumentList[0], Flags.None, out props) ); case FT.FuncUserDefined: needContext = true; if (!allowCurrent && root.Name == "current" && root.Prefix.Length == 0) { throw XPathException.Create(SR.Xp_CurrentNotAllowed); } if (!allowKey && root.Name == "key" && root.Prefix.Length == 0) { throw XPathException.Create(SR.Xp_InvalidKeyPattern, query); } qy = new FunctionQuery(root.Prefix, root.Name, ProcessArguments(root.ArgumentList, out props)); props |= Props.NonFlat; return qy; default: throw XPathException.Create(SR.Xp_NotSupported, query); } } List<Query> ProcessArguments(List<AstNode> args, out Props props) { int numArgs = args != null ? args.Count : 0; List<Query> argList = new List<Query>(numArgs); props = Props.None; for (int count = 0; count < numArgs; count++) { Props argProps; argList.Add(ProcessNode((AstNode)args[count], Flags.None, out argProps)); props |= argProps; } return argList; } private int parseDepth = 0; private const int MaxParseDepth = 1024; private Query ProcessNode(AstNode root, Flags flags, out Props props) { if (++parseDepth > MaxParseDepth) { throw XPathException.Create(SR.Xp_QueryTooComplex); } Debug.Assert(root != null, "root != null"); Query result = null; props = Props.None; switch (root.Type) { case AstNode.AstType.Axis: result = ProcessAxis((Axis)root, flags, out props); break; case AstNode.AstType.Operator: result = ProcessOperator((Operator)root, out props); break; case AstNode.AstType.Filter: result = ProcessFilter((Filter)root, flags, out props); break; case AstNode.AstType.ConstantOperand: result = new OperandQuery(((Operand)root).OperandValue); break; case AstNode.AstType.Variable: result = ProcessVariable((Variable)root); break; case AstNode.AstType.Function: result = ProcessFunction((Function)root, out props); break; case AstNode.AstType.Group: result = new GroupQuery(ProcessNode(((Group)root).GroupNode, Flags.None, out props)); break; case AstNode.AstType.Root: result = new AbsoluteQuery(); break; default: Debug.Assert(false, "Unknown QueryType encountered!!"); break; } --parseDepth; return result; } private Query Build(AstNode root, string query) { Reset(); Props props; this.query = query; Query result = ProcessNode(root, Flags.None, out props); return result; } internal Query Build(string query, bool allowVar, bool allowKey) { this.allowVar = allowVar; this.allowKey = allowKey; this.allowCurrent = true; return Build(XPathParser.ParseXPathExpresion(query), query); } internal Query Build(string query, out bool needContext) { Query result = Build(query, true, true); needContext = this.needContext; return result; } internal Query BuildPatternQuery(string query, bool allowVar, bool allowKey) { this.allowVar = allowVar; this.allowKey = allowKey; this.allowCurrent = false; return Build(XPathParser.ParseXPathPattern(query), query); } internal Query BuildPatternQuery(string query, out bool needContext) { Query result = BuildPatternQuery(query, true, true); needContext = this.needContext; return result; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System.IO; using System.Runtime.InteropServices; using Microsoft.Win32.SafeHandles; namespace System.Management.Automation.Internal { internal class CabinetExtractor : ICabinetExtractor { /// <summary> /// GC handle which prevents garbage collector from collecting this delegate. /// </summary> private CabinetNativeApi.FdiAllocDelegate _allocDelegate; private GCHandle _fdiAllocHandle; private CabinetNativeApi.FdiFreeDelegate _freeDelegate; private GCHandle _fdiFreeHandle; private CabinetNativeApi.FdiOpenDelegate _openDelegate; private GCHandle _fdiOpenHandle; private CabinetNativeApi.FdiReadDelegate _readDelegate; private GCHandle _fdiReadHandle; private CabinetNativeApi.FdiWriteDelegate _writeDelegate; private GCHandle _fdiWriteHandle; private CabinetNativeApi.FdiCloseDelegate _closeDelegate; private GCHandle _fdiCloseHandle; private CabinetNativeApi.FdiSeekDelegate _seekDelegate; private GCHandle _fdiSeekHandle; private CabinetNativeApi.FdiNotifyDelegate _notifyDelegate; private GCHandle _fdiNotifyHandle; internal CabinetNativeApi.FdiContextHandle fdiContext; // HFDI internal CabinetExtractor() { CabinetNativeApi.FdiERF err = new CabinetNativeApi.FdiERF(); populateDelegates(); // marshal the delegate to a unmanaged function pointer so that AppDomain reference is stored correctly. fdiContext = CabinetNativeApi.FDICreate( Marshal.GetFunctionPointerForDelegate(_allocDelegate), Marshal.GetFunctionPointerForDelegate(_freeDelegate), Marshal.GetFunctionPointerForDelegate(_openDelegate), Marshal.GetFunctionPointerForDelegate(_readDelegate), Marshal.GetFunctionPointerForDelegate(_writeDelegate), Marshal.GetFunctionPointerForDelegate(_closeDelegate), Marshal.GetFunctionPointerForDelegate(_seekDelegate), CabinetNativeApi.FdiCreateCpuType.Cpu80386, err); } #region IDisposable Methods /// <summary> /// Flag: Has Dispose already been called? /// </summary> private bool _disposed = false; /// <summary> /// Protected implementation of Dispose pattern. /// </summary> /// <param name="disposing"></param> protected override void Dispose(bool disposing) { if (_disposed) { return; } // Free managed objects within 'if (disposing)' if needed if (fdiContext != null) { fdiContext.Dispose(); } // Free unmanaged objects here this.CleanUpDelegates(); _disposed = true; // Call base class implementation in case it has resources to release base.Dispose(disposing); } /// <summary> /// Finalizer to ensure destruction of unmanaged resources. /// </summary> ~CabinetExtractor() { Dispose(false); } #endregion internal override bool Extract(string cabinetName, string srcPath, string destPath) { IntPtr nativeDestPath = Marshal.StringToHGlobalAnsi(destPath); bool result = CabinetNativeApi.FDICopy( fdiContext, cabinetName, srcPath, 0, // Not used Marshal.GetFunctionPointerForDelegate(_notifyDelegate), IntPtr.Zero, nativeDestPath); Marshal.FreeHGlobal(nativeDestPath); return result; } /// <summary> /// Creates delegates for the FDI* operation functions. /// </summary> private void populateDelegates() { // if a delegate is re-located by a garbage collection, it will not affect // the underlaying managed callback, so Alloc is used to add a reference // to the delegate, allowing relocation of the delegate, but preventing // disposal. Using GCHandle without pinning reduces fragmentation potential // of the managed heap. _allocDelegate = new CabinetNativeApi.FdiAllocDelegate(CabinetNativeApi.FdiAlloc); _fdiAllocHandle = GCHandle.Alloc(_allocDelegate); _freeDelegate = new CabinetNativeApi.FdiFreeDelegate(CabinetNativeApi.FdiFree); _fdiFreeHandle = GCHandle.Alloc(_freeDelegate); _openDelegate = new CabinetNativeApi.FdiOpenDelegate(CabinetNativeApi.FdiOpen); _fdiOpenHandle = GCHandle.Alloc(_openDelegate); _readDelegate = new CabinetNativeApi.FdiReadDelegate(CabinetNativeApi.FdiRead); _fdiReadHandle = GCHandle.Alloc(_readDelegate); _writeDelegate = new CabinetNativeApi.FdiWriteDelegate(CabinetNativeApi.FdiWrite); _fdiWriteHandle = GCHandle.Alloc(_writeDelegate); _closeDelegate = new CabinetNativeApi.FdiCloseDelegate(CabinetNativeApi.FdiClose); _fdiCloseHandle = GCHandle.Alloc(_closeDelegate); _seekDelegate = new CabinetNativeApi.FdiSeekDelegate(CabinetNativeApi.FdiSeek); _fdiSeekHandle = GCHandle.Alloc(_seekDelegate); _notifyDelegate = new CabinetNativeApi.FdiNotifyDelegate(CabinetNativeApi.FdiNotify); _fdiNotifyHandle = GCHandle.Alloc(_notifyDelegate); } /// <summary> /// Frees all the delegate handles. /// </summary> private void CleanUpDelegates() { // Free GCHandles so that the memory they point to may be unpinned (garbage collected) if (_fdiAllocHandle != null) { _fdiAllocHandle.Free(); _fdiFreeHandle.Free(); _fdiOpenHandle.Free(); _fdiReadHandle.Free(); _fdiWriteHandle.Free(); _fdiCloseHandle.Free(); _fdiSeekHandle.Free(); _fdiNotifyHandle.Free(); } } }; // CabinetExtractor loader implementation internal class CabinetExtractorLoader : ICabinetExtractorLoader { private static CabinetExtractor s_extractorInstance; private static CabinetExtractorLoader s_instance; private static double s_created = 0; internal static CabinetExtractorLoader GetInstance() { if (0 == System.Threading.Interlocked.CompareExchange(ref s_created, 1, 0)) { s_instance = new CabinetExtractorLoader(); s_extractorInstance = new CabinetExtractor(); } return s_instance; } internal override ICabinetExtractor GetCabinetExtractor() { return s_extractorInstance; } }; internal static class CabinetNativeApi { #region Delegates and function definitions [UnmanagedFunctionPointer(CallingConvention.Cdecl, CharSet = CharSet.Ansi)] internal delegate IntPtr FdiAllocDelegate(int size); internal static IntPtr FdiAlloc(int size) { try { return Marshal.AllocHGlobal(size); } catch (OutOfMemoryException) { return IntPtr.Zero; } } [UnmanagedFunctionPointer(CallingConvention.Cdecl, CharSet = CharSet.Ansi)] internal delegate void FdiFreeDelegate(IntPtr memblock); internal static void FdiFree(IntPtr memblock) { Marshal.FreeHGlobal(memblock); } [UnmanagedFunctionPointer(CallingConvention.Cdecl, CharSet = CharSet.Ansi)] internal delegate IntPtr FdiOpenDelegate( [MarshalAs(UnmanagedType.LPStr)] string filename, int oflag, int pmode); internal static IntPtr FdiOpen(string filename, int oflag, int pmode) { FileMode mode = CabinetNativeApi.ConvertOpflagToFileMode(oflag); FileAccess access = CabinetNativeApi.ConvertPermissionModeToFileAccess(pmode); FileShare share = CabinetNativeApi.ConvertPermissionModeToFileShare(pmode); // This method is used for opening the cab file as well as saving the extracted files. // When we are opening the cab file we only need read permissions. // We force read permissions so that non-elevated users can extract cab files. if(mode == FileMode.Open || mode == FileMode.OpenOrCreate) { access = FileAccess.Read; share = FileShare.Read; } try { FileStream stream = new FileStream(filename, mode, access, share); if (stream == null) { return new IntPtr(-1); } return GCHandle.ToIntPtr(GCHandle.Alloc(stream)); } catch (IOException) { return new IntPtr(-1); } } [UnmanagedFunctionPointer(CallingConvention.Cdecl, CharSet = CharSet.Ansi)] internal delegate int FdiReadDelegate( IntPtr fp, [In, Out] [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2, ArraySubType = UnmanagedType.U1)] byte[] buffer, int count); internal static int FdiRead(IntPtr fp, byte[] buffer, int count) { GCHandle handle = GCHandle.FromIntPtr(fp); FileStream stream = (FileStream)handle.Target; int numCharactersRead = 0; try { numCharactersRead = stream.Read(buffer, 0, count); } catch (ArgumentNullException) { numCharactersRead = -1; } catch (ArgumentOutOfRangeException) { numCharactersRead = -1; } catch (NotSupportedException) { numCharactersRead = -1; } catch (IOException) { numCharactersRead = -1; } catch (ArgumentException) { numCharactersRead = -1; } catch (ObjectDisposedException) { numCharactersRead = -1; } return numCharactersRead; } [UnmanagedFunctionPointer(CallingConvention.Cdecl, CharSet = CharSet.Ansi)] internal delegate int FdiWriteDelegate( IntPtr fp, [In] [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2, ArraySubType = UnmanagedType.U1)] byte[] buffer, int count); internal static int FdiWrite(IntPtr fp, byte[] buffer, int count) { GCHandle handle = GCHandle.FromIntPtr(fp); FileStream stream = (FileStream)handle.Target; int numCharactersWritten = 0; try { stream.Write(buffer, 0, count); numCharactersWritten = count; // Write doesn't return the number of bytes written. Per MSDN, if it succeeds, it will have written count bytes. } catch (ArgumentNullException) { numCharactersWritten = -1; } catch (ArgumentOutOfRangeException) { numCharactersWritten = -1; } catch (NotSupportedException) { numCharactersWritten = -1; } catch (IOException) { numCharactersWritten = -1; } catch (ArgumentException) { numCharactersWritten = -1; } catch (ObjectDisposedException) { numCharactersWritten = -1; } return numCharactersWritten; } [UnmanagedFunctionPointer(CallingConvention.Cdecl, CharSet = CharSet.Ansi)] internal delegate int FdiCloseDelegate(IntPtr fp); internal static int FdiClose(IntPtr fp) { GCHandle handle = GCHandle.FromIntPtr(fp); FileStream stream = (FileStream)handle.Target; if (stream == null) { return -1; } else { stream.Dispose(); return 0; } } [UnmanagedFunctionPointer(CallingConvention.Cdecl, CharSet = CharSet.Ansi)] internal delegate int FdiSeekDelegate(IntPtr fp, int offset, int origin); internal static int FdiSeek(IntPtr fp, int offset, int origin) { GCHandle handle = GCHandle.FromIntPtr(fp); FileStream stream = (FileStream)handle.Target; SeekOrigin seekOrigin = CabinetNativeApi.ConvertOriginToSeekOrigin(origin); long status = 0; try { status = stream.Seek(offset, seekOrigin); } catch (NotSupportedException) { status = -1; } catch (IOException) { status = -1; } catch (ArgumentException) { status = -1; } catch (ObjectDisposedException) { status = -1; } return (int)status; } [UnmanagedFunctionPointer(CallingConvention.Cdecl, CharSet = CharSet.Ansi)] internal delegate IntPtr FdiNotifyDelegate(FdiNotificationType fdint, FdiNotification fdin); // Handles FDI notification internal static IntPtr FdiNotify(FdiNotificationType fdint, FdiNotification fdin) { switch (fdint) { case FdiNotificationType.FdintCOPY_FILE: { // TODO: Should I catch exceptions for the new functions? // Copy target directory string destPath = Marshal.PtrToStringAnsi(fdin.pv); // Split the path to a filename and path string fileName = Path.GetFileName(fdin.psz1); string remainingPsz1Path = Path.GetDirectoryName(fdin.psz1); destPath = Path.Combine(destPath, remainingPsz1Path); Directory.CreateDirectory(destPath); // Creates all intermediate directories if necessary. // Create the file string absoluteFilePath = Path.Combine(destPath, fileName); return CabinetNativeApi.FdiOpen(absoluteFilePath, (int)OpFlags.Create, (int)(PermissionMode.Read | PermissionMode.Write)); // TODO: OK to ignore _O_SEQUENTIAL, WrOnly, and _O_BINARY? } case FdiNotificationType.FdintCLOSE_FILE_INFO: { // Close the file CabinetNativeApi.FdiClose(fdin.hf); // Set the file attributes string destPath = Marshal.PtrToStringAnsi(fdin.pv); string absoluteFilePath = Path.Combine(destPath, fdin.psz1); IntPtr hFile = PlatformInvokes.CreateFile( absoluteFilePath, PlatformInvokes.FileDesiredAccess.GenericRead | PlatformInvokes.FileDesiredAccess.GenericWrite, PlatformInvokes.FileShareMode.Read, IntPtr.Zero, PlatformInvokes.FileCreationDisposition.OpenExisting, PlatformInvokes.FileAttributes.Normal, IntPtr.Zero); if (hFile != IntPtr.Zero) { PlatformInvokes.FILETIME ftFile = new PlatformInvokes.FILETIME(); if (PlatformInvokes.DosDateTimeToFileTime(fdin.date, fdin.time, ftFile)) { PlatformInvokes.FILETIME ftLocal = new PlatformInvokes.FILETIME(); if (PlatformInvokes.LocalFileTimeToFileTime(ftFile, ftLocal)) { PlatformInvokes.SetFileTime(hFile, ftLocal, null, ftLocal); } } PlatformInvokes.CloseHandle(hFile); } PlatformInvokes.SetFileAttributesW( absoluteFilePath, (PlatformInvokes.FileAttributes)fdin.attribs & (PlatformInvokes.FileAttributes.ReadOnly | PlatformInvokes.FileAttributes.Hidden | PlatformInvokes.FileAttributes.System | PlatformInvokes.FileAttributes.Archive)); // Call notification function return new IntPtr(1); } } return new IntPtr(0); } #endregion #region Helper methods for non-trivial conversions /// <summary> /// Converts an unmanaged define into a known managed value. /// </summary> /// <param name="origin">Defined in stdio.h.</param> /// <returns>The appropriate System.IO.SeekOrigin value.</returns> internal static SeekOrigin ConvertOriginToSeekOrigin(int origin) { switch (origin) { case 0x0: // SEEK_SET return SeekOrigin.Begin; case 0x1: // SEEK_CUR return SeekOrigin.Current; case 0x2: // SEEK_END return SeekOrigin.End; default: return SeekOrigin.Current; } } /// <summary> /// Converts an unmanaged define into a known managed type. /// </summary> /// <param name="oflag">Operation mode defined in fcntl.h.</param> /// <returns>The appropriate System.IO.FileMode type.</returns> internal static FileMode ConvertOpflagToFileMode(int oflag) { // Note: This is not done in a switch because the order of tests matters. if ((int)(OpFlags.Create | OpFlags.Excl) == (oflag & (int)(OpFlags.Create | OpFlags.Excl))) { return FileMode.CreateNew; } else if ((int)(OpFlags.Create | OpFlags.Truncate) == (oflag & (int)(OpFlags.Create | OpFlags.Truncate))) { return FileMode.OpenOrCreate; } else if (0 != (oflag & (int)OpFlags.Append)) { return FileMode.Append; } else if (0 != (oflag & (int)OpFlags.Create)) { return FileMode.Create; } else if (0 != (oflag & (int)OpFlags.RdWr)) { return FileMode.Open; } else if (0 != (oflag & (int)OpFlags.Truncate)) { return FileMode.Truncate; } else { return FileMode.OpenOrCreate; // This seemed the safest way to handled unrecognized types } } /// <summary> /// Converts an unmanaged define into a known managed type. /// </summary> /// <param name="pmode">Permission mode defined in stat.h.</param> /// <returns>The appropriate System.IO.FileAccess type.</returns> internal static FileAccess ConvertPermissionModeToFileAccess(int pmode) { // Note: This is not done in a switch because the order of tests matters. if ((int)(PermissionMode.Read | PermissionMode.Write) == (pmode & (int)(PermissionMode.Read | PermissionMode.Write))) { return FileAccess.ReadWrite; } else if (0 != (pmode & (int)PermissionMode.Read)) { return FileAccess.Read; } else if (0 != (pmode & (int)PermissionMode.Write)) { return FileAccess.Write; } else { return FileAccess.Read; } } /// <summary> /// Converts an unmanaged define into a known managed type. /// </summary> /// <param name="pmode">Permission mode defined in stat.h.</param> /// <returns>The appropriate System.IO.FileShare type.</returns> internal static FileShare ConvertPermissionModeToFileShare(int pmode) { // Note: This is not done in a switch because the order of tests matters. if ((int)(PermissionMode.Read | PermissionMode.Write) == (pmode & (int)(PermissionMode.Read | PermissionMode.Write))) { return FileShare.ReadWrite; } else if (0 != (pmode & (int)PermissionMode.Read)) { return FileShare.Read; } else if (0 != (pmode & (int)PermissionMode.Write)) { return FileShare.Write; } else { return FileShare.Read; } } #endregion #region IO classes, structures, and enums [FlagsAttribute] internal enum PermissionMode : int { None = 0x0000, Write = 0x0080, Read = 0x0100 } [FlagsAttribute] internal enum OpFlags : int { RdOnly = 0x0000, WrOnly = 0x0001, RdWr = 0x0002, Append = 0x0008, Create = 0x0100, Truncate = 0x0200, Excl = 0x0400 } internal enum FdiCreateCpuType : int { CpuUnknown = -1, Cpu80286 = 0, Cpu80386 = 1 } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] internal class FdiNotification { internal int cb; // LONG internal string psz1; // char FAR * internal string psz2; // char FAR * internal string psz3; // char FAR * internal IntPtr pv; // void FAR * // In this case, it is the destination path internal IntPtr hf; // INT_PTR internal short date; // USHORT internal short time; // USHORT internal short attribs; // USHORT internal short setID; // USHORT internal short iCabinet; // USHORT internal short iFolder; // USHORT internal int fdie; // FDIERROR }; internal enum FdiNotificationType : int { FdintCABINET_INFO = 0x0, FdintPARTIAL_FILE = 0x1, FdintCOPY_FILE = 0x2, FdintCLOSE_FILE_INFO = 0x3, FdintNEXT_CABINET = 0x4, FdintENUMERATE = 0x5 } [StructLayout(LayoutKind.Sequential)] internal class FdiERF { internal int erfOper; internal int erfType; internal bool fError; }; internal sealed class FdiContextHandle : SafeHandleZeroOrMinusOneIsInvalid { private FdiContextHandle() : base(true) { } protected override bool ReleaseHandle() { return CabinetNativeApi.FDIDestroy(this.handle); } } #endregion #region PInvoke Definitions /// <summary> /// Creates an FDI context. /// </summary> /// <param name="pfnalloc">_In_ PFNALLOC - Memory allocation delegate.</param> /// <param name="pfnfree">_In_ PFNFREE - Memory free delegate.</param> /// <param name="pfnopen">_In_ PFNOPEN - File open delegate.</param> /// <param name="pfnread">_In_ PFNREAD - File read delegate.</param> /// <param name="pfnwrite">_In_ PFNWRITE - File write delegate.</param> /// <param name="pfnclose">_In_ PFNCLOSE - File close delegate.</param> /// <param name="pfnseek">_In_ PFNSEEK - File seek delegate.</param> /// <param name="cpuType">_In_ int - CPU type.</param> /// <param name="erf">_Inout_ PERF - Error structure containing error information.</param> /// <returns></returns> [DllImport("cabinet.dll", ExactSpelling = true, CallingConvention = CallingConvention.Cdecl, SetLastError = true)] internal static extern FdiContextHandle FDICreate( IntPtr pfnalloc, IntPtr pfnfree, IntPtr pfnopen, IntPtr pfnread, IntPtr pfnwrite, IntPtr pfnclose, IntPtr pfnseek, CabinetNativeApi.FdiCreateCpuType cpuType, FdiERF erf); /// <summary> /// Extracts files from cabinets. /// </summary> /// <param name="hfdi">_In_ HFDI - A valid FDI context handle returned by FDICreate.</param> /// <param name="pszCabinet">_In_ LPSTR - The name of the cabinet file.</param> /// <param name="pszCabPath">_In_ LPSTR - The path to the cabinet file excluding the file name.</param> /// <param name="flags">_In_ int - Not defined.</param> /// <param name="pfnfdin">_In_ PFNFDINOTIFY - Pointer to the notification callback delegate.</param> /// <param name="pfnfdid">_In_ PFNFDIDECRYPT - Not used.</param> /// <param name="pvUser">_In_opt_ void FAR * - Path string passed to the notification function.</param> /// <returns></returns> [DllImport("cabinet.dll", ExactSpelling = true, CallingConvention = CallingConvention.Cdecl, SetLastError = true, BestFitMapping = false)] internal static extern bool FDICopy( FdiContextHandle hfdi, [MarshalAs(UnmanagedType.LPStr)] string pszCabinet, [MarshalAs(UnmanagedType.LPStr)] string pszCabPath, int flags, IntPtr pfnfdin, IntPtr pfnfdid, IntPtr pvUser); /// <summary> /// Deletes an open FDI context. /// </summary> /// <param name="hfdi">_In_ HFDI - The FDI context handle to destroy.</param> /// <returns></returns> [DllImport("cabinet.dll", ExactSpelling = true, CallingConvention = CallingConvention.Cdecl, SetLastError = true)] internal static extern bool FDIDestroy( IntPtr hfdi); #endregion } }
using ICSharpCode.SharpZipLib.Checksum; using System; using System.IO; namespace ICSharpCode.SharpZipLib.BZip2 { /// <summary> /// An input stream that decompresses files in the BZip2 format /// </summary> public class BZip2InputStream : Stream { #region Constants private const int START_BLOCK_STATE = 1; private const int RAND_PART_A_STATE = 2; private const int RAND_PART_B_STATE = 3; private const int RAND_PART_C_STATE = 4; private const int NO_RAND_PART_A_STATE = 5; private const int NO_RAND_PART_B_STATE = 6; private const int NO_RAND_PART_C_STATE = 7; #endregion Constants #region Instance Fields /*-- index of the last char in the block, so the block size == last + 1. --*/ private int last; /*-- index in zptr[] of original string after sorting. --*/ private int origPtr; /*-- always: in the range 0 .. 9. The current block size is 100000 * this number. --*/ private int blockSize100k; private bool blockRandomised; private int bsBuff; private int bsLive; private IChecksum mCrc = new BZip2Crc(); private bool[] inUse = new bool[256]; private int nInUse; private byte[] seqToUnseq = new byte[256]; private byte[] unseqToSeq = new byte[256]; private byte[] selector = new byte[BZip2Constants.MaximumSelectors]; private byte[] selectorMtf = new byte[BZip2Constants.MaximumSelectors]; private int[] tt; private byte[] ll8; /*-- freq table collected to save a pass over the data during decompression. --*/ private int[] unzftab = new int[256]; private int[][] limit = new int[BZip2Constants.GroupCount][]; private int[][] baseArray = new int[BZip2Constants.GroupCount][]; private int[][] perm = new int[BZip2Constants.GroupCount][]; private int[] minLens = new int[BZip2Constants.GroupCount]; private readonly Stream baseStream; private bool streamEnd; private int currentChar = -1; private int currentState = START_BLOCK_STATE; private int storedBlockCRC, storedCombinedCRC; private int computedBlockCRC; private uint computedCombinedCRC; private int count, chPrev, ch2; private int tPos; private int rNToGo; private int rTPos; private int i2, j2; private byte z; #endregion Instance Fields /// <summary> /// Construct instance for reading from stream /// </summary> /// <param name="stream">Data source</param> public BZip2InputStream(Stream stream) { if (stream == null) throw new ArgumentNullException(nameof(stream)); // init arrays for (int i = 0; i < BZip2Constants.GroupCount; ++i) { limit[i] = new int[BZip2Constants.MaximumAlphaSize]; baseArray[i] = new int[BZip2Constants.MaximumAlphaSize]; perm[i] = new int[BZip2Constants.MaximumAlphaSize]; } baseStream = stream; bsLive = 0; bsBuff = 0; Initialize(); InitBlock(); SetupBlock(); } /// <summary> /// Get/set flag indicating ownership of underlying stream. /// When the flag is true <see cref="Stream.Dispose()" /> will close the underlying stream also. /// </summary> public bool IsStreamOwner { get; set; } = true; #region Stream Overrides /// <summary> /// Gets a value indicating if the stream supports reading /// </summary> public override bool CanRead { get { return baseStream.CanRead; } } /// <summary> /// Gets a value indicating whether the current stream supports seeking. /// </summary> public override bool CanSeek { get { return false; } } /// <summary> /// Gets a value indicating whether the current stream supports writing. /// This property always returns false /// </summary> public override bool CanWrite { get { return false; } } /// <summary> /// Gets the length in bytes of the stream. /// </summary> public override long Length { get { return baseStream.Length; } } /// <summary> /// Gets the current position of the stream. /// Setting the position is not supported and will throw a NotSupportException. /// </summary> /// <exception cref="NotSupportedException">Any attempt to set the position.</exception> public override long Position { get { return baseStream.Position; } set { throw new NotSupportedException("BZip2InputStream position cannot be set"); } } /// <summary> /// Flushes the stream. /// </summary> public override void Flush() { baseStream.Flush(); } /// <summary> /// Set the streams position. This operation is not supported and will throw a NotSupportedException /// </summary> /// <param name="offset">A byte offset relative to the <paramref name="origin"/> parameter.</param> /// <param name="origin">A value of type <see cref="SeekOrigin"/> indicating the reference point used to obtain the new position.</param> /// <returns>The new position of the stream.</returns> /// <exception cref="NotSupportedException">Any access</exception> public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException("BZip2InputStream Seek not supported"); } /// <summary> /// Sets the length of this stream to the given value. /// This operation is not supported and will throw a NotSupportedExceptionortedException /// </summary> /// <param name="value">The new length for the stream.</param> /// <exception cref="NotSupportedException">Any access</exception> public override void SetLength(long value) { throw new NotSupportedException("BZip2InputStream SetLength not supported"); } /// <summary> /// Writes a block of bytes to this stream using data from a buffer. /// This operation is not supported and will throw a NotSupportedException /// </summary> /// <param name="buffer">The buffer to source data from.</param> /// <param name="offset">The offset to start obtaining data from.</param> /// <param name="count">The number of bytes of data to write.</param> /// <exception cref="NotSupportedException">Any access</exception> public override void Write(byte[] buffer, int offset, int count) { throw new NotSupportedException("BZip2InputStream Write not supported"); } /// <summary> /// Writes a byte to the current position in the file stream. /// This operation is not supported and will throw a NotSupportedException /// </summary> /// <param name="value">The value to write.</param> /// <exception cref="NotSupportedException">Any access</exception> public override void WriteByte(byte value) { throw new NotSupportedException("BZip2InputStream WriteByte not supported"); } /// <summary> /// Read a sequence of bytes and advances the read position by one byte. /// </summary> /// <param name="buffer">Array of bytes to store values in</param> /// <param name="offset">Offset in array to begin storing data</param> /// <param name="count">The maximum number of bytes to read</param> /// <returns>The total number of bytes read into the buffer. This might be less /// than the number of bytes requested if that number of bytes are not /// currently available or zero if the end of the stream is reached. /// </returns> public override int Read(byte[] buffer, int offset, int count) { if (buffer == null) { throw new ArgumentNullException(nameof(buffer)); } for (int i = 0; i < count; ++i) { int rb = ReadByte(); if (rb == -1) { return i; } buffer[offset + i] = (byte)rb; } return count; } /// <summary> /// Closes the stream, releasing any associated resources. /// </summary> protected override void Dispose(bool disposing) { if (disposing && IsStreamOwner) { baseStream.Dispose(); } } /// <summary> /// Read a byte from stream advancing position /// </summary> /// <returns>byte read or -1 on end of stream</returns> public override int ReadByte() { if (streamEnd) { return -1; // ok } int retChar = currentChar; switch (currentState) { case RAND_PART_B_STATE: SetupRandPartB(); break; case RAND_PART_C_STATE: SetupRandPartC(); break; case NO_RAND_PART_B_STATE: SetupNoRandPartB(); break; case NO_RAND_PART_C_STATE: SetupNoRandPartC(); break; case START_BLOCK_STATE: case NO_RAND_PART_A_STATE: case RAND_PART_A_STATE: break; } return retChar; } #endregion Stream Overrides private void MakeMaps() { nInUse = 0; for (int i = 0; i < 256; ++i) { if (inUse[i]) { seqToUnseq[nInUse] = (byte)i; unseqToSeq[i] = (byte)nInUse; nInUse++; } } } private void Initialize() { char magic1 = BsGetUChar(); char magic2 = BsGetUChar(); char magic3 = BsGetUChar(); char magic4 = BsGetUChar(); if (magic1 != 'B' || magic2 != 'Z' || magic3 != 'h' || magic4 < '1' || magic4 > '9') { streamEnd = true; return; } SetDecompressStructureSizes(magic4 - '0'); computedCombinedCRC = 0; } private void InitBlock() { char magic1 = BsGetUChar(); char magic2 = BsGetUChar(); char magic3 = BsGetUChar(); char magic4 = BsGetUChar(); char magic5 = BsGetUChar(); char magic6 = BsGetUChar(); if (magic1 == 0x17 && magic2 == 0x72 && magic3 == 0x45 && magic4 == 0x38 && magic5 == 0x50 && magic6 == 0x90) { Complete(); return; } if (magic1 != 0x31 || magic2 != 0x41 || magic3 != 0x59 || magic4 != 0x26 || magic5 != 0x53 || magic6 != 0x59) { BadBlockHeader(); streamEnd = true; return; } storedBlockCRC = BsGetInt32(); blockRandomised = (BsR(1) == 1); GetAndMoveToFrontDecode(); mCrc.Reset(); currentState = START_BLOCK_STATE; } private void EndBlock() { computedBlockCRC = (int)mCrc.Value; // -- A bad CRC is considered a fatal error. -- if (storedBlockCRC != computedBlockCRC) { CrcError(); } // 1528150659 computedCombinedCRC = ((computedCombinedCRC << 1) & 0xFFFFFFFF) | (computedCombinedCRC >> 31); computedCombinedCRC = computedCombinedCRC ^ (uint)computedBlockCRC; } private void Complete() { storedCombinedCRC = BsGetInt32(); if (storedCombinedCRC != (int)computedCombinedCRC) { CrcError(); } streamEnd = true; } private void FillBuffer() { int thech = 0; try { thech = baseStream.ReadByte(); } catch (Exception) { CompressedStreamEOF(); } if (thech == -1) { CompressedStreamEOF(); } bsBuff = (bsBuff << 8) | (thech & 0xFF); bsLive += 8; } private int BsR(int n) { while (bsLive < n) { FillBuffer(); } int v = (bsBuff >> (bsLive - n)) & ((1 << n) - 1); bsLive -= n; return v; } private char BsGetUChar() { return (char)BsR(8); } private int BsGetIntVS(int numBits) { return BsR(numBits); } private int BsGetInt32() { int result = BsR(8); result = (result << 8) | BsR(8); result = (result << 8) | BsR(8); result = (result << 8) | BsR(8); return result; } private void RecvDecodingTables() { char[][] len = new char[BZip2Constants.GroupCount][]; for (int i = 0; i < BZip2Constants.GroupCount; ++i) { len[i] = new char[BZip2Constants.MaximumAlphaSize]; } bool[] inUse16 = new bool[16]; //--- Receive the mapping table --- for (int i = 0; i < 16; i++) { inUse16[i] = (BsR(1) == 1); } for (int i = 0; i < 16; i++) { if (inUse16[i]) { for (int j = 0; j < 16; j++) { inUse[i * 16 + j] = (BsR(1) == 1); } } else { for (int j = 0; j < 16; j++) { inUse[i * 16 + j] = false; } } } MakeMaps(); int alphaSize = nInUse + 2; //--- Now the selectors --- int nGroups = BsR(3); int nSelectors = BsR(15); for (int i = 0; i < nSelectors; i++) { int j = 0; while (BsR(1) == 1) { j++; } selectorMtf[i] = (byte)j; } //--- Undo the MTF values for the selectors. --- byte[] pos = new byte[BZip2Constants.GroupCount]; for (int v = 0; v < nGroups; v++) { pos[v] = (byte)v; } for (int i = 0; i < nSelectors; i++) { int v = selectorMtf[i]; byte tmp = pos[v]; while (v > 0) { pos[v] = pos[v - 1]; v--; } pos[0] = tmp; selector[i] = tmp; } //--- Now the coding tables --- for (int t = 0; t < nGroups; t++) { int curr = BsR(5); for (int i = 0; i < alphaSize; i++) { while (BsR(1) == 1) { if (BsR(1) == 0) { curr++; } else { curr--; } } len[t][i] = (char)curr; } } //--- Create the Huffman decoding tables --- for (int t = 0; t < nGroups; t++) { int minLen = 32; int maxLen = 0; for (int i = 0; i < alphaSize; i++) { maxLen = Math.Max(maxLen, len[t][i]); minLen = Math.Min(minLen, len[t][i]); } HbCreateDecodeTables(limit[t], baseArray[t], perm[t], len[t], minLen, maxLen, alphaSize); minLens[t] = minLen; } } private void GetAndMoveToFrontDecode() { byte[] yy = new byte[256]; int nextSym; int limitLast = BZip2Constants.BaseBlockSize * blockSize100k; origPtr = BsGetIntVS(24); RecvDecodingTables(); int EOB = nInUse + 1; int groupNo = -1; int groupPos = 0; /*-- Setting up the unzftab entries here is not strictly necessary, but it does save having to do it later in a separate pass, and so saves a block's worth of cache misses. --*/ for (int i = 0; i <= 255; i++) { unzftab[i] = 0; } for (int i = 0; i <= 255; i++) { yy[i] = (byte)i; } last = -1; if (groupPos == 0) { groupNo++; groupPos = BZip2Constants.GroupSize; } groupPos--; int zt = selector[groupNo]; int zn = minLens[zt]; int zvec = BsR(zn); int zj; while (zvec > limit[zt][zn]) { if (zn > 20) { // the longest code throw new BZip2Exception("Bzip data error"); } zn++; while (bsLive < 1) { FillBuffer(); } zj = (bsBuff >> (bsLive - 1)) & 1; bsLive--; zvec = (zvec << 1) | zj; } if (zvec - baseArray[zt][zn] < 0 || zvec - baseArray[zt][zn] >= BZip2Constants.MaximumAlphaSize) { throw new BZip2Exception("Bzip data error"); } nextSym = perm[zt][zvec - baseArray[zt][zn]]; while (true) { if (nextSym == EOB) { break; } if (nextSym == BZip2Constants.RunA || nextSym == BZip2Constants.RunB) { int s = -1; int n = 1; do { if (nextSym == BZip2Constants.RunA) { s += (0 + 1) * n; } else if (nextSym == BZip2Constants.RunB) { s += (1 + 1) * n; } n <<= 1; if (groupPos == 0) { groupNo++; groupPos = BZip2Constants.GroupSize; } groupPos--; zt = selector[groupNo]; zn = minLens[zt]; zvec = BsR(zn); while (zvec > limit[zt][zn]) { zn++; while (bsLive < 1) { FillBuffer(); } zj = (bsBuff >> (bsLive - 1)) & 1; bsLive--; zvec = (zvec << 1) | zj; } nextSym = perm[zt][zvec - baseArray[zt][zn]]; } while (nextSym == BZip2Constants.RunA || nextSym == BZip2Constants.RunB); s++; byte ch = seqToUnseq[yy[0]]; unzftab[ch] += s; while (s > 0) { last++; ll8[last] = ch; s--; } if (last >= limitLast) { BlockOverrun(); } continue; } else { last++; if (last >= limitLast) { BlockOverrun(); } byte tmp = yy[nextSym - 1]; unzftab[seqToUnseq[tmp]]++; ll8[last] = seqToUnseq[tmp]; for (int j = nextSym - 1; j > 0; --j) { yy[j] = yy[j - 1]; } yy[0] = tmp; if (groupPos == 0) { groupNo++; groupPos = BZip2Constants.GroupSize; } groupPos--; zt = selector[groupNo]; zn = minLens[zt]; zvec = BsR(zn); while (zvec > limit[zt][zn]) { zn++; while (bsLive < 1) { FillBuffer(); } zj = (bsBuff >> (bsLive - 1)) & 1; bsLive--; zvec = (zvec << 1) | zj; } nextSym = perm[zt][zvec - baseArray[zt][zn]]; continue; } } } private void SetupBlock() { int[] cftab = new int[257]; cftab[0] = 0; Array.Copy(unzftab, 0, cftab, 1, 256); for (int i = 1; i <= 256; i++) { cftab[i] += cftab[i - 1]; } for (int i = 0; i <= last; i++) { byte ch = ll8[i]; tt[cftab[ch]] = i; cftab[ch]++; } cftab = null; tPos = tt[origPtr]; count = 0; i2 = 0; ch2 = 256; /*-- not a char and not EOF --*/ if (blockRandomised) { rNToGo = 0; rTPos = 0; SetupRandPartA(); } else { SetupNoRandPartA(); } } private void SetupRandPartA() { if (i2 <= last) { chPrev = ch2; ch2 = ll8[tPos]; tPos = tt[tPos]; if (rNToGo == 0) { rNToGo = BZip2Constants.RandomNumbers[rTPos]; rTPos++; if (rTPos == 512) { rTPos = 0; } } rNToGo--; ch2 ^= (int)((rNToGo == 1) ? 1 : 0); i2++; currentChar = ch2; currentState = RAND_PART_B_STATE; mCrc.Update(ch2); } else { EndBlock(); InitBlock(); SetupBlock(); } } private void SetupNoRandPartA() { if (i2 <= last) { chPrev = ch2; ch2 = ll8[tPos]; tPos = tt[tPos]; i2++; currentChar = ch2; currentState = NO_RAND_PART_B_STATE; mCrc.Update(ch2); } else { EndBlock(); InitBlock(); SetupBlock(); } } private void SetupRandPartB() { if (ch2 != chPrev) { currentState = RAND_PART_A_STATE; count = 1; SetupRandPartA(); } else { count++; if (count >= 4) { z = ll8[tPos]; tPos = tt[tPos]; if (rNToGo == 0) { rNToGo = BZip2Constants.RandomNumbers[rTPos]; rTPos++; if (rTPos == 512) { rTPos = 0; } } rNToGo--; z ^= (byte)((rNToGo == 1) ? 1 : 0); j2 = 0; currentState = RAND_PART_C_STATE; SetupRandPartC(); } else { currentState = RAND_PART_A_STATE; SetupRandPartA(); } } } private void SetupRandPartC() { if (j2 < (int)z) { currentChar = ch2; mCrc.Update(ch2); j2++; } else { currentState = RAND_PART_A_STATE; i2++; count = 0; SetupRandPartA(); } } private void SetupNoRandPartB() { if (ch2 != chPrev) { currentState = NO_RAND_PART_A_STATE; count = 1; SetupNoRandPartA(); } else { count++; if (count >= 4) { z = ll8[tPos]; tPos = tt[tPos]; currentState = NO_RAND_PART_C_STATE; j2 = 0; SetupNoRandPartC(); } else { currentState = NO_RAND_PART_A_STATE; SetupNoRandPartA(); } } } private void SetupNoRandPartC() { if (j2 < (int)z) { currentChar = ch2; mCrc.Update(ch2); j2++; } else { currentState = NO_RAND_PART_A_STATE; i2++; count = 0; SetupNoRandPartA(); } } private void SetDecompressStructureSizes(int newSize100k) { if (!(0 <= newSize100k && newSize100k <= 9 && 0 <= blockSize100k && blockSize100k <= 9)) { throw new BZip2Exception("Invalid block size"); } blockSize100k = newSize100k; if (newSize100k == 0) { return; } int n = BZip2Constants.BaseBlockSize * newSize100k; ll8 = new byte[n]; tt = new int[n]; } private static void CompressedStreamEOF() { throw new EndOfStreamException("BZip2 input stream end of compressed stream"); } private static void BlockOverrun() { throw new BZip2Exception("BZip2 input stream block overrun"); } private static void BadBlockHeader() { throw new BZip2Exception("BZip2 input stream bad block header"); } private static void CrcError() { throw new BZip2Exception("BZip2 input stream crc error"); } private static void HbCreateDecodeTables(int[] limit, int[] baseArray, int[] perm, char[] length, int minLen, int maxLen, int alphaSize) { int pp = 0; for (int i = minLen; i <= maxLen; ++i) { for (int j = 0; j < alphaSize; ++j) { if (length[j] == i) { perm[pp] = j; ++pp; } } } for (int i = 0; i < BZip2Constants.MaximumCodeLength; i++) { baseArray[i] = 0; } for (int i = 0; i < alphaSize; i++) { ++baseArray[length[i] + 1]; } for (int i = 1; i < BZip2Constants.MaximumCodeLength; i++) { baseArray[i] += baseArray[i - 1]; } for (int i = 0; i < BZip2Constants.MaximumCodeLength; i++) { limit[i] = 0; } int vec = 0; for (int i = minLen; i <= maxLen; i++) { vec += (baseArray[i + 1] - baseArray[i]); limit[i] = vec - 1; vec <<= 1; } for (int i = minLen + 1; i <= maxLen; i++) { baseArray[i] = ((limit[i - 1] + 1) << 1) - baseArray[i]; } } } }
using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; namespace Introspect.Analyzer { [DiagnosticAnalyzer(LanguageNames.CSharp)] public class StaticInterfaceAnalyzerAnalyzer : DiagnosticAnalyzer { private static DiagnosticDescriptor CannotImplementStaticInterfaceRule = new DiagnosticDescriptor( "SI0001", "Cannot implement Static Interface", "You cannot implement static interface '{0}' directly. Implement the interface IStatic<{0}> instead.", "Semantics", DiagnosticSeverity.Error, isEnabledByDefault: true, description: "Description goes here" ); private static DiagnosticDescriptor IStaticTypeParameterRule = new DiagnosticDescriptor( "SI0002", "Must use Static Interface as type parameter for IStatic interface", "The type parameter of the IStatic<T> interface must be an interface marked with the StaticAttribute.", "Semantics", DiagnosticSeverity.Error, isEnabledByDefault: true, description: "Description goes here" ); private static DiagnosticDescriptor DoesntImplementStaticMember = new DiagnosticDescriptor( "SI0003", "Doesn't implement member", "'{0}' does not implement static interface member {1}. The implementing member must be public and static.", "Semantics", DiagnosticSeverity.Error, isEnabledByDefault: true, description: "Description goes here" ); private static DiagnosticDescriptor StaticInterfaceCannotInheritFromNonStaticInterface = new DiagnosticDescriptor( "SI0004", "Cannot inherit non-static interface", "Static interface '{0}' cannot inherit from non-static interface '{1}'.", "Semantics", DiagnosticSeverity.Error, isEnabledByDefault: true, description: "Description goes here" ); private static DiagnosticDescriptor StaticInterfaceCannotContainIndexer = new DiagnosticDescriptor( "SI0005", "Static interface cannot contain indexer", "Static interface '{0}' cannot contain an indexer.", "Semantics", DiagnosticSeverity.Error, isEnabledByDefault: true, description: "Description goes here" ); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create( IStaticTypeParameterRule, CannotImplementStaticInterfaceRule, DoesntImplementStaticMember, StaticInterfaceCannotInheritFromNonStaticInterface, StaticInterfaceCannotContainIndexer ); } } public override void Initialize(AnalysisContext context) { context.RegisterSymbolAction(ctx => { bool areInternalsVisible = false; AttributeData[] internalsVisibleToAttrs = ctx.Compilation.Assembly.GetAttributes().Where(x => x.AttributeClass.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat) == "global::System.Runtime.CompilerServices.InternalsVisibleTo").ToArray(); foreach(AttributeData data in internalsVisibleToAttrs) { if(data.ConstructorArguments.Length > 0 && data.ConstructorArguments[0].Kind == TypedConstantKind.Primitive && data.ConstructorArguments[0].Value is string && ((string)data.ConstructorArguments[0].Value) == "StaticInterfaces" ) { areInternalsVisible = true; break; } } foreach (Diagnostic diagnostic in analyzeSymbol(ctx.Symbol, areInternalsVisible)) ctx.ReportDiagnostic(diagnostic); }, SymbolKind.NamedType); } private static IEnumerable<Diagnostic> analyzeSymbol(ISymbol symbol, bool areInternalsVisible) { List<Diagnostic> diagnostics = new List<Diagnostic>(); if (symbol is ITypeSymbol) { foreach (ISymbol member in ((ITypeSymbol)symbol).GetMembers()) diagnostics.AddRange(analyzeSymbol(member, areInternalsVisible)); } else if (symbol is INamespaceSymbol) { foreach (ISymbol member in ((INamespaceSymbol)symbol).GetMembers()) diagnostics.AddRange(analyzeSymbol(member, areInternalsVisible)); } var namedTypeSymbol = symbol as INamedTypeSymbol; if (namedTypeSymbol == null) return diagnostics; if(isStaticInterface(namedTypeSymbol)) { foreach(INamedTypeSymbol nonStaticInterface in namedTypeSymbol.Interfaces.Where(x => !isStaticInterface(x))) { var d = Diagnostic.Create(StaticInterfaceCannotInheritFromNonStaticInterface, namedTypeSymbol.Locations[0], namedTypeSymbol.Name, nonStaticInterface.Name); diagnostics.Add(d); } foreach(ISymbol member in namedTypeSymbol.GetMembers()) { if(member.Kind == SymbolKind.Property) { IPropertySymbol property = (IPropertySymbol)member; if(property.IsIndexer) diagnostics.Add(Diagnostic.Create(StaticInterfaceCannotContainIndexer, member.Locations[0], namedTypeSymbol.Name)); } } return diagnostics; } var badImplementedStaticInterfaces = namedTypeSymbol.Interfaces.Where(x => isStaticInterface(x)).ToArray(); foreach (INamedTypeSymbol badImplementedStaticInterface in badImplementedStaticInterfaces) { var diagnostic = Diagnostic.Create(CannotImplementStaticInterfaceRule, namedTypeSymbol.Locations[0], badImplementedStaticInterface.Name); diagnostics.Add(diagnostic); } var implementedStaticInterfaces = namedTypeSymbol.Interfaces.Where(x => isStaticInterfaceImpl(x)).ToArray(); foreach (INamedTypeSymbol implementedStaticInterface in implementedStaticInterfaces) { if (isStaticInterface(implementedStaticInterface.TypeArguments[0] as INamedTypeSymbol)) { diagnostics.AddRange(checkStaticInterfaceImplementation(namedTypeSymbol, implementedStaticInterface.TypeArguments[0])); continue; } var diagnostic2 = Diagnostic.Create(IStaticTypeParameterRule, namedTypeSymbol.Locations[0]); diagnostics.Add(diagnostic2); } return diagnostics; } private static IEnumerable<Diagnostic> checkStaticInterfaceImplementation(INamedTypeSymbol implementingType, ITypeSymbol implementedInterface) { List<Diagnostic> diagnostics = new List<Diagnostic>(); foreach(ISymbol symbol in implementedInterface.GetMembers()) { if (symbol.Kind == SymbolKind.Property && ((IPropertySymbol)symbol).IsIndexer) continue; if (symbol.Kind == SymbolKind.Method && ((IMethodSymbol)symbol).MethodKind != MethodKind.Ordinary) continue; var possibleImplementations = implementingType.GetMembers(symbol.Name).Where( x => x.Kind == symbol.Kind && x.DeclaredAccessibility == Accessibility.Public && x.IsStatic ).ToArray(); if(possibleImplementations.Length == 0) { diagnostics.Add(Diagnostic.Create(DoesntImplementStaticMember, implementingType.Locations[0], implementingType.Name, symbol.ToDisplayString())); continue; } switch (symbol.Kind) { case SymbolKind.Event: if(!possibleImplementations.Cast<IEventSymbol>().Any(x => x.Type.Equals(((IEventSymbol)symbol).Type))) diagnostics.Add(Diagnostic.Create(DoesntImplementStaticMember, implementingType.Locations[0], implementingType.Name, symbol.ToDisplayString())); break; case SymbolKind.Property: if(!possibleImplementations.Cast<IPropertySymbol>().Any(x => x.Type.Equals(((IPropertySymbol)symbol).Type))) diagnostics.Add(Diagnostic.Create(DoesntImplementStaticMember, implementingType.Locations[0], implementingType.Name, symbol.ToDisplayString())); break; case SymbolKind.Method: if(!possibleImplementations.Cast<IMethodSymbol>().Any(x => isValidMethodImplementation(x, (IMethodSymbol)symbol))) diagnostics.Add(Diagnostic.Create(DoesntImplementStaticMember, implementingType.Locations[0], implementingType.Name, symbol.ToDisplayString())); break; } } return diagnostics; } private static bool isValidMethodImplementation(IMethodSymbol implementation, IMethodSymbol implemented) { if (implementation.Name != implemented.Name) return false; if (implementation.Arity != implemented.Arity) return false; for(int i = 0; i < implementation.TypeParameters.Length; ++i) { if (!checkMatchingTypeParameters(implementation.TypeParameters[i], implemented.TypeParameters[i])) return false; } if(!checkMatchingParameterTypes(implementation.ReturnType, implemented.ReturnType)) return false; if (implementation.Parameters.Length != implemented.Parameters.Length) return false; for(int i = 0; i < implementation.Parameters.Length; ++i) { IParameterSymbol implementationParam = implementation.Parameters[i]; IParameterSymbol implementedParam = implemented.Parameters[i]; if (!checkMatchingParameterTypes(implementationParam.Type, implementedParam.Type)) return false; if (implementationParam.RefKind != implementedParam.RefKind) return false; } return true; } private static bool checkMatchingParameterTypes(ITypeSymbol implementationParamType, ITypeSymbol implementedParamType) { if (implementationParamType.TypeKind != implementedParamType.TypeKind) return false; if (implementationParamType.TypeKind == TypeKind.TypeParameter) { var implementationTParam = (ITypeParameterSymbol)implementationParamType; var implementedTParam = (ITypeParameterSymbol)implementedParamType; if (implementationTParam.DeclaringMethod == null && implementedTParam.DeclaringMethod == null) { if (!implementationTParam.Equals(implementedTParam)) return false; } else if (implementationTParam.DeclaringMethod != null && implementedTParam.DeclaringMethod != null) { // do nothing so we fall through and return true; do not want to obscure the cascade of "return false" in this method // with an arbitrary "return true" in the middle here, which is why I'm leaving this empty. } else return false; } else { var namedImplementationParamType = implementationParamType as INamedTypeSymbol; var namedImplementedParamType = implementedParamType as INamedTypeSymbol; if (namedImplementationParamType == null || namedImplementedParamType == null) return false; if (namedImplementationParamType.Arity != namedImplementedParamType.Arity) return false; for(int i = 0; i < namedImplementationParamType.Arity; ++i) { if (!checkMatchingParameterTypes(namedImplementationParamType.TypeArguments[0], namedImplementedParamType.TypeArguments[0])) return false; } if (!implementationParamType.OriginalDefinition.Equals(implementedParamType.OriginalDefinition)) return false; } return true; } private static bool checkMatchingTypeParameters(ITypeParameterSymbol implementationTParam, ITypeParameterSymbol implementedTParam) { if (implementationTParam.Variance != implementedTParam.Variance) return false; if (implementationTParam.HasConstructorConstraint != implementedTParam.HasConstructorConstraint) return false; if (implementationTParam.HasReferenceTypeConstraint != implementedTParam.HasReferenceTypeConstraint) return false; if (implementationTParam.HasValueTypeConstraint != implementedTParam.HasValueTypeConstraint) return false; if (implementationTParam.ConstraintTypes.Length != implementedTParam.ConstraintTypes.Length) return false; for (int i = 0; i < implementedTParam.ConstraintTypes.Length; ++i) { if (!implementationTParam.ConstraintTypes[i].Equals(implementedTParam.ConstraintTypes[i])) return false; } return true; } private static bool isStaticInterface(INamedTypeSymbol symbol) { if (symbol == null) return false; if (symbol.TypeKind != TypeKind.Interface) return false; return symbol.GetAttributes().Any( x => x.AttributeClass.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat) == "global::Introspect.StaticAttribute" ); } private static bool isStaticInterfaceImpl(INamedTypeSymbol symbol) { if (symbol.TypeKind != TypeKind.Interface) return false; if (symbol.TypeArguments.Length != 1) return false; if (symbol.TypeArguments[0].Kind == SymbolKind.ErrorType) return false; return symbol.ConstructedFrom.ToDisplayString( SymbolDisplayFormat.FullyQualifiedFormat ) == "global::Introspect.IStatic<T>"; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Diagnostics.Contracts; namespace System.Globalization { public partial class CompareInfo { internal unsafe CompareInfo(CultureInfo culture) { const uint LCMAP_SORTHANDLE = 0x20000000; _name = culture.m_name; _sortName = culture.SortName; IntPtr handle; int ret = Interop.mincore.LCMapStringEx(_sortName, LCMAP_SORTHANDLE, null, 0, &handle, IntPtr.Size, null, null, IntPtr.Zero); _sortHandle = ret > 0 ? handle : IntPtr.Zero; } private static unsafe int FindStringOrdinal( uint dwFindStringOrdinalFlags, string stringSource, int offset, int cchSource, string value, int cchValue, bool bIgnoreCase) { fixed (char* pSource = stringSource) fixed (char* pValue = value) { int ret = Interop.mincore.FindStringOrdinal( dwFindStringOrdinalFlags, pSource + offset, cchSource, pValue, cchValue, bIgnoreCase ? 1 : 0); return ret < 0 ? ret : ret + offset; } } internal static int IndexOfOrdinal(string source, string value, int startIndex, int count, bool ignoreCase) { Debug.Assert(source != null); Debug.Assert(value != null); return FindStringOrdinal(FIND_FROMSTART, source, startIndex, count, value, value.Length, ignoreCase); } internal static int LastIndexOfOrdinal(string source, string value, int startIndex, int count, bool ignoreCase) { Debug.Assert(source != null); Debug.Assert(value != null); return FindStringOrdinal(FIND_FROMEND, source, startIndex - count + 1, count, value, value.Length, ignoreCase); } private unsafe int GetHashCodeOfStringCore(string source, CompareOptions options) { Debug.Assert(source != null); Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0); if (source.Length == 0) { return 0; } int tmpHash = 0; fixed (char* pSource = source) { if (Interop.mincore.LCMapStringEx(_sortHandle != IntPtr.Zero ? null : _sortName, LCMAP_HASH | (uint)GetNativeCompareFlags(options), pSource, source.Length, &tmpHash, sizeof(int), null, null, _sortHandle) == 0) { Environment.FailFast("LCMapStringEx failed!"); } } return tmpHash; } private static unsafe int CompareStringOrdinalIgnoreCase(char* string1, int count1, char* string2, int count2) { // Use the OS to compare and then convert the result to expected value by subtracting 2 return Interop.mincore.CompareStringOrdinal(string1, count1, string2, count2, true) - 2; } private unsafe int CompareString(string string1, int offset1, int length1, string string2, int offset2, int length2, CompareOptions options) { Debug.Assert(string1 != null); Debug.Assert(string2 != null); Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0); string localeName = _sortHandle != IntPtr.Zero ? null : _sortName; fixed (char* pLocaleName = localeName) fixed (char* pString1 = string1) fixed (char* pString2 = string2) { int result = Interop.mincore.CompareStringEx( pLocaleName, (uint)GetNativeCompareFlags(options), pString1 + offset1, length1, pString2 + offset2, length2, null, null, _sortHandle); if (result == 0) { Environment.FailFast("CompareStringEx failed"); } // Map CompareStringEx return value to -1, 0, 1. return result - 2; } } private unsafe int FindString( uint dwFindNLSStringFlags, string lpStringSource, int startSource, int cchSource, string lpStringValue, int startValue, int cchValue, int* matchLengthPtr) { string localeName = _sortHandle != IntPtr.Zero ? null : _sortName; fixed (char* pLocaleName = localeName) fixed (char* pSource = lpStringSource) fixed (char* pValue = lpStringValue) { char* pS = pSource + startSource; char* pV = pValue + startValue; return Interop.mincore.FindNLSStringEx( pLocaleName, dwFindNLSStringFlags, pS, cchSource, pV, cchValue, null, null, null, _sortHandle, matchLengthPtr); } } internal unsafe int IndexOfCore(string source, string target, int startIndex, int count, CompareOptions options, int* matchLengthPtr) { Debug.Assert(!string.IsNullOrEmpty(source)); Debug.Assert(target != null); Debug.Assert((options & CompareOptions.OrdinalIgnoreCase) == 0); int index; // TODO: Consider moving this up to the relevent APIs we need to ensure this behavior for // and add a precondition that target is not empty. if (target.Length == 0) { if(matchLengthPtr != null) *matchLengthPtr = 0; return startIndex; // keep Whidbey compatibility } if ((options & CompareOptions.Ordinal) != 0) { index = FastIndexOfString(source, target, startIndex, count, target.Length, findLastIndex: false); if(index != -1 && matchLengthPtr != null) *matchLengthPtr = target.Length; return index; } else { int retValue = FindString(FIND_FROMSTART | (uint)GetNativeCompareFlags(options), source, startIndex, count, target, 0, target.Length, matchLengthPtr); if (retValue >= 0) { return retValue + startIndex; } } return -1; } private unsafe int LastIndexOfCore(string source, string target, int startIndex, int count, CompareOptions options) { Debug.Assert(!string.IsNullOrEmpty(source)); Debug.Assert(target != null); Debug.Assert((options & CompareOptions.OrdinalIgnoreCase) == 0); // TODO: Consider moving this up to the relevent APIs we need to ensure this behavior for // and add a precondition that target is not empty. if (target.Length == 0) return startIndex; // keep Whidbey compatibility if ((options & CompareOptions.Ordinal) != 0) { return FastIndexOfString(source, target, startIndex, count, target.Length, findLastIndex: true); } else { int retValue = FindString(FIND_FROMEND | (uint)GetNativeCompareFlags(options), source, startIndex - count + 1, count, target, 0, target.Length, null); if (retValue >= 0) { return retValue + startIndex - (count - 1); } } return -1; } private unsafe bool StartsWith(string source, string prefix, CompareOptions options) { Debug.Assert(!string.IsNullOrEmpty(source)); Debug.Assert(!string.IsNullOrEmpty(prefix)); Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0); return FindString(FIND_STARTSWITH | (uint)GetNativeCompareFlags(options), source, 0, source.Length, prefix, 0, prefix.Length, null) >= 0; } private unsafe bool EndsWith(string source, string suffix, CompareOptions options) { Debug.Assert(!string.IsNullOrEmpty(source)); Debug.Assert(!string.IsNullOrEmpty(suffix)); Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0); return FindString(FIND_ENDSWITH | (uint)GetNativeCompareFlags(options), source, 0, source.Length, suffix, 0, suffix.Length, null) >= 0; } // PAL ends here [NonSerialized] private readonly IntPtr _sortHandle; private const uint LCMAP_HASH = 0x00040000; private const int FIND_STARTSWITH = 0x00100000; private const int FIND_ENDSWITH = 0x00200000; private const int FIND_FROMSTART = 0x00400000; private const int FIND_FROMEND = 0x00800000; // TODO: Instead of this method could we just have upstack code call IndexOfOrdinal with ignoreCase = false? private static unsafe int FastIndexOfString(string source, string target, int startIndex, int sourceCount, int targetCount, bool findLastIndex) { int retValue = -1; int sourceStartIndex = findLastIndex ? startIndex - sourceCount + 1 : startIndex; fixed (char* pSource = source, spTarget = target) { char* spSubSource = pSource + sourceStartIndex; if (findLastIndex) { int startPattern = (sourceCount - 1) - targetCount + 1; if (startPattern < 0) return -1; char patternChar0 = spTarget[0]; for (int ctrSrc = startPattern; ctrSrc >= 0; ctrSrc--) { if (spSubSource[ctrSrc] != patternChar0) continue; int ctrPat; for (ctrPat = 1; ctrPat < targetCount; ctrPat++) { if (spSubSource[ctrSrc + ctrPat] != spTarget[ctrPat]) break; } if (ctrPat == targetCount) { retValue = ctrSrc; break; } } if (retValue >= 0) { retValue += startIndex - sourceCount + 1; } } else { int endPattern = (sourceCount - 1) - targetCount + 1; if (endPattern < 0) return -1; char patternChar0 = spTarget[0]; for (int ctrSrc = 0; ctrSrc <= endPattern; ctrSrc++) { if (spSubSource[ctrSrc] != patternChar0) continue; int ctrPat; for (ctrPat = 1; ctrPat < targetCount; ctrPat++) { if (spSubSource[ctrSrc + ctrPat] != spTarget[ctrPat]) break; } if (ctrPat == targetCount) { retValue = ctrSrc; break; } } if (retValue >= 0) { retValue += startIndex; } } } return retValue; } private unsafe SortKey CreateSortKey(String source, CompareOptions options) { if (source == null) { throw new ArgumentNullException(nameof(source)); } Contract.EndContractBlock(); if ((options & ValidSortkeyCtorMaskOffFlags) != 0) { throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options)); } throw new NotImplementedException(); } private static unsafe bool IsSortable(char* text, int length) { // CompareInfo c = CultureInfo.InvariantCulture.CompareInfo; // return (InternalIsSortable(c.m_dataHandle, c.m_handleOrigin, c.m_sortName, text, text.Length)); throw new NotImplementedException(); } private const int COMPARE_OPTIONS_ORDINAL = 0x40000000; // Ordinal private const int NORM_IGNORECASE = 0x00000001; // Ignores case. (use LINGUISTIC_IGNORECASE instead) private const int NORM_IGNOREKANATYPE = 0x00010000; // Does not differentiate between Hiragana and Katakana characters. Corresponding Hiragana and Katakana will compare as equal. private const int NORM_IGNORENONSPACE = 0x00000002; // Ignores nonspacing. This flag also removes Japanese accent characters. (use LINGUISTIC_IGNOREDIACRITIC instead) private const int NORM_IGNORESYMBOLS = 0x00000004; // Ignores symbols. private const int NORM_IGNOREWIDTH = 0x00020000; // Does not differentiate between a single-byte character and the same character as a double-byte character. private const int NORM_LINGUISTIC_CASING = 0x08000000; // use linguistic rules for casing private const int SORT_STRINGSORT = 0x00001000; // Treats punctuation the same as symbols. private static int GetNativeCompareFlags(CompareOptions options) { // Use "linguistic casing" by default (load the culture's casing exception tables) int nativeCompareFlags = NORM_LINGUISTIC_CASING; if ((options & CompareOptions.IgnoreCase) != 0) { nativeCompareFlags |= NORM_IGNORECASE; } if ((options & CompareOptions.IgnoreKanaType) != 0) { nativeCompareFlags |= NORM_IGNOREKANATYPE; } if ((options & CompareOptions.IgnoreNonSpace) != 0) { nativeCompareFlags |= NORM_IGNORENONSPACE; } if ((options & CompareOptions.IgnoreSymbols) != 0) { nativeCompareFlags |= NORM_IGNORESYMBOLS; } if ((options & CompareOptions.IgnoreWidth) != 0) { nativeCompareFlags |= NORM_IGNOREWIDTH; } if ((options & CompareOptions.StringSort) != 0) { nativeCompareFlags |= SORT_STRINGSORT; } // TODO: Can we try for GetNativeCompareFlags to never // take Ordinal or OrdinalIgnoreCase. This value is not part of Win32, we just handle it special // in some places. // Suffix & Prefix shouldn't use this, make sure to turn off the NORM_LINGUISTIC_CASING flag if (options == CompareOptions.Ordinal) { nativeCompareFlags = COMPARE_OPTIONS_ORDINAL; } Debug.Assert(((options & ~(CompareOptions.IgnoreCase | CompareOptions.IgnoreKanaType | CompareOptions.IgnoreNonSpace | CompareOptions.IgnoreSymbols | CompareOptions.IgnoreWidth | CompareOptions.StringSort)) == 0) || (options == CompareOptions.Ordinal), "[CompareInfo.GetNativeCompareFlags]Expected all flags to be handled"); return nativeCompareFlags; } private SortVersion GetSortVersion() { throw new NotImplementedException(); } } }
public class StateManager : FContainer, FMultiTouchableInterface { protected StateManager() { //Initialize variable m_Factory = null; m_Running = true; m_Touches = new FTouch[] {}; m_Initialized = false; m_RemovalDepth = 0; //Listen ListenForUpdate(onUpdate); ListenForResize(onResize); EnableMultiTouch(); } public static StateManager instance { get { //Create if null if (s_Instance == null) s_Instance = new StateManager(); return s_Instance; } } public void setup(StateFactory factory) { //Set factory m_Factory = factory; } protected void initialize() { //Skip if initialized if (m_Initialized) return; m_Initialized = true; //Go to first state if (m_Factory != null) goTo(m_Factory.getFirstState(), null, false); } public void quit() { //Kill all states int ChildNumber = GetChildCount(); for (int i = 0; i < ChildNumber; i++) removeState(); //No longer running m_Running = false; } public void goTo(int id, object[] parameters, bool swap) { //Prepare variables int i = 0; bool Exist = false; //Find state while (!Exist && i < GetChildCount()) { //Is it exist? if (GetChildAt(i) is ExaState) if (((ExaState)GetChildAt(i)).getID() == id) Exist = true; //Next i++; } //If exist, return, otherwise, add a new one if (Exist) returnTo(id, parameters); else { //Create new state ExaState NewState = null; if (m_Factory != null) NewState = m_Factory.createState(id, parameters); if (NewState == null) return; //Add state addState(NewState); //If swapped and there's many states if (swap && GetChildCount() >= 2) { //Remove top m_RemovalDepth++; //Reorder AddChildAtIndex(NewState, GetChildCount() - 2); } } } protected void addState(ExaState state) { //Skip if no state if (state == null) return; //If there's a previous state if (GetChildCount() > 0) { //Get previous state ExaState Previous = GetChildAt(GetChildCount() - 1) as ExaState; if (Previous != null) Previous.onExit(); } //Add AddChild(state); //Initialize state.initialize(); state.onEnter(); } protected void removeState() { //Validate if (GetChildCount() <= 0) return; //Get top state ExaState Top = GetChildAt(GetChildCount() - 1) as ExaState; if (Top != null) { //Remove Top.onExit(); Top.onRemove(); RemoveChild(Top); //If there's a child if (GetChildCount() > 0) { ExaState NewTop = GetChildAt(GetChildCount() - 1) as ExaState; if (NewTop != null) NewTop.onEnter(); } } } protected void returnTo(int id, object[] parameters) { //Initialize m_RemovalDepth = 0; bool Found = false; int i = GetChildCount() - 1; //While not found while (i >= 0 & !Found) { //Get current state ExaState Current = GetChildAt(i) as ExaState; if (Current != null && Current.getID() == id) { //Found Found = true; Current.onEnter(); } else m_RemovalDepth++; //Next i--; } } protected void onResize(bool orientation) { //Resize all child for (int i = 0; i < GetChildCount(); i++) { ExaState Child = GetChildAt(i) as ExaState; if (Child != null) Child.onResize(orientation); } } public void HandleMultiTouch(FTouch[] touches) { //Save touches m_Touches = touches; } protected void onUpdate() { //Initialize if not if (!m_Initialized) initialize(); //Trim states for (int i = 0; i < m_RemovalDepth; i++) removeState(); m_RemovalDepth = 0; //Top state exist? bool TopExist = false; bool ActiveFound = false; if (GetChildCount() > 0) TopExist = GetChildAt(GetChildCount() - 1) != null; //While not empty while (GetChildCount() > 0 && TopExist && !ActiveFound) { //If top state is active, found ExaState Top = GetChildAt(GetChildCount() - 1) as ExaState; if (Top != null && Top.isActive()) ActiveFound = true; else removeState(); //Check TopExist = GetChildCount() > 0 && GetChildAt(GetChildCount() - 1) != null; } //Quit if empty or no last state if (GetChildCount() <= 0 || !TopExist) m_Running = false; else { //Update last state ExaState Top = GetChildAt(GetChildCount() - 1) as ExaState; if (Top != null) { //Update and clear touches Top.onUpdate(m_Touches); m_Touches = new FTouch[] {}; } } } //The only instance private static StateManager s_Instance; //Data protected FTouch[] m_Touches; protected StateFactory m_Factory; protected bool m_Running; protected bool m_Initialized; protected int m_RemovalDepth; }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Runtime.InteropServices; using System.Text; using System.Security.Principal; using Microsoft.Win32; namespace System.Diagnostics.Eventing.Reader { /// <summary> /// This internal class contains wrapper methods over the Native /// Methods of the Eventlog API. Unlike the raw Native Methods, /// these methods throw EventLogExceptions, check platform /// availability and perform additional helper functionality /// specific to function. Also, all methods of this class expose /// the Link Demand for Unmanaged Permission to callers. /// </summary> internal class NativeWrapper { public class SystemProperties { // Indicates if the SystemProperties values were already computed (for this event Instance, surely). public bool filled = false; public ushort? Id = null; public byte? Version = null; public ushort? Qualifiers = null; public byte? Level = null; public ushort? Task = null; public byte? Opcode = null; public ulong? Keywords = null; public ulong? RecordId = null; public string ProviderName = null; public Guid? ProviderId = null; public string ChannelName = null; public uint? ProcessId = null; public uint? ThreadId = null; public string ComputerName = null; public System.Security.Principal.SecurityIdentifier UserId = null; public DateTime? TimeCreated = null; public Guid? ActivityId = null; public Guid? RelatedActivityId = null; public SystemProperties() { } } public static EventLogHandle EvtQuery( EventLogHandle session, string path, string query, int flags) { EventLogHandle handle = UnsafeNativeMethods.EvtQuery(session, path, query, flags); int win32Error = Marshal.GetLastWin32Error(); if (handle.IsInvalid) EventLogException.Throw(win32Error); return handle; } public static void EvtSeek( EventLogHandle resultSet, long position, EventLogHandle bookmark, int timeout, UnsafeNativeMethods.EvtSeekFlags flags) { bool status = UnsafeNativeMethods.EvtSeek(resultSet, position, bookmark, timeout, flags); int win32Error = Marshal.GetLastWin32Error(); if (!status) EventLogException.Throw(win32Error); } public static bool EvtNext( EventLogHandle queryHandle, int eventSize, IntPtr[] events, int timeout, int flags, ref int returned) { bool status = UnsafeNativeMethods.EvtNext(queryHandle, eventSize, events, timeout, flags, ref returned); int win32Error = Marshal.GetLastWin32Error(); if (!status && win32Error != UnsafeNativeMethods.ERROR_NO_MORE_ITEMS) EventLogException.Throw(win32Error); return win32Error == 0; } public static void EvtCancel(EventLogHandle handle) { if (!UnsafeNativeMethods.EvtCancel(handle)) { int win32Error = Marshal.GetLastWin32Error(); EventLogException.Throw(win32Error); } } public static void EvtClose(IntPtr handle) { // // purposely don't check and throw - this is // always called in cleanup / finalize / etc.. // UnsafeNativeMethods.EvtClose(handle); } public static EventLogHandle EvtOpenProviderMetadata( EventLogHandle session, string ProviderId, string logFilePath, int locale, int flags) { // ignore locale and pass 0 instead: that way, the thread locale will be retrieved in the API layer // and the "strict rendering" flag will NOT be set. Otherwise, the fall back logic is broken and the descriptions // are not returned if the exact locale is not present on the server. EventLogHandle handle = UnsafeNativeMethods.EvtOpenPublisherMetadata(session, ProviderId, logFilePath, 0, flags); int win32Error = Marshal.GetLastWin32Error(); if (handle.IsInvalid) EventLogException.Throw(win32Error); return handle; } public static int EvtGetObjectArraySize(EventLogHandle objectArray) { int arraySize; bool status = UnsafeNativeMethods.EvtGetObjectArraySize(objectArray, out arraySize); int win32Error = Marshal.GetLastWin32Error(); if (!status) EventLogException.Throw(win32Error); return arraySize; } public static EventLogHandle EvtOpenEventMetadataEnum(EventLogHandle ProviderMetadata, int flags) { EventLogHandle emEnumHandle = UnsafeNativeMethods.EvtOpenEventMetadataEnum(ProviderMetadata, flags); int win32Error = Marshal.GetLastWin32Error(); if (emEnumHandle.IsInvalid) EventLogException.Throw(win32Error); return emEnumHandle; } // returns null if EOF public static EventLogHandle EvtNextEventMetadata(EventLogHandle eventMetadataEnum, int flags) { EventLogHandle emHandle = UnsafeNativeMethods.EvtNextEventMetadata(eventMetadataEnum, flags); int win32Error = Marshal.GetLastWin32Error(); if (emHandle.IsInvalid) { if (win32Error != UnsafeNativeMethods.ERROR_NO_MORE_ITEMS) EventLogException.Throw(win32Error); return null; } return emHandle; } public static EventLogHandle EvtOpenChannelEnum(EventLogHandle session, int flags) { EventLogHandle channelEnum = UnsafeNativeMethods.EvtOpenChannelEnum(session, flags); int win32Error = Marshal.GetLastWin32Error(); if (channelEnum.IsInvalid) EventLogException.Throw(win32Error); return channelEnum; } public static EventLogHandle EvtOpenProviderEnum(EventLogHandle session, int flags) { EventLogHandle pubEnum = UnsafeNativeMethods.EvtOpenPublisherEnum(session, flags); int win32Error = Marshal.GetLastWin32Error(); if (pubEnum.IsInvalid) EventLogException.Throw(win32Error); return pubEnum; } public static EventLogHandle EvtOpenChannelConfig(EventLogHandle session, String channelPath, int flags) { EventLogHandle handle = UnsafeNativeMethods.EvtOpenChannelConfig(session, channelPath, flags); int win32Error = Marshal.GetLastWin32Error(); if (handle.IsInvalid) EventLogException.Throw(win32Error); return handle; } public static void EvtSaveChannelConfig(EventLogHandle channelConfig, int flags) { bool status = UnsafeNativeMethods.EvtSaveChannelConfig(channelConfig, flags); int win32Error = Marshal.GetLastWin32Error(); if (!status) EventLogException.Throw(win32Error); } public static EventLogHandle EvtOpenLog(EventLogHandle session, string path, PathType flags) { EventLogHandle logHandle = UnsafeNativeMethods.EvtOpenLog(session, path, flags); int win32Error = Marshal.GetLastWin32Error(); if (logHandle.IsInvalid) EventLogException.Throw(win32Error); return logHandle; } public static void EvtExportLog( EventLogHandle session, string channelPath, string query, string targetFilePath, int flags) { bool status; status = UnsafeNativeMethods.EvtExportLog(session, channelPath, query, targetFilePath, flags); int win32Error = Marshal.GetLastWin32Error(); if (!status) EventLogException.Throw(win32Error); } public static void EvtArchiveExportedLog( EventLogHandle session, string logFilePath, int locale, int flags) { bool status; status = UnsafeNativeMethods.EvtArchiveExportedLog(session, logFilePath, locale, flags); int win32Error = Marshal.GetLastWin32Error(); if (!status) EventLogException.Throw(win32Error); } public static void EvtClearLog( EventLogHandle session, string channelPath, string targetFilePath, int flags) { bool status; status = UnsafeNativeMethods.EvtClearLog(session, channelPath, targetFilePath, flags); int win32Error = Marshal.GetLastWin32Error(); if (!status) EventLogException.Throw(win32Error); } public static EventLogHandle EvtCreateRenderContext( Int32 valuePathsCount, String[] valuePaths, UnsafeNativeMethods.EvtRenderContextFlags flags) { EventLogHandle renderContextHandleValues = UnsafeNativeMethods.EvtCreateRenderContext(valuePathsCount, valuePaths, flags); int win32Error = Marshal.GetLastWin32Error(); if (renderContextHandleValues.IsInvalid) EventLogException.Throw(win32Error); return renderContextHandleValues; } public static void EvtRender( EventLogHandle context, EventLogHandle eventHandle, UnsafeNativeMethods.EvtRenderFlags flags, StringBuilder buffer) { int buffUsed; int propCount; bool status = UnsafeNativeMethods.EvtRender(context, eventHandle, flags, buffer.Capacity, buffer, out buffUsed, out propCount); int win32Error = Marshal.GetLastWin32Error(); if (!status) { if (win32Error == UnsafeNativeMethods.ERROR_INSUFFICIENT_BUFFER) { // Reallocate the new RenderBuffer with the right size. buffer.Capacity = buffUsed; status = UnsafeNativeMethods.EvtRender(context, eventHandle, flags, buffer.Capacity, buffer, out buffUsed, out propCount); win32Error = Marshal.GetLastWin32Error(); } if (!status) { EventLogException.Throw(win32Error); } } } public static EventLogHandle EvtOpenSession(UnsafeNativeMethods.EvtLoginClass loginClass, ref UnsafeNativeMethods.EvtRpcLogin login, int timeout, int flags) { EventLogHandle handle = UnsafeNativeMethods.EvtOpenSession(loginClass, ref login, timeout, flags); int win32Error = Marshal.GetLastWin32Error(); if (handle.IsInvalid) EventLogException.Throw(win32Error); return handle; } public static EventLogHandle EvtCreateBookmark(string bookmarkXml) { EventLogHandle handle = UnsafeNativeMethods.EvtCreateBookmark(bookmarkXml); int win32Error = Marshal.GetLastWin32Error(); if (handle.IsInvalid) EventLogException.Throw(win32Error); return handle; } public static void EvtUpdateBookmark(EventLogHandle bookmark, EventLogHandle eventHandle) { bool status = UnsafeNativeMethods.EvtUpdateBookmark(bookmark, eventHandle); int win32Error = Marshal.GetLastWin32Error(); if (!status) EventLogException.Throw(win32Error); } public static object EvtGetEventInfo(EventLogHandle handle, UnsafeNativeMethods.EvtEventPropertyId enumType) { IntPtr buffer = IntPtr.Zero; int bufferNeeded; try { bool status = UnsafeNativeMethods.EvtGetEventInfo(handle, enumType, 0, IntPtr.Zero, out bufferNeeded); int error = Marshal.GetLastWin32Error(); if (!status) { if (error == UnsafeNativeMethods.ERROR_SUCCESS) { } else if (error != UnsafeNativeMethods.ERROR_INSUFFICIENT_BUFFER) EventLogException.Throw(error); } buffer = Marshal.AllocHGlobal((int)bufferNeeded); status = UnsafeNativeMethods.EvtGetEventInfo(handle, enumType, bufferNeeded, buffer, out bufferNeeded); error = Marshal.GetLastWin32Error(); if (!status) EventLogException.Throw(error); UnsafeNativeMethods.EvtVariant varVal = Marshal.PtrToStructure<UnsafeNativeMethods.EvtVariant>(buffer); return ConvertToObject(varVal); } finally { if (buffer != IntPtr.Zero) Marshal.FreeHGlobal(buffer); } } public static object EvtGetQueryInfo(EventLogHandle handle, UnsafeNativeMethods.EvtQueryPropertyId enumType) { IntPtr buffer = IntPtr.Zero; int bufferNeeded = 0; try { bool status = UnsafeNativeMethods.EvtGetQueryInfo(handle, enumType, 0, IntPtr.Zero, ref bufferNeeded); int error = Marshal.GetLastWin32Error(); if (!status) { if (error != UnsafeNativeMethods.ERROR_INSUFFICIENT_BUFFER) EventLogException.Throw(error); } buffer = Marshal.AllocHGlobal((int)bufferNeeded); status = UnsafeNativeMethods.EvtGetQueryInfo(handle, enumType, bufferNeeded, buffer, ref bufferNeeded); error = Marshal.GetLastWin32Error(); if (!status) EventLogException.Throw(error); UnsafeNativeMethods.EvtVariant varVal = Marshal.PtrToStructure<UnsafeNativeMethods.EvtVariant>(buffer); return ConvertToObject(varVal); } finally { if (buffer != IntPtr.Zero) Marshal.FreeHGlobal(buffer); } } public static object EvtGetPublisherMetadataProperty(EventLogHandle pmHandle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId thePropertyId) { IntPtr buffer = IntPtr.Zero; int bufferNeeded; try { bool status = UnsafeNativeMethods.EvtGetPublisherMetadataProperty(pmHandle, thePropertyId, 0, 0, IntPtr.Zero, out bufferNeeded); int error = Marshal.GetLastWin32Error(); if (!status) { if (error != UnsafeNativeMethods.ERROR_INSUFFICIENT_BUFFER) EventLogException.Throw(error); } buffer = Marshal.AllocHGlobal((int)bufferNeeded); status = UnsafeNativeMethods.EvtGetPublisherMetadataProperty(pmHandle, thePropertyId, 0, bufferNeeded, buffer, out bufferNeeded); error = Marshal.GetLastWin32Error(); if (!status) EventLogException.Throw(error); UnsafeNativeMethods.EvtVariant varVal = Marshal.PtrToStructure<UnsafeNativeMethods.EvtVariant>(buffer); return ConvertToObject(varVal); } finally { if (buffer != IntPtr.Zero) Marshal.FreeHGlobal(buffer); } } internal static EventLogHandle EvtGetPublisherMetadataPropertyHandle(EventLogHandle pmHandle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId thePropertyId) { IntPtr buffer = IntPtr.Zero; try { int bufferNeeded; bool status = UnsafeNativeMethods.EvtGetPublisherMetadataProperty(pmHandle, thePropertyId, 0, 0, IntPtr.Zero, out bufferNeeded); int error = Marshal.GetLastWin32Error(); if (!status) { if (error != UnsafeNativeMethods.ERROR_INSUFFICIENT_BUFFER) EventLogException.Throw(error); } buffer = Marshal.AllocHGlobal((int)bufferNeeded); status = UnsafeNativeMethods.EvtGetPublisherMetadataProperty(pmHandle, thePropertyId, 0, bufferNeeded, buffer, out bufferNeeded); error = Marshal.GetLastWin32Error(); if (!status) EventLogException.Throw(error); // // note: there is a case where returned variant does have allocated native resources // associated with (e.g. ConfigArrayHandle). If PtrToStructure throws, then we would // leak that resource - fortunately PtrToStructure only throws InvalidArgument which // is a logic error - not a possible runtime condition here. Other System exceptions // shouldn't be handled anyhow and the application will terminate. // UnsafeNativeMethods.EvtVariant varVal = Marshal.PtrToStructure<UnsafeNativeMethods.EvtVariant>(buffer); return ConvertToSafeHandle(varVal); } finally { if (buffer != IntPtr.Zero) Marshal.FreeHGlobal(buffer); } } // implies UnsafeNativeMethods.EvtFormatMessageFlags.EvtFormatMessageId flag. public static string EvtFormatMessage(EventLogHandle handle, uint msgId) { int bufferNeeded; StringBuilder sb = new StringBuilder(null); bool status = UnsafeNativeMethods.EvtFormatMessage(handle, EventLogHandle.Zero, msgId, 0, null, UnsafeNativeMethods.EvtFormatMessageFlags.EvtFormatMessageId, 0, sb, out bufferNeeded); int error = Marshal.GetLastWin32Error(); // ERROR_EVT_UNRESOLVED_VALUE_INSERT and its cousins are commonly returned for raw message text. if (!status && error != UnsafeNativeMethods.ERROR_EVT_UNRESOLVED_VALUE_INSERT && error != UnsafeNativeMethods.ERROR_EVT_UNRESOLVED_PARAMETER_INSERT && error != UnsafeNativeMethods.ERROR_EVT_MAX_INSERTS_REACHED) { switch (error) { case UnsafeNativeMethods.ERROR_EVT_MESSAGE_NOT_FOUND: case UnsafeNativeMethods.ERROR_EVT_MESSAGE_ID_NOT_FOUND: case UnsafeNativeMethods.ERROR_EVT_MESSAGE_LOCALE_NOT_FOUND: case UnsafeNativeMethods.ERROR_RESOURCE_LANG_NOT_FOUND: case UnsafeNativeMethods.ERROR_MUI_FILE_NOT_FOUND: return null; } if (error != UnsafeNativeMethods.ERROR_INSUFFICIENT_BUFFER) EventLogException.Throw(error); } sb.EnsureCapacity(bufferNeeded); status = UnsafeNativeMethods.EvtFormatMessage(handle, EventLogHandle.Zero, msgId, 0, null, UnsafeNativeMethods.EvtFormatMessageFlags.EvtFormatMessageId, bufferNeeded, sb, out bufferNeeded); error = Marshal.GetLastWin32Error(); if (!status && error != UnsafeNativeMethods.ERROR_EVT_UNRESOLVED_VALUE_INSERT && error != UnsafeNativeMethods.ERROR_EVT_UNRESOLVED_PARAMETER_INSERT && error != UnsafeNativeMethods.ERROR_EVT_MAX_INSERTS_REACHED) { switch (error) { case UnsafeNativeMethods.ERROR_EVT_MESSAGE_NOT_FOUND: case UnsafeNativeMethods.ERROR_EVT_MESSAGE_ID_NOT_FOUND: case UnsafeNativeMethods.ERROR_EVT_MESSAGE_LOCALE_NOT_FOUND: case UnsafeNativeMethods.ERROR_RESOURCE_LANG_NOT_FOUND: case UnsafeNativeMethods.ERROR_MUI_FILE_NOT_FOUND: return null; } if (error == UnsafeNativeMethods.ERROR_EVT_UNRESOLVED_VALUE_INSERT) { return null; } EventLogException.Throw(error); } return sb.ToString(); } public static object EvtGetObjectArrayProperty(EventLogHandle objArrayHandle, int index, int thePropertyId) { IntPtr buffer = IntPtr.Zero; int bufferNeeded; try { bool status = UnsafeNativeMethods.EvtGetObjectArrayProperty(objArrayHandle, thePropertyId, index, 0, 0, IntPtr.Zero, out bufferNeeded); int error = Marshal.GetLastWin32Error(); if (!status) { if (error != UnsafeNativeMethods.ERROR_INSUFFICIENT_BUFFER) EventLogException.Throw(error); } buffer = Marshal.AllocHGlobal((int)bufferNeeded); status = UnsafeNativeMethods.EvtGetObjectArrayProperty(objArrayHandle, thePropertyId, index, 0, bufferNeeded, buffer, out bufferNeeded); error = Marshal.GetLastWin32Error(); if (!status) EventLogException.Throw(error); UnsafeNativeMethods.EvtVariant varVal = Marshal.PtrToStructure<UnsafeNativeMethods.EvtVariant>(buffer); return ConvertToObject(varVal); } finally { if (buffer != IntPtr.Zero) Marshal.FreeHGlobal(buffer); } } public static object EvtGetEventMetadataProperty(EventLogHandle handle, UnsafeNativeMethods.EvtEventMetadataPropertyId enumType) { IntPtr buffer = IntPtr.Zero; int bufferNeeded; try { bool status = UnsafeNativeMethods.EvtGetEventMetadataProperty(handle, enumType, 0, 0, IntPtr.Zero, out bufferNeeded); int win32Error = Marshal.GetLastWin32Error(); if (!status) { if (win32Error != UnsafeNativeMethods.ERROR_INSUFFICIENT_BUFFER) EventLogException.Throw(win32Error); } buffer = Marshal.AllocHGlobal((int)bufferNeeded); status = UnsafeNativeMethods.EvtGetEventMetadataProperty(handle, enumType, 0, bufferNeeded, buffer, out bufferNeeded); win32Error = Marshal.GetLastWin32Error(); if (!status) EventLogException.Throw(win32Error); UnsafeNativeMethods.EvtVariant varVal = Marshal.PtrToStructure<UnsafeNativeMethods.EvtVariant>(buffer); return ConvertToObject(varVal); } finally { if (buffer != IntPtr.Zero) Marshal.FreeHGlobal(buffer); } } public static object EvtGetChannelConfigProperty(EventLogHandle handle, UnsafeNativeMethods.EvtChannelConfigPropertyId enumType) { IntPtr buffer = IntPtr.Zero; int bufferNeeded; try { bool status = UnsafeNativeMethods.EvtGetChannelConfigProperty(handle, enumType, 0, 0, IntPtr.Zero, out bufferNeeded); int win32Error = Marshal.GetLastWin32Error(); if (!status) { if (win32Error != UnsafeNativeMethods.ERROR_INSUFFICIENT_BUFFER) EventLogException.Throw(win32Error); } buffer = Marshal.AllocHGlobal((int)bufferNeeded); status = UnsafeNativeMethods.EvtGetChannelConfigProperty(handle, enumType, 0, bufferNeeded, buffer, out bufferNeeded); win32Error = Marshal.GetLastWin32Error(); if (!status) EventLogException.Throw(win32Error); // // note: there is a case where returned variant does have allocated native resources // associated with (e.g. ConfigArrayHandle). If PtrToStructure throws, then we would // leak that resource - fortunately PtrToStructure only throws InvalidArgument which // is a logic error - not a possible runtime condition here. Other System exceptions // shouldn't be handled anyhow and the application will terminate. // UnsafeNativeMethods.EvtVariant varVal = Marshal.PtrToStructure<UnsafeNativeMethods.EvtVariant>(buffer); return ConvertToObject(varVal); } finally { if (buffer != IntPtr.Zero) Marshal.FreeHGlobal(buffer); } } public static void EvtSetChannelConfigProperty(EventLogHandle handle, UnsafeNativeMethods.EvtChannelConfigPropertyId enumType, object val) { UnsafeNativeMethods.EvtVariant varVal = new UnsafeNativeMethods.EvtVariant(); CoTaskMemSafeHandle taskMem = new CoTaskMemSafeHandle(); using (taskMem) { if (val != null) { switch (enumType) { case UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelConfigEnabled: { varVal.Type = (uint)UnsafeNativeMethods.EvtVariantType.EvtVarTypeBoolean; if ((bool)val == true) varVal.Bool = 1; else varVal.Bool = 0; } break; case UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelConfigAccess: { varVal.Type = (uint)UnsafeNativeMethods.EvtVariantType.EvtVarTypeString; taskMem.SetMemory(Marshal.StringToCoTaskMemUni((string)val)); varVal.StringVal = taskMem.GetMemory(); } break; case UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigLogFilePath: { varVal.Type = (uint)UnsafeNativeMethods.EvtVariantType.EvtVarTypeString; taskMem.SetMemory(Marshal.StringToCoTaskMemUni((string)val)); varVal.StringVal = taskMem.GetMemory(); } break; case UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigMaxSize: { varVal.Type = (uint)UnsafeNativeMethods.EvtVariantType.EvtVarTypeUInt64; varVal.ULong = (ulong)((long)val); } break; case UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelPublishingConfigLevel: { varVal.Type = (uint)UnsafeNativeMethods.EvtVariantType.EvtVarTypeUInt32; varVal.UInteger = (uint)((int)val); } break; case UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelPublishingConfigKeywords: { varVal.Type = (uint)UnsafeNativeMethods.EvtVariantType.EvtVarTypeUInt64; varVal.ULong = (ulong)((long)val); } break; case UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigRetention: { varVal.Type = (uint)UnsafeNativeMethods.EvtVariantType.EvtVarTypeBoolean; if ((bool)val == true) varVal.Bool = 1; else varVal.Bool = 0; } break; case UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigAutoBackup: { varVal.Type = (uint)UnsafeNativeMethods.EvtVariantType.EvtVarTypeBoolean; if ((bool)val == true) varVal.Bool = 1; else varVal.Bool = 0; } break; default: throw new InvalidOperationException(); } } else { varVal.Type = (uint)UnsafeNativeMethods.EvtVariantType.EvtVarTypeNull; } bool status = UnsafeNativeMethods.EvtSetChannelConfigProperty(handle, enumType, 0, ref varVal); int win32Error = Marshal.GetLastWin32Error(); if (!status) EventLogException.Throw(win32Error); } } public static string EvtNextChannelPath(EventLogHandle handle, ref bool finish) { StringBuilder sb = new StringBuilder(null); int channelNameNeeded; bool status = UnsafeNativeMethods.EvtNextChannelPath(handle, 0, sb, out channelNameNeeded); int win32Error = Marshal.GetLastWin32Error(); if (!status) { if (win32Error == UnsafeNativeMethods.ERROR_NO_MORE_ITEMS) { finish = true; return null; } if (win32Error != UnsafeNativeMethods.ERROR_INSUFFICIENT_BUFFER) EventLogException.Throw(win32Error); } sb.EnsureCapacity(channelNameNeeded); status = UnsafeNativeMethods.EvtNextChannelPath(handle, channelNameNeeded, sb, out channelNameNeeded); win32Error = Marshal.GetLastWin32Error(); if (!status) EventLogException.Throw(win32Error); return sb.ToString(); } public static string EvtNextPublisherId(EventLogHandle handle, ref bool finish) { StringBuilder sb = new StringBuilder(null); int ProviderIdNeeded; bool status = UnsafeNativeMethods.EvtNextPublisherId(handle, 0, sb, out ProviderIdNeeded); int win32Error = Marshal.GetLastWin32Error(); if (!status) { if (win32Error == UnsafeNativeMethods.ERROR_NO_MORE_ITEMS) { finish = true; return null; } if (win32Error != UnsafeNativeMethods.ERROR_INSUFFICIENT_BUFFER) EventLogException.Throw(win32Error); } sb.EnsureCapacity(ProviderIdNeeded); status = UnsafeNativeMethods.EvtNextPublisherId(handle, ProviderIdNeeded, sb, out ProviderIdNeeded); win32Error = Marshal.GetLastWin32Error(); if (!status) EventLogException.Throw(win32Error); return sb.ToString(); } public static object EvtGetLogInfo(EventLogHandle handle, UnsafeNativeMethods.EvtLogPropertyId enumType) { IntPtr buffer = IntPtr.Zero; int bufferNeeded; try { bool status = UnsafeNativeMethods.EvtGetLogInfo(handle, enumType, 0, IntPtr.Zero, out bufferNeeded); int win32Error = Marshal.GetLastWin32Error(); if (!status) { if (win32Error != UnsafeNativeMethods.ERROR_INSUFFICIENT_BUFFER) EventLogException.Throw(win32Error); } buffer = Marshal.AllocHGlobal((int)bufferNeeded); status = UnsafeNativeMethods.EvtGetLogInfo(handle, enumType, bufferNeeded, buffer, out bufferNeeded); win32Error = Marshal.GetLastWin32Error(); if (!status) EventLogException.Throw(win32Error); UnsafeNativeMethods.EvtVariant varVal = Marshal.PtrToStructure<UnsafeNativeMethods.EvtVariant>(buffer); return ConvertToObject(varVal); } finally { if (buffer != IntPtr.Zero) Marshal.FreeHGlobal(buffer); } } public static void EvtRenderBufferWithContextSystem(EventLogHandle contextHandle, EventLogHandle eventHandle, UnsafeNativeMethods.EvtRenderFlags flag, SystemProperties systemProperties, int SYSTEM_PROPERTY_COUNT) { IntPtr buffer = IntPtr.Zero; IntPtr pointer = IntPtr.Zero; int bufferNeeded; int propCount; try { bool status = UnsafeNativeMethods.EvtRender(contextHandle, eventHandle, flag, 0, IntPtr.Zero, out bufferNeeded, out propCount); if (!status) { int error = Marshal.GetLastWin32Error(); if (error != UnsafeNativeMethods.ERROR_INSUFFICIENT_BUFFER) EventLogException.Throw(error); } buffer = Marshal.AllocHGlobal((int)bufferNeeded); status = UnsafeNativeMethods.EvtRender(contextHandle, eventHandle, flag, bufferNeeded, buffer, out bufferNeeded, out propCount); int win32Error = Marshal.GetLastWin32Error(); if (!status) EventLogException.Throw(win32Error); if (propCount != SYSTEM_PROPERTY_COUNT) throw new InvalidOperationException("We do not have " + SYSTEM_PROPERTY_COUNT + " variants given for the UnsafeNativeMethods.EvtRenderFlags.EvtRenderEventValues flag. (System Properties)"); pointer = buffer; // Read each Variant structure for (int i = 0; i < propCount; i++) { UnsafeNativeMethods.EvtVariant varVal = Marshal.PtrToStructure<UnsafeNativeMethods.EvtVariant>(pointer); switch (i) { case (int)UnsafeNativeMethods.EvtSystemPropertyId.EvtSystemProviderName: systemProperties.ProviderName = (string)ConvertToObject(varVal, UnsafeNativeMethods.EvtVariantType.EvtVarTypeString); break; case (int)UnsafeNativeMethods.EvtSystemPropertyId.EvtSystemProviderGuid: systemProperties.ProviderId = (Guid?)ConvertToObject(varVal, UnsafeNativeMethods.EvtVariantType.EvtVarTypeGuid); break; case (int)UnsafeNativeMethods.EvtSystemPropertyId.EvtSystemEventID: systemProperties.Id = (ushort?)ConvertToObject(varVal, UnsafeNativeMethods.EvtVariantType.EvtVarTypeUInt16); break; case (int)UnsafeNativeMethods.EvtSystemPropertyId.EvtSystemQualifiers: systemProperties.Qualifiers = (ushort?)ConvertToObject(varVal, UnsafeNativeMethods.EvtVariantType.EvtVarTypeUInt16); break; case (int)UnsafeNativeMethods.EvtSystemPropertyId.EvtSystemLevel: systemProperties.Level = (byte?)ConvertToObject(varVal, UnsafeNativeMethods.EvtVariantType.EvtVarTypeByte); break; case (int)UnsafeNativeMethods.EvtSystemPropertyId.EvtSystemTask: systemProperties.Task = (ushort?)ConvertToObject(varVal, UnsafeNativeMethods.EvtVariantType.EvtVarTypeUInt16); break; case (int)UnsafeNativeMethods.EvtSystemPropertyId.EvtSystemOpcode: systemProperties.Opcode = (byte?)ConvertToObject(varVal, UnsafeNativeMethods.EvtVariantType.EvtVarTypeByte); break; case (int)UnsafeNativeMethods.EvtSystemPropertyId.EvtSystemKeywords: systemProperties.Keywords = (ulong?)ConvertToObject(varVal, UnsafeNativeMethods.EvtVariantType.EvtVarTypeHexInt64); break; case (int)UnsafeNativeMethods.EvtSystemPropertyId.EvtSystemTimeCreated: systemProperties.TimeCreated = (DateTime?)ConvertToObject(varVal, UnsafeNativeMethods.EvtVariantType.EvtVarTypeFileTime); break; case (int)UnsafeNativeMethods.EvtSystemPropertyId.EvtSystemEventRecordId: systemProperties.RecordId = (ulong?)ConvertToObject(varVal, UnsafeNativeMethods.EvtVariantType.EvtVarTypeUInt64); break; case (int)UnsafeNativeMethods.EvtSystemPropertyId.EvtSystemActivityID: systemProperties.ActivityId = (Guid?)ConvertToObject(varVal, UnsafeNativeMethods.EvtVariantType.EvtVarTypeGuid); break; case (int)UnsafeNativeMethods.EvtSystemPropertyId.EvtSystemRelatedActivityID: systemProperties.RelatedActivityId = (Guid?)ConvertToObject(varVal, UnsafeNativeMethods.EvtVariantType.EvtVarTypeGuid); break; case (int)UnsafeNativeMethods.EvtSystemPropertyId.EvtSystemProcessID: systemProperties.ProcessId = (uint?)ConvertToObject(varVal, UnsafeNativeMethods.EvtVariantType.EvtVarTypeUInt32); break; case (int)UnsafeNativeMethods.EvtSystemPropertyId.EvtSystemThreadID: systemProperties.ThreadId = (uint?)ConvertToObject(varVal, UnsafeNativeMethods.EvtVariantType.EvtVarTypeUInt32); break; case (int)UnsafeNativeMethods.EvtSystemPropertyId.EvtSystemChannel: systemProperties.ChannelName = (string)ConvertToObject(varVal, UnsafeNativeMethods.EvtVariantType.EvtVarTypeString); break; case (int)UnsafeNativeMethods.EvtSystemPropertyId.EvtSystemComputer: systemProperties.ComputerName = (string)ConvertToObject(varVal, UnsafeNativeMethods.EvtVariantType.EvtVarTypeString); break; case (int)UnsafeNativeMethods.EvtSystemPropertyId.EvtSystemUserID: systemProperties.UserId = (SecurityIdentifier)ConvertToObject(varVal, UnsafeNativeMethods.EvtVariantType.EvtVarTypeSid); break; case (int)UnsafeNativeMethods.EvtSystemPropertyId.EvtSystemVersion: systemProperties.Version = (byte?)ConvertToObject(varVal, UnsafeNativeMethods.EvtVariantType.EvtVarTypeByte); break; } pointer = new IntPtr(((Int64)pointer + Marshal.SizeOf(varVal))); } } finally { if (buffer != IntPtr.Zero) Marshal.FreeHGlobal(buffer); } } // EvtRenderContextFlags can be both: EvtRenderContextFlags.EvtRenderContextUser and EvtRenderContextFlags.EvtRenderContextValues // Render with Context = ContextUser or ContextValues (with user defined Xpath query strings) public static IList<object> EvtRenderBufferWithContextUserOrValues(EventLogHandle contextHandle, EventLogHandle eventHandle) { IntPtr buffer = IntPtr.Zero; IntPtr pointer = IntPtr.Zero; int bufferNeeded; int propCount; UnsafeNativeMethods.EvtRenderFlags flag = UnsafeNativeMethods.EvtRenderFlags.EvtRenderEventValues; try { bool status = UnsafeNativeMethods.EvtRender(contextHandle, eventHandle, flag, 0, IntPtr.Zero, out bufferNeeded, out propCount); if (!status) { int error = Marshal.GetLastWin32Error(); if (error != UnsafeNativeMethods.ERROR_INSUFFICIENT_BUFFER) EventLogException.Throw(error); } buffer = Marshal.AllocHGlobal((int)bufferNeeded); status = UnsafeNativeMethods.EvtRender(contextHandle, eventHandle, flag, bufferNeeded, buffer, out bufferNeeded, out propCount); int win32Error = Marshal.GetLastWin32Error(); if (!status) EventLogException.Throw(win32Error); List<object> valuesList = new List<object>(propCount); if (propCount > 0) { pointer = buffer; for (int i = 0; i < propCount; i++) { UnsafeNativeMethods.EvtVariant varVal = Marshal.PtrToStructure<UnsafeNativeMethods.EvtVariant>(pointer); valuesList.Add(ConvertToObject(varVal)); pointer = new IntPtr(((Int64)pointer + Marshal.SizeOf(varVal))); } } return valuesList; } finally { if (buffer != IntPtr.Zero) Marshal.FreeHGlobal(buffer); } } public static string EvtFormatMessageRenderName(EventLogHandle pmHandle, EventLogHandle eventHandle, UnsafeNativeMethods.EvtFormatMessageFlags flag) { int bufferNeeded; StringBuilder sb = new StringBuilder(null); bool status = UnsafeNativeMethods.EvtFormatMessage(pmHandle, eventHandle, 0, 0, null, flag, 0, sb, out bufferNeeded); int error = Marshal.GetLastWin32Error(); if (!status && error != UnsafeNativeMethods.ERROR_EVT_UNRESOLVED_VALUE_INSERT) { // // ERROR_EVT_UNRESOLVED_VALUE_INSERT can be returned. It means // message may have one or more unsubstituted strings. This is // not an exception, but we have no way to convey the partial // success out to enduser. // switch (error) { case UnsafeNativeMethods.ERROR_EVT_MESSAGE_NOT_FOUND: case UnsafeNativeMethods.ERROR_EVT_MESSAGE_ID_NOT_FOUND: case UnsafeNativeMethods.ERROR_EVT_MESSAGE_LOCALE_NOT_FOUND: case UnsafeNativeMethods.ERROR_RESOURCE_LANG_NOT_FOUND: case UnsafeNativeMethods.ERROR_MUI_FILE_NOT_FOUND: return null; } if (error != (int)UnsafeNativeMethods.ERROR_INSUFFICIENT_BUFFER) EventLogException.Throw(error); } sb.EnsureCapacity(bufferNeeded); status = UnsafeNativeMethods.EvtFormatMessage(pmHandle, eventHandle, 0, 0, null, flag, bufferNeeded, sb, out bufferNeeded); error = Marshal.GetLastWin32Error(); if (!status && error != UnsafeNativeMethods.ERROR_EVT_UNRESOLVED_VALUE_INSERT) { switch (error) { case UnsafeNativeMethods.ERROR_EVT_MESSAGE_NOT_FOUND: case UnsafeNativeMethods.ERROR_EVT_MESSAGE_ID_NOT_FOUND: case UnsafeNativeMethods.ERROR_EVT_MESSAGE_LOCALE_NOT_FOUND: case UnsafeNativeMethods.ERROR_RESOURCE_LANG_NOT_FOUND: case UnsafeNativeMethods.ERROR_MUI_FILE_NOT_FOUND: return null; } EventLogException.Throw(error); } return sb.ToString(); } // The EvtFormatMessage used for the obtaining of the Keywords names. public static IEnumerable<string> EvtFormatMessageRenderKeywords(EventLogHandle pmHandle, EventLogHandle eventHandle, UnsafeNativeMethods.EvtFormatMessageFlags flag) { IntPtr buffer = IntPtr.Zero; int bufferNeeded; try { List<string> keywordsList = new List<string>(); bool status = UnsafeNativeMethods.EvtFormatMessageBuffer(pmHandle, eventHandle, 0, 0, IntPtr.Zero, flag, 0, IntPtr.Zero, out bufferNeeded); int error = Marshal.GetLastWin32Error(); if (!status) { switch (error) { case UnsafeNativeMethods.ERROR_EVT_MESSAGE_NOT_FOUND: case UnsafeNativeMethods.ERROR_EVT_MESSAGE_ID_NOT_FOUND: case UnsafeNativeMethods.ERROR_EVT_MESSAGE_LOCALE_NOT_FOUND: case UnsafeNativeMethods.ERROR_RESOURCE_LANG_NOT_FOUND: case UnsafeNativeMethods.ERROR_MUI_FILE_NOT_FOUND: return keywordsList.AsReadOnly(); } if (error != UnsafeNativeMethods.ERROR_INSUFFICIENT_BUFFER) EventLogException.Throw(error); } buffer = Marshal.AllocHGlobal(bufferNeeded * 2); status = UnsafeNativeMethods.EvtFormatMessageBuffer(pmHandle, eventHandle, 0, 0, IntPtr.Zero, flag, bufferNeeded, buffer, out bufferNeeded); error = Marshal.GetLastWin32Error(); if (!status) { switch (error) { case UnsafeNativeMethods.ERROR_EVT_MESSAGE_NOT_FOUND: case UnsafeNativeMethods.ERROR_EVT_MESSAGE_ID_NOT_FOUND: case UnsafeNativeMethods.ERROR_EVT_MESSAGE_LOCALE_NOT_FOUND: case UnsafeNativeMethods.ERROR_RESOURCE_LANG_NOT_FOUND: case UnsafeNativeMethods.ERROR_MUI_FILE_NOT_FOUND: return keywordsList; } EventLogException.Throw(error); } IntPtr pointer = buffer; while (true) { string s = Marshal.PtrToStringUni(pointer); if (String.IsNullOrEmpty(s)) break; keywordsList.Add(s); // nr of bytes = # chars * 2 + 2 bytes for character '\0'. pointer = new IntPtr((Int64)pointer + (s.Length * 2) + 2); } return keywordsList.AsReadOnly(); } finally { if (buffer != IntPtr.Zero) Marshal.FreeHGlobal(buffer); } } public static string EvtRenderBookmark(EventLogHandle eventHandle) { IntPtr buffer = IntPtr.Zero; int bufferNeeded; int propCount; UnsafeNativeMethods.EvtRenderFlags flag = UnsafeNativeMethods.EvtRenderFlags.EvtRenderBookmark; try { bool status = UnsafeNativeMethods.EvtRender(EventLogHandle.Zero, eventHandle, flag, 0, IntPtr.Zero, out bufferNeeded, out propCount); int error = Marshal.GetLastWin32Error(); if (!status) { if (error != UnsafeNativeMethods.ERROR_INSUFFICIENT_BUFFER) EventLogException.Throw(error); } buffer = Marshal.AllocHGlobal((int)bufferNeeded); status = UnsafeNativeMethods.EvtRender(EventLogHandle.Zero, eventHandle, flag, bufferNeeded, buffer, out bufferNeeded, out propCount); error = Marshal.GetLastWin32Error(); if (!status) EventLogException.Throw(error); return Marshal.PtrToStringUni(buffer); } finally { if (buffer != IntPtr.Zero) Marshal.FreeHGlobal(buffer); } } // Get the formatted description, using the msgId for FormatDescription(string []) public static string EvtFormatMessageFormatDescription(EventLogHandle handle, EventLogHandle eventHandle, string[] values) { int bufferNeeded; UnsafeNativeMethods.EvtStringVariant[] stringVariants = new UnsafeNativeMethods.EvtStringVariant[values.Length]; for (int i = 0; i < values.Length; i++) { stringVariants[i].Type = (uint)UnsafeNativeMethods.EvtVariantType.EvtVarTypeString; stringVariants[i].StringVal = values[i]; } StringBuilder sb = new StringBuilder(null); bool status = UnsafeNativeMethods.EvtFormatMessage(handle, eventHandle, 0xffffffff, values.Length, stringVariants, UnsafeNativeMethods.EvtFormatMessageFlags.EvtFormatMessageEvent, 0, sb, out bufferNeeded); int error = Marshal.GetLastWin32Error(); if (!status && error != UnsafeNativeMethods.ERROR_EVT_UNRESOLVED_VALUE_INSERT) { // // ERROR_EVT_UNRESOLVED_VALUE_INSERT can be returned. It means // message may have one or more unsubstituted strings. This is // not an exception, but we have no way to convey the partial // success out to enduser. // switch (error) { case UnsafeNativeMethods.ERROR_EVT_MESSAGE_NOT_FOUND: case UnsafeNativeMethods.ERROR_EVT_MESSAGE_ID_NOT_FOUND: case UnsafeNativeMethods.ERROR_EVT_MESSAGE_LOCALE_NOT_FOUND: case UnsafeNativeMethods.ERROR_RESOURCE_LANG_NOT_FOUND: case UnsafeNativeMethods.ERROR_MUI_FILE_NOT_FOUND: return null; } if (error != UnsafeNativeMethods.ERROR_INSUFFICIENT_BUFFER) EventLogException.Throw(error); } sb.EnsureCapacity(bufferNeeded); status = UnsafeNativeMethods.EvtFormatMessage(handle, eventHandle, 0xffffffff, values.Length, stringVariants, UnsafeNativeMethods.EvtFormatMessageFlags.EvtFormatMessageEvent, bufferNeeded, sb, out bufferNeeded); error = Marshal.GetLastWin32Error(); if (!status && error != UnsafeNativeMethods.ERROR_EVT_UNRESOLVED_VALUE_INSERT) { switch (error) { case UnsafeNativeMethods.ERROR_EVT_MESSAGE_NOT_FOUND: case UnsafeNativeMethods.ERROR_EVT_MESSAGE_ID_NOT_FOUND: case UnsafeNativeMethods.ERROR_EVT_MESSAGE_LOCALE_NOT_FOUND: case UnsafeNativeMethods.ERROR_RESOURCE_LANG_NOT_FOUND: case UnsafeNativeMethods.ERROR_MUI_FILE_NOT_FOUND: return null; } EventLogException.Throw(error); } return sb.ToString(); } private static object ConvertToObject(UnsafeNativeMethods.EvtVariant val) { switch (val.Type) { case (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeUInt32: return val.UInteger; case (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeInt32: return val.Integer; case (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeUInt16: return val.UShort; case (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeInt16: return val.SByte; case (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeByte: return val.UInt8; case (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeSByte: return val.SByte; case (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeUInt64: return val.ULong; case (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeInt64: return val.Long; case (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeHexInt64: return val.ULong; case (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeHexInt32: return val.Integer; case (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeSingle: return val.Single; case (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeDouble: return val.Double; case (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeNull: return null; case (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeString: return ConvertToString(val); case (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeAnsiString: return ConvertToAnsiString(val); case (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeSid: return (val.SidVal == IntPtr.Zero) ? null : new SecurityIdentifier(val.SidVal); case (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeGuid: return (val.GuidReference == IntPtr.Zero) ? Guid.Empty : Marshal.PtrToStructure<Guid>(val.GuidReference); case (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeEvtHandle: return ConvertToSafeHandle(val); case (int)(int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeFileTime: return DateTime.FromFileTime((long)val.FileTime); case (int)(int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeSysTime: UnsafeNativeMethods.SystemTime sysTime = Marshal.PtrToStructure<UnsafeNativeMethods.SystemTime>(val.SystemTime); return new DateTime(sysTime.Year, sysTime.Month, sysTime.Day, sysTime.Hour, sysTime.Minute, sysTime.Second, sysTime.Milliseconds); case (int)(int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeSizeT: return val.SizeT; case (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeBoolean: if (val.Bool != 0) return true; else return false; case (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeBinary: case ((int)UnsafeNativeMethods.EvtMasks.EVT_VARIANT_TYPE_ARRAY | (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeByte): if (val.Reference == IntPtr.Zero) return new Byte[0]; Byte[] arByte = new Byte[val.Count]; Marshal.Copy(val.Reference, arByte, 0, (int)val.Count); return arByte; case ((int)UnsafeNativeMethods.EvtMasks.EVT_VARIANT_TYPE_ARRAY | (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeInt16): if (val.Reference == IntPtr.Zero) return new Int16[0]; Int16[] arInt16 = new Int16[val.Count]; Marshal.Copy(val.Reference, arInt16, 0, (int)val.Count); return arInt16; case ((int)UnsafeNativeMethods.EvtMasks.EVT_VARIANT_TYPE_ARRAY | (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeInt32): if (val.Reference == IntPtr.Zero) return new Int32[0]; Int32[] arInt32 = new Int32[val.Count]; Marshal.Copy(val.Reference, arInt32, 0, (int)val.Count); return arInt32; case ((int)UnsafeNativeMethods.EvtMasks.EVT_VARIANT_TYPE_ARRAY | (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeInt64): if (val.Reference == IntPtr.Zero) return new Int64[0]; Int64[] arInt64 = new Int64[val.Count]; Marshal.Copy(val.Reference, arInt64, 0, (int)val.Count); return arInt64; case ((int)UnsafeNativeMethods.EvtMasks.EVT_VARIANT_TYPE_ARRAY | (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeSingle): if (val.Reference == IntPtr.Zero) return new Single[0]; Single[] arSingle = new Single[val.Count]; Marshal.Copy(val.Reference, arSingle, 0, (int)val.Count); return arSingle; case ((int)UnsafeNativeMethods.EvtMasks.EVT_VARIANT_TYPE_ARRAY | (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeDouble): if (val.Reference == IntPtr.Zero) return new Double[0]; Double[] arDouble = new Double[val.Count]; Marshal.Copy(val.Reference, arDouble, 0, (int)val.Count); return arDouble; case ((int)UnsafeNativeMethods.EvtMasks.EVT_VARIANT_TYPE_ARRAY | (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeSByte): return ConvertToArray<SByte>(val, sizeof(SByte)); // not CLS-compliant case ((int)UnsafeNativeMethods.EvtMasks.EVT_VARIANT_TYPE_ARRAY | (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeUInt16): return ConvertToArray<UInt16>(val, sizeof(UInt16)); case ((int)UnsafeNativeMethods.EvtMasks.EVT_VARIANT_TYPE_ARRAY | (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeUInt64): case ((int)UnsafeNativeMethods.EvtMasks.EVT_VARIANT_TYPE_ARRAY | (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeHexInt64): return ConvertToArray<UInt64>(val, sizeof(UInt64)); case ((int)UnsafeNativeMethods.EvtMasks.EVT_VARIANT_TYPE_ARRAY | (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeUInt32): case ((int)UnsafeNativeMethods.EvtMasks.EVT_VARIANT_TYPE_ARRAY | (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeHexInt32): return ConvertToArray<UInt32>(val, sizeof(UInt32)); case ((int)UnsafeNativeMethods.EvtMasks.EVT_VARIANT_TYPE_ARRAY | (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeString): return ConvertToStringArray(val, false); case ((int)UnsafeNativeMethods.EvtMasks.EVT_VARIANT_TYPE_ARRAY | (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeAnsiString): return ConvertToStringArray(val, true); case ((int)UnsafeNativeMethods.EvtMasks.EVT_VARIANT_TYPE_ARRAY | (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeBoolean): return ConvertToBoolArray(val); case ((int)UnsafeNativeMethods.EvtMasks.EVT_VARIANT_TYPE_ARRAY | (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeGuid): return ConvertToArray<Guid>(val, 16 * sizeof(byte)); case ((int)UnsafeNativeMethods.EvtMasks.EVT_VARIANT_TYPE_ARRAY | (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeFileTime): return ConvertToFileTimeArray(val); case ((int)UnsafeNativeMethods.EvtMasks.EVT_VARIANT_TYPE_ARRAY | (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeSysTime): return ConvertToSysTimeArray(val); case ((int)UnsafeNativeMethods.EvtMasks.EVT_VARIANT_TYPE_ARRAY | (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeBinary): // both length and count in the manifest: tracrpt supports, Crimson APIs don't case ((int)UnsafeNativeMethods.EvtMasks.EVT_VARIANT_TYPE_ARRAY | (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeSizeT): // unused: array of win:pointer is returned as HexIntXX case ((int)UnsafeNativeMethods.EvtMasks.EVT_VARIANT_TYPE_ARRAY | (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeSid): // unsupported by native APIs default: throw new EventLogInvalidDataException(); } } public static object ConvertToObject(UnsafeNativeMethods.EvtVariant val, UnsafeNativeMethods.EvtVariantType desiredType) { if (val.Type == (int)UnsafeNativeMethods.EvtVariantType.EvtVarTypeNull) return null; if (val.Type != (int)desiredType) throw new EventLogInvalidDataException(); return ConvertToObject(val); } public static string ConvertToString(UnsafeNativeMethods.EvtVariant val) { if (val.StringVal == IntPtr.Zero) return string.Empty; else return Marshal.PtrToStringUni(val.StringVal); } public static string ConvertToAnsiString(UnsafeNativeMethods.EvtVariant val) { if (val.AnsiString == IntPtr.Zero) return string.Empty; else return Marshal.PtrToStringAnsi(val.AnsiString); } public static EventLogHandle ConvertToSafeHandle(UnsafeNativeMethods.EvtVariant val) { if (val.Handle == IntPtr.Zero) return EventLogHandle.Zero; else return new EventLogHandle(val.Handle, true); } public static Array ConvertToArray<T>(UnsafeNativeMethods.EvtVariant val, int size) where T : struct { IntPtr ptr = val.Reference; if (ptr == IntPtr.Zero) { return Array.CreateInstance(typeof(T), 0); } else { Array array = Array.CreateInstance(typeof(T), (int)val.Count); for (int i = 0; i < val.Count; i++) { array.SetValue(Marshal.PtrToStructure<T>(ptr), i); ptr = new IntPtr((Int64)ptr + size); } return array; } } public static Array ConvertToBoolArray(UnsafeNativeMethods.EvtVariant val) { // NOTE: booleans are padded to 4 bytes in ETW IntPtr ptr = val.Reference; if (ptr == IntPtr.Zero) { return new bool[0]; } else { bool[] array = new bool[val.Count]; for (int i = 0; i < val.Count; i++) { bool value = (Marshal.ReadInt32(ptr) != 0) ? true : false; array[i] = value; ptr = new IntPtr((Int64)ptr + 4); } return array; } } public static Array ConvertToFileTimeArray(UnsafeNativeMethods.EvtVariant val) { IntPtr ptr = val.Reference; if (ptr == IntPtr.Zero) { return new DateTime[0]; } else { DateTime[] array = new DateTime[val.Count]; for (int i = 0; i < val.Count; i++) { array[i] = DateTime.FromFileTime(Marshal.ReadInt64(ptr)); ptr = new IntPtr((Int64)ptr + 8 * sizeof(byte)); // FILETIME values are 8 bytes } return array; } } public static Array ConvertToSysTimeArray(UnsafeNativeMethods.EvtVariant val) { IntPtr ptr = val.Reference; if (ptr == IntPtr.Zero) { return new DateTime[0]; } else { DateTime[] array = new DateTime[val.Count]; for (int i = 0; i < val.Count; i++) { UnsafeNativeMethods.SystemTime sysTime = Marshal.PtrToStructure<UnsafeNativeMethods.SystemTime>(ptr); array[i] = new DateTime(sysTime.Year, sysTime.Month, sysTime.Day, sysTime.Hour, sysTime.Minute, sysTime.Second, sysTime.Milliseconds); ptr = new IntPtr((Int64)ptr + 16 * sizeof(byte)); // SystemTime values are 16 bytes } return array; } } public static string[] ConvertToStringArray(UnsafeNativeMethods.EvtVariant val, bool ansi) { if (val.Reference == IntPtr.Zero) { return new string[0]; } else { IntPtr ptr = val.Reference; IntPtr[] pointersToString = new IntPtr[val.Count]; Marshal.Copy(ptr, pointersToString, 0, (int)val.Count); string[] stringArray = new string[val.Count]; for (int i = 0; i < val.Count; i++) { stringArray[i] = ansi ? Marshal.PtrToStringAnsi(pointersToString[i]) : Marshal.PtrToStringUni(pointersToString[i]); } return stringArray; } } } }
//------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------ namespace System.ServiceModel.Description { using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Net.Security; using System.Reflection; using System.ServiceModel.Security; [DebuggerDisplay("Name={name}, IsInitiating={isInitiating}, IsTerminating={isTerminating}")] public class OperationDescription { internal const string SessionOpenedAction = Channels.WebSocketTransportSettings.ConnectionOpenedAction; XmlName name; bool isInitiating; bool isTerminating; bool isSessionOpenNotificationEnabled; ContractDescription declaringContract; FaultDescriptionCollection faults; MessageDescriptionCollection messages; KeyedByTypeCollection<IOperationBehavior> behaviors; Collection<Type> knownTypes; MethodInfo beginMethod; MethodInfo endMethod; MethodInfo syncMethod; MethodInfo taskMethod; ProtectionLevel protectionLevel; bool hasProtectionLevel; bool validateRpcWrapperName = true; bool hasNoDisposableParameters; public OperationDescription(string name, ContractDescription declaringContract) { if (name == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("name"); } if (name.Length == 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new ArgumentOutOfRangeException("name", SR.GetString(SR.SFxOperationDescriptionNameCannotBeEmpty))); } this.name = new XmlName(name, true /*isEncoded*/); if (declaringContract == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("declaringContract"); } this.declaringContract = declaringContract; this.isInitiating = true; this.isTerminating = false; this.faults = new FaultDescriptionCollection(); this.messages = new MessageDescriptionCollection(); this.behaviors = new KeyedByTypeCollection<IOperationBehavior>(); this.knownTypes = new Collection<Type>(); } internal OperationDescription(string name, ContractDescription declaringContract, bool validateRpcWrapperName) : this(name, declaringContract) { this.validateRpcWrapperName = validateRpcWrapperName; } public KeyedCollection<Type, IOperationBehavior> OperationBehaviors { get { return this.Behaviors; } } [EditorBrowsable(EditorBrowsableState.Never)] public KeyedByTypeCollection<IOperationBehavior> Behaviors { get { return behaviors; } } // Not serializable on purpose, metadata import/export cannot // produce it, only available when binding to runtime public MethodInfo TaskMethod { get { return this.taskMethod; } set { this.taskMethod = value; } } // Not serializable on purpose, metadata import/export cannot // produce it, only available when binding to runtime public MethodInfo SyncMethod { get { return this.syncMethod; } set { this.syncMethod = value; } } // Not serializable on purpose, metadata import/export cannot // produce it, only available when binding to runtime public MethodInfo BeginMethod { get { return this.beginMethod; } set { this.beginMethod = value; } } internal MethodInfo OperationMethod { get { if (this.SyncMethod == null) { return this.TaskMethod ?? this.BeginMethod; } else { return this.SyncMethod; } } } public ProtectionLevel ProtectionLevel { get { return this.protectionLevel; } set { if (!ProtectionLevelHelper.IsDefined(value)) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value")); this.protectionLevel = value; this.hasProtectionLevel = true; } } public bool ShouldSerializeProtectionLevel() { return this.HasProtectionLevel; } public bool HasProtectionLevel { get { return this.hasProtectionLevel; } } internal bool HasNoDisposableParameters { get { return this.hasNoDisposableParameters; } set { this.hasNoDisposableParameters = value; } } // Not serializable on purpose, metadata import/export cannot // produce it, only available when binding to runtime public MethodInfo EndMethod { get { return this.endMethod; } set { this.endMethod = value; } } public ContractDescription DeclaringContract { get { return this.declaringContract; } set { if (value == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("DeclaringContract"); } else { this.declaringContract = value; } } } public FaultDescriptionCollection Faults { get { return faults; } } public bool IsOneWay { get { return this.Messages.Count == 1; } } [DefaultValue(false)] public bool IsInitiating { get { return this.isInitiating; } set { this.isInitiating = value; } } internal bool IsServerInitiated() { EnsureInvariants(); return Messages[0].Direction == MessageDirection.Output; } [DefaultValue(false)] public bool IsTerminating { get { return this.isTerminating; } set { this.isTerminating = value; } } public Collection<Type> KnownTypes { get { return this.knownTypes; } } // Messages[0] is the 'request' (first of MEP), and for non-oneway MEPs, Messages[1] is the 'response' (second of MEP) public MessageDescriptionCollection Messages { get { return messages; } } internal XmlName XmlName { get { return name; } } internal string CodeName { get { return name.DecodedName; } } public string Name { get { return name.EncodedName; } } internal bool IsValidateRpcWrapperName { get { return validateRpcWrapperName; } } //This property is set during contract inference in a hosted workflow scenario. This is required to handle correct //transactional invocation from the dispatcher in regards to scenarios involving the TransactedReceiveScope activity internal bool IsInsideTransactedReceiveScope { get; set; } //This property is set during contract inference in a hosted workflow scenario. This is required to handle correct //transactional invocation from the dispatcher in regards to scenarios involving the TransactedReceiveScope activity internal bool IsFirstReceiveOfTransactedReceiveScopeTree { get; set; } internal Type TaskTResult { get; set; } internal bool HasOutputParameters { get { // For non-oneway operations, Messages[1] is the 'response' return (this.Messages.Count > 1) && (this.Messages[1].Body.Parts.Count > 0); } } internal bool IsSessionOpenNotificationEnabled { get { return this.isSessionOpenNotificationEnabled; } set { this.isSessionOpenNotificationEnabled = value; } } internal void EnsureInvariants() { if (this.Messages.Count != 1 && this.Messages.Count != 2) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new System.InvalidOperationException(SR.GetString(SR.SFxOperationMustHaveOneOrTwoMessages, this.Name))); } } internal void ResetProtectionLevel() { this.protectionLevel = ProtectionLevel.None; this.hasProtectionLevel = false; } } }
namespace Zenject { // Zero parameters public class MemoryPool<TValue> : MemoryPoolBase<TValue>, IMemoryPool<TValue>, IFactory<TValue> { public TValue Spawn() { var item = GetInternal(); if (!Container.IsValidating) { #if ZEN_INTERNAL_PROFILING using (ProfileTimers.CreateTimedBlock("User Code")) #endif #if UNITY_EDITOR using (ProfileBlock.Start("{0}.Reinitialize", GetType())) #endif { Reinitialize(item); } } return item; } protected virtual void Reinitialize(TValue item) { // Optional } TValue IFactory<TValue>.Create() { return Spawn(); } } // One parameter public class MemoryPool<TParam1, TValue> : MemoryPoolBase<TValue>, IMemoryPool<TParam1, TValue>, IFactory<TParam1, TValue> { public TValue Spawn(TParam1 param) { var item = GetInternal(); if (!Container.IsValidating) { #if ZEN_INTERNAL_PROFILING using (ProfileTimers.CreateTimedBlock("User Code")) #endif #if UNITY_EDITOR using (ProfileBlock.Start("{0}.Reinitialize", GetType())) #endif { Reinitialize(param, item); } } return item; } protected virtual void Reinitialize(TParam1 p1, TValue item) { // Optional } TValue IFactory<TParam1, TValue>.Create(TParam1 p1) { return Spawn(p1); } } // Two parameters public class MemoryPool<TParam1, TParam2, TValue> : MemoryPoolBase<TValue>, IMemoryPool<TParam1, TParam2, TValue>, IFactory<TParam1, TParam2, TValue> { public TValue Spawn(TParam1 param1, TParam2 param2) { var item = GetInternal(); if (!Container.IsValidating) { #if ZEN_INTERNAL_PROFILING using (ProfileTimers.CreateTimedBlock("User Code")) #endif #if UNITY_EDITOR using (ProfileBlock.Start("{0}.Reinitialize", GetType())) #endif { Reinitialize(param1, param2, item); } } return item; } protected virtual void Reinitialize(TParam1 p1, TParam2 p2, TValue item) { // Optional } TValue IFactory<TParam1, TParam2, TValue>.Create(TParam1 p1, TParam2 p2) { return Spawn(p1, p2); } } // Three parameters public class MemoryPool<TParam1, TParam2, TParam3, TValue> : MemoryPoolBase<TValue>, IMemoryPool<TParam1, TParam2, TParam3, TValue>, IFactory<TParam1, TParam2, TParam3, TValue> { public TValue Spawn(TParam1 param1, TParam2 param2, TParam3 param3) { var item = GetInternal(); if (!Container.IsValidating) { #if ZEN_INTERNAL_PROFILING using (ProfileTimers.CreateTimedBlock("User Code")) #endif #if UNITY_EDITOR using (ProfileBlock.Start("{0}.Reinitialize", GetType())) #endif { Reinitialize(param1, param2, param3, item); } } return item; } protected virtual void Reinitialize(TParam1 p1, TParam2 p2, TParam3 p3, TValue item) { // Optional } TValue IFactory<TParam1, TParam2, TParam3, TValue>.Create(TParam1 p1, TParam2 p2, TParam3 p3) { return Spawn(p1, p2, p3); } } // Four parameters public class MemoryPool<TParam1, TParam2, TParam3, TParam4, TValue> : MemoryPoolBase<TValue>, IMemoryPool<TParam1, TParam2, TParam3, TParam4, TValue>, IFactory<TParam1, TParam2, TParam3, TParam4, TValue> { public TValue Spawn(TParam1 param1, TParam2 param2, TParam3 param3, TParam4 param4) { var item = GetInternal(); if (!Container.IsValidating) { #if ZEN_INTERNAL_PROFILING using (ProfileTimers.CreateTimedBlock("User Code")) #endif #if UNITY_EDITOR using (ProfileBlock.Start("{0}.Reinitialize", GetType())) #endif { Reinitialize(param1, param2, param3, param4, item); } } return item; } protected virtual void Reinitialize(TParam1 p1, TParam2 p2, TParam3 p3, TParam4 p4, TValue item) { // Optional } TValue IFactory<TParam1, TParam2, TParam3, TParam4, TValue>.Create(TParam1 p1, TParam2 p2, TParam3 p3, TParam4 p4) { return Spawn(p1, p2, p3, p4); } } // Five parameters public class MemoryPool<TParam1, TParam2, TParam3, TParam4, TParam5, TValue> : MemoryPoolBase<TValue>, IMemoryPool<TParam1, TParam2, TParam3, TParam4, TParam5, TValue>, IFactory<TParam1, TParam2, TParam3, TParam4, TParam5, TValue> { public TValue Spawn( TParam1 param1, TParam2 param2, TParam3 param3, TParam4 param4, TParam5 param5) { var item = GetInternal(); if (!Container.IsValidating) { #if ZEN_INTERNAL_PROFILING using (ProfileTimers.CreateTimedBlock("User Code")) #endif #if UNITY_EDITOR using (ProfileBlock.Start("{0}.Reinitialize", GetType())) #endif { Reinitialize(param1, param2, param3, param4, param5, item); } } return item; } protected virtual void Reinitialize(TParam1 p1, TParam2 p2, TParam3 p3, TParam4 p4, TParam5 p5, TValue item) { // Optional } TValue IFactory<TParam1, TParam2, TParam3, TParam4, TParam5, TValue>.Create(TParam1 p1, TParam2 p2, TParam3 p3, TParam4 p4, TParam5 p5) { return Spawn(p1, p2, p3, p4, p5); } } // Six parameters public class MemoryPool<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TValue> : MemoryPoolBase<TValue>, IMemoryPool<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TValue>, IFactory<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TValue> { public TValue Spawn( TParam1 param1, TParam2 param2, TParam3 param3, TParam4 param4, TParam5 param5, TParam6 param6) { var item = GetInternal(); if (!Container.IsValidating) { #if ZEN_INTERNAL_PROFILING using (ProfileTimers.CreateTimedBlock("User Code")) #endif #if UNITY_EDITOR using (ProfileBlock.Start("{0}.Reinitialize", GetType())) #endif { Reinitialize(param1, param2, param3, param4, param5, param6, item); } } return item; } protected virtual void Reinitialize(TParam1 p1, TParam2 p2, TParam3 p3, TParam4 p4, TParam5 p5, TParam6 p6, TValue item) { // Optional } TValue IFactory<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TValue>.Create(TParam1 p1, TParam2 p2, TParam3 p3, TParam4 p4, TParam5 p5, TParam6 p6) { return Spawn(p1, p2, p3, p4, p5, p6); } } // Seven parameters public class MemoryPool<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7, TValue> : MemoryPoolBase<TValue>, IMemoryPool<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7, TValue>, IFactory<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7, TValue> { public TValue Spawn( TParam1 param1, TParam2 param2, TParam3 param3, TParam4 param4, TParam5 param5, TParam6 param6, TParam7 param7) { var item = GetInternal(); if (!Container.IsValidating) { #if ZEN_INTERNAL_PROFILING using (ProfileTimers.CreateTimedBlock("User Code")) #endif #if UNITY_EDITOR using (ProfileBlock.Start("{0}.Reinitialize", GetType())) #endif { Reinitialize(param1, param2, param3, param4, param5, param6, param7, item); } } return item; } protected virtual void Reinitialize(TParam1 p1, TParam2 p2, TParam3 p3, TParam4 p4, TParam5 p5, TParam6 p6, TParam7 p7, TValue item) { // Optional } TValue IFactory<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7, TValue>.Create(TParam1 p1, TParam2 p2, TParam3 p3, TParam4 p4, TParam5 p5, TParam6 p6, TParam7 p7) { return Spawn(p1, p2, p3, p4, p5, p6, p7); } } // Eight parameters public class MemoryPool<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7, TParam8, TValue> : MemoryPoolBase<TValue>, IMemoryPool<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7, TParam8, TValue>, IFactory<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7, TParam8, TValue> { public TValue Spawn( TParam1 param1, TParam2 param2, TParam3 param3, TParam4 param4, TParam5 param5, TParam6 param6, TParam7 param7, TParam8 param8) { var item = GetInternal(); if (!Container.IsValidating) { #if ZEN_INTERNAL_PROFILING using (ProfileTimers.CreateTimedBlock("User Code")) #endif #if UNITY_EDITOR using (ProfileBlock.Start("{0}.Reinitialize", GetType())) #endif { Reinitialize(param1, param2, param3, param4, param5, param6, param7, param8, item); } } return item; } protected virtual void Reinitialize(TParam1 p1, TParam2 p2, TParam3 p3, TParam4 p4, TParam5 p5, TParam6 p6, TParam7 p7, TParam8 p8, TValue item) { // Optional } TValue IFactory<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7, TParam8, TValue>.Create( TParam1 p1, TParam2 p2, TParam3 p3, TParam4 p4, TParam5 p5, TParam6 p6, TParam7 p7, TParam8 p8) { return Spawn(p1, p2, p3, p4, p5, p6, p7, p8); } } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using sys = System; namespace Google.Ads.GoogleAds.V8.Resources { /// <summary>Resource name for the <c>AdGroupLabel</c> resource.</summary> public sealed partial class AdGroupLabelName : gax::IResourceName, sys::IEquatable<AdGroupLabelName> { /// <summary>The possible contents of <see cref="AdGroupLabelName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern <c>customers/{customer_id}/adGroupLabels/{ad_group_id}~{label_id}</c>. /// </summary> CustomerAdGroupLabel = 1, } private static gax::PathTemplate s_customerAdGroupLabel = new gax::PathTemplate("customers/{customer_id}/adGroupLabels/{ad_group_id_label_id}"); /// <summary>Creates a <see cref="AdGroupLabelName"/> 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="AdGroupLabelName"/> containing the provided /// <paramref name="unparsedResourceName"/>. /// </returns> public static AdGroupLabelName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new AdGroupLabelName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="AdGroupLabelName"/> with the pattern /// <c>customers/{customer_id}/adGroupLabels/{ad_group_id}~{label_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="adGroupId">The <c>AdGroup</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="labelId">The <c>Label</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="AdGroupLabelName"/> constructed from the provided ids.</returns> public static AdGroupLabelName FromCustomerAdGroupLabel(string customerId, string adGroupId, string labelId) => new AdGroupLabelName(ResourceNameType.CustomerAdGroupLabel, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), adGroupId: gax::GaxPreconditions.CheckNotNullOrEmpty(adGroupId, nameof(adGroupId)), labelId: gax::GaxPreconditions.CheckNotNullOrEmpty(labelId, nameof(labelId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="AdGroupLabelName"/> with pattern /// <c>customers/{customer_id}/adGroupLabels/{ad_group_id}~{label_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="adGroupId">The <c>AdGroup</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="labelId">The <c>Label</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="AdGroupLabelName"/> with pattern /// <c>customers/{customer_id}/adGroupLabels/{ad_group_id}~{label_id}</c>. /// </returns> public static string Format(string customerId, string adGroupId, string labelId) => FormatCustomerAdGroupLabel(customerId, adGroupId, labelId); /// <summary> /// Formats the IDs into the string representation of this <see cref="AdGroupLabelName"/> with pattern /// <c>customers/{customer_id}/adGroupLabels/{ad_group_id}~{label_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="adGroupId">The <c>AdGroup</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="labelId">The <c>Label</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="AdGroupLabelName"/> with pattern /// <c>customers/{customer_id}/adGroupLabels/{ad_group_id}~{label_id}</c>. /// </returns> public static string FormatCustomerAdGroupLabel(string customerId, string adGroupId, string labelId) => s_customerAdGroupLabel.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), $"{(gax::GaxPreconditions.CheckNotNullOrEmpty(adGroupId, nameof(adGroupId)))}~{(gax::GaxPreconditions.CheckNotNullOrEmpty(labelId, nameof(labelId)))}"); /// <summary>Parses the given resource name string into a new <see cref="AdGroupLabelName"/> 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}/adGroupLabels/{ad_group_id}~{label_id}</c></description> /// </item> /// </list> /// </remarks> /// <param name="adGroupLabelName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="AdGroupLabelName"/> if successful.</returns> public static AdGroupLabelName Parse(string adGroupLabelName) => Parse(adGroupLabelName, false); /// <summary> /// Parses the given resource name string into a new <see cref="AdGroupLabelName"/> 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}/adGroupLabels/{ad_group_id}~{label_id}</c></description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="adGroupLabelName">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="AdGroupLabelName"/> if successful.</returns> public static AdGroupLabelName Parse(string adGroupLabelName, bool allowUnparsed) => TryParse(adGroupLabelName, allowUnparsed, out AdGroupLabelName 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="AdGroupLabelName"/> 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}/adGroupLabels/{ad_group_id}~{label_id}</c></description> /// </item> /// </list> /// </remarks> /// <param name="adGroupLabelName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="AdGroupLabelName"/>, 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 adGroupLabelName, out AdGroupLabelName result) => TryParse(adGroupLabelName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="AdGroupLabelName"/> 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}/adGroupLabels/{ad_group_id}~{label_id}</c></description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="adGroupLabelName">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="AdGroupLabelName"/>, 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 adGroupLabelName, bool allowUnparsed, out AdGroupLabelName result) { gax::GaxPreconditions.CheckNotNull(adGroupLabelName, nameof(adGroupLabelName)); gax::TemplatedResourceName resourceName; if (s_customerAdGroupLabel.TryParseName(adGroupLabelName, out resourceName)) { string[] split1 = ParseSplitHelper(resourceName[1], new char[] { '~', }); if (split1 == null) { result = null; return false; } result = FromCustomerAdGroupLabel(resourceName[0], split1[0], split1[1]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(adGroupLabelName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private static string[] ParseSplitHelper(string s, char[] separators) { string[] result = new string[separators.Length + 1]; int i0 = 0; for (int i = 0; i <= separators.Length; i++) { int i1 = i < separators.Length ? s.IndexOf(separators[i], i0) : s.Length; if (i1 < 0 || i1 == i0) { return null; } result[i] = s.Substring(i0, i1 - i0); i0 = i1 + 1; } return result; } private AdGroupLabelName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string adGroupId = null, string customerId = null, string labelId = null) { Type = type; UnparsedResource = unparsedResourceName; AdGroupId = adGroupId; CustomerId = customerId; LabelId = labelId; } /// <summary> /// Constructs a new instance of a <see cref="AdGroupLabelName"/> class from the component parts of pattern /// <c>customers/{customer_id}/adGroupLabels/{ad_group_id}~{label_id}</c> /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="adGroupId">The <c>AdGroup</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="labelId">The <c>Label</c> ID. Must not be <c>null</c> or empty.</param> public AdGroupLabelName(string customerId, string adGroupId, string labelId) : this(ResourceNameType.CustomerAdGroupLabel, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), adGroupId: gax::GaxPreconditions.CheckNotNullOrEmpty(adGroupId, nameof(adGroupId)), labelId: gax::GaxPreconditions.CheckNotNullOrEmpty(labelId, nameof(labelId))) { } /// <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>AdGroup</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string AdGroupId { get; } /// <summary> /// The <c>Customer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string CustomerId { get; } /// <summary> /// The <c>Label</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string LabelId { 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.CustomerAdGroupLabel: return s_customerAdGroupLabel.Expand(CustomerId, $"{AdGroupId}~{LabelId}"); 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 AdGroupLabelName); /// <inheritdoc/> public bool Equals(AdGroupLabelName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(AdGroupLabelName a, AdGroupLabelName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(AdGroupLabelName a, AdGroupLabelName b) => !(a == b); } public partial class AdGroupLabel { /// <summary> /// <see cref="AdGroupLabelName"/>-typed view over the <see cref="ResourceName"/> resource name property. /// </summary> internal AdGroupLabelName ResourceNameAsAdGroupLabelName { get => string.IsNullOrEmpty(ResourceName) ? null : AdGroupLabelName.Parse(ResourceName, allowUnparsed: true); set => ResourceName = value?.ToString() ?? ""; } /// <summary> /// <see cref="AdGroupName"/>-typed view over the <see cref="AdGroup"/> resource name property. /// </summary> internal AdGroupName AdGroupAsAdGroupName { get => string.IsNullOrEmpty(AdGroup) ? null : AdGroupName.Parse(AdGroup, allowUnparsed: true); set => AdGroup = value?.ToString() ?? ""; } /// <summary><see cref="LabelName"/>-typed view over the <see cref="Label"/> resource name property.</summary> internal LabelName LabelAsLabelName { get => string.IsNullOrEmpty(Label) ? null : LabelName.Parse(Label, allowUnparsed: true); set => Label = value?.ToString() ?? ""; } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Linq; using System.Net; using Microsoft.WindowsAzure; using Microsoft.WindowsAzure.Management.Models; namespace Microsoft.WindowsAzure.Management.Models { /// <summary> /// The List Subscription Operations operation response. /// </summary> public partial class SubscriptionListOperationsResponse : OperationResponse { private string _continuationToken; /// <summary> /// The string that can be used to return the rest of the list. /// Subsequent requests must include this parameter to continue /// listing operations from where the last response left off. This /// element exists only if the complete list of subscription /// operations was not returned. /// </summary> public string ContinuationToken { get { return this._continuationToken; } set { this._continuationToken = value; } } private IList<SubscriptionListOperationsResponse.SubscriptionOperation> _subscriptionOperations; /// <summary> /// The list of operations that have been performed on the subscription /// during the specified timeframe. /// </summary> public IList<SubscriptionListOperationsResponse.SubscriptionOperation> SubscriptionOperations { get { return this._subscriptionOperations; } set { this._subscriptionOperations = value; } } /// <summary> /// Initializes a new instance of the /// SubscriptionListOperationsResponse class. /// </summary> public SubscriptionListOperationsResponse() { this._subscriptionOperations = new List<SubscriptionListOperationsResponse.SubscriptionOperation>(); } /// <summary> /// A collection of attributes that identifies the source of the /// operation. /// </summary> public partial class OperationCallerDetails { private string _clientIPAddress; /// <summary> /// The IP address of the client computer that initiated the /// operation. This element is returned only if /// UsedServiceManagementApi is true. /// </summary> public string ClientIPAddress { get { return this._clientIPAddress; } set { this._clientIPAddress = value; } } private string _subscriptionCertificateThumbprint; /// <summary> /// The thumbprint of the subscription certificate used to initiate /// the operation. /// </summary> public string SubscriptionCertificateThumbprint { get { return this._subscriptionCertificateThumbprint; } set { this._subscriptionCertificateThumbprint = value; } } private bool _usedServiceManagementApi; /// <summary> /// Indicates whether the operation was initiated by using the /// Service Management API. False if it was initiated by another /// source, such as the Management Portal. /// </summary> public bool UsedServiceManagementApi { get { return this._usedServiceManagementApi; } set { this._usedServiceManagementApi = value; } } private string _userEmailAddress; /// <summary> /// The email associated with the Windows Live ID of the user who /// initiated the operation from the Management Portal. This /// element is returned only if UsedServiceManagementApi is false. /// </summary> public string UserEmailAddress { get { return this._userEmailAddress; } set { this._userEmailAddress = value; } } /// <summary> /// Initializes a new instance of the OperationCallerDetails class. /// </summary> public OperationCallerDetails() { } } /// <summary> /// An operation that has been performed on the subscription during the /// specified timeframe. /// </summary> public partial class SubscriptionOperation { private SubscriptionListOperationsResponse.OperationCallerDetails _operationCaller; /// <summary> /// A collection of attributes that identifies the source of the /// operation. /// </summary> public SubscriptionListOperationsResponse.OperationCallerDetails OperationCaller { get { return this._operationCaller; } set { this._operationCaller = value; } } private DateTime _operationCompletedTime; /// <summary> /// The time that the operation finished executing. /// </summary> public DateTime OperationCompletedTime { get { return this._operationCompletedTime; } set { this._operationCompletedTime = value; } } private string _operationId; /// <summary> /// The globally unique identifier (GUID) of the operation. /// </summary> public string OperationId { get { return this._operationId; } set { this._operationId = value; } } private string _operationName; /// <summary> /// The name of the performed operation. /// </summary> public string OperationName { get { return this._operationName; } set { this._operationName = value; } } private string _operationObjectId; /// <summary> /// The target object for the operation. This value is equal to the /// URL for performing an HTTP GET on the object, and corresponds /// to the same values for the ObjectIdFilter in the request. /// </summary> public string OperationObjectId { get { return this._operationObjectId; } set { this._operationObjectId = value; } } private IDictionary<string, string> _operationParameters; /// <summary> /// The collection of parameters for the performed operation. /// </summary> public IDictionary<string, string> OperationParameters { get { return this._operationParameters; } set { this._operationParameters = value; } } private DateTime _operationStartedTime; /// <summary> /// The time that the operation started to execute. /// </summary> public DateTime OperationStartedTime { get { return this._operationStartedTime; } set { this._operationStartedTime = value; } } private string _operationStatus; /// <summary> /// An object that contains information on the current status of /// the operation. The object returned has the following XML /// format: <OperationStatus> /// <ID>339c6c13-1f81-412f-9bc6-00e9c5876695</ID> /// <Status>Succeeded</Status> /// <HttpStatusCode>200</HttpStatusCode> </OperationStatus> /// Possible values of the Status element, whichholds the /// operation status, are: Succeeded, Failed, InProgress. /// </summary> public string OperationStatus { get { return this._operationStatus; } set { this._operationStatus = value; } } /// <summary> /// Initializes a new instance of the SubscriptionOperation class. /// </summary> public SubscriptionOperation() { this._operationParameters = new Dictionary<string, string>(); } } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using LibGit2Sharp.Handlers; using LibGit2Sharp.Tests.TestHelpers; using Xunit; namespace LibGit2Sharp.Tests { public class PushFixture : BaseFixture { private void OnPushStatusError(PushStatusError pushStatusErrors) { Assert.True(false, string.Format("Failed to update reference '{0}': {1}", pushStatusErrors.Reference, pushStatusErrors.Message)); } private void AssertPush(Action<IRepository> push) { var scd = BuildSelfCleaningDirectory(); string originalRepoPath = SandboxBareTestRepo(); string clonedRepoPath = Repository.Clone(originalRepoPath, scd.DirectoryPath); using (var originalRepo = new Repository(originalRepoPath)) using (var clonedRepo = new Repository(clonedRepoPath)) { Remote remote = clonedRepo.Network.Remotes["origin"]; // Compare before Assert.Equal(originalRepo.Refs["HEAD"].ResolveToDirectReference().TargetIdentifier, clonedRepo.Refs["HEAD"].ResolveToDirectReference().TargetIdentifier); Assert.Equal( clonedRepo.Network.ListReferences(remote).Single(r => r.CanonicalName == "refs/heads/master"), clonedRepo.Refs.Head.ResolveToDirectReference()); // Change local state (commit) const string relativeFilepath = "new_file.txt"; Touch(clonedRepo.Info.WorkingDirectory, relativeFilepath, "__content__"); Commands.Stage(clonedRepo, relativeFilepath); clonedRepo.Commit("__commit_message__", Constants.Signature, Constants.Signature); // Assert local state has changed Assert.NotEqual(originalRepo.Refs["HEAD"].ResolveToDirectReference().TargetIdentifier, clonedRepo.Refs["HEAD"].ResolveToDirectReference().TargetIdentifier); Assert.NotEqual( clonedRepo.Network.ListReferences(remote).Single(r => r.CanonicalName == "refs/heads/master"), clonedRepo.Refs.Head.ResolveToDirectReference()); // Push the change upstream (remote state is supposed to change) push(clonedRepo); // Assert that both local and remote repos are in sync Assert.Equal(originalRepo.Refs["HEAD"].ResolveToDirectReference().TargetIdentifier, clonedRepo.Refs["HEAD"].ResolveToDirectReference().TargetIdentifier); Assert.Equal( clonedRepo.Network.ListReferences(remote).Single(r => r.CanonicalName == "refs/heads/master"), clonedRepo.Refs.Head.ResolveToDirectReference()); } } [Fact] public void CanPushABranchTrackingAnUpstreamBranch() { bool packBuilderCalled = false; PackBuilderProgressHandler packBuilderCb = (x, y, z) => { packBuilderCalled = true; return true; }; AssertPush(repo => repo.Network.Push(repo.Head)); AssertPush(repo => repo.Network.Push(repo.Branches["master"])); PushOptions options = new PushOptions() { OnPushStatusError = OnPushStatusError, OnPackBuilderProgress = packBuilderCb, }; AssertPush(repo => repo.Network.Push(repo.Network.Remotes["origin"], "HEAD", @"refs/heads/master", options)); Assert.True(packBuilderCalled); } [Fact] public void CanInvokePrePushCallbackAndSucceed() { bool packBuilderCalled = false; bool prePushHandlerCalled = false; PackBuilderProgressHandler packBuilderCb = (x, y, z) => { packBuilderCalled = true; return true; }; PrePushHandler prePushHook = (IEnumerable<PushUpdate> updates) => { Assert.True(updates.Count() == 1, "Expected 1 update, received " + updates.Count()); prePushHandlerCalled = true; return true; }; AssertPush(repo => repo.Network.Push(repo.Head)); AssertPush(repo => repo.Network.Push(repo.Branches["master"])); PushOptions options = new PushOptions() { OnPushStatusError = OnPushStatusError, OnPackBuilderProgress = packBuilderCb, OnNegotiationCompletedBeforePush = prePushHook, }; AssertPush(repo => repo.Network.Push(repo.Network.Remotes["origin"], "HEAD", @"refs/heads/master", options)); Assert.True(packBuilderCalled); Assert.True(prePushHandlerCalled); } [Fact] public void CanInvokePrePushCallbackAndFail() { bool packBuilderCalled = false; bool prePushHandlerCalled = false; PackBuilderProgressHandler packBuilderCb = (x, y, z) => { packBuilderCalled = true; return true; }; PrePushHandler prePushHook = (IEnumerable<PushUpdate> updates) => { Assert.True(updates.Count() == 1, "Expected 1 update, received " + updates.Count()); prePushHandlerCalled = true; return false; }; AssertPush(repo => repo.Network.Push(repo.Head)); AssertPush(repo => repo.Network.Push(repo.Branches["master"])); PushOptions options = new PushOptions() { OnPushStatusError = OnPushStatusError, OnPackBuilderProgress = packBuilderCb, OnNegotiationCompletedBeforePush = prePushHook }; Assert.Throws<UserCancelledException>(() => { AssertPush(repo => repo.Network.Push(repo.Network.Remotes["origin"], "HEAD", @"refs/heads/master", options)); }); Assert.False(packBuilderCalled); Assert.True(prePushHandlerCalled); } [Fact] public void PushingABranchThatDoesNotTrackAnUpstreamBranchThrows() { Assert.Throws<LibGit2SharpException>( () => AssertPush(repo => { Branch branch = repo.Branches["master"]; repo.Branches.Update(branch, b => b.TrackedBranch = null); repo.Network.Push(branch); })); } [Fact] public void CanForcePush() { string remoteRepoPath = InitNewRepository(true); // Create a new repository string localRepoPath = InitNewRepository(); using (var localRepo = new Repository(localRepoPath, new RepositoryOptions { Identity = Constants.Identity })) { // Add a commit Commit first = AddCommitToRepo(localRepo); Remote remote = localRepo.Network.Remotes.Add("origin", remoteRepoPath); localRepo.Branches.Update(localRepo.Head, b => b.Remote = remote.Name, b => b.UpstreamBranch = localRepo.Head.CanonicalName); // Push this commit localRepo.Network.Push(localRepo.Head); AssertRemoteHeadTipEquals(localRepo, first.Sha); UpdateTheRemoteRepositoryWithANewCommit(remoteRepoPath); // Add another commit var oldId = localRepo.Head.Tip.Id; Commit second = AddCommitToRepo(localRepo); // Try to fast forward push this new commit Assert.Throws<NonFastForwardException>(() => localRepo.Network.Push(localRepo.Head)); // Force push the new commit string pushRefSpec = string.Format("+{0}:{0}", localRepo.Head.CanonicalName); var before = DateTimeOffset.Now.TruncateMilliseconds(); localRepo.Network.Push(localRepo.Network.Remotes.Single(), pushRefSpec); AssertRemoteHeadTipEquals(localRepo, second.Sha); AssertRefLogEntry(localRepo, "refs/remotes/origin/master", "update by push", oldId, localRepo.Head.Tip.Id, Constants.Identity, before); } } private static void AssertRemoteHeadTipEquals(IRepository localRepo, string sha) { var remoteReferences = localRepo.Network.ListReferences(localRepo.Network.Remotes.Single()); Reference remoteHead = remoteReferences.Single(r => r.CanonicalName == "HEAD"); Assert.Equal(sha, remoteHead.ResolveToDirectReference().TargetIdentifier); } private void UpdateTheRemoteRepositoryWithANewCommit(string remoteRepoPath) { // Perform a fresh clone of the upstream repository var scd = BuildSelfCleaningDirectory(); string clonedRepoPath = Repository.Clone(remoteRepoPath, scd.DirectoryPath); using (var clonedRepo = new Repository(clonedRepoPath)) { // Add a commit AddCommitToRepo(clonedRepo); // Push this new commit toward an upstream repository clonedRepo.Network.Push(clonedRepo.Head); } } private Commit AddCommitToRepo(IRepository repository) { string random = Path.GetRandomFileName(); string filename = random + ".txt"; Touch(repository.Info.WorkingDirectory, filename, random); Commands.Stage(repository, filename); return repository.Commit("New commit", Constants.Signature, Constants.Signature); } } }
// // RangeCollection.cs // // Author: // Aaron Bockover <abockover@novell.com> // // Copyright (C) 2007-2008 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections; using System.Collections.Generic; namespace Hyena.Collections { public class RangeCollection : ICloneable, ICollection<int> { public struct Range { private int start; private int end; public Range (int start, int end) { this.start = start; this.end = end; } public override string ToString () { return String.Format ("{0}-{1} ({2})", Start, End, Count); } public int Start { get { return start; } set { start = value; } } public int End { get { return end; } set { end = value; } } public int Count { get { return End - Start + 1; } } } private const int MIN_CAPACITY = 16; private Range [] ranges; private int range_count; private int index_count; public RangeCollection () { Clear (); } #region Private Array Logic private void Shift (int start, int delta) { if (delta < 0) { start -= delta; } if (start < range_count) { Array.Copy (ranges, start, ranges, start + delta, range_count - start); } range_count += delta; } private void EnsureCapacity (int growBy) { int new_capacity = ranges.Length == 0 ? 1 : ranges.Length; int min_capacity = ranges.Length == 0 ? MIN_CAPACITY : ranges.Length + growBy; while (new_capacity < min_capacity) { new_capacity <<= 1; } Array.Resize (ref ranges, new_capacity); } private void Insert (int position, Range range) { if (range_count == ranges.Length) { EnsureCapacity (1); } Shift (position, 1); ranges[position] = range; } private void RemoveAt (int position) { Shift (position, -1); Array.Clear (ranges, range_count, 1); } #endregion #region Private Range Logic private bool RemoveIndexFromRange (int index) { int range_index = FindRangeIndexForValue (index); if (range_index < 0) { return false; } Range range = ranges[range_index]; if (range.Start == index && range.End == index) { RemoveAt (range_index); } else if (range.Start == index) { ranges[range_index].Start++; } else if (range.End == index) { ranges[range_index].End--; } else { Range split_range = new Range (index + 1, range.End); ranges[range_index].End = index - 1; Insert (range_index + 1, split_range); } index_count--; return true; } private void InsertRange (Range range) { int position = FindInsertionPosition (range); bool merged_left = MergeLeft (range, position); bool merged_right = MergeRight (range, position); if (!merged_left && !merged_right) { Insert (position, range); } else if (merged_left && merged_right) { ranges[position - 1].End = ranges[position].End; RemoveAt (position); } } private bool MergeLeft (Range range, int position) { int left = position - 1; if (left >= 0 && ranges[left].End + 1 == range.Start) { ranges[left].End = range.Start; return true; } return false; } private bool MergeRight (Range range, int position) { if (position < range_count && ranges[position].Start - 1 == range.End) { ranges[position].Start = range.End; return true; } return false; } private static int CompareRanges (Range a, Range b) { return (a.Start + (a.End - a.Start)).CompareTo (b.Start + (b.End - b.Start)); } private int FindInsertionPosition (Range range) { int min = 0; int max = range_count - 1; while (min <= max) { int mid = min + ((max - min) / 2); int cmp = CompareRanges (ranges[mid], range); if (cmp == 0) { return mid; } else if (cmp > 0) { if (mid > 0 && CompareRanges (ranges[mid - 1], range) < 0) { return mid; } max = mid - 1; } else { min = mid + 1; } } return min; } public int FindRangeIndexForValue (int value) { int min = 0; int max = range_count - 1; while (min <= max) { int mid = min + ((max - min) / 2); Range range = ranges[mid]; if (value >= range.Start && value <= range.End) { return mid; // In Range } else if (value < range.Start) { max = mid - 1; // Below Range } else { min = mid + 1; // Above Range } } return ~min; } #endregion #region Public RangeCollection API public Range [] Ranges { get { Range [] ranges_copy = new Range[range_count]; Array.Copy (ranges, ranges_copy, range_count); return ranges_copy; } } public int RangeCount { get { return range_count; } } public int IndexOf (int value) { int offset = 0; foreach (Range range in ranges) { if (value >= range.Start && value <= range.End) { return offset + (value - range.Start); } offset += range.End - range.Start + 1; } return -1; } public int this[int index] { get { for (int i = 0, cuml_count = 0; i < range_count && index >= 0; i++) { if (index < (cuml_count += ranges[i].Count)) { return ranges[i].End - (cuml_count - index) + 1; } } throw new IndexOutOfRangeException (index.ToString ()); } } #endregion #region ICollection Implementation public bool Add (int value) { if (!Contains (value)) { InsertRange (new Range (value, value)); index_count++; return true; } return false; } void ICollection<int>.Add (int value) { Add (value); } public bool Remove (int value) { return RemoveIndexFromRange (value); } public void Clear () { range_count = 0; index_count = 0; ranges = new Range[MIN_CAPACITY]; } public bool Contains (int value) { return FindRangeIndexForValue (value) >= 0; } public void CopyTo (int [] array, int index) { throw new NotImplementedException (); } public void CopyTo (Array array, int index) { throw new NotImplementedException (); } public int Count { get { return index_count; } } public bool IsReadOnly { get { return false; } } #endregion #region ICloneable Implementation public object Clone () { return MemberwiseClone (); } #endregion #region IEnumerable Implementation public IEnumerator<int> GetEnumerator () { for (int i = 0; i < range_count; i++) { for (int j = ranges[i].Start; j <= ranges[i].End; j++) { yield return j; } } } IEnumerator IEnumerable.GetEnumerator () { return GetEnumerator (); } #endregion } }
// 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; using System.Globalization; using System.Runtime.CompilerServices; using Microsoft.Scripting.Runtime; using System.Numerics; namespace IronPython.Runtime.Operations { public static class DecimalOps { public static int __cmp__(CodeContext context, decimal x, decimal other) { return x.CompareTo(other); } public static bool __nonzero__(decimal x) { return x != 0; } public static string __repr__(decimal x) { return x.ToString(CultureInfo.InvariantCulture); } [SpecialName] public static bool LessThan(decimal x, decimal y) { return x < y; } [SpecialName] public static bool LessThanOrEqual(decimal x, decimal y) { return x <= y; } [SpecialName] public static bool GreaterThan(decimal x, decimal y) { return x > y; } [SpecialName] public static bool GreaterThanOrEqual(decimal x, decimal y) { return x >= y; } [SpecialName] public static bool Equals(decimal x, decimal y) { return x == y; } [SpecialName] public static bool NotEquals(decimal x, decimal y) { return x != y; } internal static int __cmp__(BigInteger x, decimal y) { return -__cmp__(y, x); } internal static int __cmp__(decimal x, BigInteger y) { BigInteger bx = (BigInteger)x; if (bx == y) { decimal mod = x % 1; if (mod == 0) return 0; if (mod > 0) return +1; else return -1; } return bx > y ? +1 : -1; } [return: MaybeNotImplemented] internal static object __cmp__(object x, decimal y) { return __cmp__(y, x); } [return: MaybeNotImplemented] internal static object __cmp__(decimal x, object y) { if (object.ReferenceEquals(y, null)) { return ScriptingRuntimeHelpers.Int32ToObject(+1); } return PythonOps.NotImplemented; } public static int __hash__(decimal x) { return ((BigInteger)x).GetHashCode(); } public static string __format__(CodeContext/*!*/ context, decimal self, [NotNull]string/*!*/ formatSpec) { StringFormatSpec spec = StringFormatSpec.FromString(formatSpec); // default to the normal if(spec.IsEmpty) { return self.ToString(); } string digits = DecimalToFormatString(context, self, spec); return spec.AlignNumericText(digits, self != 0, self > 0); } /// <summary> /// Returns the digits for the format spec, no sign is included. /// </summary> private static string DecimalToFormatString(CodeContext/*!*/ context, decimal self, StringFormatSpec/*!*/ spec) { self = Math.Abs(self); const int DefaultPrecision = 12; int precision = spec.Precision ?? DefaultPrecision; string digits; switch (spec.Type) { case '%': { string fmt = "0." + new string('0', precision) + "%"; if (spec.ThousandsComma) { fmt = "#," + fmt; } digits = self.ToString(fmt, CultureInfo.InvariantCulture); break; } case 'f': case 'F': { string fmt = "0." + new string('0', precision); if (spec.ThousandsComma) { fmt = "#," + fmt; } digits = self.ToString(fmt, CultureInfo.InvariantCulture); break; } case 'e': case 'E': { string fmt = "0." + new string('0', precision) + spec.Type + "+00"; if (spec.ThousandsComma) { fmt = "#," + fmt; } digits = self.ToString(fmt, CultureInfo.InvariantCulture); break; } case '\0': case null: if (spec.Precision != null) { // precision applies to the combined digits before and after the decimal point // so we first need find out how many digits we have before... int digitCnt = 1; decimal cur = self; while (cur >= 10) { cur /= 10; digitCnt++; } // Use exponents if we don't have enough room for all the digits before. If we // only have as single digit avoid exponents. if (digitCnt > spec.Precision.Value && digitCnt != 1) { // first round off the decimal value self = Decimal.Round(self, 0, MidpointRounding.AwayFromZero); // then remove any insignificant digits double pow = Math.Pow(10, digitCnt - Math.Max(spec.Precision.Value, 1)); self = self - (self % (decimal)pow); // finally format w/ the requested precision string fmt = "0.0" + new string('#', spec.Precision.Value); digits = self.ToString(fmt + "e+00", CultureInfo.InvariantCulture); } else { // we're including all the numbers to the right of the decimal we can, we explicitly // round to match CPython's behavior int decimalPoints = Math.Max(spec.Precision.Value - digitCnt, 0); self = Decimal.Round(self, decimalPoints, MidpointRounding.AwayFromZero); digits = self.ToString("0.0" + new string('#', decimalPoints)); } } else { // just the default formatting if (self >= (decimal)1e12 || (self != 0 && self <= (decimal)0.00009)) { digits = self.ToString("0.#e+00", CultureInfo.InvariantCulture); } else if (spec.ThousandsComma) { digits = self.ToString("#,0.0###", CultureInfo.InvariantCulture); } else { digits = self.ToString("0.0###", CultureInfo.InvariantCulture); } } break; case 'n': case 'g': case 'G': { // precision applies to the combined digits before and after the decimal point // so we first need find out how many digits we have before... int digitCnt = 1; decimal cur = self; while (cur >= 10) { cur /= 10; digitCnt++; } // Use exponents if we don't have enough room for all the digits before. If we // only have as single digit avoid exponents. if (digitCnt > precision && digitCnt != 1) { // first round off the decimal value self = Decimal.Round(self, 0, MidpointRounding.AwayFromZero); // then remove any insignificant digits double pow = Math.Pow(10, digitCnt - Math.Max(precision, 1)); decimal rest = self / (decimal)pow; self = self - self % (decimal)pow; if ((rest % 1) >= (decimal).5) { // round up self += (decimal)pow; } string fmt; if (spec.Type == 'n' && context.LanguageContext.NumericCulture != PythonContext.CCulture) { // we've already figured out, we don't have any digits for decimal points, so just format as a number + exponent fmt = "0"; } else if (spec.Precision > 1 || digitCnt > 6) { // include the requested precision to the right of the decimal fmt = "0.#" + new string('#', precision); } else { // zero precision, no decimal fmt = "0"; } if (spec.ThousandsComma) { fmt = "#," + fmt; } digits = self.ToString(fmt + (spec.Type == 'G' ? "E+00" : "e+00"), CultureInfo.InvariantCulture); } else { // we're including all the numbers to the right of the decimal we can, we explicitly // round to match CPython's behavior if (self < 1) { // no implicit 0 digitCnt--; } int decimalPoints = Math.Max(precision - digitCnt, 0); self = Decimal.Round(self, decimalPoints, MidpointRounding.AwayFromZero); if (spec.Type == 'n' && context.LanguageContext.NumericCulture != PythonContext.CCulture) { if (digitCnt != precision && (self % 1) != 0) { digits = self.ToString("#,0.0" + new string('#', decimalPoints)); } else { // leave out the decimal if the precision == # of digits or we have a whole number digits = self.ToString("#,0"); } } else { if (digitCnt != precision && (self % 1) != 0) { digits = self.ToString("0.0" + new string('#', decimalPoints)); } else { // leave out the decimal if the precision == # of digits or we have a whole number digits = self.ToString("0"); } } } } break; default: throw PythonOps.ValueError("Unknown format code '{0}' for object of type 'decimal'", spec.Type.ToString()); } return digits; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.Win32.SafeHandles; using System.Diagnostics.CodeAnalysis; using System.Security; using System.Threading; using System.Threading.Tasks; namespace System.IO.Pipes { /// <summary> /// Named pipe server /// </summary> public sealed partial class NamedPipeServerStream : PipeStream { // Use the maximum number of server instances that the system resources allow private const int MaxAllowedServerInstances = -1; [SecuritySafeCritical] public NamedPipeServerStream(String pipeName) : this(pipeName, PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.None, 0, 0, HandleInheritability.None) { } [SecuritySafeCritical] public NamedPipeServerStream(String pipeName, PipeDirection direction) : this(pipeName, direction, 1, PipeTransmissionMode.Byte, PipeOptions.None, 0, 0, HandleInheritability.None) { } [SecuritySafeCritical] public NamedPipeServerStream(String pipeName, PipeDirection direction, int maxNumberOfServerInstances) : this(pipeName, direction, maxNumberOfServerInstances, PipeTransmissionMode.Byte, PipeOptions.None, 0, 0, HandleInheritability.None) { } [SecuritySafeCritical] public NamedPipeServerStream(String pipeName, PipeDirection direction, int maxNumberOfServerInstances, PipeTransmissionMode transmissionMode) : this(pipeName, direction, maxNumberOfServerInstances, transmissionMode, PipeOptions.None, 0, 0, HandleInheritability.None) { } [SecuritySafeCritical] public NamedPipeServerStream(String pipeName, PipeDirection direction, int maxNumberOfServerInstances, PipeTransmissionMode transmissionMode, PipeOptions options) : this(pipeName, direction, maxNumberOfServerInstances, transmissionMode, options, 0, 0, HandleInheritability.None) { } [SecuritySafeCritical] public NamedPipeServerStream(String pipeName, PipeDirection direction, int maxNumberOfServerInstances, PipeTransmissionMode transmissionMode, PipeOptions options, int inBufferSize, int outBufferSize) : this(pipeName, direction, maxNumberOfServerInstances, transmissionMode, options, inBufferSize, outBufferSize, HandleInheritability.None) { } /// <summary> /// Full named pipe server constructor /// </summary> /// <param name="pipeName">Pipe name</param> /// <param name="direction">Pipe direction: In, Out or InOut (duplex). /// Win32 note: this gets OR'd into dwOpenMode to CreateNamedPipe /// </param> /// <param name="maxNumberOfServerInstances">Maximum number of server instances. Specify a fixed value between /// 1 and 254 (Windows)/greater than 1 (Unix), or use NamedPipeServerStream.MaxAllowedServerInstances to use the /// maximum amount allowed by system resources.</param> /// <param name="transmissionMode">Byte mode or message mode. /// Win32 note: this gets used for dwPipeMode. CreateNamedPipe allows you to specify PIPE_TYPE_BYTE/MESSAGE /// and PIPE_READMODE_BYTE/MESSAGE independently, but this sets type and readmode to match. /// </param> /// <param name="options">PipeOption enum: None, Asynchronous, or Writethrough /// Win32 note: this gets passed in with dwOpenMode to CreateNamedPipe. Asynchronous corresponds to /// FILE_FLAG_OVERLAPPED option. PipeOptions enum doesn't expose FIRST_PIPE_INSTANCE option because /// this sets that automatically based on the number of instances specified. /// </param> /// <param name="inBufferSize">Incoming buffer size, 0 or higher. /// Note: this size is always advisory; OS uses a suggestion. /// </param> /// <param name="outBufferSize">Outgoing buffer size, 0 or higher (see above)</param> /// <param name="pipeSecurity">PipeSecurity, or null for default security descriptor</param> /// <param name="inheritability">Whether handle is inheritable</param> /// <param name="additionalAccessRights">Combination (logical OR) of PipeAccessRights.TakeOwnership, /// PipeAccessRights.AccessSystemSecurity, and PipeAccessRights.ChangePermissions</param> [SecuritySafeCritical] private NamedPipeServerStream(String pipeName, PipeDirection direction, int maxNumberOfServerInstances, PipeTransmissionMode transmissionMode, PipeOptions options, int inBufferSize, int outBufferSize, HandleInheritability inheritability) : base(direction, transmissionMode, outBufferSize) { if (pipeName == null) { throw new ArgumentNullException("pipeName"); } if (pipeName.Length == 0) { throw new ArgumentException(SR.Argument_NeedNonemptyPipeName); } if ((options & ~(PipeOptions.WriteThrough | PipeOptions.Asynchronous)) != 0) { throw new ArgumentOutOfRangeException("options", SR.ArgumentOutOfRange_OptionsInvalid); } if (inBufferSize < 0) { throw new ArgumentOutOfRangeException("inBufferSize", SR.ArgumentOutOfRange_NeedNonNegNum); } ValidateMaxNumberOfServerInstances(maxNumberOfServerInstances); // inheritability will always be None since this private constructor is only called from other constructors from which // inheritability is always set to None. Desktop has a public constructor to allow setting it to something else, but Core // doesnt. if (inheritability < HandleInheritability.None || inheritability > HandleInheritability.Inheritable) { throw new ArgumentOutOfRangeException("inheritability", SR.ArgumentOutOfRange_HandleInheritabilityNoneOrInheritable); } Create(pipeName, direction, maxNumberOfServerInstances, transmissionMode, options, inBufferSize, outBufferSize, inheritability); } // Create a NamedPipeServerStream from an existing server pipe handle. [SecuritySafeCritical] public NamedPipeServerStream(PipeDirection direction, bool isAsync, bool isConnected, SafePipeHandle safePipeHandle) : base(direction, PipeTransmissionMode.Byte, 0) { if (safePipeHandle == null) { throw new ArgumentNullException("safePipeHandle"); } if (safePipeHandle.IsInvalid) { throw new ArgumentException(SR.Argument_InvalidHandle, "safePipeHandle"); } ValidateHandleIsPipe(safePipeHandle); InitializeHandle(safePipeHandle, true, isAsync); if (isConnected) { State = PipeState.Connected; } } ~NamedPipeServerStream() { Dispose(false); } public Task WaitForConnectionAsync() { return WaitForConnectionAsync(CancellationToken.None); } // Server can only connect from Disconnected state [SecurityCritical] [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Consistent with security model")] private void CheckConnectOperationsServer() { // we're not checking whether already connected; this allows us to throw IOException // "pipe is being closed" if other side is closing (as does win32) or no-op if // already connected if (State == PipeState.Closed) { throw __Error.GetPipeNotOpen(); } if (InternalHandle != null && InternalHandle.IsClosed) // only check IsClosed if we have a handle { throw __Error.GetPipeNotOpen(); } if (State == PipeState.Broken) { throw new IOException(SR.IO_PipeBroken); } } // Server is allowed to disconnect from connected and broken states [SecurityCritical] private void CheckDisconnectOperations() { if (State == PipeState.WaitingToConnect) { throw new InvalidOperationException(SR.InvalidOperation_PipeNotYetConnected); } if (State == PipeState.Disconnected) { throw new InvalidOperationException(SR.InvalidOperation_PipeAlreadyDisconnected); } if (InternalHandle == null && CheckOperationsRequiresSetHandle) { throw new InvalidOperationException(SR.InvalidOperation_PipeHandleNotSet); } if ((State == PipeState.Closed) || (InternalHandle != null && InternalHandle.IsClosed)) { throw __Error.GetPipeNotOpen(); } } } #if RunAs // Users will use this delegate to specify a method to call while impersonating the client // (see NamedPipeServerStream.RunAsClient). public delegate void PipeStreamImpersonationWorker(); #endif }
using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; namespace Palaso.WritingSystems { public class IanaSubtag { public IanaSubtag(string type, string subtag, string description) { Type = type; Subtag = subtag; Description = description; } public override string ToString() { return Description; } public string Type { get; private set; } public string Subtag { get; private set; } public string Description { get; private set; } public static int CompareByDescription(IanaSubtag x, IanaSubtag y) { if (x == null) { if (y == null) { return 0; } else { return -1; } } else { if (y == null) { return 1; } else { return x.Description.CompareTo(y.Description); } } } } /// <summary> /// This class parses the IANA subtag registry in order to provide a list of valid language, script, region and variant subtags /// for use by the Rfc5646Tag and other classes. /// </summary> public class StandardTags { public class IanaVariantSubtag : IanaSubtag { /// <summary> /// A Variant with no prefixes (prefixes will be null) may be applied to any language. One with one or more prefixes may only be /// applied to those language tags which begin with that prefix. (This is currently not enforced, but the information is available /// for use by dialogs which display variant choices.) /// </summary> public string[] Prefixes { get; private set; } public IanaVariantSubtag(string type, string subtag, string description, IEnumerable<string> prefixes) : base(type, subtag, description) { if (prefixes != null) Prefixes = prefixes.ToArray(); } } static StandardTags() { ValidIso15924Scripts = new List<Iso15924Script>(); ValidIso639LanguageCodes = new List<Iso639LanguageCode>(); ValidIso3166Regions = new List<IanaSubtag>(); ValidRegisteredVariants = new List<IanaVariantSubtag>(); LoadIanaSubtags(); } public static List<Iso15924Script> ValidIso15924Scripts { get; private set; } public static List<Iso639LanguageCode> ValidIso639LanguageCodes { get; private set; } public static List<IanaSubtag> ValidIso3166Regions { get; private set; } public static List<IanaVariantSubtag> ValidRegisteredVariants { get; private set; } private static void LoadIanaSubtags() { // JohnT: can't find anywhere else to document this, so here goes: TwoToThreeMap is a file adapted from // FieldWorks Ethnologue\Data\iso-639-3_20080804.tab, by discarding all but the first column (3-letter // ethnologue codes) and the fourth (two-letter IANA codes), and all the rows where the fourth column is empty. // I then swapped the columns. So, in this resource, the string before the tab in each line is a 2-letter // Iana code, and the string after it is the one we want to return as the corresponding ISO3Code. // The following block of code assembles these lines into a map we can use to fill this slot properly // when building the main table. var TwoToThreeMap = new Dictionary<string, string>(); string[] encodingPairs = LanguageRegistryResources.TwoToThreeCodes.Replace("\r\n", "\n").Split(new[] { "\n" }, StringSplitOptions.RemoveEmptyEntries); foreach (string pair in encodingPairs) { var items = pair.Split('\t'); if (items.Length != 2) continue; TwoToThreeMap[items[0]] = items[1]; } string[] ianaSubtagsAsStrings = LanguageRegistryResources.ianaSubtagRegistry.Split(new[] { "%%" }, StringSplitOptions.None); foreach (string ianaSubtagAsString in ianaSubtagsAsStrings) { string[] subTagComponents = ianaSubtagAsString.Replace("\r\n", "\n").Split(new[] { "\n" }, StringSplitOptions.RemoveEmptyEntries); if (subTagComponents[0].Contains("File-Date")) { continue; //This is the first line of the file. } CheckIfIanaSubtagFromFileHasExpectedForm(subTagComponents); string type = subTagComponents[0].Split(' ')[1]; string subtag = subTagComponents[1].Split(' ')[1]; string description = SubTagComponentDescription(subTagComponents[2]); if (subtag.Contains("..")) // do not add private use subtags to the list { continue; } /* Note: currently we are only using the first "Description:" line in each entry. * A few script entries contain multiple Description: lines, as in the example below: * * Type: script * Subtag: Deva * Description: Devanagari * Description: Nagari * Added: 2005-10-16 * * In the future it may be necessary to build a separate iana script entry collection * that contains duplicate script codes, for the purposes of including all possible * script Descriptions. */ switch (type) { case "language": string iso3Code; if (!TwoToThreeMap.TryGetValue(subtag, out iso3Code)) iso3Code = String.Empty; ValidIso639LanguageCodes.Add( new Iso639LanguageCode(subtag, description, iso3Code) ); break; case "script": ValidIso15924Scripts.Add( new Iso15924Script(description, subtag) ); break; case "region": ValidIso3166Regions.Add( new IanaSubtag(type, subtag, description) ); break; case "variant": ValidRegisteredVariants.Add( new IanaVariantSubtag(type, subtag, description, GetVariantPrefixes(subTagComponents)) ); break; } } ValidIso639LanguageCodes.Sort(Iso639LanguageCode.CompareByName); ValidIso15924Scripts.Sort(Iso15924Script.CompareScriptOptions); ValidIso3166Regions.Sort(IanaSubtag.CompareByDescription); ValidRegisteredVariants.Sort(IanaSubtag.CompareByDescription); // Add Unlisted Language at the end ValidIso639LanguageCodes.Insert(ValidIso639LanguageCodes.Count, new Iso639LanguageCode("qaa", "Language Not Listed", String.Empty)); // To help people find Latin as a script tag ValidIso15924Scripts.Insert(0, new Iso15924Script("Roman (Latin)", "Latn")); } private static IEnumerable<string> GetVariantPrefixes(string[] subTagComponents) { foreach (var line in subTagComponents) { if (line.StartsWith("Prefix: ")) yield return line.Substring("Prefix: ".Length).Trim(); } } internal static string SubTagComponentDescription(string component) { string description = component.Substring(component.IndexOf(" ") + 1); description = Regex.Replace(description, @"\(alias for ", "("); if (description[0] == '(') { // remove parens if the description begins with an open parenthesis description = Regex.Replace(description, @"[\(\)]", ""); } description = Regex.Replace(description, @"/", "|"); return description; } private static void CheckIfIanaSubtagFromFileHasExpectedForm(string[] subTagComponents) { if (!subTagComponents[0].Contains("Type:")) { throw new ApplicationException( String.Format( "Unable to parse IANA subtag. First line was '{0}' when it should have denoted the type of subtag.", subTagComponents[0])); } if (!subTagComponents[1].Contains("Subtag:") && !subTagComponents[1].Contains("Tag:")) { throw new ApplicationException( String.Format( "Unable to parse IANA subtag. Second line was '{0}' when it should have denoted the subtag code.", subTagComponents[1] ) ); } if (!subTagComponents[2].Contains("Description:")) { throw new ApplicationException( String.Format( "Unable to parse IANA subtag. Second line was '{0}' when it should have contained a description.", subTagComponents[2])); } } public static bool IsValidIso639LanguageCode(string languageCodeToCheck) { if (languageCodeToCheck.Equals("qaa", StringComparison.OrdinalIgnoreCase)) { return true; } return ValidIso639LanguageCodes.Any(code => languageCodeToCheck.Equals(code.Code, StringComparison.OrdinalIgnoreCase)); } public static bool IsValidIso15924ScriptCode(string scriptTagToCheck) { return IsStandardIso15924ScriptCode(scriptTagToCheck) || IsPrivateUseScriptCode(scriptTagToCheck); } public static bool IsPrivateUseScriptCode(string scriptCode) { var scriptCodeU = scriptCode.ToUpperInvariant(); return (scriptCodeU.CompareTo("QAAA") >= 0 && scriptCodeU.CompareTo("QABX") <= 0); } public static bool IsStandardIso15924ScriptCode(string scriptTagToCheck) { return ValidIso15924Scripts.Any( code => scriptTagToCheck.Equals(code.Code, StringComparison.OrdinalIgnoreCase) ); } public static bool IsValidIso3166Region(string regionCodeToCheck) { return IsStandardIso3166Region(regionCodeToCheck) || IsPrivateUseRegionCode(regionCodeToCheck); } public static bool IsStandardIso3166Region(string regionCodeToCheck) { return ValidIso3166Regions.Any( code => regionCodeToCheck.Equals(code.Subtag, StringComparison.OrdinalIgnoreCase) ); } /// <summary> /// Determines whether the specified region code is private use. These are considered valid region codes, /// but not predefined ones with a known meaning. /// </summary> /// <param name="regionCode">The region code.</param> /// <returns> /// <c>true</c> if the region code is private use. /// </returns> public static bool IsPrivateUseRegionCode(string regionCode) { var regionCodeU = regionCode.ToUpperInvariant(); return regionCodeU == "AA" || regionCodeU == "ZZ" || (regionCodeU.CompareTo("QM") >= 0 && regionCodeU.CompareTo("QZ") <= 0) || (regionCodeU.CompareTo("XA") >= 0 && regionCodeU.CompareTo("XZ") <= 0); } public static bool IsValidRegisteredVariant(string variantToCheck) { return ValidRegisteredVariants.Any( code => variantToCheck.Equals(code.Subtag, StringComparison.OrdinalIgnoreCase) ); } } }
using System; using System.Collections.Generic; using CubeWorld.World; using UnityEngine; using CubeWorld.Tiles; using CubeWorld.World.Objects; using CubeWorld.Items; using CubeWorld.Avatars; public class CWObjectsManagerUnity : ICWListener { private List<TileUnity> unityTiles = new List<TileUnity>(); private List<ItemUnity> unityItems = new List<ItemUnity>(); private List<ItemTileUnity> unityItemTiles = new List<ItemTileUnity>(); private List<AvatarUnity> unityAvatars = new List<AvatarUnity>(); private Dictionary<CWObject, GameObject> createdGO = new Dictionary<CWObject, GameObject>(); private GameManagerUnity gameManagerUnity; public CWObjectsManagerUnity (GameManagerUnity gameManagerUnity) { this.gameManagerUnity = gameManagerUnity; } public void Clear() { foreach (TileUnity unityTile in unityTiles) GameObject.DestroyImmediate(unityTile.gameObject); unityTiles.Clear(); foreach (ItemUnity unityItem in unityItems) GameObject.DestroyImmediate(unityItem.gameObject); unityItems.Clear(); foreach (ItemTileUnity unityItemTile in unityItemTiles) GameObject.DestroyImmediate(unityItemTile.gameObject); unityItemTiles.Clear(); foreach (AvatarUnity unityAvatar in unityAvatars) GameObject.DestroyImmediate(unityAvatar.gameObject); unityAvatars.Clear(); } public GameObject CreateTileGameObject(DynamicTile tile) { GameObject g = new GameObject(); TileUnity tileUnity = (TileUnity)g.AddComponent(typeof(TileUnity)); tileUnity.gameManagerUnity = gameManagerUnity; tileUnity.tile = tile; unityTiles.Add(tileUnity); return g; } public void RemoveTileGameObject(GameObject g) { unityTiles.Remove(g.GetComponent<TileUnity>()); GameObject.Destroy(g); } public GameObject CreateItemGameObject(Item item) { GameObject g = new GameObject(); ItemUnity itemUnity = (ItemUnity)g.AddComponent(typeof(ItemUnity)); itemUnity.gameManagerUnity = gameManagerUnity; itemUnity.item = item; unityItems.Add(itemUnity); return g; } public void RemoveItemGameObject(GameObject g) { unityItems.Remove(g.GetComponent<ItemUnity>()); GameObject.Destroy(g); } public GameObject CreateItemTileGameObject(ItemTile item) { GameObject g = new GameObject(); ItemTileUnity itemTileUnity = (ItemTileUnity)g.AddComponent(typeof(ItemTileUnity)); itemTileUnity.gameManagerUnity = gameManagerUnity; itemTileUnity.item = item; unityItemTiles.Add(itemTileUnity); return g; } public void RemoveItemTileGameObject(GameObject g) { unityItemTiles.Remove(g.GetComponent<ItemTileUnity>()); GameObject.Destroy(g); } public GameObject CreateAvatarGameObject(CubeWorld.Avatars.Avatar avatar) { GameObject g; AvatarUnity avatarUnity; if (avatar.definition.id == "player") { g = (GameObject) GameObject.Instantiate(Resources.Load("Prefabs/Player", typeof(GameObject))); avatarUnity = g.GetComponent<PlayerUnity>(); gameManagerUnity.playerUnity = g.GetComponent<PlayerUnity>(); gameManagerUnity.playerUnity.gameManagerUnity = gameManagerUnity; gameManagerUnity.playerUnity.avatar = avatar; gameManagerUnity.playerUnity.Reset(); } else { g = new GameObject(); avatarUnity = (NonPlayerAvatarUnity)g.AddComponent(typeof(NonPlayerAvatarUnity)); avatarUnity.gameManagerUnity = gameManagerUnity; avatarUnity.avatar = avatar; } unityAvatars.Add(avatarUnity); return g; } public void RemoveAvatarGameObject(GameObject g) { unityAvatars.Remove(g.GetComponent<AvatarUnity>()); GameObject.Destroy(g); } public GameObject CreateGameObjectFromObject(CWObject cwObject) { GameObject go = null; switch(cwObject.definition.type) { case CWDefinition.DefinitionType.Item: go = CreateItemGameObject((Item) cwObject); break; case CWDefinition.DefinitionType.Tile: go = CreateTileGameObject((DynamicTile) cwObject); break; case CWDefinition.DefinitionType.ItemTile: go = CreateItemTileGameObject((ItemTile) cwObject); break; case CWDefinition.DefinitionType.Avatar: go = CreateAvatarGameObject((CubeWorld.Avatars.Avatar) cwObject); break; default: throw new System.Exception("Unknown game object to create"); } return go; } public void RemoveGameObject(GameObject go) { if (go.GetComponent<ItemUnity>()) RemoveItemGameObject(go); else if (go.GetComponent<TileUnity>()) RemoveTileGameObject(go); else if (go.GetComponent<ItemTileUnity>()) RemoveItemTileGameObject(go); else if (go.GetComponent<AvatarUnity>()) RemoveAvatarGameObject(go); else throw new System.Exception("Unknown game object to destroy"); } public GameObject FindGameObject(CWObject cwObject) { if (createdGO.ContainsKey(cwObject)) return createdGO[cwObject]; return null; } public void CreateObject(CWObject cwobject) { GameObject go = CreateGameObjectFromObject(cwobject); go.transform.position = GraphicsUnity.CubeWorldVector3ToVector3(cwobject.position); createdGO[cwobject] = go; } public void UpdateObject(CWObject cwobject) { } public void DestroyObject(CWObject cwobject) { GameObject go = createdGO[cwobject]; createdGO.Remove(cwobject); RemoveGameObject(go); } }
#region Apache License // // 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. // #endregion using System; using System.Collections; namespace Ctrip.Log4.Util { /// <summary> /// An always empty <see cref="IDictionary"/>. /// </summary> /// <remarks> /// <para> /// A singleton implementation of the <see cref="IDictionary"/> /// interface that always represents an empty collection. /// </para> /// </remarks> /// <author>Nicko Cadell</author> /// <author>Gert Driesen</author> #if !NETCF [Serializable] #endif public sealed class EmptyDictionary : IDictionary { #region Private Instance Constructors /// <summary> /// Initializes a new instance of the <see cref="EmptyDictionary" /> class. /// </summary> /// <remarks> /// <para> /// Uses a private access modifier to enforce the singleton pattern. /// </para> /// </remarks> private EmptyDictionary() { } #endregion Private Instance Constructors #region Public Static Properties /// <summary> /// Gets the singleton instance of the <see cref="EmptyDictionary" />. /// </summary> /// <returns>The singleton instance of the <see cref="EmptyDictionary" />.</returns> /// <remarks> /// <para> /// Gets the singleton instance of the <see cref="EmptyDictionary" />. /// </para> /// </remarks> public static EmptyDictionary Instance { get { return s_instance; } } #endregion Public Static Properties #region Implementation of ICollection /// <summary> /// Copies the elements of the <see cref="ICollection"/> to an /// <see cref="Array"/>, starting at a particular Array index. /// </summary> /// <param name="array">The one-dimensional <see cref="Array"/> /// that is the destination of the elements copied from /// <see cref="ICollection"/>. The Array must have zero-based /// indexing.</param> /// <param name="index">The zero-based index in array at which /// copying begins.</param> /// <remarks> /// <para> /// As the collection is empty no values are copied into the array. /// </para> /// </remarks> public void CopyTo(System.Array array, int index) { // copy nothing } /// <summary> /// Gets a value indicating if access to the <see cref="ICollection"/> is synchronized (thread-safe). /// </summary> /// <value> /// <b>true</b> if access to the <see cref="ICollection"/> is synchronized (thread-safe); otherwise, <b>false</b>. /// </value> /// <remarks> /// <para> /// For the <see cref="EmptyCollection"/> this property is always <b>true</b>. /// </para> /// </remarks> public bool IsSynchronized { get { return true; } } /// <summary> /// Gets the number of elements contained in the <see cref="ICollection"/> /// </summary> /// <value> /// The number of elements contained in the <see cref="ICollection"/>. /// </value> /// <remarks> /// <para> /// As the collection is empty the <see cref="Count"/> is always <c>0</c>. /// </para> /// </remarks> public int Count { get { return 0; } } /// <summary> /// Gets an object that can be used to synchronize access to the <see cref="ICollection"/>. /// </summary> /// <value> /// An object that can be used to synchronize access to the <see cref="ICollection"/>. /// </value> /// <remarks> /// <para> /// As the collection is empty and thread safe and synchronized this instance is also /// the <see cref="SyncRoot"/> object. /// </para> /// </remarks> public object SyncRoot { get { return this; } } #endregion Implementation of ICollection #region Implementation of IEnumerable /// <summary> /// Returns an enumerator that can iterate through a collection. /// </summary> /// <returns> /// An <see cref="IEnumerator"/> that can be used to /// iterate through the collection. /// </returns> /// <remarks> /// <para> /// As the collection is empty a <see cref="NullEnumerator"/> is returned. /// </para> /// </remarks> IEnumerator IEnumerable.GetEnumerator() { return NullEnumerator.Instance; } #endregion Implementation of IEnumerable #region Implementation of IDictionary /// <summary> /// Adds an element with the provided key and value to the /// <see cref="EmptyDictionary" />. /// </summary> /// <param name="key">The <see cref="object" /> to use as the key of the element to add.</param> /// <param name="value">The <see cref="object" /> to use as the value of the element to add.</param> /// <remarks> /// <para> /// As the collection is empty no new values can be added. A <see cref="InvalidOperationException"/> /// is thrown if this method is called. /// </para> /// </remarks> /// <exception cref="InvalidOperationException">This dictionary is always empty and cannot be modified.</exception> public void Add(object key, object value) { throw new InvalidOperationException(); } /// <summary> /// Removes all elements from the <see cref="EmptyDictionary" />. /// </summary> /// <remarks> /// <para> /// As the collection is empty no values can be removed. A <see cref="InvalidOperationException"/> /// is thrown if this method is called. /// </para> /// </remarks> /// <exception cref="InvalidOperationException">This dictionary is always empty and cannot be modified.</exception> public void Clear() { throw new InvalidOperationException(); } /// <summary> /// Determines whether the <see cref="EmptyDictionary" /> contains an element /// with the specified key. /// </summary> /// <param name="key">The key to locate in the <see cref="EmptyDictionary" />.</param> /// <returns><c>false</c></returns> /// <remarks> /// <para> /// As the collection is empty the <see cref="Contains"/> method always returns <c>false</c>. /// </para> /// </remarks> public bool Contains(object key) { return false; } /// <summary> /// Returns an enumerator that can iterate through a collection. /// </summary> /// <returns> /// An <see cref="IEnumerator"/> that can be used to /// iterate through the collection. /// </returns> /// <remarks> /// <para> /// As the collection is empty a <see cref="NullEnumerator"/> is returned. /// </para> /// </remarks> public IDictionaryEnumerator GetEnumerator() { return NullDictionaryEnumerator.Instance; } /// <summary> /// Removes the element with the specified key from the <see cref="EmptyDictionary" />. /// </summary> /// <param name="key">The key of the element to remove.</param> /// <remarks> /// <para> /// As the collection is empty no values can be removed. A <see cref="InvalidOperationException"/> /// is thrown if this method is called. /// </para> /// </remarks> /// <exception cref="InvalidOperationException">This dictionary is always empty and cannot be modified.</exception> public void Remove(object key) { throw new InvalidOperationException(); } /// <summary> /// Gets a value indicating whether the <see cref="EmptyDictionary" /> has a fixed size. /// </summary> /// <value><c>true</c></value> /// <remarks> /// <para> /// As the collection is empty <see cref="IsFixedSize"/> always returns <c>true</c>. /// </para> /// </remarks> public bool IsFixedSize { get { return true; } } /// <summary> /// Gets a value indicating whether the <see cref="EmptyDictionary" /> is read-only. /// </summary> /// <value><c>true</c></value> /// <remarks> /// <para> /// As the collection is empty <see cref="IsReadOnly"/> always returns <c>true</c>. /// </para> /// </remarks> public bool IsReadOnly { get { return true; } } /// <summary> /// Gets an <see cref="ICollection" /> containing the keys of the <see cref="EmptyDictionary" />. /// </summary> /// <value>An <see cref="ICollection" /> containing the keys of the <see cref="EmptyDictionary" />.</value> /// <remarks> /// <para> /// As the collection is empty a <see cref="EmptyCollection"/> is returned. /// </para> /// </remarks> public System.Collections.ICollection Keys { get { return EmptyCollection.Instance; } } /// <summary> /// Gets an <see cref="ICollection" /> containing the values of the <see cref="EmptyDictionary" />. /// </summary> /// <value>An <see cref="ICollection" /> containing the values of the <see cref="EmptyDictionary" />.</value> /// <remarks> /// <para> /// As the collection is empty a <see cref="EmptyCollection"/> is returned. /// </para> /// </remarks> public System.Collections.ICollection Values { get { return EmptyCollection.Instance; } } /// <summary> /// Gets or sets the element with the specified key. /// </summary> /// <param name="key">The key of the element to get or set.</param> /// <value><c>null</c></value> /// <remarks> /// <para> /// As the collection is empty no values can be looked up or stored. /// If the index getter is called then <c>null</c> is returned. /// A <see cref="InvalidOperationException"/> is thrown if the setter is called. /// </para> /// </remarks> /// <exception cref="InvalidOperationException">This dictionary is always empty and cannot be modified.</exception> public object this[object key] { get { return null; } set { throw new InvalidOperationException(); } } #endregion Implementation of IDictionary #region Private Static Fields /// <summary> /// The singleton instance of the empty dictionary. /// </summary> private readonly static EmptyDictionary s_instance = new EmptyDictionary(); #endregion Private Static Fields } }
#if UNITY_EDITOR || RUNTIME_CSG using UnityEngine; using System.Collections; using System.Collections.Generic; using System.Linq; namespace Sabresaurus.SabreCSG { /// <summary> /// Used to manipulate polygon vertices /// </summary> public static class VertexUtility { /// <summary> /// Weld all the specified vertices to their average center. /// </summary> /// <returns>The output polygons after welding has occurred.</returns> /// <param name="sourcePolygons">Source polygons, typically the brush polygons.</param> /// <param name="sourceVertices">Source vertices to weld, typically this should all vertices that share the same position so that all the polygons are updated.</param> public static Polygon[] WeldVerticesToCenter(Polygon[] sourcePolygons, List<Vertex> sourceVertices) { // Picks the average position of the selected vertices and sets all their // positions to that position. Duplicate vertices and polygons are then removed. VertexWeldOperation vertexOperation = new VertexWeldCentroidOperation(sourcePolygons, sourceVertices); return vertexOperation.Execute().ToArray(); } /// <summary> /// Welds all specified vertices within a specific tolerance /// </summary> /// <returns>The nearby vertices.</returns> /// <param name="tolerance">Maximum distance between two vertices that will allow welding.</param> /// <param name="sourcePolygons">Source polygons, typically the brush polygons.</param> /// <param name="sourceVertices">Source vertices to weld, typically this should all vertices that share the same position so that all the polygons are updated.</param> public static Polygon[] WeldNearbyVertices(float tolerance, Polygon[] sourcePolygons, List<Vertex> sourceVertices) { // Takes the selected vertices and welds together any of them that are within the tolerance distance of // other vertices. Duplicate vertices and polygons are then removed. VertexWeldOperation vertexOperation = new VertexWeldToleranceOperation(sourcePolygons, sourceVertices, tolerance); return vertexOperation.Execute().ToArray(); } /// <summary> /// Determines if two index in a given range are contiguous (including wrapping) /// </summary> /// <returns><c>true</c>, if they are neighbours, <c>false</c> otherwise.</returns> /// <param name="index1">Index1.</param> /// <param name="index2">Index2.</param> /// <param name="length">Length.</param> private static bool AreNeighbours(int index1, int index2, int length) { // First check the wrap points if(index1 == length-1 && index2 == 0 || index2 == length-1 && index1 == 0) { return true; } else if(index2-index1 == 1 || index1-index2 == 1) // Now check normally { return true; } else { return false; } } /// <summary> /// Connect the specified vertices, creating new wedges between them (and splitting original polygons) /// </summary> /// <returns>The new polygons.</returns> /// <param name="polygons">Source polygons.</param> /// <param name="sourceVertices">Source vertices that will be connected when they are on a polygon and aren't next to each other.</param> /// <param name="newEdges">New edges created by connecting source vertices.</param> public static Polygon[] ConnectVertices(Polygon[] polygons, List<Vertex> sourceVertices, out List<Edge> newEdges) { List<Polygon> newPolygons = new List<Polygon>(polygons); newEdges = new List<Edge>(); for (int i = 0; i < newPolygons.Count; i++) { // Source vertices on the polygon int matchedIndex1 = -1; int matchedIndex2 = -1; for (int j = 0; j < sourceVertices.Count; j++) { int index = System.Array.IndexOf(newPolygons[i].Vertices, sourceVertices[j]); if(index != -1) { if(matchedIndex1 == -1) { matchedIndex1 = index; } else if(matchedIndex2 == -1) { matchedIndex2 = index; } } } // Check that found two valid points and that they're not neighbours // (neighbouring vertices can't be connected as they already are by an edge) if(matchedIndex1 != -1 && matchedIndex2 != -1 && !AreNeighbours(matchedIndex1, matchedIndex2, newPolygons[i].Vertices.Length)) { // Vertex neighbourVertex = newPolygons[i].Vertices[(matchedIndex1 + 1) % newPolygons[i].Vertices.Length]; // // Vector3 vector1 = newPolygons[i].Vertices[matchedIndex1].Position - neighbourVertex.Position; // Vector3 vector2 = newPolygons[i].Vertices[matchedIndex2].Position - newPolygons[i].Vertices[matchedIndex1].Position; // Vector3 normal = Vector3.Cross(vector1, vector2).normalized; // // Vector3 thirdPoint = newPolygons[i].Vertices[matchedIndex1].Position + normal; Vector3 thirdPoint = newPolygons[i].Vertices[matchedIndex1].Position + newPolygons[i].Plane.normal; // First split the shared polygon Plane splitPlane = new Plane(newPolygons[i].Vertices[matchedIndex1].Position, newPolygons[i].Vertices[matchedIndex2].Position, thirdPoint); Polygon splitPolygon1; Polygon splitPolygon2; Vertex newVertex1; Vertex newVertex2; if(Polygon.SplitPolygon(newPolygons[i], out splitPolygon1, out splitPolygon2, out newVertex1, out newVertex2, splitPlane)) { newPolygons[i] = splitPolygon1; newPolygons.Insert(i+1, splitPolygon2); // Skip over new polygon i++; newEdges.Add(new Edge(newVertex1, newVertex2)); } else { Debug.LogWarning("Split polygon failed"); } } } return newPolygons.ToArray(); } // public static Polygon[] RemoveVertices(Polygon[] polygons, List<Vertex> sourceVertices) // { // List<Polygon> polygonsToAdd = new List<Polygon>(); // // for (int j = 0; j < sourceVertices.Count; j++) // { // // Every time we remove a vertex, track it's neighbours in case we need to generate new polygons // List<Vector3> neighbourVertices = new List<Vector3>(); // // for (int i = 0; i < polygons.Length; i++) // { // List<Vertex> vertices = new List<Vertex>(polygons[i].Vertices); // // for (int k = 0; k < vertices.Count; k++) // { // // If the vertex should be deleted // if(vertices[k].Position.EqualsWithEpsilon(sourceVertices[j].Position)) // { // // Find the neighbours // int previousNeighbour = MathHelper.Wrap(k-1, vertices.Count); // int nextNeighbour = MathHelper.Wrap(k+1, vertices.Count); // // // Track the neighbours // neighbourVertices.Add(vertices[previousNeighbour].Position); // neighbourVertices.Add(vertices[nextNeighbour].Position); // // // Delete the vertex // vertices.RemoveAt(k); // k--; // } // } // // // Update the polygon with the deleted vertices // Vertex[] vertexArray = new Vertex[vertices.Count]; // vertices.CopyTo(vertexArray); // polygons[i].SetVertices(vertexArray); // } // // // If a vertex has been deleted that shared 3 faces //// if(neighbourVertices.Count >= 6) //// { //// // Generate a polygon from the positions, stripping out duplicate positions //// Polygon polygon = PolygonFactory.ConstructPolygon(neighbourVertices, true); //// //// // If we were successful in generating a polygon //// if(polygon != null) //// { //// polygonsToAdd.Add(polygon); //// } //// } // } // // if(polygonsToAdd.Count > 0) // { // // Concat the new polygons into the array // int originalLength = polygons.Length; // System.Array.Resize(ref polygons, originalLength + polygonsToAdd.Count); // polygonsToAdd.CopyTo(polygons, originalLength); // } // // return polygons; // } /// <summary> /// Displace the polygons along their polygon normals by the specified distance, adjusting vertex positions in 3 dimensions so that connected edges are preserved. /// </summary> /// <param name="polygons">Polygons to displace in situ.</param> /// <param name="distance">Distance to displace the polygons.</param> public static void DisplacePolygons(Polygon[] polygons, float distance) { // Used for determining if two vertices are the same Polygon.VertexComparerEpsilon vertexComparer = new Polygon.VertexComparerEpsilon(); // Used for determining if two positions or normals are the same Polygon.Vector3ComparerEpsilon vectorComparer = new Polygon.Vector3ComparerEpsilon(); // Group overlapping positions and also track their normals List<List<Vertex>> groupedVertices = new List<List<Vertex>>(); List<List<Vector3>> groupedNormals = new List<List<Vector3>>(); // Maps back from a vertex to the polygon it came from, used for UV calculation Dictionary<Vertex, Polygon> vertexPolygonMappings = new Dictionary<Vertex, Polygon>(); for (int polygonIndex = 0; polygonIndex < polygons.Length; polygonIndex++) { Vertex[] vertices = polygons[polygonIndex].Vertices; // Group the selected vertices into clusters for (int vertexIndex = 0; vertexIndex < vertices.Length; vertexIndex++) { Vertex sourceVertex = vertices[vertexIndex]; vertexPolygonMappings[sourceVertex] = polygons[polygonIndex]; bool added = false; for (int groupIndex = 0; groupIndex < groupedVertices.Count; groupIndex++) { if(groupedVertices[groupIndex].Contains(sourceVertex, vertexComparer)) { groupedVertices[groupIndex].Add(sourceVertex); // Add the normal of the polygon if it hasn't already been added (this prevents issues with two polygons that are coplanar) if(!groupedNormals[groupIndex].Contains(polygons[polygonIndex].Plane.normal, vectorComparer)) { groupedNormals[groupIndex].Add(polygons[polygonIndex].Plane.normal); } added = true; break; } } if(!added) { groupedVertices.Add(new List<Vertex>() { sourceVertex } ); groupedNormals.Add(new List<Vector3>() { polygons[polygonIndex].Plane.normal } ); } } } List<List<Vector3>> groupedPositions = new List<List<Vector3>>(); List<List<Vector2>> groupedUV = new List<List<Vector2>>(); // Calculate the new positions and UVs, but don't assign them as they must be calculated in one go for (int i = 0; i < groupedVertices.Count; i++) { groupedPositions.Add(new List<Vector3>()); groupedUV.Add(new List<Vector2>()); for (int j = 0; j < groupedVertices[i].Count; j++) { Vector3 position = groupedVertices[i][j].Position; for (int k = 0; k < groupedNormals[i].Count; k++) { position += groupedNormals[i][k] * distance; } Polygon primaryPolygon = vertexPolygonMappings[groupedVertices[i][j]]; Vector2 uv = GeometryHelper.GetUVForPosition(primaryPolygon, position); groupedPositions[i].Add(position); groupedUV[i].Add(uv); } } // Apply the new positions and UVs now that they've all been calculated for (int i = 0; i < groupedVertices.Count; i++) { for (int j = 0; j < groupedVertices[i].Count; j++) { Vertex vertex = groupedVertices[i][j]; vertex.Position = groupedPositions[i][j]; vertex.UV = groupedUV[i][j]; } } // Polygon planes have moved, so recalculate them for (int polygonIndex = 0; polygonIndex < polygons.Length; polygonIndex++) { polygons[polygonIndex].CalculatePlane(); } } /// <summary> /// Translates the specified vertices by a position delta (local to the brush) and updates the UVs /// </summary> /// <param name="brush">Brush from which the vertices belong.</param> /// <param name="specifiedVertices">Specified vertices to be translated.</param> /// <param name="localDelta">Local positional delta.</param> public static void TranslateSpecifiedVertices(Brush brush, List<Vertex> specifiedVertices, Vector3 localDelta) { Polygon.Vector3ComparerEpsilon positionComparer = new Polygon.Vector3ComparerEpsilon(); // Cache the positions as the position of vertices will change while in the for loop List<Vector3> specifiedPositions = specifiedVertices.Select(item => item.Position).ToList(); // So we know which polygons need to have their normals recalculated List<Polygon> affectedPolygons = new List<Polygon>(); Polygon[] polygons = brush.GetPolygons(); for (int i = 0; i < polygons.Length; i++) { Polygon polygon = polygons[i]; int vertexCount = polygon.Vertices.Length; Vector3[] newPositions = new Vector3[vertexCount]; Vector2[] newUV = new Vector2[vertexCount]; for (int j = 0; j < vertexCount; j++) { newPositions[j] = polygon.Vertices[j].Position; newUV[j] = polygon.Vertices[j].UV; } bool polygonAffected = false; for (int j = 0; j < vertexCount; j++) { Vertex vertex = polygon.Vertices[j]; if(specifiedPositions.Contains(vertex.Position, positionComparer)) { Vector3 newPosition = vertex.Position + localDelta; newPositions[j] = newPosition; newUV[j] = GeometryHelper.GetUVForPosition(polygon, newPosition); polygonAffected = true; } } if(polygonAffected) { affectedPolygons.Add(polygon); } // Apply all the changes to the polygon for (int j = 0; j < vertexCount; j++) { Vertex vertex = polygon.Vertices[j]; vertex.Position = newPositions[j]; vertex.UV = newUV[j]; } polygon.CalculatePlane(); } if(affectedPolygons.Count > 0) { for (int i = 0; i < affectedPolygons.Count; i++) { affectedPolygons[i].ResetVertexNormals(); } } } } } #endif
// 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. //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by google-apis-code-generator 1.5.1 // C# generator version: 1.10.0 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ /** * \brief * TaskQueue API Version v1beta1 * * \section ApiInfo API Version Information * <table> * <tr><th>API * <td><a href='https://developers.google.com/appengine/docs/python/taskqueue/rest'>TaskQueue API</a> * <tr><th>API Version<td>v1beta1 * <tr><th>API Rev<td>20141111 (0) * <tr><th>API Docs * <td><a href='https://developers.google.com/appengine/docs/python/taskqueue/rest'> * https://developers.google.com/appengine/docs/python/taskqueue/rest</a> * <tr><th>Discovery Name<td>taskqueue * </table> * * \section ForMoreInfo For More Information * * The complete API documentation for using TaskQueue API can be found at * <a href='https://developers.google.com/appengine/docs/python/taskqueue/rest'>https://developers.google.com/appengine/docs/python/taskqueue/rest</a>. * * For more information about the Google APIs Client Library for .NET, see * <a href='https://developers.google.com/api-client-library/dotnet/get_started'> * https://developers.google.com/api-client-library/dotnet/get_started</a> */ namespace Google.Apis.Taskqueue.v1beta1 { /// <summary>The Taskqueue Service.</summary> public class TaskqueueService : Google.Apis.Services.BaseClientService { /// <summary>The API version.</summary> public const string Version = "v1beta1"; /// <summary>The discovery version used to generate this service.</summary> public static Google.Apis.Discovery.DiscoveryVersion DiscoveryVersionUsed = Google.Apis.Discovery.DiscoveryVersion.Version_1_0; /// <summary>Constructs a new service.</summary> public TaskqueueService() : this(new Google.Apis.Services.BaseClientService.Initializer()) {} /// <summary>Constructs a new service.</summary> /// <param name="initializer">The service initializer.</param> public TaskqueueService(Google.Apis.Services.BaseClientService.Initializer initializer) : base(initializer) { taskqueues = new TaskqueuesResource(this); tasks = new TasksResource(this); } /// <summary>Gets the service supported features.</summary> public override System.Collections.Generic.IList<string> Features { get { return new string[0]; } } /// <summary>Gets the service name.</summary> public override string Name { get { return "taskqueue"; } } /// <summary>Gets the service base URI.</summary> public override string BaseUri { get { return "https://www.googleapis.com/taskqueue/v1beta1/projects/"; } } /// <summary>Gets the service base path.</summary> public override string BasePath { get { return "taskqueue/v1beta1/projects/"; } } /// <summary>Available OAuth 2.0 scopes for use with the TaskQueue API.</summary> public class Scope { /// <summary>Manage your Tasks and Taskqueues</summary> public static string Taskqueue = "https://www.googleapis.com/auth/taskqueue"; /// <summary>Consume Tasks from your Taskqueues</summary> public static string TaskqueueConsumer = "https://www.googleapis.com/auth/taskqueue.consumer"; } private readonly TaskqueuesResource taskqueues; /// <summary>Gets the Taskqueues resource.</summary> public virtual TaskqueuesResource Taskqueues { get { return taskqueues; } } private readonly TasksResource tasks; /// <summary>Gets the Tasks resource.</summary> public virtual TasksResource Tasks { get { return tasks; } } } ///<summary>A base abstract class for Taskqueue requests.</summary> public abstract class TaskqueueBaseServiceRequest<TResponse> : Google.Apis.Requests.ClientServiceRequest<TResponse> { ///<summary>Constructs a new TaskqueueBaseServiceRequest instance.</summary> protected TaskqueueBaseServiceRequest(Google.Apis.Services.IClientService service) : base(service) { } /// <summary>Data format for the response.</summary> /// [default: json] [Google.Apis.Util.RequestParameterAttribute("alt", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<AltEnum> Alt { get; set; } /// <summary>Data format for the response.</summary> public enum AltEnum { /// <summary>Responses with Content-Type of application/json</summary> [Google.Apis.Util.StringValueAttribute("json")] Json, } /// <summary>Selector specifying which fields to include in a partial response.</summary> [Google.Apis.Util.RequestParameterAttribute("fields", Google.Apis.Util.RequestParameterType.Query)] public virtual string Fields { get; set; } /// <summary>API key. Your API key identifies your project and provides you with API access, quota, and reports. /// Required unless you provide an OAuth 2.0 token.</summary> [Google.Apis.Util.RequestParameterAttribute("key", Google.Apis.Util.RequestParameterType.Query)] public virtual string Key { get; set; } /// <summary>OAuth 2.0 token for the current user.</summary> [Google.Apis.Util.RequestParameterAttribute("oauth_token", Google.Apis.Util.RequestParameterType.Query)] public virtual string OauthToken { get; set; } /// <summary>Returns response with indentations and line breaks.</summary> /// [default: true] [Google.Apis.Util.RequestParameterAttribute("prettyPrint", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<bool> PrettyPrint { get; set; } /// <summary>Available to use for quota purposes for server-side applications. Can be any arbitrary string /// assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided.</summary> [Google.Apis.Util.RequestParameterAttribute("quotaUser", Google.Apis.Util.RequestParameterType.Query)] public virtual string QuotaUser { get; set; } /// <summary>IP address of the site where the request originates. Use this if you want to enforce per-user /// limits.</summary> [Google.Apis.Util.RequestParameterAttribute("userIp", Google.Apis.Util.RequestParameterType.Query)] public virtual string UserIp { get; set; } /// <summary>Initializes Taskqueue parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "alt", new Google.Apis.Discovery.Parameter { Name = "alt", IsRequired = false, ParameterType = "query", DefaultValue = "json", Pattern = null, }); RequestParameters.Add( "fields", new Google.Apis.Discovery.Parameter { Name = "fields", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "key", new Google.Apis.Discovery.Parameter { Name = "key", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "oauth_token", new Google.Apis.Discovery.Parameter { Name = "oauth_token", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "prettyPrint", new Google.Apis.Discovery.Parameter { Name = "prettyPrint", IsRequired = false, ParameterType = "query", DefaultValue = "true", Pattern = null, }); RequestParameters.Add( "quotaUser", new Google.Apis.Discovery.Parameter { Name = "quotaUser", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "userIp", new Google.Apis.Discovery.Parameter { Name = "userIp", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } /// <summary>The "taskqueues" collection of methods.</summary> public class TaskqueuesResource { private const string Resource = "taskqueues"; /// <summary>The service which this resource belongs to.</summary> private readonly Google.Apis.Services.IClientService service; /// <summary>Constructs a new resource.</summary> public TaskqueuesResource(Google.Apis.Services.IClientService service) { this.service = service; } /// <summary>Get detailed information about a TaskQueue.</summary> /// <param name="project">The project under which the queue lies.</param> /// <param name="taskqueue">The id of the /// taskqueue to get the properties of.</param> public virtual GetRequest Get(string project, string taskqueue) { return new GetRequest(service, project, taskqueue); } /// <summary>Get detailed information about a TaskQueue.</summary> public class GetRequest : TaskqueueBaseServiceRequest<Google.Apis.Taskqueue.v1beta1.Data.TaskQueue> { /// <summary>Constructs a new Get request.</summary> public GetRequest(Google.Apis.Services.IClientService service, string project, string taskqueue) : base(service) { Project = project; Taskqueue = taskqueue; InitParameters(); } /// <summary>The project under which the queue lies.</summary> [Google.Apis.Util.RequestParameterAttribute("project", Google.Apis.Util.RequestParameterType.Path)] public virtual string Project { get; private set; } /// <summary>The id of the taskqueue to get the properties of.</summary> [Google.Apis.Util.RequestParameterAttribute("taskqueue", Google.Apis.Util.RequestParameterType.Path)] public virtual string Taskqueue { get; private set; } /// <summary>Whether to get stats. Optional.</summary> [Google.Apis.Util.RequestParameterAttribute("getStats", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<bool> GetStats { get; set; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "get"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "GET"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "{project}/taskqueues/{taskqueue}"; } } /// <summary>Initializes Get parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "project", new Google.Apis.Discovery.Parameter { Name = "project", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "taskqueue", new Google.Apis.Discovery.Parameter { Name = "taskqueue", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "getStats", new Google.Apis.Discovery.Parameter { Name = "getStats", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } } /// <summary>The "tasks" collection of methods.</summary> public class TasksResource { private const string Resource = "tasks"; /// <summary>The service which this resource belongs to.</summary> private readonly Google.Apis.Services.IClientService service; /// <summary>Constructs a new resource.</summary> public TasksResource(Google.Apis.Services.IClientService service) { this.service = service; } /// <summary>Delete a task from a TaskQueue.</summary> /// <param name="project">The project under which the queue lies.</param> /// <param name="taskqueue">The taskqueue /// to delete a task from.</param> /// <param name="task">The id of the task to delete.</param> public virtual DeleteRequest Delete(string project, string taskqueue, string task) { return new DeleteRequest(service, project, taskqueue, task); } /// <summary>Delete a task from a TaskQueue.</summary> public class DeleteRequest : TaskqueueBaseServiceRequest<string> { /// <summary>Constructs a new Delete request.</summary> public DeleteRequest(Google.Apis.Services.IClientService service, string project, string taskqueue, string task) : base(service) { Project = project; Taskqueue = taskqueue; Task = task; InitParameters(); } /// <summary>The project under which the queue lies.</summary> [Google.Apis.Util.RequestParameterAttribute("project", Google.Apis.Util.RequestParameterType.Path)] public virtual string Project { get; private set; } /// <summary>The taskqueue to delete a task from.</summary> [Google.Apis.Util.RequestParameterAttribute("taskqueue", Google.Apis.Util.RequestParameterType.Path)] public virtual string Taskqueue { get; private set; } /// <summary>The id of the task to delete.</summary> [Google.Apis.Util.RequestParameterAttribute("task", Google.Apis.Util.RequestParameterType.Path)] public virtual string Task { get; private set; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "delete"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "DELETE"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "{project}/taskqueues/{taskqueue}/tasks/{task}"; } } /// <summary>Initializes Delete parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "project", new Google.Apis.Discovery.Parameter { Name = "project", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "taskqueue", new Google.Apis.Discovery.Parameter { Name = "taskqueue", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "task", new Google.Apis.Discovery.Parameter { Name = "task", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); } } /// <summary>Get a particular task from a TaskQueue.</summary> /// <param name="project">The project under which the queue lies.</param> /// <param name="taskqueue">The taskqueue /// in which the task belongs.</param> /// <param name="task">The task to get properties of.</param> public virtual GetRequest Get(string project, string taskqueue, string task) { return new GetRequest(service, project, taskqueue, task); } /// <summary>Get a particular task from a TaskQueue.</summary> public class GetRequest : TaskqueueBaseServiceRequest<Google.Apis.Taskqueue.v1beta1.Data.Task> { /// <summary>Constructs a new Get request.</summary> public GetRequest(Google.Apis.Services.IClientService service, string project, string taskqueue, string task) : base(service) { Project = project; Taskqueue = taskqueue; Task = task; InitParameters(); } /// <summary>The project under which the queue lies.</summary> [Google.Apis.Util.RequestParameterAttribute("project", Google.Apis.Util.RequestParameterType.Path)] public virtual string Project { get; private set; } /// <summary>The taskqueue in which the task belongs.</summary> [Google.Apis.Util.RequestParameterAttribute("taskqueue", Google.Apis.Util.RequestParameterType.Path)] public virtual string Taskqueue { get; private set; } /// <summary>The task to get properties of.</summary> [Google.Apis.Util.RequestParameterAttribute("task", Google.Apis.Util.RequestParameterType.Path)] public virtual string Task { get; private set; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "get"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "GET"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "{project}/taskqueues/{taskqueue}/tasks/{task}"; } } /// <summary>Initializes Get parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "project", new Google.Apis.Discovery.Parameter { Name = "project", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "taskqueue", new Google.Apis.Discovery.Parameter { Name = "taskqueue", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "task", new Google.Apis.Discovery.Parameter { Name = "task", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); } } /// <summary>Lease 1 or more tasks from a TaskQueue.</summary> /// <param name="project">The project under which the queue lies.</param> /// <param name="taskqueue">The taskqueue /// to lease a task from.</param> /// <param name="numTasks">The number of tasks to lease.</param> /// <param /// name="leaseSecs">The lease in seconds.</param> public virtual LeaseRequest Lease(string project, string taskqueue, int numTasks, int leaseSecs) { return new LeaseRequest(service, project, taskqueue, numTasks, leaseSecs); } /// <summary>Lease 1 or more tasks from a TaskQueue.</summary> public class LeaseRequest : TaskqueueBaseServiceRequest<Google.Apis.Taskqueue.v1beta1.Data.Tasks> { /// <summary>Constructs a new Lease request.</summary> public LeaseRequest(Google.Apis.Services.IClientService service, string project, string taskqueue, int numTasks, int leaseSecs) : base(service) { Project = project; Taskqueue = taskqueue; NumTasks = numTasks; LeaseSecs = leaseSecs; InitParameters(); } /// <summary>The project under which the queue lies.</summary> [Google.Apis.Util.RequestParameterAttribute("project", Google.Apis.Util.RequestParameterType.Path)] public virtual string Project { get; private set; } /// <summary>The taskqueue to lease a task from.</summary> [Google.Apis.Util.RequestParameterAttribute("taskqueue", Google.Apis.Util.RequestParameterType.Path)] public virtual string Taskqueue { get; private set; } /// <summary>The number of tasks to lease.</summary> [Google.Apis.Util.RequestParameterAttribute("numTasks", Google.Apis.Util.RequestParameterType.Query)] public virtual int NumTasks { get; private set; } /// <summary>The lease in seconds.</summary> [Google.Apis.Util.RequestParameterAttribute("leaseSecs", Google.Apis.Util.RequestParameterType.Query)] public virtual int LeaseSecs { get; private set; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "lease"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "POST"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "{project}/taskqueues/{taskqueue}/tasks/lease"; } } /// <summary>Initializes Lease parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "project", new Google.Apis.Discovery.Parameter { Name = "project", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "taskqueue", new Google.Apis.Discovery.Parameter { Name = "taskqueue", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "numTasks", new Google.Apis.Discovery.Parameter { Name = "numTasks", IsRequired = true, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "leaseSecs", new Google.Apis.Discovery.Parameter { Name = "leaseSecs", IsRequired = true, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } /// <summary>List Tasks in a TaskQueue</summary> /// <param name="project">The project under which the queue lies.</param> /// <param name="taskqueue">The id of the /// taskqueue to list tasks from.</param> public virtual ListRequest List(string project, string taskqueue) { return new ListRequest(service, project, taskqueue); } /// <summary>List Tasks in a TaskQueue</summary> public class ListRequest : TaskqueueBaseServiceRequest<Google.Apis.Taskqueue.v1beta1.Data.Tasks2> { /// <summary>Constructs a new List request.</summary> public ListRequest(Google.Apis.Services.IClientService service, string project, string taskqueue) : base(service) { Project = project; Taskqueue = taskqueue; InitParameters(); } /// <summary>The project under which the queue lies.</summary> [Google.Apis.Util.RequestParameterAttribute("project", Google.Apis.Util.RequestParameterType.Path)] public virtual string Project { get; private set; } /// <summary>The id of the taskqueue to list tasks from.</summary> [Google.Apis.Util.RequestParameterAttribute("taskqueue", Google.Apis.Util.RequestParameterType.Path)] public virtual string Taskqueue { get; private set; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "list"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "GET"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "{project}/taskqueues/{taskqueue}/tasks"; } } /// <summary>Initializes List parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "project", new Google.Apis.Discovery.Parameter { Name = "project", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "taskqueue", new Google.Apis.Discovery.Parameter { Name = "taskqueue", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); } } } } namespace Google.Apis.Taskqueue.v1beta1.Data { public class Task : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Time (in seconds since the epoch) at which the task was enqueued.</summary> [Newtonsoft.Json.JsonPropertyAttribute("enqueueTimestamp")] public virtual System.Nullable<long> EnqueueTimestamp { get; set; } /// <summary>Name of the task.</summary> [Newtonsoft.Json.JsonPropertyAttribute("id")] public virtual string Id { get; set; } /// <summary>The kind of object returned, in this case set to task.</summary> [Newtonsoft.Json.JsonPropertyAttribute("kind")] public virtual string Kind { get; set; } /// <summary>Time (in seconds since the epoch) at which the task lease will expire. This value is 0 if the task /// isnt currently leased out to a worker.</summary> [Newtonsoft.Json.JsonPropertyAttribute("leaseTimestamp")] public virtual System.Nullable<long> LeaseTimestamp { get; set; } /// <summary>A bag of bytes which is the task payload. The payload on the JSON side is always Base64 /// encoded.</summary> [Newtonsoft.Json.JsonPropertyAttribute("payloadBase64")] public virtual string PayloadBase64 { get; set; } /// <summary>Name of the queue that the task is in.</summary> [Newtonsoft.Json.JsonPropertyAttribute("queueName")] public virtual string QueueName { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } public class TaskQueue : Google.Apis.Requests.IDirectResponseSchema { /// <summary>ACLs that are applicable to this TaskQueue object.</summary> [Newtonsoft.Json.JsonPropertyAttribute("acl")] public virtual TaskQueue.AclData Acl { get; set; } /// <summary>Name of the taskqueue.</summary> [Newtonsoft.Json.JsonPropertyAttribute("id")] public virtual string Id { get; set; } /// <summary>The kind of REST object returned, in this case taskqueue.</summary> [Newtonsoft.Json.JsonPropertyAttribute("kind")] public virtual string Kind { get; set; } /// <summary>The number of times we should lease out tasks before giving up on them. If unset we lease them out /// forever until a worker deletes the task.</summary> [Newtonsoft.Json.JsonPropertyAttribute("maxLeases")] public virtual System.Nullable<int> MaxLeases { get; set; } /// <summary>Statistics for the TaskQueue object in question.</summary> [Newtonsoft.Json.JsonPropertyAttribute("stats")] public virtual TaskQueue.StatsData Stats { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } /// <summary>ACLs that are applicable to this TaskQueue object.</summary> public class AclData { /// <summary>Email addresses of users who are "admins" of the TaskQueue. This means they can control the /// queue, eg set ACLs for the queue.</summary> [Newtonsoft.Json.JsonPropertyAttribute("adminEmails")] public virtual System.Collections.Generic.IList<string> AdminEmails { get; set; } /// <summary>Email addresses of users who can "consume" tasks from the TaskQueue. This means they can /// Dequeue and Delete tasks from the queue.</summary> [Newtonsoft.Json.JsonPropertyAttribute("consumerEmails")] public virtual System.Collections.Generic.IList<string> ConsumerEmails { get; set; } /// <summary>Email addresses of users who can "produce" tasks into the TaskQueue. This means they can Insert /// tasks into the queue.</summary> [Newtonsoft.Json.JsonPropertyAttribute("producerEmails")] public virtual System.Collections.Generic.IList<string> ProducerEmails { get; set; } } /// <summary>Statistics for the TaskQueue object in question.</summary> public class StatsData { /// <summary>Number of tasks leased in the last hour.</summary> [Newtonsoft.Json.JsonPropertyAttribute("leasedLastHour")] public virtual System.Nullable<long> LeasedLastHour { get; set; } /// <summary>Number of tasks leased in the last minute.</summary> [Newtonsoft.Json.JsonPropertyAttribute("leasedLastMinute")] public virtual System.Nullable<long> LeasedLastMinute { get; set; } /// <summary>The timestamp (in seconds since the epoch) of the oldest unfinished task.</summary> [Newtonsoft.Json.JsonPropertyAttribute("oldestTask")] public virtual System.Nullable<long> OldestTask { get; set; } /// <summary>Number of tasks in the queue.</summary> [Newtonsoft.Json.JsonPropertyAttribute("totalTasks")] public virtual System.Nullable<int> TotalTasks { get; set; } } } public class Tasks : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The actual list of tasks returned as a result of the lease operation.</summary> [Newtonsoft.Json.JsonPropertyAttribute("items")] public virtual System.Collections.Generic.IList<Task> Items { get; set; } /// <summary>The kind of object returned, a list of tasks.</summary> [Newtonsoft.Json.JsonPropertyAttribute("kind")] public virtual string Kind { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } public class Tasks2 : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The actual list of tasks currently active in the TaskQueue.</summary> [Newtonsoft.Json.JsonPropertyAttribute("items")] public virtual System.Collections.Generic.IList<Task> Items { get; set; } /// <summary>The kind of object returned, a list of tasks.</summary> [Newtonsoft.Json.JsonPropertyAttribute("kind")] public virtual string Kind { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Linq; using Xunit; namespace System.Collections.Immutable.Tests { public abstract class ImmutableDictionaryTestBase : ImmutablesTestBase { [Fact] public virtual void EmptyTest() { this.EmptyTestHelper(Empty<int, bool>(), 5); } [Fact] public void EnumeratorTest() { this.EnumeratorTestHelper(this.Empty<int, GenericParameterHelper>()); } [Fact] public void ContainsTest() { this.ContainsTestHelper(Empty<int, string>(), 5, "foo"); } [Fact] public void RemoveTest() { this.RemoveTestHelper(Empty<int, GenericParameterHelper>(), 5); } [Fact] public void KeysTest() { this.KeysTestHelper(Empty<int, bool>(), 5); } [Fact] public void ValuesTest() { this.ValuesTestHelper(Empty<int, bool>(), 5); } [Fact] public void AddAscendingTest() { this.AddAscendingTestHelper(Empty<int, GenericParameterHelper>()); } [Fact] public void AddRangeTest() { var map = Empty<int, GenericParameterHelper>(); map = map.AddRange(Enumerable.Range(1, 100).Select(n => new KeyValuePair<int, GenericParameterHelper>(n, new GenericParameterHelper()))); CollectionAssertAreEquivalent(map.Select(kv => kv.Key).ToList(), Enumerable.Range(1, 100).ToList()); this.VerifyAvlTreeState(map); Assert.Equal(100, map.Count); // Test optimization for empty map. var map2 = Empty<int, GenericParameterHelper>(); var jointMap = map2.AddRange(map); Assert.Same(map, jointMap); jointMap = map2.AddRange(map.ToReadOnlyDictionary()); Assert.Same(map, jointMap); jointMap = map2.AddRange(map.ToBuilder()); Assert.Same(map, jointMap); } [Fact] public void AddDescendingTest() { this.AddDescendingTestHelper(Empty<int, GenericParameterHelper>()); } [Fact] public void AddRemoveRandomDataTest() { this.AddRemoveRandomDataTestHelper(Empty<double, GenericParameterHelper>()); } [Fact] public void AddRemoveEnumerableTest() { this.AddRemoveEnumerableTestHelper(Empty<int, int>()); } [Fact] public void SetItemTest() { var map = this.Empty<string, int>() .SetItem("Microsoft", 100) .SetItem("Corporation", 50); Assert.Equal(2, map.Count); map = map.SetItem("Microsoft", 200); Assert.Equal(2, map.Count); Assert.Equal(200, map["Microsoft"]); // Set it to the same thing again and make sure it's all good. var sameMap = map.SetItem("Microsoft", 200); Assert.Same(map, sameMap); } [Fact] public void SetItemsTest() { var template = new Dictionary<string, int> { { "Microsoft", 100 }, { "Corporation", 50 }, }; var map = this.Empty<string, int>().SetItems(template); Assert.Equal(2, map.Count); var changes = new Dictionary<string, int> { { "Microsoft", 150 }, { "Dogs", 90 }, }; map = map.SetItems(changes); Assert.Equal(3, map.Count); Assert.Equal(150, map["Microsoft"]); Assert.Equal(50, map["Corporation"]); Assert.Equal(90, map["Dogs"]); map = map.SetItems( new[] { new KeyValuePair<string, int>("Microsoft", 80), new KeyValuePair<string, int>("Microsoft", 70), }); Assert.Equal(3, map.Count); Assert.Equal(70, map["Microsoft"]); Assert.Equal(50, map["Corporation"]); Assert.Equal(90, map["Dogs"]); map = this.Empty<string, int>().SetItems(new[] { // use an array for code coverage new KeyValuePair<string, int>("a", 1), new KeyValuePair<string, int>("b", 2), new KeyValuePair<string, int>("a", 3), }); Assert.Equal(2, map.Count); Assert.Equal(3, map["a"]); Assert.Equal(2, map["b"]); } [Fact] public void ContainsKeyTest() { this.ContainsKeyTestHelper(Empty<int, GenericParameterHelper>(), 1, new GenericParameterHelper()); } [Fact] public void IndexGetNonExistingKeyThrowsTest() { Assert.Throws<KeyNotFoundException>(() => this.Empty<int, int>()[3]); } [Fact] public void IndexGetTest() { var map = this.Empty<int, int>().Add(3, 5); Assert.Equal(5, map[3]); } [Fact] public void DictionaryRemoveThrowsTest() { IDictionary<int, int> map = this.Empty<int, int>().Add(5, 3).ToReadOnlyDictionary(); Assert.Throws<NotSupportedException>(() => map.Remove(5)); } [Fact] public void DictionaryAddThrowsTest() { IDictionary<int, int> map = this.Empty<int, int>().ToReadOnlyDictionary(); Assert.Throws<NotSupportedException>(() => map.Add(5, 3)); } [Fact] public void DictionaryIndexSetThrowsTest() { IDictionary<int, int> map = this.Empty<int, int>().ToReadOnlyDictionary(); Assert.Throws<NotSupportedException>(() => map[3] = 5); } [Fact] public void EqualsTest() { Assert.False(Empty<int, int>().Equals(null)); Assert.False(Empty<int, int>().Equals("hi")); Assert.True(Empty<int, int>().Equals(Empty<int, int>())); Assert.False(Empty<int, int>().Add(3, 2).Equals(Empty<int, int>().Add(3, 2))); Assert.False(Empty<int, int>().Add(3, 2).Equals(Empty<int, int>().Add(3, 1))); Assert.False(Empty<int, int>().Add(5, 1).Equals(Empty<int, int>().Add(3, 1))); Assert.False(Empty<int, int>().Add(3, 1).Add(5, 1).Equals(Empty<int, int>().Add(3, 1))); Assert.False(Empty<int, int>().Add(3, 1).Equals(Empty<int, int>().Add(3, 1).Add(5, 1))); Assert.True(Empty<int, int>().ToReadOnlyDictionary().Equals(Empty<int, int>())); Assert.True(Empty<int, int>().Equals(Empty<int, int>().ToReadOnlyDictionary())); Assert.True(Empty<int, int>().ToReadOnlyDictionary().Equals(Empty<int, int>().ToReadOnlyDictionary())); Assert.False(Empty<int, int>().Add(3, 1).ToReadOnlyDictionary().Equals(Empty<int, int>())); Assert.False(Empty<int, int>().Equals(Empty<int, int>().Add(3, 1).ToReadOnlyDictionary())); Assert.False(Empty<int, int>().ToReadOnlyDictionary().Equals(Empty<int, int>().Add(3, 1).ToReadOnlyDictionary())); } /// <summary> /// Verifies that the GetHashCode method returns the standard one. /// </summary> [Fact] public void GetHashCodeTest() { var dictionary = Empty<string, int>(); Assert.Equal(EqualityComparer<object>.Default.GetHashCode(dictionary), dictionary.GetHashCode()); } [Fact] public void ICollectionOfKVMembers() { var dictionary = (ICollection<KeyValuePair<string, int>>)Empty<string, int>(); Assert.Throws<NotSupportedException>(() => dictionary.Add(new KeyValuePair<string, int>())); Assert.Throws<NotSupportedException>(() => dictionary.Remove(new KeyValuePair<string, int>())); Assert.Throws<NotSupportedException>(() => dictionary.Clear()); Assert.True(dictionary.IsReadOnly); } [Fact] public void ICollectionMembers() { ((ICollection)Empty<string, int>()).CopyTo(new object[0], 0); var dictionary = (ICollection)Empty<string, int>().Add("a", 1); Assert.True(dictionary.IsSynchronized); Assert.NotNull(dictionary.SyncRoot); Assert.Same(dictionary.SyncRoot, dictionary.SyncRoot); var array = new object[2]; dictionary.CopyTo(array, 1); Assert.Null(array[0]); Assert.Equal(new DictionaryEntry("a", 1), (DictionaryEntry)array[1]); } [Fact] public void IDictionaryOfKVMembers() { var dictionary = (IDictionary<string, int>)Empty<string, int>().Add("c", 3); Assert.Throws<NotSupportedException>(() => dictionary.Add("a", 1)); Assert.Throws<NotSupportedException>(() => dictionary.Remove("a")); Assert.Throws<NotSupportedException>(() => dictionary["a"] = 2); Assert.Throws<KeyNotFoundException>(() => dictionary["a"]); Assert.Equal(3, dictionary["c"]); } [Fact] public void IDictionaryMembers() { var dictionary = (IDictionary)Empty<string, int>().Add("c", 3); Assert.Throws<NotSupportedException>(() => dictionary.Add("a", 1)); Assert.Throws<NotSupportedException>(() => dictionary.Remove("a")); Assert.Throws<NotSupportedException>(() => dictionary["a"] = 2); Assert.Throws<NotSupportedException>(() => dictionary.Clear()); Assert.False(dictionary.Contains("a")); Assert.True(dictionary.Contains("c")); Assert.Throws<KeyNotFoundException>(() => dictionary["a"]); Assert.Equal(3, dictionary["c"]); Assert.True(dictionary.IsFixedSize); Assert.True(dictionary.IsReadOnly); Assert.Equal(new[] { "c" }, dictionary.Keys.Cast<string>().ToArray()); Assert.Equal(new[] { 3 }, dictionary.Values.Cast<int>().ToArray()); } [Fact] public void IDictionaryEnumerator() { var dictionary = (IDictionary)Empty<string, int>().Add("a", 1); var enumerator = dictionary.GetEnumerator(); Assert.Throws<InvalidOperationException>(() => enumerator.Current); Assert.Throws<InvalidOperationException>(() => enumerator.Key); Assert.Throws<InvalidOperationException>(() => enumerator.Value); Assert.Throws<InvalidOperationException>(() => enumerator.Entry); Assert.True(enumerator.MoveNext()); Assert.Equal(enumerator.Entry, enumerator.Current); Assert.Equal(enumerator.Key, enumerator.Entry.Key); Assert.Equal(enumerator.Value, enumerator.Entry.Value); Assert.Equal("a", enumerator.Key); Assert.Equal(1, enumerator.Value); Assert.False(enumerator.MoveNext()); Assert.Throws<InvalidOperationException>(() => enumerator.Current); Assert.Throws<InvalidOperationException>(() => enumerator.Key); Assert.Throws<InvalidOperationException>(() => enumerator.Value); Assert.Throws<InvalidOperationException>(() => enumerator.Entry); Assert.False(enumerator.MoveNext()); enumerator.Reset(); Assert.Throws<InvalidOperationException>(() => enumerator.Current); Assert.Throws<InvalidOperationException>(() => enumerator.Key); Assert.Throws<InvalidOperationException>(() => enumerator.Value); Assert.Throws<InvalidOperationException>(() => enumerator.Entry); Assert.True(enumerator.MoveNext()); Assert.Equal(enumerator.Key, ((DictionaryEntry)enumerator.Current).Key); Assert.Equal(enumerator.Value, ((DictionaryEntry)enumerator.Current).Value); Assert.Equal("a", enumerator.Key); Assert.Equal(1, enumerator.Value); Assert.False(enumerator.MoveNext()); Assert.Throws<InvalidOperationException>(() => enumerator.Current); Assert.Throws<InvalidOperationException>(() => enumerator.Key); Assert.Throws<InvalidOperationException>(() => enumerator.Value); Assert.Throws<InvalidOperationException>(() => enumerator.Entry); Assert.False(enumerator.MoveNext()); } [Fact] public void TryGetKey() { var dictionary = Empty<int>(StringComparer.OrdinalIgnoreCase) .Add("a", 1); string actualKey; Assert.True(dictionary.TryGetKey("a", out actualKey)); Assert.Equal("a", actualKey); Assert.True(dictionary.TryGetKey("A", out actualKey)); Assert.Equal("a", actualKey); Assert.False(dictionary.TryGetKey("b", out actualKey)); Assert.Equal("b", actualKey); } protected void EmptyTestHelper<K, V>(IImmutableDictionary<K, V> empty, K someKey) { Assert.Same(empty, empty.Clear()); Assert.Equal(0, empty.Count); Assert.Equal(0, empty.Count()); Assert.Equal(0, empty.Keys.Count()); Assert.Equal(0, empty.Values.Count()); Assert.Same(EqualityComparer<V>.Default, GetValueComparer(empty)); Assert.False(empty.ContainsKey(someKey)); Assert.False(empty.Contains(new KeyValuePair<K, V>(someKey, default(V)))); Assert.Equal(default(V), empty.GetValueOrDefault(someKey)); V value; Assert.False(empty.TryGetValue(someKey, out value)); Assert.Equal(default(V), value); } private IImmutableDictionary<TKey, TValue> AddTestHelper<TKey, TValue>(IImmutableDictionary<TKey, TValue> map, TKey key, TValue value) where TKey : IComparable<TKey> { Assert.NotNull(map); Assert.NotNull(key); IImmutableDictionary<TKey, TValue> addedMap = map.Add(key, value); Assert.NotSame(map, addedMap); ////Assert.Equal(map.Count + 1, addedMap.Count); Assert.False(map.ContainsKey(key)); Assert.True(addedMap.ContainsKey(key)); AssertAreSame(value, addedMap.GetValueOrDefault(key)); this.VerifyAvlTreeState(addedMap); return addedMap; } protected void AddAscendingTestHelper(IImmutableDictionary<int, GenericParameterHelper> map) { Assert.NotNull(map); for (int i = 0; i < 10; i++) { map = this.AddTestHelper(map, i, new GenericParameterHelper(i)); } Assert.Equal(10, map.Count); for (int i = 0; i < 10; i++) { Assert.True(map.ContainsKey(i)); } } protected void AddDescendingTestHelper(IImmutableDictionary<int, GenericParameterHelper> map) { for (int i = 10; i > 0; i--) { map = this.AddTestHelper(map, i, new GenericParameterHelper(i)); } Assert.Equal(10, map.Count); for (int i = 10; i > 0; i--) { Assert.True(map.ContainsKey(i)); } } protected void AddRemoveRandomDataTestHelper(IImmutableDictionary<double, GenericParameterHelper> map) { Assert.NotNull(map); double[] inputs = GenerateDummyFillData(); for (int i = 0; i < inputs.Length; i++) { map = this.AddTestHelper(map, inputs[i], new GenericParameterHelper()); } Assert.Equal(inputs.Length, map.Count); for (int i = 0; i < inputs.Length; i++) { Assert.True(map.ContainsKey(inputs[i])); } for (int i = 0; i < inputs.Length; i++) { map = map.Remove(inputs[i]); this.VerifyAvlTreeState(map); } Assert.Equal(0, map.Count); } protected void AddRemoveEnumerableTestHelper(IImmutableDictionary<int, int> empty) { Assert.NotNull(empty); Assert.Same(empty, empty.RemoveRange(Enumerable.Empty<int>())); Assert.Same(empty, empty.AddRange(Enumerable.Empty<KeyValuePair<int, int>>())); var list = new List<KeyValuePair<int, int>> { new KeyValuePair<int, int>(3, 5), new KeyValuePair<int, int>(8, 10) }; var nonEmpty = empty.AddRange(list); this.VerifyAvlTreeState(nonEmpty); var halfRemoved = nonEmpty.RemoveRange(Enumerable.Range(1, 5)); Assert.Equal(1, halfRemoved.Count); Assert.True(halfRemoved.ContainsKey(8)); this.VerifyAvlTreeState(halfRemoved); } protected void AddExistingKeySameValueTestHelper<TKey, TValue>(IImmutableDictionary<TKey, TValue> map, TKey key, TValue value1, TValue value2) { Assert.NotNull(map); Assert.NotNull(key); Assert.True(GetValueComparer(map).Equals(value1, value2)); map = map.Add(key, value1); Assert.Same(map, map.Add(key, value2)); Assert.Same(map, map.AddRange(new[] { new KeyValuePair<TKey, TValue>(key, value2) })); } /// <summary> /// Verifies that adding a key-value pair where the key already is in the map but with a different value throws. /// </summary> /// <typeparam name="TKey">The type of key in the map.</typeparam> /// <typeparam name="TValue">The type of value in the map.</typeparam> /// <param name="map">The map to manipulate.</param> /// <param name="key">The key to add.</param> /// <param name="value1">The first value to add.</param> /// <param name="value2">The second value to add.</param> /// <remarks> /// Adding a key-value pair to a map where that key already exists, but with a different value, cannot fit the /// semantic of "adding", either by just returning or mutating the value on the existing key. Throwing is the only reasonable response. /// </remarks> protected void AddExistingKeyDifferentValueTestHelper<TKey, TValue>(IImmutableDictionary<TKey, TValue> map, TKey key, TValue value1, TValue value2) { Assert.NotNull(map); Assert.NotNull(key); Assert.False(GetValueComparer(map).Equals(value1, value2)); var map1 = map.Add(key, value1); var map2 = map.Add(key, value2); Assert.Throws<ArgumentException>(null, () => map1.Add(key, value2)); Assert.Throws<ArgumentException>(null, () => map2.Add(key, value1)); } protected void ContainsKeyTestHelper<TKey, TValue>(IImmutableDictionary<TKey, TValue> map, TKey key, TValue value) { Assert.False(map.ContainsKey(key)); Assert.True(map.Add(key, value).ContainsKey(key)); } protected void ContainsTestHelper<TKey, TValue>(IImmutableDictionary<TKey, TValue> map, TKey key, TValue value) { Assert.False(map.Contains(new KeyValuePair<TKey, TValue>(key, value))); Assert.False(map.Contains(key, value)); Assert.True(map.Add(key, value).Contains(new KeyValuePair<TKey, TValue>(key, value))); Assert.True(map.Add(key, value).Contains(key, value)); } protected void RemoveTestHelper<TKey, TValue>(IImmutableDictionary<TKey, TValue> map, TKey key) { // no-op remove Assert.Same(map, map.Remove(key)); Assert.Same(map, map.RemoveRange(Enumerable.Empty<TKey>())); // substantial remove var addedMap = map.Add(key, default(TValue)); var removedMap = addedMap.Remove(key); Assert.NotSame(addedMap, removedMap); Assert.False(removedMap.ContainsKey(key)); } protected void KeysTestHelper<TKey, TValue>(IImmutableDictionary<TKey, TValue> map, TKey key) { Assert.Equal(0, map.Keys.Count()); Assert.Equal(0, map.ToReadOnlyDictionary().Keys.Count()); var nonEmpty = map.Add(key, default(TValue)); Assert.Equal(1, nonEmpty.Keys.Count()); Assert.Equal(1, nonEmpty.ToReadOnlyDictionary().Keys.Count()); KeysOrValuesTestHelper(((IDictionary<TKey, TValue>)nonEmpty).Keys, key); } protected void ValuesTestHelper<TKey, TValue>(IImmutableDictionary<TKey, TValue> map, TKey key) { Assert.Equal(0, map.Values.Count()); Assert.Equal(0, map.ToReadOnlyDictionary().Values.Count()); var nonEmpty = map.Add(key, default(TValue)); Assert.Equal(1, nonEmpty.Values.Count()); Assert.Equal(1, nonEmpty.ToReadOnlyDictionary().Values.Count()); KeysOrValuesTestHelper(((IDictionary<TKey, TValue>)nonEmpty).Values, default(TValue)); } protected void EnumeratorTestHelper(IImmutableDictionary<int, GenericParameterHelper> map) { for (int i = 0; i < 10; i++) { map = this.AddTestHelper(map, i, new GenericParameterHelper(i)); } int j = 0; foreach (KeyValuePair<int, GenericParameterHelper> pair in map) { Assert.Equal(j, pair.Key); Assert.Equal(j, pair.Value.Data); j++; } var list = map.ToList(); Assert.Equal<KeyValuePair<int, GenericParameterHelper>>(list, ImmutableSetTest.ToListNonGeneric<KeyValuePair<int, GenericParameterHelper>>(map)); // Apply some less common uses to the enumerator to test its metal. using (var enumerator = map.GetEnumerator()) { enumerator.Reset(); // reset isn't usually called before MoveNext ManuallyEnumerateTest(list, enumerator); enumerator.Reset(); ManuallyEnumerateTest(list, enumerator); // this time only partially enumerate enumerator.Reset(); enumerator.MoveNext(); enumerator.Reset(); ManuallyEnumerateTest(list, enumerator); } var manualEnum = map.GetEnumerator(); Assert.Throws<InvalidOperationException>(() => manualEnum.Current); while (manualEnum.MoveNext()) { } Assert.False(manualEnum.MoveNext()); Assert.Throws<InvalidOperationException>(() => manualEnum.Current); } protected abstract IImmutableDictionary<TKey, TValue> Empty<TKey, TValue>(); protected abstract IImmutableDictionary<string, TValue> Empty<TValue>(StringComparer comparer); protected abstract IEqualityComparer<TValue> GetValueComparer<TKey, TValue>(IImmutableDictionary<TKey, TValue> dictionary); internal abstract IBinaryTree GetRootNode<TKey, TValue>(IImmutableDictionary<TKey, TValue> dictionary); private static void KeysOrValuesTestHelper<T>(ICollection<T> collection, T containedValue) { Requires.NotNull(collection, nameof(collection)); Assert.True(collection.Contains(containedValue)); Assert.Throws<NotSupportedException>(() => collection.Add(default(T))); Assert.Throws<NotSupportedException>(() => collection.Clear()); var nonGeneric = (ICollection)collection; Assert.NotNull(nonGeneric.SyncRoot); Assert.Same(nonGeneric.SyncRoot, nonGeneric.SyncRoot); Assert.True(nonGeneric.IsSynchronized); Assert.True(collection.IsReadOnly); AssertExtensions.Throws<ArgumentNullException>("array", () => nonGeneric.CopyTo(null, 0)); var array = new T[collection.Count + 1]; nonGeneric.CopyTo(array, 1); Assert.Equal(default(T), array[0]); Assert.Equal(array.Skip(1), nonGeneric.Cast<T>().ToArray()); } private void VerifyAvlTreeState<TKey, TValue>(IImmutableDictionary<TKey, TValue> dictionary) { var rootNode = this.GetRootNode(dictionary); rootNode.VerifyBalanced(); rootNode.VerifyHeightIsWithinTolerance(dictionary.Count); } } }
using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Text; using Microsoft.VisualStudio.TestTools.UnitTesting; using Archichect.Rendering.TextWriting; using Archichect.Transforming.PathFinding; namespace Archichect.Tests { [TestClass, ExcludeFromCodeCoverage] public class TestFlatPathWriterWithPathMarker : AbstractWriterTest { [TestInitialize] public void TestInitialize() { new GlobalContext().ResetAll(); } private Dependency CreateDependency(WorkingGraph graph, Item from, Item to, string pathMarker, bool isStart, bool isEnd, bool isMatchedByCountMatch, bool isLoopBack) { Dependency d = FromTo(graph, from, to); d.MarkPathElement(pathMarker, 0, isStart: isStart, isEnd: isEnd, isMatchedByCountSymbol: isMatchedByCountMatch, isLoopBack: isLoopBack); return d; } [TestMethod] public void TestSimpleFlatPathWriterForOnePath() { var gc = new GlobalContext { IgnoreCase = true }; WorkingGraph graph = gc.CurrentGraph; ItemType t3 = ItemType.New("T3(ShortName:MiddleName:LongName)"); var pathMarker = "P0"; Item a = graph.CreateItem(t3, "a:aa:aaa".Split(':')); a.MarkPathElement(pathMarker, 0, isStart: false, isEnd: false, isMatchedByCountSymbol: false, isLoopBack: false); Item b = graph.CreateItem(t3, "b:bb:bbb".Split(':')); b.SetMarker(pathMarker, 1); var d = CreateDependency(graph, a, b, pathMarker, true, true, false, false); Dependency[] dependencies = { d }; using (var s = new MemoryStream()) { var w = new FlatPathWriter(); w.RenderToStreamForUnitTests(gc, dependencies, s, "P*"); string result = Encoding.ASCII.GetString(s.ToArray()); Assert.AreEqual(@"-- P0 a:aa:aaa b:bb:bbb $", result.Trim()); } } [TestMethod] public void TestSimplePathSearchAndFlatPathWriterForOnePath() { ItemType t3 = ItemType.New("T3(ShortName:MiddleName:LongName)"); var gc = new GlobalContext(); WorkingGraph graph = gc.CurrentGraph; var a = graph.CreateItem(t3, "a:aa:aaa".Split(':')); var b = graph.CreateItem(t3, "b:bb:bbb".Split(':')); var dependencies = new[] { FromTo(graph, a, b), }; string result = FindPathsAndWriteFlat(gc, dependencies, "A", CreateDefaultOptions("A")); Assert.AreEqual(@"-- A0 T3:a:aa:aaa'A0 T3:b:bb:bbb'A $", result.Trim()); } private static string FindPathsAndWriteFlat(GlobalContext gc, IEnumerable<Dependency> dependencies, string markerPrefix, string transformOptions) { var pm = new OLDPathMarker(); pm.Configure(gc, "", false); var transformedDependencies = new List<Dependency>(); pm.Transform(gc, dependencies, transformOptions, transformedDependencies, s => null); string result; using (var s = new MemoryStream()) { var w = new FlatPathWriter(); w.RenderToStreamForUnitTests(gc, transformedDependencies, s, $"{markerPrefix}* -sm"); result = Encoding.ASCII.GetString(s.ToArray()); } return result; } private static string CreateDefaultOptions(string markerPrefix, int maxPathLength = 5) { return ($"{{ {OLDPathMarker.AddIndexedMarkerOption} {markerPrefix} " + $"{OLDPathMarker.PathOptions.MaxPathLengthOption} {maxPathLength} " + $"{OLDPathMarker.PathOptions.CountItemAnchorOption} a: " + $"{OLDPathMarker.PathOptions.MultipleItemAnchorOption} ~c: }}").Replace(" ", Environment.NewLine); } [TestMethod] public void TestSimpleFlatPathWriterForNoPath() { ItemType t3 = ItemType.New("T3(ShortName:MiddleName:LongName)"); var gc = new GlobalContext(); WorkingGraph graph = gc.CurrentGraph; var a = graph.CreateItem(t3, "a:aa:aaa".Split(':')); var c = graph.CreateItem(t3, "c:cc:ccc".Split(':')); var dependencies = new[] { FromTo(graph, a, c) }; string result = FindPathsAndWriteFlat(gc, dependencies, "A", CreateDefaultOptions("A")); Assert.AreEqual("", result.Trim()); } [TestMethod] public void TestSimpleFlatPathWriter() { var gc = new GlobalContext(); IEnumerable<Dependency> dependencies = new OLDPathMarker().CreateSomeTestDependencies(gc.CurrentGraph); string result = FindPathsAndWriteFlat(gc, dependencies, "A", CreateDefaultOptions("A")); Assert.AreEqual(@"-- A0 T3:a:aa:aaa'A0+A1+A2+A3 T3:b:bb:bbb'A $ T3:c:cc:ccc'A T3:d:dd:ddd'A $ T3:e:ee:eee'A $ T3:f:ff:fff'A $ -- A1 T3:a:aa:aaa'A0+A1+A2+A3 T3:b:bb:bbb'A $ T3:c:cc:ccc'A T3:d:dd:ddd'A $ <= T3:b:bb:bbb'A $ -- A2 T3:a:aa:aaa'A0+A1+A2+A3 T3:b:bb:bbb'A $ T3:g:gg:ggg'A $ -- A3 T3:a:aa:aaa'A0+A1+A2+A3 T3:h:hh:hhh'A $ T3:g:gg:ggg'A $", result.Trim()); } [TestMethod] public void TestLimitedFlatPathWriter() { var gc = new GlobalContext(); IEnumerable<Dependency> dependencies = new OLDPathMarker().CreateSomeTestDependencies(gc.CurrentGraph); string result = FindPathsAndWriteFlat(gc, dependencies, "A", CreateDefaultOptions("A", 4)); Assert.AreEqual(@"-- A0 T3:a:aa:aaa'A0+A1+A2+A3 T3:b:bb:bbb'A $ T3:c:cc:ccc'A T3:d:dd:ddd'A $ T3:e:ee:eee'A $ -- A1 T3:a:aa:aaa'A0+A1+A2+A3 T3:b:bb:bbb'A $ T3:c:cc:ccc'A T3:d:dd:ddd'A $ <= T3:b:bb:bbb'A $ -- A2 T3:a:aa:aaa'A0+A1+A2+A3 T3:b:bb:bbb'A $ T3:g:gg:ggg'A $ -- A3 T3:a:aa:aaa'A0+A1+A2+A3 T3:h:hh:hhh'A $ T3:g:gg:ggg'A $", result.Trim()); } [TestMethod] public void TestSimpleFlatPathWriterForYPath() { ItemType t3 = ItemType.New("T3(ShortName:MiddleName:LongName)"); var gc = new GlobalContext(); WorkingGraph graph = gc.CurrentGraph; var a = graph.CreateItem(t3, "a:aa:aaa".Split(':')); var b = graph.CreateItem(t3, "b:bb:bbb".Split(':')); var c = graph.CreateItem(t3, "c:cc:ccc".Split(':')); var d = graph.CreateItem(t3, "d:dd:ddd".Split(':')); var dependencies = new[] { FromTo(graph, a, b), FromTo(graph, b, c), FromTo(graph, b ,d), }; string result = FindPathsAndWriteFlat(gc, dependencies, "A", CreateDefaultOptions("A")); Assert.AreEqual(@"-- A0 T3:a:aa:aaa'A0 T3:b:bb:bbb'A $ T3:d:dd:ddd'A $", result.Trim()); } [TestMethod] public void TestOldCountPaths() { ItemType xy = ItemType.New("NL(Name:Layer)"); var gc = new GlobalContext(); WorkingGraph graph = gc.CurrentGraph; Item a = graph.CreateItem(xy, "a", "1"); Item b = graph.CreateItem(xy, "b", "2"); Item c = graph.CreateItem(xy, "c", "2"); Item d = graph.CreateItem(xy, "d", "3"); Item e = graph.CreateItem(xy, "e", "4"); Item f = graph.CreateItem(xy, "f", "4"); Item g = graph.CreateItem(xy, "g", "5"); Dependency[] dependencies = { FromTo(graph, a, b), FromTo(graph, a, c), FromTo(graph, b, d), FromTo(graph, c, d), FromTo(graph, d, e), FromTo(graph, d, f), FromTo(graph, e, g), FromTo(graph, f, g) }; string o = FindPathsAndWriteFlat(gc, dependencies, "A", "{ -im A -pi a -ci 2 -pi g }".Replace(" ", Environment.NewLine)); Console.WriteLine(o); Assert.IsTrue(o.Contains("b:2 #")); Assert.IsTrue(o.Contains("c:2 #")); Assert.IsTrue(o.Contains("d:3'A=2")); Assert.IsTrue(o.Contains("e:4'A=2")); Assert.IsTrue(o.Contains("g:5'A=2 $")); } } }
using System; using Csla; using ParentLoadSoftDelete.DataAccess; using ParentLoadSoftDelete.DataAccess.ERLevel; namespace ParentLoadSoftDelete.Business.ERLevel { /// <summary> /// E07_Country_ReChild (editable child object).<br/> /// This is a generated base class of <see cref="E07_Country_ReChild"/> business object. /// </summary> /// <remarks> /// This class is an item of <see cref="E06_Country"/> collection. /// </remarks> [Serializable] public partial class E07_Country_ReChild : BusinessBase<E07_Country_ReChild> { #region State Fields [NotUndoable] [NonSerialized] internal int country_ID2 = 0; #endregion #region Business Properties /// <summary> /// Maintains metadata about <see cref="Country_Child_Name"/> property. /// </summary> public static readonly PropertyInfo<string> Country_Child_NameProperty = RegisterProperty<string>(p => p.Country_Child_Name, "Regions Child Name"); /// <summary> /// Gets or sets the Regions Child Name. /// </summary> /// <value>The Regions Child Name.</value> public string Country_Child_Name { get { return GetProperty(Country_Child_NameProperty); } set { SetProperty(Country_Child_NameProperty, value); } } #endregion #region Factory Methods /// <summary> /// Factory method. Creates a new <see cref="E07_Country_ReChild"/> object. /// </summary> /// <returns>A reference to the created <see cref="E07_Country_ReChild"/> object.</returns> internal static E07_Country_ReChild NewE07_Country_ReChild() { return DataPortal.CreateChild<E07_Country_ReChild>(); } /// <summary> /// Factory method. Loads a <see cref="E07_Country_ReChild"/> object from the given E07_Country_ReChildDto. /// </summary> /// <param name="data">The <see cref="E07_Country_ReChildDto"/>.</param> /// <returns>A reference to the fetched <see cref="E07_Country_ReChild"/> object.</returns> internal static E07_Country_ReChild GetE07_Country_ReChild(E07_Country_ReChildDto data) { E07_Country_ReChild obj = new E07_Country_ReChild(); // show the framework that this is a child object obj.MarkAsChild(); obj.Fetch(data); obj.MarkOld(); // check all object rules and property rules obj.BusinessRules.CheckRules(); return obj; } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="E07_Country_ReChild"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public E07_Country_ReChild() { // Use factory methods and do not use direct creation. // show the framework that this is a child object MarkAsChild(); } #endregion #region Data Access /// <summary> /// Loads default values for the <see cref="E07_Country_ReChild"/> object properties. /// </summary> [Csla.RunLocal] protected override void Child_Create() { var args = new DataPortalHookArgs(); OnCreate(args); base.Child_Create(); } /// <summary> /// Loads a <see cref="E07_Country_ReChild"/> object from the given <see cref="E07_Country_ReChildDto"/>. /// </summary> /// <param name="data">The E07_Country_ReChildDto to use.</param> private void Fetch(E07_Country_ReChildDto data) { // Value properties LoadProperty(Country_Child_NameProperty, data.Country_Child_Name); // parent properties country_ID2 = data.Parent_Country_ID; var args = new DataPortalHookArgs(data); OnFetchRead(args); } /// <summary> /// Inserts a new <see cref="E07_Country_ReChild"/> object in the database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Insert(E06_Country parent) { var dto = new E07_Country_ReChildDto(); dto.Parent_Country_ID = parent.Country_ID; dto.Country_Child_Name = Country_Child_Name; using (var dalManager = DalFactoryParentLoadSoftDelete.GetManager()) { var args = new DataPortalHookArgs(dto); OnInsertPre(args); var dal = dalManager.GetProvider<IE07_Country_ReChildDal>(); using (BypassPropertyChecks) { var resultDto = dal.Insert(dto); args = new DataPortalHookArgs(resultDto); } OnInsertPost(args); } } /// <summary> /// Updates in the database all changes made to the <see cref="E07_Country_ReChild"/> object. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Update(E06_Country parent) { if (!IsDirty) return; var dto = new E07_Country_ReChildDto(); dto.Parent_Country_ID = parent.Country_ID; dto.Country_Child_Name = Country_Child_Name; using (var dalManager = DalFactoryParentLoadSoftDelete.GetManager()) { var args = new DataPortalHookArgs(dto); OnUpdatePre(args); var dal = dalManager.GetProvider<IE07_Country_ReChildDal>(); using (BypassPropertyChecks) { var resultDto = dal.Update(dto); args = new DataPortalHookArgs(resultDto); } OnUpdatePost(args); } } /// <summary> /// Self deletes the <see cref="E07_Country_ReChild"/> object from database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_DeleteSelf(E06_Country parent) { using (var dalManager = DalFactoryParentLoadSoftDelete.GetManager()) { var args = new DataPortalHookArgs(); OnDeletePre(args); var dal = dalManager.GetProvider<IE07_Country_ReChildDal>(); using (BypassPropertyChecks) { dal.Delete(parent.Country_ID); } OnDeletePost(args); } } #endregion #region DataPortal Hooks /// <summary> /// Occurs after setting all defaults for object creation. /// </summary> partial void OnCreate(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation. /// </summary> partial void OnDeletePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after the delete operation, before Commit(). /// </summary> partial void OnDeletePost(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the fetch operation. /// </summary> partial void OnFetchPre(DataPortalHookArgs args); /// <summary> /// Occurs after the fetch operation (object or collection is fully loaded and set up). /// </summary> partial void OnFetchPost(DataPortalHookArgs args); /// <summary> /// Occurs after the low level fetch operation, before the data reader is destroyed. /// </summary> partial void OnFetchRead(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the update operation. /// </summary> partial void OnUpdatePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit(). /// </summary> partial void OnUpdatePost(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation. /// </summary> partial void OnInsertPre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit(). /// </summary> partial void OnInsertPost(DataPortalHookArgs args); #endregion } }
// 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 InsertSByte129() { var test = new SimpleUnaryOpTest__InsertSByte129(); try { if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local works test.RunLclFldScenario(); // Validates passing an instance member works test.RunFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } } catch (PlatformNotSupportedException) { test.Succeeded = true; } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleUnaryOpTest__InsertSByte129 { private const int VectorSize = 16; private const int Op1ElementCount = VectorSize / sizeof(SByte); private const int RetElementCount = VectorSize / sizeof(SByte); private static SByte[] _data = new SByte[Op1ElementCount]; private static Vector128<SByte> _clsVar; private Vector128<SByte> _fld; private SimpleUnaryOpTest__DataTable<SByte, SByte> _dataTable; static SimpleUnaryOpTest__InsertSByte129() { var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (sbyte)0; } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _clsVar), ref Unsafe.As<SByte, byte>(ref _data[0]), VectorSize); } public SimpleUnaryOpTest__InsertSByte129() { Succeeded = true; var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (sbyte)0; } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _fld), ref Unsafe.As<SByte, byte>(ref _data[0]), VectorSize); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (sbyte)0; } _dataTable = new SimpleUnaryOpTest__DataTable<SByte, SByte>(_data, new SByte[RetElementCount], VectorSize); } public bool IsSupported => Sse41.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Sse41.Insert( Unsafe.Read<Vector128<SByte>>(_dataTable.inArrayPtr), (sbyte)2, 129 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Sse41.Insert( Sse2.LoadVector128((SByte*)(_dataTable.inArrayPtr)), (sbyte)2, 129 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Sse41.Insert( Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArrayPtr)), (sbyte)2, 129 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Sse41).GetMethod(nameof(Sse41.Insert), new Type[] { typeof(Vector128<SByte>), typeof(SByte), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<SByte>>(_dataTable.inArrayPtr), (sbyte)2, (byte)129 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<SByte>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Sse41).GetMethod(nameof(Sse41.Insert), new Type[] { typeof(Vector128<SByte>), typeof(SByte), typeof(byte) }) .Invoke(null, new object[] { Sse2.LoadVector128((SByte*)(_dataTable.inArrayPtr)), (sbyte)2, (byte)129 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<SByte>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Sse41).GetMethod(nameof(Sse41.Insert), new Type[] { typeof(Vector128<SByte>), typeof(SByte), typeof(byte) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArrayPtr)), (sbyte)2, (byte)129 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<SByte>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Sse41.Insert( _clsVar, (sbyte)2, 129 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var firstOp = Unsafe.Read<Vector128<SByte>>(_dataTable.inArrayPtr); var result = Sse41.Insert(firstOp, (sbyte)2, 129); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var firstOp = Sse2.LoadVector128((SByte*)(_dataTable.inArrayPtr)); var result = Sse41.Insert(firstOp, (sbyte)2, 129); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var firstOp = Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArrayPtr)); var result = Sse41.Insert(firstOp, (sbyte)2, 129); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new SimpleUnaryOpTest__InsertSByte129(); var result = Sse41.Insert(test._fld, (sbyte)2, 129); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Sse41.Insert(_fld, (sbyte)2, 129); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector128<SByte> firstOp, void* result, [CallerMemberName] string method = "") { SByte[] inArray = new SByte[Op1ElementCount]; SByte[] outArray = new SByte[RetElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray[0]), firstOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray, outArray, method); } private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "") { SByte[] inArray = new SByte[Op1ElementCount]; SByte[] outArray = new SByte[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray, outArray, method); } private void ValidateResult(SByte[] firstOp, SByte[] result, [CallerMemberName] string method = "") { for (var i = 0; i < RetElementCount; i++) { if ((i == 1 ? result[i] != 2 : result[i] != 0)) { Succeeded = false; break; } } if (!Succeeded) { Console.WriteLine($"{nameof(Sse41)}.{nameof(Sse41.Insert)}<SByte>(Vector128<SByte><9>): {method} failed:"); Console.WriteLine($" firstOp: ({string.Join(", ", firstOp)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }