context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // using System; class r4NaNrem { //user-defined class that overloads operator % public class numHolder { float f_num; public numHolder(float f_num) { this.f_num = Convert.ToSingle(f_num); } public static float operator %(numHolder a, float b) { return a.f_num % b; } public static float operator %(numHolder a, numHolder b) { return a.f_num % b.f_num; } } static float f_s_test1_op1 = Single.NaN; static float f_s_test1_op2 = 7.1234567F; static float f_s_test2_op1 = -2.0F; static float f_s_test2_op2 = 0.0F; static float f_s_test3_op1 = Single.PositiveInfinity; static float f_s_test3_op2 = 0.0F; public static float f_test1_f(String s) { if (s == "test1_op1") return Single.NaN; else return 7.1234567F; } public static float f_test2_f(String s) { if (s == "test2_op1") return -2.0F; else return 0.0F; } public static float f_test3_f(String s) { if (s == "test3_op1") return Single.PositiveInfinity; else return 0.0F; } class CL { public float f_cl_test1_op1 = Single.NaN; public float f_cl_test1_op2 = 7.1234567F; public float f_cl_test2_op1 = -2.0F; public float f_cl_test2_op2 = 0.0F; public float f_cl_test3_op1 = Single.PositiveInfinity; public float f_cl_test3_op2 = 0.0F; } struct VT { public float f_vt_test1_op1; public float f_vt_test1_op2; public float f_vt_test2_op1; public float f_vt_test2_op2; public float f_vt_test3_op1; public float f_vt_test3_op2; } public static int Main() { bool passed = true; //initialize class CL cl1 = new CL(); //initialize struct VT vt1; vt1.f_vt_test1_op1 = Single.NaN; vt1.f_vt_test1_op2 = 7.1234567F; vt1.f_vt_test2_op1 = -2.0F; vt1.f_vt_test2_op2 = 0.0F; vt1.f_vt_test3_op1 = Single.PositiveInfinity; vt1.f_vt_test3_op2 = 0.0F; float[] f_arr1d_test1_op1 = { 0, Single.NaN }; float[,] f_arr2d_test1_op1 = { { 0, Single.NaN }, { 1, 1 } }; float[, ,] f_arr3d_test1_op1 = { { { 0, Single.NaN }, { 1, 1 } } }; float[] f_arr1d_test1_op2 = { 7.1234567F, 0, 1 }; float[,] f_arr2d_test1_op2 = { { 0, 7.1234567F }, { 1, 1 } }; float[, ,] f_arr3d_test1_op2 = { { { 0, 7.1234567F }, { 1, 1 } } }; float[] f_arr1d_test2_op1 = { 0, -2.0F }; float[,] f_arr2d_test2_op1 = { { 0, -2.0F }, { 1, 1 } }; float[, ,] f_arr3d_test2_op1 = { { { 0, -2.0F }, { 1, 1 } } }; float[] f_arr1d_test2_op2 = { 0.0F, 0, 1 }; float[,] f_arr2d_test2_op2 = { { 0, 0.0F }, { 1, 1 } }; float[, ,] f_arr3d_test2_op2 = { { { 0, 0.0F }, { 1, 1 } } }; float[] f_arr1d_test3_op1 = { 0, Single.PositiveInfinity }; float[,] f_arr2d_test3_op1 = { { 0, Single.PositiveInfinity }, { 1, 1 } }; float[, ,] f_arr3d_test3_op1 = { { { 0, Single.PositiveInfinity }, { 1, 1 } } }; float[] f_arr1d_test3_op2 = { 0.0F, 0, 1 }; float[,] f_arr2d_test3_op2 = { { 0, 0.0F }, { 1, 1 } }; float[, ,] f_arr3d_test3_op2 = { { { 0, 0.0F }, { 1, 1 } } }; int[,] index = { { 0, 0 }, { 1, 1 } }; { float f_l_test1_op1 = Single.NaN; float f_l_test1_op2 = 7.1234567F; if (!Single.IsNaN(f_l_test1_op1 % f_l_test1_op2)) { Console.WriteLine("Test1_testcase 1 failed"); passed = false; } if (!Single.IsNaN(f_l_test1_op1 % f_s_test1_op2)) { Console.WriteLine("Test1_testcase 2 failed"); passed = false; } if (!Single.IsNaN(f_l_test1_op1 % f_test1_f("test1_op2"))) { Console.WriteLine("Test1_testcase 3 failed"); passed = false; } if (!Single.IsNaN(f_l_test1_op1 % cl1.f_cl_test1_op2)) { Console.WriteLine("Test1_testcase 4 failed"); passed = false; } if (!Single.IsNaN(f_l_test1_op1 % vt1.f_vt_test1_op2)) { Console.WriteLine("Test1_testcase 5 failed"); passed = false; } if (!Single.IsNaN(f_l_test1_op1 % f_arr1d_test1_op2[0])) { Console.WriteLine("Test1_testcase 6 failed"); passed = false; } if (!Single.IsNaN(f_l_test1_op1 % f_arr2d_test1_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test1_testcase 7 failed"); passed = false; } if (!Single.IsNaN(f_l_test1_op1 % f_arr3d_test1_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test1_testcase 8 failed"); passed = false; } if (!Single.IsNaN(f_s_test1_op1 % f_l_test1_op2)) { Console.WriteLine("Test1_testcase 9 failed"); passed = false; } if (!Single.IsNaN(f_s_test1_op1 % f_s_test1_op2)) { Console.WriteLine("Test1_testcase 10 failed"); passed = false; } if (!Single.IsNaN(f_s_test1_op1 % f_test1_f("test1_op2"))) { Console.WriteLine("Test1_testcase 11 failed"); passed = false; } if (!Single.IsNaN(f_s_test1_op1 % cl1.f_cl_test1_op2)) { Console.WriteLine("Test1_testcase 12 failed"); passed = false; } if (!Single.IsNaN(f_s_test1_op1 % vt1.f_vt_test1_op2)) { Console.WriteLine("Test1_testcase 13 failed"); passed = false; } if (!Single.IsNaN(f_s_test1_op1 % f_arr1d_test1_op2[0])) { Console.WriteLine("Test1_testcase 14 failed"); passed = false; } if (!Single.IsNaN(f_s_test1_op1 % f_arr2d_test1_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test1_testcase 15 failed"); passed = false; } if (!Single.IsNaN(f_s_test1_op1 % f_arr3d_test1_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test1_testcase 16 failed"); passed = false; } if (!Single.IsNaN(f_test1_f("test1_op1") % f_l_test1_op2)) { Console.WriteLine("Test1_testcase 17 failed"); passed = false; } if (!Single.IsNaN(f_test1_f("test1_op1") % f_s_test1_op2)) { Console.WriteLine("Test1_testcase 18 failed"); passed = false; } if (!Single.IsNaN(f_test1_f("test1_op1") % f_test1_f("test1_op2"))) { Console.WriteLine("Test1_testcase 19 failed"); passed = false; } if (!Single.IsNaN(f_test1_f("test1_op1") % cl1.f_cl_test1_op2)) { Console.WriteLine("Test1_testcase 20 failed"); passed = false; } if (!Single.IsNaN(f_test1_f("test1_op1") % vt1.f_vt_test1_op2)) { Console.WriteLine("Test1_testcase 21 failed"); passed = false; } if (!Single.IsNaN(f_test1_f("test1_op1") % f_arr1d_test1_op2[0])) { Console.WriteLine("Test1_testcase 22 failed"); passed = false; } if (!Single.IsNaN(f_test1_f("test1_op1") % f_arr2d_test1_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test1_testcase 23 failed"); passed = false; } if (!Single.IsNaN(f_test1_f("test1_op1") % f_arr3d_test1_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test1_testcase 24 failed"); passed = false; } if (!Single.IsNaN(cl1.f_cl_test1_op1 % f_l_test1_op2)) { Console.WriteLine("Test1_testcase 25 failed"); passed = false; } if (!Single.IsNaN(cl1.f_cl_test1_op1 % f_s_test1_op2)) { Console.WriteLine("Test1_testcase 26 failed"); passed = false; } if (!Single.IsNaN(cl1.f_cl_test1_op1 % f_test1_f("test1_op2"))) { Console.WriteLine("Test1_testcase 27 failed"); passed = false; } if (!Single.IsNaN(cl1.f_cl_test1_op1 % cl1.f_cl_test1_op2)) { Console.WriteLine("Test1_testcase 28 failed"); passed = false; } if (!Single.IsNaN(cl1.f_cl_test1_op1 % vt1.f_vt_test1_op2)) { Console.WriteLine("Test1_testcase 29 failed"); passed = false; } if (!Single.IsNaN(cl1.f_cl_test1_op1 % f_arr1d_test1_op2[0])) { Console.WriteLine("Test1_testcase 30 failed"); passed = false; } if (!Single.IsNaN(cl1.f_cl_test1_op1 % f_arr2d_test1_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test1_testcase 31 failed"); passed = false; } if (!Single.IsNaN(cl1.f_cl_test1_op1 % f_arr3d_test1_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test1_testcase 32 failed"); passed = false; } if (!Single.IsNaN(vt1.f_vt_test1_op1 % f_l_test1_op2)) { Console.WriteLine("Test1_testcase 33 failed"); passed = false; } if (!Single.IsNaN(vt1.f_vt_test1_op1 % f_s_test1_op2)) { Console.WriteLine("Test1_testcase 34 failed"); passed = false; } if (!Single.IsNaN(vt1.f_vt_test1_op1 % f_test1_f("test1_op2"))) { Console.WriteLine("Test1_testcase 35 failed"); passed = false; } if (!Single.IsNaN(vt1.f_vt_test1_op1 % cl1.f_cl_test1_op2)) { Console.WriteLine("Test1_testcase 36 failed"); passed = false; } if (!Single.IsNaN(vt1.f_vt_test1_op1 % vt1.f_vt_test1_op2)) { Console.WriteLine("Test1_testcase 37 failed"); passed = false; } if (!Single.IsNaN(vt1.f_vt_test1_op1 % f_arr1d_test1_op2[0])) { Console.WriteLine("Test1_testcase 38 failed"); passed = false; } if (!Single.IsNaN(vt1.f_vt_test1_op1 % f_arr2d_test1_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test1_testcase 39 failed"); passed = false; } if (!Single.IsNaN(vt1.f_vt_test1_op1 % f_arr3d_test1_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test1_testcase 40 failed"); passed = false; } if (!Single.IsNaN(f_arr1d_test1_op1[1] % f_l_test1_op2)) { Console.WriteLine("Test1_testcase 41 failed"); passed = false; } if (!Single.IsNaN(f_arr1d_test1_op1[1] % f_s_test1_op2)) { Console.WriteLine("Test1_testcase 42 failed"); passed = false; } if (!Single.IsNaN(f_arr1d_test1_op1[1] % f_test1_f("test1_op2"))) { Console.WriteLine("Test1_testcase 43 failed"); passed = false; } if (!Single.IsNaN(f_arr1d_test1_op1[1] % cl1.f_cl_test1_op2)) { Console.WriteLine("Test1_testcase 44 failed"); passed = false; } if (!Single.IsNaN(f_arr1d_test1_op1[1] % vt1.f_vt_test1_op2)) { Console.WriteLine("Test1_testcase 45 failed"); passed = false; } if (!Single.IsNaN(f_arr1d_test1_op1[1] % f_arr1d_test1_op2[0])) { Console.WriteLine("Test1_testcase 46 failed"); passed = false; } if (!Single.IsNaN(f_arr1d_test1_op1[1] % f_arr2d_test1_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test1_testcase 47 failed"); passed = false; } if (!Single.IsNaN(f_arr1d_test1_op1[1] % f_arr3d_test1_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test1_testcase 48 failed"); passed = false; } if (!Single.IsNaN(f_arr2d_test1_op1[index[0, 1], index[1, 0]] % f_l_test1_op2)) { Console.WriteLine("Test1_testcase 49 failed"); passed = false; } if (!Single.IsNaN(f_arr2d_test1_op1[index[0, 1], index[1, 0]] % f_s_test1_op2)) { Console.WriteLine("Test1_testcase 50 failed"); passed = false; } if (!Single.IsNaN(f_arr2d_test1_op1[index[0, 1], index[1, 0]] % f_test1_f("test1_op2"))) { Console.WriteLine("Test1_testcase 51 failed"); passed = false; } if (!Single.IsNaN(f_arr2d_test1_op1[index[0, 1], index[1, 0]] % cl1.f_cl_test1_op2)) { Console.WriteLine("Test1_testcase 52 failed"); passed = false; } if (!Single.IsNaN(f_arr2d_test1_op1[index[0, 1], index[1, 0]] % vt1.f_vt_test1_op2)) { Console.WriteLine("Test1_testcase 53 failed"); passed = false; } if (!Single.IsNaN(f_arr2d_test1_op1[index[0, 1], index[1, 0]] % f_arr1d_test1_op2[0])) { Console.WriteLine("Test1_testcase 54 failed"); passed = false; } if (!Single.IsNaN(f_arr2d_test1_op1[index[0, 1], index[1, 0]] % f_arr2d_test1_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test1_testcase 55 failed"); passed = false; } if (!Single.IsNaN(f_arr2d_test1_op1[index[0, 1], index[1, 0]] % f_arr3d_test1_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test1_testcase 56 failed"); passed = false; } if (!Single.IsNaN(f_arr3d_test1_op1[index[0, 0], 0, index[1, 1]] % f_l_test1_op2)) { Console.WriteLine("Test1_testcase 57 failed"); passed = false; } if (!Single.IsNaN(f_arr3d_test1_op1[index[0, 0], 0, index[1, 1]] % f_s_test1_op2)) { Console.WriteLine("Test1_testcase 58 failed"); passed = false; } if (!Single.IsNaN(f_arr3d_test1_op1[index[0, 0], 0, index[1, 1]] % f_test1_f("test1_op2"))) { Console.WriteLine("Test1_testcase 59 failed"); passed = false; } if (!Single.IsNaN(f_arr3d_test1_op1[index[0, 0], 0, index[1, 1]] % cl1.f_cl_test1_op2)) { Console.WriteLine("Test1_testcase 60 failed"); passed = false; } if (!Single.IsNaN(f_arr3d_test1_op1[index[0, 0], 0, index[1, 1]] % vt1.f_vt_test1_op2)) { Console.WriteLine("Test1_testcase 61 failed"); passed = false; } if (!Single.IsNaN(f_arr3d_test1_op1[index[0, 0], 0, index[1, 1]] % f_arr1d_test1_op2[0])) { Console.WriteLine("Test1_testcase 62 failed"); passed = false; } if (!Single.IsNaN(f_arr3d_test1_op1[index[0, 0], 0, index[1, 1]] % f_arr2d_test1_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test1_testcase 63 failed"); passed = false; } if (!Single.IsNaN(f_arr3d_test1_op1[index[0, 0], 0, index[1, 1]] % f_arr3d_test1_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test1_testcase 64 failed"); passed = false; } } { float f_l_test2_op1 = -2.0F; float f_l_test2_op2 = 0.0F; if (!Single.IsNaN(f_l_test2_op1 % f_l_test2_op2)) { Console.WriteLine("Test2_testcase 1 failed"); passed = false; } if (!Single.IsNaN(f_l_test2_op1 % f_s_test2_op2)) { Console.WriteLine("Test2_testcase 2 failed"); passed = false; } if (!Single.IsNaN(f_l_test2_op1 % f_test2_f("test2_op2"))) { Console.WriteLine("Test2_testcase 3 failed"); passed = false; } if (!Single.IsNaN(f_l_test2_op1 % cl1.f_cl_test2_op2)) { Console.WriteLine("Test2_testcase 4 failed"); passed = false; } if (!Single.IsNaN(f_l_test2_op1 % vt1.f_vt_test2_op2)) { Console.WriteLine("Test2_testcase 5 failed"); passed = false; } if (!Single.IsNaN(f_l_test2_op1 % f_arr1d_test2_op2[0])) { Console.WriteLine("Test2_testcase 6 failed"); passed = false; } if (!Single.IsNaN(f_l_test2_op1 % f_arr2d_test2_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test2_testcase 7 failed"); passed = false; } if (!Single.IsNaN(f_l_test2_op1 % f_arr3d_test2_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test2_testcase 8 failed"); passed = false; } if (!Single.IsNaN(f_s_test2_op1 % f_l_test2_op2)) { Console.WriteLine("Test2_testcase 9 failed"); passed = false; } if (!Single.IsNaN(f_s_test2_op1 % f_s_test2_op2)) { Console.WriteLine("Test2_testcase 10 failed"); passed = false; } if (!Single.IsNaN(f_s_test2_op1 % f_test2_f("test2_op2"))) { Console.WriteLine("Test2_testcase 11 failed"); passed = false; } if (!Single.IsNaN(f_s_test2_op1 % cl1.f_cl_test2_op2)) { Console.WriteLine("Test2_testcase 12 failed"); passed = false; } if (!Single.IsNaN(f_s_test2_op1 % vt1.f_vt_test2_op2)) { Console.WriteLine("Test2_testcase 13 failed"); passed = false; } if (!Single.IsNaN(f_s_test2_op1 % f_arr1d_test2_op2[0])) { Console.WriteLine("Test2_testcase 14 failed"); passed = false; } if (!Single.IsNaN(f_s_test2_op1 % f_arr2d_test2_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test2_testcase 15 failed"); passed = false; } if (!Single.IsNaN(f_s_test2_op1 % f_arr3d_test2_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test2_testcase 16 failed"); passed = false; } if (!Single.IsNaN(f_test2_f("test2_op1") % f_l_test2_op2)) { Console.WriteLine("Test2_testcase 17 failed"); passed = false; } if (!Single.IsNaN(f_test2_f("test2_op1") % f_s_test2_op2)) { Console.WriteLine("Test2_testcase 18 failed"); passed = false; } if (!Single.IsNaN(f_test2_f("test2_op1") % f_test2_f("test2_op2"))) { Console.WriteLine("Test2_testcase 19 failed"); passed = false; } if (!Single.IsNaN(f_test2_f("test2_op1") % cl1.f_cl_test2_op2)) { Console.WriteLine("Test2_testcase 20 failed"); passed = false; } if (!Single.IsNaN(f_test2_f("test2_op1") % vt1.f_vt_test2_op2)) { Console.WriteLine("Test2_testcase 21 failed"); passed = false; } if (!Single.IsNaN(f_test2_f("test2_op1") % f_arr1d_test2_op2[0])) { Console.WriteLine("Test2_testcase 22 failed"); passed = false; } if (!Single.IsNaN(f_test2_f("test2_op1") % f_arr2d_test2_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test2_testcase 23 failed"); passed = false; } if (!Single.IsNaN(f_test2_f("test2_op1") % f_arr3d_test2_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test2_testcase 24 failed"); passed = false; } if (!Single.IsNaN(cl1.f_cl_test2_op1 % f_l_test2_op2)) { Console.WriteLine("Test2_testcase 25 failed"); passed = false; } if (!Single.IsNaN(cl1.f_cl_test2_op1 % f_s_test2_op2)) { Console.WriteLine("Test2_testcase 26 failed"); passed = false; } if (!Single.IsNaN(cl1.f_cl_test2_op1 % f_test2_f("test2_op2"))) { Console.WriteLine("Test2_testcase 27 failed"); passed = false; } if (!Single.IsNaN(cl1.f_cl_test2_op1 % cl1.f_cl_test2_op2)) { Console.WriteLine("Test2_testcase 28 failed"); passed = false; } if (!Single.IsNaN(cl1.f_cl_test2_op1 % vt1.f_vt_test2_op2)) { Console.WriteLine("Test2_testcase 29 failed"); passed = false; } if (!Single.IsNaN(cl1.f_cl_test2_op1 % f_arr1d_test2_op2[0])) { Console.WriteLine("Test2_testcase 30 failed"); passed = false; } if (!Single.IsNaN(cl1.f_cl_test2_op1 % f_arr2d_test2_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test2_testcase 31 failed"); passed = false; } if (!Single.IsNaN(cl1.f_cl_test2_op1 % f_arr3d_test2_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test2_testcase 32 failed"); passed = false; } if (!Single.IsNaN(vt1.f_vt_test2_op1 % f_l_test2_op2)) { Console.WriteLine("Test2_testcase 33 failed"); passed = false; } if (!Single.IsNaN(vt1.f_vt_test2_op1 % f_s_test2_op2)) { Console.WriteLine("Test2_testcase 34 failed"); passed = false; } if (!Single.IsNaN(vt1.f_vt_test2_op1 % f_test2_f("test2_op2"))) { Console.WriteLine("Test2_testcase 35 failed"); passed = false; } if (!Single.IsNaN(vt1.f_vt_test2_op1 % cl1.f_cl_test2_op2)) { Console.WriteLine("Test2_testcase 36 failed"); passed = false; } if (!Single.IsNaN(vt1.f_vt_test2_op1 % vt1.f_vt_test2_op2)) { Console.WriteLine("Test2_testcase 37 failed"); passed = false; } if (!Single.IsNaN(vt1.f_vt_test2_op1 % f_arr1d_test2_op2[0])) { Console.WriteLine("Test2_testcase 38 failed"); passed = false; } if (!Single.IsNaN(vt1.f_vt_test2_op1 % f_arr2d_test2_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test2_testcase 39 failed"); passed = false; } if (!Single.IsNaN(vt1.f_vt_test2_op1 % f_arr3d_test2_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test2_testcase 40 failed"); passed = false; } if (!Single.IsNaN(f_arr1d_test2_op1[1] % f_l_test2_op2)) { Console.WriteLine("Test2_testcase 41 failed"); passed = false; } if (!Single.IsNaN(f_arr1d_test2_op1[1] % f_s_test2_op2)) { Console.WriteLine("Test2_testcase 42 failed"); passed = false; } if (!Single.IsNaN(f_arr1d_test2_op1[1] % f_test2_f("test2_op2"))) { Console.WriteLine("Test2_testcase 43 failed"); passed = false; } if (!Single.IsNaN(f_arr1d_test2_op1[1] % cl1.f_cl_test2_op2)) { Console.WriteLine("Test2_testcase 44 failed"); passed = false; } if (!Single.IsNaN(f_arr1d_test2_op1[1] % vt1.f_vt_test2_op2)) { Console.WriteLine("Test2_testcase 45 failed"); passed = false; } if (!Single.IsNaN(f_arr1d_test2_op1[1] % f_arr1d_test2_op2[0])) { Console.WriteLine("Test2_testcase 46 failed"); passed = false; } if (!Single.IsNaN(f_arr1d_test2_op1[1] % f_arr2d_test2_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test2_testcase 47 failed"); passed = false; } if (!Single.IsNaN(f_arr1d_test2_op1[1] % f_arr3d_test2_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test2_testcase 48 failed"); passed = false; } if (!Single.IsNaN(f_arr2d_test2_op1[index[0, 1], index[1, 0]] % f_l_test2_op2)) { Console.WriteLine("Test2_testcase 49 failed"); passed = false; } if (!Single.IsNaN(f_arr2d_test2_op1[index[0, 1], index[1, 0]] % f_s_test2_op2)) { Console.WriteLine("Test2_testcase 50 failed"); passed = false; } if (!Single.IsNaN(f_arr2d_test2_op1[index[0, 1], index[1, 0]] % f_test2_f("test2_op2"))) { Console.WriteLine("Test2_testcase 51 failed"); passed = false; } if (!Single.IsNaN(f_arr2d_test2_op1[index[0, 1], index[1, 0]] % cl1.f_cl_test2_op2)) { Console.WriteLine("Test2_testcase 52 failed"); passed = false; } if (!Single.IsNaN(f_arr2d_test2_op1[index[0, 1], index[1, 0]] % vt1.f_vt_test2_op2)) { Console.WriteLine("Test2_testcase 53 failed"); passed = false; } if (!Single.IsNaN(f_arr2d_test2_op1[index[0, 1], index[1, 0]] % f_arr1d_test2_op2[0])) { Console.WriteLine("Test2_testcase 54 failed"); passed = false; } if (!Single.IsNaN(f_arr2d_test2_op1[index[0, 1], index[1, 0]] % f_arr2d_test2_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test2_testcase 55 failed"); passed = false; } if (!Single.IsNaN(f_arr2d_test2_op1[index[0, 1], index[1, 0]] % f_arr3d_test2_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test2_testcase 56 failed"); passed = false; } if (!Single.IsNaN(f_arr3d_test2_op1[index[0, 0], 0, index[1, 1]] % f_l_test2_op2)) { Console.WriteLine("Test2_testcase 57 failed"); passed = false; } if (!Single.IsNaN(f_arr3d_test2_op1[index[0, 0], 0, index[1, 1]] % f_s_test2_op2)) { Console.WriteLine("Test2_testcase 58 failed"); passed = false; } if (!Single.IsNaN(f_arr3d_test2_op1[index[0, 0], 0, index[1, 1]] % f_test2_f("test2_op2"))) { Console.WriteLine("Test2_testcase 59 failed"); passed = false; } if (!Single.IsNaN(f_arr3d_test2_op1[index[0, 0], 0, index[1, 1]] % cl1.f_cl_test2_op2)) { Console.WriteLine("Test2_testcase 60 failed"); passed = false; } if (!Single.IsNaN(f_arr3d_test2_op1[index[0, 0], 0, index[1, 1]] % vt1.f_vt_test2_op2)) { Console.WriteLine("Test2_testcase 61 failed"); passed = false; } if (!Single.IsNaN(f_arr3d_test2_op1[index[0, 0], 0, index[1, 1]] % f_arr1d_test2_op2[0])) { Console.WriteLine("Test2_testcase 62 failed"); passed = false; } if (!Single.IsNaN(f_arr3d_test2_op1[index[0, 0], 0, index[1, 1]] % f_arr2d_test2_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test2_testcase 63 failed"); passed = false; } if (!Single.IsNaN(f_arr3d_test2_op1[index[0, 0], 0, index[1, 1]] % f_arr3d_test2_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test2_testcase 64 failed"); passed = false; } } { float f_l_test3_op1 = Single.PositiveInfinity; float f_l_test3_op2 = 0.0F; if (!Single.IsNaN(f_l_test3_op1 % f_l_test3_op2)) { Console.WriteLine("Test3_testcase 1 failed"); passed = false; } if (!Single.IsNaN(f_l_test3_op1 % f_s_test3_op2)) { Console.WriteLine("Test3_testcase 2 failed"); passed = false; } if (!Single.IsNaN(f_l_test3_op1 % f_test3_f("test3_op2"))) { Console.WriteLine("Test3_testcase 3 failed"); passed = false; } if (!Single.IsNaN(f_l_test3_op1 % cl1.f_cl_test3_op2)) { Console.WriteLine("Test3_testcase 4 failed"); passed = false; } if (!Single.IsNaN(f_l_test3_op1 % vt1.f_vt_test3_op2)) { Console.WriteLine("Test3_testcase 5 failed"); passed = false; } if (!Single.IsNaN(f_l_test3_op1 % f_arr1d_test3_op2[0])) { Console.WriteLine("Test3_testcase 6 failed"); passed = false; } if (!Single.IsNaN(f_l_test3_op1 % f_arr2d_test3_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test3_testcase 7 failed"); passed = false; } if (!Single.IsNaN(f_l_test3_op1 % f_arr3d_test3_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test3_testcase 8 failed"); passed = false; } if (!Single.IsNaN(f_s_test3_op1 % f_l_test3_op2)) { Console.WriteLine("Test3_testcase 9 failed"); passed = false; } if (!Single.IsNaN(f_s_test3_op1 % f_s_test3_op2)) { Console.WriteLine("Test3_testcase 10 failed"); passed = false; } if (!Single.IsNaN(f_s_test3_op1 % f_test3_f("test3_op2"))) { Console.WriteLine("Test3_testcase 11 failed"); passed = false; } if (!Single.IsNaN(f_s_test3_op1 % cl1.f_cl_test3_op2)) { Console.WriteLine("Test3_testcase 12 failed"); passed = false; } if (!Single.IsNaN(f_s_test3_op1 % vt1.f_vt_test3_op2)) { Console.WriteLine("Test3_testcase 13 failed"); passed = false; } if (!Single.IsNaN(f_s_test3_op1 % f_arr1d_test3_op2[0])) { Console.WriteLine("Test3_testcase 14 failed"); passed = false; } if (!Single.IsNaN(f_s_test3_op1 % f_arr2d_test3_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test3_testcase 15 failed"); passed = false; } if (!Single.IsNaN(f_s_test3_op1 % f_arr3d_test3_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test3_testcase 16 failed"); passed = false; } if (!Single.IsNaN(f_test3_f("test3_op1") % f_l_test3_op2)) { Console.WriteLine("Test3_testcase 17 failed"); passed = false; } if (!Single.IsNaN(f_test3_f("test3_op1") % f_s_test3_op2)) { Console.WriteLine("Test3_testcase 18 failed"); passed = false; } if (!Single.IsNaN(f_test3_f("test3_op1") % f_test3_f("test3_op2"))) { Console.WriteLine("Test3_testcase 19 failed"); passed = false; } if (!Single.IsNaN(f_test3_f("test3_op1") % cl1.f_cl_test3_op2)) { Console.WriteLine("Test3_testcase 20 failed"); passed = false; } if (!Single.IsNaN(f_test3_f("test3_op1") % vt1.f_vt_test3_op2)) { Console.WriteLine("Test3_testcase 21 failed"); passed = false; } if (!Single.IsNaN(f_test3_f("test3_op1") % f_arr1d_test3_op2[0])) { Console.WriteLine("Test3_testcase 22 failed"); passed = false; } if (!Single.IsNaN(f_test3_f("test3_op1") % f_arr2d_test3_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test3_testcase 23 failed"); passed = false; } if (!Single.IsNaN(f_test3_f("test3_op1") % f_arr3d_test3_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test3_testcase 24 failed"); passed = false; } if (!Single.IsNaN(cl1.f_cl_test3_op1 % f_l_test3_op2)) { Console.WriteLine("Test3_testcase 25 failed"); passed = false; } if (!Single.IsNaN(cl1.f_cl_test3_op1 % f_s_test3_op2)) { Console.WriteLine("Test3_testcase 26 failed"); passed = false; } if (!Single.IsNaN(cl1.f_cl_test3_op1 % f_test3_f("test3_op2"))) { Console.WriteLine("Test3_testcase 27 failed"); passed = false; } if (!Single.IsNaN(cl1.f_cl_test3_op1 % cl1.f_cl_test3_op2)) { Console.WriteLine("Test3_testcase 28 failed"); passed = false; } if (!Single.IsNaN(cl1.f_cl_test3_op1 % vt1.f_vt_test3_op2)) { Console.WriteLine("Test3_testcase 29 failed"); passed = false; } if (!Single.IsNaN(cl1.f_cl_test3_op1 % f_arr1d_test3_op2[0])) { Console.WriteLine("Test3_testcase 30 failed"); passed = false; } if (!Single.IsNaN(cl1.f_cl_test3_op1 % f_arr2d_test3_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test3_testcase 31 failed"); passed = false; } if (!Single.IsNaN(cl1.f_cl_test3_op1 % f_arr3d_test3_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test3_testcase 32 failed"); passed = false; } if (!Single.IsNaN(vt1.f_vt_test3_op1 % f_l_test3_op2)) { Console.WriteLine("Test3_testcase 33 failed"); passed = false; } if (!Single.IsNaN(vt1.f_vt_test3_op1 % f_s_test3_op2)) { Console.WriteLine("Test3_testcase 34 failed"); passed = false; } if (!Single.IsNaN(vt1.f_vt_test3_op1 % f_test3_f("test3_op2"))) { Console.WriteLine("Test3_testcase 35 failed"); passed = false; } if (!Single.IsNaN(vt1.f_vt_test3_op1 % cl1.f_cl_test3_op2)) { Console.WriteLine("Test3_testcase 36 failed"); passed = false; } if (!Single.IsNaN(vt1.f_vt_test3_op1 % vt1.f_vt_test3_op2)) { Console.WriteLine("Test3_testcase 37 failed"); passed = false; } if (!Single.IsNaN(vt1.f_vt_test3_op1 % f_arr1d_test3_op2[0])) { Console.WriteLine("Test3_testcase 38 failed"); passed = false; } if (!Single.IsNaN(vt1.f_vt_test3_op1 % f_arr2d_test3_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test3_testcase 39 failed"); passed = false; } if (!Single.IsNaN(vt1.f_vt_test3_op1 % f_arr3d_test3_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test3_testcase 40 failed"); passed = false; } if (!Single.IsNaN(f_arr1d_test3_op1[1] % f_l_test3_op2)) { Console.WriteLine("Test3_testcase 41 failed"); passed = false; } if (!Single.IsNaN(f_arr1d_test3_op1[1] % f_s_test3_op2)) { Console.WriteLine("Test3_testcase 42 failed"); passed = false; } if (!Single.IsNaN(f_arr1d_test3_op1[1] % f_test3_f("test3_op2"))) { Console.WriteLine("Test3_testcase 43 failed"); passed = false; } if (!Single.IsNaN(f_arr1d_test3_op1[1] % cl1.f_cl_test3_op2)) { Console.WriteLine("Test3_testcase 44 failed"); passed = false; } if (!Single.IsNaN(f_arr1d_test3_op1[1] % vt1.f_vt_test3_op2)) { Console.WriteLine("Test3_testcase 45 failed"); passed = false; } if (!Single.IsNaN(f_arr1d_test3_op1[1] % f_arr1d_test3_op2[0])) { Console.WriteLine("Test3_testcase 46 failed"); passed = false; } if (!Single.IsNaN(f_arr1d_test3_op1[1] % f_arr2d_test3_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test3_testcase 47 failed"); passed = false; } if (!Single.IsNaN(f_arr1d_test3_op1[1] % f_arr3d_test3_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test3_testcase 48 failed"); passed = false; } if (!Single.IsNaN(f_arr2d_test3_op1[index[0, 1], index[1, 0]] % f_l_test3_op2)) { Console.WriteLine("Test3_testcase 49 failed"); passed = false; } if (!Single.IsNaN(f_arr2d_test3_op1[index[0, 1], index[1, 0]] % f_s_test3_op2)) { Console.WriteLine("Test3_testcase 50 failed"); passed = false; } if (!Single.IsNaN(f_arr2d_test3_op1[index[0, 1], index[1, 0]] % f_test3_f("test3_op2"))) { Console.WriteLine("Test3_testcase 51 failed"); passed = false; } if (!Single.IsNaN(f_arr2d_test3_op1[index[0, 1], index[1, 0]] % cl1.f_cl_test3_op2)) { Console.WriteLine("Test3_testcase 52 failed"); passed = false; } if (!Single.IsNaN(f_arr2d_test3_op1[index[0, 1], index[1, 0]] % vt1.f_vt_test3_op2)) { Console.WriteLine("Test3_testcase 53 failed"); passed = false; } if (!Single.IsNaN(f_arr2d_test3_op1[index[0, 1], index[1, 0]] % f_arr1d_test3_op2[0])) { Console.WriteLine("Test3_testcase 54 failed"); passed = false; } if (!Single.IsNaN(f_arr2d_test3_op1[index[0, 1], index[1, 0]] % f_arr2d_test3_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test3_testcase 55 failed"); passed = false; } if (!Single.IsNaN(f_arr2d_test3_op1[index[0, 1], index[1, 0]] % f_arr3d_test3_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test3_testcase 56 failed"); passed = false; } if (!Single.IsNaN(f_arr3d_test3_op1[index[0, 0], 0, index[1, 1]] % f_l_test3_op2)) { Console.WriteLine("Test3_testcase 57 failed"); passed = false; } if (!Single.IsNaN(f_arr3d_test3_op1[index[0, 0], 0, index[1, 1]] % f_s_test3_op2)) { Console.WriteLine("Test3_testcase 58 failed"); passed = false; } if (!Single.IsNaN(f_arr3d_test3_op1[index[0, 0], 0, index[1, 1]] % f_test3_f("test3_op2"))) { Console.WriteLine("Test3_testcase 59 failed"); passed = false; } if (!Single.IsNaN(f_arr3d_test3_op1[index[0, 0], 0, index[1, 1]] % cl1.f_cl_test3_op2)) { Console.WriteLine("Test3_testcase 60 failed"); passed = false; } if (!Single.IsNaN(f_arr3d_test3_op1[index[0, 0], 0, index[1, 1]] % vt1.f_vt_test3_op2)) { Console.WriteLine("Test3_testcase 61 failed"); passed = false; } if (!Single.IsNaN(f_arr3d_test3_op1[index[0, 0], 0, index[1, 1]] % f_arr1d_test3_op2[0])) { Console.WriteLine("Test3_testcase 62 failed"); passed = false; } if (!Single.IsNaN(f_arr3d_test3_op1[index[0, 0], 0, index[1, 1]] % f_arr2d_test3_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test3_testcase 63 failed"); passed = false; } if (!Single.IsNaN(f_arr3d_test3_op1[index[0, 0], 0, index[1, 1]] % f_arr3d_test3_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test3_testcase 64 failed"); passed = false; } } if (!passed) { Console.WriteLine("FAILED"); return 1; } else { Console.WriteLine("PASSED"); return 100; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // namespace System.Reflection.Emit { using System; using System.Globalization; using TextWriter = System.IO.TextWriter; using System.Diagnostics.SymbolStore; using System.Runtime.InteropServices; using System.Reflection; using System.Collections; using System.Collections.Generic; using System.Security.Permissions; using System.Threading; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; using System.Security; internal class DynamicILGenerator : ILGenerator { internal DynamicScope m_scope; private int m_methodSigToken; internal unsafe DynamicILGenerator(DynamicMethod method, byte[] methodSignature, int size) : base(method, size) { m_scope = new DynamicScope(); m_methodSigToken = m_scope.GetTokenFor(methodSignature); } [System.Security.SecurityCritical] // auto-generated internal void GetCallableMethod(RuntimeModule module, DynamicMethod dm) { dm.m_methodHandle = ModuleHandle.GetDynamicMethod(dm, module, m_methodBuilder.Name, (byte[])m_scope[m_methodSigToken], new DynamicResolver(this)); } #if FEATURE_APPX private bool ProfileAPICheck { get { return ((DynamicMethod)m_methodBuilder).ProfileAPICheck; } } #endif // FEATURE_APPX // *** ILGenerator api *** public override LocalBuilder DeclareLocal(Type localType, bool pinned) { LocalBuilder localBuilder; if (localType == null) throw new ArgumentNullException("localType"); Contract.EndContractBlock(); RuntimeType rtType = localType as RuntimeType; if (rtType == null) throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType")); #if FEATURE_APPX if (ProfileAPICheck && (rtType.InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", rtType.FullName)); #endif localBuilder = new LocalBuilder(m_localCount, localType, m_methodBuilder); // add the localType to local signature m_localSignature.AddArgument(localType, pinned); m_localCount++; return localBuilder; } // // // Token resolution calls // // [System.Security.SecuritySafeCritical] // auto-generated public override void Emit(OpCode opcode, MethodInfo meth) { if (meth == null) throw new ArgumentNullException("meth"); Contract.EndContractBlock(); int stackchange = 0; int token = 0; DynamicMethod dynMeth = meth as DynamicMethod; if (dynMeth == null) { RuntimeMethodInfo rtMeth = meth as RuntimeMethodInfo; if (rtMeth == null) throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeMethodInfo"), "meth"); RuntimeType declaringType = rtMeth.GetRuntimeType(); if (declaringType != null && (declaringType.IsGenericType || declaringType.IsArray)) token = GetTokenFor(rtMeth, declaringType); else token = GetTokenFor(rtMeth); } else { // rule out not allowed operations on DynamicMethods if (opcode.Equals(OpCodes.Ldtoken) || opcode.Equals(OpCodes.Ldftn) || opcode.Equals(OpCodes.Ldvirtftn)) { throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOpCodeOnDynamicMethod")); } token = GetTokenFor(dynMeth); } EnsureCapacity(7); InternalEmit(opcode); if (opcode.StackBehaviourPush == StackBehaviour.Varpush && meth.ReturnType != typeof(void)) { stackchange++; } if (opcode.StackBehaviourPop == StackBehaviour.Varpop) { stackchange -= meth.GetParametersNoCopy().Length; } // Pop the "this" parameter if the method is non-static, // and the instruction is not newobj/ldtoken/ldftn. if (!meth.IsStatic && !(opcode.Equals(OpCodes.Newobj) || opcode.Equals(OpCodes.Ldtoken) || opcode.Equals(OpCodes.Ldftn))) { stackchange--; } UpdateStackSize(opcode, stackchange); PutInteger4(token); } [System.Runtime.InteropServices.ComVisible(true)] public override void Emit(OpCode opcode, ConstructorInfo con) { if (con == null) throw new ArgumentNullException("con"); Contract.EndContractBlock(); RuntimeConstructorInfo rtConstructor = con as RuntimeConstructorInfo; if (rtConstructor == null) throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeMethodInfo"), "con"); RuntimeType declaringType = rtConstructor.GetRuntimeType(); int token; if (declaringType != null && (declaringType.IsGenericType || declaringType.IsArray)) // need to sort out the stack size story token = GetTokenFor(rtConstructor, declaringType); else token = GetTokenFor(rtConstructor); EnsureCapacity(7); InternalEmit(opcode); // need to sort out the stack size story UpdateStackSize(opcode, 1); PutInteger4(token); } public override void Emit(OpCode opcode, Type type) { if (type == null) throw new ArgumentNullException("type"); Contract.EndContractBlock(); RuntimeType rtType = type as RuntimeType; if (rtType == null) throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType")); int token = GetTokenFor(rtType); EnsureCapacity(7); InternalEmit(opcode); PutInteger4(token); } public override void Emit(OpCode opcode, FieldInfo field) { if (field == null) throw new ArgumentNullException("field"); Contract.EndContractBlock(); RuntimeFieldInfo runtimeField = field as RuntimeFieldInfo; if (runtimeField == null) throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeFieldInfo"), "field"); int token; if (field.DeclaringType == null) token = GetTokenFor(runtimeField); else token = GetTokenFor(runtimeField, runtimeField.GetRuntimeType()); EnsureCapacity(7); InternalEmit(opcode); PutInteger4(token); } public override void Emit(OpCode opcode, String str) { if (str == null) throw new ArgumentNullException("str"); Contract.EndContractBlock(); int tempVal = GetTokenForString(str); EnsureCapacity(7); InternalEmit(opcode); PutInteger4(tempVal); } // // // Signature related calls (vararg, calli) // // [System.Security.SecuritySafeCritical] // overrides SC public override void EmitCalli(OpCode opcode, CallingConventions callingConvention, Type returnType, Type[] parameterTypes, Type[] optionalParameterTypes) { int stackchange = 0; SignatureHelper sig; if (optionalParameterTypes != null) if ((callingConvention & CallingConventions.VarArgs) == 0) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotAVarArgCallingConvention")); sig = GetMemberRefSignature(callingConvention, returnType, parameterTypes, optionalParameterTypes); EnsureCapacity(7); Emit(OpCodes.Calli); // If there is a non-void return type, push one. if (returnType != typeof(void)) stackchange++; // Pop off arguments if any. if (parameterTypes != null) stackchange -= parameterTypes.Length; // Pop off vararg arguments. if (optionalParameterTypes != null) stackchange -= optionalParameterTypes.Length; // Pop the this parameter if the method has a this parameter. if ((callingConvention & CallingConventions.HasThis) == CallingConventions.HasThis) stackchange--; // Pop the native function pointer. stackchange--; UpdateStackSize(OpCodes.Calli, stackchange); int token = GetTokenForSig(sig.GetSignature(true)); PutInteger4(token); } public override void EmitCalli(OpCode opcode, CallingConvention unmanagedCallConv, Type returnType, Type[] parameterTypes) { int stackchange = 0; int cParams = 0; int i; SignatureHelper sig; if (parameterTypes != null) cParams = parameterTypes.Length; sig = SignatureHelper.GetMethodSigHelper(unmanagedCallConv, returnType); if (parameterTypes != null) for (i = 0; i < cParams; i++) sig.AddArgument(parameterTypes[i]); // If there is a non-void return type, push one. if (returnType != typeof(void)) stackchange++; // Pop off arguments if any. if (parameterTypes != null) stackchange -= cParams; // Pop the native function pointer. stackchange--; UpdateStackSize(OpCodes.Calli, stackchange); EnsureCapacity(7); Emit(OpCodes.Calli); int token = GetTokenForSig(sig.GetSignature(true)); PutInteger4(token); } [System.Security.SecuritySafeCritical] // auto-generated public override void EmitCall(OpCode opcode, MethodInfo methodInfo, Type[] optionalParameterTypes) { if (methodInfo == null) throw new ArgumentNullException("methodInfo"); if (!(opcode.Equals(OpCodes.Call) || opcode.Equals(OpCodes.Callvirt) || opcode.Equals(OpCodes.Newobj))) throw new ArgumentException(Environment.GetResourceString("Argument_NotMethodCallOpcode"), "opcode"); if (methodInfo.ContainsGenericParameters) throw new ArgumentException(Environment.GetResourceString("Argument_GenericsInvalid"), "methodInfo"); if (methodInfo.DeclaringType != null && methodInfo.DeclaringType.ContainsGenericParameters) throw new ArgumentException(Environment.GetResourceString("Argument_GenericsInvalid"), "methodInfo"); Contract.EndContractBlock(); int tk; int stackchange = 0; tk = GetMemberRefToken(methodInfo, optionalParameterTypes); EnsureCapacity(7); InternalEmit(opcode); // Push the return value if there is one. if (methodInfo.ReturnType != typeof(void)) stackchange++; // Pop the parameters. stackchange -= methodInfo.GetParameterTypes().Length; // Pop the this parameter if the method is non-static and the // instruction is not newobj. if (!(methodInfo is SymbolMethod) && methodInfo.IsStatic == false && !(opcode.Equals(OpCodes.Newobj))) stackchange--; // Pop the optional parameters off the stack. if (optionalParameterTypes != null) stackchange -= optionalParameterTypes.Length; UpdateStackSize(opcode, stackchange); PutInteger4(tk); } public override void Emit(OpCode opcode, SignatureHelper signature) { if (signature == null) throw new ArgumentNullException("signature"); Contract.EndContractBlock(); int stackchange = 0; EnsureCapacity(7); InternalEmit(opcode); // The only IL instruction that has VarPop behaviour, that takes a // Signature token as a parameter is calli. Pop the parameters and // the native function pointer. To be conservative, do not pop the // this pointer since this information is not easily derived from // SignatureHelper. if (opcode.StackBehaviourPop == StackBehaviour.Varpop) { Contract.Assert(opcode.Equals(OpCodes.Calli), "Unexpected opcode encountered for StackBehaviour VarPop."); // Pop the arguments.. stackchange -= signature.ArgumentCount; // Pop native function pointer off the stack. stackchange--; UpdateStackSize(opcode, stackchange); } int token = GetTokenForSig(signature.GetSignature(true)); ; PutInteger4(token); } // // // Exception related generation // // public override Label BeginExceptionBlock() { return base.BeginExceptionBlock(); } public override void EndExceptionBlock() { base.EndExceptionBlock(); } public override void BeginExceptFilterBlock() { throw new NotSupportedException(Environment.GetResourceString("InvalidOperation_NotAllowedInDynamicMethod")); } public override void BeginCatchBlock(Type exceptionType) { if (CurrExcStackCount == 0) throw new NotSupportedException(Environment.GetResourceString("Argument_NotInExceptionBlock")); Contract.EndContractBlock(); __ExceptionInfo current = CurrExcStack[CurrExcStackCount - 1]; RuntimeType rtType = exceptionType as RuntimeType; if (current.GetCurrentState() == __ExceptionInfo.State_Filter) { if (exceptionType != null) { throw new ArgumentException(Environment.GetResourceString("Argument_ShouldNotSpecifyExceptionType")); } this.Emit(OpCodes.Endfilter); } else { // execute this branch if previous clause is Catch or Fault if (exceptionType == null) throw new ArgumentNullException("exceptionType"); if (rtType == null) throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType")); Label endLabel = current.GetEndLabel(); this.Emit(OpCodes.Leave, endLabel); // if this is a catch block the exception will be pushed on the stack and we need to update the stack info UpdateStackSize(OpCodes.Nop, 1); } current.MarkCatchAddr(ILOffset, exceptionType); // this is relying on too much implementation details of the base and so it's highly breaking // Need to have a more integreted story for exceptions current.m_filterAddr[current.m_currentCatch - 1] = GetTokenFor(rtType); } public override void BeginFaultBlock() { throw new NotSupportedException(Environment.GetResourceString("InvalidOperation_NotAllowedInDynamicMethod")); } public override void BeginFinallyBlock() { base.BeginFinallyBlock(); } // // // debugger related calls. // // [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems. public override void UsingNamespace(String ns) { throw new NotSupportedException(Environment.GetResourceString("InvalidOperation_NotAllowedInDynamicMethod")); } [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems. public override void MarkSequencePoint(ISymbolDocumentWriter document, int startLine, int startColumn, int endLine, int endColumn) { throw new NotSupportedException(Environment.GetResourceString("InvalidOperation_NotAllowedInDynamicMethod")); } public override void BeginScope() { throw new NotSupportedException(Environment.GetResourceString("InvalidOperation_NotAllowedInDynamicMethod")); } public override void EndScope() { throw new NotSupportedException(Environment.GetResourceString("InvalidOperation_NotAllowedInDynamicMethod")); } [System.Security.SecurityCritical] // auto-generated private int GetMemberRefToken(MethodBase methodInfo, Type[] optionalParameterTypes) { Type[] parameterTypes; if (optionalParameterTypes != null && (methodInfo.CallingConvention & CallingConventions.VarArgs) == 0) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotAVarArgCallingConvention")); RuntimeMethodInfo rtMeth = methodInfo as RuntimeMethodInfo; DynamicMethod dm = methodInfo as DynamicMethod; if (rtMeth == null && dm == null) throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeMethodInfo"), "methodInfo"); ParameterInfo[] paramInfo = methodInfo.GetParametersNoCopy(); if (paramInfo != null && paramInfo.Length != 0) { parameterTypes = new Type[paramInfo.Length]; for (int i = 0; i < paramInfo.Length; i++) parameterTypes[i] = paramInfo[i].ParameterType; } else { parameterTypes = null; } SignatureHelper sig = GetMemberRefSignature(methodInfo.CallingConvention, MethodBuilder.GetMethodBaseReturnType(methodInfo), parameterTypes, optionalParameterTypes); if (rtMeth != null) return GetTokenForVarArgMethod(rtMeth, sig); else return GetTokenForVarArgMethod(dm, sig); } [System.Security.SecurityCritical] // auto-generated internal override SignatureHelper GetMemberRefSignature( CallingConventions call, Type returnType, Type[] parameterTypes, Type[] optionalParameterTypes) { int cParams; int i; SignatureHelper sig; if (parameterTypes == null) cParams = 0; else cParams = parameterTypes.Length; sig = SignatureHelper.GetMethodSigHelper(call, returnType); for (i = 0; i < cParams; i++) sig.AddArgument(parameterTypes[i]); if (optionalParameterTypes != null && optionalParameterTypes.Length != 0) { // add the sentinel sig.AddSentinel(); for (i = 0; i < optionalParameterTypes.Length; i++) sig.AddArgument(optionalParameterTypes[i]); } return sig; } internal override void RecordTokenFixup() { // DynamicMethod doesn't need fixup. } #region GetTokenFor helpers private int GetTokenFor(RuntimeType rtType) { #if FEATURE_APPX if (ProfileAPICheck && (rtType.InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", rtType.FullName)); #endif return m_scope.GetTokenFor(rtType.TypeHandle); } private int GetTokenFor(RuntimeFieldInfo runtimeField) { #if FEATURE_APPX if (ProfileAPICheck) { RtFieldInfo rtField = runtimeField as RtFieldInfo; if (rtField != null && (rtField.InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", rtField.FullName)); } #endif return m_scope.GetTokenFor(runtimeField.FieldHandle); } private int GetTokenFor(RuntimeFieldInfo runtimeField, RuntimeType rtType) { #if FEATURE_APPX if (ProfileAPICheck) { RtFieldInfo rtField = runtimeField as RtFieldInfo; if (rtField != null && (rtField.InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", rtField.FullName)); if ((rtType.InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", rtType.FullName)); } #endif return m_scope.GetTokenFor(runtimeField.FieldHandle, rtType.TypeHandle); } private int GetTokenFor(RuntimeConstructorInfo rtMeth) { #if FEATURE_APPX if (ProfileAPICheck && (rtMeth.InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", rtMeth.FullName)); #endif return m_scope.GetTokenFor(rtMeth.MethodHandle); } private int GetTokenFor(RuntimeConstructorInfo rtMeth, RuntimeType rtType) { #if FEATURE_APPX if (ProfileAPICheck) { if ((rtMeth.InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", rtMeth.FullName)); if ((rtType.InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", rtType.FullName)); } #endif return m_scope.GetTokenFor(rtMeth.MethodHandle, rtType.TypeHandle); } private int GetTokenFor(RuntimeMethodInfo rtMeth) { #if FEATURE_APPX if (ProfileAPICheck && (rtMeth.InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", rtMeth.FullName)); #endif return m_scope.GetTokenFor(rtMeth.MethodHandle); } private int GetTokenFor(RuntimeMethodInfo rtMeth, RuntimeType rtType) { #if FEATURE_APPX if (ProfileAPICheck) { if ((rtMeth.InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", rtMeth.FullName)); if ((rtType.InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", rtType.FullName)); } #endif return m_scope.GetTokenFor(rtMeth.MethodHandle, rtType.TypeHandle); } private int GetTokenFor(DynamicMethod dm) { return m_scope.GetTokenFor(dm); } private int GetTokenForVarArgMethod(RuntimeMethodInfo rtMeth, SignatureHelper sig) { #if FEATURE_APPX if (ProfileAPICheck && (rtMeth.InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", rtMeth.FullName)); #endif VarArgMethod varArgMeth = new VarArgMethod(rtMeth, sig); return m_scope.GetTokenFor(varArgMeth); } private int GetTokenForVarArgMethod(DynamicMethod dm, SignatureHelper sig) { VarArgMethod varArgMeth = new VarArgMethod(dm, sig); return m_scope.GetTokenFor(varArgMeth); } private int GetTokenForString(String s) { return m_scope.GetTokenFor(s); } private int GetTokenForSig(byte[] sig) { return m_scope.GetTokenFor(sig); } #endregion } internal class DynamicResolver : Resolver { #region Private Data Members private __ExceptionInfo[] m_exceptions; private byte[] m_exceptionHeader; private DynamicMethod m_method; private byte[] m_code; private byte[] m_localSignature; private int m_stackSize; private DynamicScope m_scope; #endregion #region Internal Methods internal DynamicResolver(DynamicILGenerator ilGenerator) { m_stackSize = ilGenerator.GetMaxStackSize(); m_exceptions = ilGenerator.GetExceptions(); m_code = ilGenerator.BakeByteArray(); m_localSignature = ilGenerator.m_localSignature.InternalGetSignatureArray(); m_scope = ilGenerator.m_scope; m_method = (DynamicMethod)ilGenerator.m_methodBuilder; m_method.m_resolver = this; } #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #endif internal DynamicResolver(DynamicILInfo dynamicILInfo) { m_stackSize = dynamicILInfo.MaxStackSize; m_code = dynamicILInfo.Code; m_localSignature = dynamicILInfo.LocalSignature; m_exceptionHeader = dynamicILInfo.Exceptions; //m_exceptions = dynamicILInfo.Exceptions; m_scope = dynamicILInfo.DynamicScope; m_method = dynamicILInfo.DynamicMethod; m_method.m_resolver = this; } // // We can destroy the unmanaged part of dynamic method only after the managed part is definitely gone and thus // nobody can call the dynamic method anymore. A call to finalizer alone does not guarantee that the managed // part is gone. A malicious code can keep a reference to DynamicMethod in long weak reference that survives finalization, // or we can be running during shutdown where everything is finalized. // // The unmanaged resolver keeps a reference to the managed resolver in long weak handle. If the long weak handle // is null, we can be sure that the managed part of the dynamic method is definitely gone and that it is safe to // destroy the unmanaged part. (Note that the managed finalizer has to be on the same object that the long weak handle // points to in order for this to work.) Unfortunately, we can not perform the above check when out finalizer // is called - the long weak handle won't be cleared yet. Instead, we create a helper scout object that will attempt // to do the destruction after next GC. // // The finalization does not have to be done using CriticalFinalizerObject. We have to go over all DynamicMethodDescs // during AppDomain shutdown anyway to avoid leaks e.g. if somebody stores reference to DynamicMethod in static. // ~DynamicResolver() { DynamicMethod method = m_method; if (method == null) return; if (method.m_methodHandle == null) return; DestroyScout scout = null; try { scout = new DestroyScout(); } catch { // We go over all DynamicMethodDesc during AppDomain shutdown and make sure // that everything associated with them is released. So it is ok to skip reregistration // for finalization during appdomain shutdown if (!Environment.HasShutdownStarted && !AppDomain.CurrentDomain.IsFinalizingForUnload()) { // Try again later. GC.ReRegisterForFinalize(this); } return; } // We can never ever have two active destroy scouts for the same method. We need to initialize the scout // outside the try/reregister block to avoid possibility of reregistration for finalization with active scout. scout.m_methodHandle = method.m_methodHandle.Value; } private class DestroyScout { internal RuntimeMethodHandleInternal m_methodHandle; [System.Security.SecuritySafeCritical] // auto-generated ~DestroyScout() { if (m_methodHandle.IsNullHandle()) return; // It is not safe to destroy the method if the managed resolver is alive. if (RuntimeMethodHandle.GetResolver(m_methodHandle) != null) { if (!Environment.HasShutdownStarted && !AppDomain.CurrentDomain.IsFinalizingForUnload()) { // Somebody might have been holding a reference on us via weak handle. // We will keep trying. It will be hopefully released eventually. GC.ReRegisterForFinalize(this); } return; } RuntimeMethodHandle.Destroy(m_methodHandle); } } // Keep in sync with vm/dynamicmethod.h [Flags] internal enum SecurityControlFlags { Default = 0x0, SkipVisibilityChecks = 0x1, RestrictedSkipVisibilityChecks = 0x2, HasCreationContext = 0x4, CanSkipCSEvaluation = 0x8, } internal override RuntimeType GetJitContext(ref int securityControlFlags) { RuntimeType typeOwner; SecurityControlFlags flags = SecurityControlFlags.Default; if (m_method.m_restrictedSkipVisibility) flags |= SecurityControlFlags.RestrictedSkipVisibilityChecks; else if (m_method.m_skipVisibility) flags |= SecurityControlFlags.SkipVisibilityChecks; typeOwner = m_method.m_typeOwner; #if FEATURE_COMPRESSEDSTACK if (m_method.m_creationContext != null) { flags |= SecurityControlFlags.HasCreationContext; if(m_method.m_creationContext.CanSkipEvaluation) { flags |= SecurityControlFlags.CanSkipCSEvaluation; } } #endif // FEATURE_COMPRESSEDSTACK securityControlFlags = (int)flags; return typeOwner; } private static int CalculateNumberOfExceptions(__ExceptionInfo[] excp) { int num = 0; if (excp == null) return 0; for (int i = 0; i < excp.Length; i++) num += excp[i].GetNumberOfCatches(); return num; } internal override byte[] GetCodeInfo( ref int stackSize, ref int initLocals, ref int EHCount) { stackSize = m_stackSize; if (m_exceptionHeader != null && m_exceptionHeader.Length != 0) { if (m_exceptionHeader.Length < 4) throw new FormatException(); byte header = m_exceptionHeader[0]; if ((header & 0x40) != 0) // Fat { byte[] size = new byte[4]; for (int q = 0; q < 3; q++) size[q] = m_exceptionHeader[q + 1]; EHCount = (BitConverter.ToInt32(size, 0) - 4) / 24; } else EHCount = (m_exceptionHeader[1] - 2) / 12; } else { EHCount = CalculateNumberOfExceptions(m_exceptions); } initLocals = (m_method.InitLocals) ? 1 : 0; return m_code; } internal override byte[] GetLocalsSignature() { return m_localSignature; } internal override unsafe byte[] GetRawEHInfo() { return m_exceptionHeader; } [System.Security.SecurityCritical] // auto-generated internal override unsafe void GetEHInfo(int excNumber, void* exc) { CORINFO_EH_CLAUSE* exception = (CORINFO_EH_CLAUSE*)exc; for (int i = 0; i < m_exceptions.Length; i++) { int excCount = m_exceptions[i].GetNumberOfCatches(); if (excNumber < excCount) { // found the right exception block exception->Flags = m_exceptions[i].GetExceptionTypes()[excNumber]; exception->TryOffset = m_exceptions[i].GetStartAddress(); if ((exception->Flags & __ExceptionInfo.Finally) != __ExceptionInfo.Finally) exception->TryLength = m_exceptions[i].GetEndAddress() - exception->TryOffset; else exception->TryLength = m_exceptions[i].GetFinallyEndAddress() - exception->TryOffset; exception->HandlerOffset = m_exceptions[i].GetCatchAddresses()[excNumber]; exception->HandlerLength = m_exceptions[i].GetCatchEndAddresses()[excNumber] - exception->HandlerOffset; // this is cheating because the filter address is the token of the class only for light code gen exception->ClassTokenOrFilterOffset = m_exceptions[i].GetFilterAddresses()[excNumber]; break; } excNumber -= excCount; } } internal override String GetStringLiteral(int token) { return m_scope.GetString(token); } #if FEATURE_COMPRESSEDSTACK internal override CompressedStack GetSecurityContext() { return m_method.m_creationContext; } #endif // FEATURE_COMPRESSEDSTACK [System.Security.SecurityCritical] internal override void ResolveToken(int token, out IntPtr typeHandle, out IntPtr methodHandle, out IntPtr fieldHandle) { typeHandle = new IntPtr(); methodHandle = new IntPtr(); fieldHandle = new IntPtr(); Object handle = m_scope[token]; if (handle == null) throw new InvalidProgramException(); if (handle is RuntimeTypeHandle) { typeHandle = ((RuntimeTypeHandle)handle).Value; return; } if (handle is RuntimeMethodHandle) { methodHandle = ((RuntimeMethodHandle)handle).Value; return; } if (handle is RuntimeFieldHandle) { fieldHandle = ((RuntimeFieldHandle)handle).Value; return; } DynamicMethod dm = handle as DynamicMethod; if (dm != null) { methodHandle = dm.GetMethodDescriptor().Value; return; } GenericMethodInfo gmi = handle as GenericMethodInfo; if (gmi != null) { methodHandle = gmi.m_methodHandle.Value; typeHandle = gmi.m_context.Value; return; } GenericFieldInfo gfi = handle as GenericFieldInfo; if (gfi != null) { fieldHandle = gfi.m_fieldHandle.Value; typeHandle = gfi.m_context.Value; return; } VarArgMethod vaMeth = handle as VarArgMethod; if (vaMeth != null) { if (vaMeth.m_dynamicMethod == null) { methodHandle = vaMeth.m_method.MethodHandle.Value; typeHandle = vaMeth.m_method.GetDeclaringTypeInternal().GetTypeHandleInternal().Value; } else methodHandle = vaMeth.m_dynamicMethod.GetMethodDescriptor().Value; return; } } internal override byte[] ResolveSignature(int token, int fromMethod) { return m_scope.ResolveSignature(token, fromMethod); } internal override MethodInfo GetDynamicMethod() { return m_method.GetMethodInfo(); } #endregion } #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #endif [System.Runtime.InteropServices.ComVisible(true)] public class DynamicILInfo { #region Private Data Members private DynamicMethod m_method; private DynamicScope m_scope; private byte[] m_exceptions; private byte[] m_code; private byte[] m_localSignature; private int m_maxStackSize; private int m_methodSignature; #endregion #region Constructor internal DynamicILInfo(DynamicScope scope, DynamicMethod method, byte[] methodSignature) { m_method = method; m_scope = scope; m_methodSignature = m_scope.GetTokenFor(methodSignature); m_exceptions = EmptyArray<Byte>.Value; m_code = EmptyArray<Byte>.Value; m_localSignature = EmptyArray<Byte>.Value; } #endregion #region Internal Methods [System.Security.SecurityCritical] // auto-generated internal void GetCallableMethod(RuntimeModule module, DynamicMethod dm) { dm.m_methodHandle = ModuleHandle.GetDynamicMethod(dm, module, m_method.Name, (byte[])m_scope[m_methodSignature], new DynamicResolver(this)); } internal byte[] LocalSignature { get { if (m_localSignature == null) m_localSignature = SignatureHelper.GetLocalVarSigHelper().InternalGetSignatureArray(); return m_localSignature; } } internal byte[] Exceptions { get { return m_exceptions; } } internal byte[] Code { get { return m_code; } } internal int MaxStackSize { get { return m_maxStackSize; } } #endregion #region Public ILGenerator Methods public DynamicMethod DynamicMethod { get { return m_method; } } internal DynamicScope DynamicScope { get { return m_scope; } } public void SetCode(byte[] code, int maxStackSize) { m_code = (code != null) ? (byte[])code.Clone() : EmptyArray<Byte>.Value; m_maxStackSize = maxStackSize; } [System.Security.SecurityCritical] // auto-generated [CLSCompliant(false)] public unsafe void SetCode(byte* code, int codeSize, int maxStackSize) { if (codeSize < 0) throw new ArgumentOutOfRangeException("codeSize", Environment.GetResourceString("ArgumentOutOfRange_GenericPositive")); if (codeSize > 0 && code == null) throw new ArgumentNullException("code"); Contract.EndContractBlock(); m_code = new byte[codeSize]; for (int i = 0; i < codeSize; i++) { m_code[i] = *code; code++; } m_maxStackSize = maxStackSize; } public void SetExceptions(byte[] exceptions) { m_exceptions = (exceptions != null) ? (byte[])exceptions.Clone() : EmptyArray<Byte>.Value; } [System.Security.SecurityCritical] // auto-generated [CLSCompliant(false)] public unsafe void SetExceptions(byte* exceptions, int exceptionsSize) { if (exceptionsSize < 0) throw new ArgumentOutOfRangeException("exceptionsSize", Environment.GetResourceString("ArgumentOutOfRange_GenericPositive")); if (exceptionsSize > 0 && exceptions == null) throw new ArgumentNullException("exceptions"); Contract.EndContractBlock(); m_exceptions = new byte[exceptionsSize]; for (int i = 0; i < exceptionsSize; i++) { m_exceptions[i] = *exceptions; exceptions++; } } public void SetLocalSignature(byte[] localSignature) { m_localSignature = (localSignature != null) ? (byte[])localSignature.Clone() : EmptyArray<Byte>.Value; } [System.Security.SecurityCritical] // auto-generated [CLSCompliant(false)] public unsafe void SetLocalSignature(byte* localSignature, int signatureSize) { if (signatureSize < 0) throw new ArgumentOutOfRangeException("signatureSize", Environment.GetResourceString("ArgumentOutOfRange_GenericPositive")); if (signatureSize > 0 && localSignature == null) throw new ArgumentNullException("localSignature"); Contract.EndContractBlock(); m_localSignature = new byte[signatureSize]; for (int i = 0; i < signatureSize; i++) { m_localSignature[i] = *localSignature; localSignature++; } } #endregion #region Public Scope Methods [System.Security.SecuritySafeCritical] // auto-generated public int GetTokenFor(RuntimeMethodHandle method) { return DynamicScope.GetTokenFor(method); } public int GetTokenFor(DynamicMethod method) { return DynamicScope.GetTokenFor(method); } public int GetTokenFor(RuntimeMethodHandle method, RuntimeTypeHandle contextType) { return DynamicScope.GetTokenFor(method, contextType); } public int GetTokenFor(RuntimeFieldHandle field) { return DynamicScope.GetTokenFor(field); } public int GetTokenFor(RuntimeFieldHandle field, RuntimeTypeHandle contextType) { return DynamicScope.GetTokenFor(field, contextType); } public int GetTokenFor(RuntimeTypeHandle type) { return DynamicScope.GetTokenFor(type); } public int GetTokenFor(string literal) { return DynamicScope.GetTokenFor(literal); } public int GetTokenFor(byte[] signature) { return DynamicScope.GetTokenFor(signature); } #endregion } internal class DynamicScope { #region Private Data Members internal List<Object> m_tokens; #endregion #region Constructor internal unsafe DynamicScope() { m_tokens = new List<Object>(); m_tokens.Add(null); } #endregion #region Internal Methods internal object this[int token] { get { token &= 0x00FFFFFF; if (token < 0 || token > m_tokens.Count) return null; return m_tokens[token]; } } internal int GetTokenFor(VarArgMethod varArgMethod) { m_tokens.Add(varArgMethod); return m_tokens.Count - 1 | (int)MetadataTokenType.MemberRef; } internal string GetString(int token) { return this[token] as string; } internal byte[] ResolveSignature(int token, int fromMethod) { if (fromMethod == 0) return (byte[])this[token]; VarArgMethod vaMethod = this[token] as VarArgMethod; if (vaMethod == null) return null; return vaMethod.m_signature.GetSignature(true); } #endregion #region Public Methods [System.Security.SecuritySafeCritical] // auto-generated public int GetTokenFor(RuntimeMethodHandle method) { IRuntimeMethodInfo methodReal = method.GetMethodInfo(); RuntimeMethodHandleInternal rmhi = methodReal.Value; if (methodReal != null && !RuntimeMethodHandle.IsDynamicMethod(rmhi)) { RuntimeType type = RuntimeMethodHandle.GetDeclaringType(rmhi); if ((type != null) && RuntimeTypeHandle.HasInstantiation(type)) { // Do we really need to retrieve this much info just to throw an exception? MethodBase m = RuntimeType.GetMethodBase(methodReal); Type t = m.DeclaringType.GetGenericTypeDefinition(); throw new ArgumentException(String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("Argument_MethodDeclaringTypeGenericLcg"), m, t)); } } m_tokens.Add(method); return m_tokens.Count - 1 | (int)MetadataTokenType.MethodDef; } public int GetTokenFor(RuntimeMethodHandle method, RuntimeTypeHandle typeContext) { m_tokens.Add(new GenericMethodInfo(method, typeContext)); return m_tokens.Count - 1 | (int)MetadataTokenType.MethodDef; } public int GetTokenFor(DynamicMethod method) { m_tokens.Add(method); return m_tokens.Count - 1 | (int)MetadataTokenType.MethodDef; } public int GetTokenFor(RuntimeFieldHandle field) { m_tokens.Add(field); return m_tokens.Count - 1 | (int)MetadataTokenType.FieldDef; } public int GetTokenFor(RuntimeFieldHandle field, RuntimeTypeHandle typeContext) { m_tokens.Add(new GenericFieldInfo(field, typeContext)); return m_tokens.Count - 1 | (int)MetadataTokenType.FieldDef; } public int GetTokenFor(RuntimeTypeHandle type) { m_tokens.Add(type); return m_tokens.Count - 1 | (int)MetadataTokenType.TypeDef; } public int GetTokenFor(string literal) { m_tokens.Add(literal); return m_tokens.Count - 1 | (int)MetadataTokenType.String; } public int GetTokenFor(byte[] signature) { m_tokens.Add(signature); return m_tokens.Count - 1 | (int)MetadataTokenType.Signature; } #endregion } internal sealed class GenericMethodInfo { internal RuntimeMethodHandle m_methodHandle; internal RuntimeTypeHandle m_context; internal GenericMethodInfo(RuntimeMethodHandle methodHandle, RuntimeTypeHandle context) { m_methodHandle = methodHandle; m_context = context; } } internal sealed class GenericFieldInfo { internal RuntimeFieldHandle m_fieldHandle; internal RuntimeTypeHandle m_context; internal GenericFieldInfo(RuntimeFieldHandle fieldHandle, RuntimeTypeHandle context) { m_fieldHandle = fieldHandle; m_context = context; } } internal sealed class VarArgMethod { internal RuntimeMethodInfo m_method; internal DynamicMethod m_dynamicMethod; internal SignatureHelper m_signature; internal VarArgMethod(DynamicMethod dm, SignatureHelper signature) { m_dynamicMethod = dm; m_signature = signature; } internal VarArgMethod(RuntimeMethodInfo method, SignatureHelper signature) { m_method = method; m_signature = signature; } } }
// 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. //#define XMLCHARTYPE_GEN_RESOURCE // generate the character properties into XmlCharType.bin using System.IO; using System.Reflection; using System.Threading; using System.Diagnostics; namespace System.Xml { /// <include file='doc\XmlCharType.uex' path='docs/doc[@for="XmlCharType"]/*' /> /// <internalonly/> /// <devdoc> /// The XmlCharType class is used for quick character type recognition /// which is optimized for the first 127 ascii characters. /// </devdoc> unsafe internal struct XmlCharType { // Surrogate constants internal const int SurHighStart = 0xd800; // 1101 10xx internal const int SurHighEnd = 0xdbff; internal const int SurLowStart = 0xdc00; // 1101 11xx internal const int SurLowEnd = 0xdfff; internal const int SurMask = 0xfc00; // 1111 11xx // Characters defined in the XML 1.0 Fourth Edition // Whitespace chars -- Section 2.3 [3] // Letters -- Appendix B [84] // Starting NCName characters -- Section 2.3 [5] (Starting Name characters without ':') // NCName characters -- Section 2.3 [4] (Name characters without ':') // Character data characters -- Section 2.2 [2] // PubidChar ::= #x20 | #xD | #xA | [a-zA-Z0-9] | [-'()+,./:=?;!*#@$_%] Section 2.3 of spec internal const int fWhitespace = 1; internal const int fLetter = 2; internal const int fNCStartNameSC = 4; internal const int fNCNameSC = 8; internal const int fCharData = 16; internal const int fNCNameXml4e = 32; internal const int fText = 64; internal const int fAttrValue = 128; // bitmap for public ID characters - 1 bit per character 0x0 - 0x80; no character > 0x80 is a PUBLIC ID char private const string s_PublicIdBitmap = "\u2400\u0000\uffbb\uafff\uffff\u87ff\ufffe\u07ff"; // size of XmlCharType table private const uint CharPropertiesSize = (uint)char.MaxValue + 1; // static lock for XmlCharType class private static object s_Lock; private static object StaticLock { get { if (s_Lock == null) { object o = new object(); Interlocked.CompareExchange<object>(ref s_Lock, o, null); } return s_Lock; } } private static volatile byte* s_CharProperties; internal byte* charProperties; private static void InitInstance() { lock (StaticLock) { if (s_CharProperties != null) { return; } UnmanagedMemoryStream memStream = (UnmanagedMemoryStream)typeof(XmlWriter).Assembly.GetManifestResourceStream("XmlCharType.bin"); Debug.Assert(memStream.Length == CharPropertiesSize); byte* chProps = memStream.PositionPointer; Thread.MemoryBarrier(); // For weak memory models (IA64) s_CharProperties = chProps; } } private XmlCharType(byte* charProperties) { Debug.Assert(s_CharProperties != null); this.charProperties = charProperties; } public static XmlCharType Instance { get { if (s_CharProperties == null) { InitInstance(); } return new XmlCharType(s_CharProperties); } } // NOTE: This method will not be inlined (because it uses byte* charProperties) public bool IsWhiteSpace(char ch) { return (charProperties[ch] & fWhitespace) != 0; } public bool IsExtender(char ch) { return (ch == 0xb7); } // NOTE: This method will not be inlined (because it uses byte* charProperties) public bool IsNCNameSingleChar(char ch) { return (charProperties[ch] & fNCNameSC) != 0; } // NOTE: This method will not be inlined (because it uses byte* charProperties) public bool IsStartNCNameSingleChar(char ch) { return (charProperties[ch] & fNCStartNameSC) != 0; } public bool IsNameSingleChar(char ch) { return IsNCNameSingleChar(ch) || ch == ':'; } public bool IsStartNameSingleChar(char ch) { return IsStartNCNameSingleChar(ch) || ch == ':'; } // NOTE: This method will not be inlined (because it uses byte* charProperties) public bool IsCharData(char ch) { return (charProperties[ch] & fCharData) != 0; } // [13] PubidChar ::= #x20 | #xD | #xA | [a-zA-Z0-9] | [-'()+,./:=?;!*#@$_%] Section 2.3 of spec public bool IsPubidChar(char ch) { if (ch < (char)0x80) { return (s_PublicIdBitmap[ch >> 4] & (1 << (ch & 0xF))) != 0; } return false; } // TextChar = CharData - { 0xA, 0xD, '<', '&', ']' } // NOTE: This method will not be inlined (because it uses byte* charProperties) internal bool IsTextChar(char ch) { return (charProperties[ch] & fText) != 0; } // AttrValueChar = CharData - { 0xA, 0xD, 0x9, '<', '>', '&', '\'', '"' } // NOTE: This method will not be inlined (because it uses byte* charProperties) internal bool IsAttributeValueChar(char ch) { return (charProperties[ch] & fAttrValue) != 0; } // XML 1.0 Fourth Edition definitions // // NOTE: This method will not be inlined (because it uses byte* charProperties) public bool IsLetter(char ch) { return (charProperties[ch] & fLetter) != 0; } // NOTE: This method will not be inlined (because it uses byte* charProperties) // This method uses the XML 4th edition name character ranges public bool IsNCNameCharXml4e(char ch) { return (charProperties[ch] & fNCNameXml4e) != 0; } // This method uses the XML 4th edition name character ranges public bool IsStartNCNameCharXml4e(char ch) { return IsLetter(ch) || ch == '_'; } // This method uses the XML 4th edition name character ranges public bool IsNameCharXml4e(char ch) { return IsNCNameCharXml4e(ch) || ch == ':'; } // This method uses the XML 4th edition name character ranges public bool IsStartNameCharXml4e(char ch) { return IsStartNCNameCharXml4e(ch) || ch == ':'; } // Digit methods public static bool IsDigit(char ch) { return InRange(ch, 0x30, 0x39); } public static bool IsHexDigit(char ch) { return InRange(ch, 0x30, 0x39) || InRange(ch, 'a', 'f') || InRange(ch, 'A', 'F'); } // Surrogate methods internal static bool IsHighSurrogate(int ch) { return InRange(ch, SurHighStart, SurHighEnd); } internal static bool IsLowSurrogate(int ch) { return InRange(ch, SurLowStart, SurLowEnd); } internal static bool IsSurrogate(int ch) { return InRange(ch, SurHighStart, SurLowEnd); } internal static int CombineSurrogateChar(int lowChar, int highChar) { return (lowChar - SurLowStart) | ((highChar - SurHighStart) << 10) + 0x10000; } internal static void SplitSurrogateChar(int combinedChar, out char lowChar, out char highChar) { int v = combinedChar - 0x10000; lowChar = (char)(SurLowStart + v % 1024); highChar = (char)(SurHighStart + v / 1024); } internal bool IsOnlyWhitespace(string str) { return IsOnlyWhitespaceWithPos(str) == -1; } // Character checking on strings internal int IsOnlyWhitespaceWithPos(string str) { if (str != null) { for (int i = 0; i < str.Length; i++) { if ((charProperties[str[i]] & fWhitespace) == 0) { return i; } } } return -1; } internal int IsOnlyCharData(string str) { if (str != null) { for (int i = 0; i < str.Length; i++) { if ((charProperties[str[i]] & fCharData) == 0) { if (i + 1 >= str.Length || !(XmlCharType.IsHighSurrogate(str[i]) && XmlCharType.IsLowSurrogate(str[i + 1]))) { return i; } else { i++; } } } } return -1; } static internal bool IsOnlyDigits(string str, int startPos, int len) { Debug.Assert(str != null); Debug.Assert(startPos + len <= str.Length); Debug.Assert(startPos <= str.Length); for (int i = startPos; i < startPos + len; i++) { if (!IsDigit(str[i])) { return false; } } return true; } static internal bool IsOnlyDigits(char[] chars, int startPos, int len) { Debug.Assert(chars != null); Debug.Assert(startPos + len <= chars.Length); Debug.Assert(startPos <= chars.Length); for (int i = startPos; i < startPos + len; i++) { if (!IsDigit(chars[i])) { return false; } } return true; } internal int IsPublicId(string str) { if (str != null) { for (int i = 0; i < str.Length; i++) { if (!IsPubidChar(str[i])) { return i; } } } return -1; } // This method tests whether a value is in a given range with just one test; start and end should be constants private static bool InRange(int value, int start, int end) { Debug.Assert(start <= end); return (uint)(value - start) <= (uint)(end - start); } #if XMLCHARTYPE_GEN_RESOURCE // // Code for generating XmlCharType.bin table and s_PublicIdBitmap // // build command line: csc XmlCharType.cs /d:XMLCHARTYPE_GEN_RESOURCE // public static void Main( string[] args ) { try { InitInstance(); // generate PublicId bitmap ushort[] bitmap = new ushort[0x80 >> 4]; for (int i = 0; i < s_PublicID.Length; i += 2) { for (int j = s_PublicID[i], last = s_PublicID[i + 1]; j <= last; j++) { bitmap[j >> 4] |= (ushort)(1 << (j & 0xF)); } } Console.Write("private const string s_PublicIdBitmap = \""); for (int i = 0; i < bitmap.Length; i++) { Console.Write("\\u{0:x4}", bitmap[i]); } Console.WriteLine("\";"); Console.WriteLine(); string fileName = ( args.Length == 0 ) ? "XmlCharType.bin" : args[0]; Console.Write( "Writing XmlCharType character properties to {0}...", fileName ); FileStream fs = new FileStream( fileName, FileMode.Create ); for ( int i = 0; i < CharPropertiesSize; i += 4096 ) { fs.Write( s_CharProperties, i, 4096 ); } fs.Close(); Console.WriteLine( "done." ); } catch ( Exception e ) { Console.WriteLine(); Console.WriteLine( "Exception: {0}", e.Message ); } } #endif } }
#if NETFX_CORE using MarkerMetro.Unity.WinLegacy.Security.Cryptography; using System.Threading.Tasks; using System.Globalization; #endif using Facebook; using System; using System.Collections.Generic; using MarkerMetro.Unity.WinIntegration; #if NETFX_CORE using Facebook.Client; using Windows.Storage; using MarkerMetro.Unity.WinIntegration.Storage; #endif using System.Linq; namespace MarkerMetro.Unity.WinIntegration.Facebook { /// <summary> /// Unity Facebook implementation /// </summary> public static class FBNative { #if NETFX_CORE private const string FBID_KEY = "FBID"; private const string FBNAME_KEY = "FBNAME"; private static Session _fbSessionClient; private static HideUnityDelegate _onHideUnity; public static string AccessToken { get { if (_fbSessionClient != null && _fbSessionClient.CurrentAccessTokenData != null) { return _fbSessionClient.CurrentAccessTokenData.AccessToken; } else { return null; } } } #else public static string AccessToken { get; private set; } #endif public static string UserId { get; private set; } public static string UserName { get; private set; } /// <summary> /// FB.Init as per Unity SDK /// </summary> /// <remarks> /// https://developers.facebook.com/docs/unity/reference/current/FB.Init /// </remarks> public static void Init(InitDelegate onInitComplete, string appId, HideUnityDelegate onHideUnity) { #if WINDOWS_PHONE_APP Dispatcher.InvokeOnUIThread(() => { _onHideUnity = onHideUnity; _fbSessionClient = Session.ActiveSession; Session.AppId = appId; Task.Run(async () => { // check and extend token if required await Session.CheckAndExtendTokenIfNeeded(); if (IsLoggedIn) { UserId = Settings.GetString(FBID_KEY); UserName = Settings.GetString(FBNAME_KEY); } if (onInitComplete != null) { Dispatcher.InvokeOnAppThread(() => { onInitComplete(); }); } }); if (onHideUnity != null) throw new NotSupportedException("onHideUnity is not currently supported at this time."); }); #else throw new PlatformNotSupportedException(""); #endif } public static void Logout() { #if NETFX_CORE _fbSessionClient.Logout(); #else throw new PlatformNotSupportedException(""); #endif } public static void Login(string permissions, FacebookDelegate callback) { #if NETFX_CORE Session.OnFacebookAuthenticationFinished = (AccessTokenData data) => { var result = new FBResult() { Text = (data == null || String.IsNullOrEmpty(data.AccessToken)) ? "Fail" : "Success", Error = (data == null || String.IsNullOrEmpty(data.AccessToken)) ? "Error" : null }; if (data == null || String.IsNullOrEmpty(data.AccessToken)) { if (callback != null) { Dispatcher.InvokeOnAppThread(() => { callback(result); }); } } else { GetCurrentUser((user) => { UserId = user.Id; UserName = user.Name; Settings.Set(FBID_KEY, UserId); Settings.Set(FBNAME_KEY, UserName); if (callback != null) { Dispatcher.InvokeOnAppThread(() => { callback(result); }); } }); } }; Dispatcher.InvokeOnUIThread(() => { _fbSessionClient.LoginWithBehavior(permissions, FacebookLoginBehavior.LoginBehaviorMobileInternetExplorerOnly); }); #else throw new PlatformNotSupportedException(""); #endif } /// <summary> /// For platforms that do not support dynamic cast it to either IDictionary<string, object> if json object or IList<object> if array. /// For primitive types cast it to bool, string, dobule or long depending on the type. /// Reference: http://facebooksdk.net/docs/making-asynchronous-requests/#1 /// </summary> public static void API( string endpoint, HttpMethod method, FacebookDelegate callback, object parameters = null) { #if NETFX_CORE Task.Run(async () => { FacebookClient fb = new FacebookClient(_fbSessionClient.CurrentAccessTokenData.AccessToken); FBResult fbResult = null; try { object apiCall; if (method == HttpMethod.GET) { apiCall = await fb.GetTaskAsync(endpoint, parameters); } else if (method == HttpMethod.POST) { apiCall = await fb.PostTaskAsync(endpoint, parameters); } else { apiCall = await fb.DeleteTaskAsync(endpoint); } if (apiCall != null) { fbResult = new FBResult(); fbResult.Text = apiCall.ToString(); fbResult.Json = apiCall as JsonObject; } } catch (Exception ex) { fbResult = new FBResult(); fbResult.Error = ex.Message; } if (callback != null) { Dispatcher.InvokeOnAppThread(() => { callback(fbResult); }); } }); #else throw new PlatformNotSupportedException(""); #endif } /// <summary> /// Get current logged in user info /// </summary> public static void GetCurrentUser(Action<FBUser> callback) { #if NETFX_CORE API("me", HttpMethod.GET, (result) => { var data = (IDictionary<string, object>)result.Json; var me = new GraphUser(data); if (callback != null) callback(new FBUser(me)); }); #else throw new PlatformNotSupportedException(""); #endif } /// <summary> /// Show Request Dialog. /// filters, excludeIds and maxRecipients are not currently supported at this time. /// </summary> public static void AppRequest( string message, string[] to = null, string filters = "", string[] excludeIds = null, int? maxRecipients = null, string data = "", string title = "", FacebookDelegate callback = null ) { #if WINDOWS_PHONE_APP if (!IsLoggedIn) { // not logged in if (callback != null) Dispatcher.InvokeOnAppThread(() => { callback(new FBResult() { Error = "Not Logged In" }); }); return; } Session.OnFacebookAppRequestFinished = (result) => { if (callback != null) Dispatcher.InvokeOnAppThread(() => { callback(new FBResult() { Text = result.Text, Error = result.Error, Json = result.Json }); }); }; // pass in params to facebook client's app request Dispatcher.InvokeOnUIThread(() => { Session.ShowAppRequestDialogViaBrowser(message, title, to != null ? to.ToList<string>() : null, data); }); // throw not supported exception when user passed in parameters not supported currently if (!string.IsNullOrWhiteSpace(filters) || excludeIds != null || maxRecipients != null) throw new NotSupportedException("filters, excludeIds and maxRecipients are not currently supported at this time."); #else throw new PlatformNotSupportedException(""); #endif } /// <summary> /// Show the Feed Dialog. /// mediaSource, actionName, actionLink, reference and properties are not currently supported at this time. /// </summary> public static void Feed( string toId = "", string link = "", string linkName = "", string linkCaption = "", string linkDescription = "", string picture = "", string mediaSource = "", string actionName = "", string actionLink = "", string reference = "", Dictionary<string, string[]> properties = null, FacebookDelegate callback = null) { #if WINDOWS_PHONE_APP if (!IsLoggedIn) { // not logged in if (callback != null) Dispatcher.InvokeOnAppThread(() => { callback(new FBResult() { Error = "Not Logged In" }); }); return; } Session.OnFacebookFeedFinished = (result) => { if (callback != null) Dispatcher.InvokeOnAppThread(() => { callback(new FBResult() { Text = result.Text, Error = result.Error, Json = result.Json }); }); }; // pass in params to facebook client's app request Dispatcher.InvokeOnUIThread(() => { Session.ShowFeedDialogViaBrowser(toId, link, linkName, linkCaption, linkDescription, picture); }); // throw not supported exception when user passed in parameters not supported currently if (!string.IsNullOrWhiteSpace(mediaSource) || !string.IsNullOrWhiteSpace(actionName) || !string.IsNullOrWhiteSpace(actionLink) || !string.IsNullOrWhiteSpace(reference) || properties != null) throw new NotSupportedException("mediaSource, actionName, actionLink, reference and properties are not currently supported at this time."); #else throw new PlatformNotSupportedException(""); #endif } // additional methods added for convenience public static bool IsLoggedIn { get { #if NETFX_CORE return _fbSessionClient != null && !String.IsNullOrEmpty(_fbSessionClient.CurrentAccessTokenData.AccessToken); #else throw new PlatformNotSupportedException("CheckAndExtendTokenIfNeeded"); #endif } } #if NETFX_CORE // return whether back button pressed event is consumed by facebook for closing the dialog public static bool BackButtonPressed() { if (_fbSessionClient != null && Session.IsDialogOpen) { Session.CloseWebDialog(); return true; } else return false; } #endif // check whether facebook is initialized public static bool IsInitialized { get { #if NETFX_CORE return _fbSessionClient != null; #else throw new PlatformNotSupportedException(""); #endif } } public static void MapUri (Uri uri) { #if WINDOWS_PHONE_APP Dispatcher.InvokeOnAppThread(() => { (new FacebookUriMapper()).MapUri(uri); }); #endif } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests.LinkedFileDiffMerging { public partial class LinkedFileDiffMergingTests { [Fact] [Trait(Traits.Feature, Traits.Features.LinkedFileDiffMerging)] public void TestIdenticalChanges() { TestLinkedFileSet( "x", new List<string> { "y", "y" }, @"y", LanguageNames.CSharp); } [Fact] [Trait(Traits.Feature, Traits.Features.LinkedFileDiffMerging)] public void TestChangesInOnlyOneFile() { TestLinkedFileSet( "a b c d e", new List<string> { "a b c d e", "a z c z e" }, @"a z c z e", LanguageNames.CSharp); } [Fact] [Trait(Traits.Feature, Traits.Features.LinkedFileDiffMerging)] public void TestIsolatedChangesInBothFiles() { TestLinkedFileSet( "a b c d e", new List<string> { "a z c d e", "a b c z e" }, @"a z c z e", LanguageNames.CSharp); } [Fact] [Trait(Traits.Feature, Traits.Features.LinkedFileDiffMerging)] public void TestIdenticalEditAfterIsolatedChanges() { TestLinkedFileSet( "a b c d e", new List<string> { "a zzz c xx e", "a b c xx e" }, @"a zzz c xx e", LanguageNames.CSharp); } [Fact] [Trait(Traits.Feature, Traits.Features.LinkedFileDiffMerging)] public void TestOneConflict() { TestLinkedFileSet( "a b c d e", new List<string> { "a b y d e", "a b z d e" }, @" /* " + string.Format(WorkspacesResources.Unmerged_change_from_project_0, "ProjectName1") + @" " + WorkspacesResources.Before_colon + @" a b c d e " + WorkspacesResources.After_colon + @" a b z d e */ a b y d e", LanguageNames.CSharp); } [Fact] [Trait(Traits.Feature, Traits.Features.LinkedFileDiffMerging)] public void TestTwoConflictsOnSameLine() { TestLinkedFileSet( "a b c d e", new List<string> { "a q1 c z1 e", "a q2 c z2 e" }, @" /* " + string.Format(WorkspacesResources.Unmerged_change_from_project_0, "ProjectName1") + @" " + WorkspacesResources.Before_colon + @" a b c d e " + WorkspacesResources.After_colon + @" a q2 c z2 e */ a q1 c z1 e", LanguageNames.CSharp); } [Fact] [Trait(Traits.Feature, Traits.Features.LinkedFileDiffMerging)] public void TestTwoConflictsOnAdjacentLines() { TestLinkedFileSet( @"One Two Three Four", new List<string> { @"One TwoY ThreeY Four", @"One TwoZ ThreeZ Four" }, @"One /* " + string.Format(WorkspacesResources.Unmerged_change_from_project_0, "ProjectName1") + @" " + WorkspacesResources.Before_colon + @" Two Three " + WorkspacesResources.After_colon + @" TwoZ ThreeZ */ TwoY ThreeY Four", LanguageNames.CSharp); } [Fact] [Trait(Traits.Feature, Traits.Features.LinkedFileDiffMerging)] public void TestTwoConflictsOnSeparatedLines() { TestLinkedFileSet( @"One Two Three Four Five", new List<string> { @"One TwoY Three FourY Five", @"One TwoZ Three FourZ Five" }, @"One /* " + string.Format(WorkspacesResources.Unmerged_change_from_project_0, "ProjectName1") + @" " + WorkspacesResources.Before_colon + @" Two " + WorkspacesResources.After_colon + @" TwoZ */ TwoY Three /* " + string.Format(WorkspacesResources.Unmerged_change_from_project_0, "ProjectName1") + @" " + WorkspacesResources.Before_colon + @" Four " + WorkspacesResources.After_colon + @" FourZ */ FourY Five", LanguageNames.CSharp); } [Fact] [Trait(Traits.Feature, Traits.Features.LinkedFileDiffMerging)] public void TestManyLinkedFilesWithOverlappingChange() { TestLinkedFileSet( @"A", new List<string> { @"A", @"B", @"C", @"", }, @" /* " + string.Format(WorkspacesResources.Unmerged_change_from_project_0, "ProjectName2") + @" " + WorkspacesResources.Before_colon + @" A " + WorkspacesResources.After_colon + @" C */ /* " + string.Format(WorkspacesResources.Unmerged_change_from_project_0, "ProjectName3") + @" " + WorkspacesResources.Removed_colon + @" A */ B", LanguageNames.CSharp); } [Fact] [Trait(Traits.Feature, Traits.Features.LinkedFileDiffMerging)] public void TestCommentsAddedCodeCSharp() { TestLinkedFileSet( @"", new List<string> { @"A", @"B", }, @" /* " + string.Format(WorkspacesResources.Unmerged_change_from_project_0, "ProjectName1") + @" " + WorkspacesResources.Added_colon + @" B */ A", LanguageNames.CSharp); } [Fact] [Trait(Traits.Feature, Traits.Features.LinkedFileDiffMerging)] public void TestCommentsAddedCodeVB() { TestLinkedFileSet( @"", new List<string> { @"A", @"B", }, @" ' " + string.Format(WorkspacesResources.Unmerged_change_from_project_0, "ProjectName1") + @" ' " + WorkspacesResources.Added_colon + @" ' B A", LanguageNames.VisualBasic); } [Fact] [Trait(Traits.Feature, Traits.Features.LinkedFileDiffMerging)] public void TestCommentsRemovedCodeCSharp() { TestLinkedFileSet( @"A", new List<string> { @"B", @"", }, @" /* " + string.Format(WorkspacesResources.Unmerged_change_from_project_0, "ProjectName1") + @" " + WorkspacesResources.Removed_colon + @" A */ B", LanguageNames.CSharp); } [Fact] [Trait(Traits.Feature, Traits.Features.LinkedFileDiffMerging)] public void TestCommentsRemovedCodeVB() { TestLinkedFileSet( @"A", new List<string> { @"B", @"", }, @" ' " + string.Format(WorkspacesResources.Unmerged_change_from_project_0, "ProjectName1") + @" ' " + WorkspacesResources.Removed_colon + @" ' A B", LanguageNames.VisualBasic); } } }
using Microsoft.CodeAnalysis; using System; using System.CodeDom; using System.CodeDom.Compiler; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Xml; namespace RoslynIntellisense { public static class GenericExtensions { public static string NormalizeAsPath(this string obj) { return obj.Replace("\\", "_") .Replace("/", "_") .Replace(":", "_") .Replace("*", "_") .Replace("?", "_") .Replace("\"", "_") .Replace("<", "_") .Replace(">", "_") .Replace("|", "_"); } public static IEnumerable<T> ForEach<T>(this IEnumerable<T> items, Action<T> action) { if (items != null) foreach (var item in items) action(item); return items; } public static string ToLiteral(this string input) { using (var writer = new StringWriter()) using (var provider = CodeDomProvider.CreateProvider("CSharp")) { provider.GenerateCodeFromExpression(new CodePrimitiveExpression(input), writer, null); return writer.ToString(); } } public static string ToLiteral(this char input) { using (var writer = new StringWriter()) using (var provider = CodeDomProvider.CreateProvider("CSharp")) { provider.GenerateCodeFromExpression(new CodePrimitiveExpression(input), writer, null); return writer.ToString(); } } public static bool IsVbFile(this string file) { return file.EndsWith(".vb", StringComparison.InvariantCultureIgnoreCase); } public static int LineNumberOf(this string text, int pos) { return text.Take(pos).Count(c => c == '\n') + 1; } public static string GetLineAt(this string text, int pos) { int start = text.Substring(0, pos).LastIndexOf('\n'); int end = text.IndexOf('\n', pos); return text.Substring(start, end - start).Trim(); } public static int LastLineStart(this string text) { var start = text.LastIndexOf('\n'); //<doc>\r\n<declaration> if (start != -1) return start + Environment.NewLine.Length; return 0; } public static bool HasText(this string text) { return !string.IsNullOrEmpty(text); } public static bool HasAny<T>(this IEnumerable<T> items) { return items != null && items.Any(); } public static IEnumerable<T> Append<T>(this IEnumerable<T> items, T item) { return items.Concat(new[] { item }); } public static T To<T>(this object obj) { return (T)obj; } public static T As<T>(this object obj) where T : class { return obj as T; } public static string PathJoin(this string path, params string[] items) { return Path.Combine(new[] { path }.Concat(items).ToArray()); } public static string GetDirName(this string path) { return Path.GetDirectoryName(path); } public static string GetFileExtension(this string path) { return Path.GetExtension(path); } public static string JoinBy(this IEnumerable<string> items, string separator = "") { return string.Join(separator, items.ToArray()); } public static bool OneOf(this string text, params string[] items) { return items.Any(x => x == text); } public static T Prev<T>(this List<T> list, T item) { int index = list.IndexOf(item); if (index > 0) return list[index - 1]; else return default(T); } public static string[] GetLines(this string data, string lineBreak = "\n") { return data.Split(new string[] { lineBreak }, StringSplitOptions.None); } public static int GetWordStartOf(this string text, int offset) { if (text[offset] != '.') //we may be at the partially complete word for (int i = offset - 1; i >= 0; i--) if (Autocompleter.Delimiters.Contains(text[i])) return i + 1; return offset; } public static object GetProp(this object obj, string name) { var property = obj.GetType().GetProperty(name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); if (property == null) throw new Exception("ReflectionExtensions: cannot find property " + name); return property.GetValue(obj, null); } public static bool HasExtension(this string file, string extension) { return string.Compare(Path.GetExtension(file), extension, true) == 0; } public static string ShrinkNamespaces(this string statement, params string[] knownNamespaces) { //statement format: "{<namespace_name>}.type" string result = statement; foreach (var item in knownNamespaces.Select(x => "{" + x + "}.")) result = result.Replace(item, ""); return result.Replace("{", "") .Replace("}", ""); } } internal static class XmlDocExtensions { public static string Shrink(this string text) { //should be replaced with RegEx (eventually) string retval = text.Replace(" \r\n", " ").Replace("\r\n ", " ").Replace("\r\n", " ").Replace("\t", " "); //Sandcastle has problem processing <para/> with the content having line breaks. This leads to the //multiple joined spaces. The following is a simplistic solution for this. string newRetval; while (true) { newRetval = retval.Replace(" ", " "); if (newRetval.Length != retval.Length) retval = newRetval; else return newRetval; } } public static string GetCrefAttribute(this XmlTextReader reader) { try { string typeName = reader.GetAttribute("cref"); if (typeName != null) { if (typeName.StartsWith("T:") || typeName.StartsWith("F:") || typeName.StartsWith("M:")) typeName = typeName.Substring(2); } else { return reader.GetAttribute(0); } return typeName; } catch { return ""; } } //XmlTextReader "crawling style" reader fits better the purpose than a "read it all at once" XDocument public static string XmlToPlainText(this string xmlDoc, bool isReflectionDocument = false, bool ignoreExceptionsInfo = false, bool vsCodeEncoding = false) { //var root.XElement.Parse("<root>" + entity.Documentation.Xml.Text + "</root>"); if (!xmlDoc.HasText()) return ""; var sections = new List<string>(); var b = new StringBuilder(); try { using (var reader = new XmlTextReader(new StringReader("<root>" + xmlDoc + "</root>"))) { string lastElementName = null; var exceptionsStarted = false; var done = false; reader.XmlResolver = null; while (reader.Read() && !done) { var nodeType = reader.NodeType; switch (nodeType) { case XmlNodeType.Text: if (lastElementName == "summary") { if (vsCodeEncoding) b.Insert(0, "doc:" + reader.Value.Shrink()); else b.Insert(0, reader.Value.Shrink()); } else { if (exceptionsStarted) b.Append(" "); if (lastElementName == "code") b.Append(reader.Value); //need to preserve all formatting (line breaks and indents) else { //if (reflectionDocument) // b.Append(reader.Value.NormalizeLines()); //need to preserve line breaks but not indents //else if (!(exceptionsStarted && ignoreExceptionsInfo)) b.Append(reader.Value.Shrink()); } } break; case XmlNodeType.Element: { bool silentElement = false; switch (reader.Name) { case "filterpriority": reader.Skip(); break; case "root": case "summary": case "c": silentElement = true; break; case "paramref": silentElement = true; b.Append(reader.GetAttribute("name")); break; case "param": silentElement = true; if (vsCodeEncoding) { if (b.Length > 0 && b[b.Length - 1] != '\n') b.AppendLine(); b.AppendLine("param_label:" + reader.GetAttribute("name")); b.Append("param_doc:"); } else { b.AppendLine(); b.Append(reader.GetAttribute("name") + ": "); } break; case "para": silentElement = true; b.AppendLine(); break; case "remarks": b.AppendLine(); b.Append("Remarks: "); break; case "returns": silentElement = true; b.AppendLine(); b.Append("Returns: "); break; case "exception": { if (!exceptionsStarted) { b.AppendLine(); sections.Add(b.ToString().Trim()); b.Length = 0; if (!ignoreExceptionsInfo) b.AppendLine("Exceptions: "); else if (vsCodeEncoding) done = true; } exceptionsStarted = true; if (!ignoreExceptionsInfo && !reader.IsEmptyElement) { bool printExInfo = false; if (printExInfo) { b.Append(" " + reader.GetCrefAttribute() + ": "); } else { b.Append(" " + reader.GetCrefAttribute()); reader.Skip(); } } break; } case "see": silentElement = true; if (reader.IsEmptyElement) { b.Append(reader.GetCrefAttribute()); } else { reader.MoveToContent(); if (reader.HasValue) { b.Append(reader.Value); } else { b.Append(reader.GetCrefAttribute()); } } break; } if (!silentElement) b.AppendLine(); lastElementName = reader.Name; break; } case XmlNodeType.EndElement: { if (reader.Name == "summary") { b.AppendLine(); sections.Add(b.ToString().Trim()); b.Length = 0; } else if (reader.Name == "returns") { b.AppendLine(); sections.Add(b.ToString().Trim()); b.Length = 0; } break; } } } } sections.Add(b.ToString().Trim()); string sectionSeparator = (isReflectionDocument ? "\r\n--------------------------\r\n" : "\r\n\r\n"); if (vsCodeEncoding) sectionSeparator = "\r\n"; return string.Join(sectionSeparator, sections.Where(x => !string.IsNullOrEmpty(x)).ToArray()); } catch (XmlException) { return xmlDoc; } } } }
// Copyright (c) 2015, Outercurve Foundation. // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // - Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // - Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // - Neither the name of the Outercurve Foundation nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using System; using System.Data; using System.Web; using System.Collections; using System.Web.Services; using System.Web.Services.Protocols; using System.ComponentModel; using Microsoft.Web.Services3; using WebsitePanel.Providers; using WebsitePanel.Providers.OS; using WebsitePanel.Server.Utils; using WebsitePanel.Providers.DNS; using WebsitePanel.Providers.DomainLookup; using System.Collections.Generic; namespace WebsitePanel.Server { /// <summary> /// Summary description for OperatingSystem /// </summary> [WebService(Namespace = "http://smbsaas/websitepanel/server/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [Policy("ServerPolicy")] [ToolboxItem(false)] public class OperatingSystem : HostingServiceProviderWebService, IOperatingSystem { private IOperatingSystem OsProvider { get { return (IOperatingSystem)Provider; } } #region Files [WebMethod, SoapHeader("settings")] public string CreatePackageFolder(string initialPath) { try { Log.WriteStart("'{0}' CreatePackageFolder", ProviderSettings.ProviderName); string result = OsProvider.CreatePackageFolder(initialPath); Log.WriteEnd("'{0}' CreatePackageFolder", ProviderSettings.ProviderName); return result; } catch (Exception ex) { Log.WriteError(String.Format("'{0}' CreatePackageFolder", ProviderSettings.ProviderName), ex); throw; } } [WebMethod, SoapHeader("settings")] public bool FileExists(string path) { try { Log.WriteStart("'{0}' FileExists", ProviderSettings.ProviderName); bool result = OsProvider.FileExists(path); Log.WriteEnd("'{0}' FileExists", ProviderSettings.ProviderName); return result; } catch (Exception ex) { Log.WriteError(String.Format("'{0}' FileExists", ProviderSettings.ProviderName), ex); throw; } } [WebMethod, SoapHeader("settings")] public bool DirectoryExists(string path) { try { Log.WriteStart("'{0}' DirectoryExists", ProviderSettings.ProviderName); bool result = OsProvider.DirectoryExists(path); Log.WriteEnd("'{0}' DirectoryExists", ProviderSettings.ProviderName); return result; } catch (Exception ex) { Log.WriteError(String.Format("'{0}' DirectoryExists", ProviderSettings.ProviderName), ex); throw; } } [WebMethod, SoapHeader("settings")] public SystemFile GetFile(string path) { try { Log.WriteStart("'{0}' GetFile", ProviderSettings.ProviderName); SystemFile result = OsProvider.GetFile(path); Log.WriteEnd("'{0}' GetFile", ProviderSettings.ProviderName); return result; } catch (Exception ex) { Log.WriteError(String.Format("'{0}' GetFile", ProviderSettings.ProviderName), ex); throw; } } [WebMethod, SoapHeader("settings")] public SystemFile[] GetFiles(string path) { try { Log.WriteStart("'{0}' GetFiles", ProviderSettings.ProviderName); SystemFile[] result = OsProvider.GetFiles(path); Log.WriteEnd("'{0}' GetFiles", ProviderSettings.ProviderName); return result; } catch (Exception ex) { Log.WriteError(String.Format("'{0}' GetFiles", ProviderSettings.ProviderName), ex); throw; } } [WebMethod, SoapHeader("settings")] public SystemFile[] GetDirectoriesRecursive(string rootFolder, string path) { try { Log.WriteStart("'{0}' GetDirectoriesRecursive", ProviderSettings.ProviderName); SystemFile[] result = OsProvider.GetDirectoriesRecursive(rootFolder, path); Log.WriteEnd("'{0}' GetDirectoriesRecursive", ProviderSettings.ProviderName); return result; } catch (Exception ex) { Log.WriteError(String.Format("'{0}' GetDirectoriesRecursive", ProviderSettings.ProviderName), ex); throw; } } [WebMethod, SoapHeader("settings")] public SystemFile[] GetFilesRecursive(string rootFolder, string path) { try { Log.WriteStart("'{0}' GetFilesRecursive", ProviderSettings.ProviderName); SystemFile[] result = OsProvider.GetFilesRecursive(rootFolder, path); Log.WriteEnd("'{0}' GetFilesRecursive", ProviderSettings.ProviderName); return result; } catch (Exception ex) { Log.WriteError(String.Format("'{0}' GetFilesRecursive", ProviderSettings.ProviderName), ex); throw; } } [WebMethod, SoapHeader("settings")] public SystemFile[] GetFilesRecursiveByPattern(string rootFolder, string path, string pattern) { try { Log.WriteStart("'{0}' GetFilesRecursiveByPattern", ProviderSettings.ProviderName); SystemFile[] result = OsProvider.GetFilesRecursiveByPattern(rootFolder, path, pattern); Log.WriteEnd("'{0}' GetFilesRecursiveByPattern", ProviderSettings.ProviderName); return result; } catch (Exception ex) { Log.WriteError(String.Format("'{0}' GetFilesRecursiveByPattern", ProviderSettings.ProviderName), ex); throw; } } [WebMethod, SoapHeader("settings")] public byte[] GetFileBinaryContent(string path) { try { Log.WriteStart("'{0}' GetFileBinaryContent", ProviderSettings.ProviderName); byte[] result = OsProvider.GetFileBinaryContent(path); Log.WriteEnd("'{0}' GetFileBinaryContent", ProviderSettings.ProviderName); return result; } catch (Exception ex) { Log.WriteError(String.Format("'{0}' GetFileBinaryContent", ProviderSettings.ProviderName), ex); throw; } } [WebMethod, SoapHeader("settings")] public byte[] GetFileBinaryContentUsingEncoding(string path, string encoding) { try { Log.WriteStart("'{0}' GetFileBinaryContentUsingEncoding", ProviderSettings.ProviderName); byte[] result = OsProvider.GetFileBinaryContentUsingEncoding(path, encoding); Log.WriteEnd("'{0}' GetFileBinaryContentUsingEncoding", ProviderSettings.ProviderName); return result; } catch (Exception ex) { Log.WriteError(String.Format("'{0}' GetFileBinaryContentUsingEncoding", ProviderSettings.ProviderName), ex); throw; } } [WebMethod, SoapHeader("settings")] public byte[] GetFileBinaryChunk(string path, int offset, int length) { try { Log.WriteStart("'{0}' GetFileBinaryChunk", ProviderSettings.ProviderName); byte[] result = OsProvider.GetFileBinaryChunk(path, offset, length); Log.WriteEnd("'{0}' GetFileBinaryChunk", ProviderSettings.ProviderName); return result; } catch (Exception ex) { Log.WriteError(String.Format("'{0}' GetFileBinaryContent", ProviderSettings.ProviderName), ex); throw; } } [WebMethod, SoapHeader("settings")] public string GetFileTextContent(string path) { try { Log.WriteStart("'{0}' GetFileTextContent", ProviderSettings.ProviderName); string result = OsProvider.GetFileTextContent(path); Log.WriteEnd("'{0}' GetFileTextContent", ProviderSettings.ProviderName); return result; } catch (Exception ex) { Log.WriteError(String.Format("'{0}' GetFileTextContent", ProviderSettings.ProviderName), ex); throw; } } [WebMethod, SoapHeader("settings")] public void CreateFile(string path) { try { Log.WriteStart("'{0}' CreateFile", ProviderSettings.ProviderName); OsProvider.CreateFile(path); Log.WriteEnd("'{0}' CreateFile", ProviderSettings.ProviderName); } catch (Exception ex) { Log.WriteError(String.Format("'{0}' CreateFile", ProviderSettings.ProviderName), ex); throw; } } [WebMethod, SoapHeader("settings")] public void CreateDirectory(string path) { try { Log.WriteStart("'{0}' CreateDirectory", ProviderSettings.ProviderName); OsProvider.CreateDirectory(path); Log.WriteEnd("'{0}' CreateDirectory", ProviderSettings.ProviderName); } catch (Exception ex) { Log.WriteError(String.Format("'{0}' CreateDirectory", ProviderSettings.ProviderName), ex); throw; } } [WebMethod, SoapHeader("settings")] public void ChangeFileAttributes(string path, DateTime createdTime, DateTime changedTime) { try { Log.WriteStart("'{0}' ChangeFileAttributes", ProviderSettings.ProviderName); OsProvider.ChangeFileAttributes(path, createdTime, changedTime); Log.WriteEnd("'{0}' ChangeFileAttributes", ProviderSettings.ProviderName); } catch (Exception ex) { Log.WriteError(String.Format("'{0}' ChangeFileAttributes", ProviderSettings.ProviderName), ex); throw; } } [WebMethod, SoapHeader("settings")] public void DeleteFile(string path) { try { Log.WriteStart("'{0}' DeleteFile", ProviderSettings.ProviderName); OsProvider.DeleteFile(path); Log.WriteEnd("'{0}' DeleteFile", ProviderSettings.ProviderName); } catch (Exception ex) { Log.WriteError(String.Format("'{0}' DeleteFile", ProviderSettings.ProviderName), ex); throw; } } [WebMethod, SoapHeader("settings")] public void DeleteFiles(string[] files) { try { Log.WriteStart("'{0}' DeleteFiles", ProviderSettings.ProviderName); OsProvider.DeleteFiles(files); Log.WriteEnd("'{0}' DeleteFiles", ProviderSettings.ProviderName); } catch (Exception ex) { Log.WriteError(String.Format("'{0}' DeleteFiles", ProviderSettings.ProviderName), ex); throw; } } [WebMethod, SoapHeader("settings")] public void DeleteEmptyDirectories(string[] directories) { try { Log.WriteStart("'{0}' DeleteEmptyDirectories", ProviderSettings.ProviderName); OsProvider.DeleteEmptyDirectories(directories); Log.WriteEnd("'{0}' DeleteEmptyDirectories", ProviderSettings.ProviderName); } catch (Exception ex) { Log.WriteError(String.Format("'{0}' DeleteEmptyDirectories", ProviderSettings.ProviderName), ex); throw; } } [WebMethod, SoapHeader("settings")] public void UpdateFileBinaryContent(string path, byte[] content) { try { Log.WriteStart("'{0}' UpdateFileBinaryContent", ProviderSettings.ProviderName); OsProvider.UpdateFileBinaryContent(path, content); Log.WriteEnd("'{0}' UpdateFileBinaryContent", ProviderSettings.ProviderName); } catch (Exception ex) { Log.WriteError(String.Format("'{0}' UpdateFileBinaryContent", ProviderSettings.ProviderName), ex); throw; } } [WebMethod, SoapHeader("settings")] public void UpdateFileBinaryContentUsingEncoding(string path, byte[] content, string encoding) { try { Log.WriteStart("'{0}' UpdateFileBinaryContentUsingEncoding", ProviderSettings.ProviderName); OsProvider.UpdateFileBinaryContentUsingEncoding(path, content, encoding); Log.WriteEnd("'{0}' UpdateFileBinaryContentUsingEncoding", ProviderSettings.ProviderName); } catch (Exception ex) { Log.WriteError(String.Format("'{0}' UpdateFileBinaryContentUsingEncoding", ProviderSettings.ProviderName), ex); throw; } } [WebMethod, SoapHeader("settings")] public void AppendFileBinaryContent(string path, byte[] chunk) { try { Log.WriteStart("'{0}' AppendFileBinaryContent", ProviderSettings.ProviderName); OsProvider.AppendFileBinaryContent(path, chunk); Log.WriteEnd("'{0}' AppendFileBinaryContent", ProviderSettings.ProviderName); } catch (Exception ex) { Log.WriteError(String.Format("'{0}' AppendFileBinaryContent", ProviderSettings.ProviderName), ex); throw; } } [WebMethod, SoapHeader("settings")] public void UpdateFileTextContent(string path, string content) { try { Log.WriteStart("'{0}' UpdateFileTextContent", ProviderSettings.ProviderName); OsProvider.UpdateFileTextContent(path, content); Log.WriteEnd("'{0}' UpdateFileTextContent", ProviderSettings.ProviderName); } catch (Exception ex) { Log.WriteError(String.Format("'{0}' UpdateFileTextContent", ProviderSettings.ProviderName), ex); throw; } } [WebMethod, SoapHeader("settings")] public void MoveFile(string sourcePath, string destinationPath) { try { Log.WriteStart("'{0}' MoveFile", ProviderSettings.ProviderName); OsProvider.MoveFile(sourcePath, destinationPath); Log.WriteEnd("'{0}' MoveFile", ProviderSettings.ProviderName); } catch (Exception ex) { Log.WriteError(String.Format("'{0}' MoveFile", ProviderSettings.ProviderName), ex); throw; } } [WebMethod, SoapHeader("settings")] public void CopyFile(string sourcePath, string destinationPath) { try { Log.WriteStart("'{0}' CopyFile", ProviderSettings.ProviderName); OsProvider.CopyFile(sourcePath, destinationPath); Log.WriteEnd("'{0}' CopyFile", ProviderSettings.ProviderName); } catch (Exception ex) { Log.WriteError(String.Format("'{0}' CopyFile", ProviderSettings.ProviderName), ex); throw; } } [WebMethod, SoapHeader("settings")] public void ZipFiles(string zipFile, string rootPath, string[] files) { try { Log.WriteStart("'{0}' ZipFiles", ProviderSettings.ProviderName); OsProvider.ZipFiles(zipFile, rootPath, files); Log.WriteEnd("'{0}' ZipFiles", ProviderSettings.ProviderName); } catch (Exception ex) { Log.WriteError(String.Format("'{0}' ZipFiles", ProviderSettings.ProviderName), ex); throw; } } [WebMethod, SoapHeader("settings")] public string[] UnzipFiles(string zipFile, string destFolder) { try { Log.WriteStart("'{0}' UnzipFiles", ProviderSettings.ProviderName); string[] result = OsProvider.UnzipFiles(zipFile, destFolder); Log.WriteEnd("'{0}' UnzipFiles", ProviderSettings.ProviderName); return result; } catch (Exception ex) { Log.WriteError(String.Format("'{0}' UnzipFiles", ProviderSettings.ProviderName), ex); throw; } } [WebMethod, SoapHeader("settings")] public void CreateAccessDatabase(string databasePath) { try { Log.WriteStart("'{0}' CreateAccessDatabase", ProviderSettings.ProviderName); OsProvider.CreateAccessDatabase(databasePath); Log.WriteEnd("'{0}' CreateAccessDatabase", ProviderSettings.ProviderName); } catch (Exception ex) { Log.WriteError(String.Format("'{0}' CreateAccessDatabase", ProviderSettings.ProviderName), ex); throw; } } [WebMethod, SoapHeader("settings")] public UserPermission[] GetGroupNtfsPermissions(string path, UserPermission[] users, string usersOU) { try { Log.WriteStart("'{0}' GetGroupNtfsPermissions", ProviderSettings.ProviderName); UserPermission[] result = OsProvider.GetGroupNtfsPermissions(path, users, usersOU); Log.WriteEnd("'{0}' GetGroupNtfsPermissions", ProviderSettings.ProviderName); return result; } catch (Exception ex) { Log.WriteError(String.Format("'{0}' GetGroupNtfsPermissions", ProviderSettings.ProviderName), ex); throw; } } [WebMethod, SoapHeader("settings")] public void GrantGroupNtfsPermissions(string path, UserPermission[] users, string usersOU, bool resetChildPermissions) { try { Log.WriteStart("'{0}' GrantGroupNtfsPermissions", ProviderSettings.ProviderName); OsProvider.GrantGroupNtfsPermissions(path, users, usersOU, resetChildPermissions); Log.WriteEnd("'{0}' GrantGroupNtfsPermissions", ProviderSettings.ProviderName); } catch (Exception ex) { Log.WriteError(String.Format("'{0}' GrantGroupNtfsPermissions", ProviderSettings.ProviderName), ex); throw; } } [WebMethod, SoapHeader("settings")] public void SetQuotaLimitOnFolder(string folderPath, string shareNameDrive, QuotaType quotaType, string quotaLimit, int mode, string wmiUserName, string wmiPassword) { try { Log.WriteStart("'{0}' SetQuotaLimitOnFolder", ProviderSettings.ProviderName); OsProvider.SetQuotaLimitOnFolder(folderPath, shareNameDrive, quotaType, quotaLimit, mode, wmiUserName, wmiPassword); Log.WriteEnd("'{0}' SetQuotaLimitOnFolder", ProviderSettings.ProviderName); } catch (Exception ex) { Log.WriteError(String.Format("'{0}' SetQuotaLimitOnFolder", ProviderSettings.ProviderName), ex); throw; } } [WebMethod, SoapHeader("settings")] public Quota GetQuotaOnFolder(string folderPath, string wmiUserName, string wmiPassword) { try { Log.WriteStart("'{0}' GetQuotaOnFolder", ProviderSettings.ProviderName); var result = OsProvider.GetQuotaOnFolder(folderPath, wmiUserName, wmiPassword); Log.WriteEnd("'{0}' GetQuotaOnFolder", ProviderSettings.ProviderName); return result; } catch (Exception ex) { Log.WriteError(String.Format("'{0}' GetQuotaOnFolder", ProviderSettings.ProviderName), ex); throw; } } [WebMethod, SoapHeader("settings")] public void DeleteDirectoryRecursive(string rootPath) { try { Log.WriteStart("'{0}' DeleteDirectoryRecursive", ProviderSettings.ProviderName); OsProvider.DeleteDirectoryRecursive(rootPath); Log.WriteEnd("'{0}' DeleteDirectoryRecursive", ProviderSettings.ProviderName); } catch (Exception ex) { Log.WriteError(String.Format("'{0}' DeleteDirectoryRecursive", ProviderSettings.ProviderName), ex); throw; } } [WebMethod, SoapHeader("settings")] public bool CheckFileServicesInstallation() { try { Log.WriteStart("'{0}' CheckFileServicesInstallation", ProviderSettings.ProviderName); bool bResult = OsProvider.CheckFileServicesInstallation(); Log.WriteEnd("'{0}' CheckFileServicesInstallation", ProviderSettings.ProviderName); return bResult; } catch (Exception ex) { Log.WriteError(String.Format("'{0}' CheckFileServicesInstallation", ProviderSettings.ProviderName), ex); throw; } } [WebMethod, SoapHeader("settings")] public bool InstallFsrmService() { try { Log.WriteStart("'{0}' InstallFsrmService", ProviderSettings.ProviderName); bool bResult = OsProvider.InstallFsrmService(); Log.WriteEnd("'{0}' InstallFsrmService", ProviderSettings.ProviderName); return bResult; } catch (Exception ex) { Log.WriteError(String.Format("'{0}' InstallFsrmService", ProviderSettings.ProviderName), ex); throw; } } #endregion #region Synchronizing [WebMethod, SoapHeader("settings")] public FolderGraph GetFolderGraph(string path) { try { Log.WriteStart("'{0}' GetFolderGraph", ProviderSettings.ProviderName); FolderGraph result = OsProvider.GetFolderGraph(path); Log.WriteEnd("'{0}' GetFolderGraph", ProviderSettings.ProviderName); return result; } catch (Exception ex) { Log.WriteError(String.Format("'{0}' GetFolderGraph", ProviderSettings.ProviderName), ex); throw; } } [WebMethod, SoapHeader("settings")] public void ExecuteSyncActions(FileSyncAction[] actions) { try { Log.WriteStart("'{0}' ExecuteSyncActions", ProviderSettings.ProviderName); OsProvider.ExecuteSyncActions(actions); Log.WriteEnd("'{0}' ExecuteSyncActions", ProviderSettings.ProviderName); } catch (Exception ex) { Log.WriteError(String.Format("'{0}' ExecuteSyncActions", ProviderSettings.ProviderName), ex); throw; } } #endregion #region ODBC DSNs [WebMethod, SoapHeader("settings")] public string[] GetInstalledOdbcDrivers() { try { Log.WriteStart("'{0}' GetInstalledOdbcDrivers", ProviderSettings.ProviderName); string[] result = OsProvider.GetInstalledOdbcDrivers(); Log.WriteEnd("'{0}' GetInstalledOdbcDrivers", ProviderSettings.ProviderName); return result; } catch (Exception ex) { Log.WriteError(String.Format("'{0}' GetInstalledOdbcDrivers", ProviderSettings.ProviderName), ex); throw; } } [WebMethod, SoapHeader("settings")] public string[] GetDSNNames() { try { Log.WriteStart("'{0}' GetDSNNames", ProviderSettings.ProviderName); string[] result = OsProvider.GetDSNNames(); Log.WriteEnd("'{0}' GetDSNNames", ProviderSettings.ProviderName); return result; } catch (Exception ex) { Log.WriteError(String.Format("'{0}' GetDSNNames", ProviderSettings.ProviderName), ex); throw; } } [WebMethod, SoapHeader("settings")] public SystemDSN GetDSN(string dsnName) { try { Log.WriteStart("'{0}' GetDSN", ProviderSettings.ProviderName); SystemDSN result = OsProvider.GetDSN(dsnName); Log.WriteEnd("'{0}' GetDSN", ProviderSettings.ProviderName); return result; } catch (Exception ex) { Log.WriteError(String.Format("'{0}' GetDSN", ProviderSettings.ProviderName), ex); throw; } } [WebMethod, SoapHeader("settings")] public void CreateDSN(SystemDSN dsn) { try { Log.WriteStart("'{0}' CreateDSN", ProviderSettings.ProviderName); OsProvider.CreateDSN(dsn); Log.WriteEnd("'{0}' CreateDSN", ProviderSettings.ProviderName); } catch (Exception ex) { Log.WriteError(String.Format("'{0}' CreateDSN", ProviderSettings.ProviderName), ex); throw; } } [WebMethod, SoapHeader("settings")] public void UpdateDSN(SystemDSN dsn) { try { Log.WriteStart("'{0}' UpdateDSN", ProviderSettings.ProviderName); OsProvider.UpdateDSN(dsn); Log.WriteEnd("'{0}' UpdateDSN", ProviderSettings.ProviderName); } catch (Exception ex) { Log.WriteError(String.Format("'{0}' UpdateDSN", ProviderSettings.ProviderName), ex); throw; } } [WebMethod, SoapHeader("settings")] public void DeleteDSN(string dsnName) { try { Log.WriteStart("'{0}' DeleteDSN", ProviderSettings.ProviderName); OsProvider.DeleteDSN(dsnName); Log.WriteEnd("'{0}' DeleteDSN", ProviderSettings.ProviderName); } catch (Exception ex) { Log.WriteError(String.Format("'{0}' DeleteDSN", ProviderSettings.ProviderName), ex); throw; } } #endregion } }
using NinjaBotCore.Database; using NinjaBotCore.Models.Wow; using Discord; using Discord.Commands; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Discord.Net; using Discord.WebSocket; using System.Text.RegularExpressions; using Microsoft.Extensions.Configuration; using NinjaBotCore.Services; using Microsoft.Extensions.Logging; using Microsoft.Extensions.DependencyInjection; namespace NinjaBotCore.Modules.Wow { public class RoseCommands : ModuleBase { private ChannelCheck _cc; private readonly IConfigurationRoot _config; private string _prefix; private readonly ILogger _logger; public RoseCommands(IServiceProvider services) { _logger = services.GetRequiredService<ILogger<RoseCommands>>(); _cc = services.GetRequiredService<ChannelCheck>(); _config = services.GetRequiredService<IConfigurationRoot>(); _prefix = _config["prefix"]; } [Command("chhelp")] public async Task RoseHelp() { var embed = new EmbedBuilder(); var sb = new StringBuilder(); embed.Title = "Character Command Help"; embed.ThumbnailUrl = Context.Guild.IconUrl; sb.AppendLine("**Add/Modify Character**"); sb.AppendLine($":white_small_square: **{_prefix}setch** characterName itemLevel traits class mainSpec offSpec"); sb.AppendLine(); sb.AppendLine($"Example: **{_prefix}setch** Oceanbreeze 850 50 Druid Resto BoomyBoi"); sb.AppendLine(); sb.AppendLine("**Change Main Character**"); sb.AppendLine($":white_small_square: **{_prefix}setmch** characterName"); sb.AppendLine(); sb.AppendLine($"Example: **{_prefix}setmch** Oceanbreeze"); sb.AppendLine(); sb.AppendLine("**Remove a Character**"); sb.AppendLine($":white_small_square: **{_prefix}remch** characterName"); sb.AppendLine(); sb.AppendLine($"Example: **{_prefix}remch** Oceanbreeze"); sb.AppendLine(); sb.AppendLine("**List Character(s)**"); sb.AppendLine($":white_small_square: **{_prefix}getch** @userName (or) **{_prefix}getch**"); sb.AppendLine(); sb.AppendLine($"Example: **{_prefix}getch** @someoneOnDiscord"); sb.AppendLine($"Example: **{_prefix}getch**"); sb.AppendLine(); sb.AppendLine("**Find a Character**"); sb.AppendLine($":white_small_square: **{_prefix}findch** characterName"); sb.AppendLine(); sb.AppendLine($"Example: **{_prefix}findch** Oceanbreeze"); embed.Description = sb.ToString(); embed.WithColor(0, 255, 100); await _cc.Reply(Context, embed); } [Command("setch")] public async Task Addchar(string charName = null, long iLvl = 0, long traits = 0, string className = null, string mainSpec = null, string offspec = null) { var sb = new StringBuilder(); if (charName != null) { try { string changeVerb = string.Empty; using (var db = new NinjaBotEntities()) { var dbChar = db.WowMChar.Where(d => (ulong)d.ServerId == Context.Guild.Id && (ulong)d.DiscordUserId == Context.User.Id && d.CharName.ToLower() == charName.ToLower()).FirstOrDefault(); if (dbChar != null) { if (iLvl != 0) { dbChar.ItemLevel = iLvl; } if (traits != 0) { dbChar.Traits = traits; } if (!string.IsNullOrEmpty(className)) { dbChar.ClassName = className; } if (!string.IsNullOrEmpty(mainSpec)) { dbChar.MainSpec = mainSpec; } if (!string.IsNullOrEmpty(offspec)) { dbChar.OffSpec = offspec; } changeVerb = "modified"; sb.AppendLine($"{Context.User.Mention}, **{charName}** has been {changeVerb}!"); } else { changeVerb = "added"; var allChars = db.WowMChar.Where(c => c.DiscordUserId == (long)Context.User.Id && c.ServerId == (long)Context.Guild.Id).ToList(); if (allChars != null && allChars.Count <= 5) { bool main = false; if (allChars.Count == 0) { main = true; } await db.WowMChar.AddAsync( new WowMChar { DiscordUserId = (long)Context.User.Id, ServerId = (long)Context.Guild.Id, CharName = charName, ItemLevel = iLvl, Traits = traits, ClassName = className, MainSpec = mainSpec, OffSpec = offspec, IsMain = main }); sb.AppendLine($"{Context.User.Mention}, **{charName}** has been {changeVerb}!"); } else { sb.AppendLine($"{Context.User.Mention}, you are at the max char limit of **6**!"); } } await db.SaveChangesAsync(); } } catch (Exception ex) { _logger.LogError($"Error adding character -> [{ex.Message}]"); sb.AppendLine($"Sorry, {Context.User.Mention}, something went terribly wrong :("); } } else { sb.AppendLine("You must at least specify a character name!"); } await _cc.Reply(Context, sb.ToString()); } [Command("setmch")] public async Task SetMainChar(string charName = null) { var embed = new EmbedBuilder(); var sb = new StringBuilder(); embed.Title = "Main Character Changer"; try { if (charName != null) { using (var db = new NinjaBotEntities()) { var newMainChar = db.WowMChar.Where(d => d.ServerId == (long)Context.Guild.Id && d.DiscordUserId == (long)Context.User.Id && d.CharName.ToLower() == charName.ToLower()).FirstOrDefault(); if (newMainChar == null) { sb.AppendLine($"Unable to find [**{charName}**]!"); embed.WithColor(255, 0, 0); } else { var curMainChar = db.WowMChar.Where(d => d.ServerId == (long)Context.Guild.Id && d.DiscordUserId == (long)Context.User.Id && d.IsMain).FirstOrDefault(); if (newMainChar.CharName == curMainChar.CharName) { sb.AppendLine($"[**{charName}**] is already your main!"); embed.WithColor(255, 0, 0); } else { newMainChar.IsMain = true; curMainChar.IsMain = false; await db.SaveChangesAsync(); sb.AppendLine($"Main character set to [**{charName}**]!"); embed.WithColor(0, 255 ,0); } } } } else { embed.WithColor(255, 0 ,0); using (var db = new NinjaBotEntities()) { sb.AppendLine("Please specify a character name!"); var chars = db.WowMChar.Where(d => d.DiscordUserId == (long)Context.User.Id && d.ServerId == (long)Context.Guild.Id).ToList(); if (chars != null && chars.Count > 0) { sb.AppendLine($"Your character's names are:"); foreach (var character in chars) { sb.AppendLine($":white_medium_small_square: [**{character.CharName}**]"); } } } } } catch (Exception ex) { embed.WithColor(255, 0, 0); sb.AppendLine("Sorry, something went wrong attempting to set your main character :("); _logger.LogError($"Error setting main char -> [{ex.Message}]"); } embed.ThumbnailUrl = Context.User.GetAvatarUrl(); embed.Description = sb.ToString(); await _cc.Reply(Context, embed); } [Command("remch")] public async Task RemoveChar(string charName = null) { var embed = new EmbedBuilder(); var sb = new StringBuilder(); if (charName != null) { try { WowMChar charMatch = null; using (var db = new NinjaBotEntities()) { charMatch = db.WowMChar.Where(d => d.DiscordUserId == (long)Context.User.Id && d.ServerId == (long)Context.Guild.Id && charName.ToLower() == d.CharName.ToLower()).FirstOrDefault(); if (charMatch != null) { db.WowMChar.Remove(charMatch); await db.SaveChangesAsync(); sb.AppendLine($"Character [**{charMatch.CharName}**] successfully removed!"); embed.WithColor(0, 255, 0); } else { sb.AppendLine($"Could not find [**{charName}**]!"); embed.WithColor(255, 0, 0); } } } catch { } } else { embed.WithColor(255, 0, 0); sb.AppendLine("Please specify a character name!"); using (var db = new NinjaBotEntities()) { var chars = db.WowMChar.Where(d => d.DiscordUserId == (long)Context.User.Id && d.ServerId == (long)Context.Guild.Id).ToList(); if (chars != null && chars.Count > 0) { sb.AppendLine($"Your character's names are:"); foreach (var character in chars) { sb.AppendLine($":white_medium_small_square: [**{character.CharName}**]"); } } } } embed.ThumbnailUrl = Context.User.GetAvatarUrl(); embed.Title = "Character Removal"; embed.Description = sb.ToString(); await _cc.Reply(Context, embed); } [Command("getch")] public async Task GetChars(IUser user = null) { if (user == null) { user = Context.User; } var embed = new EmbedBuilder(); embed.Title = $"Characters for [**{user.Username}**]"; List<WowMChar> chars = null; using (var db = new NinjaBotEntities()) { chars = db.WowMChar.Where(c => c.DiscordUserId == (long)user.Id && c.ServerId == (long)Context.Guild.Id).OrderByDescending(c => c.IsMain).ToList(); } if (chars != null) { foreach (var character in chars) { var sb = new StringBuilder(); string square = ":white_small_square:"; sb.AppendLine($"{square} ilvl [**{character.ItemLevel}**]"); sb.AppendLine($"{square} traits [**{character.Traits}**]"); if (!string.IsNullOrEmpty(character.ClassName)) { sb.AppendLine($"{square} class [**{character.ClassName}**]"); } else { sb.AppendLine($"{square} class [**much empty**]"); } if (!string.IsNullOrEmpty(character.MainSpec)) { sb.AppendLine($"{square} ms [**{character.MainSpec}**]"); } else { sb.AppendLine($"{square} ms [**much empty**]"); } if (!string.IsNullOrEmpty(character.OffSpec)) { sb.AppendLine($"{square} os [**{character.OffSpec}**]"); } else { sb.AppendLine($"{square} os [**much empty**]"); } string charName = string.Empty; if (character.IsMain) { charName = $"{character.CharName} [main]"; } else { charName = $"{character.CharName} [alt]"; } embed.WithFields( new EmbedFieldBuilder { Name = charName, Value = sb.ToString(), IsInline = true } ); } embed.WithColor(new Color(0, 255, 155)); } else { embed.Description = "No chars found!"; embed.WithColor(new Color(255, 0, 0)); } embed.ThumbnailUrl = user.GetAvatarUrl(); embed.WithFooter( new EmbedFooterBuilder { Text = $"Character info requested by [{Context.User.Username}]", IconUrl = Context.User.GetAvatarUrl() } ); await _cc.Reply(Context, embed); } [Command("findch")] public async Task FindChar(string charName = null) { var sb = new StringBuilder(); var embed = new EmbedBuilder(); embed.Title = $"Character Finder"; if (charName != null) { embed.Title = $"Character Finder [{charName}]"; WowMChar findMe = null; using (var db = new NinjaBotEntities()) { findMe = db.WowMChar.Where(d => d.ServerId == (long)Context.Guild.Id && d.CharName.ToLower().Contains(charName.ToLower())).FirstOrDefault(); if (findMe != null) { var fb = new StringBuilder(); string square = ":white_small_square:"; fb.AppendLine($"{square} ilvl [**{findMe.ItemLevel}**]"); fb.AppendLine($"{square} traits [**{findMe.Traits}**]"); if (!string.IsNullOrEmpty(findMe.ClassName)) { fb.AppendLine($"{square} class [**{findMe.ClassName}**]"); } else { fb.AppendLine($"{square} class [**much empty**]"); } if (!string.IsNullOrEmpty(findMe.MainSpec)) { fb.AppendLine($"{square} ms [**{findMe.MainSpec}**]"); } else { fb.AppendLine($"{square} ms [**much empty**]"); } if (!string.IsNullOrEmpty(findMe.OffSpec)) { fb.AppendLine($"{square} os [**{findMe.OffSpec}**]"); } else { fb.AppendLine($"{square} os [**much empty**]"); } string foundCharName = string.Empty; if (findMe.IsMain) { foundCharName = $"{findMe.CharName} [main]"; } else { foundCharName = $"{findMe.CharName} [alt]"; } embed.WithFields( new EmbedFieldBuilder { Name = foundCharName, Value = fb.ToString(), IsInline = true } ); var belongsTo = await Context.Guild.GetUserAsync((ulong)findMe.DiscordUserId); sb.AppendLine($"This character belongs to [**{belongsTo.Username}**]"); embed.WithColor(0, 200, 100); embed.ThumbnailUrl = belongsTo.GetAvatarUrl(); } else { sb.AppendLine($"Sorry {Context.User.Mention}, no results :("); embed.WithColor(255, 100, 0); } } } else { embed.WithColor(255, 0 ,0 ); sb.AppendLine("You must specify a character name!"); } embed.Description = sb.ToString(); embed.WithFooter( new EmbedFooterBuilder { Text = $"Lookup performed by [{Context.User.Username}]", IconUrl = Context.User.GetAvatarUrl() } ); await _cc.Reply(Context, embed); } } }
/* * * (c) Copyright Ascensio System Limited 2010-2021 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Generic; using System.Linq; using ASC.Api.Attributes; using ASC.CRM.Core; using ASC.MessagingSystem; using ASC.Web.CRM.Classes; using ASC.Web.CRM.Resources; namespace ASC.Api.CRM { public partial class CRMApi { //TABLE `crm_currency_rate` column `rate` DECIMAL(10,2) NOT NULL public const decimal MaxRateValue = (decimal)99999999.99; /// <summary> /// Get the list of currency rates /// </summary> /// <short>Get currency rates list</short> /// <category>Common</category> /// <returns> /// List of currency rates /// </returns> [Read(@"currency/rates")] public IEnumerable<CurrencyRateWrapper> GetCurrencyRates() { return DaoFactory.CurrencyRateDao.GetAll().ConvertAll(ToCurrencyRateWrapper); } /// <summary> /// Get currency rate by id /// </summary> /// <short>Get currency rate</short> /// <category>Common</category> /// <returns> /// Currency rate /// </returns> /// <exception cref="ArgumentException"></exception> [Read(@"currency/rates/{id:[0-9]+}")] public CurrencyRateWrapper GetCurrencyRate(int id) { if (id <= 0) throw new ArgumentException(); var currencyRate = DaoFactory.CurrencyRateDao.GetByID(id); return ToCurrencyRateWrapper(currencyRate); } /// <summary> /// Get currency rate by currencies /// </summary> /// <short>Get currency rate</short> /// <category>Common</category> /// <returns> /// Currency rate /// </returns> /// <exception cref="ArgumentException"></exception> [Read(@"currency/rates/{fromCurrency}/{toCurrency}")] public CurrencyRateWrapper GetCurrencyRate(string fromCurrency, string toCurrency) { if (string.IsNullOrEmpty(fromCurrency) || string.IsNullOrEmpty(toCurrency)) throw new ArgumentException(); var currencyRate = DaoFactory.CurrencyRateDao.GetByCurrencies(fromCurrency, toCurrency); return ToCurrencyRateWrapper(currencyRate); } /// <summary> /// Create new currency rate object /// </summary> /// <short></short> /// <category>Common</category> /// <returns></returns> [Create(@"currency/rates")] public CurrencyRateWrapper CreateCurrencyRate(string fromCurrency, string toCurrency, decimal rate) { ValidateRate(rate); ValidateCurrencies(new[] { fromCurrency, toCurrency }); var currencyRate = new CurrencyRate { FromCurrency = fromCurrency, ToCurrency = toCurrency, Rate = rate }; currencyRate.ID = DaoFactory.CurrencyRateDao.SaveOrUpdate(currencyRate); MessageService.Send(Request, MessageAction.CurrencyRateUpdated, fromCurrency, toCurrency); return ToCurrencyRateWrapper(currencyRate); } /// <summary> /// Update currency rate object /// </summary> /// <short></short> /// <category>Common</category> /// <returns></returns> [Update(@"currency/rates/{id:[0-9]+}")] public CurrencyRateWrapper UpdateCurrencyRate(int id, string fromCurrency, string toCurrency, decimal rate) { if (id <= 0) throw new ArgumentException(); ValidateRate(rate); ValidateCurrencies(new[] { fromCurrency, toCurrency }); var currencyRate = DaoFactory.CurrencyRateDao.GetByID(id); if (currencyRate == null) throw new ArgumentException(); currencyRate.FromCurrency = fromCurrency; currencyRate.ToCurrency = toCurrency; currencyRate.Rate = rate; currencyRate.ID = DaoFactory.CurrencyRateDao.SaveOrUpdate(currencyRate); MessageService.Send(Request, MessageAction.CurrencyRateUpdated, fromCurrency, toCurrency); return ToCurrencyRateWrapper(currencyRate); } /// <summary> /// Set currency rates /// </summary> /// <short></short> /// <category>Common</category> /// <returns></returns> [Create(@"currency/setrates")] public List<CurrencyRateWrapper> SetCurrencyRates(String currency, List<CurrencyRate> rates) { if (!CRMSecurity.IsAdmin) throw CRMSecurity.CreateSecurityException(); if (string.IsNullOrEmpty(currency)) throw new ArgumentException(); ValidateCurrencyRates(rates); currency = currency.ToUpper(); if (Global.TenantSettings.DefaultCurrency.Abbreviation != currency) { var cur = CurrencyProvider.Get(currency); if (cur == null) throw new ArgumentException(); Global.SaveDefaultCurrencySettings(cur); MessageService.Send(Request, MessageAction.CrmDefaultCurrencyUpdated); } rates = DaoFactory.CurrencyRateDao.SetCurrencyRates(rates); foreach (var rate in rates) { MessageService.Send(Request, MessageAction.CurrencyRateUpdated, rate.FromCurrency, rate.ToCurrency); } return rates.Select(ToCurrencyRateWrapper).ToList(); } /// <summary> /// Add currency rates /// </summary> /// <short></short> /// <category>Common</category> /// <returns></returns> [Create(@"currency/addrates")] public List<CurrencyRateWrapper> AddCurrencyRates(List<CurrencyRate> rates) { if (!CRMSecurity.IsAdmin) throw CRMSecurity.CreateSecurityException(); ValidateCurrencyRates(rates); var existingRates = DaoFactory.CurrencyRateDao.GetAll(); foreach (var rate in rates) { var exist = false; foreach (var existingRate in existingRates) { if (rate.FromCurrency != existingRate.FromCurrency || rate.ToCurrency != existingRate.ToCurrency) continue; existingRate.Rate = rate.Rate; DaoFactory.CurrencyRateDao.SaveOrUpdate(existingRate); MessageService.Send(Request, MessageAction.CurrencyRateUpdated, rate.FromCurrency, rate.ToCurrency); exist = true; break; } if (exist) continue; rate.ID = DaoFactory.CurrencyRateDao.SaveOrUpdate(rate); MessageService.Send(Request, MessageAction.CurrencyRateUpdated, rate.FromCurrency, rate.ToCurrency); existingRates.Add(rate); } return existingRates.Select(ToCurrencyRateWrapper).ToList(); } /// <summary> /// Delete currency rate object /// </summary> /// <short></short> /// <category>Common</category> /// <returns></returns> [Delete(@"currency/rates/{id:[0-9]+}")] public CurrencyRateWrapper DeleteCurrencyRate(int id) { if (id <= 0) throw new ArgumentException(); var currencyRate = DaoFactory.CurrencyRateDao.GetByID(id); if (currencyRate == null) throw new ArgumentException(); DaoFactory.CurrencyRateDao.Delete(id); return ToCurrencyRateWrapper(currencyRate); } private static void ValidateCurrencyRates(IEnumerable<CurrencyRate> rates) { var currencies = new List<string>(); foreach (var rate in rates) { ValidateRate(rate.Rate); currencies.Add(rate.FromCurrency); currencies.Add(rate.ToCurrency); } ValidateCurrencies(currencies.ToArray()); } private static void ValidateCurrencies(string[] currencies) { if (currencies.Any(string.IsNullOrEmpty)) throw new ArgumentException(); var available = CurrencyProvider.GetAll().Select(x => x.Abbreviation); var unknown = currencies.Where(x => !available.Contains(x)).ToArray(); if (!unknown.Any()) return; throw new ArgumentException(string.Format(CRMErrorsResource.UnknownCurrency, string.Join(",", unknown))); } private static void ValidateRate(decimal rate) { if (rate < 0 || rate > MaxRateValue) throw new ArgumentException(string.Format(CRMErrorsResource.InvalidCurrencyRate, rate)); } private static CurrencyRateWrapper ToCurrencyRateWrapper(CurrencyRate currencyRate) { return new CurrencyRateWrapper(currencyRate); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Runtime.InteropServices; using Avalonia.Controls; using Avalonia.Automation.Peers; using Avalonia.Controls.Platform; using Avalonia.Input; using Avalonia.Input.Raw; using Avalonia.Input.TextInput; using Avalonia.OpenGL; using Avalonia.OpenGL.Angle; using Avalonia.OpenGL.Egl; using Avalonia.OpenGL.Surfaces; using Avalonia.Platform; using Avalonia.Rendering; using Avalonia.Win32.Automation; using Avalonia.Win32.Input; using Avalonia.Win32.Interop; using Avalonia.Win32.OpenGl; using Avalonia.Win32.WinRT; using Avalonia.Win32.WinRT.Composition; using static Avalonia.Win32.Interop.UnmanagedMethods; namespace Avalonia.Win32 { /// <summary> /// Window implementation for Win32 platform. /// </summary> public partial class WindowImpl : IWindowImpl, EglGlPlatformSurface.IEglWindowGlPlatformSurfaceInfo, ITopLevelImplWithNativeControlHost, ITopLevelImplWithTextInputMethod { private static readonly List<WindowImpl> s_instances = new List<WindowImpl>(); private static readonly IntPtr DefaultCursor = LoadCursor( IntPtr.Zero, new IntPtr((int)UnmanagedMethods.Cursor.IDC_ARROW)); private static readonly Dictionary<WindowEdge, HitTestValues> s_edgeLookup = new Dictionary<WindowEdge, HitTestValues> { { WindowEdge.East, HitTestValues.HTRIGHT }, { WindowEdge.North, HitTestValues.HTTOP }, { WindowEdge.NorthEast, HitTestValues.HTTOPRIGHT }, { WindowEdge.NorthWest, HitTestValues.HTTOPLEFT }, { WindowEdge.South, HitTestValues.HTBOTTOM }, { WindowEdge.SouthEast, HitTestValues.HTBOTTOMRIGHT }, { WindowEdge.SouthWest, HitTestValues.HTBOTTOMLEFT }, { WindowEdge.West, HitTestValues.HTLEFT } }; private SavedWindowInfo _savedWindowInfo; private bool _isFullScreenActive; private bool _isClientAreaExtended; private Thickness _extendedMargins; private Thickness _offScreenMargin; private double _extendTitleBarHint = -1; private bool _isUsingComposition; private IBlurHost _blurHost; private PlatformResizeReason _resizeReason; #if USE_MANAGED_DRAG private readonly ManagedWindowResizeDragHelper _managedDrag; #endif private const WindowStyles WindowStateMask = (WindowStyles.WS_MAXIMIZE | WindowStyles.WS_MINIMIZE); private readonly TouchDevice _touchDevice; private readonly MouseDevice _mouseDevice; private readonly ManagedDeferredRendererLock _rendererLock; private readonly FramebufferManager _framebuffer; private readonly IGlPlatformSurface _gl; private Win32NativeControlHost _nativeControlHost; private WndProc _wndProcDelegate; private string _className; private IntPtr _hwnd; private bool _multitouch; private IInputRoot _owner; private WindowProperties _windowProperties; private bool _trackingMouse; private bool _topmost; private double _scaling = 1; private WindowState _showWindowState; private WindowState _lastWindowState; private OleDropTarget _dropTarget; private Size _minSize; private Size _maxSize; private POINT _maxTrackSize; private WindowImpl _parent; private ExtendClientAreaChromeHints _extendChromeHints = ExtendClientAreaChromeHints.Default; private bool _isCloseRequested; private bool _shown; private bool _hiddenWindowIsParent; private uint _langid; private bool _ignoreWmChar; public WindowImpl() { _touchDevice = new TouchDevice(); _mouseDevice = new WindowsMouseDevice(); #if USE_MANAGED_DRAG _managedDrag = new ManagedWindowResizeDragHelper(this, capture => { if (capture) UnmanagedMethods.SetCapture(Handle.Handle); else UnmanagedMethods.ReleaseCapture(); }); #endif _windowProperties = new WindowProperties { ShowInTaskbar = false, IsResizable = true, Decorations = SystemDecorations.Full }; _rendererLock = new ManagedDeferredRendererLock(); var glPlatform = AvaloniaLocator.Current.GetService<IPlatformOpenGlInterface>(); var compositionConnector = AvaloniaLocator.Current.GetService<WinUICompositorConnection>(); _isUsingComposition = compositionConnector is { } && glPlatform is EglPlatformOpenGlInterface egl && egl.Display is AngleWin32EglDisplay angleDisplay && angleDisplay.PlatformApi == AngleOptions.PlatformApi.DirectX11; CreateWindow(); _framebuffer = new FramebufferManager(_hwnd); UpdateInputMethod(GetKeyboardLayout(0)); if (glPlatform != null) { if (_isUsingComposition) { var cgl = new WinUiCompositedWindowSurface(compositionConnector, this); _blurHost = cgl; _gl = cgl; _isUsingComposition = true; } else { if (glPlatform is EglPlatformOpenGlInterface egl2) _gl = new EglGlPlatformSurface(egl2, this); else if (glPlatform is WglPlatformOpenGlInterface wgl) _gl = new WglGlPlatformSurface(wgl.PrimaryContext, this); } } Screen = new ScreenImpl(); _nativeControlHost = new Win32NativeControlHost(this, _isUsingComposition); s_instances.Add(this); } public Action Activated { get; set; } public Func<bool> Closing { get; set; } public Action Closed { get; set; } public Action Deactivated { get; set; } public Action<RawInputEventArgs> Input { get; set; } public Action<Rect> Paint { get; set; } public Action<Size, PlatformResizeReason> Resized { get; set; } public Action<double> ScalingChanged { get; set; } public Action<PixelPoint> PositionChanged { get; set; } public Action<WindowState> WindowStateChanged { get; set; } public Action LostFocus { get; set; } public Action<WindowTransparencyLevel> TransparencyLevelChanged { get; set; } public Thickness BorderThickness { get { if (HasFullDecorations) { var style = GetStyle(); var exStyle = GetExtendedStyle(); var padding = new RECT(); if (AdjustWindowRectEx(ref padding, (uint)style, false, (uint)exStyle)) { return new Thickness(-padding.left, -padding.top, padding.right, padding.bottom); } else { throw new Win32Exception(); } } else { return new Thickness(); } } } public double RenderScaling => _scaling; public double DesktopScaling => RenderScaling; public Size ClientSize { get { GetClientRect(_hwnd, out var rect); return new Size(rect.right, rect.bottom) / RenderScaling; } } public Size? FrameSize { get { if (DwmIsCompositionEnabled(out var compositionEnabled) != 0 || !compositionEnabled) { GetWindowRect(_hwnd, out var rcWindow); return new Size(rcWindow.Width, rcWindow.Height) / RenderScaling; } DwmGetWindowAttribute(_hwnd, (int)DwmWindowAttribute.DWMWA_EXTENDED_FRAME_BOUNDS, out var rect, Marshal.SizeOf<RECT>()); return new Size(rect.Width, rect.Height) / RenderScaling; } } public IScreenImpl Screen { get; } public IPlatformHandle Handle { get; private set; } public virtual Size MaxAutoSizeHint => new Size(_maxTrackSize.X / RenderScaling, _maxTrackSize.Y / RenderScaling); public IMouseDevice MouseDevice => _mouseDevice; public WindowState WindowState { get { if(_isFullScreenActive) { return WindowState.FullScreen; } var placement = default(WINDOWPLACEMENT); GetWindowPlacement(_hwnd, ref placement); return placement.ShowCmd switch { ShowWindowCommand.Maximize => WindowState.Maximized, ShowWindowCommand.Minimize => WindowState.Minimized, _ => WindowState.Normal }; } set { if (IsWindowVisible(_hwnd)) { ShowWindow(value, value != WindowState.Minimized); // If the window is minimized, it shouldn't be activated } _showWindowState = value; } } public WindowTransparencyLevel TransparencyLevel { get; private set; } protected IntPtr Hwnd => _hwnd; public void SetTransparencyLevelHint (WindowTransparencyLevel transparencyLevel) { TransparencyLevel = EnableBlur(transparencyLevel); } private WindowTransparencyLevel EnableBlur(WindowTransparencyLevel transparencyLevel) { if (Win32Platform.WindowsVersion.Major >= 6) { if (DwmIsCompositionEnabled(out var compositionEnabled) != 0 || !compositionEnabled) { return WindowTransparencyLevel.None; } else if (Win32Platform.WindowsVersion.Major >= 10) { return Win10EnableBlur(transparencyLevel); } else if (Win32Platform.WindowsVersion.Minor >= 2) { return Win8xEnableBlur(transparencyLevel); } else { return Win7EnableBlur(transparencyLevel); } } else { return WindowTransparencyLevel.None; } } private WindowTransparencyLevel Win7EnableBlur(WindowTransparencyLevel transparencyLevel) { if (transparencyLevel == WindowTransparencyLevel.AcrylicBlur) { transparencyLevel = WindowTransparencyLevel.Blur; } var blurInfo = new DWM_BLURBEHIND(false); if (transparencyLevel == WindowTransparencyLevel.Blur) { blurInfo = new DWM_BLURBEHIND(true); } DwmEnableBlurBehindWindow(_hwnd, ref blurInfo); if (transparencyLevel == WindowTransparencyLevel.Transparent) { return WindowTransparencyLevel.None; } else { return transparencyLevel; } } private WindowTransparencyLevel Win8xEnableBlur(WindowTransparencyLevel transparencyLevel) { var accent = new AccentPolicy(); var accentStructSize = Marshal.SizeOf<AccentPolicy>(); if (transparencyLevel == WindowTransparencyLevel.AcrylicBlur) { transparencyLevel = WindowTransparencyLevel.Blur; } if (transparencyLevel == WindowTransparencyLevel.Transparent) { accent.AccentState = AccentState.ACCENT_ENABLE_BLURBEHIND; } else { accent.AccentState = AccentState.ACCENT_DISABLED; } var accentPtr = Marshal.AllocHGlobal(accentStructSize); Marshal.StructureToPtr(accent, accentPtr, false); var data = new WindowCompositionAttributeData(); data.Attribute = WindowCompositionAttribute.WCA_ACCENT_POLICY; data.SizeOfData = accentStructSize; data.Data = accentPtr; SetWindowCompositionAttribute(_hwnd, ref data); Marshal.FreeHGlobal(accentPtr); if (transparencyLevel >= WindowTransparencyLevel.Blur) { Win7EnableBlur(transparencyLevel); } return transparencyLevel; } private WindowTransparencyLevel Win10EnableBlur(WindowTransparencyLevel transparencyLevel) { if (_isUsingComposition) { _blurHost?.SetBlur(transparencyLevel switch { WindowTransparencyLevel.Mica => BlurEffect.Mica, WindowTransparencyLevel.AcrylicBlur => BlurEffect.Acrylic, WindowTransparencyLevel.Blur => BlurEffect.Acrylic, _ => BlurEffect.None }); return transparencyLevel; } else { bool canUseAcrylic = Win32Platform.WindowsVersion.Major > 10 || Win32Platform.WindowsVersion.Build >= 19628; var accent = new AccentPolicy(); var accentStructSize = Marshal.SizeOf<AccentPolicy>(); if (transparencyLevel == WindowTransparencyLevel.AcrylicBlur && !canUseAcrylic) { transparencyLevel = WindowTransparencyLevel.Blur; } switch (transparencyLevel) { default: case WindowTransparencyLevel.None: accent.AccentState = AccentState.ACCENT_DISABLED; break; case WindowTransparencyLevel.Transparent: accent.AccentState = AccentState.ACCENT_ENABLE_TRANSPARENTGRADIENT; break; case WindowTransparencyLevel.Blur: accent.AccentState = AccentState.ACCENT_ENABLE_BLURBEHIND; break; case WindowTransparencyLevel.AcrylicBlur: case (WindowTransparencyLevel.AcrylicBlur + 1): // hack-force acrylic. accent.AccentState = AccentState.ACCENT_ENABLE_ACRYLIC; transparencyLevel = WindowTransparencyLevel.AcrylicBlur; break; } accent.AccentFlags = 2; accent.GradientColor = 0x01000000; var accentPtr = Marshal.AllocHGlobal(accentStructSize); Marshal.StructureToPtr(accent, accentPtr, false); var data = new WindowCompositionAttributeData(); data.Attribute = WindowCompositionAttribute.WCA_ACCENT_POLICY; data.SizeOfData = accentStructSize; data.Data = accentPtr; SetWindowCompositionAttribute(_hwnd, ref data); Marshal.FreeHGlobal(accentPtr); return transparencyLevel; } } public IEnumerable<object> Surfaces => new object[] { Handle, _gl, _framebuffer }; public PixelPoint Position { get { GetWindowRect(_hwnd, out var rc); return new PixelPoint(rc.left, rc.top); } set { SetWindowPos( Handle.Handle, IntPtr.Zero, value.X, value.Y, 0, 0, SetWindowPosFlags.SWP_NOSIZE | SetWindowPosFlags.SWP_NOACTIVATE | SetWindowPosFlags.SWP_NOZORDER); } } private bool HasFullDecorations => _windowProperties.Decorations == SystemDecorations.Full; public void Move(PixelPoint point) => Position = point; public void SetMinMaxSize(Size minSize, Size maxSize) { _minSize = minSize; _maxSize = maxSize; } public IRenderer CreateRenderer(IRenderRoot root) { var loop = AvaloniaLocator.Current.GetService<IRenderLoop>(); var customRendererFactory = AvaloniaLocator.Current.GetService<IRendererFactory>(); if (customRendererFactory != null) return customRendererFactory.Create(root, loop); return Win32Platform.UseDeferredRendering ? _isUsingComposition ? new DeferredRenderer(root, loop) { RenderOnlyOnRenderThread = true } : (IRenderer)new DeferredRenderer(root, loop, rendererLock: _rendererLock) : new ImmediateRenderer(root); } public void Resize(Size value, PlatformResizeReason reason) { int requestedClientWidth = (int)(value.Width * RenderScaling); int requestedClientHeight = (int)(value.Height * RenderScaling); GetClientRect(_hwnd, out var clientRect); // do comparison after scaling to avoid rounding issues if (requestedClientWidth != clientRect.Width || requestedClientHeight != clientRect.Height) { GetWindowRect(_hwnd, out var windowRect); using var scope = SetResizeReason(reason); SetWindowPos( _hwnd, IntPtr.Zero, 0, 0, requestedClientWidth + (_isClientAreaExtended ? 0 : windowRect.Width - clientRect.Width), requestedClientHeight + (_isClientAreaExtended ? 0 : windowRect.Height - clientRect.Height), SetWindowPosFlags.SWP_RESIZE); } } public void Activate() { SetForegroundWindow(_hwnd); } public IPopupImpl CreatePopup() => Win32Platform.UseOverlayPopups ? null : new PopupImpl(this); public void Dispose() { (_gl as IDisposable)?.Dispose(); if (_dropTarget != null) { OleContext.Current?.UnregisterDragDrop(Handle); _dropTarget.Dispose(); _dropTarget = null; } if (_hwnd != IntPtr.Zero) { // Detect if we are being closed programmatically - this would mean that WM_CLOSE was not called // and we didn't prepare this window for destruction. if (!_isCloseRequested) { BeforeCloseCleanup(true); } DestroyWindow(_hwnd); _hwnd = IntPtr.Zero; } if (_className != null) { UnregisterClass(_className, GetModuleHandle(null)); _className = null; } _framebuffer.Dispose(); } public void Invalidate(Rect rect) { var scaling = RenderScaling; var r = new RECT { left = (int)Math.Floor(rect.X * scaling), top = (int)Math.Floor(rect.Y * scaling), right = (int)Math.Ceiling(rect.Right * scaling), bottom = (int)Math.Ceiling(rect.Bottom * scaling), }; InvalidateRect(_hwnd, ref r, false); } public Point PointToClient(PixelPoint point) { var p = new POINT { X = point.X, Y = point.Y }; UnmanagedMethods.ScreenToClient(_hwnd, ref p); return new Point(p.X, p.Y) / RenderScaling; } public PixelPoint PointToScreen(Point point) { point *= RenderScaling; var p = new POINT { X = (int)point.X, Y = (int)point.Y }; ClientToScreen(_hwnd, ref p); return new PixelPoint(p.X, p.Y); } public void SetInputRoot(IInputRoot inputRoot) { _owner = inputRoot; CreateDropTarget(); } public void Hide() { UnmanagedMethods.ShowWindow(_hwnd, ShowWindowCommand.Hide); _shown = false; } public virtual void Show(bool activate, bool isDialog) { SetParent(_parent); ShowWindow(_showWindowState, activate); } public Action GotInputWhenDisabled { get; set; } public void SetParent(IWindowImpl parent) { _parent = (WindowImpl)parent; var parentHwnd = _parent?._hwnd ?? IntPtr.Zero; if (parentHwnd == IntPtr.Zero && !_windowProperties.ShowInTaskbar) { parentHwnd = OffscreenParentWindow.Handle; _hiddenWindowIsParent = true; } SetWindowLongPtr(_hwnd, (int)WindowLongParam.GWL_HWNDPARENT, parentHwnd); } public void SetEnabled(bool enable) => EnableWindow(_hwnd, enable); public void BeginMoveDrag(PointerPressedEventArgs e) { _mouseDevice.Capture(null); DefWindowProc(_hwnd, (int)WindowsMessage.WM_NCLBUTTONDOWN, new IntPtr((int)HitTestValues.HTCAPTION), IntPtr.Zero); e.Pointer.Capture(null); } public void BeginResizeDrag(WindowEdge edge, PointerPressedEventArgs e) { if (_windowProperties.IsResizable) { #if USE_MANAGED_DRAG _managedDrag.BeginResizeDrag(edge, ScreenToClient(MouseDevice.Position.ToPoint(_scaling))); #else _mouseDevice.Capture(null); DefWindowProc(_hwnd, (int)WindowsMessage.WM_NCLBUTTONDOWN, new IntPtr((int)s_edgeLookup[edge]), IntPtr.Zero); #endif } } public void SetTitle(string title) { SetWindowText(_hwnd, title); } public void SetCursor(ICursorImpl cursor) { var impl = cursor as CursorImpl; if (cursor is null || impl is object) { var hCursor = impl?.Handle ?? DefaultCursor; SetClassLong(_hwnd, ClassLongIndex.GCLP_HCURSOR, hCursor); if (_owner.IsPointerOver) { UnmanagedMethods.SetCursor(hCursor); } } } public void SetIcon(IWindowIconImpl icon) { var impl = (IconImpl)icon; var hIcon = impl?.HIcon ?? IntPtr.Zero; PostMessage(_hwnd, (int)WindowsMessage.WM_SETICON, new IntPtr((int)Icons.ICON_BIG), hIcon); } public void ShowTaskbarIcon(bool value) { var newWindowProperties = _windowProperties; newWindowProperties.ShowInTaskbar = value; UpdateWindowProperties(newWindowProperties); } public void CanResize(bool value) { var newWindowProperties = _windowProperties; newWindowProperties.IsResizable = value; UpdateWindowProperties(newWindowProperties); } public void SetSystemDecorations(SystemDecorations value) { var newWindowProperties = _windowProperties; newWindowProperties.Decorations = value; UpdateWindowProperties(newWindowProperties); } public void SetTopmost(bool value) { if (value == _topmost) { return; } IntPtr hWndInsertAfter = value ? WindowPosZOrder.HWND_TOPMOST : WindowPosZOrder.HWND_NOTOPMOST; SetWindowPos(_hwnd, hWndInsertAfter, 0, 0, 0, 0, SetWindowPosFlags.SWP_NOMOVE | SetWindowPosFlags.SWP_NOSIZE | SetWindowPosFlags.SWP_NOACTIVATE); _topmost = value; } protected virtual IntPtr CreateWindowOverride(ushort atom) { return CreateWindowEx( _isUsingComposition ? (int)WindowStyles.WS_EX_NOREDIRECTIONBITMAP : 0, atom, null, (int)WindowStyles.WS_OVERLAPPEDWINDOW | (int) WindowStyles.WS_CLIPCHILDREN, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero); } private void CreateWindow() { // Ensure that the delegate doesn't get garbage collected by storing it as a field. _wndProcDelegate = WndProc; _className = $"Avalonia-{Guid.NewGuid().ToString()}"; // Unique DC helps with performance when using Gpu based rendering const ClassStyles windowClassStyle = ClassStyles.CS_OWNDC | ClassStyles.CS_HREDRAW | ClassStyles.CS_VREDRAW; var wndClassEx = new WNDCLASSEX { cbSize = Marshal.SizeOf<WNDCLASSEX>(), style = (int)windowClassStyle, lpfnWndProc = _wndProcDelegate, hInstance = GetModuleHandle(null), hCursor = DefaultCursor, hbrBackground = IntPtr.Zero, lpszClassName = _className }; ushort atom = RegisterClassEx(ref wndClassEx); if (atom == 0) { throw new Win32Exception(); } _hwnd = CreateWindowOverride(atom); if (_hwnd == IntPtr.Zero) { throw new Win32Exception(); } Handle = new WindowImplPlatformHandle(this); _multitouch = Win32Platform.Options.EnableMultitouch ?? true; if (_multitouch) { RegisterTouchWindow(_hwnd, 0); } if (ShCoreAvailable && Win32Platform.WindowsVersion > PlatformConstants.Windows8) { var monitor = MonitorFromWindow( _hwnd, MONITOR.MONITOR_DEFAULTTONEAREST); if (GetDpiForMonitor( monitor, MONITOR_DPI_TYPE.MDT_EFFECTIVE_DPI, out var dpix, out var dpiy) == 0) { _scaling = dpix / 96.0; } } } private void CreateDropTarget() { var odt = new OleDropTarget(this, _owner); if (OleContext.Current?.RegisterDragDrop(Handle, odt) ?? false) { _dropTarget = odt; } } /// <summary> /// Ported from https://github.com/chromium/chromium/blob/master/ui/views/win/fullscreen_handler.cc /// Method must only be called from inside UpdateWindowProperties. /// </summary> /// <param name="fullscreen"></param> private void SetFullScreen(bool fullscreen) { if (fullscreen) { GetWindowRect(_hwnd, out var windowRect); _savedWindowInfo.WindowRect = windowRect; var current = GetStyle(); var currentEx = GetExtendedStyle(); _savedWindowInfo.Style = current; _savedWindowInfo.ExStyle = currentEx; // Set new window style and size. SetStyle(current & ~(WindowStyles.WS_CAPTION | WindowStyles.WS_THICKFRAME), false); SetExtendedStyle(currentEx & ~(WindowStyles.WS_EX_DLGMODALFRAME | WindowStyles.WS_EX_WINDOWEDGE | WindowStyles.WS_EX_CLIENTEDGE | WindowStyles.WS_EX_STATICEDGE), false); // On expand, if we're given a window_rect, grow to it, otherwise do // not resize. MONITORINFO monitor_info = MONITORINFO.Create(); GetMonitorInfo(MonitorFromWindow(_hwnd, MONITOR.MONITOR_DEFAULTTONEAREST), ref monitor_info); var window_rect = monitor_info.rcMonitor.ToPixelRect(); SetWindowPos(_hwnd, IntPtr.Zero, window_rect.X, window_rect.Y, window_rect.Width, window_rect.Height, SetWindowPosFlags.SWP_NOZORDER | SetWindowPosFlags.SWP_NOACTIVATE | SetWindowPosFlags.SWP_FRAMECHANGED); _isFullScreenActive = true; } else { // Reset original window style and size. The multiple window size/moves // here are ugly, but if SetWindowPos() doesn't redraw, the taskbar won't be // repainted. Better-looking methods welcome. _isFullScreenActive = false; var windowStates = GetWindowStateStyles(); SetStyle((_savedWindowInfo.Style & ~WindowStateMask) | windowStates, false); SetExtendedStyle(_savedWindowInfo.ExStyle, false); // On restore, resize to the previous saved rect size. var new_rect = _savedWindowInfo.WindowRect.ToPixelRect(); SetWindowPos(_hwnd, IntPtr.Zero, new_rect.X, new_rect.Y, new_rect.Width, new_rect.Height, SetWindowPosFlags.SWP_NOZORDER | SetWindowPosFlags.SWP_NOACTIVATE | SetWindowPosFlags.SWP_FRAMECHANGED); UpdateWindowProperties(_windowProperties, true); } TaskBarList.MarkFullscreen(_hwnd, fullscreen); ExtendClientArea(); } private MARGINS UpdateExtendMargins() { RECT borderThickness = new RECT(); RECT borderCaptionThickness = new RECT(); AdjustWindowRectEx(ref borderCaptionThickness, (uint)(GetStyle()), false, 0); AdjustWindowRectEx(ref borderThickness, (uint)(GetStyle() & ~WindowStyles.WS_CAPTION), false, 0); borderThickness.left *= -1; borderThickness.top *= -1; borderCaptionThickness.left *= -1; borderCaptionThickness.top *= -1; bool wantsTitleBar = _extendChromeHints.HasAllFlags(ExtendClientAreaChromeHints.SystemChrome) || _extendTitleBarHint == -1; if (!wantsTitleBar) { borderCaptionThickness.top = 1; } MARGINS margins = new MARGINS(); margins.cxLeftWidth = 1; margins.cxRightWidth = 1; margins.cyBottomHeight = 1; if (_extendTitleBarHint != -1) { borderCaptionThickness.top = (int)(_extendTitleBarHint * RenderScaling); } margins.cyTopHeight = _extendChromeHints.HasAllFlags(ExtendClientAreaChromeHints.SystemChrome) && !_extendChromeHints.HasAllFlags(ExtendClientAreaChromeHints.PreferSystemChrome) ? borderCaptionThickness.top : 1; if (WindowState == WindowState.Maximized) { _extendedMargins = new Thickness(0, (borderCaptionThickness.top - borderThickness.top) / RenderScaling, 0, 0); _offScreenMargin = new Thickness(borderThickness.left / RenderScaling, borderThickness.top / RenderScaling, borderThickness.right / RenderScaling, borderThickness.bottom / RenderScaling); } else { _extendedMargins = new Thickness(0, (borderCaptionThickness.top) / RenderScaling, 0, 0); _offScreenMargin = new Thickness(); } return margins; } private void ExtendClientArea() { if (!_shown) { return; } if (DwmIsCompositionEnabled(out bool compositionEnabled) < 0 || !compositionEnabled) { _isClientAreaExtended = false; return; } GetClientRect(_hwnd, out var rcClient); GetWindowRect(_hwnd, out var rcWindow); // Inform the application of the frame change. SetWindowPos(_hwnd, IntPtr.Zero, rcWindow.left, rcWindow.top, rcClient.Width, rcClient.Height, SetWindowPosFlags.SWP_FRAMECHANGED | SetWindowPosFlags.SWP_NOACTIVATE); if (_isClientAreaExtended && WindowState != WindowState.FullScreen) { var margins = UpdateExtendMargins(); DwmExtendFrameIntoClientArea(_hwnd, ref margins); } else { var margins = new MARGINS(); DwmExtendFrameIntoClientArea(_hwnd, ref margins); _offScreenMargin = new Thickness(); _extendedMargins = new Thickness(); Resize(new Size(rcWindow.Width/ RenderScaling, rcWindow.Height / RenderScaling), PlatformResizeReason.Layout); } if(!_isClientAreaExtended || (_extendChromeHints.HasAllFlags(ExtendClientAreaChromeHints.SystemChrome) && !_extendChromeHints.HasAllFlags(ExtendClientAreaChromeHints.PreferSystemChrome))) { EnableCloseButton(_hwnd); } else { DisableCloseButton(_hwnd); } ExtendClientAreaToDecorationsChanged?.Invoke(_isClientAreaExtended); } private void ShowWindow(WindowState state, bool activate) { _shown = true; if (_isClientAreaExtended) { ExtendClientArea(); } ShowWindowCommand? command; var newWindowProperties = _windowProperties; switch (state) { case WindowState.Minimized: newWindowProperties.IsFullScreen = false; command = ShowWindowCommand.Minimize; break; case WindowState.Maximized: newWindowProperties.IsFullScreen = false; command = ShowWindowCommand.Maximize; break; case WindowState.Normal: newWindowProperties.IsFullScreen = false; command = IsWindowVisible(_hwnd) ? ShowWindowCommand.Restore : activate ? ShowWindowCommand.Normal : ShowWindowCommand.ShowNoActivate; break; case WindowState.FullScreen: newWindowProperties.IsFullScreen = true; command = IsWindowVisible(_hwnd) ? (ShowWindowCommand?)null : ShowWindowCommand.Restore; break; default: throw new ArgumentException("Invalid WindowState."); } UpdateWindowProperties(newWindowProperties); if (command.HasValue) { UnmanagedMethods.ShowWindow(_hwnd, command.Value); } if (state == WindowState.Maximized) { MaximizeWithoutCoveringTaskbar(); } if (!Design.IsDesignMode && activate) { SetFocus(_hwnd); SetForegroundWindow(_hwnd); } } private void BeforeCloseCleanup(bool isDisposing) { // Based on https://github.com/dotnet/wpf/blob/master/src/Microsoft.DotNet.Wpf/src/PresentationFramework/System/Windows/Window.cs#L4270-L4337 // We need to enable parent window before destroying child window to prevent OS from activating a random window behind us (or last active window). // This is described here: https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-enablewindow#remarks // We need to verify if parent is still alive (perhaps it got destroyed somehow). if (_parent != null && IsWindow(_parent._hwnd)) { var wasActive = GetActiveWindow() == _hwnd; // We can only set enabled state if we are not disposing - generally Dispose happens after enabled state has been set. // Ignoring this would cause us to enable a window that might be disabled. if (!isDisposing) { // Our window closed callback will set enabled state to a correct value after child window gets destroyed. _parent.SetEnabled(true); } // We also need to activate our parent window since again OS might try to activate a window behind if it is not set. if (wasActive) { SetActiveWindow(_parent._hwnd); } } } private void MaximizeWithoutCoveringTaskbar() { IntPtr monitor = MonitorFromWindow(_hwnd, MONITOR.MONITOR_DEFAULTTONEAREST); if (monitor != IntPtr.Zero) { var monitorInfo = MONITORINFO.Create(); if (GetMonitorInfo(monitor, ref monitorInfo)) { var x = monitorInfo.rcWork.left; var y = monitorInfo.rcWork.top; var cx = Math.Abs(monitorInfo.rcWork.right - x); var cy = Math.Abs(monitorInfo.rcWork.bottom - y); SetWindowPos(_hwnd, WindowPosZOrder.HWND_NOTOPMOST, x, y, cx, cy, SetWindowPosFlags.SWP_SHOWWINDOW); } } } private WindowStyles GetWindowStateStyles() { return GetStyle() & WindowStateMask; } private WindowStyles GetStyle() { if (_isFullScreenActive) { return _savedWindowInfo.Style; } else { return (WindowStyles)GetWindowLong(_hwnd, (int)WindowLongParam.GWL_STYLE); } } private WindowStyles GetExtendedStyle() { if (_isFullScreenActive) { return _savedWindowInfo.ExStyle; } else { return (WindowStyles)GetWindowLong(_hwnd, (int)WindowLongParam.GWL_EXSTYLE); } } private void SetStyle(WindowStyles style, bool save = true) { if (save) { _savedWindowInfo.Style = style; } if (!_isFullScreenActive) { SetWindowLong(_hwnd, (int)WindowLongParam.GWL_STYLE, (uint)style); } } private void SetExtendedStyle(WindowStyles style, bool save = true) { if (save) { _savedWindowInfo.ExStyle = style; } if (!_isFullScreenActive) { SetWindowLong(_hwnd, (int)WindowLongParam.GWL_EXSTYLE, (uint)style); } } private void UpdateWindowProperties(WindowProperties newProperties, bool forceChanges = false) { var oldProperties = _windowProperties; // Calling SetWindowPos will cause events to be sent and we need to respond // according to the new values already. _windowProperties = newProperties; if ((oldProperties.ShowInTaskbar != newProperties.ShowInTaskbar) || forceChanges) { var exStyle = GetExtendedStyle(); if (newProperties.ShowInTaskbar) { exStyle |= WindowStyles.WS_EX_APPWINDOW; if (_hiddenWindowIsParent) { // Can't enable the taskbar icon by clearing the parent window unless the window // is hidden. Hide the window and show it again with the same activation state // when we've finished. Interestingly it seems to work fine the other way. var shown = IsWindowVisible(_hwnd); var activated = GetActiveWindow() == _hwnd; if (shown) Hide(); _hiddenWindowIsParent = false; SetParent(null); if (shown) Show(activated, false); } } else { // To hide a non-owned window's taskbar icon we need to parent it to a hidden window. if (_parent is null) { SetWindowLongPtr(_hwnd, (int)WindowLongParam.GWL_HWNDPARENT, OffscreenParentWindow.Handle); _hiddenWindowIsParent = true; } exStyle &= ~WindowStyles.WS_EX_APPWINDOW; } SetExtendedStyle(exStyle); } WindowStyles style; if ((oldProperties.IsResizable != newProperties.IsResizable) || forceChanges) { style = GetStyle(); if (newProperties.IsResizable) { style |= WindowStyles.WS_SIZEFRAME; style |= WindowStyles.WS_MAXIMIZEBOX; } else { style &= ~WindowStyles.WS_SIZEFRAME; style &= ~WindowStyles.WS_MAXIMIZEBOX; } SetStyle(style); } if (oldProperties.IsFullScreen != newProperties.IsFullScreen) { SetFullScreen(newProperties.IsFullScreen); } if ((oldProperties.Decorations != newProperties.Decorations) || forceChanges) { style = GetStyle(); const WindowStyles fullDecorationFlags = WindowStyles.WS_CAPTION | WindowStyles.WS_SYSMENU; if (newProperties.Decorations == SystemDecorations.Full) { style |= fullDecorationFlags; } else { style &= ~fullDecorationFlags; } SetStyle(style); if (!_isFullScreenActive) { var margin = newProperties.Decorations == SystemDecorations.BorderOnly ? 1 : 0; var margins = new MARGINS { cyBottomHeight = margin, cxRightWidth = margin, cxLeftWidth = margin, cyTopHeight = margin }; DwmExtendFrameIntoClientArea(_hwnd, ref margins); GetClientRect(_hwnd, out var oldClientRect); var oldClientRectOrigin = new POINT(); ClientToScreen(_hwnd, ref oldClientRectOrigin); oldClientRect.Offset(oldClientRectOrigin); var newRect = oldClientRect; if (newProperties.Decorations == SystemDecorations.Full) { AdjustWindowRectEx(ref newRect, (uint)style, false, (uint)GetExtendedStyle()); } SetWindowPos(_hwnd, IntPtr.Zero, newRect.left, newRect.top, newRect.Width, newRect.Height, SetWindowPosFlags.SWP_NOZORDER | SetWindowPosFlags.SWP_NOACTIVATE | SetWindowPosFlags.SWP_FRAMECHANGED); } } } private const int MF_BYCOMMAND = 0x0; private const int MF_BYPOSITION = 0x400; private const int MF_REMOVE = 0x1000; private const int MF_ENABLED = 0x0; private const int MF_GRAYED = 0x1; private const int MF_DISABLED = 0x2; private const int SC_CLOSE = 0xF060; void DisableCloseButton(IntPtr hwnd) { EnableMenuItem(GetSystemMenu(hwnd, false), SC_CLOSE, MF_BYCOMMAND | MF_DISABLED | MF_GRAYED); } void EnableCloseButton(IntPtr hwnd) { EnableMenuItem(GetSystemMenu(hwnd, false), SC_CLOSE, MF_BYCOMMAND | MF_ENABLED); } #if USE_MANAGED_DRAG private Point ScreenToClient(Point point) { var p = new UnmanagedMethods.POINT { X = (int)point.X, Y = (int)point.Y }; UnmanagedMethods.ScreenToClient(_hwnd, ref p); return new Point(p.X, p.Y); } #endif PixelSize EglGlPlatformSurface.IEglWindowGlPlatformSurfaceInfo.Size { get { GetClientRect(_hwnd, out var rect); return new PixelSize( Math.Max(1, rect.right - rect.left), Math.Max(1, rect.bottom - rect.top)); } } double EglGlPlatformSurface.IEglWindowGlPlatformSurfaceInfo.Scaling => RenderScaling; IntPtr EglGlPlatformSurface.IEglWindowGlPlatformSurfaceInfo.Handle => Handle.Handle; public void SetExtendClientAreaToDecorationsHint(bool hint) { _isClientAreaExtended = hint; ExtendClientArea(); } public void SetExtendClientAreaChromeHints(ExtendClientAreaChromeHints hints) { _extendChromeHints = hints; ExtendClientArea(); } /// <inheritdoc/> public void SetExtendClientAreaTitleBarHeightHint(double titleBarHeight) { _extendTitleBarHint = titleBarHeight; ExtendClientArea(); } /// <inheritdoc/> public bool IsClientAreaExtendedToDecorations => _isClientAreaExtended; /// <inheritdoc/> public Action<bool> ExtendClientAreaToDecorationsChanged { get; set; } /// <inheritdoc/> public bool NeedsManagedDecorations => _isClientAreaExtended && _extendChromeHints.HasAllFlags(ExtendClientAreaChromeHints.PreferSystemChrome); /// <inheritdoc/> public Thickness ExtendedMargins => _extendedMargins; /// <inheritdoc/> public Thickness OffScreenMargin => _offScreenMargin; /// <inheritdoc/> public AcrylicPlatformCompensationLevels AcrylicCompensationLevels { get; } = new AcrylicPlatformCompensationLevels(1, 0.8, 0); private ResizeReasonScope SetResizeReason(PlatformResizeReason reason) { var old = _resizeReason; _resizeReason = reason; return new ResizeReasonScope(this, old); } private struct SavedWindowInfo { public WindowStyles Style { get; set; } public WindowStyles ExStyle { get; set; } public RECT WindowRect { get; set; } }; private struct WindowProperties { public bool ShowInTaskbar; public bool IsResizable; public SystemDecorations Decorations; public bool IsFullScreen; } private struct ResizeReasonScope : IDisposable { private readonly WindowImpl _owner; private readonly PlatformResizeReason _restore; public ResizeReasonScope(WindowImpl owner, PlatformResizeReason restore) { _owner = owner; _restore = restore; } public void Dispose() => _owner._resizeReason = _restore; } public ITextInputMethodImpl TextInputMethod => Imm32InputMethod.Current; private class WindowImplPlatformHandle : IPlatformHandle { private readonly WindowImpl _owner; public WindowImplPlatformHandle(WindowImpl owner) => _owner = owner; public IntPtr Handle => _owner.Hwnd; public string HandleDescriptor => PlatformConstants.WindowHandleType; } } }
// This file is part of YamlDotNet - A .NET library for YAML. // Copyright (c) Antoine Aubry and contributors // Copyright (c) 2011 Andy Pickett // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies // of the Software, and to permit persons to whom the Software is furnished to do // so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. using System; using System.Collections.Generic; using System.Reflection; using System.Text; using YamlDotNet.Core; using YamlDotNet.Core.Events; using YamlDotNet.Serialization; namespace YamlDotNet.RepresentationModel { /// <summary> /// Represents a mapping node in the YAML document. /// </summary> [Serializable] public sealed class YamlMappingNode : YamlNode, IEnumerable<KeyValuePair<YamlNode, YamlNode>>, IYamlConvertible { private readonly IDictionary<YamlNode, YamlNode> children = new Dictionary<YamlNode, YamlNode>(); /// <summary> /// Gets the children of the current node. /// </summary> /// <value>The children.</value> public IDictionary<YamlNode, YamlNode> Children { get { return children; } } /// <summary> /// Gets or sets the style of the node. /// </summary> /// <value>The style.</value> public MappingStyle Style { get; set; } /// <summary> /// Initializes a new instance of the <see cref="YamlMappingNode"/> class. /// </summary> internal YamlMappingNode(IParser parser, DocumentLoadingState state) { Load(parser, state); } private void Load(IParser parser, DocumentLoadingState state) { var mapping = parser.Expect<MappingStart>(); Load(mapping, state); Style = mapping.Style; bool hasUnresolvedAliases = false; while (!parser.Accept<MappingEnd>()) { var key = ParseNode(parser, state); var value = ParseNode(parser, state); try { children.Add(key, value); } catch (ArgumentException err) { throw new YamlException(key.Start, key.End, "Duplicate key", err); } hasUnresolvedAliases |= key is YamlAliasNode || value is YamlAliasNode; } if (hasUnresolvedAliases) { state.AddNodeWithUnresolvedAliases(this); } parser.Expect<MappingEnd>(); } /// <summary> /// Initializes a new instance of the <see cref="YamlMappingNode"/> class. /// </summary> public YamlMappingNode() { } /// <summary> /// Initializes a new instance of the <see cref="YamlMappingNode"/> class. /// </summary> public YamlMappingNode(params KeyValuePair<YamlNode, YamlNode>[] children) : this((IEnumerable<KeyValuePair<YamlNode, YamlNode>>)children) { } /// <summary> /// Initializes a new instance of the <see cref="YamlMappingNode"/> class. /// </summary> public YamlMappingNode(IEnumerable<KeyValuePair<YamlNode, YamlNode>> children) { foreach (var child in children) { this.children.Add(child); } } /// <summary> /// Initializes a new instance of the <see cref="YamlMappingNode"/> class. /// </summary> /// <param name="children">A sequence of <see cref="YamlNode"/> where even elements are keys and odd elements are values.</param> public YamlMappingNode(params YamlNode[] children) : this((IEnumerable<YamlNode>)children) { } /// <summary> /// Initializes a new instance of the <see cref="YamlMappingNode"/> class. /// </summary> /// <param name="children">A sequence of <see cref="YamlNode"/> where even elements are keys and odd elements are values.</param> public YamlMappingNode(IEnumerable<YamlNode> children) { using (var enumerator = children.GetEnumerator()) { while (enumerator.MoveNext()) { var key = enumerator.Current; if (!enumerator.MoveNext()) { throw new ArgumentException("When constructing a mapping node with a sequence, the number of elements of the sequence must be even."); } Add(key, enumerator.Current); } } } /// <summary> /// Adds the specified mapping to the <see cref="Children"/> collection. /// </summary> /// <param name="key">The key node.</param> /// <param name="value">The value node.</param> public void Add(YamlNode key, YamlNode value) { children.Add(key, value); } /// <summary> /// Adds the specified mapping to the <see cref="Children"/> collection. /// </summary> /// <param name="key">The key node.</param> /// <param name="value">The value node.</param> public void Add(string key, YamlNode value) { children.Add(new YamlScalarNode(key), value); } /// <summary> /// Adds the specified mapping to the <see cref="Children"/> collection. /// </summary> /// <param name="key">The key node.</param> /// <param name="value">The value node.</param> public void Add(YamlNode key, string value) { children.Add(key, new YamlScalarNode(value)); } /// <summary> /// Adds the specified mapping to the <see cref="Children"/> collection. /// </summary> /// <param name="key">The key node.</param> /// <param name="value">The value node.</param> public void Add(string key, string value) { children.Add(new YamlScalarNode(key), new YamlScalarNode(value)); } /// <summary> /// Resolves the aliases that could not be resolved when the node was created. /// </summary> /// <param name="state">The state of the document.</param> internal override void ResolveAliases(DocumentLoadingState state) { Dictionary<YamlNode, YamlNode> keysToUpdate = null; Dictionary<YamlNode, YamlNode> valuesToUpdate = null; foreach (var entry in children) { if (entry.Key is YamlAliasNode) { if (keysToUpdate == null) { keysToUpdate = new Dictionary<YamlNode, YamlNode>(); } keysToUpdate.Add(entry.Key, state.GetNode(entry.Key.Anchor, true, entry.Key.Start, entry.Key.End)); } if (entry.Value is YamlAliasNode) { if (valuesToUpdate == null) { valuesToUpdate = new Dictionary<YamlNode, YamlNode>(); } valuesToUpdate.Add(entry.Key, state.GetNode(entry.Value.Anchor, true, entry.Value.Start, entry.Value.End)); } } if (valuesToUpdate != null) { foreach (var entry in valuesToUpdate) { children[entry.Key] = entry.Value; } } if (keysToUpdate != null) { foreach (var entry in keysToUpdate) { YamlNode value = children[entry.Key]; children.Remove(entry.Key); children.Add(entry.Value, value); } } } /// <summary> /// Saves the current node to the specified emitter. /// </summary> /// <param name="emitter">The emitter where the node is to be saved.</param> /// <param name="state">The state.</param> internal override void Emit(IEmitter emitter, EmitterState state) { emitter.Emit(new MappingStart(Anchor, Tag, true, Style)); foreach (var entry in children) { entry.Key.Save(emitter, state); entry.Value.Save(emitter, state); } emitter.Emit(new MappingEnd()); } /// <summary> /// Accepts the specified visitor by calling the appropriate Visit method on it. /// </summary> /// <param name="visitor"> /// A <see cref="IYamlVisitor"/>. /// </param> public override void Accept(IYamlVisitor visitor) { visitor.Visit(this); } /// <summary /> public override bool Equals(object obj) { var other = obj as YamlMappingNode; if (other == null || !Equals(other) || children.Count != other.children.Count) { return false; } foreach (var entry in children) { YamlNode otherNode; if (!other.children.TryGetValue(entry.Key, out otherNode) || !SafeEquals(entry.Value, otherNode)) { return false; } } return true; } /// <summary> /// Serves as a hash function for a particular type. /// </summary> /// <returns> /// A hash code for the current <see cref="T:System.Object"/>. /// </returns> public override int GetHashCode() { var hashCode = base.GetHashCode(); foreach (var entry in children) { hashCode = CombineHashCodes(hashCode, GetHashCode(entry.Key)); hashCode = CombineHashCodes(hashCode, GetHashCode(entry.Value)); } return hashCode; } /// <summary> /// Recursively enumerates all the nodes from the document, starting on the current node, /// and throwing <see cref="MaximumRecursionLevelReachedException"/> /// if <see cref="RecursionLevel.Maximum"/> is reached. /// </summary> internal override IEnumerable<YamlNode> SafeAllNodes(RecursionLevel level) { level.Increment(); yield return this; foreach (var child in children) { foreach (var node in child.Key.SafeAllNodes(level)) { yield return node; } foreach (var node in child.Value.SafeAllNodes(level)) { yield return node; } } level.Decrement(); } /// <summary> /// Gets the type of node. /// </summary> public override YamlNodeType NodeType { get { return YamlNodeType.Mapping; } } /// <summary> /// Returns a <see cref="System.String"/> that represents this instance. /// </summary> /// <returns> /// A <see cref="System.String"/> that represents this instance. /// </returns> internal override string ToString(RecursionLevel level) { if (!level.TryIncrement()) { return MaximumRecursionLevelReachedToStringValue; } var text = new StringBuilder("{ "); foreach (var child in children) { if (text.Length > 2) { text.Append(", "); } text.Append("{ ").Append(child.Key.ToString(level)).Append(", ").Append(child.Value.ToString(level)).Append(" }"); } text.Append(" }"); level.Decrement(); return text.ToString(); } /// <summary> /// Returns a <see cref="System.String"/> that represents this instance. /// </summary> /// <returns> /// A <see cref="System.String"/> that represents this instance. /// </returns> internal override string ToJson(RecursionLevel level) { if (!level.TryIncrement()) { return MaximumRecursionLevelReachedToStringValue; } var text = new StringBuilder("{"); foreach (var child in children) { if (text.Length > 1) { text.Append(","); } text.Append(child.Key.ToJson(level)).Append(":").Append(child.Value.ToJson(level)); } text.Append("}"); level.Decrement(); return text.ToString(); } #region IEnumerable<KeyValuePair<YamlNode,YamlNode>> Members /// <summary /> public IEnumerator<KeyValuePair<YamlNode, YamlNode>> GetEnumerator() { return children.GetEnumerator(); } #endregion #region IEnumerable Members System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return GetEnumerator(); } #endregion void IYamlConvertible.Read(IParser parser, Type expectedType, ObjectDeserializer nestedObjectDeserializer) { Load(parser, new DocumentLoadingState()); } void IYamlConvertible.Write(IEmitter emitter, ObjectSerializer nestedObjectSerializer) { Emit(emitter, new EmitterState()); } /// <summary> /// Creates a <see cref="YamlMappingNode" /> containing a key-value pair for each property of the specified object. /// </summary> public static YamlMappingNode FromObject(object mapping) { if (mapping == null) { throw new ArgumentNullException("mapping"); } var result = new YamlMappingNode(); foreach (var property in mapping.GetType().GetPublicProperties()) { if (property.CanRead && property.GetGetMethod().GetParameters().Length == 0) { var value = property.GetValue(mapping, null); var valueNode = (value as YamlNode) ?? (Convert.ToString(value)); result.Add(property.Name, valueNode); } } return result; } } }
// **************************************************************** // This is free software licensed under the NUnit license. You // may obtain a copy of the license as well as information regarding // copyright ownership at http://nunit.org. // **************************************************************** using System; using System.IO; using System.Reflection; using NUnit.Framework; using NUnit.Core; using NUnit.Tests.Assemblies; namespace NUnit.Util.Tests { [TestFixture] public class TestDomainFixture { private static TestDomain testDomain; private static ITest loadedTest; private static readonly string mockDll = MockAssembly.AssemblyPath; [TestFixtureSetUp] public static void MakeAppDomain() { testDomain = new TestDomain(); testDomain.Load( new TestPackage(mockDll)); loadedTest = testDomain.Test; } [TestFixtureTearDown] public static void UnloadTestDomain() { if ( testDomain != null ) testDomain.Unload(); loadedTest = null; testDomain = null; } [Test] public void AssemblyIsLoadedCorrectly() { Assert.IsNotNull(loadedTest, "Test not loaded"); Assert.AreEqual(MockAssembly.Tests, loadedTest.TestCount ); } [Test] public void AppDomainIsSetUpCorrectly() { AppDomain domain = testDomain.AppDomain; AppDomainSetup setup = testDomain.AppDomain.SetupInformation; Assert.That(setup.ApplicationName, Is.StringStarting("Tests_")); Assert.AreEqual( Path.GetDirectoryName(mockDll), setup.ApplicationBase, "ApplicationBase" ); Assert.That( Path.GetFileName( setup.ConfigurationFile ), Is.EqualTo("mock-assembly.dll.config").IgnoreCase, "ConfigurationFile"); Assert.AreEqual( null, setup.PrivateBinPath, "PrivateBinPath" ); Assert.AreEqual( Path.GetDirectoryName(mockDll), setup.ShadowCopyDirectories, "ShadowCopyDirectories" ); Assert.AreEqual( Path.GetDirectoryName(mockDll), domain.BaseDirectory, "BaseDirectory" ); Assert.That(domain.FriendlyName, Is.EqualTo("test-domain-mock-assembly.dll").IgnoreCase, "FriendlyName"); Assert.IsTrue( testDomain.AppDomain.ShadowCopyFiles, "ShadowCopyFiles" ); } [Test] public void CanRunMockAssemblyTests() { TestResult result = testDomain.Run( NullListener.NULL ); Assert.IsNotNull(result); ResultSummarizer summarizer = new ResultSummarizer(result); Assert.AreEqual(MockAssembly.TestsRun, summarizer.TestsRun, "TestsRun"); Assert.AreEqual(MockAssembly.Ignored, summarizer.Ignored, "Ignored"); Assert.AreEqual(MockAssembly.Errors, summarizer.Errors, "Errors"); Assert.AreEqual(MockAssembly.Failures, summarizer.Failures, "Failures"); } } [TestFixture] public class TestDomainRunnerTests : NUnit.Core.Tests.BasicRunnerTests { protected override TestRunner CreateRunner(int runnerID) { return new TestDomain(runnerID); } } [TestFixture] public class TestDomainTests { private TestDomain testDomain; private static readonly string mockDll = MockAssembly.AssemblyPath; [SetUp] public void SetUp() { testDomain = new TestDomain(); } [TearDown] public void TearDown() { testDomain.Unload(); } [Test] [ExpectedException(typeof(FileNotFoundException))] public void FileNotFound() { testDomain.Load( new TestPackage( "/xxxx.dll" ) ); } [Test] public void InvalidTestFixture() { TestPackage package = new TestPackage(mockDll); package.TestName = "NUnit.Tests.Assemblies.Bogus"; Assert.IsFalse( testDomain.Load( package ) ); } // Doesn't work under .NET 2.0 Beta 2 //[Test] //[ExpectedException(typeof(BadImageFormatException))] public void FileFoundButNotValidAssembly() { string badfile = Path.GetFullPath("x.dll"); try { StreamWriter sw = new StreamWriter( badfile ); //StreamWriter sw = file.AppendText(); sw.WriteLine("This is a new entry to add to the file"); sw.WriteLine("This is yet another line to add..."); sw.Flush(); sw.Close(); testDomain.Load( new TestPackage( badfile ) ); } finally { if ( File.Exists( badfile ) ) File.Delete( badfile ); } } [Test] public void SpecificTestFixture() { TestPackage package = new TestPackage(mockDll); package.TestName = "NUnit.Tests.Assemblies.MockTestFixture"; testDomain.Load( package ); TestResult result = testDomain.Run( NullListener.NULL ); ResultSummarizer summarizer = new ResultSummarizer(result); Assert.AreEqual(MockTestFixture.TestsRun, summarizer.TestsRun, "TestsRun"); Assert.AreEqual(MockTestFixture.Ignored, summarizer.Ignored, "Ignored"); Assert.AreEqual(MockTestFixture.Errors, summarizer.Errors, "Errors"); Assert.AreEqual(MockTestFixture.Failures, summarizer.Failures, "Failures"); } [Test] public void ConfigFileOverrideIsHonored() { TestPackage package = new TestPackage( "MyProject.nunit" ); package.Assemblies.Add(mockDll); package.ConfigurationFile = "override.config"; testDomain.Load( package ); Assert.AreEqual( "override.config", Path.GetFileName( testDomain.AppDomain.SetupInformation.ConfigurationFile ) ); } [Test] public void BasePathOverrideIsHonored() { TestPackage package = new TestPackage( "MyProject.nunit" ); package.Assemblies.Add( MockAssembly.AssemblyPath ); package.BasePath = Path.GetDirectoryName( Environment.CurrentDirectory ); package.PrivateBinPath = Path.GetFileName( Environment.CurrentDirectory ); testDomain.Load( package ); Assert.AreEqual( package.BasePath, testDomain.AppDomain.BaseDirectory ); } [Test] public void BinPathOverrideIsHonored() { TestPackage package = new TestPackage( "MyProject.nunit" ); package.Assemblies.Add( MockAssembly.AssemblyPath ); package.PrivateBinPath = "dummy;junk"; testDomain.Load( package ); Assert.AreEqual( "dummy;junk", testDomain.AppDomain.SetupInformation.PrivateBinPath ); } // Turning off shadow copy only works when done for the primary app domain // So this test can only work if it's already off // This doesn't seem to be documented anywhere [Test, Platform(Exclude="mono-1.0", Reason="Test hangs under the 1.0 profile")] public void TurnOffShadowCopy() { TestPackage package = new TestPackage(mockDll); package.Settings["ShadowCopyFiles"] = false; testDomain.Load( package ); Assert.IsFalse( testDomain.AppDomain.ShadowCopyFiles ); // Prove that shadow copy is really off // string location = "NOT_FOUND"; // foreach( Assembly assembly in testDomain.AppDomain.GetAssemblies() ) // { // if ( assembly.FullName.StartsWith( "mock-assembly" ) ) // { // location = Path.GetDirectoryName( assembly.Location ); // break; // } // } // // StringAssert.StartsWith( AppDomain.CurrentDomain.BaseDirectory.ToLower(), location.ToLower() ); } } }
using UnityEngine; using System.Collections; using System; using System.IO; using System.Runtime.Serialization.Formatters.Binary; using System.Xml; using System.Xml.Serialization; using System.Text; /// <summary> /// Recording /// Serialized to save game /// Fields can be added (and will assume their default value if not available in the file) /// but removing or renaming a field will result in an exception when a file is next loaded /// </summary> [Serializable] public class Save { public const string dir = ""; public const int VERSION = 5; [NonSerialized] public string filename; public int worldUnlocked; public int levelUnlocked; public string playerName = "Name"; public int droneCount = 0; public Save() { for (int i = 0; i < highScores.Length; ++i) { highScores[i].Time = 99999.00f; } } // The high scores. [Serializable] public struct LevelHighScore { public float Score; public float Speed; public float Time; public int Stars; } public LevelHighScore[] highScores = new LevelHighScore[255]; // Options public bool OnlineEnabled = true; public float BGMSound = 1.0f; // Get a high score for a level. public LevelHighScore GetHighScore(int _levelID) { if (_levelID >= highScores.Length || _levelID < 0) return new LevelHighScore(); return highScores[_levelID]; } // Update the high score for a level. public void UpdateHighScore(LevelHighScore _score, int _levelID) { // Get the current scores LevelHighScore current = GetHighScore(_levelID); // Compare them and update them. if (_score.Score > current.Score) current.Score = _score.Score; if (_score.Speed > current.Speed) current.Speed = _score.Speed; if (_score.Time < current.Time || current.Time == 0) current.Time = _score.Time; if (_score.Stars > current.Stars) current.Stars = _score.Stars; // Set the score. if (_levelID < highScores.Length && _levelID >= 0) highScores[_levelID] = current; } public string Write() { return Write(filename); } public string Write(string filename) { #if !UNITY_WEBPLAYER // Get the full path. string fullfilename = Application.persistentDataPath + dir + "/" + filename; Directory.CreateDirectory(Application.persistentDataPath + dir); // Now save. // Open the file. FileStream file = new FileStream(fullfilename, FileMode.OpenOrCreate, FileAccess.Write); BinaryWriter writer = new BinaryWriter(file); #else string fullfilename = filename; MemoryStream ms = new MemoryStream(); BinaryWriter writer = new BinaryWriter(ms); #endif // Write the identifying version number. writer.Write(VERSION); // Write the rest of the data. writer.Write(worldUnlocked); // The world unlocked. writer.Write(levelUnlocked); // The level unlocked. // Write the player name writer.Write(playerName); // Write the options (no longer used) writer.Write(false); writer.Write(0.0f); writer.Write(0.0f); // Write the high scores writer.Write(highScores.Length); // How many high scores there are. for (int i = 0; i < highScores.Length; ++i) { // Write each element. writer.Write(highScores[i].Score); // The score writer.Write(highScores[i].Speed); // The speed writer.Write(highScores[i].Time); // The time writer.Write(highScores[i].Stars); // How many stars } // Write drone count writer.Write(droneCount); #if UNITY_WEBPLAYER byte[] bytes = ms.ToArray(); string b64 = Convert.ToBase64String(bytes); PlayerPrefs.SetString("savefile", b64); ms.Close(); #endif // Cool we're done. writer.Close(); #if !UNITY_WEBPLAYER file.Close(); #endif // Return the full filename just in case something needs it. return fullfilename; } public static Save Read(string filename) { #if UNITY_WEBPLAYER string savefile = PlayerPrefs.GetString("savefile", ""); if (savefile == "") return null; byte[] binary = System.Convert.FromBase64String(savefile); MemoryStream ms = new MemoryStream(binary); BinaryReader reader = new BinaryReader(ms); #else string fullfilename = Application.persistentDataPath + dir + "/" + filename; if (!File.Exists(fullfilename)) return null; // Open the file. FileStream file = new FileStream(fullfilename, FileMode.Open, FileAccess.Read); BinaryReader reader = new BinaryReader(file); #endif // Read the version number int version = reader.ReadInt32(); // Use the function that corresponds Save read; switch (version) { case 1: read = Read1(reader); break; case 2: read = Read2(reader); break; case 3: read = Read3(reader); break; case 4: read = Read4(reader); break; case 5: read = Read5(reader); break; default: throw new NotImplementedException(); } read.filename = filename; // Close the file reader.Close(); #if UNITY_WEBPLAYER ms.Close(); #else file.Close(); #endif return read; } public static Save Read1(BinaryReader reader) { // Create a new save to read into. Save save = new Save(); // Read in the unlocked levels save.worldUnlocked = reader.ReadInt32(); save.levelUnlocked = reader.ReadInt32(); // Read in the high scores. int levelCount = reader.ReadInt32(); save.highScores = new LevelHighScore[levelCount]; // Load the scores for (int i = 0; i < levelCount; ++i) { save.highScores[i].Score = reader.ReadSingle(); save.highScores[i].Speed = reader.ReadSingle(); save.highScores[i].Time = reader.ReadSingle(); save.highScores[i].Stars = reader.ReadInt32(); } // Return the new save. return save; } public static Save Read2(BinaryReader reader) { // Create a new save to read into. Save save = new Save(); // Read in the unlocked levels save.worldUnlocked = reader.ReadInt32(); save.levelUnlocked = reader.ReadInt32(); // Read the player name save.playerName = reader.ReadString(); // Read in the high scores. int levelCount = reader.ReadInt32(); save.highScores = new LevelHighScore[levelCount]; // Load the scores for (int i = 0; i < levelCount; ++i) { save.highScores[i].Score = reader.ReadSingle(); save.highScores[i].Speed = reader.ReadSingle(); save.highScores[i].Time = reader.ReadSingle(); save.highScores[i].Stars = reader.ReadInt32(); } // Return the new save. return save; } public static Save Read3(BinaryReader reader) { // Create a new save to read into. Save save = new Save(); // Read in the unlocked levels save.worldUnlocked = reader.ReadInt32(); save.levelUnlocked = reader.ReadInt32(); // Read the player name save.playerName = reader.ReadString(); // Read the options save.OnlineEnabled = reader.ReadBoolean(); reader.ReadSingle(); reader.ReadSingle(); // Read in the high scores. int levelCount = reader.ReadInt32(); save.highScores = new LevelHighScore[levelCount]; // Load the scores for (int i = 0; i < levelCount; ++i) { save.highScores[i].Score = reader.ReadSingle(); save.highScores[i].Speed = reader.ReadSingle(); save.highScores[i].Time = reader.ReadSingle(); save.highScores[i].Stars = reader.ReadInt32(); } // Return the new save. return save; } public static Save Read4(BinaryReader reader) { // Create a new save to read into. Save save = new Save(); // Read in the unlocked levels save.worldUnlocked = reader.ReadInt32(); save.levelUnlocked = reader.ReadInt32(); // Read the player name save.playerName = reader.ReadString(); // Read the options save.OnlineEnabled = reader.ReadBoolean(); reader.ReadSingle(); reader.ReadSingle(); // Read in the high scores. int levelCount = reader.ReadInt32(); save.highScores = new LevelHighScore[levelCount]; // Load the scores for (int i = 0; i < levelCount; ++i) { save.highScores[i].Score = reader.ReadSingle(); save.highScores[i].Speed = reader.ReadSingle(); save.highScores[i].Time = reader.ReadSingle(); save.highScores[i].Stars = reader.ReadInt32(); } // Return the new save. return save; } public static Save Read5(BinaryReader reader) { // Create a new save to read into. Save save = new Save(); // Read in the unlocked levels save.worldUnlocked = reader.ReadInt32(); save.levelUnlocked = reader.ReadInt32(); // Read the player name save.playerName = reader.ReadString(); // Read the options save.OnlineEnabled = reader.ReadBoolean(); reader.ReadSingle(); reader.ReadSingle(); // Read in the high scores. int levelCount = reader.ReadInt32(); save.highScores = new LevelHighScore[levelCount]; // Load the scores for (int i = 0; i < levelCount; ++i) { save.highScores[i].Score = reader.ReadSingle(); save.highScores[i].Speed = reader.ReadSingle(); save.highScores[i].Time = reader.ReadSingle(); save.highScores[i].Stars = reader.ReadInt32(); } // Load drone count save.droneCount = reader.ReadInt32(); // Return the new save. return save; } /* The following metods came from the referenced URL */ public static string UTF8ByteArrayToString(byte[] characters) { UTF8Encoding encoding = new UTF8Encoding(); string constructedString = encoding.GetString(characters); return (constructedString); } public static byte[] StringToUTF8ByteArray(string pXmlString) { UTF8Encoding encoding = new UTF8Encoding(); byte[] byteArray = encoding.GetBytes(pXmlString); return byteArray; } // Here we serialize our UserData object of myData string SerializeObject(object pObject) { string XmlizedString = null; MemoryStream memoryStream = new MemoryStream(); XmlSerializer xs = new XmlSerializer(typeof(Save)); XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8); xs.Serialize(xmlTextWriter, pObject); memoryStream = (MemoryStream)xmlTextWriter.BaseStream; XmlizedString = UTF8ByteArrayToString(memoryStream.ToArray()); return XmlizedString; } // Here we deserialize it back into its original form public static object DeserializeObject(string pXmlizedString) { XmlSerializer xs = new XmlSerializer(typeof(Save)); MemoryStream memoryStream = new MemoryStream(StringToUTF8ByteArray(pXmlizedString)); XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8); return xs.Deserialize(memoryStream); } #if !UNITY_WEBPLAYER void CreateXML(string filelocation, string data) { StreamWriter writer; FileInfo t = new FileInfo(filelocation); if(!t.Exists) { writer = t.CreateText(); } else { t.Delete(); writer = t.CreateText(); } writer.Write(data); writer.Close(); Debug.Log("File written."); } #endif public static string LoadXML(string filelocation) { StreamReader r = File.OpenText(filelocation); string _info = r.ReadToEnd(); r.Close(); return _info; } }
namespace DeOps.Interface { partial class MainForm { /// <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 Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainForm)); this.MainSplit = new System.Windows.Forms.SplitContainer(); this.CommandSplit = new System.Windows.Forms.SplitContainer(); this.BuddyList = new DeOps.Services.Buddy.BuddyView(); this.SideNavStrip = new System.Windows.Forms.ToolStrip(); this.SideViewsButton = new System.Windows.Forms.ToolStripDropDownButton(); this.SideHelpButton = new System.Windows.Forms.ToolStripButton(); this.SideSearchButton = new System.Windows.Forms.ToolStripButton(); this.SideNewsButton = new System.Windows.Forms.ToolStripDropDownButton(); this.CommandTree = new DeOps.Services.Trust.LinkTree(); this.SelectionInfo = new DeOps.Interface.StatusPanel(); this.NavStrip = new System.Windows.Forms.ToolStrip(); this.PersonNavButton = new System.Windows.Forms.ToolStripDropDownButton(); this.ProjectNavButton = new System.Windows.Forms.ToolStripDropDownButton(); this.ComponentNavButton = new System.Windows.Forms.ToolStripDropDownButton(); this.PopoutButton = new System.Windows.Forms.ToolStripButton(); this.NewsButton = new System.Windows.Forms.ToolStripDropDownButton(); this.InternalPanel = new System.Windows.Forms.Panel(); this.TopToolStrip = new System.Windows.Forms.ToolStrip(); this.HomeButton = new System.Windows.Forms.ToolStripButton(); this.ManageButton = new System.Windows.Forms.ToolStripDropDownButton(); this.settingsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.inviteToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem1 = new System.Windows.Forms.ToolStripSeparator(); this.signOnToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.signOffToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.ToolSeparator = new System.Windows.Forms.ToolStripSeparator(); this.PlanButton = new System.Windows.Forms.ToolStripDropDownButton(); this.calanderToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.personalToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.CommButton = new System.Windows.Forms.ToolStripDropDownButton(); this.mailToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.chatToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.HelpInfoButton = new System.Windows.Forms.ToolStripButton(); this.SearchButton = new System.Windows.Forms.ToolStripButton(); this.SearchBox = new System.Windows.Forms.ToolStripTextBox(); this.DataButton = new System.Windows.Forms.ToolStripDropDownButton(); this.commonToolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem(); this.personalToolStripMenuItem2 = new System.Windows.Forms.ToolStripMenuItem(); this.SideToolStrip = new System.Windows.Forms.ToolStrip(); this.toolStripLabel2 = new System.Windows.Forms.ToolStripLabel(); this.OperationButton = new System.Windows.Forms.ToolStripButton(); this.BuddiesButton = new System.Windows.Forms.ToolStripButton(); this.ProjectsButton = new System.Windows.Forms.ToolStripDropDownButton(); this.SideButton = new System.Windows.Forms.ToolStripButton(); this.LockButton = new System.Windows.Forms.ToolStripButton(); this.NetworkButton = new System.Windows.Forms.ToolStripButton(); this.TreeImageList = new System.Windows.Forms.ImageList(this.components); this.NewsTimer = new System.Windows.Forms.Timer(this.components); this.MainSplit.Panel1.SuspendLayout(); this.MainSplit.Panel2.SuspendLayout(); this.MainSplit.SuspendLayout(); this.CommandSplit.Panel1.SuspendLayout(); this.CommandSplit.Panel2.SuspendLayout(); this.CommandSplit.SuspendLayout(); this.SideNavStrip.SuspendLayout(); this.NavStrip.SuspendLayout(); this.TopToolStrip.SuspendLayout(); this.SideToolStrip.SuspendLayout(); this.SuspendLayout(); // // MainSplit // this.MainSplit.BackColor = System.Drawing.Color.WhiteSmoke; this.MainSplit.Dock = System.Windows.Forms.DockStyle.Fill; this.MainSplit.FixedPanel = System.Windows.Forms.FixedPanel.Panel1; this.MainSplit.Location = new System.Drawing.Point(27, 0); this.MainSplit.Name = "MainSplit"; // // MainSplit.Panel1 // this.MainSplit.Panel1.Controls.Add(this.CommandSplit); // // MainSplit.Panel2 // this.MainSplit.Panel2.BackColor = System.Drawing.Color.White; this.MainSplit.Panel2.Controls.Add(this.NavStrip); this.MainSplit.Panel2.Controls.Add(this.InternalPanel); this.MainSplit.Panel2.Controls.Add(this.TopToolStrip); this.MainSplit.Size = new System.Drawing.Size(741, 447); this.MainSplit.SplitterDistance = 171; this.MainSplit.SplitterWidth = 2; this.MainSplit.TabIndex = 1; // // CommandSplit // this.CommandSplit.BackColor = System.Drawing.Color.White; this.CommandSplit.Dock = System.Windows.Forms.DockStyle.Fill; this.CommandSplit.FixedPanel = System.Windows.Forms.FixedPanel.Panel2; this.CommandSplit.ForeColor = System.Drawing.Color.White; this.CommandSplit.Location = new System.Drawing.Point(0, 0); this.CommandSplit.Name = "CommandSplit"; this.CommandSplit.Orientation = System.Windows.Forms.Orientation.Horizontal; // // CommandSplit.Panel1 // this.CommandSplit.Panel1.BackColor = System.Drawing.Color.WhiteSmoke; this.CommandSplit.Panel1.Controls.Add(this.BuddyList); this.CommandSplit.Panel1.Controls.Add(this.SideNavStrip); this.CommandSplit.Panel1.Controls.Add(this.CommandTree); // // CommandSplit.Panel2 // this.CommandSplit.Panel2.BackColor = System.Drawing.Color.WhiteSmoke; this.CommandSplit.Panel2.Controls.Add(this.SelectionInfo); this.CommandSplit.Size = new System.Drawing.Size(171, 447); this.CommandSplit.SplitterDistance = 324; this.CommandSplit.SplitterWidth = 2; this.CommandSplit.TabIndex = 4; // // BuddyList // this.BuddyList.AllowDrop = true; this.BuddyList.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.BuddyList.BackColor = System.Drawing.SystemColors.Window; this.BuddyList.BorderStyle = System.Windows.Forms.BorderStyle.None; this.BuddyList.ColumnSortColor = System.Drawing.Color.Gainsboro; this.BuddyList.ColumnTrackColor = System.Drawing.Color.WhiteSmoke; this.BuddyList.DisableHorizontalScroll = true; this.BuddyList.GridLineColor = System.Drawing.Color.WhiteSmoke; this.BuddyList.HeaderMenu = null; this.BuddyList.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.None; this.BuddyList.ItemMenu = null; this.BuddyList.LabelEdit = false; this.BuddyList.Location = new System.Drawing.Point(0, 25); this.BuddyList.MultiSelect = true; this.BuddyList.Name = "BuddyList"; this.BuddyList.RowSelectColor = System.Drawing.SystemColors.Highlight; this.BuddyList.RowTrackColor = System.Drawing.Color.WhiteSmoke; this.BuddyList.Size = new System.Drawing.Size(171, 296); this.BuddyList.SmallImageList = null; this.BuddyList.StateImageList = null; this.BuddyList.TabIndex = 0; this.BuddyList.Visible = false; // // SideNavStrip // this.SideNavStrip.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden; this.SideNavStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.SideViewsButton, this.SideHelpButton, this.SideSearchButton, this.SideNewsButton}); this.SideNavStrip.Location = new System.Drawing.Point(0, 0); this.SideNavStrip.Name = "SideNavStrip"; this.SideNavStrip.Size = new System.Drawing.Size(171, 25); this.SideNavStrip.TabIndex = 1; this.SideNavStrip.Paint += new System.Windows.Forms.PaintEventHandler(this.SideModeStrip_Paint); this.SideNavStrip.MouseClick += new System.Windows.Forms.MouseEventHandler(this.SideModeStrip_MouseClick); this.SideNavStrip.MouseMove += new System.Windows.Forms.MouseEventHandler(this.SideModeStrip_MouseMove); // // SideViewsButton // this.SideViewsButton.Image = ((System.Drawing.Image)(resources.GetObject("SideViewsButton.Image"))); this.SideViewsButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.SideViewsButton.Name = "SideViewsButton"; this.SideViewsButton.Size = new System.Drawing.Size(63, 22); this.SideViewsButton.Text = "Views"; this.SideViewsButton.DropDownOpening += new System.EventHandler(this.SideViewsButton_DropDownOpening); // // SideHelpButton // this.SideHelpButton.Alignment = System.Windows.Forms.ToolStripItemAlignment.Right; this.SideHelpButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.SideHelpButton.Image = ((System.Drawing.Image)(resources.GetObject("SideHelpButton.Image"))); this.SideHelpButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.SideHelpButton.Name = "SideHelpButton"; this.SideHelpButton.Size = new System.Drawing.Size(23, 22); this.SideHelpButton.Text = "Help"; this.SideHelpButton.Click += new System.EventHandler(this.SideHelpButton_Click); // // SideSearchButton // this.SideSearchButton.Alignment = System.Windows.Forms.ToolStripItemAlignment.Right; this.SideSearchButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.SideSearchButton.Image = ((System.Drawing.Image)(resources.GetObject("SideSearchButton.Image"))); this.SideSearchButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.SideSearchButton.Name = "SideSearchButton"; this.SideSearchButton.Size = new System.Drawing.Size(23, 22); this.SideSearchButton.Text = "toolStripButton1"; this.SideSearchButton.Visible = false; // // SideNewsButton // this.SideNewsButton.Alignment = System.Windows.Forms.ToolStripItemAlignment.Right; this.SideNewsButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.SideNewsButton.Image = ((System.Drawing.Image)(resources.GetObject("SideNewsButton.Image"))); this.SideNewsButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.SideNewsButton.Name = "SideNewsButton"; this.SideNewsButton.Size = new System.Drawing.Size(29, 22); this.SideNewsButton.Text = "News"; this.SideNewsButton.DropDownOpening += new System.EventHandler(this.SideNewsButton_DropDownOpening); // // CommandTree // this.CommandTree.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.CommandTree.BackColor = System.Drawing.SystemColors.Window; this.CommandTree.BorderStyle = System.Windows.Forms.BorderStyle.None; this.CommandTree.ColumnSortColor = System.Drawing.Color.Gainsboro; this.CommandTree.ColumnTrackColor = System.Drawing.Color.WhiteSmoke; this.CommandTree.GridLineColor = System.Drawing.Color.WhiteSmoke; this.CommandTree.HeaderMenu = null; this.CommandTree.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.None; this.CommandTree.ItemHeight = 20; this.CommandTree.ItemMenu = null; this.CommandTree.LabelEdit = false; this.CommandTree.Location = new System.Drawing.Point(0, 25); this.CommandTree.MouseActivte = true; this.CommandTree.Name = "CommandTree"; this.CommandTree.RowSelectColor = System.Drawing.SystemColors.Highlight; this.CommandTree.RowTrackColor = System.Drawing.Color.WhiteSmoke; this.CommandTree.ShowLines = true; this.CommandTree.Size = new System.Drawing.Size(171, 296); this.CommandTree.SmallImageList = null; this.CommandTree.StateImageList = null; this.CommandTree.TabIndex = 0; this.CommandTree.MouseClick += new System.Windows.Forms.MouseEventHandler(this.CommandTree_MouseClick); this.CommandTree.MouseDoubleClick += new System.Windows.Forms.MouseEventHandler(this.CommandTree_MouseDoubleClick); this.CommandTree.SelectedItemChanged += new System.EventHandler(this.CommandTree_SelectedItemChanged); // // SelectionInfo // this.SelectionInfo.Dock = System.Windows.Forms.DockStyle.Fill; this.SelectionInfo.Location = new System.Drawing.Point(0, 0); this.SelectionInfo.Name = "SelectionInfo"; this.SelectionInfo.Size = new System.Drawing.Size(171, 121); this.SelectionInfo.TabIndex = 0; // // NavStrip // this.NavStrip.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden; this.NavStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.PersonNavButton, this.ProjectNavButton, this.ComponentNavButton, this.PopoutButton, this.NewsButton}); this.NavStrip.Location = new System.Drawing.Point(0, 31); this.NavStrip.Name = "NavStrip"; this.NavStrip.ShowItemToolTips = false; this.NavStrip.Size = new System.Drawing.Size(568, 25); this.NavStrip.TabIndex = 3; this.NavStrip.Paint += new System.Windows.Forms.PaintEventHandler(this.NavStrip_Paint); this.NavStrip.MouseClick += new System.Windows.Forms.MouseEventHandler(this.NavStrip_MouseClick); this.NavStrip.MouseMove += new System.Windows.Forms.MouseEventHandler(this.NavStrip_MouseMove); // // PersonNavButton // this.PersonNavButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text; this.PersonNavButton.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.PersonNavButton.ForeColor = System.Drawing.Color.White; this.PersonNavButton.Image = ((System.Drawing.Image)(resources.GetObject("PersonNavButton.Image"))); this.PersonNavButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.PersonNavButton.Name = "PersonNavButton"; this.PersonNavButton.Size = new System.Drawing.Size(59, 22); this.PersonNavButton.Text = "Person"; // // ProjectNavButton // this.ProjectNavButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text; this.ProjectNavButton.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.ProjectNavButton.ForeColor = System.Drawing.Color.White; this.ProjectNavButton.Image = ((System.Drawing.Image)(resources.GetObject("ProjectNavButton.Image"))); this.ProjectNavButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.ProjectNavButton.Name = "ProjectNavButton"; this.ProjectNavButton.Size = new System.Drawing.Size(61, 22); this.ProjectNavButton.Text = "Project"; // // ComponentNavButton // this.ComponentNavButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text; this.ComponentNavButton.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.ComponentNavButton.ForeColor = System.Drawing.Color.White; this.ComponentNavButton.Image = ((System.Drawing.Image)(resources.GetObject("ComponentNavButton.Image"))); this.ComponentNavButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.ComponentNavButton.Name = "ComponentNavButton"; this.ComponentNavButton.Size = new System.Drawing.Size(46, 22); this.ComponentNavButton.Text = "View"; // // PopoutButton // this.PopoutButton.Alignment = System.Windows.Forms.ToolStripItemAlignment.Right; this.PopoutButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.PopoutButton.Image = ((System.Drawing.Image)(resources.GetObject("PopoutButton.Image"))); this.PopoutButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.PopoutButton.Name = "PopoutButton"; this.PopoutButton.Size = new System.Drawing.Size(23, 22); this.PopoutButton.Text = "Popout Window"; this.PopoutButton.Click += new System.EventHandler(this.PopoutButton_Click); // // NewsButton // this.NewsButton.Alignment = System.Windows.Forms.ToolStripItemAlignment.Right; this.NewsButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.NewsButton.Image = ((System.Drawing.Image)(resources.GetObject("NewsButton.Image"))); this.NewsButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.NewsButton.Name = "NewsButton"; this.NewsButton.Size = new System.Drawing.Size(29, 22); this.NewsButton.Text = "Recent News"; this.NewsButton.DropDownOpening += new System.EventHandler(this.NewsButton_DropDownOpening); // // InternalPanel // this.InternalPanel.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.InternalPanel.BackColor = System.Drawing.Color.WhiteSmoke; this.InternalPanel.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch; this.InternalPanel.Location = new System.Drawing.Point(0, 56); this.InternalPanel.Name = "InternalPanel"; this.InternalPanel.Size = new System.Drawing.Size(566, 391); this.InternalPanel.TabIndex = 2; // // TopToolStrip // this.TopToolStrip.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden; this.TopToolStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.HomeButton, this.ManageButton, this.ToolSeparator, this.PlanButton, this.CommButton, this.HelpInfoButton, this.SearchButton, this.SearchBox, this.DataButton}); this.TopToolStrip.Location = new System.Drawing.Point(0, 0); this.TopToolStrip.Name = "TopToolStrip"; this.TopToolStrip.ShowItemToolTips = false; this.TopToolStrip.Size = new System.Drawing.Size(568, 31); this.TopToolStrip.TabIndex = 0; this.TopToolStrip.Text = "MainToolstrip"; // // HomeButton // this.HomeButton.AutoToolTip = false; this.HomeButton.Image = ((System.Drawing.Image)(resources.GetObject("HomeButton.Image"))); this.HomeButton.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None; this.HomeButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.HomeButton.Name = "HomeButton"; this.HomeButton.Size = new System.Drawing.Size(79, 28); this.HomeButton.Text = "My Home"; this.HomeButton.Click += new System.EventHandler(this.HomeButton_Click); // // ManageButton // this.ManageButton.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.settingsToolStripMenuItem, this.inviteToolStripMenuItem, this.toolsToolStripMenuItem, this.toolStripMenuItem1, this.signOnToolStripMenuItem, this.signOffToolStripMenuItem}); this.ManageButton.Image = ((System.Drawing.Image)(resources.GetObject("ManageButton.Image"))); this.ManageButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.ManageButton.Name = "ManageButton"; this.ManageButton.Size = new System.Drawing.Size(74, 28); this.ManageButton.Text = "Manage"; // // settingsToolStripMenuItem // this.settingsToolStripMenuItem.Name = "settingsToolStripMenuItem"; this.settingsToolStripMenuItem.Size = new System.Drawing.Size(124, 22); this.settingsToolStripMenuItem.Text = "Settings"; // // inviteToolStripMenuItem // this.inviteToolStripMenuItem.Name = "inviteToolStripMenuItem"; this.inviteToolStripMenuItem.Size = new System.Drawing.Size(124, 22); this.inviteToolStripMenuItem.Text = "Invite"; // // toolsToolStripMenuItem // this.toolsToolStripMenuItem.Name = "toolsToolStripMenuItem"; this.toolsToolStripMenuItem.Size = new System.Drawing.Size(124, 22); this.toolsToolStripMenuItem.Text = "Tools"; // // toolStripMenuItem1 // this.toolStripMenuItem1.Name = "toolStripMenuItem1"; this.toolStripMenuItem1.Size = new System.Drawing.Size(121, 6); // // signOnToolStripMenuItem // this.signOnToolStripMenuItem.Name = "signOnToolStripMenuItem"; this.signOnToolStripMenuItem.Size = new System.Drawing.Size(124, 22); this.signOnToolStripMenuItem.Text = "Sign On"; // // signOffToolStripMenuItem // this.signOffToolStripMenuItem.Name = "signOffToolStripMenuItem"; this.signOffToolStripMenuItem.Size = new System.Drawing.Size(124, 22); this.signOffToolStripMenuItem.Text = "Sign Off"; // // ToolSeparator // this.ToolSeparator.Name = "ToolSeparator"; this.ToolSeparator.Size = new System.Drawing.Size(6, 31); // // PlanButton // this.PlanButton.AutoToolTip = false; this.PlanButton.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.calanderToolStripMenuItem, this.personalToolStripMenuItem}); this.PlanButton.Image = ((System.Drawing.Image)(resources.GetObject("PlanButton.Image"))); this.PlanButton.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None; this.PlanButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.PlanButton.Name = "PlanButton"; this.PlanButton.Size = new System.Drawing.Size(69, 28); this.PlanButton.Text = "Plans"; this.PlanButton.TextDirection = System.Windows.Forms.ToolStripTextDirection.Horizontal; // // calanderToolStripMenuItem // this.calanderToolStripMenuItem.Name = "calanderToolStripMenuItem"; this.calanderToolStripMenuItem.Size = new System.Drawing.Size(128, 22); this.calanderToolStripMenuItem.Text = "Calandar"; // // personalToolStripMenuItem // this.personalToolStripMenuItem.Name = "personalToolStripMenuItem"; this.personalToolStripMenuItem.Size = new System.Drawing.Size(128, 22); this.personalToolStripMenuItem.Text = "Personal"; // // CommButton // this.CommButton.AutoToolTip = false; this.CommButton.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.mailToolStripMenuItem, this.chatToolStripMenuItem}); this.CommButton.Image = ((System.Drawing.Image)(resources.GetObject("CommButton.Image"))); this.CommButton.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None; this.CommButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.CommButton.Name = "CommButton"; this.CommButton.Size = new System.Drawing.Size(73, 28); this.CommButton.Text = "Comm"; // // mailToolStripMenuItem // this.mailToolStripMenuItem.Name = "mailToolStripMenuItem"; this.mailToolStripMenuItem.Size = new System.Drawing.Size(108, 22); this.mailToolStripMenuItem.Text = "Mail"; // // chatToolStripMenuItem // this.chatToolStripMenuItem.Name = "chatToolStripMenuItem"; this.chatToolStripMenuItem.Size = new System.Drawing.Size(108, 22); this.chatToolStripMenuItem.Text = "Chat"; // // HelpInfoButton // this.HelpInfoButton.Alignment = System.Windows.Forms.ToolStripItemAlignment.Right; this.HelpInfoButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.HelpInfoButton.Image = ((System.Drawing.Image)(resources.GetObject("HelpInfoButton.Image"))); this.HelpInfoButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.HelpInfoButton.Name = "HelpInfoButton"; this.HelpInfoButton.Size = new System.Drawing.Size(23, 28); this.HelpInfoButton.Text = "Help"; this.HelpInfoButton.Click += new System.EventHandler(this.HelpButton_Click); // // SearchButton // this.SearchButton.Alignment = System.Windows.Forms.ToolStripItemAlignment.Right; this.SearchButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.SearchButton.Enabled = false; this.SearchButton.Image = ((System.Drawing.Image)(resources.GetObject("SearchButton.Image"))); this.SearchButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.SearchButton.Name = "SearchButton"; this.SearchButton.Size = new System.Drawing.Size(23, 28); this.SearchButton.Text = "Search"; this.SearchButton.Click += new System.EventHandler(this.SearchButton_Click); // // SearchBox // this.SearchBox.Alignment = System.Windows.Forms.ToolStripItemAlignment.Right; this.SearchBox.BackColor = System.Drawing.Color.WhiteSmoke; this.SearchBox.Enabled = false; this.SearchBox.Name = "SearchBox"; this.SearchBox.Size = new System.Drawing.Size(100, 31); // // DataButton // this.DataButton.AutoToolTip = false; this.DataButton.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.commonToolStripMenuItem1, this.personalToolStripMenuItem2}); this.DataButton.Image = ((System.Drawing.Image)(resources.GetObject("DataButton.Image"))); this.DataButton.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None; this.DataButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.DataButton.Name = "DataButton"; this.DataButton.Size = new System.Drawing.Size(67, 28); this.DataButton.Text = "Data"; // // commonToolStripMenuItem1 // this.commonToolStripMenuItem1.Name = "commonToolStripMenuItem1"; this.commonToolStripMenuItem1.Size = new System.Drawing.Size(126, 22); this.commonToolStripMenuItem1.Text = "Common"; // // personalToolStripMenuItem2 // this.personalToolStripMenuItem2.Name = "personalToolStripMenuItem2"; this.personalToolStripMenuItem2.Size = new System.Drawing.Size(126, 22); this.personalToolStripMenuItem2.Text = "Personal"; // // SideToolStrip // this.SideToolStrip.Dock = System.Windows.Forms.DockStyle.Left; this.SideToolStrip.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.SideToolStrip.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden; this.SideToolStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.toolStripLabel2, this.OperationButton, this.BuddiesButton, this.ProjectsButton, this.SideButton, this.LockButton, this.NetworkButton}); this.SideToolStrip.LayoutStyle = System.Windows.Forms.ToolStripLayoutStyle.VerticalStackWithOverflow; this.SideToolStrip.Location = new System.Drawing.Point(0, 0); this.SideToolStrip.Name = "SideToolStrip"; this.SideToolStrip.Padding = new System.Windows.Forms.Padding(3, 0, 1, 0); this.SideToolStrip.Size = new System.Drawing.Size(27, 447); this.SideToolStrip.TabIndex = 3; this.SideToolStrip.TextDirection = System.Windows.Forms.ToolStripTextDirection.Vertical270; // // toolStripLabel2 // this.toolStripLabel2.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.None; this.toolStripLabel2.Margin = new System.Windows.Forms.Padding(0, 25, 0, 2); this.toolStripLabel2.Name = "toolStripLabel2"; this.toolStripLabel2.Size = new System.Drawing.Size(18, 0); // // OperationButton // this.OperationButton.Checked = true; this.OperationButton.CheckOnClick = true; this.OperationButton.CheckState = System.Windows.Forms.CheckState.Checked; this.OperationButton.ForeColor = System.Drawing.Color.Black; this.OperationButton.Image = ((System.Drawing.Image)(resources.GetObject("OperationButton.Image"))); this.OperationButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.OperationButton.Name = "OperationButton"; this.OperationButton.Size = new System.Drawing.Size(18, 83); this.OperationButton.Text = "Operation"; this.OperationButton.TextDirection = System.Windows.Forms.ToolStripTextDirection.Vertical90; this.OperationButton.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageAboveText; this.OperationButton.CheckedChanged += new System.EventHandler(this.OperationButton_CheckedChanged); // // BuddiesButton // this.BuddiesButton.CheckOnClick = true; this.BuddiesButton.ForeColor = System.Drawing.Color.Black; this.BuddiesButton.Image = ((System.Drawing.Image)(resources.GetObject("BuddiesButton.Image"))); this.BuddiesButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.BuddiesButton.Name = "BuddiesButton"; this.BuddiesButton.Size = new System.Drawing.Size(18, 71); this.BuddiesButton.Text = "Buddies"; this.BuddiesButton.TextDirection = System.Windows.Forms.ToolStripTextDirection.Vertical90; this.BuddiesButton.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageAboveText; this.BuddiesButton.CheckedChanged += new System.EventHandler(this.OnlineButton_CheckedChanged); // // ProjectsButton // this.ProjectsButton.ForeColor = System.Drawing.Color.Black; this.ProjectsButton.Image = ((System.Drawing.Image)(resources.GetObject("ProjectsButton.Image"))); this.ProjectsButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.ProjectsButton.Name = "ProjectsButton"; this.ProjectsButton.Size = new System.Drawing.Size(18, 81); this.ProjectsButton.Text = "Projects"; this.ProjectsButton.TextDirection = System.Windows.Forms.ToolStripTextDirection.Vertical90; this.ProjectsButton.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageAboveText; this.ProjectsButton.DropDownOpening += new System.EventHandler(this.ProjectsButton_DropDownOpening); // // SideButton // this.SideButton.Alignment = System.Windows.Forms.ToolStripItemAlignment.Right; this.SideButton.CheckOnClick = true; this.SideButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.SideButton.Image = ((System.Drawing.Image)(resources.GetObject("SideButton.Image"))); this.SideButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.SideButton.Name = "SideButton"; this.SideButton.Size = new System.Drawing.Size(18, 20); this.SideButton.Text = "Toggle Sidebar"; this.SideButton.CheckedChanged += new System.EventHandler(this.SideButton_CheckedChanged); // // LockButton // this.LockButton.Alignment = System.Windows.Forms.ToolStripItemAlignment.Right; this.LockButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.LockButton.Image = ((System.Drawing.Image)(resources.GetObject("LockButton.Image"))); this.LockButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.LockButton.Name = "LockButton"; this.LockButton.Size = new System.Drawing.Size(18, 20); this.LockButton.Text = "Lockdown to Tray"; this.LockButton.Click += new System.EventHandler(this.LockButton_Click); // // NetworkButton // this.NetworkButton.Alignment = System.Windows.Forms.ToolStripItemAlignment.Right; this.NetworkButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.NetworkButton.Image = ((System.Drawing.Image)(resources.GetObject("NetworkButton.Image"))); this.NetworkButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.NetworkButton.Name = "NetworkButton"; this.NetworkButton.Size = new System.Drawing.Size(18, 20); this.NetworkButton.Text = "Network Info"; this.NetworkButton.Click += new System.EventHandler(this.NetworkButton_Click); // // TreeImageList // this.TreeImageList.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("TreeImageList.ImageStream"))); this.TreeImageList.TransparentColor = System.Drawing.Color.White; this.TreeImageList.Images.SetKeyName(0, "link_confirmed.ico"); this.TreeImageList.Images.SetKeyName(1, "link_denied.ico"); this.TreeImageList.Images.SetKeyName(2, "link_pending.ico"); // // NewsTimer // this.NewsTimer.Enabled = true; this.NewsTimer.Tick += new System.EventHandler(this.NewsTimer_Tick); // // MainForm // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackColor = System.Drawing.Color.WhiteSmoke; this.ClientSize = new System.Drawing.Size(768, 447); this.Controls.Add(this.MainSplit); this.Controls.Add(this.SideToolStrip); this.DoubleBuffered = true; this.Name = "MainForm"; this.Text = "DeOps"; this.Load += new System.EventHandler(this.MainForm_Load); this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.MainForm_FormClosing); this.MainSplit.Panel1.ResumeLayout(false); this.MainSplit.Panel2.ResumeLayout(false); this.MainSplit.Panel2.PerformLayout(); this.MainSplit.ResumeLayout(false); this.CommandSplit.Panel1.ResumeLayout(false); this.CommandSplit.Panel1.PerformLayout(); this.CommandSplit.Panel2.ResumeLayout(false); this.CommandSplit.ResumeLayout(false); this.SideNavStrip.ResumeLayout(false); this.SideNavStrip.PerformLayout(); this.NavStrip.ResumeLayout(false); this.NavStrip.PerformLayout(); this.TopToolStrip.ResumeLayout(false); this.TopToolStrip.PerformLayout(); this.SideToolStrip.ResumeLayout(false); this.SideToolStrip.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.SplitContainer MainSplit; private System.Windows.Forms.ImageList TreeImageList; private System.Windows.Forms.ToolStrip TopToolStrip; private System.Windows.Forms.ToolStripButton HomeButton; private System.Windows.Forms.ToolStripSeparator ToolSeparator; private System.Windows.Forms.ToolStripTextBox SearchBox; private System.Windows.Forms.SplitContainer CommandSplit; private System.Windows.Forms.ToolStrip SideToolStrip; private System.Windows.Forms.ToolStripButton OperationButton; private System.Windows.Forms.ToolStripButton BuddiesButton; private System.Windows.Forms.ToolStripLabel toolStripLabel2; private System.Windows.Forms.Panel InternalPanel; private System.Windows.Forms.ToolStripDropDownButton ProjectsButton; private System.Windows.Forms.ToolStripButton SideButton; private System.Windows.Forms.ToolStripDropDownButton CommButton; private System.Windows.Forms.ToolStripMenuItem mailToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem chatToolStripMenuItem; private System.Windows.Forms.ToolStripDropDownButton PlanButton; private System.Windows.Forms.ToolStripMenuItem calanderToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem personalToolStripMenuItem; private System.Windows.Forms.ToolStripDropDownButton DataButton; private System.Windows.Forms.ToolStripMenuItem commonToolStripMenuItem1; private System.Windows.Forms.ToolStripMenuItem personalToolStripMenuItem2; private DeOps.Services.Trust.LinkTree CommandTree; private System.Windows.Forms.ToolStrip NavStrip; private System.Windows.Forms.ToolStripDropDownButton PersonNavButton; private System.Windows.Forms.ToolStripDropDownButton ProjectNavButton; private System.Windows.Forms.ToolStripDropDownButton ComponentNavButton; private System.Windows.Forms.ToolStripButton PopoutButton; private System.Windows.Forms.ToolStripButton LockButton; private System.Windows.Forms.Timer NewsTimer; private System.Windows.Forms.ToolStripDropDownButton NewsButton; private System.Windows.Forms.ToolStrip SideNavStrip; private System.Windows.Forms.ToolStripDropDownButton SideViewsButton; private System.Windows.Forms.ToolStripDropDownButton SideNewsButton; private System.Windows.Forms.ToolStripDropDownButton ManageButton; private System.Windows.Forms.ToolStripButton SearchButton; private System.Windows.Forms.ToolStripMenuItem settingsToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem inviteToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem toolsToolStripMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripMenuItem1; private System.Windows.Forms.ToolStripMenuItem signOnToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem signOffToolStripMenuItem; private System.Windows.Forms.ToolStripButton SideSearchButton; private DeOps.Services.Buddy.BuddyView BuddyList; private StatusPanel SelectionInfo; private System.Windows.Forms.ToolStripButton HelpInfoButton; private System.Windows.Forms.ToolStripButton NetworkButton; private System.Windows.Forms.ToolStripButton SideHelpButton; } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Xunit; namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.conversion.conversion001.conversion001 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.conversion.conversion001.conversion001; // <Title> Compound operator in conversion.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success></Expects> // <Code> using System; public class Base1 { public int field; } public class Base2 { public int field; } public class TestClass { public int field; public static implicit operator TestClass(Base2 p1) { return new TestClass() { field = p1.field } ; } public static Base2 operator |(TestClass p1, Base1 p2) { return new Base2() { field = (p1.field | p2.field) } ; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] ars) { TestClass l = new TestClass() { field = 8 } ; Base1 r = new Base1() { field = 2 } ; dynamic d0 = l; d0 |= r; dynamic d1 = l; dynamic d2 = r; d1 |= d2; l |= d2; if (d0.field == 10 && d1.field == 10 && l.field == 10) return 0; return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.conversion.conversion002.conversion002 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.conversion.conversion002.conversion002; // <Title> Compound operator in conversion.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success></Expects> // <Code> using System; public class Base1 { public int field; } public class Base2 { public int field; } public class TestClass { public int field; public static explicit operator TestClass(Base2 p1) { return new TestClass() { field = p1.field } ; } public static Base2 operator |(TestClass p1, Base1 p2) { return new Base2() { field = (p1.field | p2.field) } ; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] ars) { TestClass l = new TestClass() { field = 8 } ; Base1 r = new Base1() { field = 2 } ; int flag = 0; dynamic d0 = l; try { d0 |= r; } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e) { if (ErrorVerifier.Verify(ErrorMessageId.NoImplicitConvCast, e.Message, "Base2", "TestClass")) { flag++; } } dynamic d1 = l; dynamic d2 = r; try { d1 |= d2; } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e) { if (ErrorVerifier.Verify(ErrorMessageId.NoImplicitConvCast, e.Message, "Base2", "TestClass")) { flag++; } } try { l |= d2; } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e) { if (ErrorVerifier.Verify(ErrorMessageId.NoImplicitConvCast, e.Message, "Base2", "TestClass")) { flag++; } } if (flag == 0) return 0; return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.conversion.conversion003.conversion003 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.conversion.conversion003.conversion003; // <Title> Compound operator in conversion.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success></Expects> // <Code> using System; public class Test { public int field; public static implicit operator Test(string p1) { return new Test() { field = 10 } ; } public static Test operator +(Test p1, Test p2) { return new Test() { field = (p1.field + p2.field) } ; } [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] ars) { dynamic d0 = new Test() { field = 2 } ; d0 += ""; dynamic d1 = new Test() { field = 2 } ; d1 += "A"; Test d2 = new Test() { field = 2 } ; dynamic t2 = ""; d2 += t2; dynamic d3 = new Test() { field = 2 } ; dynamic t3 = string.Empty; d3 += t3; if (d0.field == 12 && d1.field == 12 && d2.field == 12 && d3.field == 12) return 0; return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.conversion.conversion005.conversion005 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.conversion.conversion005.conversion005; // <Title> Compound operator in conversion.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success></Expects> // <Code> using System; public class Base1 { public int field; } public struct Base2 { public int field; } public struct TestStruct { public int field; public static explicit operator TestStruct(Base2 p1) { return new TestStruct() { field = p1.field } ; } public static Base2 operator *(TestStruct p1, Base1 p2) { return new Base2() { field = (p1.field * 2) } ; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] ars) { TestStruct l = new TestStruct() { field = 8 } ; Base1 r = new Base1() { field = 2 } ; int flag = 0; dynamic d0 = l; try { d0 *= r; } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e) { if (ErrorVerifier.Verify(ErrorMessageId.NoImplicitConvCast, e.Message, "Base2", "TestStruct")) { flag++; } } dynamic d1 = l; try { d1 *= null; } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e) { if (ErrorVerifier.Verify(ErrorMessageId.NoImplicitConvCast, e.Message, "Base2", "TestStruct")) { flag++; } } dynamic d2 = l; dynamic d3 = r; try { d2 *= d3; } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e) { if (ErrorVerifier.Verify(ErrorMessageId.NoImplicitConvCast, e.Message, "Base2", "TestStruct")) { flag++; } } try { l *= d3; } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e) { if (ErrorVerifier.Verify(ErrorMessageId.NoImplicitConvCast, e.Message, "Base2", "TestStruct")) { flag++; } } if (flag == 0) return 0; return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.conversion.conversion006.conversion006 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.conversion.conversion006.conversion006; // <Title> Compound operator in conversion(negative).</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success></Expects> // <Code> using System; public class Base1 { public int field; } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] ars) { Test l = new Test(); Base1 r = new Base1() { field = 2 } ; try { dynamic d0 = l; d0 *= r; } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e) { if (ErrorVerifier.Verify(ErrorMessageId.BadBinaryOps, e.Message, "*=", "Test", "Base1")) return 0; } return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.conversion.conversion007.conversion007 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.conversion.conversion007.conversion007; // <Title> Compound operator in conversion.</Title> // <Description> // Compound operators (d += 10) is Expanding to (d = d + 10), it turns out this does match // the semantics of the equivalent static production. // In the static context, (t += 10) will result of type Test, but in dynamic, the result is type int. // </Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success></Expects> // <Code> using System; public class TestClass { [Fact] public void RunTest() { Test.DynamicCSharpRunTest(); } } public class Test { private int _f1 = 10; public Test() { } public Test(int p1) { _f1 = p1; } public static implicit operator Test(int p1) { return new Test(p1); } public static int operator +(Test t, int p1) { return t._f1 + p1; } public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic d = new Test(); if ((((d += 10).GetType()) == typeof(int)) && (d.GetType() == typeof(int))) { return 0; } return 1; } } //</Code> }
// 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 { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Rest; using Microsoft.Rest.Azure; using Microsoft.Rest.Azure.OData; using Models; using System.Threading; using System.Threading.Tasks; /// <summary> /// Extension methods for AuthorizationServerOperations. /// </summary> public static partial class AuthorizationServerOperationsExtensions { /// <summary> /// Lists a collection of authorization servers defined within a service /// instance. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='serviceName'> /// The name of the API Management service. /// </param> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> public static IPage<AuthorizationServerContract> ListByService(this IAuthorizationServerOperations operations, string resourceGroupName, string serviceName, ODataQuery<AuthorizationServerContract> odataQuery = default(ODataQuery<AuthorizationServerContract>)) { return ((IAuthorizationServerOperations)operations).ListByServiceAsync(resourceGroupName, serviceName, odataQuery).GetAwaiter().GetResult(); } /// <summary> /// Lists a collection of authorization servers defined within a service /// instance. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='serviceName'> /// The name of the API Management service. /// </param> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<AuthorizationServerContract>> ListByServiceAsync(this IAuthorizationServerOperations operations, string resourceGroupName, string serviceName, ODataQuery<AuthorizationServerContract> odataQuery = default(ODataQuery<AuthorizationServerContract>), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListByServiceWithHttpMessagesAsync(resourceGroupName, serviceName, odataQuery, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets the details of the authorization server specified by its identifier. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='serviceName'> /// The name of the API Management service. /// </param> /// <param name='authsid'> /// Identifier of the authorization server. /// </param> public static AuthorizationServerContract Get(this IAuthorizationServerOperations operations, string resourceGroupName, string serviceName, string authsid) { return operations.GetAsync(resourceGroupName, serviceName, authsid).GetAwaiter().GetResult(); } /// <summary> /// Gets the details of the authorization server specified by its identifier. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='serviceName'> /// The name of the API Management service. /// </param> /// <param name='authsid'> /// Identifier of the authorization server. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<AuthorizationServerContract> GetAsync(this IAuthorizationServerOperations operations, string resourceGroupName, string serviceName, string authsid, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, serviceName, authsid, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Creates new authorization server or updates an existing authorization /// server. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='serviceName'> /// The name of the API Management service. /// </param> /// <param name='authsid'> /// Identifier of the authorization server. /// </param> /// <param name='parameters'> /// Create or update parameters. /// </param> public static AuthorizationServerContract CreateOrUpdate(this IAuthorizationServerOperations operations, string resourceGroupName, string serviceName, string authsid, AuthorizationServerContract parameters) { return operations.CreateOrUpdateAsync(resourceGroupName, serviceName, authsid, parameters).GetAwaiter().GetResult(); } /// <summary> /// Creates new authorization server or updates an existing authorization /// server. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='serviceName'> /// The name of the API Management service. /// </param> /// <param name='authsid'> /// Identifier of the authorization server. /// </param> /// <param name='parameters'> /// Create or update parameters. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<AuthorizationServerContract> CreateOrUpdateAsync(this IAuthorizationServerOperations operations, string resourceGroupName, string serviceName, string authsid, AuthorizationServerContract parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, serviceName, authsid, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Updates the details of the authorization server specified by its /// identifier. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='serviceName'> /// The name of the API Management service. /// </param> /// <param name='authsid'> /// Identifier of the authorization server. /// </param> /// <param name='parameters'> /// OAuth2 Server settings Update parameters. /// </param> /// <param name='ifMatch'> /// The entity state (Etag) version of the authorization server to update. A /// value of "*" can be used for If-Match to unconditionally apply the /// operation. /// </param> public static void Update(this IAuthorizationServerOperations operations, string resourceGroupName, string serviceName, string authsid, AuthorizationServerUpdateContract parameters, string ifMatch) { operations.UpdateAsync(resourceGroupName, serviceName, authsid, parameters, ifMatch).GetAwaiter().GetResult(); } /// <summary> /// Updates the details of the authorization server specified by its /// identifier. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='serviceName'> /// The name of the API Management service. /// </param> /// <param name='authsid'> /// Identifier of the authorization server. /// </param> /// <param name='parameters'> /// OAuth2 Server settings Update parameters. /// </param> /// <param name='ifMatch'> /// The entity state (Etag) version of the authorization server to update. A /// value of "*" can be used for If-Match to unconditionally apply the /// operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task UpdateAsync(this IAuthorizationServerOperations operations, string resourceGroupName, string serviceName, string authsid, AuthorizationServerUpdateContract parameters, string ifMatch, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.UpdateWithHttpMessagesAsync(resourceGroupName, serviceName, authsid, parameters, ifMatch, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Deletes specific authorization server instance. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='serviceName'> /// The name of the API Management service. /// </param> /// <param name='authsid'> /// Identifier of the authorization server. /// </param> /// <param name='ifMatch'> /// The entity state (Etag) version of the authentication server to delete. A /// value of "*" can be used for If-Match to unconditionally apply the /// operation. /// </param> public static void Delete(this IAuthorizationServerOperations operations, string resourceGroupName, string serviceName, string authsid, string ifMatch) { operations.DeleteAsync(resourceGroupName, serviceName, authsid, ifMatch).GetAwaiter().GetResult(); } /// <summary> /// Deletes specific authorization server instance. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='serviceName'> /// The name of the API Management service. /// </param> /// <param name='authsid'> /// Identifier of the authorization server. /// </param> /// <param name='ifMatch'> /// The entity state (Etag) version of the authentication server to delete. A /// value of "*" can be used for If-Match to unconditionally apply the /// operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteAsync(this IAuthorizationServerOperations operations, string resourceGroupName, string serviceName, string authsid, string ifMatch, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.DeleteWithHttpMessagesAsync(resourceGroupName, serviceName, authsid, ifMatch, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Lists a collection of authorization servers defined within a service /// instance. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static IPage<AuthorizationServerContract> ListByServiceNext(this IAuthorizationServerOperations operations, string nextPageLink) { return operations.ListByServiceNextAsync(nextPageLink).GetAwaiter().GetResult(); } /// <summary> /// Lists a collection of authorization servers defined within a service /// instance. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<AuthorizationServerContract>> ListByServiceNextAsync(this IAuthorizationServerOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListByServiceNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
// **************************************************************** // Copyright 2002-2003, Charlie Poole // This is free software licensed under the NUnit license. You may // obtain a copy of the license at http://nunit.org // **************************************************************** using System; using System.IO; using System.Text; using System.Reflection; using System.Collections; using System.Runtime.InteropServices; namespace NUnit.Util { /// <summary> /// Static methods for manipulating project paths, including both directories /// and files. Some synonyms for System.Path methods are included as well. /// </summary> public class PathUtils { public const uint FILE_ATTRIBUTE_DIRECTORY = 0x00000010; public const uint FILE_ATTRIBUTE_NORMAL = 0x00000080; public const int MAX_PATH = 256; protected static char DirectorySeparatorChar = Path.DirectorySeparatorChar; protected static char AltDirectorySeparatorChar = Path.AltDirectorySeparatorChar; #region Public methods public static bool IsAssemblyFileType( string path ) { string extension = Path.GetExtension( path ).ToLower(); return extension == ".dll" || extension == ".exe"; } /// <summary> /// Returns the relative path from a base directory to another /// directory or file. /// </summary> public static string RelativePath( string from, string to ) { if (from == null) throw new ArgumentNullException (from); if (to == null) throw new ArgumentNullException (to); string toPathRoot = Path.GetPathRoot(to); if (toPathRoot == null || toPathRoot == string.Empty) return to; string fromPathRoot = Path.GetPathRoot(from); if (!PathsEqual(toPathRoot, fromPathRoot)) return null; string fromNoRoot = from.Substring(fromPathRoot.Length); string toNoRoot = to.Substring(toPathRoot.Length); string[] _from = SplitPath(fromNoRoot); string[] _to = SplitPath(toNoRoot); StringBuilder sb = new StringBuilder (Math.Max (from.Length, to.Length)); int last_common, min = Math.Min (_from.Length, _to.Length); for (last_common = 0; last_common < min; ++last_common) { if (!PathsEqual(_from[last_common], _to[last_common])) break; } if (last_common < _from.Length) sb.Append (".."); for (int i = last_common + 1; i < _from.Length; ++i) { sb.Append (PathUtils.DirectorySeparatorChar).Append (".."); } if (sb.Length > 0) sb.Append (PathUtils.DirectorySeparatorChar); if (last_common < _to.Length) sb.Append (_to [last_common]); for (int i = last_common + 1; i < _to.Length; ++i) { sb.Append (PathUtils.DirectorySeparatorChar).Append (_to [i]); } return sb.ToString (); } /// <summary> /// Return the canonical form of a path. /// </summary> public static string Canonicalize( string path ) { ArrayList parts = new ArrayList( path.Split( DirectorySeparatorChar, AltDirectorySeparatorChar ) ); for( int index = 0; index < parts.Count; ) { string part = (string)parts[index]; switch( part ) { case ".": parts.RemoveAt( index ); break; case "..": parts.RemoveAt( index ); if ( index > 0 ) parts.RemoveAt( --index ); break; default: index++; break; } } // Trailing separator removal if (parts.Count > 1 && path.Length > 1 && (string)parts[parts.Count - 1] == "") parts.RemoveAt(parts.Count - 1); return String.Join(DirectorySeparatorChar.ToString(), (string[])parts.ToArray(typeof(string))); } /// <summary> /// True if the two paths are the same. However, two paths /// to the same file or directory using different network /// shares or drive letters are not treated as equal. /// </summary> public static bool SamePath( string path1, string path2 ) { return string.Compare( Canonicalize(path1), Canonicalize(path2), PathUtils.IsWindows() ) == 0; } /// <summary> /// True if the two paths are the same or if the second is /// directly or indirectly under the first. Note that paths /// using different network shares or drive letters are /// considered unrelated, even if they end up referencing /// the same subtrees in the file system. /// </summary> public static bool SamePathOrUnder( string path1, string path2 ) { path1 = Canonicalize( path1 ); path2 = Canonicalize( path2 ); int length1 = path1.Length; int length2 = path2.Length; // if path1 is longer, then path2 can't be under it if ( length1 > length2 ) return false; // if lengths are the same, check for equality if ( length1 == length2 ) return string.Compare( path1, path2, IsWindows() ) == 0; // path 2 is longer than path 1: see if initial parts match if ( string.Compare( path1, path2.Substring( 0, length1 ), IsWindows() ) != 0 ) return false; // must match through or up to a directory separator boundary return path2[length1-1] == DirectorySeparatorChar || path2[length1] == DirectorySeparatorChar; } public static string Combine( string path1, params string[] morePaths ) { string result = path1; foreach( string path in morePaths ) result = Path.Combine( result, path ); return result; } public static string Combine(Assembly assembly, params string[] morePaths) { return Combine(Path.GetDirectoryName(GetAssemblyPath(assembly)), morePaths); } // TODO: This logic should be in shared source public static string GetAssemblyPath( Assembly assembly ) { string uri = assembly.CodeBase; // If it wasn't loaded locally, use the Location if ( !uri.StartsWith( Uri.UriSchemeFile ) ) return assembly.Location; return GetAssemblyPathFromFileUri( uri ); } // Separate method for testability public static string GetAssemblyPathFromFileUri( string uri ) { // Skip over the file:// int start = Uri.UriSchemeFile.Length + Uri.SchemeDelimiter.Length; if ( PathUtils.DirectorySeparatorChar == '\\' ) { if ( uri[start] == '/' && uri[start+2] == ':' ) ++start; } else { if ( uri[start] != '/' ) --start; } return uri.Substring( start ); } #endregion #region Helper Methods private static bool IsWindows() { return PathUtils.DirectorySeparatorChar == '\\'; } private static string[] SplitPath(string path) { char[] separators = new char[] { PathUtils.DirectorySeparatorChar, PathUtils.AltDirectorySeparatorChar }; #if CLR_2_0 || CLR_4_0 return path.Split(separators, StringSplitOptions.RemoveEmptyEntries); #else string[] trialSplit = path.Split(separators); int emptyEntries = 0; foreach(string piece in trialSplit) if (piece == string.Empty) emptyEntries++; if (emptyEntries == 0) return trialSplit; string[] finalSplit = new string[trialSplit.Length - emptyEntries]; int index = 0; foreach(string piece in trialSplit) if (piece != string.Empty) finalSplit[index++] = piece; return finalSplit; #endif } private static bool PathsEqual(string path1, string path2) { #if CLR_2_0 || CLR_4_0 if (PathUtils.IsWindows()) return path1.Equals(path2, StringComparison.InvariantCultureIgnoreCase); else return path1.Equals(path2, StringComparison.InvariantCulture); #else if (PathUtils.IsWindows()) return path1.ToLower().Equals(path2.ToLower()); else return path1.Equals(path2); #endif } #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.Diagnostics; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using EditorBrowsableAttribute = System.ComponentModel.EditorBrowsableAttribute; using EditorBrowsableState = System.ComponentModel.EditorBrowsableState; using Internal.Runtime.CompilerServices; #pragma warning disable 0809 //warning CS0809: Obsolete member 'Span<T>.Equals(object)' overrides non-obsolete member 'object.Equals(object)' #if BIT64 using nuint = System.UInt64; #else using nuint = System.UInt32; #endif namespace System { /// <summary> /// Span represents a contiguous region of arbitrary memory. Unlike arrays, it can point to either managed /// or native memory, or to memory allocated on the stack. It is type- and memory-safe. /// </summary> [NonVersionable] public readonly ref partial struct Span<T> { /// <summary>A byref or a native ptr.</summary> internal readonly ByReference<T> _pointer; /// <summary>The number of elements this Span contains.</summary> #if PROJECTN [Bound] #endif private readonly int _length; /// <summary> /// Creates a new span over the entirety of the target array. /// </summary> /// <param name="array">The target array.</param> /// <remarks>Returns default when <paramref name="array"/> is null.</remarks> /// reference (Nothing in Visual Basic).</exception> /// <exception cref="System.ArrayTypeMismatchException">Thrown when <paramref name="array"/> is covariant and array's type is not exactly T[].</exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public Span(T[] array) { if (array == null) { this = default; return; // returns default } if (default(T) == null && array.GetType() != typeof(T[])) ThrowHelper.ThrowArrayTypeMismatchException(); _pointer = new ByReference<T>(ref Unsafe.As<byte, T>(ref array.GetRawSzArrayData())); _length = array.Length; } /// <summary> /// Creates a new span over the portion of the target array beginning /// at 'start' index and ending at 'end' index (exclusive). /// </summary> /// <param name="array">The target array.</param> /// <param name="start">The index at which to begin the span.</param> /// <param name="length">The number of items in the span.</param> /// <remarks>Returns default when <paramref name="array"/> is null.</remarks> /// reference (Nothing in Visual Basic).</exception> /// <exception cref="System.ArrayTypeMismatchException">Thrown when <paramref name="array"/> is covariant and array's type is not exactly T[].</exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown when the specified <paramref name="start"/> or end index is not in the range (&lt;0 or &gt;=Length). /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public Span(T[] array, int start, int length) { if (array == null) { if (start != 0 || length != 0) ThrowHelper.ThrowArgumentOutOfRangeException(); this = default; return; // returns default } if (default(T) == null && array.GetType() != typeof(T[])) ThrowHelper.ThrowArrayTypeMismatchException(); if ((uint)start > (uint)array.Length || (uint)length > (uint)(array.Length - start)) ThrowHelper.ThrowArgumentOutOfRangeException(); _pointer = new ByReference<T>(ref Unsafe.Add(ref Unsafe.As<byte, T>(ref array.GetRawSzArrayData()), start)); _length = length; } /// <summary> /// Creates a new span over the target unmanaged buffer. Clearly this /// is quite dangerous, because we are creating arbitrarily typed T's /// out of a void*-typed block of memory. And the length is not checked. /// But if this creation is correct, then all subsequent uses are correct. /// </summary> /// <param name="pointer">An unmanaged pointer to memory.</param> /// <param name="length">The number of <typeparamref name="T"/> elements the memory contains.</param> /// <exception cref="System.ArgumentException"> /// Thrown when <typeparamref name="T"/> is reference type or contains pointers and hence cannot be stored in unmanaged memory. /// </exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown when the specified <paramref name="length"/> is negative. /// </exception> [CLSCompliant(false)] [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe Span(void* pointer, int length) { if (RuntimeHelpers.IsReferenceOrContainsReferences<T>()) ThrowHelper.ThrowInvalidTypeWithPointersNotSupported(typeof(T)); if (length < 0) ThrowHelper.ThrowArgumentOutOfRangeException(); _pointer = new ByReference<T>(ref Unsafe.As<byte, T>(ref *(byte*)pointer)); _length = length; } // Constructor for internal use only. [MethodImpl(MethodImplOptions.AggressiveInlining)] internal Span(ref T ptr, int length) { Debug.Assert(length >= 0); _pointer = new ByReference<T>(ref ptr); _length = length; } /// Returns a reference to specified element of the Span. /// </summary> /// <param name="index"></param> /// <returns></returns> /// <exception cref="System.IndexOutOfRangeException"> /// Thrown when index less than 0 or index greater than or equal to Length /// </exception> public ref T this[int index] { #if PROJECTN [BoundsChecking] get { return ref Unsafe.Add(ref _pointer.Value, index); } #else [Intrinsic] [MethodImpl(MethodImplOptions.AggressiveInlining)] [NonVersionable] get { if ((uint)index >= (uint)_length) ThrowHelper.ThrowIndexOutOfRangeException(); return ref Unsafe.Add(ref _pointer.Value, index); } #endif } /// <summary> /// Returns a reference to the 0th element of the Span. If the Span is empty, returns null reference. /// It can be used for pinning and is required to support the use of span within a fixed statement. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public unsafe ref T GetPinnableReference() { // Ensure that the native code has just one forward branch that is predicted-not-taken. ref T ret = ref Unsafe.AsRef<T>(null); if (_length != 0) ret = ref _pointer.Value; return ref ret; } /// <summary> /// Clears the contents of this span. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Clear() { if (RuntimeHelpers.IsReferenceOrContainsReferences<T>()) { SpanHelpers.ClearWithReferences(ref Unsafe.As<T, IntPtr>(ref _pointer.Value), (nuint)_length * (nuint)(Unsafe.SizeOf<T>() / sizeof(nuint))); } else { SpanHelpers.ClearWithoutReferences(ref Unsafe.As<T, byte>(ref _pointer.Value), (nuint)_length * (nuint)Unsafe.SizeOf<T>()); } } /// <summary> /// Fills the contents of this span with the given value. /// </summary> public void Fill(T value) { if (Unsafe.SizeOf<T>() == 1) { uint length = (uint)_length; if (length == 0) return; T tmp = value; // Avoid taking address of the "value" argument. It would regress performance of the loop below. Unsafe.InitBlockUnaligned(ref Unsafe.As<T, byte>(ref _pointer.Value), Unsafe.As<T, byte>(ref tmp), length); } else { // Do all math as nuint to avoid unnecessary 64->32->64 bit integer truncations nuint length = (uint)_length; if (length == 0) return; ref T r = ref _pointer.Value; // TODO: Create block fill for value types of power of two sizes e.g. 2,4,8,16 nuint elementSize = (uint)Unsafe.SizeOf<T>(); nuint i = 0; for (; i < (length & ~(nuint)7); i += 8) { Unsafe.AddByteOffset<T>(ref r, (i + 0) * elementSize) = value; Unsafe.AddByteOffset<T>(ref r, (i + 1) * elementSize) = value; Unsafe.AddByteOffset<T>(ref r, (i + 2) * elementSize) = value; Unsafe.AddByteOffset<T>(ref r, (i + 3) * elementSize) = value; Unsafe.AddByteOffset<T>(ref r, (i + 4) * elementSize) = value; Unsafe.AddByteOffset<T>(ref r, (i + 5) * elementSize) = value; Unsafe.AddByteOffset<T>(ref r, (i + 6) * elementSize) = value; Unsafe.AddByteOffset<T>(ref r, (i + 7) * elementSize) = value; } if (i < (length & ~(nuint)3)) { Unsafe.AddByteOffset<T>(ref r, (i + 0) * elementSize) = value; Unsafe.AddByteOffset<T>(ref r, (i + 1) * elementSize) = value; Unsafe.AddByteOffset<T>(ref r, (i + 2) * elementSize) = value; Unsafe.AddByteOffset<T>(ref r, (i + 3) * elementSize) = value; i += 4; } for (; i < length; i++) { Unsafe.AddByteOffset<T>(ref r, i * elementSize) = value; } } } /// <summary> /// Copies the contents of this span into destination span. If the source /// and destinations overlap, this method behaves as if the original values in /// a temporary location before the destination is overwritten. /// </summary> /// <param name="destination">The span to copy items into.</param> /// <exception cref="System.ArgumentException"> /// Thrown when the destination Span is shorter than the source Span. /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public void CopyTo(Span<T> destination) { // Using "if (!TryCopyTo(...))" results in two branches: one for the length // check, and one for the result of TryCopyTo. Since these checks are equivalent, // we can optimize by performing the check once ourselves then calling Memmove directly. if ((uint)_length <= (uint)destination.Length) { Buffer.Memmove(ref destination._pointer.Value, ref _pointer.Value, (nuint)_length); } else { ThrowHelper.ThrowArgumentException_DestinationTooShort(); } } /// <summary> /// Copies the contents of this span into destination span. If the source /// and destinations overlap, this method behaves as if the original values in /// a temporary location before the destination is overwritten. /// </summary> /// <param name="destination">The span to copy items into.</param> /// <returns>If the destination span is shorter than the source span, this method /// return false and no data is written to the destination.</returns> public bool TryCopyTo(Span<T> destination) { bool retVal = false; if ((uint)_length <= (uint)destination.Length) { Buffer.Memmove(ref destination._pointer.Value, ref _pointer.Value, (nuint)_length); retVal = true; } return retVal; } /// <summary> /// Returns true if left and right point at the same memory and have the same length. Note that /// this does *not* check to see if the *contents* are equal. /// </summary> public static bool operator ==(Span<T> left, Span<T> right) { return left._length == right._length && Unsafe.AreSame<T>(ref left._pointer.Value, ref right._pointer.Value); } /// <summary> /// Defines an implicit conversion of a <see cref="Span{T}"/> to a <see cref="ReadOnlySpan{T}"/> /// </summary> public static implicit operator ReadOnlySpan<T>(Span<T> span) => new ReadOnlySpan<T>(ref span._pointer.Value, span._length); /// <summary> /// For <see cref="Span{Char}"/>, returns a new instance of string that represents the characters pointed to by the span. /// Otherwise, returns a <see cref="string"/> with the name of the type and the number of elements. /// </summary> public override string ToString() { if (typeof(T) == typeof(char)) { unsafe { fixed (char* src = &Unsafe.As<T, char>(ref _pointer.Value)) return new string(src, 0, _length); } } return string.Format("System.Span<{0}>[{1}]", typeof(T).Name, _length); } /// <summary> /// Forms a slice out of the given span, beginning at 'start'. /// </summary> /// <param name="start">The index at which to begin this slice.</param> /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown when the specified <paramref name="start"/> index is not in range (&lt;0 or &gt;=Length). /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public Span<T> Slice(int start) { if ((uint)start > (uint)_length) ThrowHelper.ThrowArgumentOutOfRangeException(); return new Span<T>(ref Unsafe.Add(ref _pointer.Value, start), _length - start); } /// <summary> /// Forms a slice out of the given span, beginning at 'start', of given length /// </summary> /// <param name="start">The index at which to begin this slice.</param> /// <param name="length">The desired length for the slice (exclusive).</param> /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown when the specified <paramref name="start"/> or end index is not in range (&lt;0 or &gt;=Length). /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public Span<T> Slice(int start, int length) { if ((uint)start > (uint)_length || (uint)length > (uint)(_length - start)) ThrowHelper.ThrowArgumentOutOfRangeException(); return new Span<T>(ref Unsafe.Add(ref _pointer.Value, start), length); } /// <summary> /// Copies the contents of this span into a new array. This heap /// allocates, so should generally be avoided, however it is sometimes /// necessary to bridge the gap with APIs written in terms of arrays. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public T[] ToArray() { if (_length == 0) return Array.Empty<T>(); var destination = new T[_length]; Buffer.Memmove(ref Unsafe.As<byte, T>(ref destination.GetRawSzArrayData()), ref _pointer.Value, (nuint)_length); return destination; } } }
// Copyright 2016 Google 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. using Google.Apis.Auth.OAuth2.Responses; using Google.Apis.Compute.v1.Data; using Google.Apis.Http; using System; using System.Threading; using System.Threading.Tasks; namespace Google.Cloud.Metadata.V1 { /// <summary> /// Abstract class providing operations for using metadata for Google Compute Engine. /// </summary> /// <remarks> /// <para> /// This abstract class is provided to enable testability while permitting /// additional operations to be added in the future. You can construct a <see cref="MetadataClientImpl"/> directly. /// </para> /// <para> /// All instance methods declared in this class are virtual, with an implementation which simply /// throws <see cref="NotImplementedException"/>. All these methods are overridden in <see cref="MetadataClientImpl"/>. /// </para> /// </remarks> public abstract class MetadataClient { /// <summary> /// Creates a new <see cref="MetadataClient"/> /// </summary> /// <returns>The created <see cref="MetadataClient"/>.</returns> public static MetadataClient Create(ConfigurableHttpClient httpClient = null) => new MetadataClientImpl(httpClient); /// <summary> /// Creates a new <see cref="MetadataClient"/> /// </summary> /// <returns>The created <see cref="MetadataClient"/>.</returns> public static MetadataClient Create(IHttpClientFactory httpClientFactory) => new MetadataClientImpl(httpClientFactory); /// <summary>The HTTP client which is used to create requests.</summary> public virtual ConfigurableHttpClient HttpClient { get { throw new NotImplementedException(); } } /// <summary> /// Gets a token response which contains an access token to authorize a request synchronously. /// </summary> /// <exception cref="TokenResponseException">A status code other than success was returned from the server.</exception> /// <returns>The token response.</returns> public virtual TokenResponse GetAccessToken() { throw new NotImplementedException(); } /// <summary> /// Gets a token response which contains an access token to authorize a request asynchronously. /// </summary> /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> /// <exception cref="TokenResponseException">A status code other than success was returned from the server.</exception> /// <returns>The token response.</returns> public virtual Task<TokenResponse> GetAccessTokenAsync(CancellationToken cancellationToken = default) { throw new NotImplementedException(); } /// <summary> /// Gets the instance's custom metadata value with the specified key synchronously. /// </summary> /// <remarks> /// <para> /// Custom metadata are just opaque key/value pairs which allow for custom configuration parameters, scripts, or other /// relatively small pieces of data to be associated with the instance. /// </para> /// <para> /// The key must conform to the following regular expression: [a-zA-Z0-9-_]+ and must be less than 128 bytes in length. /// </para> /// </remarks> /// <param name="key">The key of the instance's custom metadata value to get.</param> /// <exception cref="ArgumentException">The key is not in the proper format.</exception> /// <seealso cref="Instance.Metadata"/> public virtual string GetCustomInstanceMetadata(string key) { throw new NotImplementedException(); } /// <summary> /// Gets the instance's custom metadata value with the specified key asynchronously. /// </summary> /// <remarks> /// <para> /// Custom metadata are just opaque key/value pairs which allow for custom configuration parameters, scripts, or other /// relatively small pieces of data to be associated with the instance. /// </para> /// <para> /// The key must conform to the following regular expression: [a-zA-Z0-9-_]+ and must be less than 128 bytes in length. /// </para> /// </remarks> /// <param name="key">The key of the instance's custom metadata value to get.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> /// <exception cref="ArgumentException">The key is not in the proper format.</exception> /// <returns>A task representing the asynchronous operation.</returns> /// <seealso cref="Instance.Metadata"/> public virtual Task<string> GetCustomInstanceMetadataAsync(string key, CancellationToken cancellationToken = default) { throw new NotImplementedException(); } /// <summary> /// Gets the project's custom metadata value with the specified key synchronously. /// </summary> /// <remarks> /// <para> /// Custom metadata are just opaque key/value pairs which allow for custom configuration parameters, scripts, or other /// relatively small pieces of data to be associated with the project. /// </para> /// <para> /// The key must conform to the following regular expression: [a-zA-Z0-9-_]+ and must be less than 128 bytes in length. /// </para> /// </remarks> /// <param name="key">The key of the project's custom metadata to get.</param> /// <exception cref="ArgumentException">The key is not in the proper format.</exception> /// <seealso cref="Project.CommonInstanceMetadata"/> public virtual string GetCustomProjectMetadata(string key) { throw new NotImplementedException(); } /// <summary> /// Gets the project's custom metadata value with the specified key asynchronously. /// </summary> /// <remarks> /// <para> /// Custom metadata are just opaque key/value pairs which allow for custom configuration parameters, scripts, or other /// relatively small pieces of data to be associated with the project. /// </para> /// <para> /// The key must conform to the following regular expression: [a-zA-Z0-9-_]+ and must be less than 128 bytes in length. /// </para> /// </remarks> /// <param name="key">The key of the project's custom metadata value to get.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> /// <exception cref="ArgumentException">The key is not in the proper format.</exception> /// <returns>A task representing the asynchronous operation.</returns> /// <seealso cref="Project.CommonInstanceMetadata"/> public virtual Task<string> GetCustomProjectMetadataAsync(string key, CancellationToken cancellationToken = default) { throw new NotImplementedException(); } /// <summary> /// Synchronously gets the metadata for the VM currently running this code. /// </summary> /// <remarks> /// The instance metadata contains information about the instance, such as the host name, instance ID, and custom metadata and it can be /// accessed without authentication from an application running on the instance. Check <see cref="IsServerAvailable"/> or /// <see cref="IsServerAvailableAsync(CancellationToken)"/> to determine if the metadata can be accessed. /// </remarks> /// <returns>The <see cref="Instance"/> representing the metadata.</returns> public virtual Instance GetInstanceMetadata() { throw new NotImplementedException(); } /// <summary> /// Asynchronously gets the metadata for the VM currently running this code. /// </summary> /// <remarks> /// The instance metadata contains information about the instance, such as the host name, instance ID, and custom metadata and it can be /// accessed without authentication from an application running on the instance. Check <see cref="IsServerAvailable"/> or /// <see cref="IsServerAvailableAsync(CancellationToken)"/> to determine if the metadata can be accessed. /// </remarks> /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> /// <returns>A task containing the <see cref="Instance"/> representing the metadata.</returns> public virtual Task<Instance> GetInstanceMetadataAsync(CancellationToken cancellationToken = default) { throw new NotImplementedException(); } /// <summary> /// Synchronously gets the maintenance status for the VM currently running this code. /// </summary> /// <remarks> /// If the <see cref="Instance.Scheduling"/>'s <see cref="Scheduling.OnHostMaintenance"/> is set to "MIGRATE", the maintenance status will change /// to <see cref="MaintenanceStatus.Migrate"/> 60 seconds before a maintenance event starts. This will give the application an opportunity /// to perform any tasks in preparation for the event, such as backing up data or updating logs. Otherwise, the value will be /// <see cref="MaintenanceStatus.None"/>. /// </remarks> /// <returns>The current maintenance status.</returns> /// <seealso cref="Scheduling.OnHostMaintenance"/> public virtual MaintenanceStatus GetMaintenanceStatus() { throw new NotImplementedException(); } /// <summary> /// Asynchronously gets the maintenance status for the VM currently running this code. /// </summary> /// <remarks> /// If the <see cref="Instance.Scheduling"/>'s <see cref="Scheduling.OnHostMaintenance"/> is set to "MIGRATE", the maintenance status will change /// to <see cref="MaintenanceStatus.Migrate"/> 60 seconds before a maintenance event starts. This will give the application an opportunity /// to perform any tasks in preparation for the event, such as backing up data or updating logs. Otherwise, the value will be /// <see cref="MaintenanceStatus.None"/>. /// </remarks> /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> /// <returns>A task containing the current maintenance status.</returns> /// <seealso cref="Scheduling.OnHostMaintenance"/> public virtual Task<MaintenanceStatus> GetMaintenanceStatusAsync(CancellationToken cancellationToken = default) { throw new NotImplementedException(); } /// <summary> /// Gets the metadata value(s) specified by the relative URL synchronously. /// </summary> /// <remarks> /// <para> /// If the key specified is a metadata endpoint, the result will be the value, possibly separated by newlines if there are multiple values. /// If the key specified is a directory, a recursive request will be made and the result will be a JSON object containing all values in the directory. /// </para> /// <para> /// See https://cloud.google.com/compute/docs/storing-retrieving-metadata#project_and_instance_metadata for more information on available keys. /// </para> /// </remarks> /// <param name="key">The metadata key of the value(s) to get, such as "instance/scheduling/automatic-restart"</param> /// <exception cref="ArgumentException"> /// <paramref name="key"/> does not have the proper format for a metadata key, which is a relative URL. /// </exception> /// <returns>The <see cref="MetadataResult"/> with the current value(s) for an endpoint or a JSON object with the contents of the directory.</returns> /// <seealso cref="WaitForChange"/> public virtual MetadataResult GetMetadata(string key) { throw new NotImplementedException(); } /// <summary> /// Gets the metadata value(s) specified by the relative URL asynchronously. /// </summary> /// <remarks> /// <para> /// If the key specified is a metadata endpoint, the result will be the value, possibly separated by newlines if there are multiple values. /// If the key specified is a directory, a recursive request will be made and the result will be a JSON object containing all values in the directory. /// </para> /// <para> /// See https://cloud.google.com/compute/docs/storing-retrieving-metadata#project_and_instance_metadata for more information on available keys. /// </para> /// </remarks> /// <param name="key">The metadata key of the value(s) to get, such as "instance/scheduling/automatic-restart"</param> /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> /// <exception cref="ArgumentException"> /// <paramref name="key"/> does not have the proper format for a metadata key, which is a relative URL. /// </exception> /// <returns>A task containing the <see cref="MetadataResult"/> with the current value(s) for an endpoint or a JSON object with the contents of the directory.</returns> /// <seealso cref="WaitForChangeAsync"/> public virtual Task<MetadataResult> GetMetadataAsync(string key, CancellationToken cancellationToken = default) { throw new NotImplementedException(); } /// <summary> /// Synchronously gets the metadata for the project of the VM currently running this code. /// </summary> /// <remarks> /// The project metadata contains information about the project, such as its ID, and custom metadata and it can be /// accessed without authentication from an application running on an instance of that project. Check <see cref="IsServerAvailable"/> or /// <see cref="IsServerAvailableAsync(CancellationToken)"/> to determine if the metadata can be accessed. /// </remarks> /// <returns>The <see cref="Project"/> representing the metadata.</returns> public virtual Project GetProjectMetadata() { throw new NotImplementedException(); } /// <summary> /// Asynchronously gets the metadata for the project of the VM currently running this code. /// </summary> /// <remarks> /// The project metadata contains information about the project, such as its ID, and custom metadata and it can be /// accessed without authentication from an application running on an instance of that project. Check <see cref="IsServerAvailable"/> or /// <see cref="IsServerAvailableAsync(CancellationToken)"/> to determine if the metadata can be accessed. /// </remarks> /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> /// <returns>A task containing the <see cref="Project"/> representing the metadata.</returns> public virtual Task<Project> GetProjectMetadataAsync(CancellationToken cancellationToken = default) { throw new NotImplementedException(); } /// <summary> /// Gets the value indicating whether the metadata server or an emulator for the server is available synchronously. /// </summary> /// <remarks> /// Normally, the metadata server can only be accessed from an application running on a Google Compute Engine VM instance or /// Google App Engine Flexible Environment, but if an metadata server emulator is available, this will also return true. /// </remarks> /// <returns>True if the normal metadata server or an emulator is available; false otherwise.</returns> public virtual bool IsServerAvailable() { throw new NotImplementedException(); } /// <summary> /// Gets the value indicating whether the metadata server or an emulator for the server is available asynchronously. /// </summary> /// <remarks> /// Normally, the metadata server can only be accessed from an application running on a Google Compute Engine VM instance or /// Google App Engine Flexible Environment, but if an metadata server emulator is available, this will also return true. /// </remarks> /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> /// <returns>A task containing true if the normal metadata server or an emulator is available; false otherwise.</returns> public virtual Task<bool> IsServerAvailableAsync(CancellationToken cancellationToken = default) { throw new NotImplementedException(); } /// <summary> /// Occurs when the the instance's metadata has changed. /// </summary> /// <remarks> /// <para> /// To wait on changes for individual parts of the metadata, see <see cref="WaitForChange"/> or <see cref="WaitForChangeAsync"/>. /// </para> /// <para> /// Note: the event may be fired on a different thread from the one used to add the handler. /// </para> /// </remarks> /// <seealso cref="GetInstanceMetadata"/> /// <seealso cref="GetInstanceMetadataAsync"/> /// <seealso cref="WaitForChange"/> /// <seealso cref="WaitForChangeAsync"/> public virtual event EventHandler<InstanceMetadataChangedEventArgs> InstanceMetadataChanged { add { throw new NotImplementedException(); } remove { throw new NotImplementedException(); } } /// <summary> /// Occurs when the the instance's maintenance status has changed. /// </summary> /// <remarks> /// <para> /// Note: the event may be fired on a different thread from the one used to add the handler. /// </para> /// </remarks> /// <seealso cref="GetMaintenanceStatus"/> /// <seealso cref="GetMaintenanceStatusAsync(CancellationToken)"/> public virtual event EventHandler<MaintenanceStatusChangedEventArgs> MaintenanceStatusChanged { add { throw new NotImplementedException(); } remove { throw new NotImplementedException(); } } /// <summary> /// Occurs when the the project's metadata has changed. /// </summary> /// <remarks> /// <para> /// To wait on changes for individual parts of the metadata, see <see cref="WaitForChange"/> or <see cref="WaitForChangeAsync"/>. /// </para> /// <para> /// Note: the event may be fired on a different thread from the one used to add the handler. /// </para> /// </remarks> /// <seealso cref="GetProjectMetadata"/> /// <seealso cref="GetProjectMetadataAsync"/> /// <seealso cref="WaitForChange"/> /// <seealso cref="WaitForChangeAsync"/> public virtual event EventHandler<ProjectMetadataChangedEventArgs> ProjectMetadataChanged { add { throw new NotImplementedException(); } remove { throw new NotImplementedException(); } } /// <summary> /// Waits for changes to the value or values specified by the relative URL synchronously. /// </summary> /// <remarks> /// <para> /// If the key specified is a metadata endpoint, the result will be the value, possibly separated by newlines if there are multiple values. /// If the key specified is a directory, a recursive request will be made and the result will be a JSON object containing all values in the directory. /// </para> /// <para> /// If the <paramref name="lastETag"/> is specified and it differs from the ETag of the value currently on the server, it indicates that the value has already /// changed since the last known value as obtained, and the changed value will be returned immediately. /// </para> /// <para> /// If the <paramref name="timeout"/> expires before changes are made, the current value will be returned. If unspecified, half the length of the timeout in /// the <see cref="HttpClient"/> will be used instead. Note that if the the timeout in the <see cref="HttpClient"/> elapses before the wait timeout elapses /// on the server a <see cref="TaskCanceledException"/> exception will occur. /// </para> /// <para> /// See https://cloud.google.com/compute/docs/storing-retrieving-metadata#project_and_instance_metadata for more information on available keys. /// </para> /// <para> /// To detect any changes at the project or instance level, use a <paramref name="key"/> of "project" or "instance". /// Alternatively, use <seealso cref="ProjectMetadataChanged"/> or <seealso cref="InstanceMetadataChanged"/>, respectively. /// </para> /// </remarks> /// <param name="key">The metadata key on which to wait for changes, such as "instance/scheduling/automatic-restart"</param> /// <param name="lastETag">The ETag of the last known value. May be null.</param> /// <param name="timeout">The amount of time to wait for changes.</param> /// <exception cref="ArgumentException"> /// <paramref name="key"/> does not have the proper format for a metadata key, which is a relative URL, <paramref name="timeout"/> represents a negative duration, /// or <paramref name="lastETag"/> is invalid. /// </exception> /// <exception cref="TaskCanceledException"> /// The timeout in the <see cref="HttpClient"/> elapses before the response comes back from the server. /// </exception> /// <returns>The <see cref="MetadataResult"/> with the changed value(s) for an endpoint or a JSON object with the changed contents of the directory.</returns> /// <seealso cref="InstanceMetadataChanged"/> /// <seealso cref="ProjectMetadataChanged"/> /// <seealso cref="GetMetadata"/> public virtual MetadataResult WaitForChange(string key, string lastETag = null, TimeSpan timeout = default) { throw new NotImplementedException(); } /// <summary> /// Waits for changes to the value or values specified by the relative URL asynchronously. /// </summary> /// <remarks> /// <para> /// If the key specified is a metadata endpoint, the result will be the value, possibly separated by newlines if there are multiple values. /// If the key specified is a directory, a recursive request will be made and the result will be a JSON object containing all values in the directory. /// </para> /// <para> /// If the <paramref name="lastETag"/> is specified and it differs from the ETag of the value currently on the server, it indicates that the value has already /// changed since the last known value as obtained, and the changed value will be returned immediately. /// </para> /// <para> /// If the <paramref name="timeout"/> expires before changes are made, the current value will be returned. If unspecified, half the length of the timeout in /// the <see cref="HttpClient"/> will be used instead. Note that if the the timeout in the <see cref="HttpClient"/> elapses before the wait timeout elapses /// on the server a <see cref="TaskCanceledException"/> exception will occur. /// </para> /// <para> /// See https://cloud.google.com/compute/docs/storing-retrieving-metadata#project_and_instance_metadata for more information on available keys. /// </para> /// <para> /// To detect any changes at the project or instance level, use a <paramref name="key"/> of "project" or "instance". /// Alternatively, use <seealso cref="ProjectMetadataChanged"/> or <seealso cref="InstanceMetadataChanged"/>, respectively. /// </para> /// </remarks> /// <param name="key">The metadata key on which to wait for changes, such as "instance/scheduling/automatic-restart"</param> /// <param name="lastETag">The ETag of the last known value. May be null.</param> /// <param name="timeout">The amount of time to wait for changes.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> /// <exception cref="ArgumentException"> /// <paramref name="key"/> does not have the proper format for a metadata key, which is a relative URL, <paramref name="timeout"/> represents a negative duration, /// or <paramref name="lastETag"/> is invalid. /// </exception> /// <exception cref="TaskCanceledException"> /// The timeout in the <see cref="HttpClient"/> elapses before the response comes back from the server. /// </exception> /// <returns> /// A task containing the <see cref="MetadataResult"/> with the changed value(s) for an endpoint or a JSON object with the changed contents of the directory. /// </returns> /// <seealso cref="InstanceMetadataChanged"/> /// <seealso cref="ProjectMetadataChanged"/> /// <seealso cref="GetMetadataAsync"/> public virtual Task<MetadataResult> WaitForChangeAsync( string key, string lastETag = null, TimeSpan timeout = default, CancellationToken cancellationToken = default) { throw new NotImplementedException(); } } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== // // <OWNER>[....]</OWNER> /*============================================================================= ** ** Class: Mutex ** ** ** Purpose: synchronization primitive that can also be used for interprocess synchronization ** ** =============================================================================*/ namespace System.Threading { using System; using System.Threading; using System.Runtime.CompilerServices; using System.Security.Permissions; using System.IO; using Microsoft.Win32; using Microsoft.Win32.SafeHandles; using System.Runtime.InteropServices; using System.Runtime.ConstrainedExecution; using System.Runtime.Versioning; using System.Security.Principal; using System.Security; using System.Diagnostics.Contracts; #if FEATURE_MACL using System.Security.AccessControl; #endif [HostProtection(Synchronization=true, ExternalThreading=true)] [ComVisible(true)] public sealed class Mutex : WaitHandle { static bool dummyBool; #if FEATURE_MACL // Enables workaround for known OS bug at // http://support.microsoft.com/default.aspx?scid=kb;en-us;889318 // Calls to OpenMutex and CloseHandle on a mutex must essentially be serialized // to avoid a bug in which the mutex allows multiple entries. static Mutex s_ReservedMutex = null; // an arbitrary, reserved name. // const string c_ReservedMutexName = "Global\\CLR_RESERVED_MUTEX_NAME"; #endif #if !FEATURE_MACL public class MutexSecurity { } #endif [System.Security.SecurityCritical] // auto-generated_required [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] [ResourceExposure(ResourceScope.None)] [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)] public Mutex(bool initiallyOwned, String name, out bool createdNew) : this(initiallyOwned, name, out createdNew, (MutexSecurity)null) { } [System.Security.SecurityCritical] // auto-generated_required [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] [ResourceExposure(ResourceScope.Machine)] [ResourceConsumption(ResourceScope.Machine)] public unsafe Mutex(bool initiallyOwned, String name, out bool createdNew, MutexSecurity mutexSecurity) { if(null != name && System.IO.Path.MAX_PATH < name.Length) { throw new ArgumentException(Environment.GetResourceString("Argument_WaitHandleNameTooLong",name)); } Contract.EndContractBlock(); Win32Native.SECURITY_ATTRIBUTES secAttrs = null; #if FEATURE_MACL // For ACL's, get the security descriptor from the MutexSecurity. if (mutexSecurity != null) { secAttrs = new Win32Native.SECURITY_ATTRIBUTES(); secAttrs.nLength = (int)Marshal.SizeOf(secAttrs); byte[] sd = mutexSecurity.GetSecurityDescriptorBinaryForm(); byte* pSecDescriptor = stackalloc byte[sd.Length]; Buffer.Memcpy(pSecDescriptor, 0, sd, 0, sd.Length); secAttrs.pSecurityDescriptor = pSecDescriptor; } #endif CreateMutexWithGuaranteedCleanup(initiallyOwned, name, out createdNew, secAttrs); } [System.Security.SecurityCritical] // auto-generated_required [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] [ResourceExposure(ResourceScope.Machine)] [ResourceConsumption(ResourceScope.Machine)] internal Mutex(bool initiallyOwned, String name, out bool createdNew, Win32Native.SECURITY_ATTRIBUTES secAttrs) { if (null != name && Path.MAX_PATH < name.Length) { throw new ArgumentException(Environment.GetResourceString("Argument_WaitHandleNameTooLong", name)); } Contract.EndContractBlock(); CreateMutexWithGuaranteedCleanup(initiallyOwned, name, out createdNew, secAttrs); } #if FEATURE_LEGACYNETCF static string WinCEObjectNameQuirk(string name) { // WinCE allowed backslashes in kernel object names, but WinNT does not allow them. // Replace all backslashes with a rare unicode character if we are in NetCF compat mode. // Mutex was the only named kernel object exposed to phone apps, so we do not have // to apply this quirk in other places. return name.Replace('\\', '\u2044'); } #endif [System.Security.SecurityCritical] // auto-generated_required [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] [ResourceExposure(ResourceScope.Machine)] [ResourceConsumption(ResourceScope.Machine)] internal void CreateMutexWithGuaranteedCleanup(bool initiallyOwned, String name, out bool createdNew, Win32Native.SECURITY_ATTRIBUTES secAttrs) { #if FEATURE_LEGACYNETCF if (CompatibilitySwitches.IsAppEarlierThanWindowsPhone8) name = WinCEObjectNameQuirk(name); #endif RuntimeHelpers.CleanupCode cleanupCode = new RuntimeHelpers.CleanupCode(MutexCleanupCode); MutexCleanupInfo cleanupInfo = new MutexCleanupInfo(null, false); MutexTryCodeHelper tryCodeHelper = new MutexTryCodeHelper(initiallyOwned, cleanupInfo, name, secAttrs, this); RuntimeHelpers.TryCode tryCode = new RuntimeHelpers.TryCode(tryCodeHelper.MutexTryCode); RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup( tryCode, cleanupCode, cleanupInfo); createdNew = tryCodeHelper.m_newMutex; } internal class MutexTryCodeHelper { bool m_initiallyOwned; MutexCleanupInfo m_cleanupInfo; internal bool m_newMutex; String m_name; [System.Security.SecurityCritical] // auto-generated Win32Native.SECURITY_ATTRIBUTES m_secAttrs; Mutex m_mutex; [System.Security.SecurityCritical] // auto-generated [PrePrepareMethod] internal MutexTryCodeHelper(bool initiallyOwned,MutexCleanupInfo cleanupInfo, String name, Win32Native.SECURITY_ATTRIBUTES secAttrs, Mutex mutex) { m_initiallyOwned = initiallyOwned; m_cleanupInfo = cleanupInfo; m_name = name; m_secAttrs = secAttrs; m_mutex = mutex; } [System.Security.SecurityCritical] // auto-generated [PrePrepareMethod] internal void MutexTryCode(object userData) { SafeWaitHandle mutexHandle = null; // try block RuntimeHelpers.PrepareConstrainedRegions(); try { } finally { if (m_initiallyOwned) { m_cleanupInfo.inCriticalRegion = true; #if !FEATURE_CORECLR Thread.BeginThreadAffinity(); Thread.BeginCriticalRegion(); #endif //!FEATURE_CORECLR } } int errorCode = 0; RuntimeHelpers.PrepareConstrainedRegions(); try { } finally { errorCode = CreateMutexHandle(m_initiallyOwned, m_name, m_secAttrs, out mutexHandle); } if (mutexHandle.IsInvalid) { mutexHandle.SetHandleAsInvalid(); if(null != m_name && 0 != m_name.Length && Win32Native.ERROR_INVALID_HANDLE == errorCode) throw new WaitHandleCannotBeOpenedException(Environment.GetResourceString("Threading.WaitHandleCannotBeOpenedException_InvalidHandle", m_name)); __Error.WinIOError(errorCode, m_name); } m_newMutex = errorCode != Win32Native.ERROR_ALREADY_EXISTS; m_mutex.SetHandleInternal(mutexHandle); mutexHandle.SetAsMutex(); m_mutex.hasThreadAffinity = true; } } [System.Security.SecurityCritical] // auto-generated [PrePrepareMethod] private void MutexCleanupCode(Object userData, bool exceptionThrown) { MutexCleanupInfo cleanupInfo = (MutexCleanupInfo) userData; // If hasThreadAffinity isn't true, we've thrown an exception in the above try, and we must free the mutex // on this OS thread before ending our thread affninity. if(!hasThreadAffinity) { if (cleanupInfo.mutexHandle != null && !cleanupInfo.mutexHandle.IsInvalid) { if( cleanupInfo.inCriticalRegion) { Win32Native.ReleaseMutex(cleanupInfo.mutexHandle); } cleanupInfo.mutexHandle.Dispose(); } if( cleanupInfo.inCriticalRegion) { #if !FEATURE_CORECLR Thread.EndCriticalRegion(); Thread.EndThreadAffinity(); #endif } } } internal class MutexCleanupInfo { [System.Security.SecurityCritical] // auto-generated internal SafeWaitHandle mutexHandle; internal bool inCriticalRegion; [System.Security.SecurityCritical] // auto-generated internal MutexCleanupInfo(SafeWaitHandle mutexHandle, bool inCriticalRegion) { this.mutexHandle = mutexHandle; this.inCriticalRegion = inCriticalRegion; } } // For the .NET Compact Framework this constructor was security safe critical. // For Windows Phone version 8 (Apollo), all apps will run as fully trusted, // meaning the CLR is not considered a trust boundary. This API could be marked security critical. // However for Windows Phone version 7.1 applications, they will still be run // as partially trusted applications, with our security transparency model enforced. // So we have this peculiar #ifdef that should be enabled only for .NET CF backwards // compatibility. #if FEATURE_LEGACYNETCF [System.Security.SecuritySafeCritical] // auto-generated_required #else [System.Security.SecurityCritical] // auto-generated_required #endif //FEATURE_LEGACYNETCF [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] [ResourceExposure(ResourceScope.Machine)] [ResourceConsumption(ResourceScope.Machine)] public Mutex(bool initiallyOwned, String name) : this(initiallyOwned, name, out dummyBool) { } [System.Security.SecuritySafeCritical] // auto-generated [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] [ResourceExposure(ResourceScope.None)] [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)] public Mutex(bool initiallyOwned) : this(initiallyOwned, null, out dummyBool) { } [System.Security.SecuritySafeCritical] // auto-generated [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] [ResourceExposure(ResourceScope.None)] [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)] public Mutex() : this(false, null, out dummyBool) { } [System.Security.SecurityCritical] // auto-generated [ResourceExposure(ResourceScope.Machine)] [ResourceConsumption(ResourceScope.Machine)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] private Mutex(SafeWaitHandle handle) { SetHandleInternal(handle); handle.SetAsMutex(); hasThreadAffinity = true; } [System.Security.SecurityCritical] // auto-generated_required [ResourceExposure(ResourceScope.Machine)] [ResourceConsumption(ResourceScope.Machine)] public static Mutex OpenExisting(string name) { #if !FEATURE_MACL return OpenExisting(name, (MutexRights) 0); #else // FEATURE_PAL return OpenExisting(name, MutexRights.Modify | MutexRights.Synchronize); #endif // FEATURE_PAL } #if !FEATURE_MACL public enum MutexRights { } #endif [System.Security.SecurityCritical] // auto-generated_required [ResourceExposure(ResourceScope.Machine)] [ResourceConsumption(ResourceScope.Machine)] public static Mutex OpenExisting(string name, MutexRights rights) { Mutex result; switch (OpenExistingWorker(name, rights, out result)) { case OpenExistingResult.NameNotFound: throw new WaitHandleCannotBeOpenedException(); case OpenExistingResult.NameInvalid: throw new WaitHandleCannotBeOpenedException(Environment.GetResourceString("Threading.WaitHandleCannotBeOpenedException_InvalidHandle", name)); case OpenExistingResult.PathNotFound: __Error.WinIOError(Win32Native.ERROR_PATH_NOT_FOUND, name); return result; //never executes default: return result; } } [System.Security.SecurityCritical] // auto-generated_required [ResourceExposure(ResourceScope.Machine)] [ResourceConsumption(ResourceScope.Machine)] public static bool TryOpenExisting(string name, out Mutex result) { #if !FEATURE_MACL return OpenExistingWorker(name, (MutexRights)0, out result) == OpenExistingResult.Success; #else // FEATURE_PAL return OpenExistingWorker(name, MutexRights.Modify | MutexRights.Synchronize, out result) == OpenExistingResult.Success; #endif // FEATURE_PAL } [System.Security.SecurityCritical] // auto-generated_required [ResourceExposure(ResourceScope.Machine)] [ResourceConsumption(ResourceScope.Machine)] public static bool TryOpenExisting(string name, MutexRights rights, out Mutex result) { return OpenExistingWorker(name, rights, out result) == OpenExistingResult.Success; } [System.Security.SecurityCritical] [ResourceExposure(ResourceScope.Machine)] [ResourceConsumption(ResourceScope.Machine)] private static OpenExistingResult OpenExistingWorker(string name, MutexRights rights, out Mutex result) { if (name == null) { throw new ArgumentNullException("name", Environment.GetResourceString("ArgumentNull_WithParamName")); } if(name.Length == 0) { throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), "name"); } if(System.IO.Path.MAX_PATH < name.Length) { throw new ArgumentException(Environment.GetResourceString("Argument_WaitHandleNameTooLong",name)); } Contract.EndContractBlock(); result = null; #if FEATURE_LEGACYNETCF if (CompatibilitySwitches.IsAppEarlierThanWindowsPhone8) name = WinCEObjectNameQuirk(name); #endif // To allow users to view & edit the ACL's, call OpenMutex // with parameters to allow us to view & edit the ACL. This will // fail if we don't have permission to view or edit the ACL's. // If that happens, ask for less permissions. #if FEATURE_MACL SafeWaitHandle myHandle = Win32Native.OpenMutex((int) rights, false, name); #else SafeWaitHandle myHandle = Win32Native.OpenMutex(Win32Native.MUTEX_MODIFY_STATE | Win32Native.SYNCHRONIZE, false, name); #endif int errorCode = 0; if (myHandle.IsInvalid) { errorCode = Marshal.GetLastWin32Error(); if(Win32Native.ERROR_FILE_NOT_FOUND == errorCode || Win32Native.ERROR_INVALID_NAME == errorCode) return OpenExistingResult.NameNotFound; if (Win32Native.ERROR_PATH_NOT_FOUND == errorCode) return OpenExistingResult.PathNotFound; if (null != name && 0 != name.Length && Win32Native.ERROR_INVALID_HANDLE == errorCode) return OpenExistingResult.NameInvalid; // this is for passed through Win32Native Errors __Error.WinIOError(errorCode,name); } result = new Mutex(myHandle); return OpenExistingResult.Success; } // Note: To call ReleaseMutex, you must have an ACL granting you // MUTEX_MODIFY_STATE rights (0x0001). The other interesting value // in a Mutex's ACL is MUTEX_ALL_ACCESS (0x1F0001). [System.Security.SecuritySafeCritical] // auto-generated [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] public void ReleaseMutex() { if (Win32Native.ReleaseMutex(safeWaitHandle)) { #if !FEATURE_CORECLR Thread.EndCriticalRegion(); Thread.EndThreadAffinity(); #endif } else { #if FEATURE_CORECLR throw new Exception(Environment.GetResourceString("Arg_SynchronizationLockException")); #else throw new ApplicationException(Environment.GetResourceString("Arg_SynchronizationLockException")); #endif // FEATURE_CORECLR } } [System.Security.SecurityCritical] // auto-generated [ResourceExposure(ResourceScope.Machine)] [ResourceConsumption(ResourceScope.Machine)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] static int CreateMutexHandle(bool initiallyOwned, String name, Win32Native.SECURITY_ATTRIBUTES securityAttribute, out SafeWaitHandle mutexHandle) { int errorCode; bool fReservedMutexObtained = false; bool fAffinity = false; while(true) { mutexHandle = Win32Native.CreateMutex(securityAttribute, initiallyOwned, name); errorCode = Marshal.GetLastWin32Error(); if( !mutexHandle.IsInvalid) { break; } if( errorCode == Win32Native.ERROR_ACCESS_DENIED) { // If a mutex with the name already exists, OS will try to open it with FullAccess. // It might fail if we don't have enough access. In that case, we try to open the mutex will modify and synchronize access. // RuntimeHelpers.PrepareConstrainedRegions(); try { try { } finally { #if !FEATURE_CORECLR Thread.BeginThreadAffinity(); #endif fAffinity = true; } AcquireReservedMutex(ref fReservedMutexObtained); mutexHandle = Win32Native.OpenMutex(Win32Native.MUTEX_MODIFY_STATE | Win32Native.SYNCHRONIZE, false, name); if(!mutexHandle.IsInvalid) { errorCode = Win32Native.ERROR_ALREADY_EXISTS; } else { errorCode = Marshal.GetLastWin32Error(); } } finally { if (fReservedMutexObtained) ReleaseReservedMutex(); if (fAffinity) { #if !FEATURE_CORECLR Thread.EndThreadAffinity(); #endif } } // There could be a ---- here, the other owner of the mutex can free the mutex, // We need to retry creation in that case. if( errorCode != Win32Native.ERROR_FILE_NOT_FOUND) { if( errorCode == Win32Native.ERROR_SUCCESS) { errorCode = Win32Native.ERROR_ALREADY_EXISTS; } break; } } else { break; } } return errorCode; } #if FEATURE_MACL [System.Security.SecuritySafeCritical] // auto-generated public MutexSecurity GetAccessControl() { return new MutexSecurity(safeWaitHandle, AccessControlSections.Access | AccessControlSections.Owner | AccessControlSections.Group); } [System.Security.SecuritySafeCritical] // auto-generated public void SetAccessControl(MutexSecurity mutexSecurity) { if (mutexSecurity == null) throw new ArgumentNullException("mutexSecurity"); Contract.EndContractBlock(); mutexSecurity.Persist(safeWaitHandle); } #endif // Enables workaround for known OS bug at // http://support.microsoft.com/default.aspx?scid=kb;en-us;889318 // One machine-wide mutex serializes all OpenMutex and CloseHandle operations. [System.Security.SecurityCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] #if !FEATURE_CORECLR [SecurityPermission(SecurityAction.Assert, ControlPrincipal = true)] #endif internal static unsafe void AcquireReservedMutex(ref bool bHandleObtained) { #if FEATURE_MACL SafeWaitHandle mutexHandle = null; int errorCode; bHandleObtained = false; if (!Environment.IsW2k3) { return; } if (s_ReservedMutex == null) { // Create a maximally-permissive security descriptor, to ensure we never get an // ACCESS_DENIED error when calling CreateMutex MutexSecurity sec = new MutexSecurity(); SecurityIdentifier everyoneSid = new SecurityIdentifier(WellKnownSidType.WorldSid, null); sec.AddAccessRule(new MutexAccessRule(everyoneSid, MutexRights.FullControl, AccessControlType.Allow)); // For ACL's, get the security descriptor from the MutexSecurity. Win32Native.SECURITY_ATTRIBUTES secAttrs = new Win32Native.SECURITY_ATTRIBUTES(); secAttrs.nLength = (int)Marshal.SizeOf(secAttrs); byte[] sd = sec.GetSecurityDescriptorBinaryForm(); byte * bytesOnStack = stackalloc byte[sd.Length]; Buffer.Memcpy(bytesOnStack, 0, sd, 0, sd.Length); secAttrs.pSecurityDescriptor = bytesOnStack; RuntimeHelpers.PrepareConstrainedRegions(); try {} finally { mutexHandle = Win32Native.CreateMutex(secAttrs, false, c_ReservedMutexName); // need to set specially, since this mutex cannot lock on itself while closing itself. mutexHandle.SetAsReservedMutex(); } errorCode = Marshal.GetLastWin32Error(); if (mutexHandle.IsInvalid) { mutexHandle.SetHandleAsInvalid(); __Error.WinIOError(errorCode, c_ReservedMutexName); } Mutex m = new Mutex(mutexHandle); Interlocked.CompareExchange(ref s_ReservedMutex, m, null); } RuntimeHelpers.PrepareConstrainedRegions(); try { } finally { try { s_ReservedMutex.WaitOne(); bHandleObtained = true; } catch (AbandonedMutexException) { // we don't care if another process holding the Mutex was killed bHandleObtained = true; } } #else bHandleObtained = true; #endif } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] internal static void ReleaseReservedMutex() { #if FEATURE_MACL if (!Environment.IsW2k3) { return; } Contract.Assert(s_ReservedMutex != null, "ReleaseReservedMutex called without prior call to AcquireReservedMutex!"); s_ReservedMutex.ReleaseMutex(); #endif } } }
// 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 gagvc = Google.Ads.GoogleAds.V8.Common; using gagve = Google.Ads.GoogleAds.V8.Enums; using gagvr = Google.Ads.GoogleAds.V8.Resources; using gaxgrpc = Google.Api.Gax.Grpc; using gr = Google.Rpc; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using NUnit.Framework; using Google.Ads.GoogleAds.V8.Services; namespace Google.Ads.GoogleAds.Tests.V8.Services { /// <summary>Generated unit tests.</summary> public sealed class GeneratedConversionActionServiceClientTest { [Category("Autogenerated")][Test] public void GetConversionActionRequestObject() { moq::Mock<ConversionActionService.ConversionActionServiceClient> mockGrpcClient = new moq::Mock<ConversionActionService.ConversionActionServiceClient>(moq::MockBehavior.Strict); GetConversionActionRequest request = new GetConversionActionRequest { ResourceNameAsConversionActionName = gagvr::ConversionActionName.FromCustomerConversionAction("[CUSTOMER_ID]", "[CONVERSION_ACTION_ID]"), }; gagvr::ConversionAction expectedResponse = new gagvr::ConversionAction { ResourceNameAsConversionActionName = gagvr::ConversionActionName.FromCustomerConversionAction("[CUSTOMER_ID]", "[CONVERSION_ACTION_ID]"), Status = gagve::ConversionActionStatusEnum.Types.ConversionActionStatus.Hidden, Type = gagve::ConversionActionTypeEnum.Types.ConversionActionType.Salesforce, Category = gagve::ConversionActionCategoryEnum.Types.ConversionActionCategory.AddToCart, ValueSettings = new gagvr::ConversionAction.Types.ValueSettings(), CountingType = gagve::ConversionActionCountingTypeEnum.Types.ConversionActionCountingType.Unspecified, AttributionModelSettings = new gagvr::ConversionAction.Types.AttributionModelSettings(), TagSnippets = { new gagvc::TagSnippet(), }, MobileAppVendor = gagve::MobileAppVendorEnum.Types.MobileAppVendor.GoogleAppStore, FirebaseSettings = new gagvr::ConversionAction.Types.FirebaseSettings(), ThirdPartyAppAnalyticsSettings = new gagvr::ConversionAction.Types.ThirdPartyAppAnalyticsSettings(), Id = -6774108720365892680L, ConversionActionName = gagvr::ConversionActionName.FromCustomerConversionAction("[CUSTOMER_ID]", "[CONVERSION_ACTION_ID]"), OwnerCustomerAsCustomerName = gagvr::CustomerName.FromCustomer("[CUSTOMER_ID]"), IncludeInConversionsMetric = false, ClickThroughLookbackWindowDays = -4831593457096707011L, ViewThroughLookbackWindowDays = -8283075401830951626L, PhoneCallDurationSeconds = -8070508326407639729L, AppId = "app_idfead82f3", }; mockGrpcClient.Setup(x => x.GetConversionAction(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ConversionActionServiceClient client = new ConversionActionServiceClientImpl(mockGrpcClient.Object, null); gagvr::ConversionAction response = client.GetConversionAction(request); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task GetConversionActionRequestObjectAsync() { moq::Mock<ConversionActionService.ConversionActionServiceClient> mockGrpcClient = new moq::Mock<ConversionActionService.ConversionActionServiceClient>(moq::MockBehavior.Strict); GetConversionActionRequest request = new GetConversionActionRequest { ResourceNameAsConversionActionName = gagvr::ConversionActionName.FromCustomerConversionAction("[CUSTOMER_ID]", "[CONVERSION_ACTION_ID]"), }; gagvr::ConversionAction expectedResponse = new gagvr::ConversionAction { ResourceNameAsConversionActionName = gagvr::ConversionActionName.FromCustomerConversionAction("[CUSTOMER_ID]", "[CONVERSION_ACTION_ID]"), Status = gagve::ConversionActionStatusEnum.Types.ConversionActionStatus.Hidden, Type = gagve::ConversionActionTypeEnum.Types.ConversionActionType.Salesforce, Category = gagve::ConversionActionCategoryEnum.Types.ConversionActionCategory.AddToCart, ValueSettings = new gagvr::ConversionAction.Types.ValueSettings(), CountingType = gagve::ConversionActionCountingTypeEnum.Types.ConversionActionCountingType.Unspecified, AttributionModelSettings = new gagvr::ConversionAction.Types.AttributionModelSettings(), TagSnippets = { new gagvc::TagSnippet(), }, MobileAppVendor = gagve::MobileAppVendorEnum.Types.MobileAppVendor.GoogleAppStore, FirebaseSettings = new gagvr::ConversionAction.Types.FirebaseSettings(), ThirdPartyAppAnalyticsSettings = new gagvr::ConversionAction.Types.ThirdPartyAppAnalyticsSettings(), Id = -6774108720365892680L, ConversionActionName = gagvr::ConversionActionName.FromCustomerConversionAction("[CUSTOMER_ID]", "[CONVERSION_ACTION_ID]"), OwnerCustomerAsCustomerName = gagvr::CustomerName.FromCustomer("[CUSTOMER_ID]"), IncludeInConversionsMetric = false, ClickThroughLookbackWindowDays = -4831593457096707011L, ViewThroughLookbackWindowDays = -8283075401830951626L, PhoneCallDurationSeconds = -8070508326407639729L, AppId = "app_idfead82f3", }; mockGrpcClient.Setup(x => x.GetConversionActionAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::ConversionAction>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ConversionActionServiceClient client = new ConversionActionServiceClientImpl(mockGrpcClient.Object, null); gagvr::ConversionAction responseCallSettings = await client.GetConversionActionAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); gagvr::ConversionAction responseCancellationToken = await client.GetConversionActionAsync(request, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void GetConversionAction() { moq::Mock<ConversionActionService.ConversionActionServiceClient> mockGrpcClient = new moq::Mock<ConversionActionService.ConversionActionServiceClient>(moq::MockBehavior.Strict); GetConversionActionRequest request = new GetConversionActionRequest { ResourceNameAsConversionActionName = gagvr::ConversionActionName.FromCustomerConversionAction("[CUSTOMER_ID]", "[CONVERSION_ACTION_ID]"), }; gagvr::ConversionAction expectedResponse = new gagvr::ConversionAction { ResourceNameAsConversionActionName = gagvr::ConversionActionName.FromCustomerConversionAction("[CUSTOMER_ID]", "[CONVERSION_ACTION_ID]"), Status = gagve::ConversionActionStatusEnum.Types.ConversionActionStatus.Hidden, Type = gagve::ConversionActionTypeEnum.Types.ConversionActionType.Salesforce, Category = gagve::ConversionActionCategoryEnum.Types.ConversionActionCategory.AddToCart, ValueSettings = new gagvr::ConversionAction.Types.ValueSettings(), CountingType = gagve::ConversionActionCountingTypeEnum.Types.ConversionActionCountingType.Unspecified, AttributionModelSettings = new gagvr::ConversionAction.Types.AttributionModelSettings(), TagSnippets = { new gagvc::TagSnippet(), }, MobileAppVendor = gagve::MobileAppVendorEnum.Types.MobileAppVendor.GoogleAppStore, FirebaseSettings = new gagvr::ConversionAction.Types.FirebaseSettings(), ThirdPartyAppAnalyticsSettings = new gagvr::ConversionAction.Types.ThirdPartyAppAnalyticsSettings(), Id = -6774108720365892680L, ConversionActionName = gagvr::ConversionActionName.FromCustomerConversionAction("[CUSTOMER_ID]", "[CONVERSION_ACTION_ID]"), OwnerCustomerAsCustomerName = gagvr::CustomerName.FromCustomer("[CUSTOMER_ID]"), IncludeInConversionsMetric = false, ClickThroughLookbackWindowDays = -4831593457096707011L, ViewThroughLookbackWindowDays = -8283075401830951626L, PhoneCallDurationSeconds = -8070508326407639729L, AppId = "app_idfead82f3", }; mockGrpcClient.Setup(x => x.GetConversionAction(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ConversionActionServiceClient client = new ConversionActionServiceClientImpl(mockGrpcClient.Object, null); gagvr::ConversionAction response = client.GetConversionAction(request.ResourceName); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task GetConversionActionAsync() { moq::Mock<ConversionActionService.ConversionActionServiceClient> mockGrpcClient = new moq::Mock<ConversionActionService.ConversionActionServiceClient>(moq::MockBehavior.Strict); GetConversionActionRequest request = new GetConversionActionRequest { ResourceNameAsConversionActionName = gagvr::ConversionActionName.FromCustomerConversionAction("[CUSTOMER_ID]", "[CONVERSION_ACTION_ID]"), }; gagvr::ConversionAction expectedResponse = new gagvr::ConversionAction { ResourceNameAsConversionActionName = gagvr::ConversionActionName.FromCustomerConversionAction("[CUSTOMER_ID]", "[CONVERSION_ACTION_ID]"), Status = gagve::ConversionActionStatusEnum.Types.ConversionActionStatus.Hidden, Type = gagve::ConversionActionTypeEnum.Types.ConversionActionType.Salesforce, Category = gagve::ConversionActionCategoryEnum.Types.ConversionActionCategory.AddToCart, ValueSettings = new gagvr::ConversionAction.Types.ValueSettings(), CountingType = gagve::ConversionActionCountingTypeEnum.Types.ConversionActionCountingType.Unspecified, AttributionModelSettings = new gagvr::ConversionAction.Types.AttributionModelSettings(), TagSnippets = { new gagvc::TagSnippet(), }, MobileAppVendor = gagve::MobileAppVendorEnum.Types.MobileAppVendor.GoogleAppStore, FirebaseSettings = new gagvr::ConversionAction.Types.FirebaseSettings(), ThirdPartyAppAnalyticsSettings = new gagvr::ConversionAction.Types.ThirdPartyAppAnalyticsSettings(), Id = -6774108720365892680L, ConversionActionName = gagvr::ConversionActionName.FromCustomerConversionAction("[CUSTOMER_ID]", "[CONVERSION_ACTION_ID]"), OwnerCustomerAsCustomerName = gagvr::CustomerName.FromCustomer("[CUSTOMER_ID]"), IncludeInConversionsMetric = false, ClickThroughLookbackWindowDays = -4831593457096707011L, ViewThroughLookbackWindowDays = -8283075401830951626L, PhoneCallDurationSeconds = -8070508326407639729L, AppId = "app_idfead82f3", }; mockGrpcClient.Setup(x => x.GetConversionActionAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::ConversionAction>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ConversionActionServiceClient client = new ConversionActionServiceClientImpl(mockGrpcClient.Object, null); gagvr::ConversionAction responseCallSettings = await client.GetConversionActionAsync(request.ResourceName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); gagvr::ConversionAction responseCancellationToken = await client.GetConversionActionAsync(request.ResourceName, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void GetConversionActionResourceNames() { moq::Mock<ConversionActionService.ConversionActionServiceClient> mockGrpcClient = new moq::Mock<ConversionActionService.ConversionActionServiceClient>(moq::MockBehavior.Strict); GetConversionActionRequest request = new GetConversionActionRequest { ResourceNameAsConversionActionName = gagvr::ConversionActionName.FromCustomerConversionAction("[CUSTOMER_ID]", "[CONVERSION_ACTION_ID]"), }; gagvr::ConversionAction expectedResponse = new gagvr::ConversionAction { ResourceNameAsConversionActionName = gagvr::ConversionActionName.FromCustomerConversionAction("[CUSTOMER_ID]", "[CONVERSION_ACTION_ID]"), Status = gagve::ConversionActionStatusEnum.Types.ConversionActionStatus.Hidden, Type = gagve::ConversionActionTypeEnum.Types.ConversionActionType.Salesforce, Category = gagve::ConversionActionCategoryEnum.Types.ConversionActionCategory.AddToCart, ValueSettings = new gagvr::ConversionAction.Types.ValueSettings(), CountingType = gagve::ConversionActionCountingTypeEnum.Types.ConversionActionCountingType.Unspecified, AttributionModelSettings = new gagvr::ConversionAction.Types.AttributionModelSettings(), TagSnippets = { new gagvc::TagSnippet(), }, MobileAppVendor = gagve::MobileAppVendorEnum.Types.MobileAppVendor.GoogleAppStore, FirebaseSettings = new gagvr::ConversionAction.Types.FirebaseSettings(), ThirdPartyAppAnalyticsSettings = new gagvr::ConversionAction.Types.ThirdPartyAppAnalyticsSettings(), Id = -6774108720365892680L, ConversionActionName = gagvr::ConversionActionName.FromCustomerConversionAction("[CUSTOMER_ID]", "[CONVERSION_ACTION_ID]"), OwnerCustomerAsCustomerName = gagvr::CustomerName.FromCustomer("[CUSTOMER_ID]"), IncludeInConversionsMetric = false, ClickThroughLookbackWindowDays = -4831593457096707011L, ViewThroughLookbackWindowDays = -8283075401830951626L, PhoneCallDurationSeconds = -8070508326407639729L, AppId = "app_idfead82f3", }; mockGrpcClient.Setup(x => x.GetConversionAction(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ConversionActionServiceClient client = new ConversionActionServiceClientImpl(mockGrpcClient.Object, null); gagvr::ConversionAction response = client.GetConversionAction(request.ResourceNameAsConversionActionName); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task GetConversionActionResourceNamesAsync() { moq::Mock<ConversionActionService.ConversionActionServiceClient> mockGrpcClient = new moq::Mock<ConversionActionService.ConversionActionServiceClient>(moq::MockBehavior.Strict); GetConversionActionRequest request = new GetConversionActionRequest { ResourceNameAsConversionActionName = gagvr::ConversionActionName.FromCustomerConversionAction("[CUSTOMER_ID]", "[CONVERSION_ACTION_ID]"), }; gagvr::ConversionAction expectedResponse = new gagvr::ConversionAction { ResourceNameAsConversionActionName = gagvr::ConversionActionName.FromCustomerConversionAction("[CUSTOMER_ID]", "[CONVERSION_ACTION_ID]"), Status = gagve::ConversionActionStatusEnum.Types.ConversionActionStatus.Hidden, Type = gagve::ConversionActionTypeEnum.Types.ConversionActionType.Salesforce, Category = gagve::ConversionActionCategoryEnum.Types.ConversionActionCategory.AddToCart, ValueSettings = new gagvr::ConversionAction.Types.ValueSettings(), CountingType = gagve::ConversionActionCountingTypeEnum.Types.ConversionActionCountingType.Unspecified, AttributionModelSettings = new gagvr::ConversionAction.Types.AttributionModelSettings(), TagSnippets = { new gagvc::TagSnippet(), }, MobileAppVendor = gagve::MobileAppVendorEnum.Types.MobileAppVendor.GoogleAppStore, FirebaseSettings = new gagvr::ConversionAction.Types.FirebaseSettings(), ThirdPartyAppAnalyticsSettings = new gagvr::ConversionAction.Types.ThirdPartyAppAnalyticsSettings(), Id = -6774108720365892680L, ConversionActionName = gagvr::ConversionActionName.FromCustomerConversionAction("[CUSTOMER_ID]", "[CONVERSION_ACTION_ID]"), OwnerCustomerAsCustomerName = gagvr::CustomerName.FromCustomer("[CUSTOMER_ID]"), IncludeInConversionsMetric = false, ClickThroughLookbackWindowDays = -4831593457096707011L, ViewThroughLookbackWindowDays = -8283075401830951626L, PhoneCallDurationSeconds = -8070508326407639729L, AppId = "app_idfead82f3", }; mockGrpcClient.Setup(x => x.GetConversionActionAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::ConversionAction>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ConversionActionServiceClient client = new ConversionActionServiceClientImpl(mockGrpcClient.Object, null); gagvr::ConversionAction responseCallSettings = await client.GetConversionActionAsync(request.ResourceNameAsConversionActionName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); gagvr::ConversionAction responseCancellationToken = await client.GetConversionActionAsync(request.ResourceNameAsConversionActionName, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void MutateConversionActionsRequestObject() { moq::Mock<ConversionActionService.ConversionActionServiceClient> mockGrpcClient = new moq::Mock<ConversionActionService.ConversionActionServiceClient>(moq::MockBehavior.Strict); MutateConversionActionsRequest request = new MutateConversionActionsRequest { CustomerId = "customer_id3b3724cb", Operations = { new ConversionActionOperation(), }, PartialFailure = false, ValidateOnly = true, ResponseContentType = gagve::ResponseContentTypeEnum.Types.ResponseContentType.ResourceNameOnly, }; MutateConversionActionsResponse expectedResponse = new MutateConversionActionsResponse { Results = { new MutateConversionActionResult(), }, PartialFailureError = new gr::Status(), }; mockGrpcClient.Setup(x => x.MutateConversionActions(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ConversionActionServiceClient client = new ConversionActionServiceClientImpl(mockGrpcClient.Object, null); MutateConversionActionsResponse response = client.MutateConversionActions(request); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task MutateConversionActionsRequestObjectAsync() { moq::Mock<ConversionActionService.ConversionActionServiceClient> mockGrpcClient = new moq::Mock<ConversionActionService.ConversionActionServiceClient>(moq::MockBehavior.Strict); MutateConversionActionsRequest request = new MutateConversionActionsRequest { CustomerId = "customer_id3b3724cb", Operations = { new ConversionActionOperation(), }, PartialFailure = false, ValidateOnly = true, ResponseContentType = gagve::ResponseContentTypeEnum.Types.ResponseContentType.ResourceNameOnly, }; MutateConversionActionsResponse expectedResponse = new MutateConversionActionsResponse { Results = { new MutateConversionActionResult(), }, PartialFailureError = new gr::Status(), }; mockGrpcClient.Setup(x => x.MutateConversionActionsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MutateConversionActionsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ConversionActionServiceClient client = new ConversionActionServiceClientImpl(mockGrpcClient.Object, null); MutateConversionActionsResponse responseCallSettings = await client.MutateConversionActionsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); MutateConversionActionsResponse responseCancellationToken = await client.MutateConversionActionsAsync(request, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void MutateConversionActions() { moq::Mock<ConversionActionService.ConversionActionServiceClient> mockGrpcClient = new moq::Mock<ConversionActionService.ConversionActionServiceClient>(moq::MockBehavior.Strict); MutateConversionActionsRequest request = new MutateConversionActionsRequest { CustomerId = "customer_id3b3724cb", Operations = { new ConversionActionOperation(), }, }; MutateConversionActionsResponse expectedResponse = new MutateConversionActionsResponse { Results = { new MutateConversionActionResult(), }, PartialFailureError = new gr::Status(), }; mockGrpcClient.Setup(x => x.MutateConversionActions(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ConversionActionServiceClient client = new ConversionActionServiceClientImpl(mockGrpcClient.Object, null); MutateConversionActionsResponse response = client.MutateConversionActions(request.CustomerId, request.Operations); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task MutateConversionActionsAsync() { moq::Mock<ConversionActionService.ConversionActionServiceClient> mockGrpcClient = new moq::Mock<ConversionActionService.ConversionActionServiceClient>(moq::MockBehavior.Strict); MutateConversionActionsRequest request = new MutateConversionActionsRequest { CustomerId = "customer_id3b3724cb", Operations = { new ConversionActionOperation(), }, }; MutateConversionActionsResponse expectedResponse = new MutateConversionActionsResponse { Results = { new MutateConversionActionResult(), }, PartialFailureError = new gr::Status(), }; mockGrpcClient.Setup(x => x.MutateConversionActionsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MutateConversionActionsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ConversionActionServiceClient client = new ConversionActionServiceClientImpl(mockGrpcClient.Object, null); MutateConversionActionsResponse responseCallSettings = await client.MutateConversionActionsAsync(request.CustomerId, request.Operations, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); MutateConversionActionsResponse responseCancellationToken = await client.MutateConversionActionsAsync(request.CustomerId, request.Operations, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } } }
// Copyright (c) ZeroC, Inc. All rights reserved. using EnvDTE; using Microsoft.VisualStudio; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using System; using System.Collections.Generic; using System.Linq; namespace IceBuilder { public class RunningDocumentTableEventHandler : IVsRunningDocTableEvents2 { public RunningDocumentTableEventHandler(IVsRunningDocumentTable runningDocumentTable) => RunningDocumentTable = runningDocumentTable; public void BeginTrack() { ThreadHelper.JoinableTaskFactory.Run(async () => { await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); RunningDocumentTable.AdviseRunningDocTableEvents(this, out _cookie); }); } public void EndTrack() => ThreadHelper.JoinableTaskFactory.Run(async () => { await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); RunningDocumentTable.UnadviseRunningDocTableEvents(_cookie); }); public int OnAfterAttributeChange(uint docCookie, uint grfAttribs) => 0; public int OnAfterAttributeChangeEx( uint docCookie, uint grfAttribs, IVsHierarchy pHierOld, uint itemidOld, string pszMkDocumentOld, IVsHierarchy pHierNew, uint itemidNew, string pszMkDocumentNew) => 0; public int OnAfterDocumentWindowHide(uint docCookie, IVsWindowFrame pFrame) => 0; public int OnAfterFirstDocumentLock( uint docCookie, uint dwRDTLockType, uint dwReadLocksRemaining, uint dwEditLocksRemaining) => 0; public int OnAfterSave(uint docCookie) { ThreadHelper.JoinableTaskFactory.Run(async () => { await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); try { if (Package.Instance.AutoBuilding) { IVsProject project = null; uint item = 0; string path = null; GetDocumentInfo(docCookie, ref project, ref item, ref path); if (ProjectUtil.IsSliceFileName(path) && project.IsMSBuildIceBuilderInstalled()) { Package.Instance.QueueProjectsForBuilding(new List<IVsProject>(new IVsProject[] { project })); } } } catch (Exception ex) { Package.UnexpectedExceptionWarning(ex); } }); return 0; } public int OnBeforeDocumentWindowShow(uint docCookie, int fFirstShow, IVsWindowFrame pFrame) { ThreadHelper.JoinableTaskFactory.Run(async () => { await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); try { if (fFirstShow != 0) { IVsProject project = null; uint itemref = 0; string path = null; GetDocumentInfo(docCookie, ref project, ref itemref, ref path); if (project != null && !string.IsNullOrEmpty(path) && (path.EndsWith(".cs", StringComparison.CurrentCultureIgnoreCase) || path.EndsWith(".cpp", StringComparison.CurrentCultureIgnoreCase) || path.EndsWith(".h", StringComparison.CurrentCultureIgnoreCase))) { if (project.IsIceBuilderGeneratedItem(path)) { ProjectItem item = project.GetProjectItem(itemref); if (item != null) { item.Document.ReadOnly = true; } } } } } catch (Exception) { // Could happen with some document types } }); return 0; } public int OnBeforeLastDocumentUnlock( uint docCookie, uint dwRDTLockType, uint dwReadLocksRemaining, uint dwEditLocksRemaining) => 0; private void GetDocumentInfo(uint cookie, ref IVsProject project, ref uint item, ref string path) { string pbstrMkDocument = ""; IVsProject pProject = null; uint pitemid = 0; ThreadHelper.JoinableTaskFactory.Run(async () => { await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); ErrorHandler.ThrowOnFailure(RunningDocumentTable.GetDocumentInfo( cookie, out uint pgrfRDTFlags, out uint pdwReadLocks, out uint pdwEditLocks, out pbstrMkDocument, out IVsHierarchy ppHier, out pitemid, out IntPtr ppunkDocData)); pProject = ppHier as IVsProject; }); project = pProject; path = pbstrMkDocument; item = pitemid; } IVsRunningDocumentTable RunningDocumentTable { get; set; } private uint _cookie; } public class DocumentEventHandler : IVsTrackProjectDocumentsEvents2 { public DocumentEventHandler(IVsTrackProjectDocuments2 trackProjectDocuments2) => TrackProjectDocuments2 = trackProjectDocuments2; public void BeginTrack() => ThreadHelper.JoinableTaskFactory.Run(async () => { await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); TrackProjectDocuments2.AdviseTrackProjectDocumentsEvents(this, out _cookie); }); public void EndTrack() => ThreadHelper.JoinableTaskFactory.Run(async () => { await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); TrackProjectDocuments2.UnadviseTrackProjectDocumentsEvents(_cookie); }); public int OnAfterAddDirectoriesEx( int cProjects, int cDirectories, IVsProject[] rgpProjects, int[] rgFirstIndices, string[] rgpszMkDocuments, VSADDDIRECTORYFLAGS[] rgFlags) => 0; public int OnAfterAddFilesEx( int projectsLength, int filesLength, IVsProject[] projects, int[] indices, string[] names, VSADDFILEFLAGS[] rgFlags) { ThreadHelper.JoinableTaskFactory.Run(async () => { await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); try { for (int i = 0; i < projectsLength; ++i) { IVsProject project = projects[i]; if (project.IsMSBuildIceBuilderInstalled()) { int j = indices[i]; int k = i < (projectsLength - 1) ? indices[i + 1] : filesLength; for (; j < k; ++j) { string path = names[i]; if (ProjectUtil.IsSliceFileName(path)) { // Ensure the .ice file item has SliceCompile ItemType var projectItem = project.GetProjectItem(path); if (projectItem != null) { var property = projectItem.Properties.Item("ItemType"); if (property != null && !property.Value.Equals("SliceCompile")) { project.EnsureIsCheckout(); property.Value = "SliceCompile"; ProjectUtil.AddGeneratedFiles(project, path); } } break; } } } } } catch (OperationCanceledException) { // Ignore, this could happen if the project is reloaded } catch (Exception ex) { Package.UnexpectedExceptionWarning(ex); } }); return 0; } public int OnAfterRemoveDirectories( int cProjects, int cDirectories, IVsProject[] rgpProjects, int[] rgFirstIndices, string[] rgpszMkDocuments, VSREMOVEDIRECTORYFLAGS[] rgFlags) => 0; public int OnAfterRemoveFiles( int projectsLength, int filesLength, IVsProject[] projects, int[] indices, string[] names, VSREMOVEFILEFLAGS[] rgFlags) { ThreadHelper.JoinableTaskFactory.Run(async () => { await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); try { for (int i = 0; i < projectsLength; ++i) { IVsProject project = projects[i]; if (project.IsMSBuildIceBuilderInstalled()) { int j = indices[i]; int k = i < (projectsLength - 1) ? indices[i + 1] : filesLength; for (; j < k; ++j) { string path = names[i]; if (ProjectUtil.IsSliceFileName(path)) { ProjectUtil.SetupGenerated(project); break; } } } } } catch (Exception ex) { Package.UnexpectedExceptionWarning(ex); } }); return 0; } public int OnAfterRenameDirectories( int cProjects, int cDirs, IVsProject[] rgpProjects, int[] rgFirstIndices, string[] rgszMkOldNames, string[] rgszMkNewNames, VSRENAMEDIRECTORYFLAGS[] rgFlags) => 0; public int OnAfterRenameFiles( int projectsLength, int filesLength, IVsProject[] projects, int[] indices, string[] oldNames, string[] newNames, VSRENAMEFILEFLAGS[] rgFlags) { ThreadHelper.JoinableTaskFactory.Run(async () => { await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); try { for (int i = 0; i < projectsLength; ++i) { IVsProject project = projects[i]; if (project.IsMSBuildIceBuilderInstalled()) { int j = indices[i]; int k = i < (projectsLength - 1) ? indices[i + 1] : filesLength; for (; j < k; ++j) { string oldPath = oldNames[i]; string newPath = newNames[j]; if (ProjectUtil.IsSliceFileName(oldPath) || ProjectUtil.IsSliceFileName(newPath)) { ProjectUtil.SetupGenerated(project); } } } } } catch (Exception ex) { Package.UnexpectedExceptionWarning(ex); } }); return 0; } public int OnAfterSccStatusChanged( int cProjects, int cFiles, IVsProject[] rgpProjects, int[] rgFirstIndices, string[] rgpszMkDocuments, uint[] rgdwSccStatus) => 0; public int OnQueryAddDirectories( IVsProject pProject, int cDirectories, string[] rgpszMkDocuments, VSQUERYADDDIRECTORYFLAGS[] rgFlags, VSQUERYADDDIRECTORYRESULTS[] pSummaryResult, VSQUERYADDDIRECTORYRESULTS[] rgResults) => 0; public int OnQueryAddFiles( IVsProject project, int length, string[] files, VSQUERYADDFILEFLAGS[] rgFlags, VSQUERYADDFILERESULTS[] pSummaryResult, VSQUERYADDFILERESULTS[] rgResults) { ThreadHelper.JoinableTaskFactory.Run(async () => { await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); try { if (files.Any(f => ProjectUtil.IsSliceFileName(f))) { if (project.IsMSBuildIceBuilderInstalled() && project.GetEvaluatedProperty("EnableDefaultItems").Equals( "false", StringComparison.InvariantCultureIgnoreCase)) { for (int i = 0; i < length; ++i) { if (ProjectUtil.IsSliceFileName(files[i])) { if (!ProjectUtil.CheckGenerateFileIsValid(project, files[i])) { if (rgResults != null) { rgResults[i] = VSQUERYADDFILERESULTS.VSQUERYADDFILERESULTS_AddNotOK; } pSummaryResult[0] = VSQUERYADDFILERESULTS.VSQUERYADDFILERESULTS_AddNotOK; } } } } } } catch (Exception ex) { Package.UnexpectedExceptionWarning(ex); } }); return 0; } public int OnQueryRemoveDirectories( IVsProject pProject, int cDirectories, string[] rgpszMkDocuments, VSQUERYREMOVEDIRECTORYFLAGS[] rgFlags, VSQUERYREMOVEDIRECTORYRESULTS[] pSummaryResult, VSQUERYREMOVEDIRECTORYRESULTS[] rgResults) => 0; public int OnQueryRemoveFiles( IVsProject pProject, int cFiles, string[] rgpszMkDocuments, VSQUERYREMOVEFILEFLAGS[] rgFlags, VSQUERYREMOVEFILERESULTS[] pSummaryResult, VSQUERYREMOVEFILERESULTS[] rgResults) => 0; public int OnQueryRenameDirectories( IVsProject pProject, int cDirs, string[] rgszMkOldNames, string[] rgszMkNewNames, VSQUERYRENAMEDIRECTORYFLAGS[] rgFlags, VSQUERYRENAMEDIRECTORYRESULTS[] pSummaryResult, VSQUERYRENAMEDIRECTORYRESULTS[] rgResults) => 0; public int OnQueryRenameFiles( IVsProject project, int filesLength, string[] oldNames, string[] newNames, VSQUERYRENAMEFILEFLAGS[] rgFlags, VSQUERYRENAMEFILERESULTS[] pSummaryResult, VSQUERYRENAMEFILERESULTS[] rgResults) { ThreadHelper.JoinableTaskFactory.Run(async () => { await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); try { if (project.IsMSBuildIceBuilderInstalled()) { for (int i = 0; i < filesLength; ++i) { if (ProjectUtil.IsSliceFileName(newNames[i])) { if (!ProjectUtil.CheckGenerateFileIsValid(project, newNames[i])) { if (rgResults != null) { rgResults[i] = VSQUERYRENAMEFILERESULTS.VSQUERYRENAMEFILERESULTS_RenameNotOK; } pSummaryResult[0] = VSQUERYRENAMEFILERESULTS.VSQUERYRENAMEFILERESULTS_RenameNotOK; } } } } } catch (Exception ex) { Package.UnexpectedExceptionWarning(ex); } }); return 0; } IVsTrackProjectDocuments2 TrackProjectDocuments2 { get; set; } private uint _cookie = 0; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Globalization; using System.Text; using Xunit; namespace System.Tests { public partial class CharTests { [Theory] [InlineData('h', 'h', 0)] [InlineData('h', 'a', 1)] [InlineData('h', 'z', -1)] [InlineData('h', null, 1)] public void CompareTo_Other_ReturnsExpected(char c, object value, int expected) { if (value is char charValue) { Assert.Equal(expected, Math.Sign(c.CompareTo(charValue))); } Assert.Equal(expected, Math.Sign(c.CompareTo(value))); } [Theory] [InlineData("a")] [InlineData(234)] public void CompareTo_ObjectNotDouble_ThrowsArgumentException(object value) { AssertExtensions.Throws<ArgumentException>(null, () => ((char)123).CompareTo(value)); } public static IEnumerable<object[]> ConvertFromUtf32_TestData() { yield return new object[] { 0x10000, "\uD800\uDC00" }; yield return new object[] { 0x103FF, "\uD800\uDFFF" }; yield return new object[] { 0xFFFFF, "\uDBBF\uDFFF" }; yield return new object[] { 0x10FC00, "\uDBFF\uDC00" }; yield return new object[] { 0x10FFFF, "\uDBFF\uDFFF" }; yield return new object[] { 0, "\0" }; yield return new object[] { 0x3FF, "\u03FF" }; yield return new object[] { 0xE000, "\uE000" }; yield return new object[] { 0xFFFF, "\uFFFF" }; } [Theory] [MemberData(nameof(ConvertFromUtf32_TestData))] public static void ConvertFromUtf32(int utf32, string expected) { Assert.Equal(expected, char.ConvertFromUtf32(utf32)); } [Theory] [InlineData(0xD800)] [InlineData(0xDC00)] [InlineData(0xDFFF)] [InlineData(0x110000)] [InlineData(-1)] [InlineData(int.MaxValue)] [InlineData(int.MinValue)] public static void ConvertFromUtf32_InvalidUtf32_ThrowsArgumentOutOfRangeException(int utf32) { AssertExtensions.Throws<ArgumentOutOfRangeException>("utf32", () => char.ConvertFromUtf32(utf32)); } public static IEnumerable<object[]> ConvertToUtf32_String_Int_TestData() { yield return new object[] { "\uD800\uDC00", 0, 0x10000 }; yield return new object[] { "\uDBBF\uDFFF", 0, 0xFFFFF }; yield return new object[] { "\uDBFF\uDC00", 0, 0x10FC00 }; yield return new object[] { "\uDBFF\uDFFF", 0, 0x10FFFF }; yield return new object[] { "\u0000\u0001", 0, 0 }; yield return new object[] { "\u0000\u0001", 1, 1 }; yield return new object[] { "\u0000", 0, 0 }; yield return new object[] { "\u0020\uD7FF", 0, 32 }; yield return new object[] { "\u0020\uD7FF", 1, 0xD7FF }; yield return new object[] { "abcde", 4, 'e' }; // Invalid unicode yield return new object[] { "\uD800\uD800\uDFFF", 1, 0x103FF }; yield return new object[] { "\uD800\uD7FF", 1, 0xD7FF }; // High, non-surrogate yield return new object[] { "\uD800\u0000", 1, 0 }; // High, non-surrogate yield return new object[] { "\uDF01\u0000", 1, 0 }; // Low, non-surrogate } [Theory] [MemberData(nameof(ConvertToUtf32_String_Int_TestData))] public static void ConvertToUtf32_String_Int(string s, int index, int expected) { Assert.Equal(expected, char.ConvertToUtf32(s, index)); } [Fact] public static void ConvertToUtf32_String_Int_Invalid() { AssertExtensions.Throws<ArgumentNullException>("s", () => char.ConvertToUtf32(null, 0)); // String is null AssertExtensions.Throws<ArgumentException>("s", () => char.ConvertToUtf32("\uD800\uD800", 0)); // High, high AssertExtensions.Throws<ArgumentException>("s", () => char.ConvertToUtf32("\uD800\uD800", 1)); // High, high AssertExtensions.Throws<ArgumentException>("s", () => char.ConvertToUtf32("\uD800\uD7FF", 0)); // High, non-surrogate AssertExtensions.Throws<ArgumentException>("s", () => char.ConvertToUtf32("\uD800\u0000", 0)); // High, non-surrogate AssertExtensions.Throws<ArgumentException>("s", () => char.ConvertToUtf32("\uDC01\uD940", 0)); // Low, high AssertExtensions.Throws<ArgumentException>("s", () => char.ConvertToUtf32("\uDC01\uD940", 1)); // Low, high AssertExtensions.Throws<ArgumentException>("s", () => char.ConvertToUtf32("\uDD00\uDE00", 0)); // Low, low AssertExtensions.Throws<ArgumentException>("s", () => char.ConvertToUtf32("\uDD00\uDE00", 1)); // Low, hig AssertExtensions.Throws<ArgumentException>("s", () => char.ConvertToUtf32("\uDF01\u0000", 0)); // Low, non-surrogateh AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.ConvertToUtf32("abcde", -1)); // Index < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.ConvertToUtf32("abcde", 5)); // Index >= string.Length AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.ConvertToUtf32("", 0)); // Index >= string.Length } public static IEnumerable<object[]> ConvertToUtf32_Char_Char_TestData() { yield return new object[] { '\uD800', '\uDC00', 0x10000 }; yield return new object[] { '\uD800', '\uDFFF', 0x103FF }; yield return new object[] { '\uDBBF', '\uDFFF', 0xFFFFF }; yield return new object[] { '\uDBFF', '\uDC00', 0x10FC00 }; yield return new object[] { '\uDBFF', '\uDFFF', 0x10FFFF }; } [Theory] [MemberData(nameof(ConvertToUtf32_Char_Char_TestData))] public static void ConvertToUtf32_Char_Char(char highSurrogate, char lowSurrogate, int expected) { Assert.Equal(expected, char.ConvertToUtf32(highSurrogate, lowSurrogate)); } [Fact] public static void ConvertToUtf32_Char_Char_Invalid() { AssertExtensions.Throws<ArgumentOutOfRangeException>("lowSurrogate", () => char.ConvertToUtf32('\uD800', '\uD800')); // High, high AssertExtensions.Throws<ArgumentOutOfRangeException>("lowSurrogate", () => char.ConvertToUtf32('\uD800', '\uD7FF')); // High, non-surrogate AssertExtensions.Throws<ArgumentOutOfRangeException>("lowSurrogate", () => char.ConvertToUtf32('\uD800', '\u0000')); // High, non-surrogate AssertExtensions.Throws<ArgumentOutOfRangeException>("highSurrogate", () => char.ConvertToUtf32('\uDD00', '\uDE00')); // Low, low AssertExtensions.Throws<ArgumentOutOfRangeException>("highSurrogate", () => char.ConvertToUtf32('\uDC01', '\uD940')); // Low, high AssertExtensions.Throws<ArgumentOutOfRangeException>("highSurrogate", () => char.ConvertToUtf32('\uDF01', '\u0000')); // Low, non-surrogate AssertExtensions.Throws<ArgumentOutOfRangeException>("highSurrogate", () => char.ConvertToUtf32('\u0032', '\uD7FF')); // Non-surrogate, non-surrogate AssertExtensions.Throws<ArgumentOutOfRangeException>("highSurrogate", () => char.ConvertToUtf32('\u0000', '\u0000')); // Non-surrogate, non-surrogate } [Theory] [InlineData('a', 'a', true)] [InlineData('a', 'A', false)] [InlineData('a', 'b', false)] [InlineData('a', (int)'a', false)] [InlineData('a', "a", false)] [InlineData('a', null, false)] public static void Equals(char c, object obj, bool expected) { if (obj is char) { Assert.Equal(expected, c.Equals((char)obj)); Assert.Equal(expected, c.GetHashCode().Equals(obj.GetHashCode())); } Assert.Equal(expected, c.Equals(obj)); } [Theory] [InlineData('0', 0)] [InlineData('9', 9)] [InlineData('T', -1)] public static void GetNumericValue_Char(char c, int expected) { Assert.Equal(expected, char.GetNumericValue(c)); } [Theory] [InlineData("\uD800\uDD07", 0, 1)] [InlineData("9", 0, 9)] [InlineData("99", 1, 9)] [InlineData(" 7 ", 1, 7)] [InlineData("Test 7", 5, 7)] [InlineData("T", 0, -1)] public static void GetNumericValue_String_Int(string s, int index, int expected) { Assert.Equal(expected, char.GetNumericValue(s, index)); } [Fact] public static void GetNumericValue_String_Int_Invalid() { AssertExtensions.Throws<ArgumentNullException>("s", () => char.GetNumericValue(null, 0)); // String is null AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.GetNumericValue("abc", -1)); // Index < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.GetNumericValue("abc", 3)); // Index >= string.Length } [Fact] public void GetTypeCode_Invoke_ReturnsBoolean() { Assert.Equal(TypeCode.Char, 'a'.GetTypeCode()); } [Fact] public static void IsControl_Char() { foreach (char c in GetTestChars(UnicodeCategory.Control)) Assert.True(char.IsControl(c)); foreach (char c in GetTestCharsNotInCategory(UnicodeCategory.Control)) Assert.False(char.IsControl(c)); } [Fact] public static void IsControl_String_Int() { foreach (char c in GetTestChars(UnicodeCategory.Control)) Assert.True(char.IsControl(c.ToString(), 0)); foreach (char c in GetTestCharsNotInCategory(UnicodeCategory.Control)) Assert.False(char.IsControl(c.ToString(), 0)); } [Fact] public static void IsControl_String_Int_Invalid() { AssertExtensions.Throws<ArgumentNullException>("s", () => char.IsControl(null, 0)); // String is null AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsControl("abc", -1)); // Index < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsControl("abc", 3)); // Index >= string.Length } [Fact] public static void IsDigit_Char() { foreach (char c in GetTestChars(UnicodeCategory.DecimalDigitNumber)) Assert.True(char.IsDigit(c)); foreach (char c in GetTestCharsNotInCategory(UnicodeCategory.DecimalDigitNumber)) Assert.False(char.IsDigit(c)); } [Fact] public static void IsDigit_String_Int() { foreach (char c in GetTestChars(UnicodeCategory.DecimalDigitNumber)) Assert.True(char.IsDigit(c.ToString(), 0)); foreach (char c in GetTestCharsNotInCategory(UnicodeCategory.DecimalDigitNumber)) Assert.False(char.IsDigit(c.ToString(), 0)); } [Fact] public static void IsDigit_String_Int_Invalid() { AssertExtensions.Throws<ArgumentNullException>("s", () => char.IsDigit(null, 0)); // String is null AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsDigit("abc", -1)); // Index < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsDigit("abc", 3)); // Index >= string.Length } [Fact] public static void IsLetter_Char() { var categories = new UnicodeCategory[] { UnicodeCategory.UppercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.TitlecaseLetter, UnicodeCategory.ModifierLetter, UnicodeCategory.OtherLetter }; foreach (char c in GetTestChars(categories)) Assert.True(char.IsLetter(c)); foreach (char c in GetTestCharsNotInCategory(categories)) Assert.False(char.IsLetter(c)); } [Fact] public static void IsLetter_String_Int() { var categories = new UnicodeCategory[] { UnicodeCategory.UppercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.TitlecaseLetter, UnicodeCategory.ModifierLetter, UnicodeCategory.OtherLetter }; foreach (char c in GetTestChars(categories)) Assert.True(char.IsLetter(c.ToString(), 0)); foreach (char c in GetTestCharsNotInCategory(categories)) Assert.False(char.IsLetter(c.ToString(), 0)); } [Fact] public static void IsLetter_String_Int_Invalid() { AssertExtensions.Throws<ArgumentNullException>("s", () => char.IsLetter(null, 0)); // String is null AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsLetter("abc", -1)); // Index < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsLetter("abc", 3)); // Index >= string.Length } [Fact] public static void IsLetterOrDigit_Char() { var categories = new UnicodeCategory[] { UnicodeCategory.UppercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.TitlecaseLetter, UnicodeCategory.ModifierLetter, UnicodeCategory.OtherLetter, UnicodeCategory.DecimalDigitNumber }; foreach (char c in GetTestChars(categories)) Assert.True(char.IsLetterOrDigit(c)); foreach (char c in GetTestCharsNotInCategory(categories)) Assert.False(char.IsLetterOrDigit(c)); } [Fact] public static void IsLetterOrDigit_String_Int() { var categories = new UnicodeCategory[] { UnicodeCategory.UppercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.TitlecaseLetter, UnicodeCategory.ModifierLetter, UnicodeCategory.OtherLetter, UnicodeCategory.DecimalDigitNumber }; foreach (char c in GetTestChars(categories)) Assert.True(char.IsLetterOrDigit(c.ToString(), 0)); foreach (char c in GetTestCharsNotInCategory(categories)) Assert.False(char.IsLetterOrDigit(c.ToString(), 0)); } [Fact] public static void IsLetterOrDigit_String_Int_Invalid() { AssertExtensions.Throws<ArgumentNullException>("s", () => char.IsLetterOrDigit(null, 0)); // String is null AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsLetterOrDigit("abc", -1)); // Index < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsLetterOrDigit("abc", 3)); // Index >= string.Length } [Fact] public static void IsLower_Char() { foreach (char c in GetTestChars(UnicodeCategory.LowercaseLetter)) Assert.True(char.IsLower(c)); foreach (char c in GetTestCharsNotInCategory(UnicodeCategory.LowercaseLetter)) Assert.False(char.IsLower(c)); } [Fact] public static void IsLower_String_Int() { foreach (char c in GetTestChars(UnicodeCategory.LowercaseLetter)) Assert.True(char.IsLower(c.ToString(), 0)); foreach (char c in GetTestCharsNotInCategory(UnicodeCategory.LowercaseLetter)) Assert.False(char.IsLower(c.ToString(), 0)); } [Fact] public static void IsLower_String_Int_Invalid() { AssertExtensions.Throws<ArgumentNullException>("s", () => char.IsLower(null, 0)); // String is null AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsLower("abc", -1)); // Index < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsLower("abc", 3)); // Index >= string.Length } [Fact] public static void IsNumber_Char() { var categories = new UnicodeCategory[] { UnicodeCategory.DecimalDigitNumber, UnicodeCategory.LetterNumber, UnicodeCategory.OtherNumber }; foreach (char c in GetTestChars(categories)) Assert.True(char.IsNumber(c)); foreach (char c in GetTestCharsNotInCategory(categories)) Assert.False(char.IsNumber(c)); } [Fact] public static void IsNumber_String_Int() { var categories = new UnicodeCategory[] { UnicodeCategory.DecimalDigitNumber, UnicodeCategory.LetterNumber, UnicodeCategory.OtherNumber }; foreach (char c in GetTestChars(categories)) Assert.True(char.IsNumber(c.ToString(), 0)); foreach (char c in GetTestCharsNotInCategory(categories)) Assert.False(char.IsNumber(c.ToString(), 0)); } [Fact] public static void IsNumber_String_Int_Invalid() { AssertExtensions.Throws<ArgumentNullException>("s", () => char.IsNumber(null, 0)); // String is null AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsNumber("abc", -1)); // Index < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsNumber("abc", 3)); // Index >= string.Length } [Fact] public static void IsPunctuation_Char() { var categories = new UnicodeCategory[] { UnicodeCategory.ConnectorPunctuation, UnicodeCategory.DashPunctuation, UnicodeCategory.OpenPunctuation, UnicodeCategory.ClosePunctuation, UnicodeCategory.InitialQuotePunctuation, UnicodeCategory.FinalQuotePunctuation, UnicodeCategory.OtherPunctuation }; foreach (char c in GetTestChars(categories)) Assert.True(char.IsPunctuation(c)); foreach (char c in GetTestCharsNotInCategory(categories)) Assert.False(char.IsPunctuation(c)); } [Fact] public static void IsPunctuation_String_Int() { var categories = new UnicodeCategory[] { UnicodeCategory.ConnectorPunctuation, UnicodeCategory.DashPunctuation, UnicodeCategory.OpenPunctuation, UnicodeCategory.ClosePunctuation, UnicodeCategory.InitialQuotePunctuation, UnicodeCategory.FinalQuotePunctuation, UnicodeCategory.OtherPunctuation }; foreach (char c in GetTestChars(categories)) Assert.True(char.IsPunctuation(c.ToString(), 0)); foreach (char c in GetTestCharsNotInCategory(categories)) Assert.False(char.IsPunctuation(c.ToString(), 0)); } [Fact] public static void IsPunctuation_String_Int_Invalid() { AssertExtensions.Throws<ArgumentNullException>("s", () => char.IsPunctuation(null, 0)); // String is null AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsPunctuation("abc", -1)); // Index < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsPunctuation("abc", 3)); // Index >= string.Length } [Fact] public static void IsSeparator_Char() { var categories = new UnicodeCategory[] { UnicodeCategory.SpaceSeparator, UnicodeCategory.LineSeparator, UnicodeCategory.ParagraphSeparator }; foreach (char c in GetTestChars(categories)) Assert.True(char.IsSeparator(c)); foreach (char c in GetTestCharsNotInCategory(categories)) Assert.False(char.IsSeparator(c)); } [Fact] public static void IsSeparator_String_Int() { var categories = new UnicodeCategory[] { UnicodeCategory.SpaceSeparator, UnicodeCategory.LineSeparator, UnicodeCategory.ParagraphSeparator }; foreach (char c in GetTestChars(categories)) Assert.True(char.IsSeparator(c.ToString(), 0)); foreach (char c in GetTestCharsNotInCategory(categories)) Assert.False(char.IsSeparator(c.ToString(), 0)); } [Fact] public static void IsSeparator_String_Int_Invalid() { AssertExtensions.Throws<ArgumentNullException>("s", () => char.IsSeparator(null, 0)); // String is null AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsSeparator("abc", -1)); // Index < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsSeparator("abc", 3)); // Index >= string.Length } [Fact] public static void IsLowSurrogate_Char() { foreach (char c in s_lowSurrogates) Assert.True(char.IsLowSurrogate(c)); foreach (char c in s_highSurrogates) Assert.False(char.IsLowSurrogate(c)); foreach (char c in s_nonSurrogates) Assert.False(char.IsLowSurrogate(c)); } [Fact] public static void IsLowSurrogate_String_Int() { foreach (char c in s_lowSurrogates) Assert.True(char.IsLowSurrogate(c.ToString(), 0)); foreach (char c in s_highSurrogates) Assert.False(char.IsLowSurrogate(c.ToString(), 0)); foreach (char c in s_nonSurrogates) Assert.False(char.IsLowSurrogate(c.ToString(), 0)); } [Fact] public static void IsLowSurrogate_String_Int_Invalid() { AssertExtensions.Throws<ArgumentNullException>("s", () => char.IsLowSurrogate(null, 0)); // String is null AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsLowSurrogate("abc", -1)); // Index < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsLowSurrogate("abc", 3)); // Index >= string.Length } [Fact] public static void IsHighSurrogate_Char() { foreach (char c in s_highSurrogates) Assert.True(char.IsHighSurrogate(c)); foreach (char c in s_lowSurrogates) Assert.False(char.IsHighSurrogate(c)); foreach (char c in s_nonSurrogates) Assert.False(char.IsHighSurrogate(c)); } [Fact] public static void IsHighSurrogate_String_Int() { foreach (char c in s_highSurrogates) Assert.True(char.IsHighSurrogate(c.ToString(), 0)); foreach (char c in s_lowSurrogates) Assert.False(char.IsHighSurrogate(c.ToString(), 0)); foreach (char c in s_nonSurrogates) Assert.False(char.IsHighSurrogate(c.ToString(), 0)); } [Fact] public static void IsHighSurrogate_String_Int_Invalid() { AssertExtensions.Throws<ArgumentNullException>("s", () => char.IsHighSurrogate(null, 0)); // String is null AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsHighSurrogate("abc", -1)); // Index < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsHighSurrogate("abc", 3)); // Index >= string.Length } [Fact] public static void IsSurrogate_Char() { foreach (char c in s_highSurrogates) Assert.True(char.IsSurrogate(c)); foreach (char c in s_lowSurrogates) Assert.True(char.IsSurrogate(c)); foreach (char c in s_nonSurrogates) Assert.False(char.IsSurrogate(c)); } [Fact] public static void IsSurrogate_String_Int() { foreach (char c in s_highSurrogates) Assert.True(char.IsSurrogate(c.ToString(), 0)); foreach (char c in s_lowSurrogates) Assert.True(char.IsSurrogate(c.ToString(), 0)); foreach (char c in s_nonSurrogates) Assert.False(char.IsSurrogate(c.ToString(), 0)); } [Fact] public static void IsSurrogate_String_Int_Invalid() { AssertExtensions.Throws<ArgumentNullException>("s", () => char.IsSurrogate(null, 0)); // String is null AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsSurrogate("abc", -1)); // Index < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsSurrogate("abc", 3)); // Index >= string.Length } [Fact] public static void IsSurrogatePair_Char() { foreach (char hs in s_highSurrogates) foreach (char ls in s_lowSurrogates) Assert.True(char.IsSurrogatePair(hs, ls)); foreach (char hs in s_nonSurrogates) foreach (char ls in s_lowSurrogates) Assert.False(char.IsSurrogatePair(hs, ls)); foreach (char hs in s_highSurrogates) foreach (char ls in s_nonSurrogates) Assert.False(char.IsSurrogatePair(hs, ls)); } [Fact] public static void IsSurrogatePair_String_Int() { foreach (char hs in s_highSurrogates) foreach (char ls in s_lowSurrogates) Assert.True(char.IsSurrogatePair(hs.ToString() + ls, 0)); foreach (char hs in s_nonSurrogates) foreach (char ls in s_lowSurrogates) Assert.False(char.IsSurrogatePair(hs.ToString() + ls, 0)); foreach (char hs in s_highSurrogates) foreach (char ls in s_nonSurrogates) Assert.False(char.IsSurrogatePair(hs.ToString() + ls, 0)); Assert.False(char.IsSurrogatePair("\ud800\udc00", 1)); // Index + 1 >= s.Length } [Fact] public static void IsSurrogatePair_String_Int_Invalid() { AssertExtensions.Throws<ArgumentNullException>("s", () => char.IsSurrogatePair(null, 0)); // String is null AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsSurrogatePair("abc", -1)); // Index < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsSurrogatePair("abc", 3)); // Index >= string.Length } [Fact] public static void IsSymbol_Char() { var categories = new UnicodeCategory[] { UnicodeCategory.MathSymbol, UnicodeCategory.ModifierSymbol, UnicodeCategory.CurrencySymbol, UnicodeCategory.OtherSymbol }; foreach (char c in GetTestChars(categories)) Assert.True(char.IsSymbol(c)); foreach (char c in GetTestCharsNotInCategory(categories)) Assert.False(char.IsSymbol(c)); } [Fact] public static void IsSymbol_String_Int() { var categories = new UnicodeCategory[] { UnicodeCategory.MathSymbol, UnicodeCategory.ModifierSymbol, UnicodeCategory.CurrencySymbol, UnicodeCategory.OtherSymbol }; foreach (char c in GetTestChars(categories)) Assert.True(char.IsSymbol(c.ToString(), 0)); foreach (char c in GetTestCharsNotInCategory(categories)) Assert.False(char.IsSymbol(c.ToString(), 0)); } [Fact] public static void IsSymbol_String_Int_Invalid() { AssertExtensions.Throws<ArgumentNullException>("s", () => char.IsSymbol(null, 0)); // String is null AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsSymbol("abc", -1)); // Index < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsSymbol("abc", 3)); // Index >= string.Length } [Fact] public static void IsUpper_Char() { foreach (char c in GetTestChars(UnicodeCategory.UppercaseLetter)) Assert.True(char.IsUpper(c)); foreach (char c in GetTestCharsNotInCategory(UnicodeCategory.UppercaseLetter)) Assert.False(char.IsUpper(c)); } [Fact] public static void IsUpper_String_Int() { foreach (char c in GetTestChars(UnicodeCategory.UppercaseLetter)) Assert.True(char.IsUpper(c.ToString(), 0)); foreach (char c in GetTestCharsNotInCategory(UnicodeCategory.UppercaseLetter)) Assert.False(char.IsUpper(c.ToString(), 0)); } [Fact] public static void IsUpper_String_Int_Invalid() { AssertExtensions.Throws<ArgumentNullException>("s", () => char.IsUpper(null, 0)); // String is null AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsUpper("abc", -1)); // Index < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsUpper("abc", 3)); // Index >= string.Length } [Fact] public static void IsWhitespace_Char() { var categories = new UnicodeCategory[] { UnicodeCategory.SpaceSeparator, UnicodeCategory.LineSeparator, UnicodeCategory.ParagraphSeparator }; foreach (char c in GetTestChars(categories)) Assert.True(char.IsWhiteSpace(c)); foreach (char c in GetTestCharsNotInCategory(categories)) { // Need to special case some control chars that are treated as whitespace if ((c >= '\x0009' && c <= '\x000d') || c == '\x0085') continue; Assert.False(char.IsWhiteSpace(c)); } } [Fact] public static void IsWhiteSpace_String_Int() { var categories = new UnicodeCategory[] { UnicodeCategory.SpaceSeparator, UnicodeCategory.LineSeparator, UnicodeCategory.ParagraphSeparator }; foreach (char c in GetTestChars(categories)) Assert.True(char.IsWhiteSpace(c.ToString(), 0)); // Some control chars are also considered whitespace for legacy reasons. // if ((c >= '\x0009' && c <= '\x000d') || c == '\x0085') Assert.True(char.IsWhiteSpace("\u000b", 0)); Assert.True(char.IsWhiteSpace("\u0085", 0)); foreach (char c in GetTestCharsNotInCategory(categories)) { // Need to special case some control chars that are treated as whitespace if ((c >= '\x0009' && c <= '\x000d') || c == '\x0085') continue; Assert.False(char.IsWhiteSpace(c.ToString(), 0)); } } [Fact] public static void IsWhiteSpace_String_Int_Invalid() { AssertExtensions.Throws<ArgumentNullException>("s", () => char.IsWhiteSpace(null, 0)); // String is null AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsWhiteSpace("abc", -1)); // Index < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => char.IsWhiteSpace("abc", 3)); // Index >= string.Length } [Fact] public static void MaxValue() { Assert.Equal(0xffff, char.MaxValue); } [Fact] public static void MinValue() { Assert.Equal(0, char.MinValue); } [Fact] public static void ToLower() { Assert.Equal('a', char.ToLower('A')); Assert.Equal('a', char.ToLower('a')); foreach (char c in GetTestChars(UnicodeCategory.UppercaseLetter)) { char lc = char.ToLower(c); Assert.NotEqual(c, lc); Assert.True(char.IsLower(lc)); } // TitlecaseLetter can have a lower case form (e.g. \u01C8 'Lj' letter which will be 'lj') // LetterNumber can have a lower case form (e.g. \u2162 'III' letter which will be 'iii') foreach (char c in GetTestCharsNotInCategory(UnicodeCategory.UppercaseLetter, UnicodeCategory.TitlecaseLetter, UnicodeCategory.LetterNumber)) { Assert.Equal(c, char.ToLower(c)); } } [Fact] public static void ToLowerInvariant() { Assert.Equal('a', char.ToLowerInvariant('A')); Assert.Equal('a', char.ToLowerInvariant('a')); foreach (char c in GetTestChars(UnicodeCategory.UppercaseLetter)) { char lc = char.ToLowerInvariant(c); Assert.NotEqual(c, lc); Assert.True(char.IsLower(lc)); } // TitlecaseLetter can have a lower case form (e.g. \u01C8 'Lj' letter which will be 'lj') // LetterNumber can have a lower case form (e.g. \u2162 'III' letter which will be 'iii') foreach (char c in GetTestCharsNotInCategory(UnicodeCategory.UppercaseLetter, UnicodeCategory.TitlecaseLetter, UnicodeCategory.LetterNumber)) { Assert.Equal(c, char.ToLowerInvariant(c)); } } [Theory] [InlineData('a', "a")] [InlineData('\uabcd', "\uabcd")] public static void ToString(char c, string expected) { Assert.Equal(expected, c.ToString()); Assert.Equal(expected, char.ToString(c)); } [Fact] public static void ToUpper() { Assert.Equal('A', char.ToUpper('A')); Assert.Equal('A', char.ToUpper('a')); foreach (char c in GetTestChars(UnicodeCategory.LowercaseLetter)) { char lc = char.ToUpper(c); Assert.NotEqual(c, lc); Assert.True(char.IsUpper(lc)); } // TitlecaseLetter can have a uppercase form (e.g. \u01C8 'Lj' letter which will be 'LJ') // LetterNumber can have a uppercase form (e.g. \u2172 'iii' letter which will be 'III') foreach (char c in GetTestCharsNotInCategory(UnicodeCategory.LowercaseLetter, UnicodeCategory.TitlecaseLetter, UnicodeCategory.LetterNumber)) { Assert.Equal(c, char.ToUpper(c)); } } [Fact] public static void ToUpperInvariant() { Assert.Equal('A', char.ToUpperInvariant('A')); Assert.Equal('A', char.ToUpperInvariant('a')); foreach (char c in GetTestChars(UnicodeCategory.LowercaseLetter)) { char lc = char.ToUpperInvariant(c); Assert.NotEqual(c, lc); Assert.True(char.IsUpper(lc)); } // TitlecaseLetter can have a uppercase form (e.g. \u01C8 'Lj' letter which will be 'LJ') // LetterNumber can have a uppercase form (e.g. \u2172 'iii' letter which will be 'III') foreach (char c in GetTestCharsNotInCategory(UnicodeCategory.LowercaseLetter, UnicodeCategory.TitlecaseLetter, UnicodeCategory.LetterNumber)) { Assert.Equal(c, char.ToUpperInvariant(c)); } } public static IEnumerable<object[]> Parse_TestData() { yield return new object[] { "a", 'a' }; yield return new object[] { "4", '4' }; yield return new object[] { " ", ' ' }; yield return new object[] { "\n", '\n' }; yield return new object[] { "\0", '\0' }; yield return new object[] { "\u0135", '\u0135' }; yield return new object[] { "\u05d9", '\u05d9' }; yield return new object[] { "\ue001", '\ue001' }; // Private use codepoint // Lone surrogate yield return new object[] { "\ud801", '\ud801' }; // High surrogate yield return new object[] { "\udc01", '\udc01' }; // Low surrogate } [Theory] [MemberData(nameof(Parse_TestData))] public static void Parse(string s, char expected) { char c; Assert.True(char.TryParse(s, out c)); Assert.Equal(expected, c); Assert.Equal(expected, char.Parse(s)); } [Theory] [InlineData(null, typeof(ArgumentNullException))] [InlineData("", typeof(FormatException))] [InlineData("\n\r", typeof(FormatException))] [InlineData("kj", typeof(FormatException))] [InlineData(" a", typeof(FormatException))] [InlineData("a ", typeof(FormatException))] [InlineData("\\u0135", typeof(FormatException))] [InlineData("\u01356", typeof(FormatException))] [InlineData("\ud801\udc01", typeof(FormatException))] // Surrogate pair public static void Parse_Invalid(string s, Type exceptionType) { char c; Assert.False(char.TryParse(s, out c)); Assert.Equal(default(char), c); Assert.Throws(exceptionType, () => char.Parse(s)); } private static IEnumerable<char> GetTestCharsNotInCategory(params UnicodeCategory[] categories) { Assert.Equal(s_latinTestSet.Length, s_unicodeTestSet.Length); for (int i = 0; i < s_latinTestSet.Length; i++) { if (Array.Exists(categories, uc => uc == (UnicodeCategory)i)) continue; char[] latinSet = s_latinTestSet[i]; for (int j = 0; j < latinSet.Length; j++) yield return latinSet[j]; char[] unicodeSet = s_unicodeTestSet[i]; for (int k = 0; k < unicodeSet.Length; k++) yield return unicodeSet[k]; } } private static IEnumerable<char> GetTestChars(params UnicodeCategory[] categories) { for (int i = 0; i < categories.Length; i++) { char[] latinSet = s_latinTestSet[(int)categories[i]]; for (int j = 0; j < latinSet.Length; j++) yield return latinSet[j]; char[] unicodeSet = s_unicodeTestSet[(int)categories[i]]; for (int k = 0; k < unicodeSet.Length; k++) yield return unicodeSet[k]; } } private static char[][] s_latinTestSet = new char[][] { new char[] {'\u0047','\u004c','\u0051','\u0056','\u00c0','\u00c5','\u00ca','\u00cf','\u00d4','\u00da'}, // UnicodeCategory.UppercaseLetter new char[] {'\u0062','\u0068','\u006e','\u0074','\u007a','\u00e1','\u00e7','\u00ed','\u00f3','\u00fa'}, // UnicodeCategory.LowercaseLetter new char[] {}, // UnicodeCategory.TitlecaseLetter new char[] {}, // UnicodeCategory.ModifierLetter new char[] {}, // UnicodeCategory.OtherLetter new char[] {}, // UnicodeCategory.NonSpacingMark new char[] {}, // UnicodeCategory.SpacingCombiningMark new char[] {}, // UnicodeCategory.EnclosingMark new char[] {'\u0030','\u0031','\u0032','\u0033','\u0034','\u0035','\u0036','\u0037','\u0038','\u0039'}, // UnicodeCategory.DecimalDigitNumber new char[] {}, // UnicodeCategory.LetterNumber new char[] {'\u00b2','\u00b3','\u00b9','\u00bc','\u00bd','\u00be'}, // UnicodeCategory.OtherNumber new char[] {'\u0020','\u00a0'}, // UnicodeCategory.SpaceSeparator new char[] {}, // UnicodeCategory.LineSeparator new char[] {}, // UnicodeCategory.ParagraphSeparator new char[] {'\u0005','\u000b','\u0011','\u0017','\u001d','\u0082','\u0085','\u008e','\u0094','\u009a'}, // UnicodeCategory.Control new char[] {}, // UnicodeCategory.Format new char[] {}, // UnicodeCategory.Surrogate new char[] {}, // UnicodeCategory.PrivateUse new char[] {'\u005f'}, // UnicodeCategory.ConnectorPunctuation new char[] {'\u002d','\u00ad'}, // UnicodeCategory.DashPunctuation new char[] {'\u0028','\u005b','\u007b'}, // UnicodeCategory.OpenPunctuation new char[] {'\u0029','\u005d','\u007d'}, // UnicodeCategory.ClosePunctuation new char[] {'\u00ab'}, // UnicodeCategory.InitialQuotePunctuation new char[] {'\u00bb'}, // UnicodeCategory.FinalQuotePunctuation new char[] {'\u002e','\u002f','\u003a','\u003b','\u003f','\u0040','\u005c','\u00a1','\u00b7','\u00bf'}, // UnicodeCategory.OtherPunctuation new char[] {'\u002b','\u003c','\u003d','\u003e','\u007c','\u007e','\u00ac','\u00b1','\u00d7','\u00f7'}, // UnicodeCategory.MathSymbol new char[] {'\u0024','\u00a2','\u00a3','\u00a4','\u00a5'}, // UnicodeCategory.CurrencySymbol new char[] {'\u005e','\u0060','\u00a8','\u00af','\u00b4','\u00b8'}, // UnicodeCategory.ModifierSymbol new char[] {'\u00a6','\u00a7','\u00a9','\u00ae','\u00b0','\u00b6'}, // UnicodeCategory.OtherSymbol new char[] {}, // UnicodeCategory.OtherNotAssigned }; private static char[][] s_unicodeTestSet = new char[][] { new char[] {'\u0102','\u01ac','\u0392','\u0428','\u0508','\u10c4','\u1eb4','\u1fba','\u2c28','\ua668'}, // UnicodeCategory.UppercaseLetter new char[] { '\u0107', '\u012D', '\u0140', '\u0151', '\u013A', '\u01A1', '\u01F9', '\u022D', '\u1E09','\uFF45' }, // UnicodeCategory.LowercaseLetter new char[] {'\u01c8','\u1f88','\u1f8b','\u1f8e','\u1f99','\u1f9c','\u1f9f','\u1faa','\u1fad','\u1fbc'}, // UnicodeCategory.TitlecaseLetter new char[] {'\u02b7','\u02cd','\u07f4','\u1d2f','\u1d41','\u1d53','\u1d9d','\u1daf','\u2091','\u30fe'}, // UnicodeCategory.ModifierLetter new char[] {'\u01c0','\u37be','\u4970','\u5b6c','\u6d1e','\u7ed0','\u9082','\ua271','\ub985','\ucb37'}, // UnicodeCategory.OtherLetter new char[] {'\u0303','\u034e','\u05b5','\u0738','\u0a4d','\u0e49','\u0fad','\u180b','\u1dd5','\u2dfd'}, // UnicodeCategory.NonSpacingMark new char[] {'\u0982','\u0b03','\u0c41','\u0d40','\u0df3','\u1083','\u1925','\u1b44','\ua8b5' }, // UnicodeCategory.SpacingCombiningMark new char[] {'\u20dd','\u20de','\u20df','\u20e0','\u20e2','\u20e3','\u20e4','\ua670','\ua671','\ua672'}, // UnicodeCategory.EnclosingMark new char[] {'\u0660','\u0966','\u0ae6','\u0c66','\u0e50','\u1040','\u1810','\u1b50','\u1c50','\ua900'}, // UnicodeCategory.DecimalDigitNumber new char[] {'\u2162','\u2167','\u216c','\u2171','\u2176','\u217b','\u2180','\u2187','\u3023','\u3028'}, // UnicodeCategory.LetterNumber new char[] {'\u0c78','\u136b','\u17f7','\u2158','\u2471','\u248a','\u24f1','\u2780','\u3220','\u3280'}, // UnicodeCategory.OtherNumber new char[] {'\u2004','\u2005','\u2006','\u2007','\u2008','\u2009','\u200a','\u202f','\u205f','\u3000'}, // UnicodeCategory.SpaceSeparator new char[] {'\u2028'}, // UnicodeCategory.LineSeparator new char[] {'\u2029'}, // UnicodeCategory.ParagraphSeparator new char[] {}, // UnicodeCategory.Control new char[] {'\u0603','\u17b4','\u200c','\u200f','\u202c','\u2060','\u2063','\u206b','\u206e','\ufff9'}, // UnicodeCategory.Format new char[] {'\ud808','\ud8d4','\ud9a0','\uda6c','\udb38','\udc04','\udcd0','\udd9c','\ude68','\udf34'}, // UnicodeCategory.Surrogate new char[] {'\ue000','\ue280','\ue500','\ue780','\uea00','\uec80','\uef00','\uf180','\uf400','\uf680'}, // UnicodeCategory.PrivateUse new char[] {'\u203f','\u2040','\u2054','\ufe33','\ufe34','\ufe4d','\ufe4e','\ufe4f','\uff3f'}, // UnicodeCategory.ConnectorPunctuation new char[] {'\u2e17','\u2e1a','\u301c','\u3030','\u30a0','\ufe31','\ufe32','\ufe58','\ufe63','\uff0d'}, // UnicodeCategory.DashPunctuation new char[] {'\u2768','\u2774','\u27ee','\u298d','\u29d8','\u2e28','\u3014','\ufe17','\ufe3f','\ufe5d'}, // UnicodeCategory.OpenPunctuation new char[] {'\u276b','\u27c6','\u2984','\u2990','\u29db','\u3009','\u3017','\ufe18','\ufe40','\ufe5e'}, // UnicodeCategory.ClosePunctuation new char[] {'\u201b','\u201c','\u201f','\u2039','\u2e02','\u2e04','\u2e09','\u2e0c','\u2e1c','\u2e20'}, // UnicodeCategory.InitialQuotePunctuation new char[] {'\u2019','\u201d','\u203a','\u2e03','\u2e05','\u2e0a','\u2e0d','\u2e1d','\u2e21'}, // UnicodeCategory.FinalQuotePunctuation new char[] {'\u0589','\u0709','\u0f10','\u16ec','\u1b5b','\u2034','\u2058','\u2e16','\ua8cf','\ufe55'}, // UnicodeCategory.OtherPunctuation new char[] {'\u2052','\u2234','\u2290','\u22ec','\u27dd','\u2943','\u29b5','\u2a17','\u2a73','\u2acf'}, // UnicodeCategory.MathSymbol new char[] {'\u17db','\u20a2','\u20a5','\u20a8','\u20ab','\u20ae','\u20b1','\u20b4','\ufe69','\uffe1'}, // UnicodeCategory.CurrencySymbol new char[] {'\u02c5','\u02da','\u02e8','\u02f3','\u02fc','\u1fc0','\u1fee','\ua703','\ua70c','\ua715'}, // UnicodeCategory.ModifierSymbol new char[] {'\u0bf3','\u2316','\u24ac','\u25b2','\u26af','\u285c','\u2e8f','\u2f8c','\u3292','\u3392'}, // UnicodeCategory.OtherSymbol new char[] {'\u09c6','\u0dfa','\u2e5c'}, // UnicodeCategory.OtherNotAssigned }; private static char[] s_highSurrogates = new char[] { '\ud800', '\udaaa', '\udbff' }; // Range from '\ud800' to '\udbff' private static char[] s_lowSurrogates = new char[] { '\udc00', '\udeee', '\udfff' }; // Range from '\udc00' to '\udfff' private static char[] s_nonSurrogates = new char[] { '\u0000', '\ud7ff', '\ue000', '\uffff' }; private static readonly UnicodeCategory[] s_categoryForLatin1 = { UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, // 0000 - 0007 UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, // 0008 - 000F UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, // 0010 - 0017 UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, // 0018 - 001F UnicodeCategory.SpaceSeparator, UnicodeCategory.OtherPunctuation, UnicodeCategory.OtherPunctuation, UnicodeCategory.OtherPunctuation, UnicodeCategory.CurrencySymbol, UnicodeCategory.OtherPunctuation, UnicodeCategory.OtherPunctuation, UnicodeCategory.OtherPunctuation, // 0020 - 0027 UnicodeCategory.OpenPunctuation, UnicodeCategory.ClosePunctuation, UnicodeCategory.OtherPunctuation, UnicodeCategory.MathSymbol, UnicodeCategory.OtherPunctuation, UnicodeCategory.DashPunctuation, UnicodeCategory.OtherPunctuation, UnicodeCategory.OtherPunctuation, // 0028 - 002F UnicodeCategory.DecimalDigitNumber, UnicodeCategory.DecimalDigitNumber, UnicodeCategory.DecimalDigitNumber, UnicodeCategory.DecimalDigitNumber, UnicodeCategory.DecimalDigitNumber, UnicodeCategory.DecimalDigitNumber, UnicodeCategory.DecimalDigitNumber, UnicodeCategory.DecimalDigitNumber, // 0030 - 0037 UnicodeCategory.DecimalDigitNumber, UnicodeCategory.DecimalDigitNumber, UnicodeCategory.OtherPunctuation, UnicodeCategory.OtherPunctuation, UnicodeCategory.MathSymbol, UnicodeCategory.MathSymbol, UnicodeCategory.MathSymbol, UnicodeCategory.OtherPunctuation, // 0038 - 003F UnicodeCategory.OtherPunctuation, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, // 0040 - 0047 UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, // 0048 - 004F UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, // 0050 - 0057 UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.OpenPunctuation, UnicodeCategory.OtherPunctuation, UnicodeCategory.ClosePunctuation, UnicodeCategory.ModifierSymbol, UnicodeCategory.ConnectorPunctuation, // 0058 - 005F UnicodeCategory.ModifierSymbol, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, // 0060 - 0067 UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, // 0068 - 006F UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, // 0070 - 0077 UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.OpenPunctuation, UnicodeCategory.MathSymbol, UnicodeCategory.ClosePunctuation, UnicodeCategory.MathSymbol, UnicodeCategory.Control, // 0078 - 007F UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, // 0080 - 0087 UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, // 0088 - 008F UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, // 0090 - 0097 UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, UnicodeCategory.Control, // 0098 - 009F UnicodeCategory.SpaceSeparator, UnicodeCategory.OtherPunctuation, UnicodeCategory.CurrencySymbol, UnicodeCategory.CurrencySymbol, UnicodeCategory.CurrencySymbol, UnicodeCategory.CurrencySymbol, UnicodeCategory.OtherSymbol, UnicodeCategory.OtherSymbol, // 00A0 - 00A7 UnicodeCategory.ModifierSymbol, UnicodeCategory.OtherSymbol, UnicodeCategory.LowercaseLetter, UnicodeCategory.InitialQuotePunctuation, UnicodeCategory.MathSymbol, UnicodeCategory.DashPunctuation, UnicodeCategory.OtherSymbol, UnicodeCategory.ModifierSymbol, // 00A8 - 00AF UnicodeCategory.OtherSymbol, UnicodeCategory.MathSymbol, UnicodeCategory.OtherNumber, UnicodeCategory.OtherNumber, UnicodeCategory.ModifierSymbol, UnicodeCategory.LowercaseLetter, UnicodeCategory.OtherSymbol, UnicodeCategory.OtherPunctuation, // 00B0 - 00B7 UnicodeCategory.ModifierSymbol, UnicodeCategory.OtherNumber, UnicodeCategory.LowercaseLetter, UnicodeCategory.FinalQuotePunctuation, UnicodeCategory.OtherNumber, UnicodeCategory.OtherNumber, UnicodeCategory.OtherNumber, UnicodeCategory.OtherPunctuation, // 00B8 - 00BF UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, // 00C0 - 00C7 UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, // 00C8 - 00CF UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.MathSymbol, // 00D0 - 00D7 UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.UppercaseLetter, UnicodeCategory.LowercaseLetter, // 00D8 - 00DF UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, // 00E0 - 00E7 UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, // 00E8 - 00EF UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.MathSymbol, // 00F0 - 00F7 UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.LowercaseLetter, // 00F8 - 00FF }; public static IEnumerable<object[]> UpperLowerCasing_TestData() { // lower upper Culture yield return new object[] { 'a', 'A', "en-US" }; yield return new object[] { 'i', 'I', "en-US" }; yield return new object[] { '\u0131', 'I', "tr-TR" }; yield return new object[] { 'i', '\u0130', "tr-TR" }; yield return new object[] { '\u0660', '\u0660', "en-US" }; } [Fact] public static void LatinRangeTest() { StringBuilder sb = new StringBuilder(256); string latineString = sb.ToString(); for (int i=0; i < latineString.Length; i++) { Assert.Equal(s_categoryForLatin1[i], char.GetUnicodeCategory(latineString[i])); Assert.Equal(s_categoryForLatin1[i], char.GetUnicodeCategory(latineString, i)); } } [Fact] public static void NonLatinRangeTest() { for (int i=256; i <= 0xFFFF; i++) { Assert.Equal(CharUnicodeInfo.GetUnicodeCategory((char)i), char.GetUnicodeCategory((char)i)); } string nonLatinString = "\u0100\u0200\u0300\u0400\u0500\u0600\u0700\u0800\u0900\u0A00\u0B00\u0C00\u0D00\u0E00\u0F00" + "\u1000\u2000\u3000\u4000\u5000\u6000\u7000\u8000\u9000\uA000\uB000\uC000\uD000\uE000\uF000"; for (int i=0; i < nonLatinString.Length; i++) { Assert.Equal(CharUnicodeInfo.GetUnicodeCategory(nonLatinString[i]), char.GetUnicodeCategory(nonLatinString, i)); } } [Theory] [MemberData(nameof(UpperLowerCasing_TestData))] public static void CasingTest(char lowerForm, char upperForm, string cultureName) { CultureInfo ci = CultureInfo.GetCultureInfo(cultureName); Assert.Equal(lowerForm, char.ToLower(upperForm, ci)); Assert.Equal(upperForm, char.ToUpper(lowerForm, ci)); } } }
using System; using System.Globalization; using System.IO; using System.Linq; using System.Web.Compilation; using System.Web.Mvc; using System.Web.Routing; using Umbraco.Core; using Umbraco.Web.Models; using Umbraco.Web.Mvc; using Umbraco.Web.Routing; using umbraco; using umbraco.cms.businesslogic.language; namespace Umbraco.Web.Templates { /// <summary> /// This is used purely for the RenderTemplate functionality in Umbraco /// </summary> /// <remarks> /// This allows you to render either an MVC or Webforms template based purely off of a node id and an optional alttemplate id as string output. /// </remarks> internal class TemplateRenderer { private readonly UmbracoContext _umbracoContext; private object _oldPageId; private object _oldPageElements; private PublishedContentRequest _oldPublishedContentRequest; private object _oldAltTemplate; public TemplateRenderer(UmbracoContext umbracoContext, int pageId, int? altTemplateId) { if (umbracoContext == null) throw new ArgumentNullException("umbracoContext"); PageId = pageId; AltTemplate = altTemplateId; _umbracoContext = umbracoContext; } /// <summary> /// Gets/sets the page id for the template to render /// </summary> public int PageId { get; private set; } /// <summary> /// Gets/sets the alt template to render if there is one /// </summary> public int? AltTemplate { get; private set; } public void Render(StringWriter writer) { if (writer == null) throw new ArgumentNullException("writer"); // instanciate a request a process // important to use CleanedUmbracoUrl - lowercase path-only version of the current url, though this isn't going to matter // terribly much for this implementation since we are just creating a doc content request to modify it's properties manually. var contentRequest = new PublishedContentRequest(_umbracoContext.CleanedUmbracoUrl, _umbracoContext.RoutingContext); var doc = contentRequest.RoutingContext.UmbracoContext.ContentCache.GetById(PageId); if (doc == null) { writer.Write("<!-- Could not render template for Id {0}, the document was not found -->", PageId); return; } //in some cases the UmbracoContext will not have a PublishedContentRequest assigned to it if we are not in the //execution of a front-end rendered page. In this case set the culture to the default. //set the culture to the same as is currently rendering if (_umbracoContext.PublishedContentRequest == null) { var defaultLanguage = Language.GetAllAsList().FirstOrDefault(); contentRequest.Culture = defaultLanguage == null ? CultureInfo.CurrentUICulture : new CultureInfo(defaultLanguage.CultureAlias); } else { contentRequest.Culture = _umbracoContext.PublishedContentRequest.Culture; } //set the doc that was found by id contentRequest.PublishedContent = doc; //set the template, either based on the AltTemplate found or the standard template of the doc contentRequest.TemplateModel = !AltTemplate.HasValue ? ApplicationContext.Current.Services.FileService.GetTemplate(doc.TemplateId) : ApplicationContext.Current.Services.FileService.GetTemplate(AltTemplate.Value); //if there is not template then exit if (!contentRequest.HasTemplate) { if (!AltTemplate.HasValue) { writer.Write("<!-- Could not render template for Id {0}, the document's template was not found with id {0}-->", doc.TemplateId); } else { writer.Write("<!-- Could not render template for Id {0}, the altTemplate was not found with id {0}-->", AltTemplate); } return; } //First, save all of the items locally that we know are used in the chain of execution, we'll need to restore these //after this page has rendered. SaveExistingItems(); //set the new items on context objects for this templates execution SetNewItemsOnContextObjects(contentRequest); //Render the template ExecuteTemplateRendering(writer, contentRequest); //restore items on context objects to continuing rendering the parent template RestoreItems(); } private void ExecuteTemplateRendering(TextWriter sw, PublishedContentRequest contentRequest) { //NOTE: Before we used to build up the query strings here but this is not necessary because when we do a // Server.Execute in the TemplateRenderer, we pass in a 'true' to 'preserveForm' which automatically preserves all current // query strings so there's no need for this. HOWEVER, once we get MVC involved, we might have to do some fun things, // though this will happen in the TemplateRenderer. //var queryString = _umbracoContext.HttpContext.Request.QueryString.AllKeys // .ToDictionary(key => key, key => context.Request.QueryString[key]); switch (contentRequest.RenderingEngine) { case RenderingEngine.Mvc: var requestContext = new RequestContext(_umbracoContext.HttpContext, new RouteData() { Route = RouteTable.Routes["Umbraco_default"] }); var routeHandler = new RenderRouteHandler(ControllerBuilder.Current.GetControllerFactory(), _umbracoContext); var routeDef = routeHandler.GetUmbracoRouteDefinition(requestContext, contentRequest); var renderModel = new RenderModel(contentRequest.PublishedContent, contentRequest.Culture); //manually add the action/controller, this is required by mvc requestContext.RouteData.Values.Add("action", routeDef.ActionName); requestContext.RouteData.Values.Add("controller", routeDef.ControllerName); //add the rest of the required route data routeHandler.SetupRouteDataForRequest(renderModel, requestContext, contentRequest); var stringOutput = RenderUmbracoRequestToString(requestContext); sw.Write(stringOutput); break; case RenderingEngine.WebForms: default: var webFormshandler = (global::umbraco.UmbracoDefault)BuildManager .CreateInstanceFromVirtualPath("~/default.aspx", typeof(global::umbraco.UmbracoDefault)); //the 'true' parameter will ensure that the current query strings are carried through, we don't have // to build up the url again, it will just work. _umbracoContext.HttpContext.Server.Execute(webFormshandler, sw, true); break; } } /// <summary> /// This will execute the UmbracoMvcHandler for the request specified and get the string output. /// </summary> /// <param name="requestContext"> /// Assumes the RequestContext is setup specifically to render an Umbraco view. /// </param> /// <returns></returns> /// <remarks> /// To acheive this we temporarily change the output text writer of the current HttpResponse, then /// execute the controller via the handler which innevitably writes the result to the text writer /// that has been assigned to the response. Then we change the response textwriter back to the original /// before continuing . /// </remarks> private string RenderUmbracoRequestToString(RequestContext requestContext) { var currentWriter = requestContext.HttpContext.Response.Output; var newWriter = new StringWriter(); requestContext.HttpContext.Response.Output = newWriter; var handler = new UmbracoMvcHandler(requestContext); handler.ExecuteUmbracoRequest(); //reset it requestContext.HttpContext.Response.Output = currentWriter; return newWriter.ToString(); } private void SetNewItemsOnContextObjects(PublishedContentRequest contentRequest) { // handlers like default.aspx will want it and most macros currently need it contentRequest.UmbracoPage = new page(contentRequest); //now, set the new ones for this page execution _umbracoContext.HttpContext.Items["pageID"] = contentRequest.PublishedContent.Id; _umbracoContext.HttpContext.Items["pageElements"] = contentRequest.UmbracoPage.Elements; _umbracoContext.HttpContext.Items[Umbraco.Core.Constants.Conventions.Url.AltTemplate] = null; _umbracoContext.PublishedContentRequest = contentRequest; } /// <summary> /// Save all items that we know are used for rendering execution to variables so we can restore after rendering /// </summary> private void SaveExistingItems() { //Many objects require that these legacy items are in the http context items... before we render this template we need to first //save the values in them so that we can re-set them after we render so the rest of the execution works as per normal. _oldPageId = _umbracoContext.HttpContext.Items["pageID"]; _oldPageElements = _umbracoContext.HttpContext.Items["pageElements"]; _oldPublishedContentRequest = _umbracoContext.PublishedContentRequest; _oldAltTemplate = _umbracoContext.HttpContext.Items[Umbraco.Core.Constants.Conventions.Url.AltTemplate]; } /// <summary> /// Restores all items back to their context's to continue normal page rendering execution /// </summary> private void RestoreItems() { _umbracoContext.PublishedContentRequest = _oldPublishedContentRequest; _umbracoContext.HttpContext.Items["pageID"] = _oldPageId; _umbracoContext.HttpContext.Items["pageElements"] = _oldPageElements; _umbracoContext.HttpContext.Items[Umbraco.Core.Constants.Conventions.Url.AltTemplate] = _oldAltTemplate; } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using GitVersion; using GitVersion.Configuration; using GitVersion.Extensions; using GitVersion.Logging; using GitVersion.Model.Configuration; using GitVersion.VersionCalculation; using GitVersionCore.Tests.Helpers; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; using NUnit.Framework; using Shouldly; using YamlDotNet.Serialization; using Environment = System.Environment; namespace GitVersionCore.Tests { [TestFixture] public class ConfigProviderTests : TestBase { private const string DefaultRepoPath = @"c:\MyGitRepo"; private string repoPath; private IConfigProvider configProvider; private IFileSystem fileSystem; [SetUp] public void Setup() { repoPath = DefaultRepoPath; var options = Options.Create(new GitVersionOptions { WorkingDirectory = repoPath }); var sp = ConfigureServices(services => { services.AddSingleton(options); }); configProvider = sp.GetService<IConfigProvider>(); fileSystem = sp.GetService<IFileSystem>(); ShouldlyConfiguration.ShouldMatchApprovedDefaults.LocateTestMethodUsingAttribute<TestAttribute>(); } [Test] public void OverwritesDefaultsWithProvidedConfig() { var defaultConfig = configProvider.Provide(repoPath); const string text = @" next-version: 2.0.0 branches: develop: mode: ContinuousDeployment tag: dev"; SetupConfigFileContent(text); var config = configProvider.Provide(repoPath); config.NextVersion.ShouldBe("2.0.0"); config.Branches["develop"].Increment.ShouldBe(defaultConfig.Branches["develop"].Increment); config.Branches["develop"].VersioningMode.ShouldBe(defaultConfig.Branches["develop"].VersioningMode); config.Branches["develop"].Tag.ShouldBe("dev"); } [Test] public void AllBranchesModeWhenUsingMainline() { const string text = @"mode: Mainline"; SetupConfigFileContent(text); var config = configProvider.Provide(repoPath); var branches = config.Branches.Select(x => x.Value); branches.All(branch => branch.VersioningMode == VersioningMode.Mainline).ShouldBe(true); } [Test] public void CanRemoveTag() { const string text = @" next-version: 2.0.0 branches: release: tag: """""; SetupConfigFileContent(text); var config = configProvider.Provide(repoPath); config.NextVersion.ShouldBe("2.0.0"); config.Branches["release"].Tag.ShouldBe(string.Empty); } [Test] public void RegexIsRequired() { const string text = @" next-version: 2.0.0 branches: bug: tag: bugfix"; SetupConfigFileContent(text); var ex = Should.Throw<ConfigurationException>(() => configProvider.Provide(repoPath)); ex.Message.ShouldBe($"Branch configuration 'bug' is missing required configuration 'regex'{Environment.NewLine}" + "See https://gitversion.net/docs/configuration/ for more info"); } [Test] public void SourceBranchIsRequired() { const string text = @" next-version: 2.0.0 branches: bug: regex: 'bug[/-]' tag: bugfix"; SetupConfigFileContent(text); var ex = Should.Throw<ConfigurationException>(() => configProvider.Provide(repoPath)); ex.Message.ShouldBe($"Branch configuration 'bug' is missing required configuration 'source-branches'{Environment.NewLine}" + "See https://gitversion.net/docs/configuration/ for more info"); } [Test(Description = "This test proves the configuration validation will fail early with a helpful message when a branch listed in source-branches has no configuration.")] public void SourceBranchesValidationShouldFailWhenMatchingBranchConfigurationIsMissing() { const string text = @" branches: bug: regex: 'bug[/-]' tag: bugfix source-branches: [notconfigured]"; SetupConfigFileContent(text); var ex = Should.Throw<ConfigurationException>(() => configProvider.Provide(repoPath)); ex.Message.ShouldBe($"Branch configuration 'bug' defines these 'source-branches' that are not configured: '[notconfigured]'{Environment.NewLine}" + "See https://gitversion.net/docs/configuration/ for more info"); } [Test(Description = "Well-known branches may not be present in the configuration file. This test confirms the validation check succeeds when the source-branches configuration contain these well-known branches.")] [TestCase(Config.MasterBranchKey)] [TestCase(Config.DevelopBranchKey)] public void SourceBranchesValidationShouldSucceedForWellKnownBranches(string wellKnownBranchKey) { var text = $@" branches: bug: regex: 'bug[/-]' tag: bugfix source-branches: [{wellKnownBranchKey}]"; SetupConfigFileContent(text); var config = configProvider.Provide(repoPath); config.Branches["bug"].SourceBranches.ShouldBe(new List<string> { wellKnownBranchKey }); } [Test] public void CanProvideConfigForNewBranch() { const string text = @" next-version: 2.0.0 branches: bug: regex: 'bug[/-]' tag: bugfix source-branches: []"; SetupConfigFileContent(text); var config = configProvider.Provide(repoPath); config.Branches["bug"].Regex.ShouldBe("bug[/-]"); config.Branches["bug"].Tag.ShouldBe("bugfix"); } [Test] public void NextVersionCanBeInteger() { const string text = "next-version: 2"; SetupConfigFileContent(text); var config = configProvider.Provide(repoPath); config.NextVersion.ShouldBe("2.0"); } [Test] public void NextVersionCanHaveEnormousMinorVersion() { const string text = "next-version: 2.118998723"; SetupConfigFileContent(text); var config = configProvider.Provide(repoPath); config.NextVersion.ShouldBe("2.118998723"); } [Test] public void NextVersionCanHavePatch() { const string text = "next-version: 2.12.654651698"; SetupConfigFileContent(text); var config = configProvider.Provide(repoPath); config.NextVersion.ShouldBe("2.12.654651698"); } [Test] [MethodImpl(MethodImplOptions.NoInlining)] [Category(NoMono)] [Description(NoMonoDescription)] public void CanWriteOutEffectiveConfiguration() { var config = configProvider.Provide(repoPath); config.ToString().ShouldMatchApproved(); } [Test] public void CanUpdateAssemblyInformationalVersioningScheme() { const string text = @" assembly-versioning-scheme: MajorMinor assembly-file-versioning-scheme: MajorMinorPatch assembly-informational-format: '{NugetVersion}'"; SetupConfigFileContent(text); var config = configProvider.Provide(repoPath); config.AssemblyVersioningScheme.ShouldBe(AssemblyVersioningScheme.MajorMinor); config.AssemblyFileVersioningScheme.ShouldBe(AssemblyFileVersioningScheme.MajorMinorPatch); config.AssemblyInformationalFormat.ShouldBe("{NugetVersion}"); } [Test] public void CanUpdateAssemblyInformationalVersioningSchemeWithMultipleVariables() { const string text = @" assembly-versioning-scheme: MajorMinor assembly-file-versioning-scheme: MajorMinorPatch assembly-informational-format: '{Major}.{Minor}.{Patch}'"; SetupConfigFileContent(text); var config = configProvider.Provide(repoPath); config.AssemblyVersioningScheme.ShouldBe(AssemblyVersioningScheme.MajorMinor); config.AssemblyFileVersioningScheme.ShouldBe(AssemblyFileVersioningScheme.MajorMinorPatch); config.AssemblyInformationalFormat.ShouldBe("{Major}.{Minor}.{Patch}"); } [Test] public void CanUpdateAssemblyInformationalVersioningSchemeWithFullSemVer() { const string text = @"assembly-versioning-scheme: MajorMinorPatch assembly-file-versioning-scheme: MajorMinorPatch assembly-informational-format: '{FullSemVer}' mode: ContinuousDelivery next-version: 5.3.0 branches: {}"; SetupConfigFileContent(text); var config = configProvider.Provide(repoPath); config.AssemblyVersioningScheme.ShouldBe(AssemblyVersioningScheme.MajorMinorPatch); config.AssemblyFileVersioningScheme.ShouldBe(AssemblyFileVersioningScheme.MajorMinorPatch); config.AssemblyInformationalFormat.ShouldBe("{FullSemVer}"); } [Test] public void CanReadDefaultDocument() { const string text = ""; SetupConfigFileContent(text); var config = configProvider.Provide(repoPath); config.AssemblyVersioningScheme.ShouldBe(AssemblyVersioningScheme.MajorMinorPatch); config.AssemblyFileVersioningScheme.ShouldBe(AssemblyFileVersioningScheme.MajorMinorPatch); config.AssemblyInformationalFormat.ShouldBe(null); config.Branches["develop"].Tag.ShouldBe("alpha"); config.Branches["release"].Tag.ShouldBe("beta"); config.TagPrefix.ShouldBe(Config.DefaultTagPrefix); config.NextVersion.ShouldBe(null); } [Test] public void VerifyAliases() { var config = typeof(Config); var propertiesMissingAlias = config.GetProperties() .Where(p => p.GetCustomAttribute<ObsoleteAttribute>() == null) .Where(p => p.GetCustomAttribute(typeof(YamlMemberAttribute)) == null) .Select(p => p.Name); propertiesMissingAlias.ShouldBeEmpty(); } [Test] public void NoWarnOnGitVersionYmlFile() { SetupConfigFileContent(string.Empty); var stringLogger = string.Empty; void Action(string info) => stringLogger = info; var logAppender = new TestLogAppender(Action); var log = new Log(logAppender); var options = Options.Create(new GitVersionOptions { WorkingDirectory = repoPath }); var sp = ConfigureServices(services => { services.AddSingleton(options); services.AddSingleton<ILog>(log); }); configProvider = sp.GetService<IConfigProvider>(); configProvider.Provide(repoPath); stringLogger.Length.ShouldBe(0); } private string SetupConfigFileContent(string text, string fileName = DefaultConfigFileLocator.DefaultFileName) { return SetupConfigFileContent(text, fileName, repoPath); } private string SetupConfigFileContent(string text, string fileName, string path) { var fullPath = Path.Combine(path, fileName); fileSystem.WriteAllText(fullPath, text); return fullPath; } [Test] public void ShouldUseSpecifiedSourceBranchesForDevelop() { const string text = @" next-version: 2.0.0 branches: develop: mode: ContinuousDeployment source-branches: ['develop'] tag: dev"; SetupConfigFileContent(text); var config = configProvider.Provide(repoPath); config.Branches["develop"].SourceBranches.ShouldBe(new List<string> { "develop" }); } [Test] public void ShouldUseDefaultSourceBranchesWhenNotSpecifiedForDevelop() { const string text = @" next-version: 2.0.0 branches: develop: mode: ContinuousDeployment tag: dev"; SetupConfigFileContent(text); var config = configProvider.Provide(repoPath); config.Branches["develop"].SourceBranches.ShouldBe(new List<string>()); } [Test] public void ShouldUseSpecifiedSourceBranchesForFeature() { const string text = @" next-version: 2.0.0 branches: feature: mode: ContinuousDeployment source-branches: ['develop', 'release'] tag: dev"; SetupConfigFileContent(text); var config = configProvider.Provide(repoPath); config.Branches["feature"].SourceBranches.ShouldBe(new List<string> { "develop", "release" }); } [Test] public void ShouldUseDefaultSourceBranchesWhenNotSpecifiedForFeature() { const string text = @" next-version: 2.0.0 branches: feature: mode: ContinuousDeployment tag: dev"; SetupConfigFileContent(text); var config = configProvider.Provide(repoPath); config.Branches["feature"].SourceBranches.ShouldBe( new List<string> { "develop", "master", "release", "feature", "support", "hotfix" }); } [Test] public void ShouldNotOverrideAnythingWhenOverrideConfigIsEmpty() { const string text = @" next-version: 1.2.3 tag-prefix: custom-tag-prefix-from-yml"; SetupConfigFileContent(text); var expectedConfig = configProvider.Provide(repoPath, overrideConfig: null); var overridenConfig = configProvider.Provide(repoPath, overrideConfig: new Config()); overridenConfig.AssemblyVersioningScheme.ShouldBe(expectedConfig.AssemblyVersioningScheme); overridenConfig.AssemblyFileVersioningScheme.ShouldBe(expectedConfig.AssemblyFileVersioningScheme); overridenConfig.AssemblyInformationalFormat.ShouldBe(expectedConfig.AssemblyInformationalFormat); overridenConfig.AssemblyVersioningFormat.ShouldBe(expectedConfig.AssemblyVersioningFormat); overridenConfig.AssemblyFileVersioningFormat.ShouldBe(expectedConfig.AssemblyFileVersioningFormat); overridenConfig.VersioningMode.ShouldBe(expectedConfig.VersioningMode); overridenConfig.TagPrefix.ShouldBe(expectedConfig.TagPrefix); overridenConfig.ContinuousDeploymentFallbackTag.ShouldBe(expectedConfig.ContinuousDeploymentFallbackTag); overridenConfig.NextVersion.ShouldBe(expectedConfig.NextVersion); overridenConfig.MajorVersionBumpMessage.ShouldBe(expectedConfig.MajorVersionBumpMessage); overridenConfig.MinorVersionBumpMessage.ShouldBe(expectedConfig.MinorVersionBumpMessage); overridenConfig.PatchVersionBumpMessage.ShouldBe(expectedConfig.PatchVersionBumpMessage); overridenConfig.NoBumpMessage.ShouldBe(expectedConfig.NoBumpMessage); overridenConfig.LegacySemVerPadding.ShouldBe(expectedConfig.LegacySemVerPadding); overridenConfig.BuildMetaDataPadding.ShouldBe(expectedConfig.BuildMetaDataPadding); overridenConfig.CommitsSinceVersionSourcePadding.ShouldBe(expectedConfig.CommitsSinceVersionSourcePadding); overridenConfig.TagPreReleaseWeight.ShouldBe(expectedConfig.TagPreReleaseWeight); overridenConfig.CommitMessageIncrementing.ShouldBe(expectedConfig.CommitMessageIncrementing); overridenConfig.Increment.ShouldBe(expectedConfig.Increment); overridenConfig.CommitDateFormat.ShouldBe(expectedConfig.CommitDateFormat); overridenConfig.MergeMessageFormats.ShouldBe(expectedConfig.MergeMessageFormats); overridenConfig.UpdateBuildNumber.ShouldBe(expectedConfig.UpdateBuildNumber); overridenConfig.Ignore.ShouldBeEquivalentTo(expectedConfig.Ignore); overridenConfig.Branches.Keys.ShouldBe(expectedConfig.Branches.Keys); foreach (var branch in overridenConfig.Branches.Keys) { overridenConfig.Branches[branch].ShouldBeEquivalentTo(expectedConfig.Branches[branch]); } } [Test] public void ShouldUseDefaultTagPrefixWhenNotSetInConfigFile() { const string text = ""; SetupConfigFileContent(text); var config = configProvider.Provide(repoPath); config.TagPrefix.ShouldBe("[vV]"); } [Test] public void ShouldUseTagPrefixFromConfigFileWhenProvided() { const string text = "tag-prefix: custom-tag-prefix-from-yml"; SetupConfigFileContent(text); var config = configProvider.Provide(repoPath); config.TagPrefix.ShouldBe("custom-tag-prefix-from-yml"); } [Test] public void ShouldOverrideTagPrefixWithOverrideConfigValue([Values] bool tagPrefixSetAtYmlFile) { var text = tagPrefixSetAtYmlFile ? "tag-prefix: custom-tag-prefix-from-yml" : ""; SetupConfigFileContent(text); var config = configProvider.Provide(repoPath, overrideConfig: new Config { TagPrefix = "tag-prefix-from-override-config" }); config.TagPrefix.ShouldBe("tag-prefix-from-override-config"); } [Test] public void ShouldNotOverrideDefaultTagPrefixWhenNotSetInOverrideConfig() { const string text = ""; SetupConfigFileContent(text); var config = configProvider.Provide(repoPath, overrideConfig: new Config { TagPrefix = null }); config.TagPrefix.ShouldBe("[vV]"); } [Test] public void ShouldNotOverrideTagPrefixFromConfigFileWhenNotSetInOverrideConfig() { const string text = "tag-prefix: custom-tag-prefix-from-yml"; SetupConfigFileContent(text); var config = configProvider.Provide(repoPath, overrideConfig: new Config { TagPrefix = null }); config.TagPrefix.ShouldBe("custom-tag-prefix-from-yml"); } } }
using System; using System.Reflection; using System.Collections.Generic; using System.IO; using System.Linq; using System.Security; using System.Security.Permissions; using System.Security.Policy; /// Manages the scripting. /// Scripts run in a new AppDomain with the help of the script-helper helper library. public class ScriptManager { private const string HELPER_ASSEMBLY = "script-helper.dll"; private const string HELPER_TYPE = "ScriptHelper"; public ScriptManager(World world, IRenderer renderer, IControls controls) { context = new ScriptContext(world, renderer); Yondr.Entity.Context = context; this.world = world; if (controls != null) { // this is a client this.controls = controls; var group = world.GroupDictionary[World.Self]; self = new Yondr.Entity(group.Index, group.Entities[1].Index); } else { // this is a server self = null; } methods = new List<MethodInfo>[(int)Event.COUNT]; for (int i = 0; i < methods.Length; i++) { methods[i] = new List<MethodInfo>(); } createAppDomain(); } private void createAppDomain() { // Scripts only have execution permissions. var permissions = new PermissionSet(PermissionState.None); permissions.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution)); var helperType = typeof(ScriptHelper); var helperStrongName = GetStrongName(helperType.Assembly); var contextStrongName = GetStrongName(typeof(Yondr.IContext).Assembly); // Create appdomain. domain = AppDomain.CreateDomain( "ScriptDomain", new Evidence(), new AppDomainSetup(), permissions, new[] { helperStrongName, contextStrongName } ); helper = (ScriptHelper)domain.CreateInstanceFromAndUnwrap(HELPER_ASSEMBLY, HELPER_TYPE); } ~ScriptManager() { //AppDomain.Unload(domain); (times out) } private static StrongName GetStrongName(Assembly ass) { AssemblyName assemblyName = ass.GetName(); byte[] publicKey = assemblyName.GetPublicKey(); if (publicKey == null || publicKey.Length == 0) { throw new InvalidOperationException(String.Format("{0} is not strongly named", ass)); } var keyBlob = new StrongNamePublicKeyBlob(publicKey); return new StrongName(keyBlob, assemblyName.Name, assemblyName.Version); } public void Compile(Res.Package package) { string outDir = getDllFilename(package); Assembly ass = null; // Get all the scripts in the package. DateTime pakDate = DateTime.MinValue; var scripts = new List<string>(); foreach (Res.Res res in package.Resources.Values) { if (res.Type == Res.Type.SCRIPT) { scripts.Add(res.Path); DateTime scriptDate = File.GetLastWriteTime(res.Path); if (scriptDate > pakDate) { // package date is the last modified date pakDate = scriptDate; } } } if (scripts.Count == 0) return; // Check if package is already compiled. if (File.Exists(outDir)) { DateTime outDate = File.GetLastWriteTime(outDir); if (pakDate < outDate) ass = helper.Load(outDir); if (ass != null) Log.Info("Loaded {0}", outDir); } if (ass == null) { // Compile them. string path = generateProperties(package); scripts.Add(path); var result = helper.Compile(scripts.ToArray(), outDir); foreach (var error in result.Errors) Log.Info(" {0}", error); foreach (var output in result.Output) Log.Info(" {0}", output); if (result.Errors.HasErrors) { Log.Error("Failed to compile {0}:", outDir); return; } Log.Info("Compiled {0}", outDir); ass = result.CompiledAssembly; } findMethods(ass); // Set the context static value. //var entities = ass.GetType("Yondr.Entity"); //foreach (var type in ass.GetTypes()) { // Log.Debug("Poof: {0}", type.Name); //} //var prop = entities.GetProperty("Context"); //prop.SetValue(null, context); } private string generateProperties(Res.Package package) { // Generate the file containing all the property constants. string filename = Path.Combine(package.Path, "_properties.cs"); using (var file = new StreamWriter(filename)) { file.WriteLine("using System;"); file.WriteLine("namespace Yondr {"); file.WriteLine("namespace Groups {"); foreach (var group in world.Groups) { file.WriteLine("\tpublic static class {0} {{", group.CamelCaseName); for (ushort i = 0; i < group.PropertySystem.Count; i++) { Property prop = group.PropertySystem.At(i); file.WriteLine( "\t\tpublic static Property<{0}> {1} = new Property<{0}>({2}, {3});", prop.Value.val.GetType().Name, prop.CamelCaseName, group.Index, prop.Index ); } file.WriteLine("\t}"); } file.WriteLine("}"); file.WriteLine("}"); } return filename; } private void findMethods(Assembly ass) { // We look for public static methods in a class called Events, // and add them to our collection of scripts. var flags = BindingFlags.Public | BindingFlags.Static; var events = ass.GetType("Events", false); if (events != null) { foreach (MethodInfo meth in events.GetMethods(flags)) { Event? even = null; switch (meth.Name) { case "Init": even = Event.INIT; break; case "Update": even = Event.UPDATE; break; case "Exit": even = Event.EXIT; break; default: string[] parts = meth.Name.Split(new[] { '_' }, 2); if (parts.Length < 2) break; switch (parts[0]) { case "While": AddWhile(parts[1], meth); continue; case "On": AddOn( parts[1], meth); continue; } break; } if (even == null) { Log.Warn("{0} does not match any known events. " + "If it's a helper function, make it private.", meth.Name); continue; } if (!checkMethodParams(meth, EventParameters[(int)even])) continue; methods[(int)even].Add(meth); } } } public void DeleteDll(Res.Package package) { string filename = getDllFilename(package); Log.Info("Deleting {0}", filename); File.Delete(filename); } private static string getDllFilename(Res.Package package) { return "_" + package.Name + ".dll"; } private static bool checkMethodParams(MethodInfo meth, Type[] expectedParams) { var foundParams = meth.GetParameters().Select((p, _) => p.ParameterType); if (!foundParams.SequenceEqual(expectedParams)) { Log.Error("'{0}' does not have the correct parameters.\n" + " Expected: {1}\n Found: {2}", meth.Name, expectedParams, foundParams); return false; } return true; } private void AddWhile(string name, MethodInfo meth) { if (!checkMethodParams(meth, new[] { typeof(Yondr.Entity), typeof(float) })) return; if (controls != null) { // is client controls.AddWhile(name, d => meth.Invoke(null, new object[] { self, d })); } } private void AddOn(string name, MethodInfo meth) { if (!checkMethodParams(meth, new[] { typeof(Yondr.Entity) })) return; if (controls != null) { // is client controls.AddOn(name, () => meth.Invoke(null, new object[] { self })); } } public enum Event { INIT, UPDATE, EXIT, COUNT, } private Type[][] EventParameters = new Type[][] { new Type[] { typeof(Yondr.Entity?), typeof(Yondr.IContext) }, new Type[] { typeof(float) }, new Type[] { }, }; public void Init() { foreach (MethodInfo meth in methods[(int)Event.INIT]) { meth.Invoke(null, new object[] { self, context }); } } public void Update(float diff) { foreach (MethodInfo meth in methods[(int)Event.UPDATE]) { meth.Invoke(null, new object[] { diff }); } } public void Exit() { foreach (MethodInfo meth in methods[(int)Event.EXIT]) { meth.Invoke(null, new object[] { }); } } private readonly IControls controls; private readonly ScriptContext context; private AppDomain domain; private ScriptHelper helper; private readonly List<MethodInfo>[] methods; private Yondr.Entity? self; private World world; }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Xml; using Nop.Core.Domain.Affiliates; using Nop.Core.Domain.Common; using Nop.Core.Domain.Directory; using Nop.Core.Domain.Forums; using Nop.Core.Domain.Localization; using Nop.Core.Domain.Logging; using Nop.Core.Domain.Orders; using Nop.Core.Domain.Tax; namespace Nop.Core.Domain.Customers { /// <summary> /// Represents a customer /// </summary> public partial class Customer : BaseEntity { private ICollection<ExternalAuthenticationRecord> _externalAuthenticationRecords; private ICollection<CustomerContent> _customerContent; private ICollection<CustomerRole> _customerRoles; private ICollection<ShoppingCartItem> _shoppingCartItems; private ICollection<Order> _orders; private ICollection<RewardPointsHistory> _rewardPointsHistory; private ICollection<ReturnRequest> _returnRequests; private ICollection<Address> _addresses; private ICollection<ForumTopic> _forumTopics; private ICollection<ForumPost> _forumPosts; public Customer() { this.CustomerGuid = Guid.NewGuid(); this.PasswordFormat = PasswordFormat.Clear; } /// <summary> /// Gets or sets the customer Guid /// </summary> public virtual Guid CustomerGuid { get; set; } public virtual string Username { get; set; } public virtual string Email { get; set; } public virtual string Password { get; set; } public virtual int PasswordFormatId { get; set; } public virtual PasswordFormat PasswordFormat { get { return (PasswordFormat)PasswordFormatId; } set { this.PasswordFormatId = (int)value; } } public virtual string PasswordSalt { get; set; } /// <summary> /// Gets or sets the admin comment /// </summary> public virtual string AdminComment { get; set; } /// <summary> /// Gets or sets the language identifier /// </summary> public virtual int? LanguageId { get; set; } /// <summary> /// Gets or sets the currency identifier /// </summary> public virtual int? CurrencyId { get; set; } /// <summary> /// Gets or sets the tax display type identifier /// </summary> public virtual int TaxDisplayTypeId { get; set; } /// <summary> /// Gets or sets a value indicating whether the customer is tax exempt /// </summary> public virtual bool IsTaxExempt { get; set; } /// <summary> /// Gets or sets a VAT number (including counry code) /// </summary> public virtual string VatNumber { get; set; } /// <summary> /// Gets or sets the VAT number status identifier /// </summary> public virtual int VatNumberStatusId { get; set; } /// <summary> /// Gets or sets the last payment method system name (selected one) /// </summary> public virtual string SelectedPaymentMethodSystemName { get; set; } /// <summary> /// Gets or sets the selected checkout attributes (serialized) /// </summary> public virtual string CheckoutAttributes { get; set; } /// <summary> /// Gets or sets the applied discount coupon code /// </summary> public virtual string DiscountCouponCode { get; set; } /// <summary> /// Gets or sets the applied gift card coupon codes (serialized) /// </summary> public virtual string GiftCardCouponCodes { get; set; } /// <summary> /// Gets or sets a value indicating whether to use reward points during checkout /// </summary> public virtual bool UseRewardPointsDuringCheckout { get; set; } /// <summary> /// Gets or sets the time zone identifier /// </summary> public virtual string TimeZoneId { get; set; } /// <summary> /// Gets or sets the affiliate identifier /// </summary> public virtual int? AffiliateId { get; set; } /// <summary> /// Gets or sets a value indicating whether the customer is active /// </summary> public virtual bool Active { get; set; } /// <summary> /// Gets or sets a value indicating whether the customer has been deleted /// </summary> public virtual bool Deleted { get; set; } /// <summary> /// Gets or sets a value indicating whether the customer account is system /// </summary> public virtual bool IsSystemAccount { get; set; } /// <summary> /// Gets or sets the customer system name /// </summary> public virtual string SystemName { get; set; } /// <summary> /// Gets or sets the last IP address /// </summary> public virtual string LastIpAddress { get; set; } /// <summary> /// Gets or sets the date and time of entity creation /// </summary> public virtual DateTime CreatedOnUtc { get; set; } /// <summary> /// Gets or sets the date and time of last login /// </summary> public virtual DateTime? LastLoginDateUtc { get; set; } /// <summary> /// Gets or sets the date and time of last activity /// </summary> public virtual DateTime LastActivityDateUtc { get; set; } #region Custom properties /// <summary> /// Gets the tax display type /// </summary> public virtual TaxDisplayType TaxDisplayType { get { return (TaxDisplayType)this.TaxDisplayTypeId; } set { this.TaxDisplayTypeId = (int)value; } } /// <summary> /// Gets the VAT number status /// </summary> public virtual VatNumberStatus VatNumberStatus { get { return (VatNumberStatus)this.VatNumberStatusId; } set { this.VatNumberStatusId = (int)value; } } #endregion #region Navigation properties /// <summary> /// Gets or sets the affiliate /// </summary> public virtual Affiliate Affiliate { get; set; } /// <summary> /// Gets or sets the language /// </summary> public virtual Language Language { get; set; } /// <summary> /// Gets or sets the currency /// </summary> public virtual Currency Currency { get; set; } /// <summary> /// Gets or sets customer generated content /// </summary> public virtual ICollection<ExternalAuthenticationRecord> ExternalAuthenticationRecords { get { return _externalAuthenticationRecords ?? (_externalAuthenticationRecords = new List<ExternalAuthenticationRecord>()); } protected set { _externalAuthenticationRecords = value; } } /// <summary> /// Gets or sets customer generated content /// </summary> public virtual ICollection<CustomerContent> CustomerContent { get { return _customerContent ?? (_customerContent = new List<CustomerContent>()); } protected set { _customerContent = value; } } /// <summary> /// Gets or sets the customer roles /// </summary> public virtual ICollection<CustomerRole> CustomerRoles { get { return _customerRoles ?? (_customerRoles = new List<CustomerRole>()); } protected set { _customerRoles = value; } } /// <summary> /// Gets or sets shopping cart items /// </summary> public virtual ICollection<ShoppingCartItem> ShoppingCartItems { get { return _shoppingCartItems ?? (_shoppingCartItems = new List<ShoppingCartItem>()); } protected set { _shoppingCartItems = value; } } /// <summary> /// Gets or sets orders /// </summary> public virtual ICollection<Order> Orders { get { return _orders ?? (_orders = new List<Order>()); } protected set { _orders = value; } } /// <summary> /// Gets or sets reward points history /// </summary> public virtual ICollection<RewardPointsHistory> RewardPointsHistory { get { return _rewardPointsHistory ?? (_rewardPointsHistory = new List<RewardPointsHistory>()); } protected set { _rewardPointsHistory = value; } } /// <summary> /// Gets or sets return request of this customer /// </summary> public virtual ICollection<ReturnRequest> ReturnRequests { get { return _returnRequests ?? (_returnRequests = new List<ReturnRequest>()); } protected set { _returnRequests = value; } } /// <summary> /// Default billing address /// </summary> public virtual Address BillingAddress { get; set; } /// <summary> /// Default shipping address /// </summary> public virtual Address ShippingAddress { get; set; } /// <summary> /// Gets or sets customer addresses /// </summary> public virtual ICollection<Address> Addresses { get { return _addresses ?? (_addresses = new List<Address>()); } protected set { _addresses = value; } } /// <summary> /// Gets or sets the created forum topics /// </summary> public virtual ICollection<ForumTopic> ForumTopics { get { return _forumTopics ?? (_forumTopics = new List<ForumTopic>()); } protected set { _forumTopics = value; } } /// <summary> /// Gets or sets the created forum posts /// </summary> public virtual ICollection<ForumPost> ForumPosts { get { return _forumPosts ?? (_forumPosts = new List<ForumPost>()); } protected set { _forumPosts = value; } } #endregion #region Addresses public virtual void RemoveAddress(Address address) { if (this.Addresses.Contains(address)) { if (this.BillingAddress == address) this.BillingAddress = null; if (this.ShippingAddress == address) this.ShippingAddress = null; this.Addresses.Remove(address); } } #endregion #region Reward points public virtual void AddRewardPointsHistoryEntry(int points, string message = "", Order usedWithOrder = null, decimal usedAmount = 0M) { int newPointsBalance = this.GetRewardPointsBalance() + points; var rewardPointsHistory = new RewardPointsHistory() { Customer = this, UsedWithOrder = usedWithOrder, Points = points, PointsBalance = newPointsBalance, UsedAmount = usedAmount, Message = message, CreatedOnUtc = DateTime.UtcNow }; this.RewardPointsHistory.Add(rewardPointsHistory); } /// <summary> /// Gets reward points balance /// </summary> public virtual int GetRewardPointsBalance() { int result = 0; if (this.RewardPointsHistory.Count > 0) result = this.RewardPointsHistory.OrderByDescending(rph => rph.CreatedOnUtc).ThenByDescending(rph => rph.Id).FirstOrDefault().PointsBalance; return result; } #endregion #region Gift cards /// <summary> /// Gets coupon codes /// </summary> /// <returns>Coupon codes</returns> public virtual string[] ParseAppliedGiftCardCouponCodes() { string serializedGiftCartCouponCodes = this.GiftCardCouponCodes; var couponCodes = new List<string>(); if (String.IsNullOrEmpty(serializedGiftCartCouponCodes)) return couponCodes.ToArray(); try { var xmlDoc = new XmlDocument(); xmlDoc.LoadXml(serializedGiftCartCouponCodes); var nodeList1 = xmlDoc.SelectNodes(@"//GiftCardCouponCodes/CouponCode"); foreach (XmlNode node1 in nodeList1) { if (node1.Attributes != null && node1.Attributes["Code"] != null) { string code = node1.Attributes["Code"].InnerText.Trim(); couponCodes.Add(code); } } } catch (Exception exc) { Debug.Write(exc.ToString()); } return couponCodes.ToArray(); } /// <summary> /// Adds a coupon code /// </summary> /// <param name="couponCode">Coupon code</param> /// <returns>New coupon codes document</returns> public virtual void ApplyGiftCardCouponCode(string couponCode) { string result = string.Empty; try { var serializedGiftCartCouponCodes = this.GiftCardCouponCodes; couponCode = couponCode.Trim().ToLower(); var xmlDoc = new XmlDocument(); if (String.IsNullOrEmpty(serializedGiftCartCouponCodes)) { var element1 = xmlDoc.CreateElement("GiftCardCouponCodes"); xmlDoc.AppendChild(element1); } else { xmlDoc.LoadXml(serializedGiftCartCouponCodes); } var rootElement = (XmlElement)xmlDoc.SelectSingleNode(@"//GiftCardCouponCodes"); XmlElement element = null; //find existing var nodeList1 = xmlDoc.SelectNodes(@"//GiftCardCouponCodes/CouponCode"); foreach (XmlNode node1 in nodeList1) { if (node1.Attributes != null && node1.Attributes["Code"] != null) { string _couponCode = node1.Attributes["Code"].InnerText.Trim(); if (_couponCode.ToLower() == couponCode.ToLower()) { element = (XmlElement)node1; break; } } } //create new one if not found if (element == null) { element = xmlDoc.CreateElement("CouponCode"); element.SetAttribute("Code", couponCode); rootElement.AppendChild(element); } result = xmlDoc.OuterXml; } catch (Exception exc) { Debug.Write(exc.ToString()); } //apply new value this.GiftCardCouponCodes = result; } /// <summary> /// Removes a coupon code /// </summary> /// <param name="couponCode">Coupon code to remove</param> /// <returns>New coupon codes document</returns> public virtual void RemoveGiftCardCouponCode(string couponCode) { //get applied coupon codes var existingCouponCodes = ParseAppliedGiftCardCouponCodes(); //clear them this.GiftCardCouponCodes = string.Empty; //save again except removed one foreach (string existingCouponCode in existingCouponCodes) if (!existingCouponCode.Equals(couponCode, StringComparison.InvariantCultureIgnoreCase)) ApplyGiftCardCouponCode(existingCouponCode); } #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 ConvertToUInt32Vector128UInt32() { var test = new SimdScalarUnaryOpConvertTest__ConvertToUInt32Vector128UInt32(); 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 class works test.RunClassLclFldScenario(); // Validates passing an instance member of a class works test.RunClassFldScenario(); // Validates passing the field of a local struct works test.RunStructLclFldScenario(); // Validates passing an instance member of a struct works test.RunStructFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimdScalarUnaryOpConvertTest__ConvertToUInt32Vector128UInt32 { private struct TestStruct { public Vector128<UInt32> _fld; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref testStruct._fld), ref Unsafe.As<UInt32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); return testStruct; } public void RunStructFldScenario(SimdScalarUnaryOpConvertTest__ConvertToUInt32Vector128UInt32 testClass) { var result = Sse2.ConvertToUInt32(_fld); testClass.ValidateResult(_fld, result); } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<UInt32>>() / sizeof(UInt32); private static UInt32[] _data = new UInt32[Op1ElementCount]; private static Vector128<UInt32> _clsVar; private Vector128<UInt32> _fld; private SimdScalarUnaryOpTest__DataTable<UInt32> _dataTable; static SimdScalarUnaryOpConvertTest__ConvertToUInt32Vector128UInt32() { for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _clsVar), ref Unsafe.As<UInt32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); } public SimdScalarUnaryOpConvertTest__ConvertToUInt32Vector128UInt32() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _fld), ref Unsafe.As<UInt32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt32(); } _dataTable = new SimdScalarUnaryOpTest__DataTable<UInt32>(_data, LargestVectorSize); } public bool IsSupported => Sse2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Sse2.ConvertToUInt32( Unsafe.Read<Vector128<UInt32>>(_dataTable.inArrayPtr) ); ValidateResult(_dataTable.inArrayPtr, result); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Sse2.ConvertToUInt32( Sse2.LoadVector128((UInt32*)(_dataTable.inArrayPtr)) ); ValidateResult(_dataTable.inArrayPtr, result); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Sse2.ConvertToUInt32( Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArrayPtr)) ); ValidateResult(_dataTable.inArrayPtr, result); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Sse2).GetMethod(nameof(Sse2.ConvertToUInt32), new Type[] { typeof(Vector128<UInt32>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<UInt32>>(_dataTable.inArrayPtr) }); ValidateResult(_dataTable.inArrayPtr, (UInt32)(result)); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Sse2).GetMethod(nameof(Sse2.ConvertToUInt32), new Type[] { typeof(Vector128<UInt32>) }) .Invoke(null, new object[] { Sse2.LoadVector128((UInt32*)(_dataTable.inArrayPtr)) }); ValidateResult(_dataTable.inArrayPtr, (UInt32)(result)); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Sse2).GetMethod(nameof(Sse2.ConvertToUInt32), new Type[] { typeof(Vector128<UInt32>) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArrayPtr)) }); ValidateResult(_dataTable.inArrayPtr, (UInt32)(result)); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Sse2.ConvertToUInt32( _clsVar ); ValidateResult(_clsVar, result); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var firstOp = Unsafe.Read<Vector128<UInt32>>(_dataTable.inArrayPtr); var result = Sse2.ConvertToUInt32(firstOp); ValidateResult(firstOp, result); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var firstOp = Sse2.LoadVector128((UInt32*)(_dataTable.inArrayPtr)); var result = Sse2.ConvertToUInt32(firstOp); ValidateResult(firstOp, result); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var firstOp = Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArrayPtr)); var result = Sse2.ConvertToUInt32(firstOp); ValidateResult(firstOp, result); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimdScalarUnaryOpConvertTest__ConvertToUInt32Vector128UInt32(); var result = Sse2.ConvertToUInt32(test._fld); ValidateResult(test._fld, result); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Sse2.ConvertToUInt32(_fld); ValidateResult(_fld, result); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Sse2.ConvertToUInt32(test._fld); ValidateResult(test._fld, result); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<UInt32> firstOp, UInt32 result, [CallerMemberName] string method = "") { UInt32[] inArray = new UInt32[Op1ElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray[0]), firstOp); ValidateResult(inArray, result, method); } private void ValidateResult(void* firstOp, UInt32 result, [CallerMemberName] string method = "") { UInt32[] inArray = new UInt32[Op1ElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); ValidateResult(inArray, result, method); } private void ValidateResult(UInt32[] firstOp, UInt32 result, [CallerMemberName] string method = "") { bool succeeded = true; if (firstOp[0] != result) { succeeded = false; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Sse2)}.{nameof(Sse2.ConvertToUInt32)}<UInt32>(Vector128<UInt32>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" result: result"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using DereTore.Common; namespace DereTore.Exchange.Audio.HCA { public sealed class HcaAudioStream : HcaAudioStreamBase { public HcaAudioStream(Stream baseStream) : this(baseStream, DecodeParams.Default) { } public HcaAudioStream(Stream baseStream, AudioParams audioParams) : this(baseStream, DecodeParams.Default, audioParams) { } public HcaAudioStream(Stream baseStream, DecodeParams decodeParams) : this(baseStream, decodeParams, AudioParams.Default) { } public HcaAudioStream(Stream baseStream, DecodeParams decodeParams, AudioParams audioParams) : base(baseStream, decodeParams) { var decoder = new HcaDecoder(baseStream, decodeParams); _decoder = decoder; _audioParams = audioParams; var buffer = new byte[GetTotalAfterDecodingWaveDataSize()]; _memoryCache = new MemoryStream(buffer, true); _decodedBlocks = new Dictionary<long, long>(); _decodeBuffer = new byte[decoder.GetMinWaveDataBufferSize()]; _hasLoop = decoder.HcaInfo.LoopFlag; PrepareDecoding(); } public override long Seek(long offset, SeekOrigin origin) { if (!EnsureNotDisposed()) { return 0; } switch (origin) { case SeekOrigin.Begin: Position = offset; break; case SeekOrigin.Current: Position = Position + offset; break; case SeekOrigin.End: Position = Length - offset; break; default: break; } return Position; } public override int Read(byte[] buffer, int offset, int count) { if (!EnsureNotDisposed()) { return 0; } if (!HasMoreData) { return 0; } if (offset < 0 || offset >= buffer.Length) { throw new ArgumentOutOfRangeException(nameof(offset)); } if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count)); } if (count == 0) { return 0; } var hcaInfo = HcaInfo; var memoryCache = _memoryCache; var position = Position; var read = 0; if (position < hcaInfo.DataOffset) { var maxCopy = Math.Min(Math.Min((int)(hcaInfo.DataOffset - position), count), buffer.Length - offset); if (maxCopy == 0) { return 0; } memoryCache.Seek(position, SeekOrigin.Begin); memoryCache.Read(buffer, offset, maxCopy); count -= maxCopy; offset += maxCopy; position += maxCopy; if (count <= 0 || offset >= buffer.Length) { Position = position; return maxCopy; } read += maxCopy; } var audioParams = _audioParams; var length = Length; count = HasLoop && audioParams.InfiniteLoop ? Math.Min(count, buffer.Length - offset) : Math.Min((int)(length - position), count); if (_decodedBlocks.Count < hcaInfo.BlockCount) { if (HasLoop && audioParams.SimulatedLoopCount > 0) { EnsureSoundDataDecodedWithLoops(position, count); } else { EnsureSoundDataDecoded(position, count); } } var headerSize = _headerSize; var waveBlockSize = _decoder.GetMinWaveDataBufferSize(); while (count > 0) { var positionNonLooped = MapPosToNonLoopedWaveStreamPos(position); memoryCache.Seek(positionNonLooped, SeekOrigin.Begin); var shouldRead = Math.Min(count, waveBlockSize - ((int)(positionNonLooped - headerSize) % waveBlockSize)); if (shouldRead == 0) { break; } var realRead = memoryCache.Read(buffer, offset, shouldRead); Debug.Assert(realRead == shouldRead); count -= realRead; offset += realRead; read += realRead; position += realRead; } Position = position; return read; } public override bool CanSeek => true; public override long Length { get { if (!EnsureNotDisposed()) { return 0; } if (_length != null) { return _length.Value; } var audioParams = _audioParams; if (HasLoop && audioParams.InfiniteLoop) { _length = long.MaxValue; return _length.Value; } var hcaInfo = HcaInfo; long totalLength = 0; if (_audioParams.OutputWaveHeader) { totalLength += _headerSize; } var waveDataBlockSize = _decoder.GetMinWaveDataBufferSize(); totalLength += waveDataBlockSize * hcaInfo.BlockCount; if (HasLoop && audioParams.SimulatedLoopCount > 0) { var loopedBlockCount = hcaInfo.LoopEnd - hcaInfo.LoopStart + 1; totalLength += waveDataBlockSize * loopedBlockCount * audioParams.SimulatedLoopCount; } _length = totalLength; return _length.Value; } } public override long Position { get { return EnsureNotDisposed() ? _position : 0; } set { EnsureNotDisposed(); if (value < 0 || value > Length) { throw new ArgumentOutOfRangeException(nameof(value)); } _position = value; } } public override float LengthInSeconds => HcaHelper.CalculateLengthInSeconds(HcaInfo, _audioParams.SimulatedLoopCount, _audioParams.InfiniteLoop); public override uint LengthInSamples => HcaHelper.CalculateLengthInSamples(HcaInfo, _audioParams.SimulatedLoopCount, _audioParams.InfiniteLoop); protected override void Dispose(bool disposing) { if (!IsDisposed) { _memoryCache.Dispose(); } base.Dispose(disposing); } protected override bool HasMoreData => Position < Length; private void EnsureSoundDataDecoded(long waveDataOffset, int byteCount) { var decoder = _decoder; var headerSize = _headerSize; var blockSize = decoder.GetMinWaveDataBufferSize(); var startBlockIndex = (uint)((waveDataOffset - headerSize) / blockSize); var hcaInfo = HcaInfo; var endBlockIndex = (uint)((waveDataOffset + byteCount - headerSize) / blockSize); endBlockIndex = Math.Min(endBlockIndex, hcaInfo.BlockCount - 1); for (var i = startBlockIndex; i <= endBlockIndex; ++i) { EnsureDecodeOneBlock(i); } } private void EnsureSoundDataDecodedWithLoops(long waveDataOffset, int byteCount) { waveDataOffset = MapPosToNonLoopedWaveStreamPos(waveDataOffset); var decoder = _decoder; var headerSize = _headerSize; var waveBlockSize = decoder.GetMinWaveDataBufferSize(); var startBlockIndex = (uint)((waveDataOffset - headerSize) / waveBlockSize); var waveDataEnd = waveDataOffset + byteCount; var hcaInfo = HcaInfo; var audioParams = _audioParams; var decodedSize = (waveDataOffset - headerSize) / waveBlockSize * waveBlockSize; // For those before or in the loop range... if (audioParams.InfiniteLoop || startBlockIndex <= hcaInfo.LoopEnd + (hcaInfo.LoopEnd - hcaInfo.LoopStart + 1) * audioParams.SimulatedLoopCount) { var blockIndex = startBlockIndex; var executed = false; while (true) { if (executed && blockIndex == startBlockIndex) { if (audioParams.InfiniteLoop) { return; } else { break; } } if (!audioParams.InfiniteLoop && decodedSize >= waveDataEnd) { break; } EnsureDecodeOneBlock(blockIndex); decodedSize += waveBlockSize; ++blockIndex; if (blockIndex > hcaInfo.LoopEnd) { blockIndex = hcaInfo.LoopStart; } executed = true; } } // And those following it. if (audioParams.InfiniteLoop) { return; } var endBlockIndex = hcaInfo.LoopEnd + (hcaInfo.LoopEnd - hcaInfo.LoopStart + 1) * audioParams.SimulatedLoopCount; var startOfAfterLoopRegion = endBlockIndex * waveBlockSize; if (waveDataEnd >= startOfAfterLoopRegion) { for (var blockIndex = hcaInfo.LoopEnd + 1; blockIndex < hcaInfo.BlockCount && decodedSize < waveDataEnd; ++blockIndex) { EnsureDecodeOneBlock(blockIndex); decodedSize += waveBlockSize; } } } private void EnsureDecodeOneBlock(uint blockIndex) { var decodedBlocks = _decodedBlocks; if (decodedBlocks.ContainsKey(blockIndex)) { return; } var decodeBuffer = _decodeBuffer; var decoder = _decoder; decoder.DecodeBlock(decodeBuffer, blockIndex); var positionInOutputStream = _headerSize + decoder.GetMinWaveDataBufferSize() * blockIndex; var memoryCache = _memoryCache; memoryCache.Seek(positionInOutputStream, SeekOrigin.Begin); memoryCache.WriteBytes(decodeBuffer); decodedBlocks.Add(blockIndex, positionInOutputStream); } private long MapPosToNonLoopedWaveStreamPos(long requestedPosition) { if (!HasLoop) { return requestedPosition; } var hcaInfo = HcaInfo; var waveBlockSize = _decoder.GetMinWaveDataBufferSize(); var headerSize = _headerSize; var relativeDataPosition = requestedPosition - headerSize; var endLoopDataPosition = (hcaInfo.LoopEnd + 1) * waveBlockSize; if (relativeDataPosition < endLoopDataPosition) { return requestedPosition; } var startLoopDataPosition = hcaInfo.LoopStart * waveBlockSize; var loopLength = endLoopDataPosition - startLoopDataPosition; var audioParams = _audioParams; if (audioParams.InfiniteLoop) { return headerSize + startLoopDataPosition + (relativeDataPosition - startLoopDataPosition) % loopLength; } var extendedLength = endLoopDataPosition + loopLength * audioParams.SimulatedLoopCount; if (relativeDataPosition < extendedLength) { return headerSize + startLoopDataPosition + (relativeDataPosition - startLoopDataPosition) % loopLength; } else { return headerSize + endLoopDataPosition + (relativeDataPosition - extendedLength); } } private bool HasLoop => _hasLoop; private void PrepareDecoding() { var decoder = _decoder; var memoryCache = _memoryCache; if (_audioParams.OutputWaveHeader) { var waveHeaderBufferSize = decoder.GetMinWaveHeaderBufferSize(); var waveHeaderBuffer = new byte[waveHeaderBufferSize]; decoder.WriteWaveHeader(waveHeaderBuffer, _audioParams); memoryCache.WriteBytes(waveHeaderBuffer); _headerSize = waveHeaderBufferSize; } else { _headerSize = 0; } memoryCache.Position = 0; } private int GetTotalAfterDecodingWaveDataSize() { var hcaInfo = HcaInfo; var totalLength = 0; if (_audioParams.OutputWaveHeader) { totalLength += _decoder.GetMinWaveHeaderBufferSize(); } totalLength += _decoder.GetMinWaveDataBufferSize() * (int)hcaInfo.BlockCount; return totalLength; } private readonly AudioParams _audioParams; private int _headerSize; private readonly MemoryStream _memoryCache; private readonly Dictionary<long, long> _decodedBlocks; private long? _length; private long _position; private readonly byte[] _decodeBuffer; private readonly bool _hasLoop; } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading; using System.Threading.Tasks; using Hyak.Common; using Hyak.Common.Internals; using Microsoft.Azure.Management.Insights; using Microsoft.Azure.Management.Insights.Models; using Newtonsoft.Json.Linq; namespace Microsoft.Azure.Management.Insights { /// <summary> /// Operations for managing log profiles. /// </summary> internal partial class LogProfilesOperations : IServiceOperations<InsightsManagementClient>, ILogProfilesOperations { /// <summary> /// Initializes a new instance of the LogProfilesOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal LogProfilesOperations(InsightsManagementClient client) { this._client = client; } private InsightsManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.Azure.Management.Insights.InsightsManagementClient. /// </summary> public InsightsManagementClient Client { get { return this._client; } } /// <summary> /// Create or update the log profile. /// </summary> /// <param name='name'> /// Required. The name of the log profile. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Generic empty response. We only pass it to ensure json error /// handling /// </returns> public async Task<EmptyResponse> CreateOrUpdateAsync(string name, LogProfileCreatOrUpdateParameters parameters, CancellationToken cancellationToken) { // Validate if (name == null) { throw new ArgumentNullException("name"); } if (parameters == null) { throw new ArgumentNullException("parameters"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("name", name); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "CreateOrUpdateAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/providers/microsoft.insights/logprofiles/"; url = url + Uri.EscapeDataString(name); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2016-03-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 httpRequest.Headers.Add("Accept", "application/json"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; JToken requestDoc = null; JObject logProfileCreatOrUpdateParametersValue = new JObject(); requestDoc = logProfileCreatOrUpdateParametersValue; if (parameters.Properties != null) { JObject propertiesValue = new JObject(); logProfileCreatOrUpdateParametersValue["properties"] = propertiesValue; if (parameters.Properties.StorageAccountId != null) { propertiesValue["storageAccountId"] = parameters.Properties.StorageAccountId; } if (parameters.Properties.ServiceBusRuleId != null) { propertiesValue["serviceBusRuleId"] = parameters.Properties.ServiceBusRuleId; } if (parameters.Properties.Locations != null) { if (parameters.Properties.Locations is ILazyCollection == false || ((ILazyCollection)parameters.Properties.Locations).IsInitialized) { JArray locationsArray = new JArray(); foreach (string locationsItem in parameters.Properties.Locations) { locationsArray.Add(locationsItem); } propertiesValue["locations"] = locationsArray; } } if (parameters.Properties.Categories != null) { if (parameters.Properties.Categories is ILazyCollection == false || ((ILazyCollection)parameters.Properties.Categories).IsInitialized) { JArray categoriesArray = new JArray(); foreach (string categoriesItem in parameters.Properties.Categories) { categoriesArray.Add(categoriesItem); } propertiesValue["categories"] = categoriesArray; } } if (parameters.Properties.RetentionPolicy != null) { JObject retentionPolicyValue = new JObject(); propertiesValue["retentionPolicy"] = retentionPolicyValue; retentionPolicyValue["enabled"] = parameters.Properties.RetentionPolicy.Enabled; retentionPolicyValue["days"] = parameters.Properties.RetentionPolicy.Days; } } requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json"); // 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 EmptyResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Created || statusCode == HttpStatusCode.Accepted) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new EmptyResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { } } 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> /// Deletes the log profile. /// </summary> /// <param name='name'> /// Required. The name of the log profile. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Generic empty response. We only pass it to ensure json error /// handling /// </returns> public async Task<EmptyResponse> DeleteAsync(string name, CancellationToken cancellationToken) { // Validate if (name == null) { throw new ArgumentNullException("name"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("name", name); 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 + "/providers/microsoft.insights/logprofiles/"; url = url + Uri.EscapeDataString(name); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2016-03-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 httpRequest.Headers.Add("Accept", "application/json"); // 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 EmptyResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new EmptyResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { } } 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 log profile. /// </summary> /// <param name='name'> /// Required. The name of the log profile. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public async Task<LogProfileGetResponse> GetAsync(string name, CancellationToken cancellationToken) { // Validate if (name == null) { throw new ArgumentNullException("name"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("name", name); 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 + "/providers/microsoft.insights/logprofiles/"; url = url + Uri.EscapeDataString(name); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2016-03-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 httpRequest.Headers.Add("Accept", "application/json"); // 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 LogProfileGetResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new LogProfileGetResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken idValue = responseDoc["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); result.Id = idInstance; } JToken nameValue = responseDoc["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); result.Name = nameInstance; } JToken propertiesValue = responseDoc["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { LogProfile propertiesInstance = new LogProfile(); result.Properties = propertiesInstance; JToken storageAccountIdValue = propertiesValue["storageAccountId"]; if (storageAccountIdValue != null && storageAccountIdValue.Type != JTokenType.Null) { string storageAccountIdInstance = ((string)storageAccountIdValue); propertiesInstance.StorageAccountId = storageAccountIdInstance; } JToken serviceBusRuleIdValue = propertiesValue["serviceBusRuleId"]; if (serviceBusRuleIdValue != null && serviceBusRuleIdValue.Type != JTokenType.Null) { string serviceBusRuleIdInstance = ((string)serviceBusRuleIdValue); propertiesInstance.ServiceBusRuleId = serviceBusRuleIdInstance; } JToken locationsArray = propertiesValue["locations"]; if (locationsArray != null && locationsArray.Type != JTokenType.Null) { foreach (JToken locationsValue in ((JArray)locationsArray)) { propertiesInstance.Locations.Add(((string)locationsValue)); } } JToken categoriesArray = propertiesValue["categories"]; if (categoriesArray != null && categoriesArray.Type != JTokenType.Null) { foreach (JToken categoriesValue in ((JArray)categoriesArray)) { propertiesInstance.Categories.Add(((string)categoriesValue)); } } JToken retentionPolicyValue = propertiesValue["retentionPolicy"]; if (retentionPolicyValue != null && retentionPolicyValue.Type != JTokenType.Null) { RetentionPolicy retentionPolicyInstance = new RetentionPolicy(); propertiesInstance.RetentionPolicy = retentionPolicyInstance; JToken enabledValue = retentionPolicyValue["enabled"]; if (enabledValue != null && enabledValue.Type != JTokenType.Null) { bool enabledInstance = ((bool)enabledValue); retentionPolicyInstance.Enabled = enabledInstance; } JToken daysValue = retentionPolicyValue["days"]; if (daysValue != null && daysValue.Type != JTokenType.Null) { int daysInstance = ((int)daysValue); retentionPolicyInstance.Days = daysInstance; } } } } } 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> /// List the log profiles. /// </summary> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public async Task<LogProfileListResponse> ListAsync(CancellationToken cancellationToken) { // Validate // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); 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 + "/providers/microsoft.insights/logprofiles"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2016-03-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 httpRequest.Headers.Add("Accept", "application/json"); // 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 LogProfileListResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new LogProfileListResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { LogProfileCollection logProfileCollectionInstance = new LogProfileCollection(); result.LogProfileCollection = logProfileCollectionInstance; JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { LogProfileResource logProfileResourceInstance = new LogProfileResource(); logProfileCollectionInstance.Value.Add(logProfileResourceInstance); JToken idValue = valueValue["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); logProfileResourceInstance.Id = idInstance; } JToken nameValue = valueValue["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); logProfileResourceInstance.Name = nameInstance; } JToken propertiesValue = valueValue["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { LogProfile propertiesInstance = new LogProfile(); logProfileResourceInstance.Properties = propertiesInstance; JToken storageAccountIdValue = propertiesValue["storageAccountId"]; if (storageAccountIdValue != null && storageAccountIdValue.Type != JTokenType.Null) { string storageAccountIdInstance = ((string)storageAccountIdValue); propertiesInstance.StorageAccountId = storageAccountIdInstance; } JToken serviceBusRuleIdValue = propertiesValue["serviceBusRuleId"]; if (serviceBusRuleIdValue != null && serviceBusRuleIdValue.Type != JTokenType.Null) { string serviceBusRuleIdInstance = ((string)serviceBusRuleIdValue); propertiesInstance.ServiceBusRuleId = serviceBusRuleIdInstance; } JToken locationsArray = propertiesValue["locations"]; if (locationsArray != null && locationsArray.Type != JTokenType.Null) { foreach (JToken locationsValue in ((JArray)locationsArray)) { propertiesInstance.Locations.Add(((string)locationsValue)); } } JToken categoriesArray = propertiesValue["categories"]; if (categoriesArray != null && categoriesArray.Type != JTokenType.Null) { foreach (JToken categoriesValue in ((JArray)categoriesArray)) { propertiesInstance.Categories.Add(((string)categoriesValue)); } } JToken retentionPolicyValue = propertiesValue["retentionPolicy"]; if (retentionPolicyValue != null && retentionPolicyValue.Type != JTokenType.Null) { RetentionPolicy retentionPolicyInstance = new RetentionPolicy(); propertiesInstance.RetentionPolicy = retentionPolicyInstance; JToken enabledValue = retentionPolicyValue["enabled"]; if (enabledValue != null && enabledValue.Type != JTokenType.Null) { bool enabledInstance = ((bool)enabledValue); retentionPolicyInstance.Enabled = enabledInstance; } JToken daysValue = retentionPolicyValue["days"]; if (daysValue != null && daysValue.Type != JTokenType.Null) { int daysInstance = ((int)daysValue); retentionPolicyInstance.Days = daysInstance; } } } } } } } 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(); } } } } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Management.Automation.Internal; namespace System.Management.Automation.Provider { #region ItemCmdletProvider /// <summary> /// The base class for Cmdlet providers that expose an item as an MSH path. /// </summary> /// <remarks> /// The ItemCmdletProvider class is a base class that a provider derives from to /// inherit a set of methods that allows the Monad engine /// to provide a core set of commands for getting and setting of data on one or /// more items. A provider should derive from this class if they want /// to take advantage of the item core commands that are /// already implemented by the Monad engine. This allows users to have common /// commands and semantics across multiple providers. /// </remarks> public abstract class ItemCmdletProvider : DriveCmdletProvider { #region internal methods /// <summary> /// Internal wrapper for the GetItem protected method. It is called instead /// of the protected method that is overridden by derived classes so that the /// context of the command can be set. /// </summary> /// <param name="path"> /// The path to the item to retrieve. /// </param> /// <param name="context"> /// The context under which this method is being called. /// </param> /// <returns> /// Nothing is returned, but all objects should be written to the WriteObject method. /// </returns> internal void GetItem(string path, CmdletProviderContext context) { Context = context; // Call virtual method GetItem(path); } /// <summary> /// Gives the provider to attach additional parameters to /// the get-item cmdlet. /// </summary> /// <param name="path"> /// If the path was specified on the command line, this is the path /// to the item to get the dynamic parameters for. /// </param> /// <param name="context"> /// The context under which this method is being called. /// </param> /// <returns> /// Overrides of this method should return an object that has properties and fields decorated with /// parsing attributes similar to a cmdlet class or a /// <see cref="System.Management.Automation.RuntimeDefinedParameterDictionary"/>. /// /// The default implementation returns null. (no additional parameters) /// </returns> internal object GetItemDynamicParameters(string path, CmdletProviderContext context) { Context = context; return GetItemDynamicParameters(path); } /// <summary> /// Internal wrapper for the SetItem protected method. It is called instead /// of the protected method that is overridden by derived classes so that the /// context of the command can be set. /// </summary> /// <param name="path"> /// The path to the item to set. /// </param> /// <param name="value"> /// The value of the item specified by the path. /// </param> /// <param name="context"> /// The context under which this method is being called. /// </param> /// <returns> /// The item that was set at the specified path. /// </returns> internal void SetItem( string path, object value, CmdletProviderContext context) { providerBaseTracer.WriteLine("ItemCmdletProvider.SetItem"); Context = context; // Call virtual method SetItem(path, value); } /// <summary> /// Gives the provider to attach additional parameters to /// the set-item cmdlet. /// </summary> /// <param name="path"> /// If the path was specified on the command line, this is the path /// to the item to get the dynamic parameters for. /// </param> /// <param name="value"> /// The value of the item specified by the path. /// </param> /// <param name="context"> /// The context under which this method is being called. /// </param> /// <returns> /// Overrides of this method should return an object that has properties and fields decorated with /// parsing attributes similar to a cmdlet class or a /// <see cref="System.Management.Automation.RuntimeDefinedParameterDictionary"/>. /// /// The default implementation returns null. (no additional parameters) /// </returns> internal object SetItemDynamicParameters( string path, object value, CmdletProviderContext context) { Context = context; return SetItemDynamicParameters(path, value); } /// <summary> /// Internal wrapper for the ClearItem protected method. It is called instead /// of the protected method that is overridden by derived classes so that the /// context of the command can be set. /// </summary> /// <param name="path"> /// The path to the item to clear. /// </param> /// <param name="context"> /// The context under which this method is being called. /// </param> internal void ClearItem( string path, CmdletProviderContext context) { providerBaseTracer.WriteLine("ItemCmdletProvider.ClearItem"); Context = context; // Call virtual method ClearItem(path); } /// <summary> /// Gives the provider to attach additional parameters to /// the clear-item cmdlet. /// </summary> /// <param name="path"> /// If the path was specified on the command line, this is the path /// to the item to get the dynamic parameters for. /// </param> /// <param name="context"> /// The context under which this method is being called. /// </param> /// <returns> /// Overrides of this method should return an object that has properties and fields decorated with /// parsing attributes similar to a cmdlet class or a /// <see cref="System.Management.Automation.RuntimeDefinedParameterDictionary"/>. /// /// The default implementation returns null. (no additional parameters) /// </returns> internal object ClearItemDynamicParameters( string path, CmdletProviderContext context) { Context = context; return ClearItemDynamicParameters(path); } /// <summary> /// Internal wrapper for the InvokeDefaultAction protected method. It is called instead /// of the protected method that is overridden by derived classes so that the /// context of the command can be set. /// </summary> /// <param name="path"> /// The path to the item to perform the default action on. /// </param> /// <param name="context"> /// The context under which this method is being called. /// </param> internal void InvokeDefaultAction( string path, CmdletProviderContext context) { providerBaseTracer.WriteLine("ItemCmdletProvider.InvokeDefaultAction"); Context = context; // Call virtual method InvokeDefaultAction(path); } /// <summary> /// Gives the provider to attach additional parameters to /// the invoke-item cmdlet. /// </summary> /// <param name="path"> /// If the path was specified on the command line, this is the path /// to the item to get the dynamic parameters for. /// </param> /// <param name="context"> /// The context under which this method is being called. /// </param> /// <returns> /// Overrides of this method should return an object that has properties and fields decorated with /// parsing attributes similar to a cmdlet class or a /// <see cref="System.Management.Automation.RuntimeDefinedParameterDictionary"/>. /// /// The default implementation returns null. (no additional parameters) /// </returns> internal object InvokeDefaultActionDynamicParameters( string path, CmdletProviderContext context) { Context = context; return InvokeDefaultActionDynamicParameters(path); } /// <summary> /// Internal wrapper for the Exists protected method. It is called instead /// of the protected method that is overridden by derived classes so that the /// context of the command can be set. /// </summary> /// <param name="path"> /// The path to the item to see if it exists. /// </param> /// <param name="context"> /// The context under which this method is being called. /// </param> /// <returns> /// True if the item exists, false otherwise. /// </returns> internal bool ItemExists(string path, CmdletProviderContext context) { Context = context; // Call virtual method bool itemExists = false; try { // Some providers don't expect non-valid path elements, and instead // throw an exception here. itemExists = ItemExists(path); } catch (Exception) { } return itemExists; } /// <summary> /// Gives the provider to attach additional parameters to /// the test-path cmdlet. /// </summary> /// <param name="path"> /// If the path was specified on the command line, this is the path /// to the item to get the dynamic parameters for. /// </param> /// <param name="context"> /// The context under which this method is being called. /// </param> /// <returns> /// Overrides of this method should return an object that has properties and fields decorated with /// parsing attributes similar to a cmdlet class or a /// <see cref="System.Management.Automation.RuntimeDefinedParameterDictionary"/>. /// /// The default implementation returns null. (no additional parameters) /// </returns> internal object ItemExistsDynamicParameters( string path, CmdletProviderContext context) { Context = context; return ItemExistsDynamicParameters(path); } /// <summary> /// Internal wrapper for the IsValidPath protected method. It is called instead /// of the protected method that is overridden by derived classes so that the /// context of the command can be set. /// </summary> /// <param name="path"> /// The path to check for validity. /// </param> /// <param name="context"> /// The context under which this method is being called. /// </param> /// <returns> /// True if the path is syntactically and semantically valid for the provider, or /// false otherwise. /// </returns> /// <remarks> /// This test should not verify the existence of the item at the path. It should /// only perform syntactic and semantic validation of the path. For instance, for /// the file system provider, that path should be canonicalized, syntactically verified, /// and ensure that the path does not refer to a device. /// </remarks> internal bool IsValidPath(string path, CmdletProviderContext context) { Context = context; // Call virtual method return IsValidPath(path); } /// <summary> /// Internal wrapper for the ExpandPath protected method. It is called instead /// of the protected method that is overridden by derived classes so that the /// context of the command can be set. Only called for providers that declare /// the ExpandWildcards capability. /// </summary> /// <param name="path"> /// The path to expand. Expansion must be consistent with the wildcarding /// rules of PowerShell's WildcardPattern class. /// </param> /// <param name="context"> /// The context under which this method is being called. /// </param> /// <returns> /// A list of provider paths that this path expands to. They must all exist. /// </returns> internal string[] ExpandPath(string path, CmdletProviderContext context) { Context = context; // Call virtual method return ExpandPath(path); } #endregion internal methods #region Protected methods /// <summary> /// Gets the item at the specified path. /// </summary> /// <param name="path"> /// The path to the item to retrieve. /// </param> /// <returns> /// Nothing is returned, but all objects should be written to the WriteItemObject method. /// </returns> /// <remarks> /// Providers override this method to give the user access to the provider objects using /// the get-item and get-childitem cmdlets. /// /// Providers that declare <see cref="System.Management.Automation.Provider.ProviderCapabilities"/> /// of ExpandWildcards, Filter, Include, or Exclude should ensure that the path passed meets those /// requirements by accessing the appropriate property from the base class. /// /// By default overrides of this method should not write objects that are generally hidden from /// the user unless the Force property is set to true. For instance, the FileSystem provider should /// not call WriteItemObject for hidden or system files unless the Force property is set to true. /// /// The default implementation of this method throws an <see cref="System.Management.Automation.PSNotSupportedException"/>. /// </remarks> protected virtual void GetItem(string path) { using (PSTransactionManager.GetEngineProtectionScope()) { throw PSTraceSource.NewNotSupportedException( SessionStateStrings.CmdletProvider_NotSupported); } } /// <summary> /// Gives the provider an opportunity to attach additional parameters to /// the get-item cmdlet. /// </summary> /// <param name="path"> /// If the path was specified on the command line, this is the path /// to the item to get the dynamic parameters for. /// </param> /// <returns> /// Overrides of this method should return an object that has properties and fields decorated with /// parsing attributes similar to a cmdlet class or a /// <see cref="System.Management.Automation.RuntimeDefinedParameterDictionary"/>. /// /// The default implementation returns null. (no additional parameters) /// </returns> protected virtual object GetItemDynamicParameters(string path) { using (PSTransactionManager.GetEngineProtectionScope()) { return null; } } /// <summary> /// Sets the item specified by the path. /// </summary> /// <param name="path"> /// The path to the item to set. /// </param> /// <param name="value"> /// The value of the item specified by the path. /// </param> /// <returns> /// Nothing. The item that was set should be passed to the WriteItemObject method. /// </returns> /// <remarks> /// Providers override this method to give the user the ability to modify provider objects using /// the set-item cmdlet. /// /// Providers that declare <see cref="System.Management.Automation.Provider.ProviderCapabilities"/> /// of ExpandWildcards, Filter, Include, or Exclude should ensure that the path passed meets those /// requirements by accessing the appropriate property from the base class. /// /// By default overrides of this method should not set or write objects that are generally hidden from /// the user unless the Force property is set to true. An error should be sent to the WriteError method if /// the path represents an item that is hidden from the user and Force is set to false. /// /// The default implementation of this method throws an <see cref="System.Management.Automation.PSNotSupportedException"/>. /// </remarks> protected virtual void SetItem( string path, object value) { using (PSTransactionManager.GetEngineProtectionScope()) { throw PSTraceSource.NewNotSupportedException( SessionStateStrings.CmdletProvider_NotSupported); } } /// <summary> /// Gives the provider an opportunity to attach additional parameters to /// the set-item cmdlet. /// </summary> /// <param name="path"> /// If the path was specified on the command line, this is the path /// to the item to get the dynamic parameters for. /// </param> /// <param name="value"> /// The value of the item specified by the path. /// </param> /// <returns> /// Overrides of this method should return an object that has properties and fields decorated with /// parsing attributes similar to a cmdlet class or a /// <see cref="System.Management.Automation.RuntimeDefinedParameterDictionary"/>. /// /// The default implementation returns null. (no additional parameters) /// </returns> protected virtual object SetItemDynamicParameters(string path, object value) { using (PSTransactionManager.GetEngineProtectionScope()) { return null; } } /// <summary> /// Clears the item specified by the path. /// </summary> /// <param name="path"> /// The path to the item to clear. /// </param> /// <returns> /// Nothing. The item that was cleared should be passed to the WriteItemObject method. /// </returns> /// <remarks> /// Providers override this method to give the user the ability to clear provider objects using /// the clear-item cmdlet. /// /// Providers that declare <see cref="System.Management.Automation.Provider.ProviderCapabilities"/> /// of ExpandWildcards, Filter, Include, or Exclude should ensure that the path passed meets those /// requirements by accessing the appropriate property from the base class. /// /// By default overrides of this method should not clear or write objects that are generally hidden from /// the user unless the Force property is set to true. An error should be sent to the WriteError method if /// the path represents an item that is hidden from the user and Force is set to false. /// /// The default implementation of this method throws an <see cref="System.Management.Automation.PSNotSupportedException"/>. /// </remarks> protected virtual void ClearItem( string path) { using (PSTransactionManager.GetEngineProtectionScope()) { throw PSTraceSource.NewNotSupportedException( SessionStateStrings.CmdletProvider_NotSupported); } } /// <summary> /// Gives the provider an opportunity to attach additional parameters to /// the clear-item cmdlet. /// </summary> /// <param name="path"> /// If the path was specified on the command line, this is the path /// to the item to get the dynamic parameters for. /// </param> /// <returns> /// Overrides of this method should return an object that has properties and fields decorated with /// parsing attributes similar to a cmdlet class or a /// <see cref="System.Management.Automation.RuntimeDefinedParameterDictionary"/>. /// /// The default implementation returns null. (no additional parameters) /// </returns> protected virtual object ClearItemDynamicParameters(string path) { using (PSTransactionManager.GetEngineProtectionScope()) { return null; } } /// <summary> /// Invokes the default action on the specified item. /// </summary> /// <param name="path"> /// The path to the item to perform the default action on. /// </param> /// <returns> /// Nothing. The item that was set should be passed to the WriteItemObject method. /// </returns> /// <remarks> /// The default implementation does nothing. /// /// Providers override this method to give the user the ability to invoke provider objects using /// the invoke-item cmdlet. Think of the invocation as a double click in the Windows Shell. This /// method provides a default action based on the path that was passed. /// /// Providers that declare <see cref="System.Management.Automation.Provider.ProviderCapabilities"/> /// of ExpandWildcards, Filter, Include, or Exclude should ensure that the path passed meets those /// requirements by accessing the appropriate property from the base class. /// /// By default overrides of this method should not invoke objects that are generally hidden from /// the user unless the Force property is set to true. An error should be sent to the WriteError method if /// the path represents an item that is hidden from the user and Force is set to false. /// </remarks> protected virtual void InvokeDefaultAction( string path) { using (PSTransactionManager.GetEngineProtectionScope()) { throw PSTraceSource.NewNotSupportedException( SessionStateStrings.CmdletProvider_NotSupported); } } /// <summary> /// Gives the provider an opportunity to attach additional parameters to /// the invoke-item cmdlet. /// </summary> /// <param name="path"> /// If the path was specified on the command line, this is the path /// to the item to get the dynamic parameters for. /// </param> /// <returns> /// Overrides of this method should return an object that has properties and fields decorated with /// parsing attributes similar to a cmdlet class or a /// <see cref="System.Management.Automation.RuntimeDefinedParameterDictionary"/>. /// /// The default implementation returns null. (no additional parameters) /// </returns> protected virtual object InvokeDefaultActionDynamicParameters(string path) { using (PSTransactionManager.GetEngineProtectionScope()) { return null; } } /// <summary> /// Determines if an item exists at the specified path. /// </summary> /// <param name="path"> /// The path to the item to see if it exists. /// </param> /// <returns> /// True if the item exists, false otherwise. /// </returns> /// <returns> /// Nothing. The item that was set should be passed to the WriteItemObject method. /// </returns> /// <remarks> /// Providers override this method to give the user the ability to check for the existence of provider objects using /// the set-item cmdlet. /// /// Providers that declare <see cref="System.Management.Automation.Provider.ProviderCapabilities"/> /// of ExpandWildcards, Filter, Include, or Exclude should ensure that the path passed meets those /// requirements by accessing the appropriate property from the base class. /// /// The implementation of this method should take into account any form of access to the object that may /// make it visible to the user. For instance, if a user has write access to a file in the file system /// provider bug not read access, the file still exists and the method should return true. Sometimes this /// may require checking the parent to see if the child can be enumerated. /// /// The default implementation of this method throws an <see cref="System.Management.Automation.PSNotSupportedException"/>. /// </remarks> protected virtual bool ItemExists(string path) { using (PSTransactionManager.GetEngineProtectionScope()) { throw PSTraceSource.NewNotSupportedException( SessionStateStrings.CmdletProvider_NotSupported); } } /// <summary> /// Gives the provider an opportunity to attach additional parameters to /// the test-path cmdlet. /// </summary> /// <param name="path"> /// If the path was specified on the command line, this is the path /// to the item to get the dynamic parameters for. /// </param> /// <returns> /// Overrides of this method should return an object that has properties and fields decorated with /// parsing attributes similar to a cmdlet class or a /// <see cref="System.Management.Automation.RuntimeDefinedParameterDictionary"/>. /// /// The default implementation returns null. (no additional parameters) /// </returns> protected virtual object ItemExistsDynamicParameters(string path) { using (PSTransactionManager.GetEngineProtectionScope()) { return null; } } /// <summary> /// Providers must override this method to verify the syntax and semantics /// of their paths. /// </summary> /// <param name="path"> /// The path to check for validity. /// </param> /// <returns> /// True if the path is syntactically and semantically valid for the provider, or /// false otherwise. /// </returns> /// <remarks> /// This test should not verify the existence of the item at the path. It should /// only perform syntactic and semantic validation of the path. For instance, for /// the file system provider, that path should be canonicalized, syntactically verified, /// and ensure that the path does not refer to a device. /// </remarks> protected abstract bool IsValidPath(string path); /// <summary> /// Expand a provider path that contains wildcards to a list of provider /// paths that the path represents.Only called for providers that declare /// the ExpandWildcards capability. /// </summary> /// <param name="path"> /// The path to expand. Expansion must be consistent with the wildcarding /// rules of PowerShell's WildcardPattern class. /// </param> /// <returns> /// A list of provider paths that this path expands to. They must all exist. /// </returns> protected virtual string[] ExpandPath(string path) { using (PSTransactionManager.GetEngineProtectionScope()) { return new string[] { path }; } } #endregion Protected methods } #endregion ItemCmdletProvider }
// ReSharper disable once CheckNamespace namespace Fluent { using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Globalization; using System.Linq; using System.Windows; using System.Windows.Automation.Peers; using System.Windows.Controls; using System.Windows.Markup; using Fluent.Collections; using Fluent.Extensions; using Fluent.Internal; using Fluent.Internal.KnownBoxes; /// <summary> /// Represents quick access toolbar /// </summary> [TemplatePart(Name = "PART_ShowAbove", Type = typeof(MenuItem))] [TemplatePart(Name = "PART_ShowBelow", Type = typeof(MenuItem))] [TemplatePart(Name = "PART_MenuPanel", Type = typeof(Panel))] [TemplatePart(Name = "PART_RootPanel", Type = typeof(Panel))] [ContentProperty(nameof(QuickAccessItems))] [TemplatePart(Name = "PART_MenuDownButton", Type = typeof(DropDownButton))] [TemplatePart(Name = "PART_ToolbarDownButton", Type = typeof(DropDownButton))] [TemplatePart(Name = "PART_ToolBarPanel", Type = typeof(Panel))] [TemplatePart(Name = "PART_ToolBarOverflowPanel", Type = typeof(Panel))] public class QuickAccessToolBar : Control, ILogicalChildSupport { #region Events /// <summary> /// Occured when items are added or removed from Quick Access toolbar /// </summary> public event NotifyCollectionChangedEventHandler ItemsChanged; #endregion #region Fields private DropDownButton toolBarDownButton; internal DropDownButton MenuDownButton { get; private set; } // Show above menu item private MenuItem showAbove; // Show below menu item private MenuItem showBelow; // Items of quick access menu private ItemCollectionWithLogicalTreeSupport<QuickAccessMenuItem> quickAccessItems; // Root panel private Panel rootPanel; // ToolBar panel private Panel toolBarPanel; // ToolBar overflow panel private Panel toolBarOverflowPanel; // Items of quick access menu private ObservableCollection<UIElement> items; private Size cachedConstraint; private int cachedNonOverflowItemsCount = -1; // Itemc collection was changed private bool itemsHadChanged; private double cachedMenuDownButtonWidth; private double cachedOverflowDownButtonWidth; #endregion #region Properties #region Items /// <summary> /// Gets items collection /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public ObservableCollection<UIElement> Items { get { if (this.items is null) { this.items = new ObservableCollection<UIElement>(); this.items.CollectionChanged += this.OnItemsCollectionChanged; } return this.items; } } private void OnItemsCollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { this.cachedNonOverflowItemsCount = this.GetNonOverflowItemsCount(this.DesiredSize.Width); this.UpdateHasOverflowItems(); this.itemsHadChanged = true; this.Refresh(); this.UpdateKeyTips(); if (e.OldItems != null) { foreach (var item in e.OldItems.OfType<FrameworkElement>()) { item.SizeChanged -= this.OnChildSizeChanged; } } if (e.NewItems != null) { foreach (var item in e.NewItems.OfType<FrameworkElement>()) { item.SizeChanged += this.OnChildSizeChanged; } } if (e.Action == NotifyCollectionChangedAction.Reset) { foreach (var item in this.Items.OfType<FrameworkElement>()) { item.SizeChanged -= this.OnChildSizeChanged; } } // Raise items changed event this.ItemsChanged?.Invoke(this, e); if (this.Items.Count == 0 && this.toolBarDownButton != null) { this.toolBarDownButton.IsDropDownOpen = false; } } private void OnChildSizeChanged(object sender, SizeChangedEventArgs e) { this.InvalidateMeasureOfTitleBar(); } #endregion #region HasOverflowItems /// <summary> /// Gets whether QuickAccessToolBar has overflow items /// </summary> public bool HasOverflowItems { get { return (bool)this.GetValue(HasOverflowItemsProperty); } private set { this.SetValue(HasOverflowItemsPropertyKey, value); } } // ReSharper disable once InconsistentNaming private static readonly DependencyPropertyKey HasOverflowItemsPropertyKey = DependencyProperty.RegisterReadOnly(nameof(HasOverflowItems), typeof(bool), typeof(QuickAccessToolBar), new PropertyMetadata(BooleanBoxes.FalseBox)); /// <summary>Identifies the <see cref="HasOverflowItems"/> dependency property.</summary> public static readonly DependencyProperty HasOverflowItemsProperty = HasOverflowItemsPropertyKey.DependencyProperty; #endregion #region QuickAccessItems /// <summary> /// Gets quick access menu items /// </summary> public ItemCollectionWithLogicalTreeSupport<QuickAccessMenuItem> QuickAccessItems { get { if (this.quickAccessItems is null) { this.quickAccessItems = new ItemCollectionWithLogicalTreeSupport<QuickAccessMenuItem>(this); this.quickAccessItems.CollectionChanged += this.OnQuickAccessItemsCollectionChanged; } return this.quickAccessItems; } } /// <summary> /// Handles collection of quick access menu items changes /// </summary> /// <param name="sender">Sender</param> /// <param name="e">The event data</param> private void OnQuickAccessItemsCollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (this.MenuDownButton is null) { return; } switch (e.Action) { case NotifyCollectionChangedAction.Add: foreach (var item in e.NewItems.OfType<QuickAccessMenuItem>()) { var index = this.QuickAccessItems.IndexOf(item); this.MenuDownButton.Items.Insert(index + 1, item); this.QuickAccessItems[index].InvalidateProperty(QuickAccessMenuItem.TargetProperty); } break; case NotifyCollectionChangedAction.Remove: foreach (var item in e.OldItems.OfType<QuickAccessMenuItem>()) { this.MenuDownButton.Items.Remove(item); item.InvalidateProperty(QuickAccessMenuItem.TargetProperty); } break; case NotifyCollectionChangedAction.Replace: foreach (var item in e.OldItems.OfType<QuickAccessMenuItem>()) { this.MenuDownButton.Items.Remove(item); item.InvalidateProperty(QuickAccessMenuItem.TargetProperty); } foreach (var item in e.NewItems.OfType<QuickAccessMenuItem>()) { var index = this.QuickAccessItems.IndexOf(item); this.MenuDownButton.Items.Insert(index + 1, item); this.QuickAccessItems[index].InvalidateProperty(QuickAccessMenuItem.TargetProperty); } break; } } #endregion #region ShowAboveRibbon /// <summary> /// Gets or sets whether quick access toolbar showes above ribbon /// </summary> public bool ShowAboveRibbon { get { return (bool)this.GetValue(ShowAboveRibbonProperty); } set { this.SetValue(ShowAboveRibbonProperty, value); } } /// <summary>Identifies the <see cref="ShowAboveRibbon"/> dependency property.</summary> public static readonly DependencyProperty ShowAboveRibbonProperty = DependencyProperty.Register(nameof(ShowAboveRibbon), typeof(bool), typeof(QuickAccessToolBar), new PropertyMetadata(BooleanBoxes.TrueBox)); #endregion #region CanQuickAccessLocationChanging /// <summary> /// Gets or sets whether user can change location of QAT /// </summary> public bool CanQuickAccessLocationChanging { get { return (bool)this.GetValue(CanQuickAccessLocationChangingProperty); } set { this.SetValue(CanQuickAccessLocationChangingProperty, value); } } /// <summary>Identifies the <see cref="CanQuickAccessLocationChanging"/> dependency property.</summary> public static readonly DependencyProperty CanQuickAccessLocationChangingProperty = DependencyProperty.Register(nameof(CanQuickAccessLocationChanging), typeof(bool), typeof(QuickAccessToolBar), new PropertyMetadata(BooleanBoxes.TrueBox)); #endregion #region DropDownVisibility /// <summary> /// Gets or sets whether the Menu-DropDown is visible or not. /// </summary> public bool IsMenuDropDownVisible { get { return (bool)this.GetValue(IsMenuDropDownVisibleProperty); } set { this.SetValue(IsMenuDropDownVisibleProperty, value); } } /// <summary>Identifies the <see cref="IsMenuDropDownVisible"/> dependency property.</summary> public static readonly DependencyProperty IsMenuDropDownVisibleProperty = DependencyProperty.Register(nameof(IsMenuDropDownVisible), typeof(bool), typeof(QuickAccessToolBar), new FrameworkPropertyMetadata(BooleanBoxes.TrueBox, FrameworkPropertyMetadataOptions.AffectsArrange | FrameworkPropertyMetadataOptions.AffectsMeasure, OnIsMenuDropDownVisibleChanged)); private static void OnIsMenuDropDownVisibleChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var control = (QuickAccessToolBar)d; if ((bool)e.NewValue == false) { control.cachedMenuDownButtonWidth = 0; } } #endregion DropDownVisibility #endregion #region Initialization /// <summary> /// Static constructor /// </summary> static QuickAccessToolBar() { DefaultStyleKeyProperty.OverrideMetadata(typeof(QuickAccessToolBar), new FrameworkPropertyMetadata(typeof(QuickAccessToolBar))); } /// <summary> /// Creates a new instance. /// </summary> public QuickAccessToolBar() { this.Loaded += (sender, args) => this.InvalidateMeasureOfTitleBar(); } #endregion #region Override /// <inheritdoc /> public override void OnApplyTemplate() { if (this.showAbove != null) { this.showAbove.Click -= this.OnShowAboveClick; } if (this.showBelow != null) { this.showBelow.Click -= this.OnShowBelowClick; } this.showAbove = this.GetTemplateChild("PART_ShowAbove") as MenuItem; this.showBelow = this.GetTemplateChild("PART_ShowBelow") as MenuItem; if (this.showAbove != null) { this.showAbove.Click += this.OnShowAboveClick; } if (this.showBelow != null) { this.showBelow.Click += this.OnShowBelowClick; } if (this.MenuDownButton != null) { foreach (var item in this.QuickAccessItems) { this.MenuDownButton.Items.Remove(item); item.InvalidateProperty(QuickAccessMenuItem.TargetProperty); } this.QuickAccessItems.AquireLogicalOwnership(); } this.MenuDownButton = this.GetTemplateChild("PART_MenuDownButton") as DropDownButton; if (this.MenuDownButton != null) { this.QuickAccessItems.ReleaseLogicalOwnership(); for (var i = 0; i < this.QuickAccessItems.Count; i++) { this.MenuDownButton.Items.Insert(i + 1, this.QuickAccessItems[i]); this.QuickAccessItems[i].InvalidateProperty(QuickAccessMenuItem.TargetProperty); } } this.toolBarDownButton = this.GetTemplateChild("PART_ToolbarDownButton") as DropDownButton; // ToolBar panels this.toolBarPanel = this.GetTemplateChild("PART_ToolBarPanel") as Panel; this.toolBarOverflowPanel = this.GetTemplateChild("PART_ToolBarOverflowPanel") as Panel; if (this.rootPanel != null) { this.RemoveLogicalChild(this.rootPanel); } this.rootPanel = this.GetTemplateChild("PART_RootPanel") as Panel; if (this.rootPanel != null) { this.AddLogicalChild(this.rootPanel); } // Clears cache this.cachedMenuDownButtonWidth = 0; this.cachedOverflowDownButtonWidth = 0; this.cachedNonOverflowItemsCount = this.GetNonOverflowItemsCount(this.ActualWidth); this.cachedConstraint = default; } /// <summary> /// Handles show below menu item click /// </summary> /// <param name="sender">Sender</param> /// <param name="e">The event data</param> private void OnShowBelowClick(object sender, RoutedEventArgs e) { this.ShowAboveRibbon = false; } /// <summary> /// Handles show above menu item click /// </summary> /// <param name="sender">Sender</param> /// <param name="e">The event data</param> private void OnShowAboveClick(object sender, RoutedEventArgs e) { this.ShowAboveRibbon = true; } /// <inheritdoc /> protected override Size MeasureOverride(Size constraint) { if (this.IsLoaded == false) { return base.MeasureOverride(constraint); } if ((this.cachedConstraint == constraint) && !this.itemsHadChanged) { return base.MeasureOverride(constraint); } var nonOverflowItemsCount = this.GetNonOverflowItemsCount(constraint.Width); if (this.itemsHadChanged == false && nonOverflowItemsCount == this.cachedNonOverflowItemsCount) { return base.MeasureOverride(constraint); } this.cachedNonOverflowItemsCount = nonOverflowItemsCount; this.UpdateHasOverflowItems(); this.cachedConstraint = constraint; // Clear overflow panel to prevent items from having a visual/logical parent this.toolBarOverflowPanel.Children.Clear(); if (this.itemsHadChanged) { // Refill toolbar this.toolBarPanel.Children.Clear(); for (var i = 0; i < this.cachedNonOverflowItemsCount; i++) { this.toolBarPanel.Children.Add(this.Items[i]); } this.itemsHadChanged = false; } else { if (this.cachedNonOverflowItemsCount > this.toolBarPanel.Children.Count) { // Add needed items var savedCount = this.toolBarPanel.Children.Count; for (var i = savedCount; i < this.cachedNonOverflowItemsCount; i++) { this.toolBarPanel.Children.Add(this.Items[i]); } } else { // Remove nonneeded items for (var i = this.toolBarPanel.Children.Count - 1; i >= this.cachedNonOverflowItemsCount; i--) { this.toolBarPanel.Children.Remove(this.Items[i]); } } } // Move overflowing items to overflow panel for (var i = this.cachedNonOverflowItemsCount; i < this.Items.Count; i++) { this.toolBarOverflowPanel.Children.Add(this.Items[i]); } return base.MeasureOverride(constraint); } /// <summary> /// We have to use this function because setting a <see cref="DependencyProperty"/> very frequently is quite expensive /// </summary> private void UpdateHasOverflowItems() { var newValue = this.cachedNonOverflowItemsCount < this.Items.Count; // ReSharper disable RedundantCheckBeforeAssignment if (this.HasOverflowItems != newValue) // ReSharper restore RedundantCheckBeforeAssignment { // todo: code runs very often on startup this.HasOverflowItems = newValue; } } #endregion #region Methods /// <summary> /// First calls <see cref="UIElement.InvalidateMeasure"/> and then <see cref="InvalidateMeasureOfTitleBar"/> /// </summary> public void Refresh() { this.InvalidateMeasure(); this.InvalidateMeasureOfTitleBar(); } private void InvalidateMeasureOfTitleBar() { if (this.IsLoaded == false) { return; } var titleBar = RibbonControl.GetParentRibbon(this)?.TitleBar ?? UIHelper.GetParent<RibbonTitleBar>(this); titleBar?.ForceMeasureAndArrange(); } /// <summary> /// Gets or sets a custom action to generate KeyTips for items in this control. /// </summary> public Action<QuickAccessToolBar> UpdateKeyTipsAction { get { return (Action<QuickAccessToolBar>)this.GetValue(UpdateKeyTipsActionProperty); } set { this.SetValue(UpdateKeyTipsActionProperty, value); } } /// <summary>Identifies the <see cref="UpdateKeyTipsAction"/> dependency property.</summary> public static readonly DependencyProperty UpdateKeyTipsActionProperty = DependencyProperty.Register(nameof(UpdateKeyTipsAction), typeof(Action<QuickAccessToolBar>), typeof(QuickAccessToolBar), new PropertyMetadata(OnUpdateKeyTipsActionChanged)); private static void OnUpdateKeyTipsActionChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var quickAccessToolBar = (QuickAccessToolBar)d; quickAccessToolBar.UpdateKeyTips(); } private void UpdateKeyTips() { if (this.UpdateKeyTipsAction is null) { DefaultUpdateKeyTips(this); return; } this.UpdateKeyTipsAction(this); } // Updates keys for keytip access private static void DefaultUpdateKeyTips(QuickAccessToolBar quickAccessToolBar) { for (var i = 0; i < Math.Min(9, quickAccessToolBar.Items.Count); i++) { // 1, 2, 3, ... , 9 KeyTip.SetKeys(quickAccessToolBar.Items[i], (i + 1).ToString(CultureInfo.InvariantCulture)); } for (var i = 9; i < Math.Min(18, quickAccessToolBar.Items.Count); i++) { // 09, 08, 07, ... , 01 KeyTip.SetKeys(quickAccessToolBar.Items[i], "0" + (18 - i).ToString(CultureInfo.InvariantCulture)); } var startChar = 'A'; for (var i = 18; i < Math.Min(9 + 9 + 26, quickAccessToolBar.Items.Count); i++) { // 0A, 0B, 0C, ... , 0Z KeyTip.SetKeys(quickAccessToolBar.Items[i], "0" + startChar++); } } private int GetNonOverflowItemsCount(in double width) { // Cache width of menuDownButton if (DoubleUtil.AreClose(this.cachedMenuDownButtonWidth, 0) && this.rootPanel != null && this.MenuDownButton != null && this.IsMenuDropDownVisible) { this.rootPanel.Measure(SizeConstants.Infinite); this.cachedMenuDownButtonWidth = this.MenuDownButton.DesiredSize.Width; } // Cache width of toolBarDownButton if (DoubleUtil.AreClose(this.cachedOverflowDownButtonWidth, 0) && this.rootPanel != null && this.MenuDownButton != null) { this.rootPanel.Measure(SizeConstants.Infinite); this.cachedOverflowDownButtonWidth = this.toolBarDownButton.DesiredSize.Width; } // If IsMenuDropDownVisible is true we have less width available var widthReductionWhenNotCompressed = this.IsMenuDropDownVisible ? this.cachedMenuDownButtonWidth : 0; return CalculateNonOverflowItems(this.Items, width, widthReductionWhenNotCompressed, this.cachedOverflowDownButtonWidth); } private static int CalculateNonOverflowItems(IList<UIElement> items, double maxAvailableWidth, double widthReductionWhenNotCompressed, double widthReductionWhenCompressed) { // Calculate how many items we can fit into the available width var maxPossibleItems = GetMaxPossibleItems(maxAvailableWidth - widthReductionWhenNotCompressed, true); if (maxPossibleItems < items.Count) { // If we can't fit all items into the available width // we have to reduce the available width as the overflow button also needs space. var availableWidth = maxAvailableWidth - widthReductionWhenCompressed; return GetMaxPossibleItems(availableWidth, false); } return items.Count; int GetMaxPossibleItems(double availableWidth, bool measureItems) { var currentWidth = 0D; for (var i = 0; i < items.Count; i++) { var currentItem = items[i]; if (measureItems) { currentItem.Measure(SizeConstants.Infinite); } currentWidth += currentItem.DesiredSize.Width; if (currentWidth > availableWidth) { return i; } } return items.Count; } } #endregion /// <inheritdoc /> protected override AutomationPeer OnCreateAutomationPeer() => new Fluent.Automation.Peers.RibbonQuickAccessToolBarAutomationPeer(this); /// <inheritdoc /> void ILogicalChildSupport.AddLogicalChild(object child) { this.AddLogicalChild(child); } /// <inheritdoc /> void ILogicalChildSupport.RemoveLogicalChild(object child) { this.RemoveLogicalChild(child); } /// <inheritdoc /> protected override IEnumerator LogicalChildren { get { var baseEnumerator = base.LogicalChildren; while (baseEnumerator?.MoveNext() == true) { yield return baseEnumerator.Current; } yield return this.rootPanel; foreach (var item in this.QuickAccessItems.GetLogicalChildren()) { yield return item; } } } } }
// 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.Linq; using Avalonia.Interactivity; using Avalonia.Rendering; using Avalonia.VisualTree; namespace Avalonia.Input { /// <summary> /// Implements input-related functionality for a control. /// </summary> public class InputElement : Interactive, IInputElement { /// <summary> /// Defines the <see cref="Focusable"/> property. /// </summary> public static readonly StyledProperty<bool> FocusableProperty = AvaloniaProperty.Register<InputElement, bool>(nameof(Focusable)); /// <summary> /// Defines the <see cref="IsEnabled"/> property. /// </summary> public static readonly StyledProperty<bool> IsEnabledProperty = AvaloniaProperty.Register<InputElement, bool>(nameof(IsEnabled), true); /// <summary> /// Defines the <see cref="IsEnabledCore"/> property. /// </summary> public static readonly StyledProperty<bool> IsEnabledCoreProperty = AvaloniaProperty.Register<InputElement, bool>("IsEnabledCore", true); /// <summary> /// Gets or sets associated mouse cursor. /// </summary> public static readonly StyledProperty<Cursor> CursorProperty = AvaloniaProperty.Register<InputElement, Cursor>("Cursor", null, true); /// <summary> /// Defines the <see cref="IsFocused"/> property. /// </summary> public static readonly DirectProperty<InputElement, bool> IsFocusedProperty = AvaloniaProperty.RegisterDirect<InputElement, bool>("IsFocused", o => o.IsFocused); /// <summary> /// Defines the <see cref="IsHitTestVisible"/> property. /// </summary> public static readonly StyledProperty<bool> IsHitTestVisibleProperty = AvaloniaProperty.Register<InputElement, bool>("IsHitTestVisible", true); /// <summary> /// Defines the <see cref="IsPointerOver"/> property. /// </summary> public static readonly DirectProperty<InputElement, bool> IsPointerOverProperty = AvaloniaProperty.RegisterDirect<InputElement, bool>("IsPointerOver", o => o.IsPointerOver); /// <summary> /// Defines the <see cref="GotFocus"/> event. /// </summary> public static readonly RoutedEvent<GotFocusEventArgs> GotFocusEvent = RoutedEvent.Register<InputElement, GotFocusEventArgs>("GotFocus", RoutingStrategies.Bubble); /// <summary> /// Defines the <see cref="LostFocus"/> event. /// </summary> public static readonly RoutedEvent<RoutedEventArgs> LostFocusEvent = RoutedEvent.Register<InputElement, RoutedEventArgs>("LostFocus", RoutingStrategies.Bubble); /// <summary> /// Defines the <see cref="KeyDown"/> event. /// </summary> public static readonly RoutedEvent<KeyEventArgs> KeyDownEvent = RoutedEvent.Register<InputElement, KeyEventArgs>( "KeyDown", RoutingStrategies.Tunnel | RoutingStrategies.Bubble); /// <summary> /// Defines the <see cref="KeyUp"/> event. /// </summary> public static readonly RoutedEvent<KeyEventArgs> KeyUpEvent = RoutedEvent.Register<InputElement, KeyEventArgs>( "KeyUp", RoutingStrategies.Tunnel | RoutingStrategies.Bubble); /// <summary> /// Defines the <see cref="TextInput"/> event. /// </summary> public static readonly RoutedEvent<TextInputEventArgs> TextInputEvent = RoutedEvent.Register<InputElement, TextInputEventArgs>( "TextInput", RoutingStrategies.Tunnel | RoutingStrategies.Bubble); /// <summary> /// Defines the <see cref="PointerEnter"/> event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerEnterEvent = RoutedEvent.Register<InputElement, PointerEventArgs>("PointerEnter", RoutingStrategies.Direct); /// <summary> /// Defines the <see cref="PointerLeave"/> event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerLeaveEvent = RoutedEvent.Register<InputElement, PointerEventArgs>("PointerLeave", RoutingStrategies.Direct); /// <summary> /// Defines the <see cref="PointerMoved"/> event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerMovedEvent = RoutedEvent.Register<InputElement, PointerEventArgs>( "PointerMove", RoutingStrategies.Tunnel | RoutingStrategies.Bubble); /// <summary> /// Defines the <see cref="PointerPressed"/> event. /// </summary> public static readonly RoutedEvent<PointerPressedEventArgs> PointerPressedEvent = RoutedEvent.Register<InputElement, PointerPressedEventArgs>( "PointerPressed", RoutingStrategies.Tunnel | RoutingStrategies.Bubble); /// <summary> /// Defines the <see cref="PointerReleased"/> event. /// </summary> public static readonly RoutedEvent<PointerReleasedEventArgs> PointerReleasedEvent = RoutedEvent.Register<InputElement, PointerReleasedEventArgs>( "PointerReleased", RoutingStrategies.Tunnel | RoutingStrategies.Bubble); /// <summary> /// Defines the <see cref="PointerWheelChanged"/> event. /// </summary> public static readonly RoutedEvent<PointerWheelEventArgs> PointerWheelChangedEvent = RoutedEvent.Register<InputElement, PointerWheelEventArgs>( "PointerWheelChanged", RoutingStrategies.Tunnel | RoutingStrategies.Bubble); /// <summary> /// Defines the <see cref="Tapped"/> event. /// </summary> public static readonly RoutedEvent<RoutedEventArgs> TappedEvent = Gestures.TappedEvent; /// <summary> /// Defines the <see cref="DoubleTapped"/> event. /// </summary> public static readonly RoutedEvent<RoutedEventArgs> DoubleTappedEvent = Gestures.DoubleTappedEvent; private bool _isFocused; private bool _isPointerOver; /// <summary> /// Initializes static members of the <see cref="InputElement"/> class. /// </summary> static InputElement() { IsEnabledProperty.Changed.Subscribe(IsEnabledChanged); GotFocusEvent.AddClassHandler<InputElement>(x => x.OnGotFocus); LostFocusEvent.AddClassHandler<InputElement>(x => x.OnLostFocus); KeyDownEvent.AddClassHandler<InputElement>(x => x.OnKeyDown); KeyUpEvent.AddClassHandler<InputElement>(x => x.OnKeyUp); TextInputEvent.AddClassHandler<InputElement>(x => x.OnTextInput); PointerEnterEvent.AddClassHandler<InputElement>(x => x.OnPointerEnter); PointerLeaveEvent.AddClassHandler<InputElement>(x => x.OnPointerLeave); PointerMovedEvent.AddClassHandler<InputElement>(x => x.OnPointerMoved); PointerPressedEvent.AddClassHandler<InputElement>(x => x.OnPointerPressed); PointerReleasedEvent.AddClassHandler<InputElement>(x => x.OnPointerReleased); PointerWheelChangedEvent.AddClassHandler<InputElement>(x => x.OnPointerWheelChanged); } /// <summary> /// Occurs when the control receives focus. /// </summary> public event EventHandler<RoutedEventArgs> GotFocus { add { AddHandler(GotFocusEvent, value); } remove { RemoveHandler(GotFocusEvent, value); } } /// <summary> /// Occurs when the control loses focus. /// </summary> public event EventHandler<RoutedEventArgs> LostFocus { add { AddHandler(LostFocusEvent, value); } remove { RemoveHandler(LostFocusEvent, value); } } /// <summary> /// Occurs when a key is pressed while the control has focus. /// </summary> public event EventHandler<KeyEventArgs> KeyDown { add { AddHandler(KeyDownEvent, value); } remove { RemoveHandler(KeyDownEvent, value); } } /// <summary> /// Occurs when a key is released while the control has focus. /// </summary> public event EventHandler<KeyEventArgs> KeyUp { add { AddHandler(KeyUpEvent, value); } remove { RemoveHandler(KeyUpEvent, value); } } /// <summary> /// Occurs when a user typed some text while the control has focus. /// </summary> public event EventHandler<TextInputEventArgs> TextInput { add { AddHandler(TextInputEvent, value); } remove { RemoveHandler(TextInputEvent, value); } } /// <summary> /// Occurs when the pointer enters the control. /// </summary> public event EventHandler<PointerEventArgs> PointerEnter { add { AddHandler(PointerEnterEvent, value); } remove { RemoveHandler(PointerEnterEvent, value); } } /// <summary> /// Occurs when the pointer leaves the control. /// </summary> public event EventHandler<PointerEventArgs> PointerLeave { add { AddHandler(PointerLeaveEvent, value); } remove { RemoveHandler(PointerLeaveEvent, value); } } /// <summary> /// Occurs when the pointer moves over the control. /// </summary> public event EventHandler<PointerEventArgs> PointerMoved { add { AddHandler(PointerMovedEvent, value); } remove { RemoveHandler(PointerMovedEvent, value); } } /// <summary> /// Occurs when the pointer is pressed over the control. /// </summary> public event EventHandler<PointerPressedEventArgs> PointerPressed { add { AddHandler(PointerPressedEvent, value); } remove { RemoveHandler(PointerPressedEvent, value); } } /// <summary> /// Occurs when the pointer is released over the control. /// </summary> public event EventHandler<PointerReleasedEventArgs> PointerReleased { add { AddHandler(PointerReleasedEvent, value); } remove { RemoveHandler(PointerReleasedEvent, value); } } /// <summary> /// Occurs when the mouse wheen is scrolled over the control. /// </summary> public event EventHandler<PointerWheelEventArgs> PointerWheelChanged { add { AddHandler(PointerWheelChangedEvent, value); } remove { RemoveHandler(PointerWheelChangedEvent, value); } } /// <summary> /// Occurs when a tap gesture occurs on the control. /// </summary> public event EventHandler<RoutedEventArgs> Tapped { add { AddHandler(TappedEvent, value); } remove { RemoveHandler(TappedEvent, value); } } /// <summary> /// Occurs when a double-tap gesture occurs on the control. /// </summary> public event EventHandler<RoutedEventArgs> DoubleTapped { add { AddHandler(DoubleTappedEvent, value); } remove { RemoveHandler(DoubleTappedEvent, value); } } /// <summary> /// Gets or sets a value indicating whether the control can receive focus. /// </summary> public bool Focusable { get { return GetValue(FocusableProperty); } set { SetValue(FocusableProperty, value); } } /// <summary> /// Gets or sets a value indicating whether the control is enabled for user interaction. /// </summary> public bool IsEnabled { get { return GetValue(IsEnabledProperty); } set { SetValue(IsEnabledProperty, value); } } /// <summary> /// Gets or sets associated mouse cursor. /// </summary> public Cursor Cursor { get { return GetValue(CursorProperty); } set { SetValue(CursorProperty, value); } } /// <summary> /// Gets or sets a value indicating whether the control is focused. /// </summary> public bool IsFocused { get { return _isFocused; } private set { SetAndRaise(IsFocusedProperty, ref _isFocused, value); } } /// <summary> /// Gets or sets a value indicating whether the control is considered for hit testing. /// </summary> public bool IsHitTestVisible { get { return GetValue(IsHitTestVisibleProperty); } set { SetValue(IsHitTestVisibleProperty, value); } } /// <summary> /// Gets or sets a value indicating whether the pointer is currently over the control. /// </summary> public bool IsPointerOver { get { return _isPointerOver; } internal set { SetAndRaise(IsPointerOverProperty, ref _isPointerOver, value); } } /// <summary> /// Gets a value indicating whether the control is effectively enabled for user interaction. /// </summary> /// <remarks> /// The <see cref="IsEnabled"/> property is used to toggle the enabled state for individual /// controls. The <see cref="IsEnabledCore"/> property takes into account the /// <see cref="IsEnabled"/> value of this control and its parent controls. /// </remarks> bool IInputElement.IsEnabledCore => IsEnabledCore; /// <summary> /// Gets a value indicating whether the control is effectively enabled for user interaction. /// </summary> /// <remarks> /// The <see cref="IsEnabled"/> property is used to toggle the enabled state for individual /// controls. The <see cref="IsEnabledCore"/> property takes into account the /// <see cref="IsEnabled"/> value of this control and its parent controls. /// </remarks> protected bool IsEnabledCore { get { return GetValue(IsEnabledCoreProperty); } set { SetValue(IsEnabledCoreProperty, value); } } public List<KeyBinding> KeyBindings { get; } = new List<KeyBinding>(); /// <summary> /// Focuses the control. /// </summary> public void Focus() { FocusManager.Instance.Focus(this); } /// <inheritdoc/> protected override void OnDetachedFromVisualTreeCore(VisualTreeAttachmentEventArgs e) { base.OnDetachedFromVisualTreeCore(e); if (IsFocused) { FocusManager.Instance.Focus(null); } } /// <inheritdoc/> protected override void OnAttachedToVisualTreeCore(VisualTreeAttachmentEventArgs e) { base.OnAttachedToVisualTreeCore(e); UpdateIsEnabledCore(); } /// <summary> /// Called before the <see cref="GotFocus"/> event occurs. /// </summary> /// <param name="e">The event args.</param> protected virtual void OnGotFocus(GotFocusEventArgs e) { IsFocused = e.Source == this; } /// <summary> /// Called before the <see cref="LostFocus"/> event occurs. /// </summary> /// <param name="e">The event args.</param> protected virtual void OnLostFocus(RoutedEventArgs e) { IsFocused = false; } /// <summary> /// Called before the <see cref="KeyDown"/> event occurs. /// </summary> /// <param name="e">The event args.</param> protected virtual void OnKeyDown(KeyEventArgs e) { } /// <summary> /// Called before the <see cref="KeyUp"/> event occurs. /// </summary> /// <param name="e">The event args.</param> protected virtual void OnKeyUp(KeyEventArgs e) { } /// <summary> /// Called before the <see cref="TextInput"/> event occurs. /// </summary> /// <param name="e">The event args.</param> protected virtual void OnTextInput(TextInputEventArgs e) { } /// <summary> /// Called before the <see cref="PointerEnter"/> event occurs. /// </summary> /// <param name="e">The event args.</param> protected virtual void OnPointerEnter(PointerEventArgs e) { IsPointerOver = true; } /// <summary> /// Called before the <see cref="PointerLeave"/> event occurs. /// </summary> /// <param name="e">The event args.</param> protected virtual void OnPointerLeave(PointerEventArgs e) { IsPointerOver = false; } /// <summary> /// Called before the <see cref="PointerMoved"/> event occurs. /// </summary> /// <param name="e">The event args.</param> protected virtual void OnPointerMoved(PointerEventArgs e) { } /// <summary> /// Called before the <see cref="PointerPressed"/> event occurs. /// </summary> /// <param name="e">The event args.</param> protected virtual void OnPointerPressed(PointerPressedEventArgs e) { } /// <summary> /// Called before the <see cref="PointerReleased"/> event occurs. /// </summary> /// <param name="e">The event args.</param> protected virtual void OnPointerReleased(PointerReleasedEventArgs e) { } /// <summary> /// Called before the <see cref="PointerWheelChanged"/> event occurs. /// </summary> /// <param name="e">The event args.</param> protected virtual void OnPointerWheelChanged(PointerWheelEventArgs e) { } private static void IsEnabledChanged(AvaloniaPropertyChangedEventArgs e) { ((InputElement)e.Sender).UpdateIsEnabledCore(); } /// <summary> /// Updates the <see cref="IsEnabledCore"/> property value. /// </summary> private void UpdateIsEnabledCore() { UpdateIsEnabledCore(this.GetVisualParent<InputElement>()); } /// <summary> /// Updates the <see cref="IsEnabledCore"/> property based on the parent's /// <see cref="IsEnabledCore"/>. /// </summary> /// <param name="parent">The parent control.</param> private void UpdateIsEnabledCore(InputElement parent) { if (parent != null) { IsEnabledCore = IsEnabled && parent.IsEnabledCore; } else { IsEnabledCore = IsEnabled; } foreach (var child in this.GetVisualChildren().OfType<InputElement>()) { child.UpdateIsEnabledCore(this); } } } }
exec("scripts/navigation/main.cs"); exec("scripts/stateMachine/main.cs"); exec("scripts/events/main.cs"); exec("scripts/say/main.cs"); exec("./touristAI.cs"); exec("./rangerAI.cs"); function delete(%obj) { %obj.delete(); } // Convenience function for state machines. function makeSM(%type, %obj) { %parent = %type @ SM; eval("%sm = new ScriptObject(\"\" : " @ %parent @ Template @ ");"); %sm.superclass = StateMachine; %sm.class = %parent; %sm.state = null; %sm.owner = %obj; return %sm; } // And allow onEvent to be called on AIPlayers. function AIPlayer::onEvent(%obj, %event) { if(isObject(%obj.sm)) { %obj.sm.onEvent(%event); } } function AIPlayer::increaseDetection(%obj, %amount) { if(%obj._detection $= "") { %obj._detection = 0; } %obj._detection++; %obj.getDataBlock().onDetectionChange(%obj, %obj._detection); } function AIPlayer::resetDetection(%obj) { %obj._detection = 0; } function AIPlayer::timeOut(%obj, %time) { %obj._timeout = schedule(%time, %obj, AIPlayer__timeOut, %obj); } function AIPlayer__timeOut(%obj) { %obj._timeout = ""; %obj.onEvent(timeOut); } function AIPlayer::stopTimeOut(%obj) { if(%obj._timeout !$= "") { cancel(%obj._timeout); } %obj._timeout = ""; } // Events relevant to the monster's actions. eventQueue(Monster); event(Monster, Swim, "Player AIPlayer"); event(Monster, Bubble, "Player AIPlayer"); event(Monster, Attack, "Player AIPlayer"); // Events that come from tourists. eventQueue(Tourist); event(Tourist, Scared); event(Tourist, Eaten); event(Tourist, AskHelp); function chooseGroundPos(%airPos, %radius) { if(%radius $= "") { %radius = 0; } %count = 0; while(%count < 10) { %count++; if(%radius > 0) { %angle = getRandom() * 2 * 3.14159; %diff = mSin(%angle) * %radius SPC mCos(%angle) * %radius SPC 0; %newPos = VectorAdd(%airPos, %diff); } else { %newPos = %airPos; } %start = getWords(%newPos, 0, 1) SPC getWord(%newPos, 2) + 5; %end = getWords(%newPos, 0, 1) SPC 0; %ray = ContainerRayCast(%start, %end, $TypeMasks::StaticObjectType); %obj = getWord(%ray, 0); if(isObject(%obj)) { return VectorAdd(getWords(%ray, 1, 3), "0 0 0.1"); } } return %airPos; } $Monster::swimNoiseMs = 500; $Monster::swimNoiseSpeed = 3.5; function Monster__makeNoise(%this, %obj) { %obj.moveS = schedule($Monster::swimNoiseMs, %this, Monster__makeNoise, %this, %obj); if(VectorLen(%obj.getVelocity()) > $Monster::swimNoiseSpeed) { postEvent(Monster, Swim, %obj.getPosition()); } } function Monster::onAdd(%this, %obj) { subscribe(%obj, Monster, Attack); subscribe(%obj, Monster, Bubble); subscribe(%obj, Monster, Swim); %obj.moveS = schedule($Monster::swimNoiseMs, %this, Monster__makeNoise, %this, %obj); } function Monster::onRemove(%this, %obj) { cancel(%obj.moveS); } function Monster::onMonsterAttack(%this, %obj, %pos) { %p = new ParticleEmitterNode() { datablock = DefaultNode; emitter = AttackRippleEmitter; active = true; position = getWords(%obj.getPosition(), 0, 1) SPC 3.1; }; %p.schedule(1000, delete, %p); GameGroup.add(%p); %p = new ParticleEmitterNode() { datablock = DefaultNode; emitter = AttackSplashEmitter; active = true; position = getWords(%obj.getPosition(), 0, 1) SPC 2; }; %p.schedule(500, delete, %p); GameGroup.add(%p); %p = new ParticleEmitterNode() { datablock = DefaultNode; emitter = AttackJetEmitter; active = true; position = getWords(%obj.getPosition(), 0, 1) SPC 2.8; }; %p.schedule(300, delete, %p); GameGroup.add(%p); } function Monster::onMonsterBubble(%this, %obj, %pos) { %p = new ParticleEmitterNode() { datablock = DefaultNode; emitter = BubbleRippleEmitter; active = true; position = getWords(%obj.getPosition(), 0, 1) SPC 3.2; }; %p.schedule(1000, delete, %p); GameGroup.add(%p); %p = new ParticleEmitterNode() { datablock = DefaultNode; emitter = BubbleEmitter; active = true; position = getWords(%obj.getPosition(), 0, 1) SPC 2.5; }; %p.schedule(700, delete, %p); GameGroup.add(%p); } function Monster::onMonsterSwim(%this, %obj, %pos) { %p = new ParticleEmitterNode() { datablock = DefaultNode; emitter = WakeEmitter; active = true; position = getWords(%obj.getPosition(), 0, 1) SPC 3.2; }; %p.schedule(3000, delete, %p); GameGroup.add(%p); } function Person::onReachPathDestination(%this, %obj) { %obj.onEvent(reachDestination); } function Person::onMonsterAttack(%this, %obj, %pos) { %p1 = getWords(%obj.getPosition(), 0, 1) SPC 0; %p2 = getWords(%pos, 0, 1) SPC 0; %d = VectorLen(VectorSub(%p1, %p2)); if(%d < 5) { %obj.eaten = true; %obj.schedule(750, delete, %obj); postEvent(Tourist, Eaten, %obj.getPosition()); %obj.onEvent(attackNear); } else if(%d < 30) { %obj.onEvent(attackNear); } else if(%d < 60) { %obj.onEvent(attackFar); } } function Person::onMonsterBubble(%this, %obj, %pos) { %p1 = getWords(%obj.getPosition(), 0, 1) SPC 0; %p2 = getWords(%pos, 0, 1) SPC 0; %d = VectorLen(VectorSub(%p1, %p2)); if(%d < 20) { %obj.increaseDetection(3); } else if(%d < 40) { %obj.increaseDetection(2); } } function Person::onMonsterSwim(%this, %obj, %pos) { %p1 = getWords(%obj.getPosition(), 0, 1) SPC 0; %p2 = getWords(%pos, 0, 1) SPC 0; %d = VectorLen(VectorSub(%p1, %p2)); if(%d < 10) { %obj.increaseDetection(1); } } function Person::onDetectionChange(%this, %obj, %val) { if(%val == %obj.threshold) { %obj.onEvent(monsterNoise); %obj.resetDetection(); } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ using System.Collections.Generic; using ParquetSharp.Example.Data; using ParquetSharp.Example.Data.Simple; using ParquetSharp.External; using ParquetSharp.Format.Converter; using ParquetSharp.Hadoop; using ParquetSharp.Hadoop.Example; using ParquetSharp.Hadoop.Metadata; using ParquetSharp.IO.Api; using ParquetSharp.Schema; using Xunit; namespace ParquetHadoopTests.Hadoop { public class TestMergeMetadataFiles { // @Rule public TemporaryFolder temp = new TemporaryFolder(); private static readonly MessageType schema = parseMessageType( "message test { " + "required binary binary_field; " + "required int32 int32_field; " + "required int64 int64_field; " + "required boolean boolean_field; " + "required float float_field; " + "required double double_field; " + "required fixed_len_byte_array(3) flba_field; " + "required int96 int96_field; " + "} "); // schema1 with a field removed private static readonly MessageType schema2 = parseMessageType( "message test { " + "required binary binary_field; " + "required int32 int32_field; " + "required int64 int64_field; " + "required boolean boolean_field; " + "required float float_field; " + "required double double_field; " + "required fixed_len_byte_array(3) flba_field; " + "} "); private static void writeFile(File @out, Configuration conf, bool useSchema2) { if (!useSchema2) { GroupWriteSupport.setSchema(schema, conf); } else { GroupWriteSupport.setSchema(schema2, conf); } SimpleGroupFactory f = new SimpleGroupFactory(schema); Dictionary<string, string> extraMetaData = new Dictionary<string, string>(); extraMetaData.put("schema_num", useSchema2 ? "2" : "1"); ParquetWriter<Group> writer = ExampleParquetWriter .builder(new Path(@out.getAbsolutePath())) .withConf(conf) .withExtraMetaData(extraMetaData) .build(); for (int i = 0; i < 1000; i++) { Group g = f.newGroup() .append("binary_field", "test" + i) .append("int32_field", i) .append("int64_field", (long)i) .append("boolean_field", i % 2 == 0) .append("float_field", (float)i) .append("double_field", (double)i) .append("flba_field", "foo"); if (!useSchema2) { g = g.append("int96_field", Binary.fromConstantByteArray(new byte[12])); } writer.write(g); } writer.close(); } class WrittenFileInfo { public Configuration conf; public Path metaPath1; public Path metaPath2; public Path commonMetaPath1; public Path commonMetaPath2; } private WrittenFileInfo writeFiles(bool mixedSchemas) { WrittenFileInfo info = new WrittenFileInfo(); Configuration conf = new Configuration(); info.conf = conf; File root1 = new File(temp.getRoot(), "out1"); File root2 = new File(temp.getRoot(), "out2"); Path rootPath1 = new Path(root1.getAbsolutePath()); Path rootPath2 = new Path(root2.getAbsolutePath()); for (int i = 0; i < 10; i++) { writeFile(new File(root1, i + ".parquet"), conf, true); } List<Footer> footers = ParquetFileReader.readFooters(conf, rootPath1.getFileSystem(conf).getFileStatus(rootPath1), false); ParquetFileWriter.writeMetadataFile(conf, rootPath1, footers, JobSummaryLevel.ALL); for (int i = 0; i < 7; i++) { writeFile(new File(root2, i + ".parquet"), conf, !mixedSchemas); } footers = ParquetFileReader.readFooters(conf, rootPath2.getFileSystem(conf).getFileStatus(rootPath2), false); ParquetFileWriter.writeMetadataFile(conf, rootPath2, footers, JobSummaryLevel.ALL); info.commonMetaPath1 = new Path(new File(root1, ParquetFileWriter.PARQUET_COMMON_METADATA_FILE).getAbsolutePath()); info.commonMetaPath2 = new Path(new File(root2, ParquetFileWriter.PARQUET_COMMON_METADATA_FILE).getAbsolutePath()); info.metaPath1 = new Path(new File(root1, ParquetFileWriter.PARQUET_METADATA_FILE).getAbsolutePath()); info.metaPath2 = new Path(new File(root2, ParquetFileWriter.PARQUET_METADATA_FILE).getAbsolutePath()); return info; } [Fact] public void testMergeMetadataFiles() { WrittenFileInfo info = writeFiles(false); ParquetMetadata commonMeta1 = ParquetFileReader.readFooter(info.conf, info.commonMetaPath1, ParquetMetadataConverter.NO_FILTER); ParquetMetadata commonMeta2 = ParquetFileReader.readFooter(info.conf, info.commonMetaPath2, ParquetMetadataConverter.NO_FILTER); ParquetMetadata meta1 = ParquetFileReader.readFooter(info.conf, info.metaPath1, ParquetMetadataConverter.NO_FILTER); ParquetMetadata meta2 = ParquetFileReader.readFooter(info.conf, info.metaPath2, ParquetMetadataConverter.NO_FILTER); Assert.True(commonMeta1.getBlocks().isEmpty()); Assert.True(commonMeta2.getBlocks().isEmpty()); Assert.Equal(commonMeta1.getFileMetaData().getSchema(), commonMeta2.getFileMetaData().getSchema()); Assert.False(meta1.getBlocks().isEmpty()); Assert.False(meta2.getBlocks().isEmpty()); Assert.Equal(meta1.getFileMetaData().getSchema(), meta2.getFileMetaData().getSchema()); Assert.Equal(commonMeta1.getFileMetaData().getKeyValueMetaData(), commonMeta2.getFileMetaData().getKeyValueMetaData()); Assert.Equal(meta1.getFileMetaData().getKeyValueMetaData(), meta2.getFileMetaData().getKeyValueMetaData()); // test file serialization Path mergedOut = new Path(new File(temp.getRoot(), "merged_meta").getAbsolutePath()); Path mergedCommonOut = new Path(new File(temp.getRoot(), "merged_common_meta").getAbsolutePath()); ParquetFileWriter.writeMergedMetadataFile(Arrays.asList(info.metaPath1, info.metaPath2), mergedOut, info.conf); ParquetFileWriter.writeMergedMetadataFile(Arrays.asList(info.commonMetaPath1, info.commonMetaPath2), mergedCommonOut, info.conf); ParquetMetadata mergedMeta = ParquetFileReader.readFooter(info.conf, mergedOut, ParquetMetadataConverter.NO_FILTER); ParquetMetadata mergedCommonMeta = ParquetFileReader.readFooter(info.conf, mergedCommonOut, ParquetMetadataConverter.NO_FILTER); // ideally we'd assert equality here, but BlockMetaData and it's references don't implement equals Assert.Equal(meta1.getBlocks().size() + meta2.getBlocks().size(), mergedMeta.getBlocks().size()); Assert.True(mergedCommonMeta.getBlocks().isEmpty()); Assert.Equal(meta1.getFileMetaData().getSchema(), mergedMeta.getFileMetaData().getSchema()); Assert.Equal(commonMeta1.getFileMetaData().getSchema(), mergedCommonMeta.getFileMetaData().getSchema()); Assert.Equal(meta1.getFileMetaData().getKeyValueMetaData(), mergedMeta.getFileMetaData().getKeyValueMetaData()); Assert.Equal(commonMeta1.getFileMetaData().getKeyValueMetaData(), mergedCommonMeta.getFileMetaData().getKeyValueMetaData()); } [Fact] public void testThrowsWhenIncompatible() { WrittenFileInfo info = writeFiles(true); Path mergedOut = new Path(new File(temp.getRoot(), "merged_meta").getAbsolutePath()); Path mergedCommonOut = new Path(new File(temp.getRoot(), "merged_common_meta").getAbsolutePath()); try { ParquetFileWriter.writeMergedMetadataFile(Arrays.asList(info.metaPath1, info.metaPath2), mergedOut, info.conf); Assert.True(false, "this should throw"); } catch (RuntimeException e) { Assert.Equal("could not merge metadata: key schema_num has conflicting values: [2, 1]", e.Message); } try { ParquetFileWriter.writeMergedMetadataFile(Arrays.asList(info.commonMetaPath1, info.commonMetaPath2), mergedCommonOut, info.conf); Assert.True(false, "this should throw"); } catch (RuntimeException e) { Assert.Equal("could not merge metadata: key schema_num has conflicting values: [2, 1]", e.Message); } } } }
// SF API version v50.0 // Custom fields included: False // Relationship objects included: True using System; using NetCoreForce.Client.Models; using NetCoreForce.Client.Attributes; using Newtonsoft.Json; namespace NetCoreForce.Models { ///<summary> /// Opportunity Stage ///<para>SObject Name: OpportunityStage</para> ///<para>Custom Object: False</para> ///</summary> public class SfOpportunityStage : SObject { [JsonIgnore] public static string SObjectTypeName { get { return "OpportunityStage"; } } ///<summary> /// Opportunity Stage ID /// <para>Name: Id</para> /// <para>SF Type: id</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "id")] [Updateable(false), Createable(false)] public string Id { get; set; } ///<summary> /// Master Label /// <para>Name: MasterLabel</para> /// <para>SF Type: string</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "masterLabel")] [Updateable(false), Createable(false)] public string MasterLabel { get; set; } ///<summary> /// Api Name /// <para>Name: ApiName</para> /// <para>SF Type: string</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "apiName")] [Updateable(false), Createable(false)] public string ApiName { get; set; } ///<summary> /// Is Active /// <para>Name: IsActive</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "isActive")] [Updateable(false), Createable(false)] public bool? IsActive { get; set; } ///<summary> /// Sort Order /// <para>Name: SortOrder</para> /// <para>SF Type: int</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "sortOrder")] [Updateable(false), Createable(false)] public int? SortOrder { get; set; } ///<summary> /// Closed /// <para>Name: IsClosed</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "isClosed")] [Updateable(false), Createable(false)] public bool? IsClosed { get; set; } ///<summary> /// Won /// <para>Name: IsWon</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "isWon")] [Updateable(false), Createable(false)] public bool? IsWon { get; set; } ///<summary> /// Forecast Category /// <para>Name: ForecastCategory</para> /// <para>SF Type: picklist</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "forecastCategory")] [Updateable(false), Createable(false)] public string ForecastCategory { get; set; } ///<summary> /// Forecast Category Name /// <para>Name: ForecastCategoryName</para> /// <para>SF Type: picklist</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "forecastCategoryName")] [Updateable(false), Createable(false)] public string ForecastCategoryName { get; set; } ///<summary> /// Probability (%) /// <para>Name: DefaultProbability</para> /// <para>SF Type: percent</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "defaultProbability")] [Updateable(false), Createable(false)] public double? DefaultProbability { get; set; } ///<summary> /// Description /// <para>Name: Description</para> /// <para>SF Type: string</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "description")] [Updateable(false), Createable(false)] public string Description { get; set; } ///<summary> /// Created By ID /// <para>Name: CreatedById</para> /// <para>SF Type: reference</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "createdById")] [Updateable(false), Createable(false)] public string CreatedById { get; set; } ///<summary> /// ReferenceTo: User /// <para>RelationshipName: CreatedBy</para> ///</summary> [JsonProperty(PropertyName = "createdBy")] [Updateable(false), Createable(false)] public SfUser CreatedBy { get; set; } ///<summary> /// Created Date /// <para>Name: CreatedDate</para> /// <para>SF Type: datetime</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "createdDate")] [Updateable(false), Createable(false)] public DateTimeOffset? CreatedDate { get; set; } ///<summary> /// Last Modified By ID /// <para>Name: LastModifiedById</para> /// <para>SF Type: reference</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "lastModifiedById")] [Updateable(false), Createable(false)] public string LastModifiedById { get; set; } ///<summary> /// ReferenceTo: User /// <para>RelationshipName: LastModifiedBy</para> ///</summary> [JsonProperty(PropertyName = "lastModifiedBy")] [Updateable(false), Createable(false)] public SfUser LastModifiedBy { get; set; } ///<summary> /// Last Modified Date /// <para>Name: LastModifiedDate</para> /// <para>SF Type: datetime</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "lastModifiedDate")] [Updateable(false), Createable(false)] public DateTimeOffset? LastModifiedDate { get; set; } ///<summary> /// System Modstamp /// <para>Name: SystemModstamp</para> /// <para>SF Type: datetime</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "systemModstamp")] [Updateable(false), Createable(false)] public DateTimeOffset? SystemModstamp { get; set; } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Description; using ImageGallery.Areas.HelpPage.Models; namespace ImageGallery.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 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 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) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); model = GenerateApiModel(apiDescription, sampleGenerator); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HelpPageSampleGenerator sampleGenerator) { HelpPageApiModel apiModel = new HelpPageApiModel(); apiModel.ApiDescription = apiDescription; try { foreach (var item in sampleGenerator.GetSampleRequests(apiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(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}", e.Message)); } return apiModel; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.DirectoryServices.ActiveDirectory { using System; using System.Text; using System.Threading; using System.Collections; using System.Globalization; using System.Diagnostics; using System.Runtime.InteropServices; using System.Security.Permissions; internal enum NCFlags : int { InstanceTypeIsNCHead = 1, InstanceTypeIsWriteable = 4 } internal enum ApplicationPartitionType : int { Unknown = -1, ADApplicationPartition = 0, ADAMApplicationPartition = 1 } public class ApplicationPartition : ActiveDirectoryPartition { private bool _disposed = false; private ApplicationPartitionType _appType = (ApplicationPartitionType)(-1); private bool _committed = true; private DirectoryEntry _domainDNSEntry = null; private DirectoryEntry _crossRefEntry = null; private string _dnsName = null; private DirectoryServerCollection _cachedDirectoryServers = null; private bool _securityRefDomainModified = false; private string _securityRefDomain = null; #region constructors // Public Constructors public ApplicationPartition(DirectoryContext context, string distinguishedName) { // validate the parameters ValidateApplicationPartitionParameters(context, distinguishedName, null, false); // call private function for creating the application partition CreateApplicationPartition(distinguishedName, "domainDns"); } public ApplicationPartition(DirectoryContext context, string distinguishedName, string objectClass) { // validate the parameters ValidateApplicationPartitionParameters(context, distinguishedName, objectClass, true); // call private function for creating the application partition CreateApplicationPartition(distinguishedName, objectClass); } // Internal Constructors internal ApplicationPartition(DirectoryContext context, string distinguishedName, string dnsName, ApplicationPartitionType appType, DirectoryEntryManager directoryEntryMgr) : base(context, distinguishedName) { this.directoryEntryMgr = directoryEntryMgr; _appType = appType; _dnsName = dnsName; } internal ApplicationPartition(DirectoryContext context, string distinguishedName, string dnsName, DirectoryEntryManager directoryEntryMgr) : this(context, distinguishedName, dnsName, GetApplicationPartitionType(context), directoryEntryMgr) { } #endregion constructors #region IDisposable // private Dispose method protected override void Dispose(bool disposing) { if (!_disposed) { try { // if there are any managed or unmanaged // resources to be freed, those should be done here // if disposing = true, only unmanaged resources should // be freed, else both managed and unmanaged. if (_crossRefEntry != null) { _crossRefEntry.Dispose(); _crossRefEntry = null; } if (_domainDNSEntry != null) { _domainDNSEntry.Dispose(); _domainDNSEntry = null; } _disposed = true; } finally { base.Dispose(); } } } #endregion IDisposable #region public methods public static ApplicationPartition GetApplicationPartition(DirectoryContext context) { // validate the context if (context == null) { throw new ArgumentNullException("context"); } // contexttype should be ApplicationPartiton if (context.ContextType != DirectoryContextType.ApplicationPartition) { throw new ArgumentException(SR.TargetShouldBeAppNCDnsName, "context"); } // target must be ndnc dns name if (!context.isNdnc()) { throw new ActiveDirectoryObjectNotFoundException(SR.NDNCNotFound, typeof(ApplicationPartition), context.Name); } // work with copy of the context context = new DirectoryContext(context); // bind to the application partition head (this will verify credentials) string distinguishedName = Utils.GetDNFromDnsName(context.Name); DirectoryEntryManager directoryEntryMgr = new DirectoryEntryManager(context); DirectoryEntry appNCHead = null; try { appNCHead = directoryEntryMgr.GetCachedDirectoryEntry(distinguishedName); // need to force the bind appNCHead.Bind(true); } catch (COMException e) { int errorCode = e.ErrorCode; if (errorCode == unchecked((int)0x8007203a)) { throw new ActiveDirectoryObjectNotFoundException(SR.NDNCNotFound, typeof(ApplicationPartition), context.Name); } else { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } } return new ApplicationPartition(context, distinguishedName, context.Name, ApplicationPartitionType.ADApplicationPartition, directoryEntryMgr); } public static ApplicationPartition FindByName(DirectoryContext context, string distinguishedName) { ApplicationPartition partition = null; DirectoryEntryManager directoryEntryMgr = null; DirectoryContext appNCContext = null; // check that the argument is not null if (context == null) throw new ArgumentNullException("context"); if ((context.Name == null) && (!context.isRootDomain())) { throw new ArgumentException(SR.ContextNotAssociatedWithDomain, "context"); } if (context.Name != null) { // the target should be a valid forest name, configset name or a server if (!((context.isRootDomain()) || (context.isADAMConfigSet()) || context.isServer())) { throw new ArgumentException(SR.NotADOrADAM, "context"); } } // check that the distingushed name of the application partition is not null or empty if (distinguishedName == null) throw new ArgumentNullException("distinguishedName"); if (distinguishedName.Length == 0) throw new ArgumentException(SR.EmptyStringParameter, "distinguishedName"); if (!Utils.IsValidDNFormat(distinguishedName)) throw new ArgumentException(SR.InvalidDNFormat, "distinguishedName"); // work with copy of the context context = new DirectoryContext(context); // search in the partitions container of the forest for // crossRef objects that have their nCName set to the specified distinguishedName directoryEntryMgr = new DirectoryEntryManager(context); DirectoryEntry partitionsEntry = null; try { partitionsEntry = DirectoryEntryManager.GetDirectoryEntry(context, directoryEntryMgr.ExpandWellKnownDN(WellKnownDN.PartitionsContainer)); } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } catch (ActiveDirectoryObjectNotFoundException) { // this is the case where the context is a config set and we could not find an ADAM instance in that config set throw new ActiveDirectoryOperationException(String.Format(CultureInfo.CurrentCulture, SR.ADAMInstanceNotFoundInConfigSet , context.Name)); } // build the filter StringBuilder str = new StringBuilder(15); str.Append("(&("); str.Append(PropertyManager.ObjectCategory); str.Append("=crossRef)("); str.Append(PropertyManager.SystemFlags); str.Append(":1.2.840.113556.1.4.804:="); str.Append((int)SystemFlag.SystemFlagNtdsNC); str.Append(")(!("); str.Append(PropertyManager.SystemFlags); str.Append(":1.2.840.113556.1.4.803:="); str.Append((int)SystemFlag.SystemFlagNtdsDomain); str.Append("))("); str.Append(PropertyManager.NCName); str.Append("="); str.Append(Utils.GetEscapedFilterValue(distinguishedName)); str.Append("))"); string filter = str.ToString(); string[] propertiesToLoad = new string[2]; propertiesToLoad[0] = PropertyManager.DnsRoot; propertiesToLoad[1] = PropertyManager.NCName; ADSearcher searcher = new ADSearcher(partitionsEntry, filter, propertiesToLoad, SearchScope.OneLevel, false /*not paged search*/, false /*no cached results*/); SearchResult res = null; try { res = searcher.FindOne(); } catch (COMException e) { if (e.ErrorCode == unchecked((int)0x80072030)) { // object is not found since we cannot even find the container in which to search throw new ActiveDirectoryObjectNotFoundException(SR.AppNCNotFound, typeof(ApplicationPartition), distinguishedName); } else { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } } finally { partitionsEntry.Dispose(); } if (res == null) { // the specified application partition could not be found in the given forest throw new ActiveDirectoryObjectNotFoundException(SR.AppNCNotFound, typeof(ApplicationPartition), distinguishedName); } string appNCDnsName = null; try { appNCDnsName = (res.Properties[PropertyManager.DnsRoot].Count > 0) ? (string)res.Properties[PropertyManager.DnsRoot][0] : null; } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } // verify that if the target is a server, then this partition is a naming context on it ApplicationPartitionType appType = GetApplicationPartitionType(context); if (context.ContextType == DirectoryContextType.DirectoryServer) { bool hostsCurrentPartition = false; DistinguishedName appNCDN = new DistinguishedName(distinguishedName); DirectoryEntry rootDSE = DirectoryEntryManager.GetDirectoryEntry(context, WellKnownDN.RootDSE); try { foreach (string namingContext in rootDSE.Properties[PropertyManager.NamingContexts]) { DistinguishedName dn = new DistinguishedName(namingContext); if (dn.Equals(appNCDN)) { hostsCurrentPartition = true; break; } } } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } finally { rootDSE.Dispose(); } if (!hostsCurrentPartition) { throw new ActiveDirectoryObjectNotFoundException(SR.AppNCNotFound, typeof(ApplicationPartition), distinguishedName); } appNCContext = context; } else { // we need to find a server which hosts this application partition if (appType == ApplicationPartitionType.ADApplicationPartition) { int errorCode = 0; DomainControllerInfo domainControllerInfo; errorCode = Locator.DsGetDcNameWrapper(null, appNCDnsName, null, (long)PrivateLocatorFlags.OnlyLDAPNeeded, out domainControllerInfo); if (errorCode == NativeMethods.ERROR_NO_SUCH_DOMAIN) { throw new ActiveDirectoryObjectNotFoundException(SR.AppNCNotFound, typeof(ApplicationPartition), distinguishedName); } else if (errorCode != 0) { throw ExceptionHelper.GetExceptionFromErrorCode(errorCode); } Debug.Assert(domainControllerInfo.DomainControllerName.Length > 2, "ApplicationPartition:FindByName - domainControllerInfo.DomainControllerName.Length <= 2"); string serverName = domainControllerInfo.DomainControllerName.Substring(2); appNCContext = Utils.GetNewDirectoryContext(serverName, DirectoryContextType.DirectoryServer, context); } else { // this will find an adam instance that hosts this partition and which is alive and responding. string adamInstName = ConfigurationSet.FindOneAdamInstance(context.Name, context, distinguishedName, null).Name; appNCContext = Utils.GetNewDirectoryContext(adamInstName, DirectoryContextType.DirectoryServer, context); } } partition = new ApplicationPartition(appNCContext, (string)PropertyManager.GetSearchResultPropertyValue(res, PropertyManager.NCName), appNCDnsName, appType, directoryEntryMgr); return partition; } public DirectoryServer FindDirectoryServer() { DirectoryServer directoryServer = null; CheckIfDisposed(); if (_appType == ApplicationPartitionType.ADApplicationPartition) { // AD directoryServer = FindDirectoryServerInternal(null, false); } else { // Check that the application partition has been committed if (!_committed) { throw new InvalidOperationException(SR.CannotPerformOperationOnUncommittedObject); } directoryServer = ConfigurationSet.FindOneAdamInstance(context, Name, null); } return directoryServer; } public DirectoryServer FindDirectoryServer(string siteName) { DirectoryServer directoryServer = null; CheckIfDisposed(); if (siteName == null) { throw new ArgumentNullException("siteName"); } if (_appType == ApplicationPartitionType.ADApplicationPartition) { // AD directoryServer = FindDirectoryServerInternal(siteName, false); } else { // Check that the application partition has been committed if (!_committed) { throw new InvalidOperationException(SR.CannotPerformOperationOnUncommittedObject); } directoryServer = ConfigurationSet.FindOneAdamInstance(context, Name, siteName); } return directoryServer; } public DirectoryServer FindDirectoryServer(bool forceRediscovery) { DirectoryServer directoryServer = null; CheckIfDisposed(); if (_appType == ApplicationPartitionType.ADApplicationPartition) { // AD directoryServer = FindDirectoryServerInternal(null, forceRediscovery); } else { // Check that the application partition has been committed if (!_committed) { throw new InvalidOperationException(SR.CannotPerformOperationOnUncommittedObject); } // forceRediscovery is ignored for ADAM Application partition directoryServer = ConfigurationSet.FindOneAdamInstance(context, Name, null); } return directoryServer; } public DirectoryServer FindDirectoryServer(string siteName, bool forceRediscovery) { DirectoryServer directoryServer = null; CheckIfDisposed(); if (siteName == null) { throw new ArgumentNullException("siteName"); } if (_appType == ApplicationPartitionType.ADApplicationPartition) { // AD directoryServer = FindDirectoryServerInternal(siteName, forceRediscovery); } else { // Check that the application partition has been committed if (!_committed) { throw new InvalidOperationException(SR.CannotPerformOperationOnUncommittedObject); } // forceRediscovery is ignored for ADAM Application partition directoryServer = ConfigurationSet.FindOneAdamInstance(context, Name, siteName); } return directoryServer; } public ReadOnlyDirectoryServerCollection FindAllDirectoryServers() { CheckIfDisposed(); if (_appType == ApplicationPartitionType.ADApplicationPartition) { // AD return FindAllDirectoryServersInternal(null); } else { // Check that the application partition has been committed if (!_committed) { throw new InvalidOperationException(SR.CannotPerformOperationOnUncommittedObject); } ReadOnlyDirectoryServerCollection directoryServers = new ReadOnlyDirectoryServerCollection(); directoryServers.AddRange(ConfigurationSet.FindAdamInstances(context, Name, null)); return directoryServers; } } public ReadOnlyDirectoryServerCollection FindAllDirectoryServers(string siteName) { CheckIfDisposed(); if (siteName == null) { throw new ArgumentNullException("siteName"); } if (_appType == ApplicationPartitionType.ADApplicationPartition) { // AD return FindAllDirectoryServersInternal(siteName); } else { // Check that the application partition has been committed if (!_committed) { throw new InvalidOperationException(SR.CannotPerformOperationOnUncommittedObject); } ReadOnlyDirectoryServerCollection directoryServers = new ReadOnlyDirectoryServerCollection(); directoryServers.AddRange(ConfigurationSet.FindAdamInstances(context, Name, siteName)); return directoryServers; } } public ReadOnlyDirectoryServerCollection FindAllDiscoverableDirectoryServers() { CheckIfDisposed(); if (_appType == ApplicationPartitionType.ADApplicationPartition) { // AD return FindAllDiscoverableDirectoryServersInternal(null); } else { // // throw exception for ADAM // throw new NotSupportedException(SR.OperationInvalidForADAM); } } public ReadOnlyDirectoryServerCollection FindAllDiscoverableDirectoryServers(string siteName) { CheckIfDisposed(); if (siteName == null) { throw new ArgumentNullException("siteName"); } if (_appType == ApplicationPartitionType.ADApplicationPartition) { // AD return FindAllDiscoverableDirectoryServersInternal(siteName); } else { // // throw exception for ADAM // throw new NotSupportedException(SR.OperationInvalidForADAM); } } public void Delete() { CheckIfDisposed(); // Check that the application partition has been committed if (!_committed) { throw new InvalidOperationException(SR.CannotPerformOperationOnUncommittedObject); } // Get the partitions container and delete the crossRef entry for this // application partition DirectoryEntry partitionsEntry = DirectoryEntryManager.GetDirectoryEntry(context, directoryEntryMgr.ExpandWellKnownDN(WellKnownDN.PartitionsContainer)); try { GetCrossRefEntry(); partitionsEntry.Children.Remove(_crossRefEntry); } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } finally { partitionsEntry.Dispose(); } } public void Save() { CheckIfDisposed(); if (!_committed) { bool createManually = false; if (_appType == ApplicationPartitionType.ADApplicationPartition) { try { _domainDNSEntry.CommitChanges(); } catch (COMException e) { if (e.ErrorCode == unchecked((int)0x80072029)) { // inappropriate authentication (we might have fallen back to NTLM) createManually = true; } else { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } } } else { // for ADAM we always create the crossRef manually before creating the domainDNS object createManually = true; } if (createManually) { // we need to first save the cross ref entry try { InitializeCrossRef(partitionName); _crossRefEntry.CommitChanges(); } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } try { _domainDNSEntry.CommitChanges(); } catch (COMException e) { // //delete the crossRef entry // DirectoryEntry partitionsEntry = _crossRefEntry.Parent; try { partitionsEntry.Children.Remove(_crossRefEntry); } catch (COMException e2) { throw ExceptionHelper.GetExceptionFromCOMException(e2); } throw ExceptionHelper.GetExceptionFromCOMException(context, e); } // if the crossRef is created manually we need to refresh the cross ref entry to get the changes that were made // due to the creation of the partition try { _crossRefEntry.RefreshCache(); } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } } // When we create a domainDNS object on DC1 (Naming Master = DC2), // then internally DC1 will contact DC2 to create the disabled crossRef object. // DC2 will force replicate the crossRef object to DC1. DC1 will then create // the domainDNS object and enable the crossRef on DC1 (not DC2). // Here we need to force replicate the enabling of the crossRef to the FSMO (DC2) // so that we can later add replicas (which need to modify an attribute on the crossRef // on DC2, the FSMO, and can only be done if the crossRef on DC2 is enabled) // get the ntdsa name of the server on which the partition is created DirectoryEntry rootDSE = directoryEntryMgr.GetCachedDirectoryEntry(WellKnownDN.RootDSE); string primaryServerNtdsaName = (string)PropertyManager.GetPropertyValue(context, rootDSE, PropertyManager.DsServiceName); // get the DN of the crossRef entry that needs to be replicated to the fsmo role if (_appType == ApplicationPartitionType.ADApplicationPartition) { // for AD we may not have the crossRef entry yet GetCrossRefEntry(); } string crossRefDN = (string)PropertyManager.GetPropertyValue(context, _crossRefEntry, PropertyManager.DistinguishedName); // Now set the operational attribute "replicateSingleObject" on the Rootdse of the fsmo role // to <ntdsa name of the source>:<DN of the crossRef object which needs to be replicated> DirectoryContext fsmoContext = Utils.GetNewDirectoryContext(GetNamingRoleOwner(), DirectoryContextType.DirectoryServer, context); DirectoryEntry fsmoRootDSE = DirectoryEntryManager.GetDirectoryEntry(fsmoContext, WellKnownDN.RootDSE); try { fsmoRootDSE.Properties[PropertyManager.ReplicateSingleObject].Value = primaryServerNtdsaName + ":" + crossRefDN; fsmoRootDSE.CommitChanges(); } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } finally { fsmoRootDSE.Dispose(); } // the partition has been created _committed = true; // commit the replica locations information or security reference domain if applicable if ((_cachedDirectoryServers != null) || (_securityRefDomainModified)) { if (_cachedDirectoryServers != null) { _crossRefEntry.Properties[PropertyManager.MsDSNCReplicaLocations].AddRange(_cachedDirectoryServers.GetMultiValuedProperty()); } if (_securityRefDomainModified) { _crossRefEntry.Properties[PropertyManager.MsDSSDReferenceDomain].Value = _securityRefDomain; } try { _crossRefEntry.CommitChanges(); } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } } } else { // just save the crossRef entry for teh directory servers and the // security reference domain information if ((_cachedDirectoryServers != null) || (_securityRefDomainModified)) { try { // we should already have the crossRef entries as some attribute on it has already // been modified Debug.Assert(_crossRefEntry != null, "ApplicationPartition::Save - crossRefEntry on already committed partition which is being modified is null."); _crossRefEntry.CommitChanges(); } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } } } // invalidate cached info _cachedDirectoryServers = null; _securityRefDomainModified = false; } public override DirectoryEntry GetDirectoryEntry() { CheckIfDisposed(); if (!_committed) { throw new InvalidOperationException(SR.CannotGetObject); } return DirectoryEntryManager.GetDirectoryEntry(context, Name); } #endregion public methods #region public properties public DirectoryServerCollection DirectoryServers { get { CheckIfDisposed(); if (_cachedDirectoryServers == null) { ReadOnlyDirectoryServerCollection servers = (_committed) ? FindAllDirectoryServers() : new ReadOnlyDirectoryServerCollection(); bool isADAM = (_appType == ApplicationPartitionType.ADAMApplicationPartition) ? true : false; // Get the cross ref entry if we don't already have it if (_committed) { GetCrossRefEntry(); } // // If the application partition is already committed at this point, we pass in the directory entry for teh crossRef, so any modifications // are made directly on the crossRef entry. If at this point we do not have a crossRefEntry, we pass in null, while saving, we get the information // from the collection and set it on the appropriate attribute on the crossRef directory entry. // // _cachedDirectoryServers = new DirectoryServerCollection(context, (_committed) ? _crossRefEntry : null, isADAM, servers); } return _cachedDirectoryServers; } } public string SecurityReferenceDomain { get { CheckIfDisposed(); if (_appType == ApplicationPartitionType.ADAMApplicationPartition) { throw new NotSupportedException(SR.PropertyInvalidForADAM); } if (_committed) { GetCrossRefEntry(); try { if (_crossRefEntry.Properties[PropertyManager.MsDSSDReferenceDomain].Count > 0) { return (string)_crossRefEntry.Properties[PropertyManager.MsDSSDReferenceDomain].Value; } else { return null; } } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } } else { return _securityRefDomain; } } set { CheckIfDisposed(); if (_appType == ApplicationPartitionType.ADAMApplicationPartition) { throw new NotSupportedException(SR.PropertyInvalidForADAM); } if (_committed) { GetCrossRefEntry(); // modify the security reference domain // this will get committed when the crossRefEntry is committed if (value == null) { if (_crossRefEntry.Properties.Contains(PropertyManager.MsDSSDReferenceDomain)) { _crossRefEntry.Properties[PropertyManager.MsDSSDReferenceDomain].Clear(); _securityRefDomainModified = true; } } else { _crossRefEntry.Properties[PropertyManager.MsDSSDReferenceDomain].Value = value; _securityRefDomainModified = true; } } else { if (!((_securityRefDomain == null) && (value == null))) { _securityRefDomain = value; _securityRefDomainModified = true; } } } } #endregion public properties #region private methods private void ValidateApplicationPartitionParameters(DirectoryContext context, string distinguishedName, string objectClass, bool objectClassSpecified) { // validate context if (context == null) { throw new ArgumentNullException("context"); } // contexttype should be DirectoryServer if ((context.Name == null) || (!context.isServer())) { throw new ArgumentException(SR.TargetShouldBeServer, "context"); } // check that the distinguished name is not null or empty if (distinguishedName == null) { throw new ArgumentNullException("distinguishedName"); } if (distinguishedName.Length == 0) { throw new ArgumentException(SR.EmptyStringParameter, "distinguishedName"); } // initialize private variables this.context = new DirectoryContext(context); this.directoryEntryMgr = new DirectoryEntryManager(this.context); // validate the distinguished name // Utils.GetDnsNameFromDN will throw an ArgumentException if the dn is not valid (cannot be syntactically converted to dns name) _dnsName = Utils.GetDnsNameFromDN(distinguishedName); this.partitionName = distinguishedName; // // if the partition being created is a one-level partition, we do not support it // Component[] components = Utils.GetDNComponents(distinguishedName); if (components.Length == 1) { throw new NotSupportedException(SR.OneLevelPartitionNotSupported); } // check if the object class can be specified _appType = GetApplicationPartitionType(this.context); if ((_appType == ApplicationPartitionType.ADApplicationPartition) && (objectClassSpecified)) { throw new InvalidOperationException(SR.NoObjectClassForADPartition); } else if (objectClassSpecified) { // ADAM case and objectClass is explicitly specified, so must be validated if (objectClass == null) { throw new ArgumentNullException("objectClass"); } if (objectClass.Length == 0) { throw new ArgumentException(SR.EmptyStringParameter, "objectClass"); } } if (_appType == ApplicationPartitionType.ADApplicationPartition) { // // the target in the directory context could be the netbios name of the server, so we will get the dns name // (since application partition creation will fail if dns name is not specified) // string serverDnsName = null; try { DirectoryEntry rootDSEEntry = directoryEntryMgr.GetCachedDirectoryEntry(WellKnownDN.RootDSE); serverDnsName = (string)PropertyManager.GetPropertyValue(this.context, rootDSEEntry, PropertyManager.DnsHostName); } catch (COMException e) { ExceptionHelper.GetExceptionFromCOMException(this.context, e); } this.context = Utils.GetNewDirectoryContext(serverDnsName, DirectoryContextType.DirectoryServer, context); } } private void CreateApplicationPartition(string distinguishedName, string objectClass) { if (_appType == ApplicationPartitionType.ADApplicationPartition) { // // AD // 1. Bind to the non-existent application partition using the fast bind and delegation option // 2. Get the Parent object and create a new "domainDNS" object under it // 3. Set the instanceType and the description for the application partitin object // DirectoryEntry tempEntry = null; DirectoryEntry parent = null; try { AuthenticationTypes authType = Utils.DefaultAuthType | AuthenticationTypes.FastBind | AuthenticationTypes.Delegation; authType |= AuthenticationTypes.ServerBind; tempEntry = new DirectoryEntry("LDAP://" + context.GetServerName() + "/" + distinguishedName, context.UserName, context.Password, authType); parent = tempEntry.Parent; _domainDNSEntry = parent.Children.Add(Utils.GetRdnFromDN(distinguishedName), PropertyManager.DomainDNS); // set the instance type to 5 _domainDNSEntry.Properties[PropertyManager.InstanceType].Value = NCFlags.InstanceTypeIsNCHead | NCFlags.InstanceTypeIsWriteable; // mark this as uncommitted _committed = false; } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } finally { // dispose all resources if (parent != null) { parent.Dispose(); } if (tempEntry != null) { tempEntry.Dispose(); } } } else { // // ADAM // 1. Bind to the partitions container on the domain naming owner instance // 2. Create a disabled crossRef object for the new application partition // 3. Bind to the target hint and follow the same steps as for AD // try { InitializeCrossRef(distinguishedName); DirectoryEntry tempEntry = null; DirectoryEntry parent = null; try { AuthenticationTypes authType = Utils.DefaultAuthType | AuthenticationTypes.FastBind; authType |= AuthenticationTypes.ServerBind; tempEntry = new DirectoryEntry("LDAP://" + context.Name + "/" + distinguishedName, context.UserName, context.Password, authType); parent = tempEntry.Parent; _domainDNSEntry = parent.Children.Add(Utils.GetRdnFromDN(distinguishedName), objectClass); // set the instance type to 5 _domainDNSEntry.Properties[PropertyManager.InstanceType].Value = NCFlags.InstanceTypeIsNCHead | NCFlags.InstanceTypeIsWriteable; // mark this as uncommitted _committed = false; } finally { // dispose all resources if (parent != null) { parent.Dispose(); } if (tempEntry != null) { tempEntry.Dispose(); } } } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } } } private void InitializeCrossRef(string distinguishedName) { if (_crossRefEntry != null) // already initialized return; DirectoryEntry partitionsEntry = null; try { string namingFsmoName = GetNamingRoleOwner(); DirectoryContext roleOwnerContext = Utils.GetNewDirectoryContext(namingFsmoName, DirectoryContextType.DirectoryServer, context); partitionsEntry = DirectoryEntryManager.GetDirectoryEntry(roleOwnerContext, WellKnownDN.PartitionsContainer); string uniqueName = "CN={" + Guid.NewGuid() + "}"; _crossRefEntry = partitionsEntry.Children.Add(uniqueName, "crossRef"); string dnsHostName = null; if (_appType == ApplicationPartitionType.ADAMApplicationPartition) { // Bind to rootdse and get the server name DirectoryEntry rootDSE = directoryEntryMgr.GetCachedDirectoryEntry(WellKnownDN.RootDSE); string ntdsaName = (string)PropertyManager.GetPropertyValue(context, rootDSE, PropertyManager.DsServiceName); dnsHostName = Utils.GetAdamHostNameAndPortsFromNTDSA(context, ntdsaName); } else { // for AD the name in the context will be the dns name of the server dnsHostName = context.Name; } // create disabled cross ref object _crossRefEntry.Properties[PropertyManager.DnsRoot].Value = dnsHostName; _crossRefEntry.Properties[PropertyManager.Enabled].Value = false; _crossRefEntry.Properties[PropertyManager.NCName].Value = distinguishedName; } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } finally { if (partitionsEntry != null) { partitionsEntry.Dispose(); } } } private static ApplicationPartitionType GetApplicationPartitionType(DirectoryContext context) { ApplicationPartitionType type = ApplicationPartitionType.Unknown; DirectoryEntry rootDSE = DirectoryEntryManager.GetDirectoryEntry(context, WellKnownDN.RootDSE); try { foreach (string supportedCapability in rootDSE.Properties[PropertyManager.SupportedCapabilities]) { if (String.Compare(supportedCapability, SupportedCapability.ADOid, StringComparison.OrdinalIgnoreCase) == 0) { type = ApplicationPartitionType.ADApplicationPartition; } if (String.Compare(supportedCapability, SupportedCapability.ADAMOid, StringComparison.OrdinalIgnoreCase) == 0) { type = ApplicationPartitionType.ADAMApplicationPartition; } } } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } finally { rootDSE.Dispose(); } // should not happen if (type == ApplicationPartitionType.Unknown) { throw new ActiveDirectoryOperationException(SR.ApplicationPartitionTypeUnknown); } return type; } // we always get the crossEntry bound to the FSMO role // this is so that we do not encounter any replication delay related issues internal DirectoryEntry GetCrossRefEntry() { if (_crossRefEntry != null) { return _crossRefEntry; } DirectoryEntry partitionsEntry = DirectoryEntryManager.GetDirectoryEntry(context, directoryEntryMgr.ExpandWellKnownDN(WellKnownDN.PartitionsContainer)); try { _crossRefEntry = Utils.GetCrossRefEntry(context, partitionsEntry, Name); } finally { partitionsEntry.Dispose(); } return _crossRefEntry; } internal string GetNamingRoleOwner() { string namingFsmo = null; DirectoryEntry partitionsEntry = DirectoryEntryManager.GetDirectoryEntry(context, directoryEntryMgr.ExpandWellKnownDN(WellKnownDN.PartitionsContainer)); try { if (_appType == ApplicationPartitionType.ADApplicationPartition) { namingFsmo = Utils.GetDnsHostNameFromNTDSA(context, (string)PropertyManager.GetPropertyValue(context, partitionsEntry, PropertyManager.FsmoRoleOwner)); } else { namingFsmo = Utils.GetAdamDnsHostNameFromNTDSA(context, (string)PropertyManager.GetPropertyValue(context, partitionsEntry, PropertyManager.FsmoRoleOwner)); } } finally { partitionsEntry.Dispose(); } return namingFsmo; } private DirectoryServer FindDirectoryServerInternal(string siteName, bool forceRediscovery) { DirectoryServer directoryServer = null; LocatorOptions flag = 0; int errorCode = 0; DomainControllerInfo domainControllerInfo; if (siteName != null && siteName.Length == 0) { throw new ArgumentException(SR.EmptyStringParameter, "siteName"); } // Check that the application partition has been committed if (!_committed) { throw new InvalidOperationException(SR.CannotPerformOperationOnUncommittedObject); } // set the force rediscovery flag if required if (forceRediscovery) { flag = LocatorOptions.ForceRediscovery; } // call DsGetDcName errorCode = Locator.DsGetDcNameWrapper(null, _dnsName, siteName, (long)flag | (long)PrivateLocatorFlags.OnlyLDAPNeeded, out domainControllerInfo); if (errorCode == NativeMethods.ERROR_NO_SUCH_DOMAIN) { throw new ActiveDirectoryObjectNotFoundException(SR.ReplicaNotFound, typeof(DirectoryServer), null); } else if (errorCode != 0) { throw ExceptionHelper.GetExceptionFromErrorCode(errorCode); } Debug.Assert(domainControllerInfo.DomainControllerName.Length > 2, "ApplicationPartition:FindDirectoryServerInternal - domainControllerInfo.DomainControllerName.Length <= 2"); string dcName = domainControllerInfo.DomainControllerName.Substring(2); // create a new context object for the domain controller passing on only the // credentials from the forest context DirectoryContext dcContext = Utils.GetNewDirectoryContext(dcName, DirectoryContextType.DirectoryServer, context); directoryServer = new DomainController(dcContext, dcName); return directoryServer; } private ReadOnlyDirectoryServerCollection FindAllDirectoryServersInternal(string siteName) { if (siteName != null && siteName.Length == 0) { throw new ArgumentException(SR.EmptyStringParameter, "siteName"); } // Check that the application partition has been committed if (!_committed) { throw new InvalidOperationException(SR.CannotPerformOperationOnUncommittedObject); } ArrayList dcList = new ArrayList(); foreach (string dcName in Utils.GetReplicaList(context, Name, siteName, false /* isDefaultNC */, false /* isADAM */, false /* mustBeGC */)) { DirectoryContext dcContext = Utils.GetNewDirectoryContext(dcName, DirectoryContextType.DirectoryServer, context); dcList.Add(new DomainController(dcContext, dcName)); } return new ReadOnlyDirectoryServerCollection(dcList); } private ReadOnlyDirectoryServerCollection FindAllDiscoverableDirectoryServersInternal(string siteName) { if (siteName != null && siteName.Length == 0) { throw new ArgumentException(SR.EmptyStringParameter, "siteName"); } // Check that the application partition has been committed if (!_committed) { throw new InvalidOperationException(SR.CannotPerformOperationOnUncommittedObject); } long flag = (long)PrivateLocatorFlags.OnlyLDAPNeeded; return new ReadOnlyDirectoryServerCollection(Locator.EnumerateDomainControllers(context, _dnsName, siteName, flag)); } #endregion private methods } }
using Loon.Utils; using System; using Loon.Java; using UnityEngine; namespace Loon.Core.Geom { public class RectBox : Shape { public class Rect2i { public int left; public int top; public int right; public int bottom; public override int GetHashCode() { return JavaRuntime.IdentityHashCode(this); } public Rect2i() { } public Rect2i(int left_0, int top_1, int right_2, int bottom_3) { this.left = left_0; this.top = top_1; this.right = right_2; this.bottom = bottom_3; } public Rect2i(Rect2i r) { left = r.left; top = r.top; right = r.right; bottom = r.bottom; } public override bool Equals(object obj) { Rect2i r = (Rect2i) obj; if (r != null) { return left == r.left && top == r.top && right == r.right && bottom == r.bottom; } return false; } public bool IsEmpty() { return left >= right || top >= bottom; } public int Width() { return right - left; } public int Height() { return bottom - top; } public int CenterX() { return (left + right) >> 1; } public int CenterY() { return (top + bottom) >> 1; } public float ExactCenterX() { return (left + right) * 0.5f; } public float ExactCenterY() { return (top + bottom) * 0.5f; } public void SetEmpty() { left = right = top = bottom = 0; } public void Set(int left_0, int top_1, int right_2, int bottom_3) { this.left = left_0; this.top = top_1; this.right = right_2; this.bottom = bottom_3; } public void Set(Rect2i src) { this.left = src.left; this.top = src.top; this.right = src.right; this.bottom = src.bottom; } public void Offset(int dx, int dy) { left += dx; top += dy; right += dx; bottom += dy; } public void OffsetTo(int newLeft, int newTop) { right += newLeft - left; bottom += newTop - top; left = newLeft; top = newTop; } public void Inset(int dx, int dy) { left += dx; top += dy; right -= dx; bottom -= dy; } public bool Contains(int x, int y) { return left < right && top < bottom && x >= left && x < right && y >= top && y < bottom; } public bool Contains(int left_0, int top_1, int right_2, int bottom_3) { return this.left < this.right && this.top < this.bottom && this.left <= left_0 && this.top <= top_1 && this.right >= right_2 && this.bottom >= bottom_3; } public bool Contains(Rect2i r) { return this.left < this.right && this.top < this.bottom && left <= r.left && top <= r.top && right >= r.right && bottom >= r.bottom; } public bool Intersect(int left_0, int top_1, int right_2, int bottom_3) { if (this.left < right_2 && left_0 < this.right && this.top < bottom_3 && top_1 < this.bottom) { if (this.left < left_0) { this.left = left_0; } if (this.top < top_1) { this.top = top_1; } if (this.right > right_2) { this.right = right_2; } if (this.bottom > bottom_3) { this.bottom = bottom_3; } return true; } return false; } public bool Intersect(Rect2i r) { return Intersect(r.left, r.top, r.right, r.bottom); } public bool SetIntersect(Rect2i a, Rect2i b) { if (a.left < b.right && b.left < a.right && a.top < b.bottom && b.top < a.bottom) { left = Math.Max(a.left,b.left); top = Math.Max(a.top,b.top); right = Math.Min(a.right,b.right); bottom = Math.Min(a.bottom,b.bottom); return true; } return false; } public bool Intersects(int left_0, int top_1, int right_2, int bottom_3) { return this.left < right_2 && left_0 < this.right && this.top < bottom_3 && top_1 < this.bottom; } public static bool Intersects(Rect2i a, Rect2i b) { return a.left < b.right && b.left < a.right && a.top < b.bottom && b.top < a.bottom; } public void Union(int left_0, int top_1, int right_2, int bottom_3) { if ((left_0 < right_2) && (top_1 < bottom_3)) { if ((this.left < this.right) && (this.top < this.bottom)) { if (this.left > left_0) this.left = left_0; if (this.top > top_1) this.top = top_1; if (this.right < right_2) this.right = right_2; if (this.bottom < bottom_3) this.bottom = bottom_3; } else { this.left = left_0; this.top = top_1; this.right = right_2; this.bottom = bottom_3; } } } public void Union(Rect2i r) { Union(r.left, r.top, r.right, r.bottom); } public void Union(int x, int y) { if (x < left) { left = x; } else if (x > right) { right = x; } if (y < top) { top = y; } else if (y > bottom) { bottom = y; } } public void Sort() { if (left > right) { int temp = left; left = right; right = temp; } if (top > bottom) { int temp_0 = top; top = bottom; bottom = temp_0; } } public void Scale(float scale) { if (scale != 1.0f) { left = (int) (left * scale + 0.5f); top = (int) (top * scale + 0.5f); right = (int) (right * scale + 0.5f); bottom = (int) (bottom * scale + 0.5f); } } } public override int GetHashCode() { return JavaRuntime.IdentityHashCode(this); } public int width; public int height; public void Offset(Vector2f offset) { x += offset.x; y += offset.y; } public void Offset(int offsetX, int offsetY) { x += offsetX; y += offsetY; } public int Left() { return this.X(); } public int Right() { return (int) (this.x + this.width); } public int Top() { return this.Y(); } public int Bottom() { return (int) (this.y + this.height); } public RectBox() { SetBounds(0, 0, 0, 0); } public RectBox(int x, int y, int width_0, int height_1) { SetBounds(x, y, width_0, height_1); } public RectBox(float x, float y, float width_0, float height_1) { SetBounds(x, y, width_0, height_1); } public RectBox(double x, double y, double width_0, double height_1) { SetBounds(x, y, width_0, height_1); } public RectBox(RectBox rect) { SetBounds(rect.x, rect.y, rect.width, rect.height); } public void SetBounds(RectBox rect) { SetBounds(rect.x, rect.y, rect.width, rect.height); } public void SetBounds(double x, double y, double width_0, double height_1) { SetBounds((float) x, (float) y, (float) width_0, (float) height_1); } public void SetBounds(float x, float y, float width_0, float height_1) { this.type = ShapeType.BOX_SHAPE; this.x = x; this.y = y; this.width = (int) width_0; this.height = (int) height_1; this.minX = x; this.minY = y; this.maxX = x + width_0; this.maxY = y + height_1; this.pointsDirty = true; this.CheckPoints(); } public void Inflate(int horizontalValue, int verticalValue) { this.x -= horizontalValue; this.y -= verticalValue; this.width += horizontalValue * 2; this.height += verticalValue * 2; } public void SetLocation(RectBox r) { this.x = r.x; this.y = r.y; } public void SetLocation(Point r) { this.x = r.x; this.y = r.y; } public void SetLocation(int x, int y) { this.x = x; this.y = y; } public void Grow(float h, float v) { SetX(GetX() - h); SetY(GetY() - v); SetWidth(GetWidth() + (h * 2)); SetHeight(GetHeight() + (v * 2)); } public void ScaleGrow(float h, float v) { Grow(GetWidth() * (h - 1), GetHeight() * (v - 1)); } public override void SetScale(float sx, float sy) { if (scaleX != sx || scaleY != sy) { SetSize(width * (scaleX = sx), height * (scaleY * sy)); } } public void SetSize(float width_0, float height_1) { SetWidth(width_0); SetHeight(height_1); } public bool Overlaps(RectBox rectangle) { return !(x > rectangle.x + rectangle.width || x + width < rectangle.x || y > rectangle.y + rectangle.height || y + height < rectangle.y); } public int X() { return (int) x; } public int Y() { return (int) y; } public override float GetX() { return x; } public override void SetX(float x) { this.x = x; } public override float GetY() { return y; } public override void SetY(float y) { this.y = y; } public void Copy(RectBox other) { this.x = other.x; this.y = other.y; this.width = other.width; this.height = other.height; } public override float GetMinX() { return GetX(); } public override float GetMinY() { return GetY(); } public override float GetMaxX() { return this.x + this.width; } public override float GetMaxY() { return this.y + this.height; } public float GetRight() { return GetMaxX(); } public float GetBottom() { return GetMaxY(); } public float GetMiddleX() { return this.x + this.width / 2; } public float GetMiddleY() { return this.y + this.height / 2; } public override float GetCenterX() { return x + width / 2f; } public override float GetCenterY() { return y + height / 2f; } public static RectBox GetIntersection(RectBox a, RectBox b) { float a_x = a.GetX(); float a_r = a.GetRight(); float a_y = a.GetY(); float a_t = a.GetBottom(); float b_x = b.GetX(); float b_r = b.GetRight(); float b_y = b.GetY(); float b_t = b.GetBottom(); float i_x = MathUtils.Max(a_x, b_x); float i_r = MathUtils.Min(a_r, b_r); float i_y = MathUtils.Max(a_y, b_y); float i_t = MathUtils.Min(a_t, b_t); return (i_x < i_r && i_y < i_t) ? new RectBox(i_x, i_y, i_r - i_x, i_t - i_y) : null; } public static RectBox GetIntersection(RectBox a, RectBox b, RectBox result) { float a_x = a.GetX(); float a_r = a.GetRight(); float a_y = a.GetY(); float a_t = a.GetBottom(); float b_x = b.GetX(); float b_r = b.GetRight(); float b_y = b.GetY(); float b_t = b.GetBottom(); float i_x = MathUtils.Max(a_x, b_x); float i_r = MathUtils.Min(a_r, b_r); float i_y = MathUtils.Max(a_y, b_y); float i_t = MathUtils.Min(a_t, b_t); if (i_x < i_r && i_y < i_t) { result.SetBounds(i_x, i_y, i_r - i_x, i_t - i_y); return result; } return null; } public float[] ToFloat() { return new float[] { x, y, width, height }; } public override RectBox GetRect() { return this; } private Rect rectangle = new Rect(); public Rect GetRectangle2D() { rectangle.x = x; rectangle.y = y; rectangle.width = width; rectangle.height = height; return rectangle; } public override float GetHeight() { return height; } public void SetHeight(float height_0) { this.height = (int) height_0; } public override float GetWidth() { return width; } public void SetWidth(float width_0) { this.width = (int) width_0; } public override bool Equals(object obj) { if (obj is RectBox) { RectBox rect = (RectBox) obj; return Equals(rect.x, rect.y, rect.width, rect.height); } else { return false; } } public bool Equals(float x, float y, float width_0, float height_1) { return (this.x == x && this.y == y && this.width == width_0 && this.height == height_1); } public int GetArea() { return width * height; } public override bool Contains(float x, float y) { return Contains(x, y, 0, 0); } public bool Contains(float x, float y, float width_0, float height_1) { return (x >= this.x && y >= this.y && ((x + width_0) <= (this.x + this.width)) && ((y + height_1) <= (this.y + this.height))); } public bool Contains(RectBox rect) { return Contains(rect.x, rect.y, rect.width, rect.height); } public bool Intersects(RectBox rect) { return Intersects(rect.x, rect.y, rect.width, rect.height); } public bool Intersects(int x, int y) { return Intersects(0, 0, width, height); } public bool Intersects(float x, float y, float width_0, float height_1) { return x + width_0 > this.x && x < this.x + this.width && y + height_1 > this.y && y < this.y + this.height; } public void Intersection(RectBox rect) { Intersection(rect.x, rect.y, rect.width, rect.height); } public void Intersection(float x, float y, float width_0, float height_1) { int x1 = (int) MathUtils.Max(this.x, x); int y1 = (int) MathUtils.Max(this.y, y); int x2 = (int) MathUtils.Min(this.x + this.width - 1, x + width_0 - 1); int y2 = (int) MathUtils.Min(this.y + this.height - 1, y + height_1 - 1); SetBounds(x1, y1, Math.Max(0,x2 - x1 + 1), Math.Max(0,y2 - y1 + 1)); } public bool Inside(int x, int y) { return (x >= this.x) && ((x - this.x) < this.width) && (y >= this.y) && ((y - this.y) < this.height); } public RectBox GetIntersection(RectBox rect) { int x1 = (int) MathUtils.Max(x, rect.x); int x2 = (int) MathUtils.Min(x + width, rect.x + rect.width); int y1 = (int) MathUtils.Max(y, rect.y); int y2 = (int) MathUtils.Min(y + height, rect.y + rect.height); return new RectBox(x1, y1, x2 - x1, y2 - y1); } public void Union(RectBox rect) { Union(rect.x, rect.y, rect.width, rect.height); } public void Union(float x, float y, float width_0, float height_1) { int x1 = (int) MathUtils.Min(this.x, x); int y1 = (int) MathUtils.Min(this.y, y); int x2 = (int) MathUtils.Max(this.x + this.width - 1, x + width_0 - 1); int y2 = (int) MathUtils.Max(this.y + this.height - 1, y + height_1 - 1); SetBounds(x1, y1, x2 - x1 + 1, y2 - y1 + 1); } protected internal override void CreatePoints() { float useWidth = width; float useHeight = height; points = new float[8]; points[0] = x; points[1] = y; points[2] = x + useWidth; points[3] = y; points[4] = x + useWidth; points[5] = y + useHeight; points[6] = x; points[7] = y + useHeight; maxX = points[2]; maxY = points[5]; minX = points[0]; minY = points[1]; FindCenter(); CalculateRadius(); } public override Shape Transform(Matrix transform) { CheckPoints(); Polygon resultPolygon = new Polygon(); float[] result = new float[points.Length]; transform.Transform(points, 0, result, 0, points.Length / 2); resultPolygon.points = result; resultPolygon.FindCenter(); resultPolygon.CheckPoints(); return resultPolygon; } public void ModX(float xMod) { x += xMod; } public void ModY(float yMod) { y += yMod; } public void ModWidth(float w) { this.width += (int)w; } public void ModHeight(float h) { this.height += (int)h; } public bool IntersectsLine(float x1, float y1, float x2, float y2) { return Contains(x1, y1) || Contains(x2, y2); } public bool Inside(float x, float y) { return (x >= this.x) && ((x - this.x) < this.width) && (y >= this.y) && ((y - this.y) < this.height); } } }
using System; using UnityEngine; using System.Collections; using System.Runtime.InteropServices; namespace MMT { public class MobileMovieTexture : MonoBehaviour { #region Types public delegate void OnFinished(MobileMovieTexture sender); #endregion #region Editor Variables /// <summary> /// File path to the video file, includes the extension, usually .ogg or .ogv /// </summary> #if UNITY_EDITOR #if UNITY_3_5 || UNITY_4_0 || UNITY_4_1 || UNITY_4_2 || UNITY_4_3 || UNITY_4_5 || UNITY_4_6 [StreamingAssetsLinkAttribute(typeof(MovieTexture), "Movie")] #else [StreamingAssetsLinkAttribute(typeof(UnityEngine.Object), "Movie")] #endif #endif [SerializeField] private string m_path; /// <summary> /// Material(s) to decode the movie on to, MMT sets up the textures and the texture scale/offset /// </summary> [SerializeField] private Material[] m_movieMaterials; /// <summary> /// Whether to start playing automatically, be careful to set advance /// </summary> [SerializeField] private bool m_playAutomatically = true; /// <summary> /// Whether the movie should advance, used to pause, or also to just decode the first frame /// </summary> [SerializeField] private bool m_advance = true; /// <summary> /// How many times to loop, -1 == infinite /// </summary> [SerializeField] private int m_loopCount = -1; /// <summary> /// Playback speed, has to be positive, can't play backwards /// </summary> [SerializeField] private float m_playSpeed = 1.0f; /// <summary> /// Whether to scan the duration of the movie on opening. This makes opening movies more expensive as it reads the whole file. Ideally cache this off if you need it /// </summary> [SerializeField] private bool m_scanDuration = true; /// <summary> /// When seeking, it tries to find a keyframe to seek to, however it often fails. If this is set, after a seek, it will decode till it hits a keyframe. Without it set, you may see artifacts on a seek /// </summary> [SerializeField] private bool m_seekKeyFrame = false; #endregion #region Other Variables private IntPtr m_nativeContext = IntPtr.Zero; private IntPtr m_nativeTextureContext = IntPtr.Zero; private int m_picX = 0; private int m_picY = 0; private int m_yStride = 0; private int m_yHeight = 0; private int m_uvStride = 0; private int m_uvHeight = 0; private Vector2 m_uvYScale; private Vector2 m_uvYOffset; private Vector2 m_uvCrCbScale; private Vector2 m_uvCrCbOffset; private const int CHANNELS = 3; //Y,Cb,Cr private Texture2D[] m_ChannelTextures = new Texture2D[CHANNELS]; private double m_elapsedTime; private bool m_hasFinished = true; public MobileMovieTexture() { Height = 0; Width = 0; } #endregion /// <summary> /// Function to call on finish /// </summary> public event OnFinished onFinished; #region Properties /// <summary> /// File path to the video file, includes the extension, usually .ogg or .ogv /// </summary> public string Path { get { return m_path; } set { m_path = value; } } /// <summary> /// Whether the path is absolute or in the streaming assets directory /// </summary> public bool AbsolutePath { get; set; } /// <summary> /// Material to decode the movie on to, MMT sets up the textures and the texture scale/offset /// </summary> public Material[] MovieMaterial { get { return m_movieMaterials; } } /// <summary> /// Whether to start playing automatically, be careful to set advance /// </summary> public bool PlayAutomatically { set { m_playAutomatically = value; } } /// <summary> /// How many times to loop, -1 == infinite /// </summary> public int LoopCount { get { return m_loopCount; } set { m_loopCount = value; } } /// <summary> /// Playback speed, has to be positive, can't play backwards /// </summary> public float PlaySpeed { get { return m_playSpeed; } set { m_playSpeed = value; } } /// <summary> /// Whether to scan the duration of the movie on opening. This makes opening movies more expensive as it reads the whole file. Ideally cache this off if you need it /// </summary> public bool ScanDuration { get { return m_scanDuration; } set { m_scanDuration = value; } } /// <summary> /// When seeking, it tries to find a keyframe to seek to, however it often fails. If this is set, after a seek, it will decode till it hits a keyframe. Without it set, you may see artifacts on a seek /// </summary> public bool SeekKeyFrame { get { return m_seekKeyFrame; } set { m_seekKeyFrame = value; } } /// <summary> /// Width of the movie in pixels /// </summary> public int Width { get; private set; } /// <summary> /// Height of the movie in pixels /// </summary> public int Height { get; private set; } /// <summary> /// Aspect ratio (width/height) of movie /// </summary> public float AspectRatio { get { if (m_nativeContext != IntPtr.Zero) { return GetAspectRatio(m_nativeContext); } else { return 1.0f; } } } /// <summary> /// Frames per second of movie /// </summary> public double FPS { get { if (m_nativeContext != IntPtr.Zero) { return GetVideoFPS(m_nativeContext); } else { return 1.0; } } } /// <summary> /// Is the movie currently playing /// </summary> public bool IsPlaying { get { return m_nativeContext != IntPtr.Zero && !m_hasFinished && m_advance; } } public bool Pause { get { return !m_advance; } set { m_advance = !value; } } /// <summary> /// Use this to retrieve the play position and to seek. NB after you seek, the play position will not be exactly what you seeked to, as it is tries to find a key frame /// </summary> public double PlayPosition { get { return m_elapsedTime; } set { if (m_nativeContext != IntPtr.Zero) { m_elapsedTime = Seek(m_nativeContext, value, m_seekKeyFrame); } } } /// <summary> /// The length of the movie, this is only valid if you have ScanDuration set /// </summary> public double Duration { get { return m_nativeContext != IntPtr.Zero ? GetDuration(m_nativeContext) : 0.0; } } #endregion #region Native Interface #if UNITY_IPHONE && !UNITY_EDITOR private const string PLATFORM_DLL = "__Internal"; #else private const string PLATFORM_DLL = "theorawrapper"; #endif [DllImport(PLATFORM_DLL)] private static extern IntPtr CreateContext(); [DllImport(PLATFORM_DLL)] private static extern void DestroyContext(IntPtr context); [DllImport(PLATFORM_DLL)] private static extern bool OpenStream(IntPtr context, string path, int offset, int size, bool pot, bool scanDuration, int maxSkipFrames); [DllImport(PLATFORM_DLL)] private static extern void CloseStream(IntPtr context); [DllImport(PLATFORM_DLL)] private static extern int GetPicWidth(IntPtr context); [DllImport(PLATFORM_DLL)] private static extern int GetPicHeight(IntPtr context); [DllImport(PLATFORM_DLL)] private static extern int GetPicX(IntPtr context); [DllImport(PLATFORM_DLL)] private static extern int GetPicY(IntPtr context); [DllImport(PLATFORM_DLL)] private static extern int GetYStride(IntPtr context); [DllImport(PLATFORM_DLL)] private static extern int GetYHeight(IntPtr context); [DllImport(PLATFORM_DLL)] private static extern int GetUVStride(IntPtr context); [DllImport(PLATFORM_DLL)] private static extern int GetUVHeight(IntPtr context); [DllImport(PLATFORM_DLL)] private static extern bool HasFinished(IntPtr context); [DllImport(PLATFORM_DLL)] private static extern double GetDecodedFrameTime(IntPtr context); [DllImport(PLATFORM_DLL)] private static extern double GetUploadedFrameTime(IntPtr context); [DllImport(PLATFORM_DLL)] private static extern double GetTargetDecodeFrameTime(IntPtr context); [DllImport(PLATFORM_DLL)] private static extern void SetTargetDisplayDecodeTime(IntPtr context, double targetTime); [DllImport(PLATFORM_DLL)] private static extern double GetVideoFPS(IntPtr context); [DllImport(PLATFORM_DLL)] private static extern float GetAspectRatio(IntPtr context); [DllImport(PLATFORM_DLL)] private static extern double Seek(IntPtr context, double seconds, bool waitKeyFrame); [DllImport(PLATFORM_DLL)] private static extern double GetDuration(IntPtr context); [DllImport(PLATFORM_DLL)] private static extern IntPtr GetNativeHandle(IntPtr context, int planeIndex); [DllImport(PLATFORM_DLL)] private static extern IntPtr GetNativeTextureContext(IntPtr context); [DllImport(PLATFORM_DLL)] private static extern void SetPostProcessingLevel(IntPtr context, int level); #endregion #region Behaviour Overrides void Start() { m_nativeContext = CreateContext(); if (m_nativeContext == IntPtr.Zero) { Debug.LogError("Unable to create Mobile Movie Texture native context"); return; } if (m_playAutomatically) { Play(); } } void OnDestroy() { DestroyTextures(); DestroyContext(m_nativeContext); } void Update() { if (m_nativeContext != IntPtr.Zero && !m_hasFinished) { //Texture context can change when resizing windows //when put into the background etc var textureContext = GetNativeTextureContext(m_nativeContext); if (textureContext != m_nativeTextureContext) { DestroyTextures(); AllocateTexures(); m_nativeTextureContext = textureContext; } m_hasFinished = HasFinished(m_nativeContext); if (!m_hasFinished) { if (m_advance) { m_elapsedTime += Time.deltaTime * Mathf.Max(m_playSpeed, 0.0f); } } else { if ((m_loopCount - 1) > 0 || m_loopCount == -1) { if (m_loopCount != -1) { m_loopCount--; } m_elapsedTime = m_elapsedTime % GetDecodedFrameTime(m_nativeContext); Seek(m_nativeContext, 0, false); m_hasFinished = false; } else if (onFinished != null) { m_elapsedTime = GetDecodedFrameTime(m_nativeContext); onFinished(this); } } SetTargetDisplayDecodeTime(m_nativeContext, m_elapsedTime); } } #endregion #region Methods public void Play() { m_elapsedTime = 0.0; Open(); m_hasFinished = false; //Create a manager if we don't have one if (MobileMovieManager.Instance == null) { gameObject.AddComponent<MobileMovieManager>(); } } public void Stop() { CloseStream(m_nativeContext); m_hasFinished = true; } private void Open() { string path = m_path; long offset = 0; long length = 0; if (!AbsolutePath) { switch (Application.platform) { case RuntimePlatform.Android: path = Application.dataPath; if (!AssetStream.GetZipFileOffsetLength(Application.dataPath, m_path, out offset, out length)) { return; } break; default: path = Application.streamingAssetsPath + "/" + m_path; break; } } //No platform should need power of 2 textures anymore const bool powerOf2Textures = false; //This is maximum frames decoded before a frame is uploaded const int maxSkipFrames = 16; if (m_nativeContext != IntPtr.Zero && OpenStream(m_nativeContext, path, (int)offset, (int)length, powerOf2Textures, m_scanDuration, maxSkipFrames)) { Width = GetPicWidth(m_nativeContext); Height = GetPicHeight(m_nativeContext); m_picX = GetPicX(m_nativeContext); m_picY = GetPicY(m_nativeContext); m_yStride = GetYStride(m_nativeContext); m_yHeight = GetYHeight(m_nativeContext); m_uvStride = GetUVStride(m_nativeContext); m_uvHeight = GetUVHeight(m_nativeContext); CalculateUVScaleOffset(); } else { Debug.LogError("Unable to open movie " + m_nativeContext, this); } } private void AllocateTexures() { m_ChannelTextures[0] = Texture2D.CreateExternalTexture(m_yStride, m_yHeight, TextureFormat.Alpha8, false, false, GetNativeHandle(m_nativeContext, 0)); m_ChannelTextures[1] = Texture2D.CreateExternalTexture(m_uvStride, m_uvHeight, TextureFormat.Alpha8, false, false, GetNativeHandle(m_nativeContext, 1)); m_ChannelTextures[2] = Texture2D.CreateExternalTexture(m_uvStride, m_uvHeight, TextureFormat.Alpha8, false, false, GetNativeHandle(m_nativeContext, 2)); if (m_movieMaterials != null) { for (int i = 0; i < m_movieMaterials.Length; ++i) { var mat = m_movieMaterials[i]; if (mat != null) { SetTextures(mat); } } } } public void SetTextures(Material material) { material.SetTexture("_YTex", m_ChannelTextures[0]); material.SetTexture("_CbTex", m_ChannelTextures[1]); material.SetTexture("_CrTex", m_ChannelTextures[2]); material.SetTextureScale("_YTex", m_uvYScale); material.SetTextureOffset("_YTex", m_uvYOffset); material.SetTextureScale("_CbTex", m_uvCrCbScale); material.SetTextureOffset("_CbTex", m_uvCrCbOffset); } public void RemoveTextures(Material material) { material.SetTexture("_YTex", null); material.SetTexture("_CbTex", null); material.SetTexture("_CrTex", null); } private void CalculateUVScaleOffset() { var picWidth = (float)Width; var picHeight = (float)Height; var picX = (float)m_picX; var picY = (float)m_picY; var yStride = (float)m_yStride; var yHeight = (float)m_yHeight; var uvStride = (float)m_uvStride; var uvHeight = (float)m_uvHeight; m_uvYScale = new Vector2(picWidth / yStride, -(picHeight / yHeight)); m_uvYOffset = new Vector2(picX / yStride, (picHeight + picY) / yHeight); m_uvCrCbScale = new Vector2(); m_uvCrCbOffset = new Vector2(); if (m_uvStride == m_yStride) { m_uvCrCbScale.x = m_uvYScale.x; } else { m_uvCrCbScale.x = (picWidth / 2.0f) / uvStride; } if (m_uvHeight == m_yHeight) { m_uvCrCbScale.y = m_uvYScale.y; m_uvCrCbOffset = m_uvYOffset; } else { m_uvCrCbScale.y = -((picHeight / 2.0f) / uvHeight); m_uvCrCbOffset = new Vector2((picX / 2.0f) / uvStride, (((picHeight + picY) / 2.0f) / uvHeight)); } } private void DestroyTextures() { if (m_movieMaterials != null) { for (int i = 0; i < m_movieMaterials.Length; ++i) { var mat = m_movieMaterials[i]; if (mat != null) { RemoveTextures(mat); } } } for (int i = 0; i < CHANNELS; ++i) { if (m_ChannelTextures[i] != null) { Destroy(m_ChannelTextures[i]); m_ChannelTextures[i] = null; } } } #endregion } }
using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using NetGore.Collections; using NUnit.Framework; // ReSharper disable RedundantAssignment #pragma warning disable 219 #pragma warning disable 168 namespace NetGore.Tests.Collections { [TestFixture] public class DArrayTests { [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "TrackFree")] static void AddTestSub(bool trackFree) { var o1 = new object(); var o2 = new object(); var d = new DArray<object>(trackFree) { o1, o2 }; Assert.IsTrue(d.Contains(o1), "TrackFree = " + trackFree); Assert.IsTrue(d.Contains(o2), "TrackFree = " + trackFree); Assert.AreEqual(2, d.Length, "TrackFree = " + trackFree); } [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "TrackFree")] static void AddValueTypeTestSub(bool trackFree) { const int o1 = new int(); const int o2 = new int(); var d = new DArray<object>(trackFree) { o1, o2 }; Assert.IsTrue(d.Contains(o1), "TrackFree = " + trackFree); Assert.IsTrue(d.Contains(o2), "TrackFree = " + trackFree); Assert.AreEqual(2, d.Length, "TrackFree = " + trackFree); } [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "ArgumentOutOfRangeException")] static void CanGetAndIndexRangeTestSub(bool trackFree) { var d = new DArray<object>(trackFree); d[0] = new object(); var o = d[0]; Assert.IsFalse(d.CanGet(-1)); Assert.Throws<ArgumentOutOfRangeException>(() => o = d[-1], "Failed to generate ArgumentOutOfRangeException for d[-1]."); Assert.IsFalse(d.CanGet(1)); Assert.Throws<ArgumentOutOfRangeException>(() => o = d[-1], "Failed to generate ArgumentOutOfRangeException for d[1]."); } [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "IndexOutOfRangeException" )] static void ClearTestSub(bool trackFree) { const int size = 50; var d = new DArray<object>(trackFree); for (var i = 0; i < size; i++) { d[i] = new object(); } d.Clear(); Assert.AreEqual(0, d.Length); Assert.AreEqual(0, d.Count); object o; Assert.Throws<ArgumentOutOfRangeException>(() => o = d[0], "Failed to generate IndexOutOfRangeException for d[0]."); Assert.IsFalse(d.CanGet(0)); } static void ContainsTestSub(bool trackFree) { const int size = 10; var d = new DArray<object>(trackFree); for (var i = 0; i < size; i++) { d[i] = new object(); } for (var i = 0; i < size; i++) { Assert.IsTrue(d.Contains(d[i])); } } [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "TrackFree")] static void CountTestSub(bool trackFree) { var expectedCount = 0; var d = new DArray<object>(trackFree); for (var i = 0; i < 1000; i++) { if ((i % 3) == 0) { d[i] = new object(); expectedCount++; Assert.AreEqual(expectedCount, d.Count, "TrackFree = " + trackFree); } } for (var i = 0; i < d.Length; i++) { if ((i % 2) == 0 && d[i] != null) { Assert.IsNotNull(d[i]); d.RemoveAt(i); expectedCount--; Assert.IsNull(d[i]); Assert.AreEqual(expectedCount, d.Count, "TrackFree = " + trackFree); } } for (var i = 0; i < 50; i++) { d.Add(new object()); expectedCount++; Assert.AreEqual(expectedCount, d.Count, "TrackFree = " + trackFree); } } [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "objs")] static void EnumerateTestSub(bool trackFree) { const int size = 100; var objs = new object[size]; for (var i = 0; i < size; i++) { if ((i % 2) == 0) objs[i] = new object(); } var d = new DArray<object>(size * 2, trackFree); for (var i = 0; i < size; i++) { if (objs[i] != null) d[i] = objs[i]; } foreach (var obj in d) { var i = d.IndexOf(obj); Assert.IsNotNull(obj); Assert.AreSame(objs[i], obj); Assert.AreSame(objs[i], d[i]); objs[i] = null; } var remainingObjs = objs.Count(obj => obj != null); Assert.AreEqual(0, remainingObjs, "One or more items failed to be enumerated since all enumerated " + "items should have been removed from objs[]."); } static void EnumerateValueTypeTestSub(bool trackFree) { const int size = 100; var objs = new int[size]; for (var i = 0; i < size; i++) { objs[i] = i * 4; } var d = new DArray<int>(size * 2, trackFree); for (var i = 0; i < size; i++) { d[i] = objs[i]; } foreach (var obj in d) { var i = d.IndexOf(obj); Assert.AreEqual(objs[i], obj); Assert.AreEqual(objs[i], d[i]); objs[i] = -1; } var remainingObjs = objs.Where(obj => obj != -1).Count(); Assert.AreEqual(0, remainingObjs, "One or more items failed to be enumerated since all enumerated " + "items should be equal to -1."); } [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "InvalidOperationException")] [SuppressMessage("Microsoft.Performance", "CA1804:RemoveUnusedLocals", MessageId = "obj")] static void EnumerateVersionTestSub(bool trackFree) { var d = new DArray<object>(50, trackFree) { new object(), new object() }; try { foreach (var obj in d) { d[10] = new object(); } Assert.Fail("Failed to generate InvalidOperationException."); } catch (InvalidOperationException) { } try { foreach (var obj in d) { d.RemoveAt(0); } Assert.Fail("Failed to generate InvalidOperationException."); } catch (InvalidOperationException) { } try { foreach (var obj in d) { d[0] = new object(); } Assert.Fail("Failed to generate InvalidOperationException."); } catch (InvalidOperationException) { } } static void GetSetTestSub(bool trackFree) { const int size = 1000; var objs = new object[size]; for (var i = 0; i < size; i++) { objs[i] = new object(); } var d = new DArray<object>(trackFree); for (var i = 0; i < 1000; i++) { d[i] = objs[i]; } for (var i = 0; i < 1000; i++) { Assert.AreSame(objs[i], d[i]); } } static void IndexOfTestSub(bool trackFree) { const int size = 50; var d = new DArray<object>(trackFree); for (var i = 0; i < size; i++) { d[i] = new object(); } for (var i = 0; i < size; i++) { Assert.AreEqual(i, d.IndexOf(d[i])); } } static void IndexOfValueTypeTestSub(bool trackFree) { const int size = 50; var d = new DArray<int>(trackFree); for (var i = 0; i < size; i++) { d[i] = i * 4; } for (var i = 0; i < size; i++) { Assert.AreEqual(i, d.IndexOf(d[i])); } } [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "TrackFree")] static void LengthTestSub(bool trackFree) { var d = new DArray<object>(trackFree); for (var i = 0; i < 1000; i++) { Assert.AreEqual(i, d.Length, "TrackFree = " + trackFree); d[i] = new object(); } } [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "TrackFree")] static void RemoveInsertTestSub(bool trackFree) { var d = new DArray<object>(trackFree); for (var i = 0; i < 10; i++) { d[i] = new object(); } d.RemoveAt(0); d.RemoveAt(5); d.RemoveAt(6); d.RemoveAt(9); var usedIndices = new List<int>(); for (var i = 0; i < 7; i++) { usedIndices.Add(d.Insert(new object())); } var expected = new int[] { 0, 5, 6, 9, 10, 11, 12 }; Assert.AreEqual(usedIndices.Count(), expected.Length); foreach (var i in usedIndices) { Assert.IsTrue(expected.Contains(i), "TrackFree = " + trackFree); } } static void RemoveTestSub(bool trackFree) { var d = new DArray<object>(trackFree); for (var i = 0; i < 10; i++) { d[i] = new object(); } var o = d[5]; Assert.IsTrue(d.Remove(o)); Assert.IsFalse(d.Contains(o)); } [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "TrackFree")] static void TrimTestSub(bool trackFree) { const int size = 1000; var objs = new object[size]; for (var i = 0; i < size / 2; i++) { if ((i % 3) == 0) objs[i] = i.ToString(); } var d = new DArray<object>(size, trackFree); for (var i = 0; i < size; i++) { if (objs[i] != null) d[i] = objs[i]; } d.Trim(); // Make sure our data has not changed for (var i = 0; i < size; i++) { if (objs[i] != null) Assert.AreSame(objs[i], d[i], "TrackFree = " + trackFree); } // Make sure the null slots are still null for (var i = 0; i < d.Length; i++) { Assert.AreSame(objs[i], d[i], "TrackFree = " + trackFree); } // Make sure that inserts first fill up the gaps, THEN expand var startLen = d.Length; var gaps = startLen - d.Count; for (var i = 0; i < gaps; i++) { d.Insert(new object()); } Assert.AreEqual(startLen, d.Length, "TrackFree = " + trackFree); // Make sure we start expanding now for (var i = 0; i < 10; i++) { var before = d.Length; d.Insert(new object()); Assert.AreEqual(before + 1, d.Length, "TrackFree = " + trackFree); } } #region Unit tests [Test] public void AddTest() { AddTestSub(true); AddTestSub(false); } [Test] public void AddValueTypeTest() { AddValueTypeTestSub(true); AddValueTypeTestSub(false); } [Test] public void CanGetAndIndexRangeTest() { CanGetAndIndexRangeTestSub(true); CanGetAndIndexRangeTestSub(false); } [Test] public void ClearTest() { ClearTestSub(true); ClearTestSub(false); } [Test] public void ContainsTest() { ContainsTestSub(true); ContainsTestSub(false); } [Test] public void CountTest() { CountTestSub(true); CountTestSub(false); } [Test] public void EnumerateTest() { EnumerateTestSub(true); EnumerateTestSub(false); } [Test] public void EnumerateValueTypeTest() { EnumerateValueTypeTestSub(true); EnumerateValueTypeTestSub(false); } [Test] public void EnumerateVersionTest() { EnumerateVersionTestSub(true); EnumerateVersionTestSub(false); } [Test] public void GetSetTest() { GetSetTestSub(true); GetSetTestSub(false); } [Test] public void IndexOfTest() { IndexOfTestSub(true); IndexOfTestSub(false); } [Test] public void IndexOfValueTypeTest() { IndexOfValueTypeTestSub(true); IndexOfValueTypeTestSub(false); } [Test] public void LengthTest() { LengthTestSub(true); LengthTestSub(false); } [Test] public void RemoveInsertTest() { RemoveInsertTestSub(true); RemoveInsertTestSub(false); } [Test] public void RemoveTest() { RemoveTestSub(true); RemoveTestSub(false); } [Test] public void TrimTest() { TrimTestSub(true); TrimTestSub(false); } #endregion } }
using System; using System.Collections.Generic; using System.Collections.Immutable; using AutoMapper.Extended.Net4; using HappyMapper.AutoMapper.ConfigurationAPI; using HappyMapper.AutoMapper.ConfigurationAPI.Configuration; namespace HappyMapper.Text { internal class MethodInnerCodeBuilder { public Dictionary<TypePair, string> TemplateCache { get; } = new Dictionary<TypePair, string>(); public ImmutableDictionary<TypePair, TypeMap> ExplicitTypeMaps { get; } public IDictionary<TypePair, TypeMap> ImplicitTypeMaps { get; } public TypeMapFactory TypeMapFactory { get; } = new TypeMapFactory(); public MapperConfigurationExpression Options { get; } public HashSet<string> DetectedLocations { get; } = new HashSet<string>(); public MethodInnerCodeBuilder(IDictionary<TypePair, TypeMap> explicitTypeMaps, MapperConfigurationExpression mce) { ExplicitTypeMaps = explicitTypeMaps.ToImmutableDictionary(); ImplicitTypeMaps = explicitTypeMaps.ShallowCopy(); Options = mce; } public Assignment GetAssignment(TypeMap map) { RememberTypeLocations(map); var assignment = ProcessTypeMap(map); return assignment; } private Assignment ProcessTypeMap(TypeMap rootMap) { var recorder = new Recorder(); using (var bfm = new BeforeMapPrinter(new TypeNameContext(rootMap), recorder)) { } foreach (PropertyMap propertyMap in rootMap.PropertyMaps) { if (propertyMap.Ignored) continue; RememberTypeLocations(propertyMap); var ctx = new PropertyNameContext(propertyMap); //using (var condition = new ConditionPrinter(context, Recorder)) using (var condition = new ConditionPrinterV2(ctx, recorder)) { //assign without explicit cast var st = propertyMap.SrcType; var dt = propertyMap.DestType; if (dt.IsAssignableFrom(st) || dt.IsImplicitCastableFrom(st)) { recorder.AppendAssignment(Assign.AsNoCast, ctx); continue; } //assign with explicit cast if (dt.IsExplicitCastableFrom(st)) { recorder.AppendAssignment(Assign.AsExplicitCast, ctx); continue; } //assign with src.ToString() call if (dt == typeof(string) && st != typeof(string)) { recorder.AppendAssignment(Assign.AsToStringCall, ctx); continue; } //assign with Convert call if (st == typeof(string) && dt.IsValueType) { recorder.AppendAssignment(Assign.AsStringToValueTypeConvert, ctx); continue; } if (!st.IsValueType && !dt.IsValueType) { using (var block = new Block(recorder, "if", $"{{0}}.{ctx.SrcMemberName} == null")) { recorder.AppendLine($"{{1}}.{ctx.DestMemberName} = null;"); } using (var block = new Block(recorder, "else")) { if (st.IsCollectionType() && dt.IsCollectionType()) { string template = AssignCollections(ctx) .AddPropertyNamesToTemplate(ctx.SrcMemberName, ctx.DestMemberName); recorder.AppendLine(template); } else { string template = AssignReferenceTypes(ctx) .AddPropertyNamesToTemplate(ctx.SrcMemberName, ctx.DestMemberName); recorder.AppendLine(template); } } } else { throw new NotSupportedException(); } } } var assignment = recorder.ToAssignment(); TemplateCache.AddIfNotExist(rootMap.TypePair, assignment.RelativeTemplate); return assignment; } private string AssignCollections(IPropertyNameContext ctx) { var recorder = new Recorder(); var itemSrcType = ctx.SrcType.GenericTypeArguments[0]; var itemDestType = ctx.DestType.GenericTypeArguments[0]; using (var block = new Block(recorder, "if", "{1} == null")) { string newCollection = CreationTemplates.NewCollection(ctx.DestType, "{0}.Count"); recorder.AppendLine($"{{1}} = {newCollection};"); } using (var block = new Block(recorder, "else")) { recorder.AppendLine("{1}.Clear();"); } //fill new (or cleared) collection with the new set of items recorder.AppendLine(CreationTemplates.Add("{1}", "{0}.Count", itemDestType)); //inner cycle variables (on each iteration itemSrcName is mapped to itemDestName). string itemSrcName = "src_" + NamingTools.NewGuid(4); string itemDestName = "dest_" + NamingTools.NewGuid(4); var typePair = new TypePair(itemSrcType, itemDestType); Assignment itemAssignment = new Assignment(); string cachedTemplate; if (TemplateCache.TryGetValue(typePair, out cachedTemplate)) { itemAssignment.RelativeTemplate = cachedTemplate; } else if (itemSrcType.IsCollectionType() && itemDestType.IsCollectionType()) { var innerContext = PropertyNameContextFactory.CreateWithoutPropertyMap( itemSrcType, itemDestType, itemSrcName, itemDestName); string innerTemplate = AssignCollections(innerContext); itemAssignment.RelativeTemplate = innerTemplate; } else { var nodeMap = GetTypeMap(typePair); itemAssignment = ProcessTypeMap(nodeMap); } string iterationCode = itemAssignment.GetCode(itemSrcName, itemDestName); string forCode = StatementTemplates.For(iterationCode, new ForDeclarationContext( "{0}", "{1}", itemSrcName, itemDestName)); recorder.AppendLine(forCode); string template = recorder.ToAssignment().RelativeTemplate; return template; } private string AssignReferenceTypes(PropertyNameContext ctx) { Recorder recorder = new Recorder(); //has parameterless ctor if (ctx.DestType.HasParameterlessCtor()) { recorder.AppendLine($"{{1}} = {StatementTemplates.New(ctx.DestTypeFullName)};"); } else { throw new HappyMapperException(ErrorMessages.NoParameterlessCtor(ctx.DestType)); } string template; //typepair isn't in template cache if (!TemplateCache.TryGetValue(ctx.TypePair, out template)) { var nodeMap = GetTypeMap(ctx.TypePair); var assignment = ProcessTypeMap(nodeMap); template = assignment.RelativeTemplate; } recorder.AppendLine(template); return recorder.ToAssignment().RelativeTemplate; } /// <summary> /// remember all used types /// </summary> /// <param name="propertyMap"></param> private void RememberTypeLocations(PropertyMap propertyMap) { DetectedLocations.Add(propertyMap.SrcType.Assembly.Location); DetectedLocations.Add(propertyMap.DestType.Assembly.Location); } private void RememberTypeLocations(TypeMap typeMap) { DetectedLocations.Add(typeMap.SourceType.Assembly.Location); DetectedLocations.Add(typeMap.DestinationType.Assembly.Location); } private TypeMap GetTypeMap(TypePair typePair) { TypeMap nodeMap; //typepair explicitly mapped by user ExplicitTypeMaps.TryGetValue(typePair, out nodeMap); if (nodeMap == null) { if (!ImplicitTypeMaps.TryGetValue(typePair, out nodeMap)) { //create implicit map nodeMap = TypeMapFactory.CreateTypeMap(typePair.SourceType, typePair.DestinationType, Options); ImplicitTypeMaps.AddIfNotExist(nodeMap); } } return nodeMap; } } }
// <copyright file="SqlEventSourceTests.netfx.cs" company="OpenTelemetry Authors"> // Copyright The OpenTelemetry Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> #if NETFRAMEWORK using System; using System.Data; using System.Data.SqlClient; using System.Diagnostics; using System.Diagnostics.Tracing; using System.Linq; using System.Threading.Tasks; using Moq; using OpenTelemetry.Instrumentation.SqlClient.Implementation; using OpenTelemetry.Tests; using OpenTelemetry.Trace; using Xunit; namespace OpenTelemetry.Instrumentation.SqlClient.Tests { public class SqlEventSourceTests { /* To run the integration tests, set the OTEL_SQLCONNECTIONSTRING machine-level environment variable to a valid Sql Server connection string. To use Docker... 1) Run: docker run -d --name sql2019 -e "ACCEPT_EULA=Y" -e "SA_PASSWORD=Pass@word" -p 5433:1433 mcr.microsoft.com/mssql/server:2019-latest 2) Set OTEL_SQLCONNECTIONSTRING as: Data Source=127.0.0.1,5433; User ID=sa; Password=Pass@word */ private const string SqlConnectionStringEnvVarName = "OTEL_SQLCONNECTIONSTRING"; private static readonly string SqlConnectionString = SkipUnlessEnvVarFoundTheoryAttribute.GetEnvironmentVariable(SqlConnectionStringEnvVarName); [Trait("CategoryName", "SqlIntegrationTests")] [SkipUnlessEnvVarFoundTheory(SqlConnectionStringEnvVarName)] [InlineData(CommandType.Text, "select 1/1", false)] [InlineData(CommandType.Text, "select 1/0", false, true)] [InlineData(CommandType.StoredProcedure, "sp_who", false)] [InlineData(CommandType.StoredProcedure, "sp_who", true)] public async Task SuccessfulCommandTest(CommandType commandType, string commandText, bool captureText, bool isFailure = false) { var activityProcessor = new Mock<BaseProcessor<Activity>>(); using var shutdownSignal = Sdk.CreateTracerProviderBuilder() .AddProcessor(activityProcessor.Object) .AddSqlClientInstrumentation(options => { options.SetDbStatement = captureText; }) .Build(); using SqlConnection sqlConnection = new SqlConnection(SqlConnectionString); await sqlConnection.OpenAsync().ConfigureAwait(false); string dataSource = sqlConnection.DataSource; sqlConnection.ChangeDatabase("master"); using SqlCommand sqlCommand = new SqlCommand(commandText, sqlConnection) { CommandType = commandType, }; try { await sqlCommand.ExecuteNonQueryAsync().ConfigureAwait(false); } catch { } Assert.Equal(3, activityProcessor.Invocations.Count); var activity = (Activity)activityProcessor.Invocations[1].Arguments[0]; VerifyActivityData(commandText, captureText, isFailure, dataSource, activity); } [Theory] [InlineData(typeof(FakeBehavingAdoNetSqlEventSource), CommandType.Text, "select 1/1", false)] [InlineData(typeof(FakeBehavingAdoNetSqlEventSource), CommandType.Text, "select 1/0", false, true)] [InlineData(typeof(FakeBehavingAdoNetSqlEventSource), CommandType.StoredProcedure, "sp_who", false)] [InlineData(typeof(FakeBehavingAdoNetSqlEventSource), CommandType.StoredProcedure, "sp_who", true, false, 0, true)] [InlineData(typeof(FakeBehavingMdsSqlEventSource), CommandType.Text, "select 1/1", false)] [InlineData(typeof(FakeBehavingMdsSqlEventSource), CommandType.Text, "select 1/0", false, true)] [InlineData(typeof(FakeBehavingMdsSqlEventSource), CommandType.StoredProcedure, "sp_who", false)] [InlineData(typeof(FakeBehavingMdsSqlEventSource), CommandType.StoredProcedure, "sp_who", true, false, 0, true)] public void EventSourceFakeTests( Type eventSourceType, CommandType commandType, string commandText, bool captureText, bool isFailure = false, int sqlExceptionNumber = 0, bool enableConnectionLevelAttributes = false) { using IFakeBehavingSqlEventSource fakeSqlEventSource = (IFakeBehavingSqlEventSource)Activator.CreateInstance(eventSourceType); var activityProcessor = new Mock<BaseProcessor<Activity>>(); using var shutdownSignal = Sdk.CreateTracerProviderBuilder() .AddProcessor(activityProcessor.Object) .AddSqlClientInstrumentation(options => { options.SetDbStatement = captureText; options.EnableConnectionLevelAttributes = enableConnectionLevelAttributes; }) .Build(); int objectId = Guid.NewGuid().GetHashCode(); fakeSqlEventSource.WriteBeginExecuteEvent(objectId, "127.0.0.1", "master", commandType == CommandType.StoredProcedure ? commandText : string.Empty); // success is stored in the first bit in compositeState 0b001 int successFlag = !isFailure ? 1 : 0; // isSqlException is stored in the second bit in compositeState 0b010 int isSqlExceptionFlag = sqlExceptionNumber > 0 ? 2 : 0; // synchronous state is stored in the third bit in compositeState 0b100 int synchronousFlag = false ? 4 : 0; int compositeState = successFlag | isSqlExceptionFlag | synchronousFlag; fakeSqlEventSource.WriteEndExecuteEvent(objectId, compositeState, sqlExceptionNumber); shutdownSignal.Dispose(); Assert.Equal(5, activityProcessor.Invocations.Count); // SetTracerProvider/OnStart/OnEnd/OnShutdown/Dispose called. var activity = (Activity)activityProcessor.Invocations[2].Arguments[0]; VerifyActivityData(commandText, captureText, isFailure, "127.0.0.1", activity, enableConnectionLevelAttributes); } [Theory] [InlineData(typeof(FakeMisbehavingAdoNetSqlEventSource))] [InlineData(typeof(FakeMisbehavingMdsSqlEventSource))] public void EventSourceFakeUnknownEventWithNullPayloadTest(Type eventSourceType) { using IFakeMisbehavingSqlEventSource fakeSqlEventSource = (IFakeMisbehavingSqlEventSource)Activator.CreateInstance(eventSourceType); var activityProcessor = new Mock<BaseProcessor<Activity>>(); using var shutdownSignal = Sdk.CreateTracerProviderBuilder() .AddProcessor(activityProcessor.Object) .AddSqlClientInstrumentation() .Build(); fakeSqlEventSource.WriteUnknownEventWithNullPayload(); shutdownSignal.Dispose(); Assert.Equal(3, activityProcessor.Invocations.Count); // SetTracerProvider/OnShutdown/Dispose called. } [Theory] [InlineData(typeof(FakeMisbehavingAdoNetSqlEventSource))] [InlineData(typeof(FakeMisbehavingMdsSqlEventSource))] public void EventSourceFakeInvalidPayloadTest(Type eventSourceType) { using IFakeMisbehavingSqlEventSource fakeSqlEventSource = (IFakeMisbehavingSqlEventSource)Activator.CreateInstance(eventSourceType); var activityProcessor = new Mock<BaseProcessor<Activity>>(); using var shutdownSignal = Sdk.CreateTracerProviderBuilder() .AddProcessor(activityProcessor.Object) .AddSqlClientInstrumentation() .Build(); fakeSqlEventSource.WriteBeginExecuteEvent("arg1"); fakeSqlEventSource.WriteEndExecuteEvent("arg1", "arg2", "arg3", "arg4"); shutdownSignal.Dispose(); Assert.Equal(3, activityProcessor.Invocations.Count); // SetTracerProvider/OnShutdown/Dispose called. } [Theory] [InlineData(typeof(FakeBehavingAdoNetSqlEventSource))] [InlineData(typeof(FakeBehavingMdsSqlEventSource))] public void DefaultCaptureTextFalse(Type eventSourceType) { using IFakeBehavingSqlEventSource fakeSqlEventSource = (IFakeBehavingSqlEventSource)Activator.CreateInstance(eventSourceType); var activityProcessor = new Mock<BaseProcessor<Activity>>(); using var shutdownSignal = Sdk.CreateTracerProviderBuilder() .AddProcessor(activityProcessor.Object) .AddSqlClientInstrumentation() .Build(); int objectId = Guid.NewGuid().GetHashCode(); const string commandText = "TestCommandTest"; fakeSqlEventSource.WriteBeginExecuteEvent(objectId, "127.0.0.1", "master", commandText); // success is stored in the first bit in compositeState 0b001 int successFlag = 1; // isSqlException is stored in the second bit in compositeState 0b010 int isSqlExceptionFlag = 2; // synchronous state is stored in the third bit in compositeState 0b100 int synchronousFlag = 4; int compositeState = successFlag | isSqlExceptionFlag | synchronousFlag; fakeSqlEventSource.WriteEndExecuteEvent(objectId, compositeState, 0); shutdownSignal.Dispose(); Assert.Equal(5, activityProcessor.Invocations.Count); // SetTracerProvider/OnStart/OnEnd/OnShutdown/Dispose called. var activity = (Activity)activityProcessor.Invocations[2].Arguments[0]; const bool captureText = false; VerifyActivityData(commandText, captureText, false, "127.0.0.1", activity, false); } private static void VerifyActivityData( string commandText, bool captureText, bool isFailure, string dataSource, Activity activity, bool enableConnectionLevelAttributes = false) { Assert.Equal("master", activity.DisplayName); Assert.Equal(ActivityKind.Client, activity.Kind); Assert.Equal(SqlActivitySourceHelper.MicrosoftSqlServerDatabaseSystemName, activity.GetTagValue(SemanticConventions.AttributeDbSystem)); if (!enableConnectionLevelAttributes) { Assert.Equal(dataSource, activity.GetTagValue(SemanticConventions.AttributePeerService)); } else { var connectionDetails = SqlClientInstrumentationOptions.ParseDataSource(dataSource); if (!string.IsNullOrEmpty(connectionDetails.ServerHostName)) { Assert.Equal(connectionDetails.ServerHostName, activity.GetTagValue(SemanticConventions.AttributeNetPeerName)); } else { Assert.Equal(connectionDetails.ServerIpAddress, activity.GetTagValue(SemanticConventions.AttributeNetPeerIp)); } if (!string.IsNullOrEmpty(connectionDetails.InstanceName)) { Assert.Equal(connectionDetails.InstanceName, activity.GetTagValue(SemanticConventions.AttributeDbMsSqlInstanceName)); } if (!string.IsNullOrEmpty(connectionDetails.Port)) { Assert.Equal(connectionDetails.Port, activity.GetTagValue(SemanticConventions.AttributeNetPeerPort)); } } Assert.Equal("master", activity.GetTagValue(SemanticConventions.AttributeDbName)); // "db.statement_type" is never set by the SqlEventSource instrumentation Assert.Null(activity.GetTagValue(SpanAttributeConstants.DatabaseStatementTypeKey)); if (captureText) { Assert.Equal(commandText, activity.GetTagValue(SemanticConventions.AttributeDbStatement)); } else { Assert.Null(activity.GetTagValue(SemanticConventions.AttributeDbStatement)); } if (!isFailure) { Assert.Equal(Status.Unset, activity.GetStatus()); } else { var status = activity.GetStatus(); Assert.Equal(Status.Error.StatusCode, status.StatusCode); Assert.NotNull(status.Description); } } #pragma warning disable SA1201 // Elements should appear in the correct order // Helper interface to be able to have single test method for multiple EventSources, want to keep it close to the event sources themselves. private interface IFakeBehavingSqlEventSource : IDisposable #pragma warning restore SA1201 // Elements should appear in the correct order { void WriteBeginExecuteEvent(int objectId, string dataSource, string databaseName, string commandText); void WriteEndExecuteEvent(int objectId, int compositeState, int sqlExceptionNumber); } private interface IFakeMisbehavingSqlEventSource : IDisposable { void WriteBeginExecuteEvent(string arg1); void WriteEndExecuteEvent(string arg1, string arg2, string arg3, string arg4); void WriteUnknownEventWithNullPayload(); } [EventSource(Name = SqlEventSourceListener.AdoNetEventSourceName + "-FakeFriendly")] private class FakeBehavingAdoNetSqlEventSource : EventSource, IFakeBehavingSqlEventSource { [Event(SqlEventSourceListener.BeginExecuteEventId)] public void WriteBeginExecuteEvent(int objectId, string dataSource, string databaseName, string commandText) { this.WriteEvent(SqlEventSourceListener.BeginExecuteEventId, objectId, dataSource, databaseName, commandText); } [Event(SqlEventSourceListener.EndExecuteEventId)] public void WriteEndExecuteEvent(int objectId, int compositeState, int sqlExceptionNumber) { this.WriteEvent(SqlEventSourceListener.EndExecuteEventId, objectId, compositeState, sqlExceptionNumber); } } [EventSource(Name = SqlEventSourceListener.MdsEventSourceName + "-FakeFriendly")] private class FakeBehavingMdsSqlEventSource : EventSource, IFakeBehavingSqlEventSource { [Event(SqlEventSourceListener.BeginExecuteEventId)] public void WriteBeginExecuteEvent(int objectId, string dataSource, string databaseName, string commandText) { this.WriteEvent(SqlEventSourceListener.BeginExecuteEventId, objectId, dataSource, databaseName, commandText); } [Event(SqlEventSourceListener.EndExecuteEventId)] public void WriteEndExecuteEvent(int objectId, int compositeState, int sqlExceptionNumber) { this.WriteEvent(SqlEventSourceListener.EndExecuteEventId, objectId, compositeState, sqlExceptionNumber); } } [EventSource(Name = SqlEventSourceListener.AdoNetEventSourceName + "-FakeEvil")] private class FakeMisbehavingAdoNetSqlEventSource : EventSource, IFakeMisbehavingSqlEventSource { [Event(SqlEventSourceListener.BeginExecuteEventId)] public void WriteBeginExecuteEvent(string arg1) { this.WriteEvent(SqlEventSourceListener.BeginExecuteEventId, arg1); } [Event(SqlEventSourceListener.EndExecuteEventId)] public void WriteEndExecuteEvent(string arg1, string arg2, string arg3, string arg4) { this.WriteEvent(SqlEventSourceListener.EndExecuteEventId, arg1, arg2, arg3, arg4); } [Event(3)] public void WriteUnknownEventWithNullPayload() { object[] args = null; this.WriteEvent(3, args); } } [EventSource(Name = SqlEventSourceListener.MdsEventSourceName + "-FakeEvil")] private class FakeMisbehavingMdsSqlEventSource : EventSource, IFakeMisbehavingSqlEventSource { [Event(SqlEventSourceListener.BeginExecuteEventId)] public void WriteBeginExecuteEvent(string arg1) { this.WriteEvent(SqlEventSourceListener.BeginExecuteEventId, arg1); } [Event(SqlEventSourceListener.EndExecuteEventId)] public void WriteEndExecuteEvent(string arg1, string arg2, string arg3, string arg4) { this.WriteEvent(SqlEventSourceListener.EndExecuteEventId, arg1, arg2, arg3, arg4); } [Event(3)] public void WriteUnknownEventWithNullPayload() { object[] args = null; this.WriteEvent(3, args); } } } } #endif
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Security; using System.Security.AccessControl; using System.Security.Principal; using System.ServiceProcess; using System.Threading; using Microsoft.VisualStudio.Services.Agent.Util; using Microsoft.Win32; namespace Microsoft.VisualStudio.Services.Agent.Listener.Configuration { [ServiceLocator(Default = typeof(NativeWindowsServiceHelper))] public interface INativeWindowsServiceHelper : IAgentService { string GetUniqueBuildGroupName(); bool LocalGroupExists(string groupName); void CreateLocalGroup(string groupName); void DeleteLocalGroup(string groupName); void AddMemberToLocalGroup(string accountName, string groupName); void GrantFullControlToGroup(string path, string groupName); void RemoveGroupFromFolderSecuritySetting(string folderPath, string groupName); bool IsUserHasLogonAsServicePrivilege(string domain, string userName); bool GrantUserLogonAsServicePrivilage(string domain, string userName); bool IsValidCredential(string domain, string userName, string logonPassword); NTAccount GetDefaultServiceAccount(); NTAccount GetDefaultAdminServiceAccount(); bool IsServiceExists(string serviceName); void InstallService(string serviceName, string serviceDisplayName, string logonAccount, string logonPassword); void UninstallService(string serviceName); void StartService(string serviceName); void StopService(string serviceName); void CreateVstsAgentRegistryKey(); void DeleteVstsAgentRegistryKey(); string GetSecurityId(string domainName, string userName); void SetAutoLogonPassword(string password); void ResetAutoLogonPassword(); bool IsRunningInElevatedMode(); void LoadUserProfile(string domain, string userName, string logonPassword, out IntPtr tokenHandle, out PROFILEINFO userProfile); void UnloadUserProfile(IntPtr tokenHandle, PROFILEINFO userProfile); bool IsValidAutoLogonCredential(string domain, string userName, string logonPassword); void GrantDirectoryPermissionForAccount(string accountName, IList<string> folders); void RevokeDirectoryPermissionForAccount(IList<string> folders); } public class NativeWindowsServiceHelper : AgentService, INativeWindowsServiceHelper { private const string AgentServiceLocalGroupPrefix = "VSTS_AgentService_G"; private ITerminal _term; public override void Initialize(IHostContext hostContext) { ArgUtil.NotNull(hostContext, nameof(hostContext)); base.Initialize(hostContext); _term = hostContext.GetService<ITerminal>(); } public string GetUniqueBuildGroupName() { return AgentServiceLocalGroupPrefix + IOUtil.GetPathHash(HostContext.GetDirectory(WellKnownDirectory.Bin)).Substring(0, 5); } // TODO: Make sure to remove Old agent's group and registry changes made during auto upgrade to vsts-agent. public bool LocalGroupExists(string groupName) { Trace.Entering(); bool exists = false; IntPtr bufptr; int returnCode = NetLocalGroupGetInfo(null, // computer name groupName, 1, // group info with comment out bufptr); // Win32GroupAPI.LocalGroupInfo try { switch (returnCode) { case ReturnCode.S_OK: Trace.Info($"Local group '{groupName}' exist."); exists = true; break; case ReturnCode.NERR_GroupNotFound: case ReturnCode.ERROR_NO_SUCH_ALIAS: exists = false; break; case ReturnCode.ERROR_ACCESS_DENIED: // NOTE: None of the exception thrown here are userName facing. The caller logs this exception and prints a more understandable error throw new UnauthorizedAccessException(StringUtil.Loc("AccessDenied")); default: throw new InvalidOperationException(StringUtil.Loc("OperationFailed", nameof(NetLocalGroupGetInfo), returnCode)); } } finally { // we don't need to actually read the info to determine whether it exists int bufferFreeError = NetApiBufferFree(bufptr); if (bufferFreeError != 0) { Trace.Error(StringUtil.Format("Buffer free error, could not free buffer allocated, error code: {0}", bufferFreeError)); } } return exists; } public void CreateLocalGroup(string groupName) { Trace.Entering(); LocalGroupInfo groupInfo = new LocalGroupInfo(); groupInfo.Name = groupName; groupInfo.Comment = StringUtil.Format("Built-in group used by Team Foundation Server."); int returnCode = NetLocalGroupAdd(null, // computer name 1, // 1 means include comment ref groupInfo, 0); // param error number // return on success if (returnCode == ReturnCode.S_OK) { Trace.Info($"Local Group '{groupName}' created"); return; } // Error Cases switch (returnCode) { case ReturnCode.NERR_GroupExists: case ReturnCode.ERROR_ALIAS_EXISTS: Trace.Info(StringUtil.Format("Group {0} already exists", groupName)); break; case ReturnCode.ERROR_ACCESS_DENIED: throw new UnauthorizedAccessException(StringUtil.Loc("AccessDenied")); case ReturnCode.ERROR_INVALID_PARAMETER: throw new ArgumentException(StringUtil.Loc("InvalidGroupName", groupName)); default: throw new InvalidOperationException(StringUtil.Loc("OperationFailed", nameof(NetLocalGroupAdd), returnCode)); } } public void DeleteLocalGroup(string groupName) { Trace.Entering(); int returnCode = NetLocalGroupDel(null, // computer name groupName); // return on success if (returnCode == ReturnCode.S_OK) { Trace.Info($"Local Group '{groupName}' deleted"); return; } // Error Cases switch (returnCode) { case ReturnCode.NERR_GroupNotFound: case ReturnCode.ERROR_NO_SUCH_ALIAS: Trace.Info(StringUtil.Format("Group {0} not exists.", groupName)); break; case ReturnCode.ERROR_ACCESS_DENIED: throw new UnauthorizedAccessException(StringUtil.Loc("AccessDenied")); default: throw new InvalidOperationException(StringUtil.Loc("OperationFailed", nameof(NetLocalGroupDel), returnCode)); } } public void AddMemberToLocalGroup(string accountName, string groupName) { Trace.Entering(); LocalGroupMemberInfo memberInfo = new LocalGroupMemberInfo(); memberInfo.FullName = accountName; int returnCode = NetLocalGroupAddMembers(null, // computer name groupName, 3, // group info with fullname (vs sid) ref memberInfo, 1); //total entries // return on success if (returnCode == ReturnCode.S_OK) { Trace.Info($"Account '{accountName}' is added to local group '{groupName}'."); return; } // Error Cases switch (returnCode) { case ReturnCode.ERROR_MEMBER_IN_ALIAS: Trace.Info(StringUtil.Format("Account {0} is already member of group {1}", accountName, groupName)); break; case ReturnCode.NERR_GroupNotFound: case ReturnCode.ERROR_NO_SUCH_ALIAS: throw new ArgumentException(StringUtil.Loc("GroupDoesNotExists", groupName)); case ReturnCode.ERROR_NO_SUCH_MEMBER: throw new ArgumentException(StringUtil.Loc("MemberDoesNotExists", accountName)); case ReturnCode.ERROR_INVALID_MEMBER: throw new ArgumentException(StringUtil.Loc("InvalidMember")); case ReturnCode.ERROR_ACCESS_DENIED: throw new UnauthorizedAccessException(StringUtil.Loc("AccessDenied")); default: throw new InvalidOperationException(StringUtil.Loc("OperationFailed", nameof(NetLocalGroupAddMembers), returnCode)); } } public void GrantFullControlToGroup(string path, string groupName) { Trace.Entering(); if (IsGroupHasFullControl(path, groupName)) { Trace.Info($"Local group '{groupName}' already has full control to path '{path}'."); return; } DirectoryInfo dInfo = new DirectoryInfo(path); DirectorySecurity dSecurity = dInfo.GetAccessControl(); if (!dSecurity.AreAccessRulesCanonical) { Trace.Warning("Acls are not canonical, this may cause failure"); } dSecurity.AddAccessRule( new FileSystemAccessRule( groupName, FileSystemRights.FullControl, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow)); dInfo.SetAccessControl(dSecurity); } private bool IsGroupHasFullControl(string path, string groupName) { DirectoryInfo dInfo = new DirectoryInfo(path); DirectorySecurity dSecurity = dInfo.GetAccessControl(); var allAccessRuls = dSecurity.GetAccessRules(true, true, typeof(SecurityIdentifier)).Cast<FileSystemAccessRule>(); SecurityIdentifier sid = (SecurityIdentifier)new NTAccount(groupName).Translate(typeof(SecurityIdentifier)); if (allAccessRuls.Any(x => x.IdentityReference.Value == sid.ToString() && x.AccessControlType == AccessControlType.Allow && x.FileSystemRights.HasFlag(FileSystemRights.FullControl) && x.InheritanceFlags == (InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit) && x.PropagationFlags == PropagationFlags.None)) { return true; } else { return false; } } public bool IsUserHasLogonAsServicePrivilege(string domain, string userName) { Trace.Entering(); ArgUtil.NotNullOrEmpty(userName, nameof(userName)); bool userHasPermission = false; using (LsaPolicy lsaPolicy = new LsaPolicy()) { IntPtr rightsPtr; uint count; uint result = LsaEnumerateAccountRights(lsaPolicy.Handle, GetSidBinaryFromWindows(domain, userName), out rightsPtr, out count); try { if (result == 0) { IntPtr incrementPtr = rightsPtr; for (int i = 0; i < count; i++) { LSA_UNICODE_STRING nativeRightString = Marshal.PtrToStructure<LSA_UNICODE_STRING>(incrementPtr); string rightString = Marshal.PtrToStringUni(nativeRightString.Buffer); Trace.Verbose($"Account {userName} has '{rightString}' right."); if (string.Equals(rightString, s_logonAsServiceName, StringComparison.OrdinalIgnoreCase)) { userHasPermission = true; } incrementPtr += Marshal.SizeOf(nativeRightString); } } else { Trace.Error($"Can't enumerate account rights, return code {result}."); } } finally { result = LsaFreeMemory(rightsPtr); if (result != 0) { Trace.Error(StringUtil.Format("Failed to free memory from LsaEnumerateAccountRights. Return code : {0} ", result)); } } } return userHasPermission; } public bool GrantUserLogonAsServicePrivilage(string domain, string userName) { Trace.Entering(); ArgUtil.NotNullOrEmpty(userName, nameof(userName)); using (LsaPolicy lsaPolicy = new LsaPolicy()) { // STATUS_SUCCESS == 0 uint result = LsaAddAccountRights(lsaPolicy.Handle, GetSidBinaryFromWindows(domain, userName), LogonAsServiceRights, 1); if (result == 0) { Trace.Info($"Successfully grant logon as service privilage to account '{userName}'"); return true; } else { Trace.Info($"Fail to grant logon as service privilage to account '{userName}', error code {result}."); return false; } } } public static bool IsWellKnownIdentity(String accountName) { NTAccount ntaccount = new NTAccount(accountName); SecurityIdentifier sid = (SecurityIdentifier)ntaccount.Translate(typeof(SecurityIdentifier)); SecurityIdentifier networkServiceSid = new SecurityIdentifier(WellKnownSidType.NetworkServiceSid, null); SecurityIdentifier localServiceSid = new SecurityIdentifier(WellKnownSidType.LocalServiceSid, null); SecurityIdentifier localSystemSid = new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null); return sid.Equals(networkServiceSid) || sid.Equals(localServiceSid) || sid.Equals(localSystemSid); } public bool IsValidCredential(string domain, string userName, string logonPassword) { return IsValidCredentialInternal(domain, userName, logonPassword, LOGON32_LOGON_NETWORK); } public bool IsValidAutoLogonCredential(string domain, string userName, string logonPassword) { return IsValidCredentialInternal(domain, userName, logonPassword, LOGON32_LOGON_INTERACTIVE); } public NTAccount GetDefaultServiceAccount() { SecurityIdentifier sid = new SecurityIdentifier(WellKnownSidType.NetworkServiceSid, domainSid: null); NTAccount account = sid.Translate(typeof(NTAccount)) as NTAccount; if (account == null) { throw new InvalidOperationException(StringUtil.Loc("NetworkServiceNotFound")); } return account; } public NTAccount GetDefaultAdminServiceAccount() { SecurityIdentifier sid = new SecurityIdentifier(WellKnownSidType.LocalSystemSid, domainSid: null); NTAccount account = sid.Translate(typeof(NTAccount)) as NTAccount; if (account == null) { throw new InvalidOperationException(StringUtil.Loc("LocalSystemAccountNotFound")); } return account; } public void RemoveGroupFromFolderSecuritySetting(string folderPath, string groupName) { DirectoryInfo dInfo = new DirectoryInfo(folderPath); if (dInfo.Exists) { DirectorySecurity dSecurity = dInfo.GetAccessControl(); var allAccessRuls = dSecurity.GetAccessRules(true, true, typeof(SecurityIdentifier)).Cast<FileSystemAccessRule>(); SecurityIdentifier sid = (SecurityIdentifier)new NTAccount(groupName).Translate(typeof(SecurityIdentifier)); foreach (FileSystemAccessRule ace in allAccessRuls) { if (String.Equals(sid.ToString(), ace.IdentityReference.Value, StringComparison.OrdinalIgnoreCase)) { dSecurity.RemoveAccessRuleSpecific(ace); } } dInfo.SetAccessControl(dSecurity); } } public bool IsServiceExists(string serviceName) { Trace.Entering(); ServiceController service = ServiceController.GetServices().FirstOrDefault(x => x.ServiceName.Equals(serviceName, StringComparison.OrdinalIgnoreCase)); return service != null; } public void InstallService(string serviceName, string serviceDisplayName, string logonAccount, string logonPassword) { Trace.Entering(); string agentServiceExecutable = "\"" + Path.Combine(HostContext.GetDirectory(WellKnownDirectory.Bin), WindowsServiceControlManager.WindowsServiceControllerName) + "\""; IntPtr scmHndl = IntPtr.Zero; IntPtr svcHndl = IntPtr.Zero; IntPtr tmpBuf = IntPtr.Zero; IntPtr svcLock = IntPtr.Zero; try { //invoke the service with special argument, that tells it to register an event log trace source (need to run as an admin) using (var processInvoker = HostContext.CreateService<IProcessInvoker>()) { processInvoker.OutputDataReceived += delegate (object sender, ProcessDataReceivedEventArgs message) { _term.WriteLine(message.Data); }; processInvoker.ErrorDataReceived += delegate (object sender, ProcessDataReceivedEventArgs message) { _term.WriteLine(message.Data); }; processInvoker.ExecuteAsync(workingDirectory: string.Empty, fileName: agentServiceExecutable, arguments: "init", environment: null, requireExitCodeZero: true, cancellationToken: CancellationToken.None).GetAwaiter().GetResult(); } Trace.Verbose(StringUtil.Format("Trying to open SCManager.")); scmHndl = OpenSCManager(null, null, ServiceManagerRights.AllAccess); if (scmHndl.ToInt64() <= 0) { throw new InvalidOperationException(StringUtil.Loc("FailedToOpenSCM")); } Trace.Verbose(StringUtil.Format("Opened SCManager. Trying to create service {0}", serviceName)); svcHndl = CreateService(scmHndl, serviceName, serviceDisplayName, ServiceRights.AllAccess, SERVICE_WIN32_OWN_PROCESS, ServiceBootFlag.AutoStart, ServiceError.Normal, agentServiceExecutable, null, IntPtr.Zero, null, logonAccount, logonPassword); if (svcHndl.ToInt64() <= 0) { throw new InvalidOperationException(StringUtil.Loc("OperationFailed", nameof(CreateService), GetLastError())); } _term.WriteLine(StringUtil.Loc("ServiceInstalled", serviceName)); //set recovery option to restart on failure. ArrayList failureActions = new ArrayList(); //first failure, we will restart the service right away. failureActions.Add(new FailureAction(RecoverAction.Restart, 0)); //second failure, we will restart the service after 1 min. failureActions.Add(new FailureAction(RecoverAction.Restart, 60000)); //subsequent failures, we will restart the service after 1 min failureActions.Add(new FailureAction(RecoverAction.Restart, 60000)); // Lock the Service Database svcLock = LockServiceDatabase(scmHndl); if (svcLock.ToInt64() <= 0) { throw new InvalidOperationException(StringUtil.Loc("FailedToLockServiceDB")); } int[] actions = new int[failureActions.Count * 2]; int currInd = 0; foreach (FailureAction fa in failureActions) { actions[currInd] = (int)fa.Type; actions[++currInd] = fa.Delay; currInd++; } // Need to pack 8 bytes per struct tmpBuf = Marshal.AllocHGlobal(failureActions.Count * 8); // Move array into marshallable pointer Marshal.Copy(actions, 0, tmpBuf, failureActions.Count * 2); // Change service error actions // Set the SERVICE_FAILURE_ACTIONS struct SERVICE_FAILURE_ACTIONS sfa = new SERVICE_FAILURE_ACTIONS(); sfa.cActions = failureActions.Count; sfa.dwResetPeriod = SERVICE_NO_CHANGE; sfa.lpCommand = String.Empty; sfa.lpRebootMsg = String.Empty; sfa.lpsaActions = tmpBuf.ToInt64(); // Call the ChangeServiceFailureActions() abstraction of ChangeServiceConfig2() bool falureActionsResult = ChangeServiceFailureActions(svcHndl, SERVICE_CONFIG_FAILURE_ACTIONS, ref sfa); //Check the return if (!falureActionsResult) { int lastErrorCode = (int)GetLastError(); Exception win32exception = new Win32Exception(lastErrorCode); if (lastErrorCode == ReturnCode.ERROR_ACCESS_DENIED) { throw new SecurityException(StringUtil.Loc("AccessDeniedSettingRecoveryOption"), win32exception); } else { throw win32exception; } } else { _term.WriteLine(StringUtil.Loc("ServiceRecoveryOptionSet", serviceName)); } // Change service to delayed auto start SERVICE_DELAYED_AUTO_START_INFO sdasi = new SERVICE_DELAYED_AUTO_START_INFO(); sdasi.fDelayedAutostart = true; // Call the ChangeServiceDelayedAutoStart() abstraction of ChangeServiceConfig2() bool delayedStartResult = ChangeServiceDelayedAutoStart(svcHndl, SERVICE_CONFIG_DELAYED_AUTO_START_INFO, ref sdasi); //Check the return if (!delayedStartResult) { int lastErrorCode = (int)GetLastError(); Exception win32exception = new Win32Exception(lastErrorCode); if (lastErrorCode == ReturnCode.ERROR_ACCESS_DENIED) { throw new SecurityException(StringUtil.Loc("AccessDeniedSettingDelayedStartOption"), win32exception); } else { throw win32exception; } } else { _term.WriteLine(StringUtil.Loc("ServiceDelayedStartOptionSet", serviceName)); } _term.WriteLine(StringUtil.Loc("ServiceConfigured", serviceName)); } finally { if (scmHndl != IntPtr.Zero) { // Unlock the service database if (svcLock != IntPtr.Zero) { UnlockServiceDatabase(svcLock); svcLock = IntPtr.Zero; } // Close the service control manager handle CloseServiceHandle(scmHndl); scmHndl = IntPtr.Zero; } // Close the service handle if (svcHndl != IntPtr.Zero) { CloseServiceHandle(svcHndl); svcHndl = IntPtr.Zero; } // Free the memory if (tmpBuf != IntPtr.Zero) { Marshal.FreeHGlobal(tmpBuf); tmpBuf = IntPtr.Zero; } } } public void UninstallService(string serviceName) { Trace.Entering(); Trace.Verbose(StringUtil.Format("Trying to open SCManager.")); IntPtr scmHndl = OpenSCManager(null, null, ServiceManagerRights.Connect); if (scmHndl.ToInt64() <= 0) { throw new InvalidOperationException(StringUtil.Loc("FailedToOpenSCManager")); } try { Trace.Verbose(StringUtil.Format("Opened SCManager. query installed service {0}", serviceName)); IntPtr serviceHndl = OpenService(scmHndl, serviceName, ServiceRights.StandardRightsRequired | ServiceRights.Stop | ServiceRights.QueryStatus); if (serviceHndl == IntPtr.Zero) { int lastError = Marshal.GetLastWin32Error(); throw new Win32Exception(lastError); } try { Trace.Info(StringUtil.Format("Trying to delete service {0}", serviceName)); int result = DeleteService(serviceHndl); if (result == 0) { result = Marshal.GetLastWin32Error(); throw new Win32Exception(result, StringUtil.Loc("CouldNotRemoveService", serviceName)); } Trace.Info("successfully removed the service"); } finally { CloseServiceHandle(serviceHndl); } } finally { CloseServiceHandle(scmHndl); } } public void StartService(string serviceName) { Trace.Entering(); try { ServiceController service = ServiceController.GetServices().FirstOrDefault(x => x.ServiceName.Equals(serviceName, StringComparison.OrdinalIgnoreCase)); if (service != null) { service.Start(); _term.WriteLine(StringUtil.Loc("ServiceStartedSuccessfully", serviceName)); } else { throw new InvalidOperationException(StringUtil.Loc("CanNotFindService", serviceName)); } } catch (Exception exception) { Trace.Error(exception); _term.WriteError(StringUtil.Loc("CanNotStartService")); // This is the last step in the configuration. Even if the start failed the status of the configuration should be error // If its configured through scripts its mandatory we indicate the failure where configuration failed to start the service throw; } } public void StopService(string serviceName) { Trace.Entering(); try { ServiceController service = ServiceController.GetServices().FirstOrDefault(x => x.ServiceName.Equals(serviceName, StringComparison.OrdinalIgnoreCase)); if (service != null) { if (service.Status == ServiceControllerStatus.Running) { Trace.Info("Trying to stop the service"); service.Stop(); try { _term.WriteLine(StringUtil.Loc("WaitForServiceToStop")); service.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(35)); } catch (System.ServiceProcess.TimeoutException) { throw new InvalidOperationException(StringUtil.Loc("CanNotStopService", serviceName)); } } Trace.Info("Successfully stopped the service"); } else { Trace.Info(StringUtil.Loc("CanNotFindService", serviceName)); } } catch (Exception exception) { Trace.Error(exception); _term.WriteError(StringUtil.Loc("CanNotStopService", serviceName)); // Log the exception but do not report it as error. We can try uninstalling the service and then report it as error if something goes wrong. } } public void CreateVstsAgentRegistryKey() { RegistryKey tfsKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\TeamFoundationServer\15.0", true); if (tfsKey == null) { //We could be on a machine that doesn't have TFS installed on it, create the key tfsKey = Registry.LocalMachine.CreateSubKey(@"SOFTWARE\Microsoft\TeamFoundationServer\15.0"); } if (tfsKey == null) { throw new ArgumentNullException("Unable to create regiestry key: 'HKLM\\SOFTWARE\\Microsoft\\TeamFoundationServer\\15.0'"); } try { using (RegistryKey vstsAgentsKey = tfsKey.CreateSubKey("VstsAgents")) { String hash = IOUtil.GetPathHash(HostContext.GetDirectory(WellKnownDirectory.Bin)); using (RegistryKey agentKey = vstsAgentsKey.CreateSubKey(hash)) { agentKey.SetValue("InstallPath", Path.Combine(HostContext.GetDirectory(WellKnownDirectory.Bin), "Agent.Listener.exe")); } } } finally { tfsKey.Dispose(); } } public void DeleteVstsAgentRegistryKey() { RegistryKey tfsKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\TeamFoundationServer\15.0", true); if (tfsKey != null) { try { RegistryKey vstsAgentsKey = tfsKey.OpenSubKey("VstsAgents", true); if (vstsAgentsKey != null) { try { String hash = IOUtil.GetPathHash(HostContext.GetDirectory(WellKnownDirectory.Bin)); vstsAgentsKey.DeleteSubKeyTree(hash); } finally { vstsAgentsKey.Dispose(); } } } finally { tfsKey.Dispose(); } } } public string GetSecurityId(string domainName, string userName) { var account = new NTAccount(domainName, userName); var sid = account.Translate(typeof(SecurityIdentifier)); return sid != null ? sid.ToString() : null; } public void SetAutoLogonPassword(string password) { using (LsaPolicy lsaPolicy = new LsaPolicy(LSA_AccessPolicy.POLICY_CREATE_SECRET)) { lsaPolicy.SetSecretData(LsaPolicy.DefaultPassword, password); } } public void ResetAutoLogonPassword() { using (LsaPolicy lsaPolicy = new LsaPolicy(LSA_AccessPolicy.POLICY_CREATE_SECRET)) { lsaPolicy.SetSecretData(LsaPolicy.DefaultPassword, null); } } public bool IsRunningInElevatedMode() { return new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator); } public void LoadUserProfile(string domain, string userName, string logonPassword, out IntPtr tokenHandle, out PROFILEINFO userProfile) { Trace.Entering(); tokenHandle = IntPtr.Zero; ArgUtil.NotNullOrEmpty(userName, nameof(userName)); if (LogonUser(userName, domain, logonPassword, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, out tokenHandle) == 0) { throw new Win32Exception(Marshal.GetLastWin32Error()); } userProfile = new PROFILEINFO(); userProfile.dwSize = Marshal.SizeOf(typeof(PROFILEINFO)); userProfile.lpUserName = userName; if (!LoadUserProfile(tokenHandle, ref userProfile)) { throw new Win32Exception(Marshal.GetLastWin32Error()); } Trace.Info($"Successfully loaded the profile for {domain}\\{userName}."); } public void UnloadUserProfile(IntPtr tokenHandle, PROFILEINFO userProfile) { Trace.Entering(); if (tokenHandle == IntPtr.Zero) { Trace.Verbose("The handle to unload user profile is not set. Returning."); } if (!UnloadUserProfile(tokenHandle, userProfile.hProfile)) { throw new Win32Exception(Marshal.GetLastWin32Error()); } Trace.Info($"Successfully unloaded the profile for {userProfile.lpUserName}."); } public void GrantDirectoryPermissionForAccount(string accountName, IList<string> folders) { ArgUtil.NotNull(folders, nameof(folders)); Trace.Entering(); string groupName = GetUniqueBuildGroupName(); Trace.Info(StringUtil.Format("Calculated unique group name {0}", groupName)); if (!LocalGroupExists(groupName)) { Trace.Info(StringUtil.Format("Trying to create group {0}", groupName)); CreateLocalGroup(groupName); } Trace.Info(StringUtil.Format("Trying to add userName {0} to the group {1}", accountName, groupName)); AddMemberToLocalGroup(accountName, groupName); // grant permssion for folders foreach(var folder in folders) { if (Directory.Exists(folder)) { Trace.Info(StringUtil.Format("Set full access control to group for the folder {0}", folder)); GrantFullControlToGroup(folder, groupName); } } } public void RevokeDirectoryPermissionForAccount(IList<string> folders) { ArgUtil.NotNull(folders, nameof(folders)); Trace.Entering(); string groupName = GetUniqueBuildGroupName(); Trace.Info(StringUtil.Format("Calculated unique group name {0}", groupName)); // remove the group from folders foreach(var folder in folders) { if (Directory.Exists(folder)) { Trace.Info(StringUtil.Format($"Remove the group {groupName} for the folder {folder}.")); try { RemoveGroupFromFolderSecuritySetting(folder, groupName); } catch(Exception ex) { Trace.Error(ex); } } } //delete group Trace.Info(StringUtil.Format($"Delete the group {groupName}.")); DeleteLocalGroup(groupName); } private bool IsValidCredentialInternal(string domain, string userName, string logonPassword, UInt32 logonType) { Trace.Entering(); IntPtr tokenHandle = IntPtr.Zero; ArgUtil.NotNullOrEmpty(userName, nameof(userName)); Trace.Info($"Verify credential for account {userName}."); int result = LogonUser(userName, domain, logonPassword, logonType, LOGON32_PROVIDER_DEFAULT, out tokenHandle); if (tokenHandle.ToInt32() != 0) { if (!CloseHandle(tokenHandle)) { Trace.Error("Failed during CloseHandle on token from LogonUser"); } } if (result != 0) { Trace.Info($"Credential for account '{userName}' is valid."); return true; } else { Trace.Info($"Credential for account '{userName}' is invalid."); return false; } } private byte[] GetSidBinaryFromWindows(string domain, string user) { try { SecurityIdentifier sid = (SecurityIdentifier)new NTAccount(StringUtil.Format("{0}\\{1}", domain, user).TrimStart('\\')).Translate(typeof(SecurityIdentifier)); byte[] binaryForm = new byte[sid.BinaryLength]; sid.GetBinaryForm(binaryForm, 0); return binaryForm; } catch (Exception exception) { Trace.Error(exception); return null; } } // Helper class not to repeat whenever we deal with LSA* api internal class LsaPolicy : IDisposable { public IntPtr Handle { get; set; } public LsaPolicy() : this(LSA_AccessPolicy.POLICY_ALL_ACCESS) { } public LsaPolicy(LSA_AccessPolicy access) { LSA_UNICODE_STRING system = new LSA_UNICODE_STRING(); LSA_OBJECT_ATTRIBUTES attrib = new LSA_OBJECT_ATTRIBUTES() { Length = 0, RootDirectory = IntPtr.Zero, Attributes = 0, SecurityDescriptor = IntPtr.Zero, SecurityQualityOfService = IntPtr.Zero, }; IntPtr handle = IntPtr.Zero; uint hr = LsaOpenPolicy(ref system, ref attrib, (uint)access, out handle); if (hr != 0 || handle == IntPtr.Zero) { throw new InvalidOperationException(StringUtil.Loc("OperationFailed", nameof(LsaOpenPolicy), hr)); } Handle = handle; } public void SetSecretData(string key, string value) { LSA_UNICODE_STRING secretData = new LSA_UNICODE_STRING(); LSA_UNICODE_STRING secretName = new LSA_UNICODE_STRING(); secretName.Buffer = Marshal.StringToHGlobalUni(key); var charSize = sizeof(char); secretName.Length = (UInt16)(key.Length * charSize); secretName.MaximumLength = (UInt16)((key.Length + 1) * charSize); if (value != null && value.Length > 0) { // Create data and key secretData.Buffer = Marshal.StringToHGlobalUni(value); secretData.Length = (UInt16)(value.Length * charSize); secretData.MaximumLength = (UInt16)((value.Length + 1) * charSize); } else { // Delete data and key secretData.Buffer = IntPtr.Zero; secretData.Length = 0; secretData.MaximumLength = 0; } uint result = LsaStorePrivateData(Handle, ref secretName, ref secretData); uint winErrorCode = LsaNtStatusToWinError(result); if (winErrorCode != 0) { throw new InvalidOperationException(StringUtil.Loc("OperationFailed", nameof(LsaNtStatusToWinError), winErrorCode)); } } void IDisposable.Dispose() { // We will ignore LsaClose error LsaClose(Handle); GC.SuppressFinalize(this); } internal static string DefaultPassword = "DefaultPassword"; } internal enum LSA_AccessPolicy : long { POLICY_VIEW_LOCAL_INFORMATION = 0x00000001L, POLICY_VIEW_AUDIT_INFORMATION = 0x00000002L, POLICY_GET_PRIVATE_INFORMATION = 0x00000004L, POLICY_TRUST_ADMIN = 0x00000008L, POLICY_CREATE_ACCOUNT = 0x00000010L, POLICY_CREATE_SECRET = 0x00000020L, POLICY_CREATE_PRIVILEGE = 0x00000040L, POLICY_SET_DEFAULT_QUOTA_LIMITS = 0x00000080L, POLICY_SET_AUDIT_REQUIREMENTS = 0x00000100L, POLICY_AUDIT_LOG_ADMIN = 0x00000200L, POLICY_SERVER_ADMIN = 0x00000400L, POLICY_LOOKUP_NAMES = 0x00000800L, POLICY_NOTIFICATION = 0x00001000L, POLICY_ALL_ACCESS = 0x00001FFFL } [DllImport("advapi32.dll", SetLastError = true, PreserveSig = true)] public static extern uint LsaStorePrivateData( IntPtr policyHandle, ref LSA_UNICODE_STRING KeyName, ref LSA_UNICODE_STRING PrivateData ); [DllImport("advapi32.dll", SetLastError = true, PreserveSig = true)] public static extern uint LsaNtStatusToWinError( uint status ); private static UInt32 LOGON32_LOGON_INTERACTIVE = 2; private const UInt32 LOGON32_LOGON_NETWORK = 3; // Declaration of external pinvoke functions private static readonly string s_logonAsServiceName = "SeServiceLogonRight"; private const UInt32 LOGON32_PROVIDER_DEFAULT = 0; private const int SERVICE_WIN32_OWN_PROCESS = 0x00000010; private const int SERVICE_NO_CHANGE = -1; private const int SERVICE_CONFIG_FAILURE_ACTIONS = 0x2; private const int SERVICE_CONFIG_DELAYED_AUTO_START_INFO = 0x3; // TODO Fix this. This is not yet available in coreclr (newer version?) private const int UnicodeCharSize = 2; private static LSA_UNICODE_STRING[] LogonAsServiceRights { get { return new[] { new LSA_UNICODE_STRING() { Buffer = Marshal.StringToHGlobalUni(s_logonAsServiceName), Length = (UInt16)(s_logonAsServiceName.Length * UnicodeCharSize), MaximumLength = (UInt16) ((s_logonAsServiceName.Length + 1) * UnicodeCharSize) } }; } } public struct ReturnCode { public const int S_OK = 0; public const int ERROR_ACCESS_DENIED = 5; public const int ERROR_INVALID_PARAMETER = 87; public const int ERROR_MEMBER_NOT_IN_ALIAS = 1377; // member not in a group public const int ERROR_MEMBER_IN_ALIAS = 1378; // member already exists public const int ERROR_ALIAS_EXISTS = 1379; // group already exists public const int ERROR_NO_SUCH_ALIAS = 1376; public const int ERROR_NO_SUCH_MEMBER = 1387; public const int ERROR_INVALID_MEMBER = 1388; public const int NERR_GroupNotFound = 2220; public const int NERR_GroupExists = 2223; public const int NERR_UserInGroup = 2236; public const uint STATUS_ACCESS_DENIED = 0XC0000022; //NTSTATUS error code: Access Denied } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct LocalGroupInfo { [MarshalAs(UnmanagedType.LPWStr)] public string Name; [MarshalAs(UnmanagedType.LPWStr)] public string Comment; } [StructLayout(LayoutKind.Sequential)] public struct LSA_UNICODE_STRING { public UInt16 Length; public UInt16 MaximumLength; // We need to use an IntPtr because if we wrap the Buffer with a SafeHandle-derived class, we get a failure during LsaAddAccountRights public IntPtr Buffer; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct LocalGroupMemberInfo { [MarshalAs(UnmanagedType.LPWStr)] public string FullName; } [StructLayout(LayoutKind.Sequential)] public struct LSA_OBJECT_ATTRIBUTES { public UInt32 Length; public IntPtr RootDirectory; public LSA_UNICODE_STRING ObjectName; public UInt32 Attributes; public IntPtr SecurityDescriptor; public IntPtr SecurityQualityOfService; } [StructLayout(LayoutKind.Sequential)] public struct SERVICE_FAILURE_ACTIONS { public int dwResetPeriod; public string lpRebootMsg; public string lpCommand; public int cActions; public long lpsaActions; } [StructLayout(LayoutKind.Sequential)] public struct SERVICE_DELAYED_AUTO_START_INFO { public bool fDelayedAutostart; } // Class to represent a failure action which consists of a recovery // action type and an action delay private class FailureAction { // Property to set recover action type public RecoverAction Type { get; set; } // Property to set recover action delay public int Delay { get; set; } // Constructor public FailureAction(RecoverAction actionType, int actionDelay) { Type = actionType; Delay = actionDelay; } } [Flags] public enum ServiceManagerRights { Connect = 0x0001, CreateService = 0x0002, EnumerateService = 0x0004, Lock = 0x0008, QueryLockStatus = 0x0010, ModifyBootConfig = 0x0020, StandardRightsRequired = 0xF0000, AllAccess = (StandardRightsRequired | Connect | CreateService | EnumerateService | Lock | QueryLockStatus | ModifyBootConfig) } [Flags] public enum ServiceRights { QueryConfig = 0x1, ChangeConfig = 0x2, QueryStatus = 0x4, EnumerateDependants = 0x8, Start = 0x10, Stop = 0x20, PauseContinue = 0x40, Interrogate = 0x80, UserDefinedControl = 0x100, Delete = 0x00010000, StandardRightsRequired = 0xF0000, AllAccess = (StandardRightsRequired | QueryConfig | ChangeConfig | QueryStatus | EnumerateDependants | Start | Stop | PauseContinue | Interrogate | UserDefinedControl) } public enum ServiceError { Ignore = 0x00000000, Normal = 0x00000001, Severe = 0x00000002, Critical = 0x00000003 } public enum ServiceBootFlag { Start = 0x00000000, SystemStart = 0x00000001, AutoStart = 0x00000002, DemandStart = 0x00000003, Disabled = 0x00000004 } // Enum for recovery actions (correspond to the Win32 equivalents ) private enum RecoverAction { None = 0, Restart = 1, Reboot = 2, RunCommand = 3 } [DllImport("Netapi32.dll")] private extern static int NetLocalGroupGetInfo(string servername, string groupname, int level, out IntPtr bufptr); [DllImport("Netapi32.dll")] private extern static int NetApiBufferFree(IntPtr Buffer); [DllImport("Netapi32.dll")] private extern static int NetLocalGroupAdd([MarshalAs(UnmanagedType.LPWStr)] string servername, int level, ref LocalGroupInfo buf, int parm_err); [DllImport("Netapi32.dll")] private extern static int NetLocalGroupAddMembers([MarshalAs(UnmanagedType.LPWStr)] string serverName, [MarshalAs(UnmanagedType.LPWStr)] string groupName, int level, ref LocalGroupMemberInfo buf, int totalEntries); [DllImport("Netapi32.dll")] public extern static int NetLocalGroupDel([MarshalAs(UnmanagedType.LPWStr)] string servername, [MarshalAs(UnmanagedType.LPWStr)] string groupname); [DllImport("advapi32.dll")] private static extern Int32 LsaClose(IntPtr ObjectHandle); [DllImport("advapi32.dll", SetLastError = true, PreserveSig = true)] private static extern uint LsaOpenPolicy( ref LSA_UNICODE_STRING SystemName, ref LSA_OBJECT_ATTRIBUTES ObjectAttributes, uint DesiredAccess, out IntPtr PolicyHandle); [DllImport("advapi32.dll", SetLastError = true, PreserveSig = true)] private static extern uint LsaAddAccountRights( IntPtr PolicyHandle, byte[] AccountSid, LSA_UNICODE_STRING[] UserRights, uint CountOfRights); [DllImport("advapi32.dll", SetLastError = true, PreserveSig = true)] public static extern uint LsaEnumerateAccountRights( IntPtr PolicyHandle, byte[] AccountSid, out IntPtr UserRights, out uint CountOfRights); [DllImport("advapi32.dll", SetLastError = true, PreserveSig = true)] public static extern uint LsaFreeMemory(IntPtr pBuffer); [DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)] public static extern int LogonUser(string userName, string domain, string password, uint logonType, uint logonProvider, out IntPtr tokenHandle); [DllImport("userenv.dll", SetLastError = true, CharSet = CharSet.Unicode)] public static extern Boolean LoadUserProfile(IntPtr hToken, ref PROFILEINFO lpProfileInfo); [DllImport("userenv.dll", SetLastError = true, CharSet = CharSet.Unicode)] public static extern Boolean UnloadUserProfile(IntPtr hToken, IntPtr hProfile); [DllImport("kernel32", SetLastError = true)] public static extern bool CloseHandle(IntPtr handle); [DllImport("advapi32.dll", EntryPoint = "CreateServiceA")] private static extern IntPtr CreateService( IntPtr hSCManager, string lpServiceName, string lpDisplayName, ServiceRights dwDesiredAccess, int dwServiceType, ServiceBootFlag dwStartType, ServiceError dwErrorControl, string lpBinaryPathName, string lpLoadOrderGroup, IntPtr lpdwTagId, string lpDependencies, string lp, string lpPassword); [DllImport("advapi32.dll")] public static extern IntPtr OpenSCManager(string lpMachineName, string lpDatabaseName, ServiceManagerRights dwDesiredAccess); [DllImport("advapi32.dll", SetLastError = true)] public static extern IntPtr OpenService(IntPtr hSCManager, string lpServiceName, ServiceRights dwDesiredAccess); [DllImport("advapi32.dll", SetLastError = true)] public static extern int DeleteService(IntPtr hService); [DllImport("advapi32.dll")] public static extern int CloseServiceHandle(IntPtr hSCObject); [DllImport("advapi32.dll")] public static extern IntPtr LockServiceDatabase(IntPtr hSCManager); [DllImport("advapi32.dll")] public static extern bool UnlockServiceDatabase(IntPtr hSCManager); [DllImport("advapi32.dll", EntryPoint = "ChangeServiceConfig2")] public static extern bool ChangeServiceFailureActions(IntPtr hService, int dwInfoLevel, ref SERVICE_FAILURE_ACTIONS lpInfo); [DllImport("advapi32.dll", EntryPoint = "ChangeServiceConfig2")] public static extern bool ChangeServiceDelayedAutoStart(IntPtr hService, int dwInfoLevel, ref SERVICE_DELAYED_AUTO_START_INFO lpInfo); [DllImport("kernel32.dll")] static extern uint GetLastError(); } [StructLayout(LayoutKind.Sequential)] public struct PROFILEINFO { public int dwSize; public int dwFlags; [MarshalAs(UnmanagedType.LPTStr)] public String lpUserName; [MarshalAs(UnmanagedType.LPTStr)] public String lpProfilePath; [MarshalAs(UnmanagedType.LPTStr)] public String lpDefaultPath; [MarshalAs(UnmanagedType.LPTStr)] public String lpServerName; [MarshalAs(UnmanagedType.LPTStr)] public String lpPolicyPath; public IntPtr hProfile; } }
namespace AngleSharp.Css.Parser { using AngleSharp.Css.Dom; using AngleSharp.Css.Values; using AngleSharp.Text; using System; using System.Collections.Generic; static class TransformParser { private static readonly Dictionary<String, Func<StringSource, ICssTransformFunctionValue>> TransformFunctions = new Dictionary<String, Func<StringSource, ICssTransformFunctionValue>> { { FunctionNames.Skew, ParseSkew2d }, { FunctionNames.SkewX, ParseSkewX }, { FunctionNames.SkewY, ParseSkewY }, { FunctionNames.Matrix, ParseMatrix2d }, { FunctionNames.Matrix3d, ParseMatrix3d }, { FunctionNames.Rotate, ParseRotate2d }, { FunctionNames.Rotate3d, ParseRotate3d }, { FunctionNames.RotateX, ParseRotateX }, { FunctionNames.RotateY, ParseRotateY }, { FunctionNames.RotateZ, ParseRotateZ }, { FunctionNames.Scale, ParseScale2d }, { FunctionNames.Scale3d, ParseScale3d }, { FunctionNames.ScaleX, ParseScaleX }, { FunctionNames.ScaleY, ParseScaleY }, { FunctionNames.ScaleZ, ParseScaleZ }, { FunctionNames.Translate, ParseTranslate2d }, { FunctionNames.Translate3d, ParseTranslate3d }, { FunctionNames.TranslateX, ParseTranslateX }, { FunctionNames.TranslateY, ParseTranslateY }, { FunctionNames.TranslateZ, ParseTranslateZ }, { FunctionNames.Perspective, ParsePerspective }, }; public static ICssTransformFunctionValue ParseTransform(this StringSource source) { var pos = source.Index; var ident = source.ParseIdent(); if (ident != null) { if (source.Current == Symbols.RoundBracketOpen) { var function = default(Func<StringSource, ICssTransformFunctionValue>); if (TransformFunctions.TryGetValue(ident, out function)) { source.SkipCurrentAndSpaces(); return function.Invoke(source); } } } source.BackTo(pos); return null; } /// <summary> /// A broad variety of skew transforms. /// http://www.w3.org/TR/css3-transforms/#funcdef-skew /// </summary> private static CssSkewValue ParseSkew2d(StringSource source) { var x = source.ParseAngleOrCalc(); var c = source.SkipGetSkip(); var y = source.ParseAngleOrCalc(); var f = source.SkipGetSkip(); if (x != null && y != null && c == Symbols.Comma && f == Symbols.RoundBracketClose) { return new CssSkewValue(x, y); } return null; } /// <summary> /// A broad variety of skew transforms. /// http://www.w3.org/TR/css3-transforms/#funcdef-skew /// </summary> private static CssSkewValue ParseSkewX(StringSource source) { var x = source.ParseAngleOrCalc(); var f = source.SkipGetSkip(); if (x != null && f == Symbols.RoundBracketClose) { return new CssSkewValue(x, null); } return null; } /// <summary> /// A broad variety of skew transforms. /// http://www.w3.org/TR/css3-transforms/#funcdef-skew /// </summary> private static CssSkewValue ParseSkewY(StringSource source) { var y = source.ParseAngleOrCalc(); var f = source.SkipGetSkip(); if (y != null && f == Symbols.RoundBracketClose) { return new CssSkewValue(null, y); } return null; } /// <summary> /// Sets the transformation matrix explicitly. /// http://www.w3.org/TR/css3-transforms/#funcdef-matrix3d /// </summary> private static CssMatrixValue ParseMatrix2d(StringSource source) { return ParseMatrix(source, 6); } /// <summary> /// Sets the transformation matrix explicitly. /// http://www.w3.org/TR/css3-transforms/#funcdef-matrix3d /// </summary> private static CssMatrixValue ParseMatrix3d(StringSource source) { return ParseMatrix(source, 16); } /// <summary> /// Sets the transformation matrix explicitly. /// http://www.w3.org/TR/css3-transforms/#funcdef-matrix3d /// </summary> private static CssMatrixValue ParseMatrix(StringSource source, Int32 count) { var numbers = new Double[count]; var num = source.ParseNumber(); if (num.HasValue) { numbers[0] = num.Value; var index = 1; while (index < numbers.Length) { var c = source.SkipGetSkip(); num = source.ParseNumber(); if (c != Symbols.Comma || !num.HasValue) break; numbers[index++] = num.Value; } var f = source.SkipGetSkip(); if (index == count && f == Symbols.RoundBracketClose) { return new CssMatrixValue(numbers); } } return null; } /// <summary> /// A broad variety of rotate transforms. /// http://www.w3.org/TR/css3-transforms/#funcdef-rotate3d /// </summary> private static CssRotateValue ParseRotate2d(StringSource source) { return ParseRotate(source, Double.NaN, Double.NaN, Double.NaN); } /// <summary> /// A broad variety of rotate transforms. /// http://www.w3.org/TR/css3-transforms/#funcdef-rotate3d /// </summary> private static CssRotateValue ParseRotate3d(StringSource source) { var x = source.ParseNumber(); var c1 = source.SkipGetSkip(); var y = source.ParseNumber(); var c2 = source.SkipGetSkip(); var z = source.ParseNumber(); var c3 = source.SkipGetSkip(); if (x.HasValue && y.HasValue && z.HasValue && c1 == c2 && c1 == c3 && c1 == Symbols.Comma) { return ParseRotate(source, x.Value, y.Value, z.Value); } return null; } /// <summary> /// A broad variety of rotate transforms. /// http://www.w3.org/TR/css3-transforms/#funcdef-rotate3d /// </summary> private static CssRotateValue ParseRotateX(StringSource source) { return ParseRotate(source, 1f, 0f, 0f); } /// <summary> /// A broad variety of rotate transforms. /// http://www.w3.org/TR/css3-transforms/#funcdef-rotate3d /// </summary> private static CssRotateValue ParseRotateY(StringSource source) { return ParseRotate(source, 0f, 1f, 0f); } /// <summary> /// A broad variety of rotate transforms. /// http://www.w3.org/TR/css3-transforms/#funcdef-rotate3d /// </summary> private static CssRotateValue ParseRotateZ(StringSource source) { return ParseRotate(source, 0f, 0f, 1f); } /// <summary> /// A broad variety of rotate transforms. /// http://www.w3.org/TR/css3-transforms/#funcdef-rotate3d /// </summary> private static CssRotateValue ParseRotate(StringSource source, Double x, Double y, Double z) { var angle = source.ParseAngleOrCalc(); var f = source.SkipGetSkip(); if (angle != null && f == Symbols.RoundBracketClose) { return new CssRotateValue(x, z, y, angle); } return null; } /// <summary> /// A broad variety of scale transforms. /// http://www.w3.org/TR/css3-transforms/#funcdef-scale3d /// </summary> private static CssScaleValue ParseScale2d(StringSource source) { var x = source.ParseNumber(); var f = source.SkipGetSkip(); if (x.HasValue) { var y = default(Double?); if (f == Symbols.Comma) { y = source.ParseNumber(); f = source.SkipGetSkip(); } if (f == Symbols.RoundBracketClose) { return new CssScaleValue(x.Value, y ?? x.Value, 1.0); } } return null; } /// <summary> /// A broad variety of scale transforms. /// http://www.w3.org/TR/css3-transforms/#funcdef-scale3d /// </summary> private static CssScaleValue ParseScale3d(StringSource source) { var x = source.ParseNumber(); var f = source.SkipGetSkip(); if (x.HasValue) { var y = default(Double?); var z = default(Double?); if (f == Symbols.Comma) { y = source.ParseNumber(); f = source.SkipGetSkip(); if (!y.HasValue) { return null; } if (f == Symbols.Comma) { z = source.ParseNumber(); f = source.SkipGetSkip(); } } if (f == Symbols.RoundBracketClose) { return new CssScaleValue(x.Value, y ?? x.Value, z ?? x.Value); } } return null; } /// <summary> /// A broad variety of scale transforms. /// http://www.w3.org/TR/css3-transforms/#funcdef-scale3d /// </summary> private static CssScaleValue ParseScaleX(StringSource source) { var x = source.ParseNumber(); var f = source.SkipGetSkip(); if (x.HasValue && f == Symbols.RoundBracketClose) { return new CssScaleValue(x.Value, 1.0, 1.0); } return null; } /// <summary> /// A broad variety of scale transforms. /// http://www.w3.org/TR/css3-transforms/#funcdef-scale3d /// </summary> private static CssScaleValue ParseScaleY(StringSource source) { var y = source.ParseNumber(); var f = source.SkipGetSkip(); if (y.HasValue && f == Symbols.RoundBracketClose) { return new CssScaleValue(1.0, y.Value, 1.0); } return null; } /// <summary> /// A broad variety of scale transforms. /// http://www.w3.org/TR/css3-transforms/#funcdef-scale3d /// </summary> private static CssScaleValue ParseScaleZ(StringSource source) { var z = source.ParseNumber(); var f = source.SkipGetSkip(); if (z.HasValue && f == Symbols.RoundBracketClose) { return new CssScaleValue(1.0, 1.0, z.Value); } return null; } /// <summary> /// A broad variety of translate transforms. /// http://www.w3.org/TR/css3-transforms/#funcdef-translate3d /// </summary> private static CssTranslateValue ParseTranslate2d(StringSource source) { var x = source.ParseDistanceOrCalc(); var f = source.SkipGetSkip(); if (x != null) { var y = default(ICssValue); if (f == Symbols.Comma) { y = source.ParseDistanceOrCalc(); f = source.SkipGetSkip(); } if (f == Symbols.RoundBracketClose) { return new CssTranslateValue(x, y, null); } } return null; } /// <summary> /// A broad variety of translate transforms. /// http://www.w3.org/TR/css3-transforms/#funcdef-translate3d /// </summary> private static CssTranslateValue ParseTranslate3d(StringSource source) { var x = source.ParseDistanceOrCalc(); var f = source.SkipGetSkip(); if (x != null) { var y = default(ICssValue); var z = default(ICssValue); if (f == Symbols.Comma) { y = source.ParseDistanceOrCalc(); f = source.SkipGetSkip(); if (y == null) { return null; } if (f == Symbols.Comma) { z = source.ParseDistanceOrCalc(); f = source.SkipGetSkip(); } } if (f == Symbols.RoundBracketClose) { return new CssTranslateValue(x, y, z); } } return null; } /// <summary> /// A broad variety of translate transforms. /// http://www.w3.org/TR/css3-transforms/#funcdef-translate3d /// </summary> private static CssTranslateValue ParseTranslateX(StringSource source) { var x = source.ParseDistanceOrCalc(); var f = source.SkipGetSkip(); if (x != null && f == Symbols.RoundBracketClose) { return new CssTranslateValue(x, null, null); } return null; } /// <summary> /// A broad variety of translate transforms. /// http://www.w3.org/TR/css3-transforms/#funcdef-translate3d /// </summary> private static CssTranslateValue ParseTranslateY(StringSource source) { var y = source.ParseDistanceOrCalc(); var f = source.SkipGetSkip(); if (y != null && f == Symbols.RoundBracketClose) { return new CssTranslateValue(null, y, null); } return null; } /// <summary> /// A broad variety of translate transforms. /// http://www.w3.org/TR/css3-transforms/#funcdef-translate3d /// </summary> private static CssTranslateValue ParseTranslateZ(StringSource source) { var z = source.ParseDistanceOrCalc(); var f = source.SkipGetSkip(); if (z != null && f == Symbols.RoundBracketClose) { return new CssTranslateValue(null, null, z); } return null; } /// <summary> /// A perspective for 3D transformations. /// http://www.w3.org/TR/css3-transforms/#funcdef-perspective /// </summary> private static ICssTransformFunctionValue ParsePerspective(StringSource source) { var l = source.ParseLengthOrCalc(); var f = source.SkipGetSkip(); if (l != null && f == Symbols.RoundBracketClose) { return new CssPerspectiveValue(l); } return null; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using Xunit; namespace System.Linq.Parallel.Tests { public class SkipSkipWhileTests { // // Skip // public static IEnumerable<object[]> SkipUnorderedData(int[] counts) { Func<int, IEnumerable<int>> skip = x => new[] { -x, -1, 0, 1, x / 2, x, x * 2 }.Distinct(); foreach (object[] results in UnorderedSources.Ranges(counts.Cast<int>(), skip)) yield return results; } public static IEnumerable<object[]> SkipData(int[] counts) { Func<int, IEnumerable<int>> skip = x => new[] { -x, -1, 0, 1, x / 2, x, x * 2 }.Distinct(); foreach (object[] results in Sources.Ranges(counts.Cast<int>(), skip)) yield return results; } [Theory] [MemberData("SkipUnorderedData", (object)(new int[] { 0, 1, 2, 16 }))] public static void Skip_Unordered(Labeled<ParallelQuery<int>> labeled, int count, int skip) { ParallelQuery<int> query = labeled.Item; // For unordered collections, which elements are skipped isn't actually guaranteed, but an effect of the implementation. // If this test starts failing it should be updated, and possibly mentioned in release notes. IntegerRangeSet seen = new IntegerRangeSet(Math.Max(skip, 0), Math.Min(count, Math.Max(0, count - skip))); foreach (int i in query.Skip(skip)) { seen.Add(i); } seen.AssertComplete(); } [Theory] [OuterLoop] [MemberData("SkipUnorderedData", (object)(new int[] { 1024 * 32 }))] public static void Skip_Unordered_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int skip) { Skip_Unordered(labeled, count, skip); } [Theory] [MemberData("SkipData", (object)(new int[] { 0, 1, 2, 16 }))] public static void Skip(Labeled<ParallelQuery<int>> labeled, int count, int skip) { ParallelQuery<int> query = labeled.Item; int seen = Math.Max(0, skip); foreach (int i in query.Skip(skip)) { Assert.Equal(seen++, i); } Assert.Equal(Math.Max(skip, count), seen); } [Theory] [OuterLoop] [MemberData("SkipData", (object)(new int[] { 1024 * 32 }))] public static void Skip_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int skip) { Skip(labeled, count, skip); } [Theory] [MemberData("SkipUnorderedData", (object)(new int[] { 0, 1, 2, 16 }))] public static void Skip_Unordered_NotPipelined(Labeled<ParallelQuery<int>> labeled, int count, int skip) { ParallelQuery<int> query = labeled.Item; // For unordered collections, which elements are skipped isn't actually guaranteed, but an effect of the implementation. // If this test starts failing it should be updated, and possibly mentioned in release notes. IntegerRangeSet seen = new IntegerRangeSet(Math.Max(skip, 0), Math.Min(count, Math.Max(0, count - skip))); Assert.All(query.Skip(skip).ToList(), x => seen.Add(x)); seen.AssertComplete(); } [Theory] [OuterLoop] [MemberData("SkipUnorderedData", (object)(new int[] { 1024 * 32 }))] public static void Skip_Unordered_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int skip) { Skip_Unordered_NotPipelined(labeled, count, skip); } [Theory] [MemberData("SkipData", (object)(new int[] { 0, 1, 2, 16 }))] public static void Skip_NotPipelined(Labeled<ParallelQuery<int>> labeled, int count, int skip) { ParallelQuery<int> query = labeled.Item; int seen = Math.Max(0, skip); Assert.All(query.Skip(skip).ToList(), x => Assert.Equal(seen++, x)); Assert.Equal(Math.Max(skip, count), seen); } [Theory] [OuterLoop] [MemberData("SkipData", (object)(new int[] { 1024 * 32 }))] public static void Skip_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int skip) { Skip_NotPipelined(labeled, count, skip); } [Fact] public static void Skip_ArgumentNullException() { Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<bool>)null).Skip(0)); } // // SkipWhile // public static IEnumerable<object[]> SkipWhileData(int[] counts) { foreach (object[] results in Sources.Ranges(counts.Cast<int>())) { yield return new[] { results[0], results[1], new[] { 0 } }; yield return new[] { results[0], results[1], Enumerable.Range((int)results[1] / 2, ((int)results[1] - 1) / 2 + 1) }; yield return new[] { results[0], results[1], new[] { (int)results[1] - 1 } }; } } [Theory] [MemberData("SkipUnorderedData", (object)(new int[] { 0, 1, 2, 16 }))] public static void SkipWhile_Unordered(Labeled<ParallelQuery<int>> labeled, int count, int skip) { ParallelQuery<int> query = labeled.Item; // For unordered collections, which elements (if any) are skipped isn't actually guaranteed, but an effect of the implementation. // If this test starts failing it should be updated, and possibly mentioned in release notes. IntegerRangeSet seen = new IntegerRangeSet(Math.Max(skip, 0), Math.Min(count, Math.Max(0, count - skip))); foreach (int i in query.SkipWhile(x => x < skip)) { seen.Add(i); } seen.AssertComplete(); } [Theory] [OuterLoop] [MemberData("SkipUnorderedData", (object)(new int[] { 1024 * 32 }))] public static void SkipWhile_Unordered_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int skip) { SkipWhile_Unordered(labeled, count, skip); } [Theory] [MemberData("SkipData", (object)(new int[] { 0, 1, 2, 16 }))] public static void SkipWhile(Labeled<ParallelQuery<int>> labeled, int count, int skip) { ParallelQuery<int> query = labeled.Item; int seen = Math.Max(0, skip); foreach (int i in query.SkipWhile(x => x < skip)) { Assert.Equal(seen++, i); } Assert.Equal(Math.Max(skip, count), seen); } [Theory] [OuterLoop] [MemberData("SkipData", (object)(new int[] { 1024 * 32 }))] public static void SkipWhile_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int skip) { SkipWhile(labeled, count, skip); } [Theory] [MemberData("SkipUnorderedData", (object)(new int[] { 0, 1, 2, 16 }))] public static void SkipWhile_Unordered_NotPipelined(Labeled<ParallelQuery<int>> labeled, int count, int skip) { ParallelQuery<int> query = labeled.Item; // For unordered collections, which elements (if any) are skipped isn't actually guaranteed, but an effect of the implementation. // If this test starts failing it should be updated, and possibly mentioned in release notes. IntegerRangeSet seen = new IntegerRangeSet(Math.Max(skip, 0), Math.Min(count, Math.Max(0, count - skip))); Assert.All(query.SkipWhile(x => x < skip).ToList(), x => seen.Add(x)); seen.AssertComplete(); } [Theory] [OuterLoop] [MemberData("SkipUnorderedData", (object)(new int[] { 1024 * 32 }))] public static void SkipWhile_Unordered_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int skip) { SkipWhile_Unordered_NotPipelined(labeled, count, skip); } [Theory] [MemberData("SkipData", (object)(new int[] { 0, 1, 2, 16 }))] public static void SkipWhile_NotPipelined(Labeled<ParallelQuery<int>> labeled, int count, int skip) { ParallelQuery<int> query = labeled.Item; int seen = Math.Max(0, skip); Assert.All(query.SkipWhile(x => x < skip).ToList(), x => Assert.Equal(seen++, x)); Assert.Equal(Math.Max(skip, count), seen); } [Theory] [OuterLoop] [MemberData("SkipData", (object)(new int[] { 1024 * 32 }))] public static void SkipWhile_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int skip) { SkipWhile_NotPipelined(labeled, count, skip); } [Theory] [MemberData("SkipUnorderedData", (object)(new int[] { 0, 1, 2, 16 }))] public static void SkipWhile_Indexed_Unordered(Labeled<ParallelQuery<int>> labeled, int count, int skip) { ParallelQuery<int> query = labeled.Item; // For unordered collections, which elements (if any) are skipped isn't actually guaranteed, but an effect of the implementation. // If this test starts failing it should be updated, and possibly mentioned in release notes. IntegerRangeSet seen = new IntegerRangeSet(Math.Max(skip, 0), Math.Min(count, Math.Max(0, count - skip))); foreach (int i in query.SkipWhile((x, index) => index < skip)) { seen.Add(i); } seen.AssertComplete(); } [Theory] [OuterLoop] [MemberData("SkipUnorderedData", (object)(new int[] { 1024 * 32 }))] public static void SkipWhile_Indexed_Unordered_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int skip) { SkipWhile_Indexed_Unordered(labeled, count, skip); } [Theory] [MemberData("SkipData", (object)(new int[] { 0, 1, 2, 16 }))] public static void SkipWhile_Indexed(Labeled<ParallelQuery<int>> labeled, int count, int skip) { ParallelQuery<int> query = labeled.Item; int seen = Math.Max(0, skip); foreach (int i in query.SkipWhile((x, index) => index < skip)) { Assert.Equal(seen++, i); } Assert.Equal(Math.Max(skip, count), seen); } [Theory] [OuterLoop] [MemberData("SkipData", (object)(new int[] { 1024 * 32 }))] public static void SkipWhile_Indexed_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int skip) { SkipWhile_Indexed(labeled, count, skip); } [Theory] [MemberData("SkipUnorderedData", (object)(new int[] { 0, 1, 2, 16 }))] public static void SkipWhile_Indexed_Unordered_NotPipelined(Labeled<ParallelQuery<int>> labeled, int count, int skip) { ParallelQuery<int> query = labeled.Item; // For unordered collections, which elements (if any) are skipped isn't actually guaranteed, but an effect of the implementation. // If this test starts failing it should be updated, and possibly mentioned in release notes. IntegerRangeSet seen = new IntegerRangeSet(Math.Max(skip, 0), Math.Min(count, Math.Max(0, count - skip))); Assert.All(query.SkipWhile((x, index) => index < skip), x => seen.Add(x)); seen.AssertComplete(); } [Theory] [OuterLoop] [MemberData("SkipUnorderedData", (object)(new int[] { 1024 * 32 }))] public static void SkipWhile_Indexed_Unordered_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int skip) { SkipWhile_Indexed_Unordered_NotPipelined(labeled, count, skip); } [Theory] [MemberData("SkipData", (object)(new int[] { 0, 1, 2, 16 }))] public static void SkipWhile_Indexed_NotPipelined(Labeled<ParallelQuery<int>> labeled, int count, int skip) { ParallelQuery<int> query = labeled.Item; int seen = Math.Max(0, skip); Assert.All(query.SkipWhile((x, index) => index < skip), x => Assert.Equal(seen++, x)); Assert.Equal(Math.Max(skip, count), seen); } [Theory] [OuterLoop] [MemberData("SkipData", (object)(new int[] { 1024 * 32 }))] public static void SkipWhile_Indexed_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int skip) { SkipWhile_Indexed_NotPipelined(labeled, count, skip); } [Theory] [MemberData("SkipData", (object)(new int[] { 0, 1, 2, 16 }))] public static void SkipWhile_AllFalse(Labeled<ParallelQuery<int>> labeled, int count, int skip) { ParallelQuery<int> query = labeled.Item; int seen = 0; Assert.All(query.SkipWhile(x => false), x => Assert.Equal(seen++, x)); Assert.Equal(count, seen); } [Theory] [OuterLoop] [MemberData("SkipData", (object)(new int[] { 1024 * 32 }))] public static void SkipWhile_AllFalse_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int skip) { SkipWhile_AllFalse(labeled, count, skip); } [Theory] [MemberData("SkipData", (object)(new int[] { 0, 1, 2, 16 }))] public static void SkipWhile_AllTrue(Labeled<ParallelQuery<int>> labeled, int count, int skip) { ParallelQuery<int> query = labeled.Item; IntegerRangeSet seen = new IntegerRangeSet(0, count); Assert.Empty(query.SkipWhile(x => seen.Add(x))); seen.AssertComplete(); } [Theory] [OuterLoop] [MemberData("SkipData", (object)(new int[] { 1024 * 32 }))] public static void SkipWhile_AllTrue_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int skip) { SkipWhile_AllTrue(labeled, count, skip); } [Theory] [MemberData("SkipWhileData", (object)(new int[] { 2, 16 }))] public static void SkipWhile_SomeTrue(Labeled<ParallelQuery<int>> labeled, int count, IEnumerable<int> skip) { ParallelQuery<int> query = labeled.Item; int seen = skip.Min() == 0 ? 1 : 0; Assert.All(query.SkipWhile(x => skip.Contains(x)), x => Assert.Equal(seen++, x)); Assert.Equal(skip.Min() >= count ? 0 : count, seen); } [Theory] [OuterLoop] [MemberData("SkipWhileData", (object)(new int[] { 1024 * 32 }))] public static void SkipWhile_SomeTrue_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, IEnumerable<int> skip) { SkipWhile_SomeTrue(labeled, count, skip); } [Theory] [MemberData("SkipWhileData", (object)(new int[] { 2, 16 }))] public static void SkipWhile_SomeFalse(Labeled<ParallelQuery<int>> labeled, int count, IEnumerable<int> skip) { ParallelQuery<int> query = labeled.Item; int seen = skip.Min(); Assert.All(query.SkipWhile(x => !skip.Contains(x)), x => Assert.Equal(seen++, x)); Assert.Equal(count, seen); } [Theory] [OuterLoop] [MemberData("SkipWhileData", (object)(new int[] { 1024 * 32 }))] public static void SkipWhile_SomeFalse_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, IEnumerable<int> skip) { SkipWhile_SomeFalse(labeled, count, skip); } [Fact] public static void SkipWhile_ArgumentNullException() { Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<bool>)null).SkipWhile(x => true)); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Empty<bool>().SkipWhile((Func<bool, bool>)null)); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Empty<bool>().SkipWhile((Func<bool, int, bool>)null)); } } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ namespace ParquetSharp.Column.Values.Fallback { using System.Globalization; using ParquetSharp.Bytes; using ParquetSharp.Column.Page; using ParquetSharp.IO.Api; public static class FallbackValuesWriter { public static FallbackValuesWriter<I, F> of<I, F>(I initialWriter, F fallBackWriter) where I : ValuesWriter, RequiresFallback where F : ValuesWriter { return new FallbackValuesWriter<I, F>(initialWriter, fallBackWriter); } } public class FallbackValuesWriter<I, F> : ValuesWriter where I : ValuesWriter, RequiresFallback where F : ValuesWriter { /** writer to start with */ public readonly I initialWriter; /** fallback */ public readonly F fallBackWriter; private bool fellBackAlready = false; /** writer currently written to */ private ValuesWriter currentWriter; private bool initialUsedAndHadDictionary = false; /* size of raw data, even if dictionary is used, it will not have effect on raw data size, it is used to decide * if fall back to plain encoding is better by comparing rawDataByteSize with Encoded data size * It's also used in getBufferedSize, so the page will be written based on raw data size */ private long rawDataByteSize = 0; /** indicates if this is the first page being processed */ private bool firstPage = true; public FallbackValuesWriter(I initialWriter, F fallBackWriter) { this.initialWriter = initialWriter; this.fallBackWriter = fallBackWriter; this.currentWriter = initialWriter; } public override long getBufferedSize() { // use raw data size to decide if we want to flush the page // so the actual size of the page written could be much more smaller // due to dictionary encoding. This prevents page being too big when fallback happens. return rawDataByteSize; } public override BytesInput getBytes() { if (!fellBackAlready && firstPage) { // we use the first page to decide if we're going to use this encoding BytesInput bytes = initialWriter.getBytes(); if (!initialWriter.isCompressionSatisfying(rawDataByteSize, bytes.size())) { fallBack(); } else { return bytes; } } return currentWriter.getBytes(); } public override Encoding getEncoding() { Encoding encoding = currentWriter.getEncoding(); if (!fellBackAlready && !initialUsedAndHadDictionary) { initialUsedAndHadDictionary = encoding.usesDictionary(); } return encoding; } public override void reset() { rawDataByteSize = 0; firstPage = false; currentWriter.reset(); } public override void close() { initialWriter.close(); fallBackWriter.close(); } public override DictionaryPage toDictPageAndClose() { if (initialUsedAndHadDictionary) { return initialWriter.toDictPageAndClose(); } else { return currentWriter.toDictPageAndClose(); } } public override void resetDictionary() { if (initialUsedAndHadDictionary) { initialWriter.resetDictionary(); } else { currentWriter.resetDictionary(); } currentWriter = initialWriter; fellBackAlready = false; initialUsedAndHadDictionary = false; firstPage = true; } public override long getAllocatedSize() { return currentWriter.getAllocatedSize(); } public override string memUsageString(string prefix) { return string.Format( CultureInfo.InvariantCulture, "{0} FallbackValuesWriter{{\n" + "{1}\n" + "{2}\n" + "{3}}}\n", prefix, initialWriter.memUsageString(prefix + " initial:"), fallBackWriter.memUsageString(prefix + " fallback:"), prefix ); } private void checkFallback() { if (!fellBackAlready && initialWriter.shouldFallBack()) { fallBack(); } } private void fallBack() { fellBackAlready = true; initialWriter.fallBackAllValuesTo(fallBackWriter); currentWriter = fallBackWriter; } // passthrough writing the value public override void writeByte(int value) { rawDataByteSize += 1; currentWriter.writeByte(value); checkFallback(); } public override void writeBytes(Binary v) { //for rawdata, length(4 bytes int) is stored, followed by the binary content itself rawDataByteSize += v.length() + 4; currentWriter.writeBytes(v); checkFallback(); } public override void writeInteger(int v) { rawDataByteSize += 4; currentWriter.writeInteger(v); checkFallback(); } public override void writeLong(long v) { rawDataByteSize += 8; currentWriter.writeLong(v); checkFallback(); } public override void writeFloat(float v) { rawDataByteSize += 4; currentWriter.writeFloat(v); checkFallback(); } public override void writeDouble(double v) { rawDataByteSize += 8; currentWriter.writeDouble(v); checkFallback(); } } }
// 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.CodeAnalysis; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Threading.Tasks; namespace System.IO { // This class implements a TextWriter for writing characters to a Stream. // This is designed for character output in a particular Encoding, // whereas the Stream class is designed for byte input and output. public class StreamWriter : TextWriter { // For UTF-8, the values of 1K for the default buffer size and 4K for the // file stream buffer size are reasonable & give very reasonable // performance for in terms of construction time for the StreamWriter and // write perf. Note that for UTF-8, we end up allocating a 4K byte buffer, // which means we take advantage of adaptive buffering code. // The performance using UnicodeEncoding is acceptable. private const int DefaultBufferSize = 1024; // char[] private const int DefaultFileStreamBufferSize = 4096; private const int MinBufferSize = 128; // Bit bucket - Null has no backing store. Non closable. public new static readonly StreamWriter Null = new StreamWriter(Stream.Null, UTF8NoBOM, MinBufferSize, leaveOpen: true); private readonly Stream _stream; private readonly Encoding _encoding; private readonly Encoder _encoder; private readonly byte[] _byteBuffer; private readonly char[] _charBuffer; private int _charPos; private int _charLen; private bool _autoFlush; private bool _haveWrittenPreamble; private readonly bool _closable; private bool _disposed; // We don't guarantee thread safety on StreamWriter, but we should at // least prevent users from trying to write anything while an Async // write from the same thread is in progress. private Task _asyncWriteTask = Task.CompletedTask; private void CheckAsyncTaskInProgress() { // We are not locking the access to _asyncWriteTask because this is not meant to guarantee thread safety. // We are simply trying to deter calling any Write APIs while an async Write from the same thread is in progress. if (!_asyncWriteTask.IsCompleted) { ThrowAsyncIOInProgress(); } } [DoesNotReturn] private static void ThrowAsyncIOInProgress() => throw new InvalidOperationException(SR.InvalidOperation_AsyncIOInProgress); // The high level goal is to be tolerant of encoding errors when we read and very strict // when we write. Hence, default StreamWriter encoding will throw on encoding error. // Note: when StreamWriter throws on invalid encoding chars (for ex, high surrogate character // D800-DBFF without a following low surrogate character DC00-DFFF), it will cause the // internal StreamWriter's state to be irrecoverable as it would have buffered the // illegal chars and any subsequent call to Flush() would hit the encoding error again. // Even Close() will hit the exception as it would try to flush the unwritten data. // Maybe we can add a DiscardBufferedData() method to get out of such situation (like // StreamReader though for different reason). Either way, the buffered data will be lost! private static Encoding UTF8NoBOM => EncodingCache.UTF8NoBOM; public StreamWriter(Stream stream) : this(stream, UTF8NoBOM, DefaultBufferSize, false) { } public StreamWriter(Stream stream, Encoding encoding) : this(stream, encoding, DefaultBufferSize, false) { } // Creates a new StreamWriter for the given stream. The // character encoding is set by encoding and the buffer size, // in number of 16-bit characters, is set by bufferSize. // public StreamWriter(Stream stream, Encoding encoding, int bufferSize) : this(stream, encoding, bufferSize, false) { } public StreamWriter(Stream stream, Encoding? encoding = null, int bufferSize = -1, bool leaveOpen = false) : base(null) // Ask for CurrentCulture all the time { if (stream == null) { throw new ArgumentNullException(nameof(stream)); } if (encoding == null) { encoding = UTF8NoBOM; } if (!stream.CanWrite) { throw new ArgumentException(SR.Argument_StreamNotWritable); } if (bufferSize == -1) { bufferSize = DefaultBufferSize; } else if (bufferSize <= 0) { throw new ArgumentOutOfRangeException(nameof(bufferSize), SR.ArgumentOutOfRange_NeedPosNum); } _stream = stream; _encoding = encoding; _encoder = _encoding.GetEncoder(); if (bufferSize < MinBufferSize) { bufferSize = MinBufferSize; } _charBuffer = new char[bufferSize]; _byteBuffer = new byte[_encoding.GetMaxByteCount(bufferSize)]; _charLen = bufferSize; // If we're appending to a Stream that already has data, don't write // the preamble. if (_stream.CanSeek && _stream.Position > 0) { _haveWrittenPreamble = true; } _closable = !leaveOpen; } public StreamWriter(string path) : this(path, false, UTF8NoBOM, DefaultBufferSize) { } public StreamWriter(string path, bool append) : this(path, append, UTF8NoBOM, DefaultBufferSize) { } public StreamWriter(string path, bool append, Encoding encoding) : this(path, append, encoding, DefaultBufferSize) { } public StreamWriter(string path, bool append, Encoding encoding, int bufferSize) : this(ValidateArgsAndOpenPath(path, append, encoding, bufferSize), encoding, bufferSize, leaveOpen: false) { } private static Stream ValidateArgsAndOpenPath(string path, bool append, Encoding encoding, int bufferSize) { if (path == null) throw new ArgumentNullException(nameof(path)); if (encoding == null) throw new ArgumentNullException(nameof(encoding)); if (path.Length == 0) throw new ArgumentException(SR.Argument_EmptyPath); if (bufferSize <= 0) throw new ArgumentOutOfRangeException(nameof(bufferSize), SR.ArgumentOutOfRange_NeedPosNum); return new FileStream(path, append ? FileMode.Append : FileMode.Create, FileAccess.Write, FileShare.Read, DefaultFileStreamBufferSize, FileOptions.SequentialScan); } public override void Close() { Dispose(true); GC.SuppressFinalize(this); } protected override void Dispose(bool disposing) { try { // We need to flush any buffered data if we are being closed/disposed. // Also, we never close the handles for stdout & friends. So we can safely // write any buffered data to those streams even during finalization, which // is generally the right thing to do. if (!_disposed && disposing) { // Note: flush on the underlying stream can throw (ex., low disk space) CheckAsyncTaskInProgress(); Flush(flushStream: true, flushEncoder: true); } } finally { CloseStreamFromDispose(disposing); } } private void CloseStreamFromDispose(bool disposing) { // Dispose of our resources if this StreamWriter is closable. if (_closable && !_disposed) { try { // Attempt to close the stream even if there was an IO error from Flushing. // Note that Stream.Close() can potentially throw here (may or may not be // due to the same Flush error). In this case, we still need to ensure // cleaning up internal resources, hence the finally block. if (disposing) { _stream.Close(); } } finally { _disposed = true; _charLen = 0; base.Dispose(disposing); } } } public override ValueTask DisposeAsync() => GetType() != typeof(StreamWriter) ? base.DisposeAsync() : DisposeAsyncCore(); private async ValueTask DisposeAsyncCore() { // Same logic as in Dispose(), but with async flushing. Debug.Assert(GetType() == typeof(StreamWriter)); try { if (!_disposed) { await FlushAsync().ConfigureAwait(false); } } finally { CloseStreamFromDispose(disposing: true); } GC.SuppressFinalize(this); } public override void Flush() { CheckAsyncTaskInProgress(); Flush(true, true); } private void Flush(bool flushStream, bool flushEncoder) { // flushEncoder should be true at the end of the file and if // the user explicitly calls Flush (though not if AutoFlush is true). // This is required to flush any dangling characters from our UTF-7 // and UTF-8 encoders. ThrowIfDisposed(); // Perf boost for Flush on non-dirty writers. if (_charPos == 0 && !flushStream && !flushEncoder) { return; } if (!_haveWrittenPreamble) { _haveWrittenPreamble = true; ReadOnlySpan<byte> preamble = _encoding.Preamble; if (preamble.Length > 0) { _stream.Write(preamble); } } int count = _encoder.GetBytes(_charBuffer, 0, _charPos, _byteBuffer, 0, flushEncoder); _charPos = 0; if (count > 0) { _stream.Write(_byteBuffer, 0, count); } // By definition, calling Flush should flush the stream, but this is // only necessary if we passed in true for flushStream. The Web // Services guys have some perf tests where flushing needlessly hurts. if (flushStream) { _stream.Flush(); } } public virtual bool AutoFlush { get { return _autoFlush; } set { CheckAsyncTaskInProgress(); _autoFlush = value; if (value) { Flush(true, false); } } } public virtual Stream BaseStream { get { return _stream; } } public override Encoding Encoding { get { return _encoding; } } public override void Write(char value) { CheckAsyncTaskInProgress(); if (_charPos == _charLen) { Flush(false, false); } _charBuffer[_charPos] = value; _charPos++; if (_autoFlush) { Flush(true, false); } } [MethodImpl(MethodImplOptions.NoInlining)] // prevent WriteSpan from bloating call sites public override void Write(char[]? buffer) { WriteSpan(buffer, appendNewLine: false); } [MethodImpl(MethodImplOptions.NoInlining)] // prevent WriteSpan from bloating call sites public override void Write(char[] buffer, int index, int count) { if (buffer == null) { throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); } if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum); } if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); } if (buffer.Length - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } WriteSpan(buffer.AsSpan(index, count), appendNewLine: false); } [MethodImpl(MethodImplOptions.NoInlining)] // prevent WriteSpan from bloating call sites public override void Write(ReadOnlySpan<char> buffer) { if (GetType() == typeof(StreamWriter)) { WriteSpan(buffer, appendNewLine: false); } else { // If a derived class may have overridden existing Write behavior, // we need to make sure we use it. base.Write(buffer); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private unsafe void WriteSpan(ReadOnlySpan<char> buffer, bool appendNewLine) { CheckAsyncTaskInProgress(); if (buffer.Length <= 4 && // Threshold of 4 chosen based on perf experimentation buffer.Length <= _charLen - _charPos) { // For very short buffers and when we don't need to worry about running out of space // in the char buffer, just copy the chars individually. for (int i = 0; i < buffer.Length; i++) { _charBuffer[_charPos++] = buffer[i]; } } else { // For larger buffers or when we may run out of room in the internal char buffer, copy in chunks. // Use unsafe code until https://github.com/dotnet/coreclr/issues/13827 is addressed, as spans are // resulting in significant overhead (even when the if branch above is taken rather than this // else) due to temporaries that need to be cleared. Given the use of unsafe code, we also // make local copies of instance state to protect against potential concurrent misuse. ThrowIfDisposed(); char[] charBuffer = _charBuffer; fixed (char* bufferPtr = &MemoryMarshal.GetReference(buffer)) fixed (char* dstPtr = &charBuffer[0]) { char* srcPtr = bufferPtr; int count = buffer.Length; int dstPos = _charPos; // use a local copy of _charPos for safety while (count > 0) { if (dstPos == charBuffer.Length) { Flush(false, false); dstPos = 0; } int n = Math.Min(charBuffer.Length - dstPos, count); int bytesToCopy = n * sizeof(char); Buffer.MemoryCopy(srcPtr, dstPtr + dstPos, bytesToCopy, bytesToCopy); _charPos += n; dstPos += n; srcPtr += n; count -= n; } } } if (appendNewLine) { char[] coreNewLine = CoreNewLine; for (int i = 0; i < coreNewLine.Length; i++) // Generally 1 (\n) or 2 (\r\n) iterations { if (_charPos == _charLen) { Flush(false, false); } _charBuffer[_charPos] = coreNewLine[i]; _charPos++; } } if (_autoFlush) { Flush(true, false); } } [MethodImpl(MethodImplOptions.NoInlining)] // prevent WriteSpan from bloating call sites public override void Write(string? value) { WriteSpan(value, appendNewLine: false); } [MethodImpl(MethodImplOptions.NoInlining)] // prevent WriteSpan from bloating call sites public override void WriteLine(string? value) { CheckAsyncTaskInProgress(); WriteSpan(value, appendNewLine: true); } [MethodImpl(MethodImplOptions.NoInlining)] // prevent WriteSpan from bloating call sites public override void WriteLine(ReadOnlySpan<char> value) { if (GetType() == typeof(StreamWriter)) { CheckAsyncTaskInProgress(); WriteSpan(value, appendNewLine: true); } else { // If a derived class may have overridden existing WriteLine behavior, // we need to make sure we use it. base.WriteLine(value); } } private void WriteFormatHelper(string format, ParamsArray args, bool appendNewLine) { StringBuilder sb = StringBuilderCache.Acquire((format?.Length ?? 0) + args.Length * 8) .AppendFormatHelper(null, format!, args); // AppendFormatHelper will appropriately throw ArgumentNullException for a null format StringBuilder.ChunkEnumerator chunks = sb.GetChunks(); bool more = chunks.MoveNext(); while (more) { ReadOnlySpan<char> current = chunks.Current.Span; more = chunks.MoveNext(); // If final chunk, include the newline if needed WriteSpan(current, appendNewLine: more ? false : appendNewLine); } StringBuilderCache.Release(sb); } public override void Write(string format, object? arg0) { if (GetType() == typeof(StreamWriter)) { WriteFormatHelper(format, new ParamsArray(arg0), appendNewLine: false); } else { base.Write(format, arg0); } } public override void Write(string format, object? arg0, object? arg1) { if (GetType() == typeof(StreamWriter)) { WriteFormatHelper(format, new ParamsArray(arg0, arg1), appendNewLine: false); } else { base.Write(format, arg0, arg1); } } public override void Write(string format, object? arg0, object? arg1, object? arg2) { if (GetType() == typeof(StreamWriter)) { WriteFormatHelper(format, new ParamsArray(arg0, arg1, arg2), appendNewLine: false); } else { base.Write(format, arg0, arg1, arg2); } } public override void Write(string format, params object?[] arg) { if (GetType() == typeof(StreamWriter)) { if (arg == null) { throw new ArgumentNullException((format == null) ? nameof(format) : nameof(arg)); // same as base logic } WriteFormatHelper(format, new ParamsArray(arg), appendNewLine: false); } else { base.Write(format, arg); } } public override void WriteLine(string format, object? arg0) { if (GetType() == typeof(StreamWriter)) { WriteFormatHelper(format, new ParamsArray(arg0), appendNewLine: true); } else { base.WriteLine(format, arg0); } } public override void WriteLine(string format, object? arg0, object? arg1) { if (GetType() == typeof(StreamWriter)) { WriteFormatHelper(format, new ParamsArray(arg0, arg1), appendNewLine: true); } else { base.WriteLine(format, arg0, arg1); } } public override void WriteLine(string format, object? arg0, object? arg1, object? arg2) { if (GetType() == typeof(StreamWriter)) { WriteFormatHelper(format, new ParamsArray(arg0, arg1, arg2), appendNewLine: true); } else { base.WriteLine(format, arg0, arg1, arg2); } } public override void WriteLine(string format, params object?[] arg) { if (GetType() == typeof(StreamWriter)) { if (arg == null) { throw new ArgumentNullException(nameof(arg)); } WriteFormatHelper(format, new ParamsArray(arg), appendNewLine: true); } else { base.WriteLine(format, arg); } } public override Task WriteAsync(char value) { // If we have been inherited into a subclass, the following implementation could be incorrect // since it does not call through to Write() which a subclass might have overridden. // To be safe we will only use this implementation in cases where we know it is safe to do so, // and delegate to our base class (which will call into Write) when we are not sure. if (GetType() != typeof(StreamWriter)) { return base.WriteAsync(value); } ThrowIfDisposed(); CheckAsyncTaskInProgress(); Task task = WriteAsyncInternal(this, value, _charBuffer, _charPos, _charLen, CoreNewLine, _autoFlush, appendNewLine: false); _asyncWriteTask = task; return task; } // We pass in private instance fields of this MarshalByRefObject-derived type as local params // to ensure performant access inside the state machine that corresponds this async method. // Fields that are written to must be assigned at the end of the method *and* before instance invocations. private static async Task WriteAsyncInternal(StreamWriter _this, char value, char[] charBuffer, int charPos, int charLen, char[] coreNewLine, bool autoFlush, bool appendNewLine) { if (charPos == charLen) { await _this.FlushAsyncInternal(false, false, charBuffer, charPos).ConfigureAwait(false); Debug.Assert(_this._charPos == 0); charPos = 0; } charBuffer[charPos] = value; charPos++; if (appendNewLine) { for (int i = 0; i < coreNewLine.Length; i++) // Expect 2 iterations, no point calling BlockCopy { if (charPos == charLen) { await _this.FlushAsyncInternal(false, false, charBuffer, charPos).ConfigureAwait(false); Debug.Assert(_this._charPos == 0); charPos = 0; } charBuffer[charPos] = coreNewLine[i]; charPos++; } } if (autoFlush) { await _this.FlushAsyncInternal(true, false, charBuffer, charPos).ConfigureAwait(false); Debug.Assert(_this._charPos == 0); charPos = 0; } _this._charPos = charPos; } public override Task WriteAsync(string? value) { // If we have been inherited into a subclass, the following implementation could be incorrect // since it does not call through to Write() which a subclass might have overridden. // To be safe we will only use this implementation in cases where we know it is safe to do so, // and delegate to our base class (which will call into Write) when we are not sure. if (GetType() != typeof(StreamWriter)) { return base.WriteAsync(value); } if (value != null) { ThrowIfDisposed(); CheckAsyncTaskInProgress(); Task task = WriteAsyncInternal(this, value, _charBuffer, _charPos, _charLen, CoreNewLine, _autoFlush, appendNewLine: false); _asyncWriteTask = task; return task; } else { return Task.CompletedTask; } } // We pass in private instance fields of this MarshalByRefObject-derived type as local params // to ensure performant access inside the state machine that corresponds this async method. // Fields that are written to must be assigned at the end of the method *and* before instance invocations. private static async Task WriteAsyncInternal(StreamWriter _this, string value, char[] charBuffer, int charPos, int charLen, char[] coreNewLine, bool autoFlush, bool appendNewLine) { Debug.Assert(value != null); int count = value.Length; int index = 0; while (count > 0) { if (charPos == charLen) { await _this.FlushAsyncInternal(false, false, charBuffer, charPos).ConfigureAwait(false); Debug.Assert(_this._charPos == 0); charPos = 0; } int n = charLen - charPos; if (n > count) { n = count; } Debug.Assert(n > 0, "StreamWriter::Write(String) isn't making progress! This is most likely a race condition in user code."); value.CopyTo(index, charBuffer, charPos, n); charPos += n; index += n; count -= n; } if (appendNewLine) { for (int i = 0; i < coreNewLine.Length; i++) // Expect 2 iterations, no point calling BlockCopy { if (charPos == charLen) { await _this.FlushAsyncInternal(false, false, charBuffer, charPos).ConfigureAwait(false); Debug.Assert(_this._charPos == 0); charPos = 0; } charBuffer[charPos] = coreNewLine[i]; charPos++; } } if (autoFlush) { await _this.FlushAsyncInternal(true, false, charBuffer, charPos).ConfigureAwait(false); Debug.Assert(_this._charPos == 0); charPos = 0; } _this._charPos = charPos; } public override Task WriteAsync(char[] buffer, int index, int count) { if (buffer == null) { throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); } if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum); } if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); } if (buffer.Length - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } // If we have been inherited into a subclass, the following implementation could be incorrect // since it does not call through to Write() which a subclass might have overridden. // To be safe we will only use this implementation in cases where we know it is safe to do so, // and delegate to our base class (which will call into Write) when we are not sure. if (GetType() != typeof(StreamWriter)) { return base.WriteAsync(buffer, index, count); } ThrowIfDisposed(); CheckAsyncTaskInProgress(); Task task = WriteAsyncInternal(this, new ReadOnlyMemory<char>(buffer, index, count), _charBuffer, _charPos, _charLen, CoreNewLine, _autoFlush, appendNewLine: false, cancellationToken: default); _asyncWriteTask = task; return task; } public override Task WriteAsync(ReadOnlyMemory<char> buffer, CancellationToken cancellationToken = default) { if (GetType() != typeof(StreamWriter)) { // If a derived type may have overridden existing WriteASync(char[], ...) behavior, make sure we use it. return base.WriteAsync(buffer, cancellationToken); } ThrowIfDisposed(); CheckAsyncTaskInProgress(); if (cancellationToken.IsCancellationRequested) { return Task.FromCanceled(cancellationToken); } Task task = WriteAsyncInternal(this, buffer, _charBuffer, _charPos, _charLen, CoreNewLine, _autoFlush, appendNewLine: false, cancellationToken: cancellationToken); _asyncWriteTask = task; return task; } // We pass in private instance fields of this MarshalByRefObject-derived type as local params // to ensure performant access inside the state machine that corresponds this async method. // Fields that are written to must be assigned at the end of the method *and* before instance invocations. private static async Task WriteAsyncInternal(StreamWriter _this, ReadOnlyMemory<char> source, char[] charBuffer, int charPos, int charLen, char[] coreNewLine, bool autoFlush, bool appendNewLine, CancellationToken cancellationToken) { int copied = 0; while (copied < source.Length) { if (charPos == charLen) { await _this.FlushAsyncInternal(false, false, charBuffer, charPos, cancellationToken).ConfigureAwait(false); Debug.Assert(_this._charPos == 0); charPos = 0; } int n = Math.Min(charLen - charPos, source.Length - copied); Debug.Assert(n > 0, "StreamWriter::Write(char[], int, int) isn't making progress! This is most likely a race condition in user code."); source.Span.Slice(copied, n).CopyTo(new Span<char>(charBuffer, charPos, n)); charPos += n; copied += n; } if (appendNewLine) { for (int i = 0; i < coreNewLine.Length; i++) // Expect 2 iterations, no point calling BlockCopy { if (charPos == charLen) { await _this.FlushAsyncInternal(false, false, charBuffer, charPos, cancellationToken).ConfigureAwait(false); Debug.Assert(_this._charPos == 0); charPos = 0; } charBuffer[charPos] = coreNewLine[i]; charPos++; } } if (autoFlush) { await _this.FlushAsyncInternal(true, false, charBuffer, charPos, cancellationToken).ConfigureAwait(false); Debug.Assert(_this._charPos == 0); charPos = 0; } _this._charPos = charPos; } public override Task WriteLineAsync() { // If we have been inherited into a subclass, the following implementation could be incorrect // since it does not call through to Write() which a subclass might have overridden. // To be safe we will only use this implementation in cases where we know it is safe to do so, // and delegate to our base class (which will call into Write) when we are not sure. if (GetType() != typeof(StreamWriter)) { return base.WriteLineAsync(); } ThrowIfDisposed(); CheckAsyncTaskInProgress(); Task task = WriteAsyncInternal(this, ReadOnlyMemory<char>.Empty, _charBuffer, _charPos, _charLen, CoreNewLine, _autoFlush, appendNewLine: true, cancellationToken: default); _asyncWriteTask = task; return task; } public override Task WriteLineAsync(char value) { // If we have been inherited into a subclass, the following implementation could be incorrect // since it does not call through to Write() which a subclass might have overridden. // To be safe we will only use this implementation in cases where we know it is safe to do so, // and delegate to our base class (which will call into Write) when we are not sure. if (GetType() != typeof(StreamWriter)) { return base.WriteLineAsync(value); } ThrowIfDisposed(); CheckAsyncTaskInProgress(); Task task = WriteAsyncInternal(this, value, _charBuffer, _charPos, _charLen, CoreNewLine, _autoFlush, appendNewLine: true); _asyncWriteTask = task; return task; } public override Task WriteLineAsync(string? value) { if (value == null) { return WriteLineAsync(); } // If we have been inherited into a subclass, the following implementation could be incorrect // since it does not call through to Write() which a subclass might have overridden. // To be safe we will only use this implementation in cases where we know it is safe to do so, // and delegate to our base class (which will call into Write) when we are not sure. if (GetType() != typeof(StreamWriter)) { return base.WriteLineAsync(value); } ThrowIfDisposed(); CheckAsyncTaskInProgress(); Task task = WriteAsyncInternal(this, value, _charBuffer, _charPos, _charLen, CoreNewLine, _autoFlush, appendNewLine: true); _asyncWriteTask = task; return task; } public override Task WriteLineAsync(char[] buffer, int index, int count) { if (buffer == null) { throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); } if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum); } if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); } if (buffer.Length - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } // If we have been inherited into a subclass, the following implementation could be incorrect // since it does not call through to Write() which a subclass might have overridden. // To be safe we will only use this implementation in cases where we know it is safe to do so, // and delegate to our base class (which will call into Write) when we are not sure. if (GetType() != typeof(StreamWriter)) { return base.WriteLineAsync(buffer, index, count); } ThrowIfDisposed(); CheckAsyncTaskInProgress(); Task task = WriteAsyncInternal(this, new ReadOnlyMemory<char>(buffer, index, count), _charBuffer, _charPos, _charLen, CoreNewLine, _autoFlush, appendNewLine: true, cancellationToken: default); _asyncWriteTask = task; return task; } public override Task WriteLineAsync(ReadOnlyMemory<char> buffer, CancellationToken cancellationToken = default) { if (GetType() != typeof(StreamWriter)) { return base.WriteLineAsync(buffer, cancellationToken); } ThrowIfDisposed(); CheckAsyncTaskInProgress(); if (cancellationToken.IsCancellationRequested) { return Task.FromCanceled(cancellationToken); } Task task = WriteAsyncInternal(this, buffer, _charBuffer, _charPos, _charLen, CoreNewLine, _autoFlush, appendNewLine: true, cancellationToken: cancellationToken); _asyncWriteTask = task; return task; } public override Task FlushAsync() { // If we have been inherited into a subclass, the following implementation could be incorrect // since it does not call through to Flush() which a subclass might have overridden. To be safe // we will only use this implementation in cases where we know it is safe to do so, // and delegate to our base class (which will call into Flush) when we are not sure. if (GetType() != typeof(StreamWriter)) { return base.FlushAsync(); } // flushEncoder should be true at the end of the file and if // the user explicitly calls Flush (though not if AutoFlush is true). // This is required to flush any dangling characters from our UTF-7 // and UTF-8 encoders. ThrowIfDisposed(); CheckAsyncTaskInProgress(); Task task = FlushAsyncInternal(true, true, _charBuffer, _charPos); _asyncWriteTask = task; return task; } private Task FlushAsyncInternal(bool flushStream, bool flushEncoder, char[] sCharBuffer, int sCharPos, CancellationToken cancellationToken = default) { if (cancellationToken.IsCancellationRequested) { return Task.FromCanceled(cancellationToken); } // Perf boost for Flush on non-dirty writers. if (sCharPos == 0 && !flushStream && !flushEncoder) { return Task.CompletedTask; } Task flushTask = FlushAsyncInternal(this, flushStream, flushEncoder, sCharBuffer, sCharPos, _haveWrittenPreamble, _encoding, _encoder, _byteBuffer, _stream, cancellationToken); _charPos = 0; return flushTask; } // We pass in private instance fields of this MarshalByRefObject-derived type as local params // to ensure performant access inside the state machine that corresponds this async method. private static async Task FlushAsyncInternal(StreamWriter _this, bool flushStream, bool flushEncoder, char[] charBuffer, int charPos, bool haveWrittenPreamble, Encoding encoding, Encoder encoder, byte[] byteBuffer, Stream stream, CancellationToken cancellationToken) { if (!haveWrittenPreamble) { _this._haveWrittenPreamble = true; byte[] preamble = encoding.GetPreamble(); if (preamble.Length > 0) { await stream.WriteAsync(new ReadOnlyMemory<byte>(preamble), cancellationToken).ConfigureAwait(false); } } int count = encoder.GetBytes(charBuffer, 0, charPos, byteBuffer, 0, flushEncoder); if (count > 0) { await stream.WriteAsync(new ReadOnlyMemory<byte>(byteBuffer, 0, count), cancellationToken).ConfigureAwait(false); } // By definition, calling Flush should flush the stream, but this is // only necessary if we passed in true for flushStream. The Web // Services guys have some perf tests where flushing needlessly hurts. if (flushStream) { await stream.FlushAsync(cancellationToken).ConfigureAwait(false); } } private void ThrowIfDisposed() { if (_disposed) { ThrowObjectDisposedException(); } void ThrowObjectDisposedException() => throw new ObjectDisposedException(GetType().Name, SR.ObjectDisposed_WriterClosed); } } // class StreamWriter } // namespace
// Adaptive Quality|Scripts|0240 // Adapted from The Lab Renderer's ValveCamera.cs, available at // https://github.com/ValveSoftware/the_lab_renderer/blob/ae64c48a8ccbe5406aba1e39b160d4f2f7156c2c/Assets/TheLabRenderer/Scripts/ValveCamera.cs // For The Lab Renderer's license see THIRD_PARTY_NOTICES. // **Only Compatible With Unity 5.4 and above** #if (UNITY_5_4_OR_NEWER) namespace VRTK { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Text; using UnityEngine; using UnityEngine.VR; /// <summary> /// Adaptive Quality dynamically changes rendering settings to maintain VR framerate while maximizing GPU utilization. /// </summary> /// <remarks> /// > **Only Compatible With Unity 5.4 and above** /// /// The Adaptive Quality script is attached to the `eye` object within the `[CameraRig]` prefab. /// <para>&#160;</para> /// There are two goals: /// <list type="bullet"> /// <item> <description>Reduce the chances of dropping frames and reprojecting</description> </item> /// <item> <description>Increase quality when there are idle GPU cycles</description> </item> /// </list> /// <para /> /// This script currently changes the following to reach these goals: /// <list type="bullet"> /// <item> <description>Rendering resolution and viewport (aka Dynamic Resolution)</description> </item> /// </list> /// <para /> /// In the future it could be changed to also change the following: /// <list type="bullet"> /// <item> <description>MSAA level</description> </item> /// <item> <description>Fixed Foveated Rendering</description> </item> /// <item> <description>Radial Density Masking</description> </item> /// <item> <description>(Non-fixed) Foveated Rendering (once HMDs support eye tracking)</description> </item> /// </list> /// <para /> /// Some shaders, especially Image Effects, need to be modified to work with the changed render scale. To fix them /// pass `1.0f / VRSettings.renderViewportScale` into the shader and scale all incoming UV values with it in the vertex /// program. Do this by using `Material.SetFloat` to set the value in the script that configures the shader. /// <para /> /// In more detail: /// <list type="bullet"> /// <item> <description>In the `.shader` file: Add a new runtime-set property value `float _InverseOfRenderViewportScale` /// and add `vertexInput.texcoord *= _InverseOfRenderViewportScale` to the start of the vertex program</description> </item> /// <item> <description>In the `.cs` file: Before using the material (eg. `Graphics.Blit`) add /// `material.SetFloat("_InverseOfRenderViewportScale", 1.0f / VRSettings.renderViewportScale)`</description> </item> /// </list> /// </remarks> /// <example> /// `VRTK/Examples/039_CameraRig_AdaptiveQuality` displays the frames per second in the centre of the headset view. /// The debug visualization of this script is displayed near the top edge of the headset view. /// Pressing the trigger generates a new sphere and pressing the touchpad generates ten new spheres. /// Eventually when lots of spheres are present the FPS will drop and demonstrate the script. /// </example> public sealed class VRTK_AdaptiveQuality : MonoBehaviour { #region Public fields [Tooltip("Toggles whether the render quality is dynamically adjusted to maintain VR framerate.\n\n" + "If unchecked, the renderer will render at the recommended resolution provided by the current `VRDevice`.")] public bool active = true; [Tooltip("Toggles whether to show the debug overlay.\n\n" + "Each square represents a different level on the quality scale. Levels increase from left to right," + " and the first green box that is lit above represents the recommended render target resolution provided by" + " the current `VRDevice`. The yellow boxes represent resolutions below the recommended render target resolution.\n" + "The currently lit box becomes red whenever the user is likely seeing reprojection in the HMD since the" + " application isn't maintaining VR framerate. If lit, the box all the way on the left is almost always lit red because" + " it represents the lowest render scale with reprojection on.")] public bool drawDebugVisualization; [Tooltip("Toggles whether to allow keyboard shortcuts to control this script.\n\n" + "* The supported shortcuts are:\n" + " * `Shift+F1`: Toggle debug visualization on/off\n" + " * `Shift+F2`: Toggle usage of override render scale on/off\n" + " * `Shift+F3`: Decrease override render scale level\n" + " * `Shift+F4`: Increase override render scale level")] public bool respondsToKeyboardShortcuts = true; [Tooltip("Toggles whether to allow command line arguments to control this script at startup of the standalone build.\n\n" + "* The supported command line arguments all begin with '-' and are:\n" + " * `-noaq`: Disable adaptive quality\n" + " * `-aqminscale X`: Set minimum render scale to X\n" + " * `-aqmaxscale X`: Set maximum render scale to X\n" + " * `-aqmaxres X`: Set maximum render target dimension to X\n" + " * `-aqfillratestep X`: Set render scale fill rate step size in percent to X (X from 1 to 100)\n" + " * `-aqoverride X`: Set override render scale level to X\n" + " * `-vrdebug`: Enable debug visualization\n" + " * `-msaa X`: Set MSAA level to X")] public bool respondsToCommandLineArguments = true; [Tooltip("The MSAA level to use.")] [Header("Quality")] [Range(0, 8)] public int msaaLevel = 4; [Tooltip("The minimum allowed render scale.")] [Header("Render Scale")] [Range(0.01f, 5)] public float minimumRenderScale = 0.8f; [Tooltip("The maximum allowed render scale.")] public float maximumRenderScale = 1.4f; [Tooltip("The maximum allowed render target dimension.\n\n" + "This puts an upper limit on the size of the render target regardless of the maximum render scale.")] public int maximumRenderTargetDimension = 4096; [Tooltip("The fill rate step size in percent by which the render scale levels will be calculated.")] [Range(1, 100)] public int renderScaleFillRateStepSizeInPercent = 15; [Tooltip("Toggles whether to override the used render scale level.")] [Header("Override")] [NonSerialized] public bool overrideRenderScale; [Tooltip("The render scale level to override the current one with.")] [NonSerialized] public int overrideRenderScaleLevel; #endregion #region Public readonly fields & properties /// <summary> /// All the calculated render scales. /// </summary> /// <remarks> /// The elements of this collection are to be interpreted as modifiers to the recommended render target /// resolution provided by the current `VRDevice`. /// </remarks> public readonly ReadOnlyCollection<float> renderScales; /// <summary> /// The current render scale. /// </summary> /// <remarks> /// A render scale of 1.0 represents the recommended render target resolution provided by the current `VRDevice`. /// </remarks> public float currentRenderScale { get { return VRSettings.renderScale * VRSettings.renderViewportScale; } } /// <summary> /// The recommended render target resolution provided by the current `VRDevice`. /// </summary> public Vector2 defaultRenderTargetResolution { get { return RenderTargetResolutionForRenderScale(allRenderScales[defaultRenderScaleLevel]); } } /// <summary> /// The current render target resolution. /// </summary> public Vector2 currentRenderTargetResolution { get { return RenderTargetResolutionForRenderScale(currentRenderScale); } } #endregion #region Private fields /// <summary> /// The frame duration in milliseconds to fallback to if the current `VRDevice` specifies no refresh rate. /// </summary> private const float DefaultFrameDurationInMilliseconds = 1000f / 90f; private readonly List<float> allRenderScales = new List<float>(); private int defaultRenderScaleLevel; private int currentRenderScaleLevel; private float previousMinimumRenderScale; private float previousMaximumRenderScale; private float previousRenderScaleFillRateStepSizeInPercent; private int lastRenderScaleChangeFrameCount; private readonly float[] frameTimeRingBuffer = { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f }; private int frameTimeRingBufferIndex; private bool interleavedReprojectionEnabled; private bool hmdDisplayIsOnDesktop; private float singleFrameDurationInMilliseconds; private GameObject debugVisualizationQuad; private Material debugVisualizationQuadMaterial; #endregion public VRTK_AdaptiveQuality() { renderScales = allRenderScales.AsReadOnly(); } /// <summary> /// Calculates and returns the render target resolution for a given render scale. /// </summary> /// <param name="renderScale"> /// The render scale to calculate the render target resolution with. /// </param> /// <returns> /// The render target resolution for `renderScale`. /// </returns> public static Vector2 RenderTargetResolutionForRenderScale(float renderScale) { return new Vector2((int)(VRSettings.eyeTextureWidth / VRSettings.renderScale * renderScale), (int)(VRSettings.eyeTextureHeight / VRSettings.renderScale * renderScale)); } /// <summary> /// Calculates and returns the biggest allowed maximum render scale to be used for `maximumRenderScale` /// given the current `maximumRenderTargetDimension`. /// </summary> /// <returns> /// The biggest allowed maximum render scale. /// </returns> public float BiggestAllowedMaximumRenderScale() { if (VRSettings.eyeTextureWidth == 0 || VRSettings.eyeTextureHeight == 0) { return maximumRenderScale; } float maximumHorizontalRenderScale = maximumRenderTargetDimension * VRSettings.renderScale / VRSettings.eyeTextureWidth; float maximumVerticalRenderScale = maximumRenderTargetDimension * VRSettings.renderScale / VRSettings.eyeTextureHeight; return Mathf.Min(maximumHorizontalRenderScale, maximumVerticalRenderScale); } /// <summary> /// A summary of this script by listing all the calculated render scales with their /// corresponding render target resolution. /// </summary> /// <returns> /// The summary. /// </returns> public override string ToString() { var stringBuilder = new StringBuilder("Adaptive Quality:\n"); for (int index = 0; index < allRenderScales.Count; index++) { float renderScale = allRenderScales[index]; var renderTargetResolution = RenderTargetResolutionForRenderScale(renderScale); stringBuilder.Append(index); stringBuilder.Append(". "); stringBuilder.Append(" "); stringBuilder.Append((int)renderTargetResolution.x); stringBuilder.Append("x"); stringBuilder.Append((int)renderTargetResolution.y); stringBuilder.Append(" "); stringBuilder.Append(renderScale); if (index == 0) { stringBuilder.Append(" (Interleaved reprojection hint)"); } else if (index == defaultRenderScaleLevel) { stringBuilder.Append(" (Default)"); } if (index != allRenderScales.Count - 1) { stringBuilder.Append("\n"); } } return stringBuilder.ToString(); } #region MonoBehaviour methods private void OnEnable() { hmdDisplayIsOnDesktop = VRTK_SDK_Bridge.IsDisplayOnDesktop(); singleFrameDurationInMilliseconds = VRDevice.refreshRate > 0.0f ? 1000.0f / VRDevice.refreshRate : DefaultFrameDurationInMilliseconds; HandleCommandLineArguments(); if (!Application.isEditor) { OnValidate(); } CreateOrDestroyDebugVisualization(); } private void OnDisable() { CreateOrDestroyDebugVisualization(); SetRenderScale(1.0f, 1.0f); } private void OnValidate() { minimumRenderScale = Mathf.Max(0.01f, minimumRenderScale); maximumRenderScale = Mathf.Max(minimumRenderScale, maximumRenderScale); maximumRenderTargetDimension = Mathf.Max(2, maximumRenderTargetDimension); renderScaleFillRateStepSizeInPercent = Mathf.Max(1, renderScaleFillRateStepSizeInPercent); msaaLevel = msaaLevel == 1 ? 0 : Mathf.Clamp(Mathf.ClosestPowerOfTwo(msaaLevel), 0, 8); CreateOrDestroyDebugVisualization(); } private void Update() { HandleKeyPresses(); UpdateRenderScaleLevels(); UpdateDebugVisualization(); } #if UNITY_5_4_1 || UNITY_5_5_OR_NEWER private void LateUpdate() { UpdateRenderScale(); } #endif private void OnPreCull() { #if !(UNITY_5_4_1 || UNITY_5_5_OR_NEWER) UpdateRenderScale(); #endif UpdateMSAALevel(); } #endregion private void HandleCommandLineArguments() { if (!respondsToCommandLineArguments) { return; } var commandLineArguments = Environment.GetCommandLineArgs(); for (int index = 0; index < commandLineArguments.Length; index++) { string argument = commandLineArguments[index]; string nextArgument = index + 1 < commandLineArguments.Length ? commandLineArguments[index + 1] : ""; switch (argument) { case CommandLineArguments.Disable: active = false; break; case CommandLineArguments.MinimumRenderScale: minimumRenderScale = float.Parse(nextArgument); break; case CommandLineArguments.MaximumRenderScale: maximumRenderScale = float.Parse(nextArgument); break; case CommandLineArguments.MaximumRenderTargetDimension: maximumRenderTargetDimension = int.Parse(nextArgument); break; case CommandLineArguments.RenderScaleFillRateStepSizeInPercent: renderScaleFillRateStepSizeInPercent = int.Parse(nextArgument); break; case CommandLineArguments.OverrideRenderScaleLevel: overrideRenderScale = true; overrideRenderScaleLevel = int.Parse(nextArgument); break; case CommandLineArguments.DrawDebugVisualization: drawDebugVisualization = true; CreateOrDestroyDebugVisualization(); break; case CommandLineArguments.MSAALevel: msaaLevel = int.Parse(nextArgument); break; } } } private void HandleKeyPresses() { if (!respondsToKeyboardShortcuts || !(Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift))) { return; } // Toggle debug visualization on Shift+F1 if (Input.GetKeyDown(KeyCode.F1)) { drawDebugVisualization = !drawDebugVisualization; CreateOrDestroyDebugVisualization(); } // Toggle usage of override render scale on Shift+F2 if (Input.GetKeyDown(KeyCode.F2)) { overrideRenderScale = !overrideRenderScale; } // Decrease override render scale level on Shift+F3 if (Input.GetKeyDown(KeyCode.F3)) { overrideRenderScaleLevel = Mathf.Clamp(overrideRenderScaleLevel - 1, 0, allRenderScales.Count - 1); } // Increase override render scale level on Shift+F4 if (Input.GetKeyDown(KeyCode.F4)) { overrideRenderScaleLevel = Mathf.Clamp(overrideRenderScaleLevel + 1, 0, allRenderScales.Count - 1); } } private void UpdateMSAALevel() { if (QualitySettings.antiAliasing != msaaLevel) { QualitySettings.antiAliasing = msaaLevel; } } #region Render scale methods private void UpdateRenderScaleLevels() { if (Mathf.Abs(previousMinimumRenderScale - minimumRenderScale) <= float.Epsilon && Mathf.Abs(previousMaximumRenderScale - maximumRenderScale) <= float.Epsilon && Mathf.Abs(previousRenderScaleFillRateStepSizeInPercent - renderScaleFillRateStepSizeInPercent) <= float.Epsilon) { return; } previousMinimumRenderScale = minimumRenderScale; previousMaximumRenderScale = maximumRenderScale; previousRenderScaleFillRateStepSizeInPercent = renderScaleFillRateStepSizeInPercent; allRenderScales.Clear(); // Respect maximumRenderTargetDimension float allowedMaximumRenderScale = BiggestAllowedMaximumRenderScale(); float renderScaleToAdd = Mathf.Min(minimumRenderScale, allowedMaximumRenderScale); // Add min scale as the reprojection scale allRenderScales.Add(renderScaleToAdd); // Add all entries while (renderScaleToAdd <= maximumRenderScale) { allRenderScales.Add(renderScaleToAdd); renderScaleToAdd = Mathf.Sqrt((renderScaleFillRateStepSizeInPercent + 100) / 100.0f * renderScaleToAdd * renderScaleToAdd); if (renderScaleToAdd > allowedMaximumRenderScale) { // Too large break; } } // Figure out default level for debug visualization defaultRenderScaleLevel = Mathf.Clamp( allRenderScales.FindIndex(renderScale => renderScale >= 1.0f), 1, allRenderScales.Count - 1); currentRenderScaleLevel = defaultRenderScaleLevel; overrideRenderScaleLevel = Mathf.Clamp(overrideRenderScaleLevel, 0, allRenderScales.Count - 1); currentRenderScaleLevel = Mathf.Clamp(currentRenderScaleLevel, 0, allRenderScales.Count - 1); } private void UpdateRenderScale() { if (!active) { SetRenderScale(1.0f, 1.0f); return; } // Add latest timing to ring buffer frameTimeRingBufferIndex = (frameTimeRingBufferIndex + 1) % frameTimeRingBuffer.Length; frameTimeRingBuffer[frameTimeRingBufferIndex] = VRStats.gpuTimeLastFrame; // Rendering in low resolution means adaptive quality needs to scale back the render scale target to free up gpu cycles bool renderInLowResolution = VRTK_SDK_Bridge.ShouldAppRenderWithLowResources(); // Thresholds float thresholdModifier = renderInLowResolution ? singleFrameDurationInMilliseconds * 0.75f : singleFrameDurationInMilliseconds; float lowThresholdInMilliseconds = 0.7f * thresholdModifier; float extrapolationThresholdInMilliseconds = 0.85f * thresholdModifier; float highThresholdInMilliseconds = 0.9f * thresholdModifier; // Get latest 3 frames float frameMinus0 = frameTimeRingBuffer[(frameTimeRingBufferIndex - 0 + frameTimeRingBuffer.Length) % frameTimeRingBuffer.Length]; float frameMinus1 = frameTimeRingBuffer[(frameTimeRingBufferIndex - 1 + frameTimeRingBuffer.Length) % frameTimeRingBuffer.Length]; float frameMinus2 = frameTimeRingBuffer[(frameTimeRingBufferIndex - 2 + frameTimeRingBuffer.Length) % frameTimeRingBuffer.Length]; int previousLevel = currentRenderScaleLevel; // Always drop 2 levels except when dropping from level 2 int dropTargetLevel = previousLevel == 2 ? 1 : previousLevel - 2; int newLevel = Mathf.Clamp(dropTargetLevel, 0, allRenderScales.Count - 1); // Ignore frame timings if overriding if (overrideRenderScale) { currentRenderScaleLevel = overrideRenderScaleLevel; } // Rapidly reduce quality 2 levels if last frame was critical else if (Time.frameCount >= lastRenderScaleChangeFrameCount + 2 + 1 && frameMinus0 > highThresholdInMilliseconds && newLevel != previousLevel) { currentRenderScaleLevel = newLevel; lastRenderScaleChangeFrameCount = Time.frameCount; } // Rapidly reduce quality 2 levels if last 3 frames are expensive else if (Time.frameCount >= lastRenderScaleChangeFrameCount + 2 + 3 && frameMinus0 > highThresholdInMilliseconds && frameMinus1 > highThresholdInMilliseconds && frameMinus2 > highThresholdInMilliseconds && newLevel != previousLevel) { currentRenderScaleLevel = newLevel; lastRenderScaleChangeFrameCount = Time.frameCount; } // Predict next frame's cost using linear extrapolation: max(frame-1 to frame+1, frame-2 to frame+1) else if (Time.frameCount >= lastRenderScaleChangeFrameCount + 2 + 2 && frameMinus0 > extrapolationThresholdInMilliseconds) { float frameDelta = frameMinus0 - frameMinus1; // Use frame-2 if it's available if (Time.frameCount >= lastRenderScaleChangeFrameCount + 2 + 3) { float frameDelta2 = (frameMinus0 - frameMinus2) * 0.5f; frameDelta = Mathf.Max(frameDelta, frameDelta2); } if (frameMinus0 + frameDelta > highThresholdInMilliseconds && newLevel != previousLevel) { currentRenderScaleLevel = newLevel; lastRenderScaleChangeFrameCount = Time.frameCount; } } else { // Increase quality 1 level if last 3 frames are cheap newLevel = Mathf.Clamp(previousLevel + 1, 0, allRenderScales.Count - 1); if (Time.frameCount >= lastRenderScaleChangeFrameCount + 2 + 3 && frameMinus0 < lowThresholdInMilliseconds && frameMinus1 < lowThresholdInMilliseconds && frameMinus2 < lowThresholdInMilliseconds && newLevel != previousLevel) { currentRenderScaleLevel = newLevel; lastRenderScaleChangeFrameCount = Time.frameCount; } } // Force on interleaved reprojection for level 0 which is just a replica of level 1 with reprojection enabled float additionalViewportScale = 1.0f; if (!hmdDisplayIsOnDesktop) { if (currentRenderScaleLevel == 0) { if (interleavedReprojectionEnabled && frameMinus0 < singleFrameDurationInMilliseconds * 0.85f) { interleavedReprojectionEnabled = false; } else if (frameMinus0 > singleFrameDurationInMilliseconds * 0.925f) { interleavedReprojectionEnabled = true; } } else { interleavedReprojectionEnabled = false; } VRTK_SDK_Bridge.ForceInterleavedReprojectionOn(interleavedReprojectionEnabled); } // Not running in direct mode! Interleaved reprojection not supported, so scale down the viewport else if (currentRenderScaleLevel == 0) { additionalViewportScale = 0.8f; } float newRenderScale = allRenderScales[allRenderScales.Count - 1]; float newRenderViewportScale = allRenderScales[currentRenderScaleLevel] / newRenderScale * additionalViewportScale; SetRenderScale(newRenderScale, newRenderViewportScale); } private static void SetRenderScale(float renderScale, float renderViewportScale) { if (Mathf.Abs(VRSettings.renderScale - renderScale) > float.Epsilon) { VRSettings.renderScale = renderScale; } if (Mathf.Abs(VRSettings.renderViewportScale - renderViewportScale) > float.Epsilon) { VRSettings.renderViewportScale = renderViewportScale; } } #endregion #region Debug visualization methods private void CreateOrDestroyDebugVisualization() { if (!Application.isPlaying) { return; } if (enabled && drawDebugVisualization && debugVisualizationQuad == null) { var mesh = new Mesh { vertices = new[] { new Vector3(-0.5f, 0.9f, 1.0f), new Vector3(-0.5f, 1.0f, 1.0f), new Vector3(0.5f, 1.0f, 1.0f), new Vector3(0.5f, 0.9f, 1.0f) }, uv = new[] { new Vector2(0.0f, 0.0f), new Vector2(0.0f, 1.0f), new Vector2(1.0f, 1.0f), new Vector2(1.0f, 0.0f) }, triangles = new[] { 0, 1, 2, 0, 2, 3 } }; mesh.Optimize(); mesh.UploadMeshData(true); debugVisualizationQuad = new GameObject("AdaptiveQualityDebugVisualizationQuad"); debugVisualizationQuad.transform.parent = transform; debugVisualizationQuad.transform.localPosition = Vector3.forward; debugVisualizationQuad.transform.localRotation = Quaternion.identity; debugVisualizationQuad.AddComponent<MeshFilter>().mesh = mesh; debugVisualizationQuadMaterial = Resources.Load<Material>("AdaptiveQualityDebugVisualization"); debugVisualizationQuad.AddComponent<MeshRenderer>().material = debugVisualizationQuadMaterial; } else if ((!enabled || !drawDebugVisualization) && debugVisualizationQuad != null) { Destroy(debugVisualizationQuad); debugVisualizationQuad = null; debugVisualizationQuadMaterial = null; } } private void UpdateDebugVisualization() { if (!drawDebugVisualization || debugVisualizationQuadMaterial == null) { return; } int lastFrameIsInBudget = interleavedReprojectionEnabled || VRStats.gpuTimeLastFrame > singleFrameDurationInMilliseconds ? 0 : 1; debugVisualizationQuadMaterial.SetInt(ShaderPropertyIDs.LevelsCount, allRenderScales.Count); debugVisualizationQuadMaterial.SetInt(ShaderPropertyIDs.DefaultLevel, defaultRenderScaleLevel); debugVisualizationQuadMaterial.SetInt(ShaderPropertyIDs.CurrentLevel, currentRenderScaleLevel); debugVisualizationQuadMaterial.SetInt(ShaderPropertyIDs.LastFrameIsInBudget, lastFrameIsInBudget); } #endregion #region Private helper classes private static class CommandLineArguments { public const string Disable = "-noaq"; public const string MinimumRenderScale = "-aqminscale"; public const string MaximumRenderScale = "-aqmaxscale"; public const string MaximumRenderTargetDimension = "-aqmaxres"; public const string RenderScaleFillRateStepSizeInPercent = "-aqfillratestep"; public const string OverrideRenderScaleLevel = "-aqoverride"; public const string DrawDebugVisualization = "-vrdebug"; public const string MSAALevel = "-msaa"; } private static class ShaderPropertyIDs { public static readonly int LevelsCount = Shader.PropertyToID("_LevelsCount"); public static readonly int DefaultLevel = Shader.PropertyToID("_DefaultLevel"); public static readonly int CurrentLevel = Shader.PropertyToID("_CurrentLevel"); public static readonly int LastFrameIsInBudget = Shader.PropertyToID("_LastFrameIsInBudget"); } #endregion } } #endif
namespace Nancy.ModelBinding { using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using Nancy.Validation; public static class ModuleExtensions { private static readonly string[] NoBlacklistedProperties = ArrayCache.Empty<string>(); /// <summary> /// Parses an array of expressions like <code>t =&gt; t.Property</code> to a list of strings containing the property names; /// </summary> /// <typeparam name="T">Type of the model</typeparam> /// <param name="expressions">Expressions that tell which property should be ignored</param> /// <returns>Array of strings containing the names of the properties.</returns> private static string[] ParseBlacklistedPropertiesExpressionTree<T>(this IEnumerable<Expression<Func<T, object>>> expressions) { return expressions.Select(p => p.GetTargetMemberInfo().Name).ToArray(); } /// <summary> /// Bind the incoming request to a model /// </summary> /// <param name="module">Current module</param> /// <param name="blacklistedProperties">Property names to blacklist from binding</param> /// <returns>Model adapter - cast to a model type to bind it</returns> public static dynamic Bind(this INancyModule module, params string[] blacklistedProperties) { return module.Bind(BindingConfig.Default, blacklistedProperties); } /// <summary> /// Bind the incoming request to a model /// </summary> /// <param name="module">Current module</param> /// <param name="configuration">The <see cref="BindingConfig"/> that should be applied during binding.</param> /// <param name="blacklistedProperties">Property names to blacklist from binding</param> /// <returns>Model adapter - cast to a model type to bind it</returns> public static dynamic Bind(this INancyModule module, BindingConfig configuration, params string[] blacklistedProperties) { return new DynamicModelBinderAdapter(module.ModelBinderLocator, module.Context, null, configuration, blacklistedProperties); } /// <summary> /// Bind the incoming request to a model /// </summary> /// <typeparam name="TModel">Model type</typeparam> /// <param name="module">Current module</param> /// <returns>Bound model instance</returns> public static TModel Bind<TModel>(this INancyModule module) { return module.Bind(); } /// <summary> /// Bind the incoming request to a model /// </summary> /// <typeparam name="TModel">Model type</typeparam> /// <param name="module">Current module</param> /// <param name="blacklistedProperties">Property names to blacklist from binding</param> /// <returns>Bound model instance</returns> public static TModel Bind<TModel>(this INancyModule module, params string[] blacklistedProperties) { return module.Bind(blacklistedProperties); } /// <summary> /// Bind the incoming request to a model /// </summary> /// <typeparam name="TModel">Model type</typeparam> /// <param name="module">Current module</param> /// <param name="blacklistedProperties">Expressions that tell which property should be ignored</param> /// <example>this.Bind&lt;Person&gt;(p =&gt; p.Name, p =&gt; p.Age)</example> /// <returns>Bound model instance</returns> public static TModel Bind<TModel>(this INancyModule module, params Expression<Func<TModel, object>>[] blacklistedProperties) { return module.Bind<TModel>(blacklistedProperties.ParseBlacklistedPropertiesExpressionTree()); } /// <summary> /// Bind the incoming request to a model and validate /// </summary> /// <typeparam name="TModel">Model type</typeparam> /// <param name="module">Current module</param> /// <param name="blacklistedProperties">Property names to blacklist from binding</param> /// <returns>Bound model instance</returns> /// <remarks><see cref="ModelValidationResult"/> is stored in NancyModule.ModelValidationResult and NancyContext.ModelValidationResult.</remarks> public static TModel BindAndValidate<TModel>(this INancyModule module, params string[] blacklistedProperties) { var model = module.Bind<TModel>(blacklistedProperties); module.Validate(model); return model; } /// <summary> /// Bind the incoming request to a model and validate /// </summary> /// <typeparam name="TModel">Model type</typeparam> /// <param name="module">Current module</param> /// <param name="blacklistedProperties">Expressions that tell which property should be ignored</param> /// <example>this.Bind&lt;Person&gt;(p =&gt; p.Name, p =&gt; p.Age)</example> /// <returns>Bound model instance</returns> /// <remarks><see cref="ModelValidationResult"/> is stored in NancyModule.ModelValidationResult and NancyContext.ModelValidationResult.</remarks> public static TModel BindAndValidate<TModel>(this INancyModule module, params Expression<Func<TModel, object>>[] blacklistedProperties) { var model = module.Bind<TModel>(blacklistedProperties.ParseBlacklistedPropertiesExpressionTree()); module.Validate(model); return model; } /// <summary> /// Bind the incoming request to a model and validate /// </summary> /// <typeparam name="TModel">Model type</typeparam> /// <param name="module">Current module</param> /// <returns>Bound model instance</returns> /// <remarks><see cref="ModelValidationResult"/> is stored in NancyModule.ModelValidationResult and NancyContext.ModelValidationResult.</remarks> public static TModel BindAndValidate<TModel>(this INancyModule module) { var model = module.Bind<TModel>(NoBlacklistedProperties); module.Validate(model); return model; } /// <summary> /// Bind the incoming request to a model /// </summary> /// <typeparam name="TModel">Model type</typeparam> /// <param name="module">Current module</param> /// <param name="configuration">The <see cref="BindingConfig"/> that should be applied during binding.</param> /// <returns>Bound model instance</returns> public static TModel Bind<TModel>(this INancyModule module, BindingConfig configuration) { return module.Bind(configuration); } /// <summary> /// Bind the incoming request to a model /// </summary> /// <typeparam name="TModel">Model type</typeparam> /// <param name="module">Current module</param> /// <param name="configuration">The <see cref="BindingConfig"/> that should be applied during binding.</param> /// <param name="blacklistedProperties">Property names to blacklist from binding</param> /// <returns>Bound model instance</returns> public static TModel Bind<TModel>(this INancyModule module, BindingConfig configuration, params string[] blacklistedProperties) { return module.Bind(configuration, blacklistedProperties); } /// <summary> /// Bind the incoming request to a model /// </summary> /// <typeparam name="TModel">Model type</typeparam> /// <param name="module">Current module</param> /// <param name="configuration">The <see cref="BindingConfig"/> that should be applied during binding.</param> /// <param name="blacklistedProperty">Expressions that tell which property should be ignored</param> /// <example>this.Bind&lt;Person&gt;(p =&gt; p.Name, p =&gt; p.Age)</example> /// <returns>Bound model instance</returns> public static TModel Bind<TModel>(this INancyModule module, BindingConfig configuration, Expression<Func<TModel, object>> blacklistedProperty) { return module.Bind(configuration, new [] { blacklistedProperty }.ParseBlacklistedPropertiesExpressionTree()); } /// <summary> /// Bind the incoming request to a model /// </summary> /// <typeparam name="TModel">Model type</typeparam> /// <param name="module">Current module</param> /// <param name="configuration">The <see cref="BindingConfig"/> that should be applied during binding.</param> /// <param name="blacklistedProperties">Expressions that tell which property should be ignored</param> /// <example>this.Bind&lt;Person&gt;(p =&gt; p.Name, p =&gt; p.Age)</example> /// <returns>Bound model instance</returns> public static TModel Bind<TModel>(this INancyModule module, BindingConfig configuration, params Expression<Func<TModel, object>>[] blacklistedProperties) { return module.Bind(configuration, blacklistedProperties.ParseBlacklistedPropertiesExpressionTree()); } /// <summary> /// Bind the incoming request to a model and validate /// </summary> /// <typeparam name="TModel">Model type</typeparam> /// <param name="module">Current module</param> /// <param name="configuration">The <see cref="BindingConfig"/> that should be applied during binding.</param> /// <param name="blacklistedProperties">Property names to blacklist from binding</param> /// <returns>Bound model instance</returns> /// <remarks><see cref="ModelValidationResult"/> is stored in NancyModule.ModelValidationResult and NancyContext.ModelValidationResult.</remarks> public static TModel BindAndValidate<TModel>(this INancyModule module, BindingConfig configuration, params string[] blacklistedProperties) { var model = module.Bind<TModel>(configuration, blacklistedProperties); module.Validate(model); return model; } /// <summary> /// Bind the incoming request to a model and validate /// </summary> /// <typeparam name="TModel">Model type</typeparam> /// <param name="module">Current module</param> /// <param name="configuration">The <see cref="BindingConfig"/> that should be applied during binding.</param> /// <param name="blacklistedProperties">Expressions that tell which property should be ignored</param> /// <example>this.Bind&lt;Person&gt;(p =&gt; p.Name, p =&gt; p.Age)</example> /// <returns>Bound model instance</returns> /// <remarks><see cref="ModelValidationResult"/> is stored in NancyModule.ModelValidationResult and NancyContext.ModelValidationResult.</remarks> public static TModel BindAndValidate<TModel>(this INancyModule module, BindingConfig configuration, params Expression<Func<TModel, object>>[] blacklistedProperties) { var model = module.Bind<TModel>(configuration, blacklistedProperties.ParseBlacklistedPropertiesExpressionTree()); module.Validate(model); return model; } /// <summary> /// Bind the incoming request to a model and validate /// </summary> /// <typeparam name="TModel">Model type</typeparam> /// <param name="module">Current module</param> /// <param name="configuration">The <see cref="BindingConfig"/> that should be applied during binding.</param> /// <returns>Bound model instance</returns> /// <remarks><see cref="ModelValidationResult"/> is stored in NancyModule.ModelValidationResult and NancyContext.ModelValidationResult.</remarks> public static TModel BindAndValidate<TModel>(this INancyModule module, BindingConfig configuration) { var model = module.Bind<TModel>(configuration, NoBlacklistedProperties); module.Validate(model); return model; } /// <summary> /// Bind the incoming request to an existing instance /// </summary> /// <typeparam name="TModel">Model type</typeparam> /// <param name="module">Current module</param> /// <param name="instance">The class instance to bind properties to</param> /// <param name="blacklistedProperties">Property names to blacklist from binding</param> public static TModel BindTo<TModel>(this INancyModule module, TModel instance, params string[] blacklistedProperties) { return module.BindTo(instance, BindingConfig.NoOverwrite, blacklistedProperties); } /// <summary> /// Bind the incoming request to an existing instance /// </summary> /// <typeparam name="TModel">Model type</typeparam> /// <param name="module">Current module</param> /// <param name="instance">The class instance to bind properties to</param> /// <param name="blacklistedProperties">Expressions that tell which property should be ignored</param> /// <example>this.Bind&lt;Person&gt;(p =&gt; p.Name, p =&gt; p.Age)</example> public static TModel BindTo<TModel>(this INancyModule module, TModel instance, params Expression<Func<TModel, object>>[] blacklistedProperties) { return module.BindTo(instance, BindingConfig.NoOverwrite, blacklistedProperties.ParseBlacklistedPropertiesExpressionTree()); } /// <summary> /// Bind the incoming request to an existing instance /// </summary> /// <typeparam name="TModel">Model type</typeparam> /// <param name="module">Current module</param> /// <param name="instance">The class instance to bind properties to</param> public static TModel BindTo<TModel>(this INancyModule module, TModel instance) { return module.BindTo(instance, BindingConfig.NoOverwrite, NoBlacklistedProperties); } /// <summary> /// Bind the incoming request to an existing instance and validate /// </summary> /// <typeparam name="TModel">Model type</typeparam> /// <param name="module">Current module</param> /// <param name="instance">The class instance to bind properties to</param> /// <param name="blacklistedProperties">Property names to blacklist from binding</param> /// <remarks><see cref="ModelValidationResult"/> is stored in NancyModule.ModelValidationResult and NancyContext.ModelValidationResult.</remarks> public static TModel BindToAndValidate<TModel>(this INancyModule module, TModel instance, params string[] blacklistedProperties) { var model = module.BindTo(instance, blacklistedProperties); module.Validate(model); return model; } /// <summary> /// Bind the incoming request to an existing instance and validate /// </summary> /// <typeparam name="TModel">Model type</typeparam> /// <param name="module">Current module</param> /// <param name="instance">The class instance to bind properties to</param> /// <param name="blacklistedProperties">Expressions that tell which property should be ignored</param> /// <example>this.Bind&lt;Person&gt;(p =&gt; p.Name, p =&gt; p.Age)</example> /// <remarks><see cref="ModelValidationResult"/> is stored in NancyModule.ModelValidationResult and NancyContext.ModelValidationResult.</remarks> public static TModel BindToAndValidate<TModel>(this INancyModule module, TModel instance, params Expression<Func<TModel, object>>[] blacklistedProperties) { var model = module.BindTo(instance, blacklistedProperties.ParseBlacklistedPropertiesExpressionTree()); module.Validate(model); return model; } /// <summary> /// Bind the incoming request to an existing instance and validate /// </summary> /// <typeparam name="TModel">Model type</typeparam> /// <param name="module">Current module</param> /// <param name="instance">The class instance to bind properties to</param> /// <remarks><see cref="ModelValidationResult"/> is stored in NancyModule.ModelValidationResult and NancyContext.ModelValidationResult.</remarks> public static TModel BindToAndValidate<TModel>(this INancyModule module, TModel instance) { var model = module.BindTo(instance, NoBlacklistedProperties); module.Validate(model); return model; } /// <summary> /// Bind the incoming request to an existing instance /// </summary> /// <typeparam name="TModel">Model type</typeparam> /// <param name="module">Current module</param> /// <param name="instance">The class instance to bind properties to</param> /// <param name="configuration">The <see cref="BindingConfig"/> that should be applied during binding.</param> /// <param name="blacklistedProperties">Property names to blacklist from binding</param> public static TModel BindTo<TModel>(this INancyModule module, TModel instance, BindingConfig configuration, params string[] blacklistedProperties) { dynamic adapter = new DynamicModelBinderAdapter(module.ModelBinderLocator, module.Context, instance, configuration, blacklistedProperties); return adapter; } /// <summary> /// Bind the incoming request to an existing instance /// </summary> /// <typeparam name="TModel">Model type</typeparam> /// <param name="module">Current module</param> /// <param name="instance">The class instance to bind properties to</param> /// <param name="configuration">The <see cref="BindingConfig"/> that should be applied during binding.</param> /// <param name="blacklistedProperties">Expressions that tell which property should be ignored</param> /// <example>this.Bind&lt;Person&gt;(p =&gt; p.Name, p =&gt; p.Age)</example> public static TModel BindTo<TModel>(this INancyModule module, TModel instance, BindingConfig configuration, params Expression<Func<TModel, object>>[] blacklistedProperties) { return module.BindTo(instance, configuration, blacklistedProperties.ParseBlacklistedPropertiesExpressionTree()); } /// <summary> /// Bind the incoming request to an existing instance /// </summary> /// <typeparam name="TModel">Model type</typeparam> /// <param name="module">Current module</param> /// <param name="instance">The class instance to bind properties to</param> /// <param name="configuration">The <see cref="BindingConfig"/> that should be applied during binding.</param> public static TModel BindTo<TModel>(this INancyModule module, TModel instance, BindingConfig configuration) { return module.BindTo(instance, configuration, NoBlacklistedProperties); } /// <summary> /// Bind the incoming request to an existing instance and validate /// </summary> /// <typeparam name="TModel">Model type</typeparam> /// <param name="module">Current module</param> /// <param name="instance">The class instance to bind properties to</param> /// <param name="configuration">The <see cref="BindingConfig"/> that should be applied during binding.</param> /// <param name="blacklistedProperties">Property names to blacklist from binding</param> /// <remarks><see cref="ModelValidationResult"/> is stored in NancyModule.ModelValidationResult and NancyContext.ModelValidationResult.</remarks> public static TModel BindToAndValidate<TModel>(this INancyModule module, TModel instance, BindingConfig configuration, params string[] blacklistedProperties) { var model = module.BindTo(instance, configuration, blacklistedProperties); module.Validate(model); return model; } /// <summary> /// Bind the incoming request to an existing instance and validate /// </summary> /// <typeparam name="TModel">Model type</typeparam> /// <param name="module">Current module</param> /// <param name="instance">The class instance to bind properties to</param> /// <param name="configuration">The <see cref="BindingConfig"/> that should be applied during binding.</param> /// <param name="blacklistedProperties">Expressions that tell which property should be ignored</param> /// <remarks><see cref="ModelValidationResult"/> is stored in NancyModule.ModelValidationResult and NancyContext.ModelValidationResult.</remarks> /// <example>this.BindToAndValidate(person, config, p =&gt; p.Name, p =&gt; p.Age)</example> public static TModel BindToAndValidate<TModel>(this INancyModule module, TModel instance, BindingConfig configuration, params Expression<Func<TModel, object>>[] blacklistedProperties) { var model = module.BindTo(instance, configuration, blacklistedProperties.ParseBlacklistedPropertiesExpressionTree()); module.Validate(model); return model; } /// <summary> /// Bind the incoming request to an existing instance and validate /// </summary> /// <typeparam name="TModel">Model type</typeparam> /// <param name="module">Current module</param> /// <param name="instance">The class instance to bind properties to</param> /// <param name="configuration">The <see cref="BindingConfig"/> that should be applied during binding.</param> /// <remarks><see cref="ModelValidationResult"/> is stored in NancyModule.ModelValidationResult and NancyContext.ModelValidationResult.</remarks> public static TModel BindToAndValidate<TModel>(this INancyModule module, TModel instance, BindingConfig configuration) { var model = module.BindTo(instance, configuration, NoBlacklistedProperties); module.Validate(model); return model; } } }
// 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.ApplicationInsights.Management { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Azure.Management.ApplicationInsights; 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> /// WebTestsOperations operations. /// </summary> internal partial class WebTestsOperations : IServiceOperations<ApplicationInsightsManagementClient>, IWebTestsOperations { /// <summary> /// Initializes a new instance of the WebTestsOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal WebTestsOperations(ApplicationInsightsManagementClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the ApplicationInsightsManagementClient /// </summary> public ApplicationInsightsManagementClient Client { get; private set; } /// <summary> /// Get all Application Insights web tests defined within a specified 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<WebTest>>> ListByResourceGroupWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // 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("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListByResourceGroup", 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.insights/webtests").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 (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<WebTest>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<WebTest>>(_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> /// Get a specific Application Insights web test definition. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='webTestName'> /// The name of the Application Insights webtest resource. /// </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<WebTest>> GetWithHttpMessagesAsync(string resourceGroupName, string webTestName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (webTestName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "webTestName"); } // 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("webTestName", webTestName); 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.insights/webtests/{webTestName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{webTestName}", System.Uri.EscapeDataString(webTestName)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<WebTest>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<WebTest>(_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 an Application Insights web test definition. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='webTestName'> /// The name of the Application Insights webtest resource. /// </param> /// <param name='webTestDefinition'> /// Properties that need to be specified to create or update an Application /// Insights web test definition. /// </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<WebTest>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string webTestName, WebTest webTestDefinition, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (webTestName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "webTestName"); } if (webTestDefinition == null) { throw new ValidationException(ValidationRules.CannotBeNull, "webTestDefinition"); } if (webTestDefinition != null) { webTestDefinition.Validate(); } // 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("webTestName", webTestName); tracingParameters.Add("webTestDefinition", webTestDefinition); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "CreateOrUpdate", 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.insights/webtests/{webTestName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{webTestName}", System.Uri.EscapeDataString(webTestName)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.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(webTestDefinition != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(webTestDefinition, 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 != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<WebTest>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<WebTest>(_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 an Application Insights web test definition. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='webTestName'> /// The name of the Application Insights webtest resource. /// </param> /// <param name='tags'> /// Resource tags /// </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<WebTest>> UpdateTagsWithHttpMessagesAsync(string resourceGroupName, string webTestName, IDictionary<string, string> tags = default(IDictionary<string, string>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (webTestName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "webTestName"); } TagsResource webTestTags = new TagsResource(); if (tags != null) { webTestTags.Tags = tags; } // 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("webTestName", webTestName); tracingParameters.Add("webTestTags", webTestTags); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "UpdateTags", 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.insights/webtests/{webTestName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{webTestName}", System.Uri.EscapeDataString(webTestName)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.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("PATCH"); _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(webTestTags != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(webTestTags, 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 != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<WebTest>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<WebTest>(_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 an Application Insights web test. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='webTestName'> /// The name of the Application Insights webtest resource. /// </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> DeleteWithHttpMessagesAsync(string resourceGroupName, string webTestName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (webTestName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "webTestName"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // 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("webTestName", webTestName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Delete", 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.insights/webtests/{webTestName}").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{webTestName}", System.Uri.EscapeDataString(webTestName)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.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 != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _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> /// Get all Application Insights web test alerts definitioned within 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<WebTest>>> ListWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); 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}/providers/microsoft.insights/webtests").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<WebTest>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<WebTest>>(_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> /// Get all Application Insights web tests defined within a specified 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<WebTest>>> ListByResourceGroupNextWithHttpMessagesAsync(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, "ListByResourceGroupNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<WebTest>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<WebTest>>(_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> /// Get all Application Insights web test alerts definitioned within 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<WebTest>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<WebTest>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<WebTest>>(_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; } } }
using EngineLayer; using MzLibUtil; using Nett; using Newtonsoft.Json.Linq; using Proteomics; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Input; using TaskLayer; namespace MetaMorpheusGUI { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { private readonly ObservableCollection<RawDataForDataGrid> SpectraFilesObservableCollection = new ObservableCollection<RawDataForDataGrid>(); private readonly ObservableCollection<ProteinDbForDataGrid> ProteinDbObservableCollection = new ObservableCollection<ProteinDbForDataGrid>(); private readonly ObservableCollection<PreRunTask> StaticTasksObservableCollection = new ObservableCollection<PreRunTask>(); private readonly ObservableCollection<RawDataForDataGrid> SelectedRawFiles = new ObservableCollection<RawDataForDataGrid>(); private ObservableCollection<InRunTask> DynamicTasksObservableCollection; public MainWindow() { InitializeComponent(); Title = "MetaMorpheus: version " + GlobalVariables.MetaMorpheusVersion; dataGridProteinDatabases.DataContext = ProteinDbObservableCollection; dataGridSpectraFiles.DataContext = SpectraFilesObservableCollection; tasksTreeView.DataContext = StaticTasksObservableCollection; EverythingRunnerEngine.NewDbsHandler += AddNewDB; EverythingRunnerEngine.NewSpectrasHandler += AddNewSpectra; EverythingRunnerEngine.NewFileSpecificTomlHandler += AddNewFileSpecificToml; EverythingRunnerEngine.StartingAllTasksEngineHandler += NewSuccessfullyStartingAllTasks; EverythingRunnerEngine.FinishedAllTasksEngineHandler += NewSuccessfullyFinishedAllTasks; EverythingRunnerEngine.WarnHandler += GuiWarnHandler; EverythingRunnerEngine.FinishedWritingAllResultsFileHandler += EverythingRunnerEngine_FinishedWritingAllResultsFileHandler; MetaMorpheusTask.StartingSingleTaskHander += Po_startingSingleTaskHander; MetaMorpheusTask.FinishedSingleTaskHandler += Po_finishedSingleTaskHandler; MetaMorpheusTask.FinishedWritingFileHandler += NewSuccessfullyFinishedWritingFile; MetaMorpheusTask.StartingDataFileHandler += MyTaskEngine_StartingDataFileHandler; MetaMorpheusTask.FinishedDataFileHandler += MyTaskEngine_FinishedDataFileHandler; MetaMorpheusTask.OutLabelStatusHandler += NewoutLabelStatus; MetaMorpheusTask.NewCollectionHandler += NewCollectionHandler; MetaMorpheusTask.OutProgressHandler += NewoutProgressBar; MetaMorpheusTask.WarnHandler += GuiWarnHandler; MetaMorpheusEngine.OutProgressHandler += NewoutProgressBar; MetaMorpheusEngine.OutLabelStatusHandler += NewoutLabelStatus; MetaMorpheusEngine.WarnHandler += GuiWarnHandler; MyFileManager.WarnHandler += GuiWarnHandler; UpdateSpectraFileGuiStuff(); UpdateTaskGuiStuff(); UpdateOutputFolderTextbox(); FileSpecificParameters.ValidateFileSpecificVariableNames(); SearchModifications.SetUpModSearchBoxes(); // LOAD GUI SETTINGS if (File.Exists(Path.Combine(GlobalVariables.DataDir, @"GUIsettings.toml"))) { GuiGlobalParams = Toml.ReadFile<GuiGlobalParams>(Path.Combine(GlobalVariables.DataDir, @"GUIsettings.toml")); } else { Toml.WriteFile(GuiGlobalParams, Path.Combine(GlobalVariables.DataDir, @"GUIsettings.toml"), MetaMorpheusTask.tomlConfig); notificationsTextBox.Document = YoutubeWikiNotification(); } if (GlobalVariables.MetaMorpheusVersion.Contains("Not a release version")) { GuiGlobalParams.AskAboutUpdating = false; } try { GetVersionNumbersFromWeb(); } catch (Exception e) { GuiWarnHandler(null, new StringEventArgs("Could not get newest version from web: " + e.Message, null)); } Application.Current.MainWindow.Closing += new CancelEventHandler(MainWindow_Closing); } private FlowDocument YoutubeWikiNotification() { FlowDocument doc = notificationsTextBox.Document; Paragraph p = new Paragraph(); Run run1 = new Run("Visit our "); Run run2 = new Run("Wiki"); Run run3 = new Run(" or "); Run run4 = new Run("Youtube channel"); Run run5 = new Run(" to check out what MetaMorpheus can do!" + System.Environment.NewLine); Hyperlink wikiLink = new Hyperlink(run2); wikiLink.NavigateUri = new Uri(@"https://github.com/smith-chem-wisc/MetaMorpheus/wiki"); Hyperlink youtubeLink = new Hyperlink(run4); youtubeLink.NavigateUri = new Uri(@"https://www.youtube.com/playlist?list=PLVk5tTSZ1aWlhNPh7jxPQ8pc0ElyzSUQb"); var links = new List<Hyperlink> { wikiLink, youtubeLink }; p.Inlines.Add(run1); p.Inlines.Add(wikiLink); p.Inlines.Add(run3); p.Inlines.Add(youtubeLink); p.Inlines.Add(run5); foreach (Hyperlink link in links) { link.RequestNavigate += (sender, e) => { System.Diagnostics.Process.Start(e.Uri.ToString()); }; } doc.Blocks.Add(p); return doc; } public static string NewestKnownVersion { get; private set; } internal GuiGlobalParams GuiGlobalParams = new GuiGlobalParams(); private static void GetVersionNumbersFromWeb() { // Attempt to get current MetaMorpheus version using (var client = new HttpClient()) { client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)"); using (var response = client.GetAsync("https://api.github.com/repos/smith-chem-wisc/MetaMorpheus/releases/latest").Result) { var json = response.Content.ReadAsStringAsync().Result; JObject deserialized = JObject.Parse(json); var assets = deserialized["assets"].Select(b => b["name"].ToString()).ToList(); if (!assets.Contains("MetaMorpheusInstaller.msi")) { throw new MetaMorpheusException("A new version of MetaMorpheus was detected, but the files haven't been" + " uploaded yet. Try again in a few minutes."); } NewestKnownVersion = deserialized["tag_name"].ToString(); } } } private void MyWindow_Loaded(object sender, RoutedEventArgs e) { if (NewestKnownVersion != null && !GlobalVariables.MetaMorpheusVersion.Equals(NewestKnownVersion) && GuiGlobalParams.AskAboutUpdating) { try { MetaUpdater newwind = new MetaUpdater(); newwind.ShowDialog(); } catch (Exception ex) { MessageBox.Show(ex.ToString()); } } this.KeyDown += new KeyEventHandler(Window_KeyDown); // hide the "InProgress" column dataGridProteinDatabases.Columns.Where(p => p.Header.Equals(nameof(ProteinDbForDataGrid.InProgress))).First().Visibility = Visibility.Hidden; dataGridSpectraFiles.Columns.Where(p => p.Header.Equals(nameof(RawDataForDataGrid.InProgress))).First().Visibility = Visibility.Hidden; PrintErrorsReadingMods(); } private void EverythingRunnerEngine_FinishedWritingAllResultsFileHandler(object sender, StringEventArgs e) { if (!Dispatcher.CheckAccess()) { Dispatcher.BeginInvoke(new Action(() => EverythingRunnerEngine_FinishedWritingAllResultsFileHandler(sender, e))); } else { DynamicTasksObservableCollection.Add(new InRunTask("All Task Results", null)); DynamicTasksObservableCollection.Last().Progress = 100; DynamicTasksObservableCollection.Last().Children.Add(new OutputFileForTreeView(e.S, Path.GetFileNameWithoutExtension(e.S))); } } private void GuiWarnHandler(object sender, StringEventArgs e) { if (!Dispatcher.CheckAccess()) { Dispatcher.BeginInvoke(new Action(() => GuiWarnHandler(sender, e))); } else { notificationsTextBox.AppendText(e.S); notificationsTextBox.AppendText(Environment.NewLine); } } private void MyTaskEngine_FinishedDataFileHandler(object sender, StringEventArgs s) { if (!Dispatcher.CheckAccess()) { Dispatcher.BeginInvoke(new Action(() => MyTaskEngine_FinishedDataFileHandler(sender, s))); } else { var huh = SpectraFilesObservableCollection.First(b => b.FilePath.Equals(s.S)); huh.SetInProgress(false); dataGridSpectraFiles.Items.Refresh(); } } private void MyTaskEngine_StartingDataFileHandler(object sender, StringEventArgs s) { if (!Dispatcher.CheckAccess()) { Dispatcher.BeginInvoke(new Action(() => MyTaskEngine_StartingDataFileHandler(sender, s))); } else { var huh = SpectraFilesObservableCollection.First(b => b.FilePath.Equals(s.S)); huh.SetInProgress(true); dataGridSpectraFiles.Items.Refresh(); } } private void AddNewDB(object sender, XmlForTaskListEventArgs e) { if (!Dispatcher.CheckAccess()) { Dispatcher.BeginInvoke(new Action(() => AddNewDB(sender, e))); } else { foreach (var uu in ProteinDbObservableCollection) { uu.Use = false; } foreach (var uu in e.NewDatabases) { ProteinDbObservableCollection.Add(new ProteinDbForDataGrid(uu)); } dataGridProteinDatabases.Items.Refresh(); } } private void AddNewSpectra(object sender, StringListEventArgs e) { if (!Dispatcher.CheckAccess()) { Dispatcher.BeginInvoke(new Action(() => AddNewSpectra(sender, e))); } else { var newFiles = e.StringList.ToList(); foreach (var oldFile in SpectraFilesObservableCollection) { if (!newFiles.Contains(oldFile.FilePath)) { oldFile.Use = false; } } var files = SpectraFilesObservableCollection.Select(p => p.FilePath).ToList(); foreach (var newRawData in newFiles.Where(p => !files.Contains(p))) { SpectraFilesObservableCollection.Add(new RawDataForDataGrid(newRawData)); } UpdateOutputFolderTextbox(); } } private void AddNewFileSpecificToml(object sender, StringListEventArgs e) { if (!Dispatcher.CheckAccess()) { Dispatcher.BeginInvoke(new Action(() => AddNewFileSpecificToml(sender, e))); } else { foreach (var path in e.StringList) { UpdateFileSpecificParamsDisplayJustAdded(path); } } } private void UpdateOutputFolderTextbox() { if (SpectraFilesObservableCollection.Any()) { // if current output folder is blank and there is a spectra file, use the spectra file's path as the output path if (string.IsNullOrWhiteSpace(OutputFolderTextBox.Text)) { var pathOfFirstSpectraFile = Path.GetDirectoryName(SpectraFilesObservableCollection.First().FilePath); OutputFolderTextBox.Text = Path.Combine(pathOfFirstSpectraFile, @"$DATETIME"); } // else do nothing (do not override if there is a path already there; might clear user-defined path) } else { // no spectra files; clear the output folder from the GUI OutputFolderTextBox.Clear(); } } private void Po_startingSingleTaskHander(object sender, SingleTaskEventArgs s) { if (!Dispatcher.CheckAccess()) { Dispatcher.BeginInvoke(new Action(() => Po_startingSingleTaskHander(sender, s))); } else { var theTask = DynamicTasksObservableCollection.First(b => b.DisplayName.Equals(s.DisplayName)); theTask.Status = "Starting..."; dataGridSpectraFiles.Items.Refresh(); dataGridProteinDatabases.Items.Refresh(); } } private void Po_finishedSingleTaskHandler(object sender, SingleTaskEventArgs s) { if (!Dispatcher.CheckAccess()) { Dispatcher.BeginInvoke(new Action(() => Po_finishedSingleTaskHandler(sender, s))); } else { var theTask = DynamicTasksObservableCollection.First(b => b.DisplayName.Equals(s.DisplayName)); theTask.IsIndeterminate = false; theTask.Progress = 100; theTask.Status = "Done!"; dataGridSpectraFiles.Items.Refresh(); dataGridProteinDatabases.Items.Refresh(); } } private void ClearSpectraFiles_Click(object sender, RoutedEventArgs e) { SpectraFilesObservableCollection.Clear(); UpdateOutputFolderTextbox(); } private void OpenOutputFolder_Click(object sender, RoutedEventArgs e) { string outputFolder = OutputFolderTextBox.Text; if (outputFolder.Contains("$DATETIME")) { // the exact file path isn't known, so just open the parent directory outputFolder = Directory.GetParent(outputFolder).FullName; } if (!Directory.Exists(outputFolder) && !string.IsNullOrEmpty(outputFolder)) { // create the directory if it doesn't exist yet try { Directory.CreateDirectory(outputFolder); } catch (Exception ex) { GuiWarnHandler(null, new StringEventArgs("Error opening directory: " + ex.Message, null)); } } if (Directory.Exists(outputFolder)) { // open the directory System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo() { FileName = outputFolder, UseShellExecute = true, Verb = "open" }); } else { // this should only happen if the file path is empty or something unexpected happened GuiWarnHandler(null, new StringEventArgs("Output folder does not exist", null)); } } private void AddProteinDatabase_Click(object sender, RoutedEventArgs e) { Microsoft.Win32.OpenFileDialog openPicker = new Microsoft.Win32.OpenFileDialog() { Filter = "Database Files|*.xml;*.xml.gz;*.fasta;*.fa", FilterIndex = 1, RestoreDirectory = true, Multiselect = true }; if (openPicker.ShowDialog() == true) { foreach (var filepath in openPicker.FileNames.OrderBy(p => p)) { AddAFile(filepath); } } dataGridProteinDatabases.Items.Refresh(); } private void AddSpectraFile_Click(object sender, RoutedEventArgs e) { Microsoft.Win32.OpenFileDialog openFileDialog1 = new Microsoft.Win32.OpenFileDialog { Filter = "Spectra Files(*.raw;*.mzML;*.mgf)|*.raw;*.mzML;*.mgf", FilterIndex = 1, RestoreDirectory = true, Multiselect = true }; if (openFileDialog1.ShowDialog() == true) { foreach (var rawDataFromSelected in openFileDialog1.FileNames.OrderBy(p => p)) { AddAFile(rawDataFromSelected); } } dataGridSpectraFiles.Items.Refresh(); } private void Window_Drop(object sender, DragEventArgs e) { if (LoadTaskButton.IsEnabled) { string[] files = ((string[])e.Data.GetData(DataFormats.FileDrop)).OrderBy(p => p).ToArray(); if (files != null) { foreach (var draggedFilePath in files) { if (Directory.Exists(draggedFilePath)) { foreach (string file in Directory.EnumerateFiles(draggedFilePath, "*.*", SearchOption.AllDirectories)) { AddAFile(file); } } else { AddAFile(draggedFilePath); } dataGridSpectraFiles.CommitEdit(DataGridEditingUnit.Row, true); dataGridProteinDatabases.CommitEdit(DataGridEditingUnit.Row, true); dataGridSpectraFiles.Items.Refresh(); dataGridProteinDatabases.Items.Refresh(); } } UpdateTaskGuiStuff(); } } private void AddAFile(string draggedFilePath) { // this line is NOT used because .xml.gz (extensions with two dots) mess up with Path.GetExtension //var theExtension = Path.GetExtension(draggedFilePath).ToLowerInvariant(); // we need to get the filename before parsing out the extension because if we assume that everything after the dot // is the extension and there are dots in the file path (i.e. in a folder name), this will mess up var filename = Path.GetFileName(draggedFilePath); var theExtension = Path.GetExtension(filename).ToLowerInvariant(); bool compressed = theExtension.EndsWith("gz"); // allows for .bgz and .tgz, too which are used on occasion theExtension = compressed ? Path.GetExtension(Path.GetFileNameWithoutExtension(filename)).ToLowerInvariant() : theExtension; switch (theExtension) { case ".raw": if (!GlobalVariables.GlobalSettings.UserHasAgreedToThermoRawFileReaderLicence) { // open the Thermo RawFileReader licence agreement var thermoLicenceWindow = new ThermoLicenceAgreementWindow(); thermoLicenceWindow.LicenceText.AppendText(ThermoRawFileReader.ThermoRawFileReaderLicence.ThermoLicenceText); var dialogResult = thermoLicenceWindow.ShowDialog(); var newGlobalSettings = new GlobalSettings { UserHasAgreedToThermoRawFileReaderLicence = dialogResult.Value, WriteExcelCompatibleTSVs = GlobalVariables.GlobalSettings.WriteExcelCompatibleTSVs }; Toml.WriteFile<GlobalSettings>(newGlobalSettings, Path.Combine(GlobalVariables.DataDir, @"settings.toml")); GlobalVariables.GlobalSettings = newGlobalSettings; // user declined agreement if (!GlobalVariables.GlobalSettings.UserHasAgreedToThermoRawFileReaderLicence) { return; } } goto case ".mzml"; case ".mgf": GuiWarnHandler(null, new StringEventArgs(".mgf files lack MS1 spectra, which are needed for quantification and searching for coisolated peptides. All other features of MetaMorpheus will function.", null)); goto case ".mzml"; case ".mzml": if (compressed) // not implemented yet { GuiWarnHandler(null, new StringEventArgs("Cannot read, try uncompressing: " + draggedFilePath, null)); break; } RawDataForDataGrid zz = new RawDataForDataGrid(draggedFilePath); if (!SpectraFileExists(SpectraFilesObservableCollection, zz)) { SpectraFilesObservableCollection.Add(zz); } UpdateFileSpecificParamsDisplayJustAdded(Path.ChangeExtension(draggedFilePath, ".toml")); UpdateOutputFolderTextbox(); break; case ".xml": case ".fasta": case ".fa": ProteinDbForDataGrid uu = new ProteinDbForDataGrid(draggedFilePath); if (!DatabaseExists(ProteinDbObservableCollection, uu)) { ProteinDbObservableCollection.Add(uu); if (theExtension.Equals(".xml")) { try { GlobalVariables.AddMods(UsefulProteomicsDatabases.ProteinDbLoader.GetPtmListFromProteinXml(draggedFilePath).OfType<Modification>(), true); PrintErrorsReadingMods(); } catch (Exception ee) { MessageBox.Show(ee.ToString()); GuiWarnHandler(null, new StringEventArgs("Cannot parse modification info from: " + draggedFilePath, null)); ProteinDbObservableCollection.Remove(uu); } } } break; case ".toml": TomlTable tomlFile = null; try { tomlFile = Toml.ReadFile(draggedFilePath, MetaMorpheusTask.tomlConfig); } catch (Exception) { GuiWarnHandler(null, new StringEventArgs("Cannot read toml: " + draggedFilePath, null)); break; } if (tomlFile.ContainsKey("TaskType")) { try { switch (tomlFile.Get<string>("TaskType")) { case "Search": var ye1 = Toml.ReadFile<SearchTask>(draggedFilePath, MetaMorpheusTask.tomlConfig); AddTaskToCollection(ye1); break; case "Calibrate": var ye2 = Toml.ReadFile<CalibrationTask>(draggedFilePath, MetaMorpheusTask.tomlConfig); AddTaskToCollection(ye2); break; case "Gptmd": var ye3 = Toml.ReadFile<GptmdTask>(draggedFilePath, MetaMorpheusTask.tomlConfig); AddTaskToCollection(ye3); break; case "XLSearch": var ye4 = Toml.ReadFile<XLSearchTask>(draggedFilePath, MetaMorpheusTask.tomlConfig); AddTaskToCollection(ye4); break; } } catch (Exception e) { GuiWarnHandler(null, new StringEventArgs("Cannot read task toml: " + e.Message, null)); } } break; default: GuiWarnHandler(null, new StringEventArgs("Unrecognized file type: " + theExtension, null)); break; } } private void AddTaskToCollection(MetaMorpheusTask ye) { PreRunTask te = new PreRunTask(ye); StaticTasksObservableCollection.Add(te); StaticTasksObservableCollection.Last().DisplayName = "Task" + (StaticTasksObservableCollection.IndexOf(te) + 1) + "-" + ye.CommonParameters.TaskDescriptor; } // handles double-clicking on a data grid row private void Row_DoubleClick(object sender, MouseButtonEventArgs e) { var ye = sender as DataGridCell; // prevent opening protein DB or spectra files if a run is in progress if ((ye.DataContext is ProteinDbForDataGrid || ye.DataContext is RawDataForDataGrid) && !LoadTaskButton.IsEnabled) { return; } // open the file with the default process for this file format if (ye.Content is TextBlock hm && hm != null && !string.IsNullOrEmpty(hm.Text)) { try { System.Diagnostics.Process.Start(hm.Text); } catch (Exception) { } } } private void RunAllTasks_Click(object sender, RoutedEventArgs e) { GlobalVariables.StopLoops = false; CancelButton.IsEnabled = true; // check for valid tasks/spectra files/protein databases if (!StaticTasksObservableCollection.Any()) { GuiWarnHandler(null, new StringEventArgs("You need to add at least one task!", null)); return; } if (!SpectraFilesObservableCollection.Any()) { GuiWarnHandler(null, new StringEventArgs("You need to add at least one spectra file!", null)); return; } if (!ProteinDbObservableCollection.Any()) { GuiWarnHandler(null, new StringEventArgs("You need to add at least one protein database!", null)); return; } DynamicTasksObservableCollection = new ObservableCollection<InRunTask>(); for (int i = 0; i < StaticTasksObservableCollection.Count; i++) { DynamicTasksObservableCollection.Add(new InRunTask("Task" + (i + 1) + "-" + StaticTasksObservableCollection[i].metaMorpheusTask.CommonParameters.TaskDescriptor, StaticTasksObservableCollection[i].metaMorpheusTask)); } tasksTreeView.DataContext = DynamicTasksObservableCollection; notificationsTextBox.Document.Blocks.Clear(); // output folder if (string.IsNullOrEmpty(OutputFolderTextBox.Text)) { var pathOfFirstSpectraFile = Path.GetDirectoryName(SpectraFilesObservableCollection.First().FilePath); OutputFolderTextBox.Text = Path.Combine(pathOfFirstSpectraFile, @"$DATETIME"); } var startTimeForAllFilenames = DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss", CultureInfo.InvariantCulture); string outputFolder = OutputFolderTextBox.Text.Replace("$DATETIME", startTimeForAllFilenames); OutputFolderTextBox.Text = outputFolder; // check that experimental design is defined if normalization is enabled // TODO: move all of this over to EverythingRunnerEngine var searchTasks = StaticTasksObservableCollection .Where(p => p.metaMorpheusTask.TaskType == MyTask.Search) .Select(p => (SearchTask)p.metaMorpheusTask); string pathToExperDesign = Directory.GetParent(SpectraFilesObservableCollection.First().FilePath).FullName; pathToExperDesign = Path.Combine(pathToExperDesign, GlobalVariables.ExperimentalDesignFileName); foreach (var searchTask in searchTasks.Where(p => p.SearchParameters.Normalize)) { if (!File.Exists(pathToExperDesign)) { MessageBox.Show("Experimental design must be defined for normalization!\n" + "Click the \"Experimental Design\" button in the bottom left by the spectra files"); return; } // check that experimental design is OK (spectra files may have been added after exper design was defined) // TODO: experimental design might still have flaws if user edited the file manually, need to check for this var experDesign = File.ReadAllLines(pathToExperDesign).ToDictionary(p => p.Split('\t')[0], p => p); var filesToUse = new HashSet<string>(SpectraFilesObservableCollection.Select(p => Path.GetFileNameWithoutExtension(p.FileName))); var experDesignFilesDefined = new HashSet<string>(experDesign.Keys); var undefined = filesToUse.Except(experDesignFilesDefined); if (undefined.Any()) { MessageBox.Show("Need to define experimental design parameters for file: " + undefined.First()); return; } } BtnQuantSet.IsEnabled = false; // everything is OK to run EverythingRunnerEngine a = new EverythingRunnerEngine(DynamicTasksObservableCollection.Select(b => (b.DisplayName, b.Task)).ToList(), SpectraFilesObservableCollection.Where(b => b.Use).Select(b => b.FilePath).ToList(), ProteinDbObservableCollection.Where(b => b.Use).Select(b => new DbForTask(b.FilePath, b.Contaminant)).ToList(), outputFolder); var t = new Task(a.Run); t.ContinueWith(EverythingRunnerExceptionHandler, TaskContinuationOptions.OnlyOnFaulted); t.Start(); } private void EverythingRunnerExceptionHandler(Task obj) { if (!Dispatcher.CheckAccess()) { Dispatcher.BeginInvoke(new Action(() => EverythingRunnerExceptionHandler(obj))); } else { Exception e = obj.Exception; while (e.InnerException != null) { e = e.InnerException; } var message = "Run failed, Exception: " + e.Message; var messageBoxResult = System.Windows.MessageBox.Show(message + "\n\nWould you like to report this crash?", "Runtime Error", MessageBoxButton.YesNo); notificationsTextBox.AppendText(message + Environment.NewLine); Exception exception = e; //Find Output Folder string outputFolder = e.Data["folder"].ToString(); string tomlText = ""; if (Directory.Exists(outputFolder)) { var tomls = Directory.GetFiles(outputFolder, "*.toml"); //will only be 1 toml per task foreach (var tomlFile in tomls) { tomlText += "\n" + File.ReadAllText(tomlFile); } if (!tomls.Any()) { tomlText = "TOML not found"; } } else { tomlText = "Directory not found"; } if (messageBoxResult == MessageBoxResult.Yes) { string body = exception.Message + "%0D%0A" + exception.Data + "%0D%0A" + exception.StackTrace + "%0D%0A" + exception.Source + "%0D%0A %0D%0A %0D%0A %0D%0A SYSTEM INFO: %0D%0A " + SystemInfo.CompleteSystemInfo() + "%0D%0A%0D%0A MetaMorpheus: version " + GlobalVariables.MetaMorpheusVersion + "%0D%0A %0D%0A %0D%0A %0D%0A TOML: %0D%0A " + tomlText; body = body.Replace('&', ' '); body = body.Replace("\n", "%0D%0A"); body = body.Replace("\r", "%0D%0A"); string mailto = string.Format("mailto:{0}?Subject=MetaMorpheus. Issue:&Body={1}", "mm_support@chem.wisc.edu", body); System.Diagnostics.Process.Start(mailto); Console.WriteLine(body); } ResetTasksButton.IsEnabled = true; } } private void ClearTasks_Click(object sender, RoutedEventArgs e) { StaticTasksObservableCollection.Clear(); UpdateTaskGuiStuff(); } private void UpdateTaskGuiStuff() { if (StaticTasksObservableCollection.Count == 0) { RunTasksButton.IsEnabled = false; DeleteSelectedTaskButton.IsEnabled = false; ClearTasksButton.IsEnabled = false; ResetTasksButton.IsEnabled = false; } else { RunTasksButton.IsEnabled = true; DeleteSelectedTaskButton.IsEnabled = true; ClearTasksButton.IsEnabled = true; // this exists so that when a task is deleted, the remaining tasks are renamed to keep the task numbers correct for (int i = 0; i < StaticTasksObservableCollection.Count; i++) { string newName = "Task" + (i + 1) + "-" + StaticTasksObservableCollection[i].metaMorpheusTask.CommonParameters.TaskDescriptor; StaticTasksObservableCollection[i].DisplayName = newName; } tasksTreeView.Items.Refresh(); } } private void UpdateSpectraFileGuiStuff() { ChangeFileParameters.IsEnabled = SelectedRawFiles.Count > 0 && LoadTaskButton.IsEnabled; } private void AddSearchTaskButton_Click(object sender, RoutedEventArgs e) { var dialog = new SearchTaskWindow(); if (dialog.ShowDialog() == true) { AddTaskToCollection(dialog.TheTask); UpdateTaskGuiStuff(); } } private void AddCalibrateTaskButton_Click(object sender, RoutedEventArgs e) { var dialog = new CalibrateTaskWindow(); if (dialog.ShowDialog() == true) { AddTaskToCollection(dialog.TheTask); UpdateTaskGuiStuff(); } } private void AddGPTMDTaskButton_Click(object sender, RoutedEventArgs e) { var dialog = new GptmdTaskWindow(); if (dialog.ShowDialog() == true) { AddTaskToCollection(dialog.TheTask); UpdateTaskGuiStuff(); } } private void BtnAddCrosslinkSearch_Click(object sender, RoutedEventArgs e) { var dialog = new XLSearchTaskWindow(); if (dialog.ShowDialog() == true) { AddTaskToCollection(dialog.TheTask); UpdateTaskGuiStuff(); } } // deletes the selected task private void DeleteSelectedTask(object sender, RoutedEventArgs e) { var selectedTask = (PreRunTask)tasksTreeView.SelectedItem; if (selectedTask != null) { StaticTasksObservableCollection.Remove(selectedTask); UpdateTaskGuiStuff(); } } // move the task up or down in the GUI private void MoveSelectedTask(object sender, RoutedEventArgs e, bool moveTaskUp) { var selectedTask = (PreRunTask)tasksTreeView.SelectedItem; if (selectedTask == null) { return; } int indexOfSelected = StaticTasksObservableCollection.IndexOf(selectedTask); int indexToMoveTo = indexOfSelected - 1; if (moveTaskUp) { indexToMoveTo = indexOfSelected + 1; } if (indexToMoveTo >= 0 && indexToMoveTo < StaticTasksObservableCollection.Count) { var temp = StaticTasksObservableCollection[indexToMoveTo]; StaticTasksObservableCollection[indexToMoveTo] = selectedTask; StaticTasksObservableCollection[indexOfSelected] = temp; UpdateTaskGuiStuff(); var item = tasksTreeView.ItemContainerGenerator.ContainerFromItem(selectedTask); ((TreeViewItem)item).IsSelected = true; } } // handles keyboard input in the main window private void Window_KeyDown(object sender, KeyEventArgs e) { if (LoadTaskButton.IsEnabled) { // delete selected task if (e.Key == Key.Delete || e.Key == Key.Back) { DeleteSelectedTask(sender, e); e.Handled = true; } // move task up if (e.Key == Key.Add || e.Key == Key.OemPlus) { MoveSelectedTask(sender, e, true); e.Handled = true; } // move task down if (e.Key == Key.Subtract || e.Key == Key.OemMinus) { MoveSelectedTask(sender, e, false); e.Handled = true; } } } private void NewCollectionHandler(object sender, StringEventArgs s) { if (!Dispatcher.CheckAccess()) { Dispatcher.BeginInvoke(new Action(() => NewCollectionHandler(sender, s))); } else { // Find the task or the collection!!! ForTreeView theEntityOnWhichToUpdateLabel = DynamicTasksObservableCollection.First(b => b.Id.Equals(s.NestedIDs[0])); for (int i = 1; i < s.NestedIDs.Count - 1; i++) { var hm = s.NestedIDs[i]; try { theEntityOnWhichToUpdateLabel = theEntityOnWhichToUpdateLabel.Children.First(b => b.Id.Equals(hm)); } catch { theEntityOnWhichToUpdateLabel.Children.Add(new CollectionForTreeView(hm, hm)); theEntityOnWhichToUpdateLabel = theEntityOnWhichToUpdateLabel.Children.First(b => b.Id.Equals(hm)); } } theEntityOnWhichToUpdateLabel.Children.Add(new CollectionForTreeView(s.S, s.NestedIDs.Last())); } } private void NewoutLabelStatus(object sender, StringEventArgs s) { if (!Dispatcher.CheckAccess()) { Dispatcher.BeginInvoke(new Action(() => NewoutLabelStatus(sender, s))); } else { // Find the task or the collection!!! ForTreeView theEntityOnWhichToUpdateLabel = DynamicTasksObservableCollection.First(b => b.Id.Equals(s.NestedIDs[0])); foreach (var hm in s.NestedIDs.Skip(1)) { try { theEntityOnWhichToUpdateLabel = theEntityOnWhichToUpdateLabel.Children.First(b => b.Id.Equals(hm)); } catch { theEntityOnWhichToUpdateLabel.Children.Add(new CollectionForTreeView(hm, hm)); theEntityOnWhichToUpdateLabel = theEntityOnWhichToUpdateLabel.Children.First(b => b.Id.Equals(hm)); } } theEntityOnWhichToUpdateLabel.Status = s.S; theEntityOnWhichToUpdateLabel.IsIndeterminate = true; } } // update progress bar for task/file private void NewoutProgressBar(object sender, ProgressEventArgs s) { if (!Dispatcher.CheckAccess()) { Dispatcher.BeginInvoke(new Action(() => NewoutProgressBar(sender, s))); } else { ForTreeView theEntityOnWhichToUpdateLabel = DynamicTasksObservableCollection.First(b => b.Id.Equals(s.NestedIDs[0])); foreach (var hm in s.NestedIDs.Skip(1)) { try { theEntityOnWhichToUpdateLabel = theEntityOnWhichToUpdateLabel.Children.First(b => b.Id.Equals(hm)); } catch { theEntityOnWhichToUpdateLabel.Children.Add(new CollectionForTreeView(hm, hm)); theEntityOnWhichToUpdateLabel = theEntityOnWhichToUpdateLabel.Children.First(b => b.Id.Equals(hm)); } } theEntityOnWhichToUpdateLabel.Status = s.V; theEntityOnWhichToUpdateLabel.IsIndeterminate = false; theEntityOnWhichToUpdateLabel.Progress = s.NewProgress; } } private void NewRefreshBetweenTasks(object sender, EventArgs e) { if (!Dispatcher.CheckAccess()) { Dispatcher.BeginInvoke(new Action(() => NewRefreshBetweenTasks(sender, e))); } else { dataGridSpectraFiles.Items.Refresh(); dataGridProteinDatabases.Items.Refresh(); } } private void NewSuccessfullyStartingAllTasks(object sender, EventArgs e) { if (!Dispatcher.CheckAccess()) { Dispatcher.BeginInvoke(new Action(() => NewSuccessfullyStartingAllTasks(sender, e))); } else { dataGridSpectraFiles.Items.Refresh(); ClearTasksButton.IsEnabled = false; DeleteSelectedTaskButton.IsEnabled = false; RunTasksButton.IsEnabled = false; LoadTaskButton.IsEnabled = false; addCalibrateTaskButton.IsEnabled = false; addGPTMDTaskButton.IsEnabled = false; addSearchTaskButton.IsEnabled = false; btnAddCrosslinkSearch.IsEnabled = false; AddXML.IsEnabled = false; ClearXML.IsEnabled = false; AddContaminantXML.IsEnabled = false; AddRaw.IsEnabled = false; ClearRaw.IsEnabled = false; OutputFolderTextBox.IsEnabled = false; dataGridSpectraFiles.IsReadOnly = true; dataGridProteinDatabases.IsReadOnly = true; } } private void NewSuccessfullyFinishedAllTasks(object sender, StringEventArgs e) { if (!Dispatcher.CheckAccess()) { Dispatcher.BeginInvoke(new Action(() => NewSuccessfullyFinishedAllTasks(sender, e))); } else { ResetTasksButton.IsEnabled = true; dataGridSpectraFiles.Items.Refresh(); } } private void NewSuccessfullyFinishedWritingFile(object sender, SingleFileEventArgs v) { if (!Dispatcher.CheckAccess()) { Dispatcher.BeginInvoke(new Action(() => NewSuccessfullyFinishedWritingFile(sender, v))); } else { ForTreeView AddWrittenFileToThisOne = DynamicTasksObservableCollection.First(b => b.Id.Equals(v.NestedIDs[0])); foreach (var hm in v.NestedIDs.Skip(1)) { try { AddWrittenFileToThisOne = AddWrittenFileToThisOne.Children.First(b => b.Id.Equals(hm)); } catch { } } AddWrittenFileToThisOne.Children.Add(new OutputFileForTreeView(v.WrittenFile, Path.GetFileName(v.WrittenFile))); } } private void ClearXML_Click(object sender, RoutedEventArgs e) { ProteinDbObservableCollection.Clear(); } private void ResetTasksButton_Click(object sender, RoutedEventArgs e) { tasksGroupBox.IsEnabled = true; ClearTasksButton.IsEnabled = true; DeleteSelectedTaskButton.IsEnabled = true; RunTasksButton.IsEnabled = true; addCalibrateTaskButton.IsEnabled = true; addGPTMDTaskButton.IsEnabled = true; addSearchTaskButton.IsEnabled = true; btnAddCrosslinkSearch.IsEnabled = true; ResetTasksButton.IsEnabled = false; OutputFolderTextBox.IsEnabled = true; dataGridSpectraFiles.IsReadOnly = false; dataGridProteinDatabases.IsReadOnly = false; AddXML.IsEnabled = true; ClearXML.IsEnabled = true; AddContaminantXML.IsEnabled = true; AddRaw.IsEnabled = true; ClearRaw.IsEnabled = true; BtnQuantSet.IsEnabled = true; LoadTaskButton.IsEnabled = true; tasksTreeView.DataContext = StaticTasksObservableCollection; UpdateSpectraFileGuiStuff(); var pathOfFirstSpectraFile = Path.GetDirectoryName(SpectraFilesObservableCollection.First().FilePath); OutputFolderTextBox.Text = Path.Combine(pathOfFirstSpectraFile, @"$DATETIME"); } private void TasksTreeView_MouseDoubleClick(object sender, MouseButtonEventArgs e) { var a = sender as TreeView; if (a.SelectedItem is PreRunTask preRunTask) { switch (preRunTask.metaMorpheusTask.TaskType) { case MyTask.Search: var searchDialog = new SearchTaskWindow(preRunTask.metaMorpheusTask as SearchTask); searchDialog.ShowDialog(); preRunTask.DisplayName = "Task" + (StaticTasksObservableCollection.IndexOf(preRunTask) + 1) + "-" + searchDialog.TheTask.CommonParameters.TaskDescriptor; tasksTreeView.Items.Refresh(); return; case MyTask.Gptmd: var gptmddialog = new GptmdTaskWindow(preRunTask.metaMorpheusTask as GptmdTask); gptmddialog.ShowDialog(); preRunTask.DisplayName = "Task" + (StaticTasksObservableCollection.IndexOf(preRunTask) + 1) + "-" + gptmddialog.TheTask.CommonParameters.TaskDescriptor; tasksTreeView.Items.Refresh(); return; case MyTask.Calibrate: var calibratedialog = new CalibrateTaskWindow(preRunTask.metaMorpheusTask as CalibrationTask); calibratedialog.ShowDialog(); preRunTask.DisplayName = "Task" + (StaticTasksObservableCollection.IndexOf(preRunTask) + 1) + "-" + calibratedialog.TheTask.CommonParameters.TaskDescriptor; tasksTreeView.Items.Refresh(); return; case MyTask.XLSearch: var XLSearchdialog = new XLSearchTaskWindow(preRunTask.metaMorpheusTask as XLSearchTask); XLSearchdialog.ShowDialog(); preRunTask.DisplayName = "Task" + (StaticTasksObservableCollection.IndexOf(preRunTask) + 1) + "-" + XLSearchdialog.TheTask.CommonParameters.TaskDescriptor; tasksTreeView.Items.Refresh(); return; } } if (a.SelectedItem is OutputFileForTreeView fileThing) { if (File.Exists(fileThing.FullPath)) { System.Diagnostics.Process.Start(fileThing.FullPath); } else { MessageBox.Show("File " + Path.GetFileName(fileThing.FullPath) + " does not exist"); } } } private void LoadTaskButton_Click(object sender, RoutedEventArgs e) { Microsoft.Win32.OpenFileDialog openFileDialog1 = new Microsoft.Win32.OpenFileDialog() { Filter = "TOML files(*.toml)|*.toml", FilterIndex = 1, RestoreDirectory = true, Multiselect = true }; if (openFileDialog1.ShowDialog() == true) { foreach (var tomlFromSelected in openFileDialog1.FileNames.OrderBy(p => p)) { AddAFile(tomlFromSelected); } } UpdateTaskGuiStuff(); } //run if fileSpecificParams are changed from GUI private void UpdateFileSpecificParamsDisplay(string[] tomlLocations) { string[] fullPathofTomls = tomlLocations; foreach (var file in SelectedRawFiles) { for (int j = 0; j < fullPathofTomls.Count(); j++) { if (Path.GetFileNameWithoutExtension(file.FileName) == Path.GetFileNameWithoutExtension(fullPathofTomls[j])) { if (File.Exists(fullPathofTomls[j])) { TomlTable fileSpecificSettings = Toml.ReadFile(fullPathofTomls[j], MetaMorpheusTask.tomlConfig); try { // parse to make sure toml is readable var temp = new FileSpecificParameters(fileSpecificSettings); // toml is ok; display the file-specific settings in the gui file.SetParametersText(File.ReadAllText(fullPathofTomls[j])); } catch (MetaMorpheusException e) { GuiWarnHandler(null, new StringEventArgs("Problem parsing the file-specific toml " + Path.GetFileName(fullPathofTomls[j]) + "; " + e.Message + "; is the toml from an older version of MetaMorpheus?", null)); } } else { file.SetParametersText(null); } } } } UpdateSpectraFileGuiStuff(); dataGridSpectraFiles.Items.Refresh(); } //run if data file has just been added with and checks for Existing fileSpecficParams private void UpdateFileSpecificParamsDisplayJustAdded(string tomlLocation) { string assumedPathOfSpectraFileWithoutExtension = Path.Combine(Directory.GetParent(tomlLocation).ToString(), Path.GetFileNameWithoutExtension(tomlLocation)); for (int i = 0; i < SpectraFilesObservableCollection.Count; i++) { string thisFilesPathWihoutExtension = Path.Combine(Directory.GetParent(SpectraFilesObservableCollection[i].FilePath).ToString(), Path.GetFileNameWithoutExtension(SpectraFilesObservableCollection[i].FilePath)); if (File.Exists(tomlLocation) && assumedPathOfSpectraFileWithoutExtension.Equals(thisFilesPathWihoutExtension)) { TomlTable fileSpecificSettings = Toml.ReadFile(tomlLocation, MetaMorpheusTask.tomlConfig); try { // parse to make sure toml is readable var temp = new FileSpecificParameters(fileSpecificSettings); // toml is ok; display the file-specific settings in the gui SpectraFilesObservableCollection[i].SetParametersText(File.ReadAllText(tomlLocation)); } catch (MetaMorpheusException e) { GuiWarnHandler(null, new StringEventArgs("Problem parsing the file-specific toml " + Path.GetFileName(tomlLocation) + "; " + e.Message + "; is the toml from an older version of MetaMorpheus?", null)); } } } UpdateSpectraFileGuiStuff(); dataGridSpectraFiles.Items.Refresh(); } private void AddSelectedSpectra(object sender, RoutedEventArgs e) { DataGridRow obj = (DataGridRow)sender; RawDataForDataGrid ok = (RawDataForDataGrid)obj.DataContext; SelectedRawFiles.Add(ok); UpdateSpectraFileGuiStuff(); } private void RemoveSelectedSpectra(object sender, RoutedEventArgs e) { DataGridRow obj = (DataGridRow)sender; RawDataForDataGrid ok = (RawDataForDataGrid)obj.DataContext; SelectedRawFiles.Remove(ok); UpdateSpectraFileGuiStuff(); } private void MenuItem_Click(object sender, RoutedEventArgs e) { System.Diagnostics.Process.Start(@"https://github.com/smith-chem-wisc/MetaMorpheus/wiki"); } private void MenuItem_YouTube(object sender, RoutedEventArgs e) { System.Diagnostics.Process.Start(@"https://www.youtube.com/playlist?list=PLVk5tTSZ1aWlhNPh7jxPQ8pc0ElyzSUQb"); } private void MenuItem_ProteomicsNewsBlog(object sender, RoutedEventArgs e) { System.Diagnostics.Process.Start(@"https://proteomicsnews.blogspot.com/"); } private void MenuItem_Click_1(object sender, RoutedEventArgs e) { var globalSettingsDialog = new GlobalSettingsWindow(); globalSettingsDialog.ShowDialog(); } private bool DatabaseExists(ObservableCollection<ProteinDbForDataGrid> pDOC, ProteinDbForDataGrid uuu) { foreach (ProteinDbForDataGrid pdoc in pDOC) { if (pdoc.FilePath == uuu.FilePath) { return true; } } return false; } private bool SpectraFileExists(ObservableCollection<RawDataForDataGrid> rDOC, RawDataForDataGrid zzz) { foreach (RawDataForDataGrid rdoc in rDOC) { if (rdoc.FileName == zzz.FileName) { return true; } } return false; } private void CancelButton_Click(object sender, RoutedEventArgs e) { string grammar = StaticTasksObservableCollection.Count <= 1 ? "this task" : "these tasks"; if (MessageBox.Show("Are you sure you want to cancel " + grammar + "?", "Cancel Tasks", MessageBoxButton.OKCancel) == MessageBoxResult.OK) { GlobalVariables.StopLoops = true; CancelButton.IsEnabled = false; notificationsTextBox.AppendText("Canceling...\n"); } } private void ChangeFileParameters_Click(object sender, RoutedEventArgs e) { var dialog = new FileSpecificParametersWindow(SelectedRawFiles); if (dialog.ShowDialog() == true) { var tomlPathsForSelectedFiles = SelectedRawFiles.Select(p => Path.Combine(Directory.GetParent(p.FilePath).ToString(), Path.GetFileNameWithoutExtension(p.FileName)) + ".toml").ToList(); UpdateFileSpecificParamsDisplay(tomlPathsForSelectedFiles.ToArray()); } } private void BtnQuantSet_Click(object sender, RoutedEventArgs e) { var dialog = new ExperimentalDesignWindow(SpectraFilesObservableCollection); dialog.ShowDialog(); } private void MenuItem_Click_2(object sender, RoutedEventArgs e) { try { GetVersionNumbersFromWeb(); } catch (Exception ex) { GuiWarnHandler(null, new StringEventArgs("Could not get newest MM version from web: " + ex.Message, null)); return; } if (GlobalVariables.MetaMorpheusVersion.Equals(NewestKnownVersion)) { MessageBox.Show("You have the most updated version!"); } else { try { MetaUpdater newwind = new MetaUpdater(); newwind.ShowDialog(); } catch (Exception ex) { MessageBox.Show(ex.ToString()); } } } private void MenuItem_Click_4(object sender, RoutedEventArgs e) { string mailto = string.Format("mailto:{0}?Subject=MetaMorpheus. Issue:", "mm_support@chem.wisc.edu"); System.Diagnostics.Process.Start(mailto); } private void MenuItem_Click_5(object sender, RoutedEventArgs e) { System.Diagnostics.Process.Start(@"https://github.com/smith-chem-wisc/MetaMorpheus/issues/new"); } private void MenuItem_Twitter(object sender, RoutedEventArgs e) { System.Diagnostics.Process.Start(@"https://twitter.com/Smith_Chem_Wisc"); } private void MenuItem_Slack(object sender, RoutedEventArgs e) { System.Diagnostics.Process.Start(@"https://join.slack.com/t/smith-chem-public/shared_invite/enQtNDYzNTM5Mzg5NzY0LTRiYWQ5MzVmYmExZWIyMTcyZmNlODJjMWI0YjVhNGM2MmQ2NjE4ZDAzNmM4NWYxMDFhNTQyNDBiM2E0MWE0NGU"); } private void MenuItem_Click_6(object sender, RoutedEventArgs e) { System.Diagnostics.Process.Start(GlobalVariables.DataDir); } private void MenuItem_Click_3(object sender, RoutedEventArgs e) { System.Diagnostics.Process.Start(Path.Combine(GlobalVariables.DataDir, @"settings.toml")); Application.Current.Shutdown(); } private void MenuItem_Click_7(object sender, RoutedEventArgs e) { System.Diagnostics.Process.Start(Path.Combine(GlobalVariables.DataDir, @"GUIsettings.toml")); Application.Current.Shutdown(); } private void MetaDrawMenu_Click(object sender, RoutedEventArgs e) { MetaDraw metaDrawGui = new MetaDraw(); metaDrawGui.Show(); } private void PrintErrorsReadingMods() { // print any error messages reading the mods to the notifications area foreach (var error in GlobalVariables.ErrorsReadingMods) { GuiWarnHandler(null, new StringEventArgs(error, null)); } GlobalVariables.ErrorsReadingMods.Clear(); } private void AddContaminantXML_Click(object sender, RoutedEventArgs e) { string[] contaminantFiles = Directory.GetFiles(Path.Combine(GlobalVariables.DataDir, "Contaminants")); foreach (string contaminantFile in contaminantFiles) { AddAFile(contaminantFile); } dataGridProteinDatabases.Items.Refresh(); } private void AddCustomMod_Click(object sender, RoutedEventArgs e) { var dialog = new CustomModWindow(); dialog.ShowDialog(); } private void AddCustomAminoAcid_Click(object sender, RoutedEventArgs e) { var dialog = new CustomAminoAcidWindow(); dialog.ShowDialog(); } private void AddCustomCrosslinker_Click(object sender, RoutedEventArgs e) { var dialog = new CustomCrosslinkerWindow(); dialog.ShowDialog(); } // handle window closing private void MainWindow_Closing(object sender, CancelEventArgs e) { if (!GuiGlobalParams.DisableCloseWindow && !GlobalVariables.MetaMorpheusVersion.Contains("DEBUG")) { e.Cancel = true; var exit = CustomMsgBox.Show("Exit MetaMorpheus", "Are you sure you want to exit MetaMorpheus?", "Yes", "No", "Yes and don't ask me again"); if (exit == MessageBoxResult.Yes) { e.Cancel = false; } else if (exit == MessageBoxResult.OK) { GuiGlobalParams.DisableCloseWindow = true; Toml.WriteFile(GuiGlobalParams, Path.Combine(GlobalVariables.DataDir, @"GUIsettings.toml"), MetaMorpheusTask.tomlConfig); e.Cancel = false; } } } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: booking/rpc/ota_sync_svc.proto #pragma warning disable 1591 #region Designer generated code using System; using System.Threading; using System.Threading.Tasks; using grpc = global::Grpc.Core; namespace HOLMS.Types.Booking.RPC { public static partial class OTASyncSvc { static readonly string __ServiceName = "holms.types.booking.rpc.OTASyncSvc"; static readonly grpc::Marshaller<global::Google.Protobuf.WellKnownTypes.Empty> __Marshaller_Empty = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Protobuf.WellKnownTypes.Empty.Parser.ParseFrom); static readonly grpc::Marshaller<global::HOLMS.Types.Booking.RPC.ServerTaskDetails> __Marshaller_ServerTaskDetails = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Booking.RPC.ServerTaskDetails.Parser.ParseFrom); static readonly grpc::Marshaller<global::HOLMS.Types.Booking.RPC.SchedulerStartAttemptResponse> __Marshaller_SchedulerStartAttemptResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Booking.RPC.SchedulerStartAttemptResponse.Parser.ParseFrom); static readonly grpc::Marshaller<global::HOLMS.Types.Booking.RPC.PBXServiceStartAttemptResponse> __Marshaller_PBXServiceStartAttemptResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Booking.RPC.PBXServiceStartAttemptResponse.Parser.ParseFrom); static readonly grpc::Method<global::Google.Protobuf.WellKnownTypes.Empty, global::Google.Protobuf.WellKnownTypes.Empty> __Method_SyncReservations = new grpc::Method<global::Google.Protobuf.WellKnownTypes.Empty, global::Google.Protobuf.WellKnownTypes.Empty>( grpc::MethodType.Unary, __ServiceName, "SyncReservations", __Marshaller_Empty, __Marshaller_Empty); static readonly grpc::Method<global::Google.Protobuf.WellKnownTypes.Empty, global::HOLMS.Types.Booking.RPC.ServerTaskDetails> __Method_GetSchedulerLastWorkingTime = new grpc::Method<global::Google.Protobuf.WellKnownTypes.Empty, global::HOLMS.Types.Booking.RPC.ServerTaskDetails>( grpc::MethodType.Unary, __ServiceName, "GetSchedulerLastWorkingTime", __Marshaller_Empty, __Marshaller_ServerTaskDetails); static readonly grpc::Method<global::Google.Protobuf.WellKnownTypes.Empty, global::HOLMS.Types.Booking.RPC.SchedulerStartAttemptResponse> __Method_AttemptStartScheduler = new grpc::Method<global::Google.Protobuf.WellKnownTypes.Empty, global::HOLMS.Types.Booking.RPC.SchedulerStartAttemptResponse>( grpc::MethodType.Unary, __ServiceName, "AttemptStartScheduler", __Marshaller_Empty, __Marshaller_SchedulerStartAttemptResponse); static readonly grpc::Method<global::Google.Protobuf.WellKnownTypes.Empty, global::HOLMS.Types.Booking.RPC.PBXServiceStartAttemptResponse> __Method_AttemptStartPBXService = new grpc::Method<global::Google.Protobuf.WellKnownTypes.Empty, global::HOLMS.Types.Booking.RPC.PBXServiceStartAttemptResponse>( grpc::MethodType.Unary, __ServiceName, "AttemptStartPBXService", __Marshaller_Empty, __Marshaller_PBXServiceStartAttemptResponse); static readonly grpc::Method<global::Google.Protobuf.WellKnownTypes.Empty, global::Google.Protobuf.WellKnownTypes.Empty> __Method_SyncPriceForOccupancyFactor = new grpc::Method<global::Google.Protobuf.WellKnownTypes.Empty, global::Google.Protobuf.WellKnownTypes.Empty>( grpc::MethodType.Unary, __ServiceName, "SyncPriceForOccupancyFactor", __Marshaller_Empty, __Marshaller_Empty); static readonly grpc::Method<global::Google.Protobuf.WellKnownTypes.Empty, global::Google.Protobuf.WellKnownTypes.Empty> __Method_SyncPriceForTimeFactor = new grpc::Method<global::Google.Protobuf.WellKnownTypes.Empty, global::Google.Protobuf.WellKnownTypes.Empty>( grpc::MethodType.Unary, __ServiceName, "SyncPriceForTimeFactor", __Marshaller_Empty, __Marshaller_Empty); /// <summary>Service descriptor</summary> public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor { get { return global::HOLMS.Types.Booking.RPC.OtaSyncSvcReflection.Descriptor.Services[0]; } } /// <summary>Base class for server-side implementations of OTASyncSvc</summary> public abstract partial class OTASyncSvcBase { public virtual global::System.Threading.Tasks.Task<global::Google.Protobuf.WellKnownTypes.Empty> SyncReservations(global::Google.Protobuf.WellKnownTypes.Empty request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Booking.RPC.ServerTaskDetails> GetSchedulerLastWorkingTime(global::Google.Protobuf.WellKnownTypes.Empty request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Booking.RPC.SchedulerStartAttemptResponse> AttemptStartScheduler(global::Google.Protobuf.WellKnownTypes.Empty request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Booking.RPC.PBXServiceStartAttemptResponse> AttemptStartPBXService(global::Google.Protobuf.WellKnownTypes.Empty request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } public virtual global::System.Threading.Tasks.Task<global::Google.Protobuf.WellKnownTypes.Empty> SyncPriceForOccupancyFactor(global::Google.Protobuf.WellKnownTypes.Empty request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } public virtual global::System.Threading.Tasks.Task<global::Google.Protobuf.WellKnownTypes.Empty> SyncPriceForTimeFactor(global::Google.Protobuf.WellKnownTypes.Empty request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } } /// <summary>Client for OTASyncSvc</summary> public partial class OTASyncSvcClient : grpc::ClientBase<OTASyncSvcClient> { /// <summary>Creates a new client for OTASyncSvc</summary> /// <param name="channel">The channel to use to make remote calls.</param> public OTASyncSvcClient(grpc::Channel channel) : base(channel) { } /// <summary>Creates a new client for OTASyncSvc that uses a custom <c>CallInvoker</c>.</summary> /// <param name="callInvoker">The callInvoker to use to make remote calls.</param> public OTASyncSvcClient(grpc::CallInvoker callInvoker) : base(callInvoker) { } /// <summary>Protected parameterless constructor to allow creation of test doubles.</summary> protected OTASyncSvcClient() : base() { } /// <summary>Protected constructor to allow creation of configured clients.</summary> /// <param name="configuration">The client configuration.</param> protected OTASyncSvcClient(ClientBaseConfiguration configuration) : base(configuration) { } public virtual global::Google.Protobuf.WellKnownTypes.Empty SyncReservations(global::Google.Protobuf.WellKnownTypes.Empty request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return SyncReservations(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual global::Google.Protobuf.WellKnownTypes.Empty SyncReservations(global::Google.Protobuf.WellKnownTypes.Empty request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_SyncReservations, null, options, request); } public virtual grpc::AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> SyncReservationsAsync(global::Google.Protobuf.WellKnownTypes.Empty request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return SyncReservationsAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual grpc::AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> SyncReservationsAsync(global::Google.Protobuf.WellKnownTypes.Empty request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_SyncReservations, null, options, request); } public virtual global::HOLMS.Types.Booking.RPC.ServerTaskDetails GetSchedulerLastWorkingTime(global::Google.Protobuf.WellKnownTypes.Empty request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return GetSchedulerLastWorkingTime(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual global::HOLMS.Types.Booking.RPC.ServerTaskDetails GetSchedulerLastWorkingTime(global::Google.Protobuf.WellKnownTypes.Empty request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_GetSchedulerLastWorkingTime, null, options, request); } public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Booking.RPC.ServerTaskDetails> GetSchedulerLastWorkingTimeAsync(global::Google.Protobuf.WellKnownTypes.Empty request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return GetSchedulerLastWorkingTimeAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Booking.RPC.ServerTaskDetails> GetSchedulerLastWorkingTimeAsync(global::Google.Protobuf.WellKnownTypes.Empty request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_GetSchedulerLastWorkingTime, null, options, request); } public virtual global::HOLMS.Types.Booking.RPC.SchedulerStartAttemptResponse AttemptStartScheduler(global::Google.Protobuf.WellKnownTypes.Empty request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return AttemptStartScheduler(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual global::HOLMS.Types.Booking.RPC.SchedulerStartAttemptResponse AttemptStartScheduler(global::Google.Protobuf.WellKnownTypes.Empty request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_AttemptStartScheduler, null, options, request); } public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Booking.RPC.SchedulerStartAttemptResponse> AttemptStartSchedulerAsync(global::Google.Protobuf.WellKnownTypes.Empty request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return AttemptStartSchedulerAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Booking.RPC.SchedulerStartAttemptResponse> AttemptStartSchedulerAsync(global::Google.Protobuf.WellKnownTypes.Empty request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_AttemptStartScheduler, null, options, request); } public virtual global::HOLMS.Types.Booking.RPC.PBXServiceStartAttemptResponse AttemptStartPBXService(global::Google.Protobuf.WellKnownTypes.Empty request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return AttemptStartPBXService(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual global::HOLMS.Types.Booking.RPC.PBXServiceStartAttemptResponse AttemptStartPBXService(global::Google.Protobuf.WellKnownTypes.Empty request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_AttemptStartPBXService, null, options, request); } public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Booking.RPC.PBXServiceStartAttemptResponse> AttemptStartPBXServiceAsync(global::Google.Protobuf.WellKnownTypes.Empty request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return AttemptStartPBXServiceAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Booking.RPC.PBXServiceStartAttemptResponse> AttemptStartPBXServiceAsync(global::Google.Protobuf.WellKnownTypes.Empty request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_AttemptStartPBXService, null, options, request); } public virtual global::Google.Protobuf.WellKnownTypes.Empty SyncPriceForOccupancyFactor(global::Google.Protobuf.WellKnownTypes.Empty request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return SyncPriceForOccupancyFactor(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual global::Google.Protobuf.WellKnownTypes.Empty SyncPriceForOccupancyFactor(global::Google.Protobuf.WellKnownTypes.Empty request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_SyncPriceForOccupancyFactor, null, options, request); } public virtual grpc::AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> SyncPriceForOccupancyFactorAsync(global::Google.Protobuf.WellKnownTypes.Empty request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return SyncPriceForOccupancyFactorAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual grpc::AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> SyncPriceForOccupancyFactorAsync(global::Google.Protobuf.WellKnownTypes.Empty request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_SyncPriceForOccupancyFactor, null, options, request); } public virtual global::Google.Protobuf.WellKnownTypes.Empty SyncPriceForTimeFactor(global::Google.Protobuf.WellKnownTypes.Empty request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return SyncPriceForTimeFactor(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual global::Google.Protobuf.WellKnownTypes.Empty SyncPriceForTimeFactor(global::Google.Protobuf.WellKnownTypes.Empty request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_SyncPriceForTimeFactor, null, options, request); } public virtual grpc::AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> SyncPriceForTimeFactorAsync(global::Google.Protobuf.WellKnownTypes.Empty request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return SyncPriceForTimeFactorAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual grpc::AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> SyncPriceForTimeFactorAsync(global::Google.Protobuf.WellKnownTypes.Empty request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_SyncPriceForTimeFactor, null, options, request); } /// <summary>Creates a new instance of client from given <c>ClientBaseConfiguration</c>.</summary> protected override OTASyncSvcClient NewInstance(ClientBaseConfiguration configuration) { return new OTASyncSvcClient(configuration); } } /// <summary>Creates service definition that can be registered with a server</summary> /// <param name="serviceImpl">An object implementing the server-side handling logic.</param> public static grpc::ServerServiceDefinition BindService(OTASyncSvcBase serviceImpl) { return grpc::ServerServiceDefinition.CreateBuilder() .AddMethod(__Method_SyncReservations, serviceImpl.SyncReservations) .AddMethod(__Method_GetSchedulerLastWorkingTime, serviceImpl.GetSchedulerLastWorkingTime) .AddMethod(__Method_AttemptStartScheduler, serviceImpl.AttemptStartScheduler) .AddMethod(__Method_AttemptStartPBXService, serviceImpl.AttemptStartPBXService) .AddMethod(__Method_SyncPriceForOccupancyFactor, serviceImpl.SyncPriceForOccupancyFactor) .AddMethod(__Method_SyncPriceForTimeFactor, serviceImpl.SyncPriceForTimeFactor).Build(); } } } #endregion
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Text; using Microsoft.Deployment.WindowsInstaller; using WixSharp.CommonTasks; using IO = System.IO; namespace WixSharp { /// <summary> /// Extends <see cref="T:WixSharp.Project"/> with runtime event-driven behavior ans managed UI (see <see cref="T:WixSharp.ManagedUI"/> and /// <see cref="T:WixSharp.UI.Forms.ManagedForm"/>). /// <para> /// The managed project has three very important events that are raised during deployment at run: Load/BeforeInstall/AfterInstall. /// </para> /// <remark> /// ManagedProject still maintains backward compatibility for the all older features. That is why it is important to distinguish the use cases /// associated with the project class members dedicated to the same problem domain but resolving the problems in different ways: /// <para><c>UI support</c></para> /// <para> project.UI - to be used to define native MSI/WiX UI.</para> /// <para> project.CustomUI - to be used for minor to customization of native MSI/WiX UI and injection of CLR dialogs. </para> /// <para> project.ManagedUI - to be used to define managed Embedded UI. It allows full customization of the UI</para> /// <para> </para> /// <para><c>Events</c></para> /// <para> project.WixSourceGenerated</para> /// <para> project.WixSourceFormated</para> /// <para> project.WixSourceSaved - to be used at compile time to customize WiX source code (XML) generation.</para> /// <para> </para> /// <para> project.Load</para> /// <para> project.BeforeInstall</para> /// <para> project.AfterInstall - to be used at runtime (msi execution) to customize deployment behaver.</para> /// </remark> /// </summary> /// <example>The following is an example of a simple setup handling the three setup events at runtime. /// <code> /// var project = new ManagedProject("ManagedSetup", /// new Dir(@"%ProgramFiles%\My Company\My Product", /// new File(@"..\Files\bin\MyApp.exe"))); /// /// project.GUID = new Guid("6f330b47-2577-43ad-9095-1861ba25889b"); /// /// project.ManagedUI = ManagedUI.Empty; /// /// project.Load += project_Load; /// project.BeforeInstall += project_BeforeInstall; /// project.AfterInstall += project_AfterInstall; /// /// project.BuildMsi(); /// </code> /// </example> public class ManagedProject : Project { //some materials to consider: http://cpiekarski.com/2012/05/18/wix-custom-action-sequencing/ /// <summary> /// Initializes a new instance of the <see cref="ManagedProject"/> class. /// </summary> public ManagedProject() { } /// <summary> /// Initializes a new instance of the <see cref="ManagedProject"/> class. /// </summary> /// <param name="name">The name of the project. Typically it is the name of the product to be installed.</param> /// <param name="items">The project installable items (e.g. directories, files, registry keys, Custom Actions).</param> public ManagedProject(string name, params WixObject[] items) : base(name, items) { } /// <summary> /// Gets or sets a value indicating whether the full or reduced custom drawing algorithm should be used for rendering the Features dialog /// tree view control. The reduced algorithm involves no manual positioning of the visual elements so it handles better custom screen resolutions. /// However it also leads to the slightly less intuitive tree view item appearance. /// <para>Reduced custom drawing will render disabled tree view items with the text grayed out.</para> /// <para>Full custom drawing will render disabled tree view items with the checkbox grayed out.</para> /// </summary> /// <value> /// <c>true</c> (default) if custom drawing should be reduced otherwise, <c>false</c>. /// </value> public bool MinimalCustomDrawing { get { return Properties.Where(x => x.Name == "WixSharpUI_TreeNode_TexOnlyDrawing").FirstOrDefault() != null; } set { if (value) { var prop = Properties.Where(x => x.Name == "WixSharpUI_TreeNode_TexOnlyDrawing").FirstOrDefault(); if (prop != null) prop.Value = "true"; else this.AddProperty(new Property("WixSharpUI_TreeNode_TexOnlyDrawing", "true")); } else { Properties = Properties.Where(x => x.Name != "WixSharpUI_TreeNode_TexOnlyDrawing").ToArray(); } } } /// <summary> /// Event handler of the ManagedSetup for the MSI runtime events. /// </summary> /// <param name="e">The <see cref="SetupEventArgs"/> instance containing the event data.</param> public delegate void SetupEventHandler(SetupEventArgs e); /// <summary> /// Indicates if the installations should be aborted if managed event handler throws an unhanded exception. /// <para> /// Aborting is the default behavior if this field is not set. /// </para> /// </summary> public bool? AbortSetupOnUnhandledExceptions; /// <summary> /// Occurs on EmbeddedUI initialized but before the first dialog is displayed. It is only invoked if ManagedUI is set. /// </summary> public event SetupEventHandler UIInitialized; /// <summary> /// Occurs on EmbeddedUI loaded and ShellView (main window) is displayed but before first dialog is positioned within ShellView. /// It is only invoked if ManagedUI is set. /// <para>Note that this event is fired on the loading the UI main window thus it's not a good stage for any decision regarding /// aborting/continuing the whole setup process. That is UILoaded event will ignore any value set to SetupEventArgs.Result by the user. /// </para> /// </summary> public event SetupEventHandler UILoaded; /// <summary> /// Occurs before AppSearch standard action. /// </summary> public event SetupEventHandler Load; /// <summary> /// Occurs before InstallFiles standard action. /// </summary> public event SetupEventHandler BeforeInstall; /// <summary> /// Occurs after InstallFiles standard action. The event is fired from the elevated execution context. /// </summary> public event SetupEventHandler AfterInstall; /// <summary> /// An instance of ManagedUI defining MSI UI dialogs sequence. User should set it if he/she wants native MSI dialogs to be /// replaced by managed ones. /// </summary> public IManagedUI ManagedUI; bool preprocessed = false; string thisAsm = typeof(ManagedProject).Assembly.Location; bool IsHandlerSet<T>(Expression<Func<T>> expression) { var name = Reflect.NameOf(expression); var handler = expression.Compile()() as Delegate; return (handler != null); } void Bind<T>(Expression<Func<T>> expression, When when = When.Before, Step step = null, bool elevated = false) { var name = Reflect.NameOf(expression); var handler = expression.Compile()() as Delegate; const string wixSharpProperties = "WIXSHARP_RUNTIME_DATA"; if (handler != null) { if (this.AbortSetupOnUnhandledExceptions.HasValue) { var abortOnErrorName = "WIXSHARP_ABORT_ON_ERROR"; if (!Properties.Any(p => p.Name == abortOnErrorName)) this.AddProperty(new Property(abortOnErrorName, this.AbortSetupOnUnhandledExceptions.Value.ToString())); } //foreach (string handlerAsm in handler.GetInvocationList().Select(x => x.Method.DeclaringType.Assembly.Location)) foreach (var type in handler.GetInvocationList().Select(x => x.Method.DeclaringType)) { string location = type.Assembly.Location; //Resolving scriptAsmLocation is not properly tested yet bool resolveInMemAsms = true; if (resolveInMemAsms) { if (location.IsEmpty()) location = type.Assembly.GetLocation(); } if (location.IsEmpty()) throw new ApplicationException($"The location of the assembly for ManagedProject event handler ({type}) cannot be obtained.\n" + "The assembly must be a file based one but it looks like it was loaded from memory.\n" + "If you are using CS-Script to build MSI ensure it has 'InMemoryAssembly' set to false."); if (!this.DefaultRefAssemblies.Contains(location)) this.DefaultRefAssemblies.Add(location); } this.AddProperty(new Property("WixSharp_{0}_Handlers".FormatWith(name), GetHandlersInfo(handler as MulticastDelegate))); string dllEntry = "WixSharp_{0}_Action".FormatWith(name); if (step != null) { if (elevated) this.AddAction(new ElevatedManagedAction(dllEntry) { Id = new Id(dllEntry), ActionAssembly = thisAsm, Return = Return.check, When = when, Step = step, Condition = Condition.Create("1"), UsesProperties = "WixSharp_{0}_Handlers,{1},{2}".FormatWith(name, wixSharpProperties, DefaultDeferredProperties), }); else this.AddAction(new ManagedAction(dllEntry) { Id = new Id(dllEntry), ActionAssembly = thisAsm, Return = Return.check, When = when, Step = step, Condition = Condition.Create("1") }); } } } void AddCancelFromUIIHandler() { string dllEntry = "CancelRequestHandler"; this.AddAction(new ElevatedManagedAction(dllEntry) { Id = new Id(dllEntry), ActionAssembly = thisAsm, Return = Return.check, When = When.Before, Step = Step.InstallFinalize, Condition = Condition.NOT_BeingRemoved, UsesProperties = "UpgradeCode" }); } /// <summary> /// The default properties mapped for use with the deferred custom actions. See <see cref="ManagedAction.UsesProperties"/> for the details. /// <para>The default value is "INSTALLDIR,UILevel"</para> /// </summary> public string DefaultDeferredProperties { set { defaultDeferredProperties = value; } get { return string.Join(",", this.Properties .Where(x => x.IsDeferred) .Select(x => x.Name) .Concat(defaultDeferredProperties.Split(',')) .Where(x => x.IsNotEmpty()) .Select(x => x.Trim()) .Distinct() .ToArray()); } } string defaultDeferredProperties = "INSTALLDIR,UILevel,ProductName,FOUNDPREVIOUSVERSION"; /// <summary> /// Flags that indicates if <c>WixSharp_InitRuntime_Action</c> custom action should be always scheduled. The default value is <c>true</c>. /// <para><c>WixSharp_InitRuntime_Action</c> is the action, which ManagedSetup performs at startup (before AppSearch). /// In this action the most important MSI properties are pushed into Session.CustomActionData. These properties are typically consumed /// from other custom actions (e.g. Project.AfterInstall event) and they are: /// <list type="bullet"> /// <item><description>Installed</description></item> /// <item><description>REMOVE</description></item> /// <item><description>ProductName</description></item> /// <item><description>REINSTALL</description></item> /// <item><description>UPGRADINGPRODUCTCODE</description></item> /// <item><description>UILevel</description></item> /// <item><description>WIXSHARP_MANAGED_UI</description></item> /// </list> /// </para> /// <para>However in same cases (e.g. oversizes msi file) it is desirable to minimize amount of time the msi loaded into memory /// (e.g. by custom actions). Thus setting AlwaysScheduleInitRuntime to <c>false</c> will prevent scheduling <c>WixSharp_InitRuntime_Action</c> /// unless any of the ManagedProject events (e.g. Project.AfterInstall) has user handler assigned. /// </para> /// </summary> public bool AlwaysScheduleInitRuntime = true; override internal void Preprocess() { //Debug.Assert(false); base.Preprocess(); if (!preprocessed) { preprocessed = true; //It is too late to set prerequisites. Launch conditions are evaluated after UI is popped up. //this.SetNetFxPrerequisite(Condition.Net35_Installed, "Please install .NET v3.5 first."); if (ManagedUI?.Icon != null) { this.AddBinary(new Binary(new Id("ui_shell_icon"), ManagedUI.Icon)); } string dllEntry = "WixSharp_InitRuntime_Action"; bool needInvokeInitRuntime = (IsHandlerSet(() => UIInitialized) || IsHandlerSet(() => Load) || IsHandlerSet(() => UILoaded) || IsHandlerSet(() => BeforeInstall) || IsHandlerSet(() => AfterInstall) || AlwaysScheduleInitRuntime); if (needInvokeInitRuntime) this.AddAction(new ManagedAction(dllEntry) { Id = new Id(dllEntry), ActionAssembly = thisAsm, Return = Return.check, When = When.Before, Step = Step.AppSearch, Condition = Condition.Always }); if (ManagedUI != null) { this.AddProperty(new Property("WixSharp_UI_INSTALLDIR", ManagedUI.InstallDirId ?? "INSTALLDIR")); if (AutoElements.EnableUACRevealer) this.AddProperty(new Property("UAC_REVEALER_ENABLED", "true")); if (AutoElements.UACWarning.IsNotEmpty()) this.AddProperty(new Property("UAC_WARNING", AutoElements.UACWarning)); ManagedUI.BeforeBuild(this); InjectDialogs("WixSharp_InstallDialogs", ManagedUI.InstallDialogs); InjectDialogs("WixSharp_ModifyDialogs", ManagedUI.ModifyDialogs); this.EmbeddedUI = new EmbeddedAssembly(new Id("WixSharp_EmbeddedUI_Asm"), ManagedUI.GetType().Assembly.Location); this.DefaultRefAssemblies.AddRange(ManagedUI.InstallDialogs.Assemblies); // WixSharp.UI and WixSharp.UI.WPF this.DefaultRefAssemblies.AddRange(ManagedUI.ModifyDialogs.Assemblies); this.DefaultRefAssemblies.AddRange(GetUiDialogsDependencies(ManagedUI)); // Caliburn, etc. this.DefaultRefAssemblies.Add(ManagedUI.GetType().Assembly.Location); this.DefaultRefAssemblies.FilterDuplicates(); Bind(() => UIInitialized); Bind(() => UILoaded); AddCancelFromUIIHandler(); } Bind(() => Load, When.Before, Step.AppSearch); Bind(() => BeforeInstall, When.Before, Step.InstallFiles); Bind(() => AfterInstall, When.After, Step.InstallFiles, true); } } string[] GetUiDialogsDependencies(IManagedUI ui) { var usngWpfStockDialogs = ui.InstallDialogs .Combine(ui.ModifyDialogs) .SelectMany(x => x.Assembly.GetReferencedAssemblies()) .Any(a => a.Name.StartsWith("WixSharp.UI.WPF")); if (usngWpfStockDialogs) return new[] { System.Reflection.Assembly.Load("Caliburn.Micro").Location, System.Reflection.Assembly.Load("Caliburn.Micro.Platform").Location, System.Reflection.Assembly.Load("Caliburn.Micro.Platform.Core").Location, System.Reflection.Assembly.Load("System.Windows.Interactivity").Location }; else return new string[0]; } void InjectDialogs(string name, ManagedDialogs dialogs) { if (dialogs.Any()) { var dialogsInfo = new StringBuilder(); foreach (var item in dialogs) { if (!this.DefaultRefAssemblies.Contains(item.Assembly.GetLocation())) this.DefaultRefAssemblies.Add(item.Assembly.GetLocation()); var info = GetDialogInfo(item); ValidateDialogInfo(info); dialogsInfo.Append(info + "\n"); } this.AddProperty(new Property(name, dialogsInfo.ToString().Trim())); } } /// <summary> /// Reads and returns the dialog types from the string definition. This method is to be used by WixSharp assembly. /// </summary> /// <param name="data">The data.</param> /// <returns></returns> public static List<Type> ReadDialogs(string data) { return data.Split('\n') .Select(x => x.Trim()) .Where(x => x.IsNotEmpty()) .Select(x => ManagedProject.GetDialog(x)) .ToList(); } static void ValidateDialogInfo(string info) { try { GetDialog(info); } catch (Exception) { //may need to do extra logging; not important for now throw; } } static string GetDialogInfo(Type dialog) { var info = "{0}|{1}".FormatWith( dialog.Assembly.FullName, dialog.FullName); return info; } internal static Type GetDialog(string info) { string[] parts = info.Split('|'); var assembly = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(x => x.GetName().Name.StartsWith(parts[0])) ?? System.Reflection.Assembly.Load(parts[0]); var dialogType = assembly.GetType(parts[1]); if (dialogType == null) throw new Exception($"Cannot instantiate '{parts[1]}'. " + $"Make sure you added this type assembly to your setup with 'project.{nameof(DefaultRefAssemblies)}'"); return dialogType; } static void ValidateHandlerInfo(string info) { try { GetHandler(info); } catch (Exception) { //may need to do extra logging; not important for now throw; } } internal static string GetHandlersInfo(MulticastDelegate handlers) { var result = new StringBuilder(); foreach (Delegate action in handlers.GetInvocationList()) { var handlerInfo = "{0}|{1}|{2}".FormatWith( action.Method.DeclaringType.Assembly.FullName, action.Method.DeclaringType.FullName, action.Method.Name); ValidateHandlerInfo(handlerInfo); result.AppendLine(handlerInfo); } return result.ToString().Trim(); } static MethodInfo GetHandler(string info) { string[] parts = info.Split('|'); // Try to see if it's already loaded. `Assembly.Load(name)` still loads from the file // if found. Even though the file-less (or renamed) assembly is loaded. // Yep, it's not what one would expect. // // If not done this way it might locks the asm file, which in turn leads // to the problems if host is a cs-script app. var assembly = System.AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(x => x.FullName.StartsWith(parts[0])) ?? System.Reflection.Assembly.Load(parts[0]); Type type = null; // Ideally need to iterate through the all types in order to find even private ones // Though loading some internal (irrelevant) types can fail because of the dependencies. try { assembly.GetTypes().Single(t => t.FullName == parts[1]); } catch { } //If we failed to iterate through the types then try to load the type explicitly. Though in this case it has to be public. if (type == null) type = assembly.GetType(parts[1]); var method = type.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.InvokeMethod | BindingFlags.Static) .Single(m => m.Name == parts[2]); return method; } static void InvokeClientHandler(string info, SetupEventArgs eventArgs) { MethodInfo method = GetHandler(info); if (method.IsStatic) method.Invoke(null, new object[] { eventArgs }); else method.Invoke(Activator.CreateInstance(method.DeclaringType), new object[] { eventArgs }); } internal static ActionResult InvokeClientHandlers(Session session, string eventName, IShellView UIShell = null) { var eventArgs = Convert(session); eventArgs.ManagedUI = UIShell; try { string handlersInfo = session.Property("WixSharp_{0}_Handlers".FormatWith(eventName)); if (!string.IsNullOrEmpty(handlersInfo)) { foreach (string item in handlersInfo.Trim().Split('\n')) { InvokeClientHandler(item.Trim(), eventArgs); if (eventArgs.Result == ActionResult.Failure || eventArgs.Result == ActionResult.UserExit) break; } eventArgs.SaveData(); } } catch (Exception e) { session.Log("WixSharp aborted the session because of the error:" + Environment.NewLine + e.ToPublicString()); if (session.AbortOnError()) eventArgs.Result = ActionResult.Failure; } return eventArgs.Result; } internal static ActionResult Init(Session session) { //System.Diagnostics.Debugger.Launch(); var data = new SetupEventArgs.AppData(); try { data["Installed"] = session["Installed"]; data["REMOVE"] = session["REMOVE"]; data["ProductName"] = session["ProductName"]; data["ProductCode"] = session["ProductCode"]; data["UpgradeCode"] = session["UpgradeCode"]; data["REINSTALL"] = session["REINSTALL"]; data["MsiFile"] = session["OriginalDatabase"]; data["UPGRADINGPRODUCTCODE"] = session["UPGRADINGPRODUCTCODE"]; data["FOUNDPREVIOUSVERSION"] = session["FOUNDPREVIOUSVERSION"]; data["UILevel"] = session["UILevel"]; data["WIXSHARP_MANAGED_UI"] = session["WIXSHARP_MANAGED_UI"]; data["WIXSHARP_MANAGED_UI_HANDLE"] = session["WIXSHARP_MANAGED_UI_HANDLE"]; } catch (Exception e) { session.Log(e.Message); } data.MergeReplace(session["WIXSHARP_RUNTIME_DATA"]); session["WIXSHARP_RUNTIME_DATA"] = data.ToString(); return ActionResult.Success; } internal static SetupEventArgs Convert(Session session) { //Debugger.Launch(); var result = new SetupEventArgs { Session = session }; try { string data = session.Property("WIXSHARP_RUNTIME_DATA"); result.Data.InitFrom(data); result.Data.SetEnvironmentVariables(); session.CustomActionData.SetEnvironmentVariables(); } catch (Exception e) { session.Log(e.Message); } return result; } } }
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/ // Portions Copyright 2000-2004 Jonathan de Halleux // // 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. #region Copyright (c) 2002-2003, James W. Newkirk, Michael C. Two, Alexei A. Vorontsov, Charlie Poole, Philip A. Craig #endregion using System; using System.Collections.Generic; using System.IO; using System.Timers; namespace Gallio.Icarus.Remoting { /// <summary> /// FileWatcher keeps track of one or more files to /// see if they have changed. It incorporates a delayed notification /// and uses a standard event to notify any interested parties /// about the change. The path to the file is provided as /// an argument to the event handler so that one routine can /// be used to handle events from multiple watchers. /// </summary> /// <remarks> /// <para> /// Based on code taken from NUnit. /// <code> /// /************************************************************************************ /// ' /// ' Copyright 2002-2003 James W. Newkirk, Michael C. Two, Alexei A. Vorontsov, Charlie Poole /// ' Copyright 2000-2002 Philip A. Craig /// ' /// ' This software is provided 'as-is', without any express or implied warranty. In no /// ' event will the authors be held liable for any damages arising from the use of this /// ' software. /// ' /// ' Permission is granted to anyone to use this software for any purpose, including /// ' commercial applications, and to alter it and redistribute it freely, subject to the /// ' following restrictions: /// ' /// ' 1. The origin of this software must not be misrepresented; you must not claim that /// ' you wrote the original software. If you use this software in a product, an /// ' acknowledgment (see the following) in the product documentation is required. /// ' /// ' Portions Copyright 2002-2003 James W. Newkirk, Michael C. Two, Alexei A. Vorontsov, Charlie Poole /// ' or Copyright 2000-2002 Philip A. Craig /// ' /// ' 2. Altered source versions must be plainly marked as such, and must not be /// ' misrepresented as being the original software. /// ' /// ' 3. This notice may not be removed or altered from any source distribution. /// ' /// '***********************************************************************************/ /// </code> /// </para> /// </remarks> public class FileWatcher : IFileWatcher { private readonly Dictionary<string, SingleFileWatcher> fileWatchers = new Dictionary<string, SingleFileWatcher>(); protected Timer timer; protected string changedFilePath; public event FileChangedHandler FileChangedEvent; public FileWatcher() { timer = new Timer(1000); timer.AutoReset = false; timer.Enabled = false; timer.Elapsed += OnTimer; } public void Add(IList<string> files) { foreach (string file in files) Add(file); } public void Add(string filePath) { if (fileWatchers.ContainsKey(filePath)) return; FileInfo file = new FileInfo(filePath); if (!file.Directory.Exists) return; SingleFileWatcher fw = new SingleFileWatcher(file); fw.Watcher.Path = file.DirectoryName; fw.Watcher.Filter = file.Name; fw.Watcher.NotifyFilter = NotifyFilters.Size | NotifyFilters.LastWrite; fw.Watcher.Changed += OnChanged; fw.Watcher.EnableRaisingEvents = false; fileWatchers.Add(filePath, fw); if (fileWatchers.Count > 0) Start(); } public void Remove(string filePath) { if (fileWatchers.ContainsKey(filePath)) fileWatchers.Remove(filePath); } public void Clear() { Stop(); foreach(string key in fileWatchers.Keys) { SingleFileWatcher fw = fileWatchers[key]; fw.Watcher.Changed -= OnChanged; } fileWatchers.Clear(); } public void Start() { EnableWatchers(true); } public void Stop() { EnableWatchers(false); } private void EnableWatchers(bool enable) { foreach (string key in fileWatchers.Keys) { SingleFileWatcher watcher = fileWatchers[key]; watcher.Watcher.EnableRaisingEvents = enable; } } protected void OnTimer(Object source, ElapsedEventArgs e) { lock(this) { PublishEvent(); timer.Enabled=false; } } protected void OnChanged(object source, FileSystemEventArgs e) { changedFilePath = e.FullPath; if ( timer != null ) { lock(this) { if(!timer.Enabled) timer.Enabled=true; timer.Start(); } } else { PublishEvent(); } } protected void PublishEvent() { if (FileChangedEvent != null) FileChangedEvent(changedFilePath); } private sealed class SingleFileWatcher { private readonly FileSystemWatcher watcher = new FileSystemWatcher(); private readonly FileInfo info; public SingleFileWatcher(FileInfo info) { this.info = info; } public FileSystemWatcher Watcher { get { return watcher; } } public FileInfo Info { get { return info; } } } } }
using System; using System.Collections.Generic; using System.Text; using System.Runtime.InteropServices; namespace gView.SDEWrapper { public class CONST { public const int SE_MAX_MESSAGE_LENGTH = 512; public const int SE_MAX_SQL_MESSAGE_LENGTH = 4096; public const int SE_MAX_CONFIG_KEYWORD_LEN = 32; public const int SE_MAX_DESCRIPTION_LEN = 64; public const int SE_MAX_DATABASE_LEN = 32; public const int SE_MAX_OWNER_LEN = 32; public const int SE_MAX_TABLE_LEN = 160; public const int SE_MAX_COLUMN_LEN = 32; public const int SE_QUALIFIED_TABLE_NAME = (SE_MAX_DATABASE_LEN + SE_MAX_OWNER_LEN + SE_MAX_TABLE_LEN + 2); public const System.Int32 SE_NIL_TYPE_MASK = (1); public const System.Int32 SE_POINT_TYPE_MASK = (1 << 1); public const System.Int32 SE_LINE_TYPE_MASK = (1 << 2); public const System.Int32 SE_SIMPLE_LINE_TYPE_MASK = (1 << 3); public const System.Int32 SE_AREA_TYPE_MASK = (1 << 4); public const System.Int32 SE_UNVERIFIED_SHAPE_MASK = (1 << 11); public const System.Int32 SE_MULTIPART_TYPE_MASK = (1 << 18); public const System.Int32 SE_SMALLINT_TYPE = 1; /* 2-byte Integer */ public const System.Int32 SE_INTEGER_TYPE = 2; /* 4-byte Integer */ public const System.Int32 SE_FLOAT_TYPE = 3; /* 4-byte Float */ public const System.Int32 SE_DOUBLE_TYPE = 4; /* 8-byte Float */ public const System.Int32 SE_STRING_TYPE = 5; /* Null Term. Character Array */ public const System.Int32 SE_BLOB_TYPE = 6; /* Variable Length Data */ public const System.Int32 SE_DATE_TYPE = 7; /* Struct tm Date */ public const System.Int32 SE_SHAPE_TYPE = 8; /* Shape geometry (SE_SHAPE) */ public const System.Int32 SE_RASTER_TYPE = 9; /* Raster */ public const System.Int32 SE_XML_TYPE = 10; /* XML Document */ public const System.Int32 SE_INT64_TYPE = 11; /* 8-byte Integer */ public const System.Int32 SE_UUID_TYPE = 12; /* A Universal Unique ID */ public const System.Int32 SE_CLOB_TYPE = 13; /* Character variable length data */ public const System.Int32 SE_NSTRING_TYPE = 14; /* UNICODE Null Term. Character Array */ public const System.Int32 SE_NCLOB_TYPE = 15; /* UNICODE Character Large Object */ public const System.Int32 SE_POINT_TYPE = 20; /* Point ADT */ public const System.Int32 SE_CURVE_TYPE = 21; /* LineString ADT */ public const System.Int32 SE_LINESTRING_TYPE = 22; /* LineString ADT */ public const System.Int32 SE_SURFACE_TYPE = 23; /* Polygon ADT */ public const System.Int32 SE_POLYGON_TYPE = 24; /* Polygon ADT */ public const System.Int32 SE_GEOMETRYCOLLECTION_TYPE = 25; /* MultiPoint ADT */ public const System.Int32 SE_MULTISURFACE_TYPE = 26; /* LineString ADT */ public const System.Int32 SE_MULTICURVE_TYPE = 27; /* LineString ADT */ public const System.Int32 SE_MULTIPOINT_TYPE = 28; /* MultiPoint ADT */ public const System.Int32 SE_MULTILINESTRING_TYPE = 29; /* MultiLineString ADT */ public const System.Int32 SE_MULTIPOLYGON_TYPE = 30; /* MultiPolygon ADT */ public const System.Int32 SE_GEOMETRY_TYPE = 31; /* Geometry ADT */ public const System.Int32 SE_QUERYTYPE_ATTRIBUTE_FIRST = 1; public const System.Int32 SE_QUERYTYPE_JFA = 2; public const System.Int32 SE_QUERYTYPE_JSF = 3; public const System.Int32 SE_QUERYTYPE_JSFA = 4; public const System.Int32 SE_QUERYTYPE_V3 = 5; public const System.Int32 SE_MAX_QUERYTYPE = 5; /************************************************************ *** SEARCH ORDERS ************************************************************/ public const System.Int16 SE_ATTRIBUTE_FIRST = 1; /* DO NOT USE SPATIAL INDEX */ public const System.Int16 SE_SPATIAL_FIRST = 2; /* USE SPATIAL INDEX */ public const System.Int16 SE_OPTIMIZE = 3; /* * ...Search Methods... */ public const System.Int32 SM_ENVP = 0; /* ENVELOPES OVERLAP */ public const System.Int32 SM_ENVP_BY_GRID = 1; /* ENVELOPES OVERLAP */ public const System.Int32 SM_CP = 2; /* COMMON POINT */ public const System.Int32 SM_LCROSS = 3; /* LINE CROSS */ public const System.Int32 SM_COMMON = 4; /* COMMON EDGE/LINE */ public const System.Int32 SM_CP_OR_LCROSS = 5; /* COMMON POINT OR LINE CROSS */ public const System.Int32 SM_LCROSS_OR_CP = 5; /* COMMON POINT OR LINE CROSS */ public const System.Int32 SM_ET_OR_AI = 6; /* EDGE TOUCH OR AREA INTERSECT */ public const System.Int32 SM_AI_OR_ET = 6; /* EDGE TOUCH OR AREA INTERSECT */ public const System.Int32 SM_ET_OR_II = 6; /* EDGE TOUCH OR INTERIOR INTERSECT */ public const System.Int32 SM_II_OR_ET = 6; /* EDGE TOUCH OR INTERIOR INTERSECT */ public const System.Int32 SM_AI = 7; /* AREA INTERSECT */ public const System.Int32 SM_II = 7; /* INTERIOR INTERSECT */ public const System.Int32 SM_AI_NO_ET = 8; /* AREA INTERSECT AND NO EDGE TOUCH */ public const System.Int32 SM_II_NO_ET = 8; /* INTERIOR INTERSECT AND NO EDGE TOUCH */ public const System.Int32 SM_PC = 9; /* PRIMARY CONTAINED IN SECONDARY */ public const System.Int32 SM_SC = 10; /* SECONDARY CONTAINED IN PRIMARY */ public const System.Int32 SM_PC_NO_ET = 11; /* PRIM CONTAINED AND NO EDGE TOUCH */ public const System.Int32 SM_SC_NO_ET = 12; /* SEC CONTAINED AND NO EDGE TOUCH */ public const System.Int32 SM_PIP = 13; /* FIRST POINT IN PRIMARY IN SEC */ public const System.Int32 SM_IDENTICAL = 15; /* IDENTICAL */ public const System.Int32 SM_CBM = 16; /* Calculus-based method [Clementini] */ /******************************************************************** *** SPATIAL FILTER TYPES FOR SPATIAL CONSTRAINTS AND STABLE SEARCHES *********************************************************************/ public const System.Int32 SE_SHAPE_FILTER = 1; public const System.Int32 SE_ID_FILTER = 2; public const System.Int32 SE_FINISHED = -4; /* * ...Allowable shape types... */ public const System.Int32 SG_NIL_SHAPE = 0; public const System.Int32 SG_POINT_SHAPE = 1; public const System.Int32 SG_LINE_SHAPE = 2; public const System.Int32 SG_SIMPLE_LINE_SHAPE = 4; public const System.Int32 SG_AREA_SHAPE = 8; public const System.Int32 SG_SHAPE_CLASS_MASK = 255; /* Mask all of the previous */ public const System.Int32 SG_SHAPE_MULTI_PART_MASK = 256; /* Bit flag indicates mult parts */ public const System.Int32 SG_MULTI_POINT_SHAPE = 257; public const System.Int32 SG_MULTI_LINE_SHAPE = 258; public const System.Int32 SG_MULTI_SIMPLE_LINE_SHAPE = 260; public const System.Int32 SG_MULTI_AREA_SHAPE = 264; /****************************/ /*** State Reserved Ids ***/ /****************************/ public const System.Int32 SE_BASE_STATE_ID = (0); public const System.Int32 SE_NULL_STATE_ID = (-1); public const System.Int32 SE_DEFAULT_STATE_ID = (-2); /*************************************/ /*** State Conflict Filter Types ***/ /*************************************/ public const System.Int32 SE_STATE_DIFF_NOCHECK = 0; public const System.Int32 SE_STATE_DIFF_NOCHANGE_UPDATE = 1; public const System.Int32 SE_STATE_DIFF_NOCHANGE_DELETE = 2; public const System.Int32 SE_STATE_DIFF_UPDATE_NOCHANGE = 3; public const System.Int32 SE_STATE_DIFF_UPDATE_UPDATE = 4; public const System.Int32 SE_STATE_DIFF_UPDATE_DELETE = 5; public const System.Int32 SE_STATE_DIFF_INSERT = 6; } public enum SE_ROTATION_TYPE { SE_DEFAULT_ROTATION, SE_LEFT_HAND_ROTATION, SE_RIGHT_HAND_ROTATION }; // SE_ERROR [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct SE_ERROR { public System.Int32 sde_error; public System.Int32 ext_error; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 512)] public byte[] err_msg1; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4096)] public byte[] err_msg2; } // SE_CONNECTION [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct SE_CONNECTION { public System.Int32 handle; }; // SE_COLUMN_DEF [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct SE_COLUMN_DEF { [MarshalAs(UnmanagedType.ByValArray, SizeConst = CONST.SE_MAX_COLUMN_LEN)] public byte[] column_name; /* the column name */ public System.Int32 sde_type; /* the SDE data type */ public System.Int32 size; /* the size of the column values */ public System.Int16 decimal_digits; /* number of digits after decimal */ public System.Boolean nulls_allowed; /* allow NULL values ? */ public System.Int16 row_id_type; /* column's use as table's row id */ }; // SE_POINT [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] struct SE_POINT { public double x, y; } // SE_REGINFO [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct SE_REGINFO { public System.Int32 handle; }; // SE_LAYERINFO [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct SE_LAYERINFO { public System.Int32 handle; }; // SE_ENVELOPE [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct SE_ENVELOPE { public double minx; public double miny; public double maxx; public double maxy; }; // SE_SHAPE [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct SE_SHAPE { public System.Int32 handle; }; // SE_QUERYINFO [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct SE_QUERYINFO { public System.Int32 handle; }; // SE_COORDREF [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct SE_COORDREF { public System.Int32 handle; }; //[StructLayout(LayoutKind.Explicit, CharSet = CharSet.Ansi)] //public struct SE_FILTER2 //{ // [FieldOffset(0), MarshalAs(UnmanagedType.ByValTStr, SizeConst = CONST.SE_QUALIFIED_TABLE_NAME)] // public string table; /* the spatial table name */ // [FieldOffset(226), MarshalAs(UnmanagedType.ByValTStr, SizeConst = CONST.SE_MAX_COLUMN_LEN)] // public string column; /* the spatial column name */ // [FieldOffset(258)] // public System.Int32 filter_type; /* the type of spatial filter */ // //union // //{ // [FieldOffset(262)] // public SE_SHAPE shape; /* a shape object */ // //struct id // //{ // [FieldOffset(262)] // public System.Int32 ID; /* A SDE_ROW_ID id for a shape */ // [FieldOffset(266), MarshalAs(UnmanagedType.ByValTStr, SizeConst = CONST.SE_QUALIFIED_TABLE_NAME)] // string tableID; /* The shape's spatial table */ // //}; // //} filter; // [FieldOffset(492)] // public System.Int32 method; /* the search method to satisfy */ // [FieldOffset(496)] // public System.Boolean truth; /* TRUE to pass the test, FALSE if it must NOT pass */ // [FieldOffset(497)] // public System.IntPtr cbm_source; /* set ONLY if the method is SM_CBM */ // [FieldOffset(401)] // public System.IntPtr cbm_object_code; /* internal system use only */ //}; [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct SE_FILTER { [MarshalAs(UnmanagedType.ByValTStr, SizeConst = CONST.SE_QUALIFIED_TABLE_NAME)] public string table; /* the spatial table name */ [MarshalAs(UnmanagedType.ByValTStr, SizeConst = CONST.SE_MAX_COLUMN_LEN)] public string column; /* the spatial column name */ public System.Int32 filter_type; /* the type of spatial filter */ //union //{ public SE_SHAPE shape; /* a shape object */ //struct id //{ //public System.Int32 ID; /* A SDE_ROW_ID id for a shape */ [MarshalAs(UnmanagedType.ByValTStr, SizeConst = CONST.SE_QUALIFIED_TABLE_NAME)] string tableID; /* The shape's spatial table */ //}; //} filter; public System.Int32 method; /* the search method to satisfy */ public System.Boolean truth; /* TRUE to pass the test, FALSE if it must NOT pass */ public System.IntPtr cbm_source; /* set ONLY if the method is SM_CBM */ public System.IntPtr cbm_object_code; /* internal system use only */ }; // SE_STREAM [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct SE_STREAM { public System.Int32 handle; }; // tm [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct tm { public int tm_sec; /* seconds after the minute - [0,59] */ public int tm_min; /* minutes after the hour - [0,59] */ public int tm_hour; /* hours since midnight - [0,23] */ public int tm_mday; /* day of the month - [1,31] */ public int tm_mon; /* months since January - [0,11] */ public int tm_year; /* years since 1900 */ public int tm_wday; /* days since Sunday - [0,6] */ public int tm_yday; /* days since January 1 - [0,365] */ public int tm_isdst; /* daylight savings time flag */ }; }
using System; using System.Collections.Generic; using System.Xml; using Server.Items; using Server.Mobiles; using Server.Network; using Server.ServerSeasons; using Server.Gumps; namespace Server.Regions { public enum SpawnZLevel { Lowest, Highest, Random } public class BaseRegion : Region, ISeasons { #region Scriptiz : gestion des saisons private Season m_Season = Season.Summer; public virtual Season Season { get { return m_Season; } set { m_Season = value; UpdateSeason(); } } public void UpdateSeason() { foreach (Mobile m in this.GetPlayers()) UpdateSeason(m); } public void UpdateSeason(Mobile m) { UpdateSeason(m, (int)m_Season); } private void UpdateSeason(Mobile m, int s) { if (s < 0 || s > 4) return; if (m is PlayerMobile) { NetState state = m.NetState; if (state != null) state.Send(new SeasonChange(s)); } } public override void OnEnter(Mobile m) { if (m is PlayerMobile && ((PlayerMobile)m).Young) { if (!this.YoungProtected) { m.SendGump(new YoungDungeonWarning()); } } UpdateSeason(m); } public override void OnExit(Mobile m) { UpdateSeason(m, m.Map.Season); base.OnExit(m); } #endregion public virtual bool YoungProtected { get { return true; } } public virtual bool YoungMayEnter { get { return true; } } public virtual bool MountsAllowed { get { return true; } } public virtual bool DeadMayEnter { get { return true; } } public virtual bool ResurrectionAllowed { get { return true; } } public virtual bool LogoutAllowed { get { return true; } } public static void Configure() { Region.DefaultRegionType = typeof( BaseRegion ); } private string m_RuneName; private bool m_NoLogoutDelay; private SpawnEntry[] m_Spawns; private SpawnZLevel m_SpawnZLevel; private bool m_ExcludeFromParentSpawns; public string RuneName{ get{ return m_RuneName; } set{ m_RuneName = value; } } public bool NoLogoutDelay{ get{ return m_NoLogoutDelay; } set{ m_NoLogoutDelay = value; } } public SpawnEntry[] Spawns { get{ return m_Spawns; } set { if ( m_Spawns != null ) { for ( int i = 0; i < m_Spawns.Length; i++ ) m_Spawns[i].Delete(); } m_Spawns = value; } } public SpawnZLevel SpawnZLevel{ get{ return m_SpawnZLevel; } set{ m_SpawnZLevel = value; } } public bool ExcludeFromParentSpawns{ get{ return m_ExcludeFromParentSpawns; } set{ m_ExcludeFromParentSpawns = value; } } public override void OnUnregister() { base.OnUnregister(); this.Spawns = null; } public static string GetRuneNameFor( Region region ) { while ( region != null ) { BaseRegion br = region as BaseRegion; if ( br != null && br.m_RuneName != null ) return br.m_RuneName; region = region.Parent; } return null; } public override TimeSpan GetLogoutDelay( Mobile m ) { if ( m_NoLogoutDelay ) { if ( m.Aggressors.Count == 0 && m.Aggressed.Count == 0 && !m.Criminal ) return TimeSpan.Zero; } return base.GetLogoutDelay( m ); } public static bool CanSpawn( Region region, params Type[] types ) { while ( region != null ) { if ( !region.AllowSpawn() ) return false; BaseRegion br = region as BaseRegion; if ( br != null ) { if ( br.Spawns != null ) { for ( int i = 0; i < br.Spawns.Length; i++ ) { SpawnEntry entry = br.Spawns[i]; if ( entry.Definition.CanSpawn( types ) ) return true; } } if ( br.ExcludeFromParentSpawns ) return false; } region = region.Parent; } return false; } public override bool AcceptsSpawnsFrom( Region region ) { if ( region == this || !m_ExcludeFromParentSpawns ) return base.AcceptsSpawnsFrom( region ); return false; } private Rectangle3D[] m_Rectangles; private int[] m_RectangleWeights; private int m_TotalWeight; private static List<Rectangle3D> m_RectBuffer1 = new List<Rectangle3D>(); private static List<Rectangle3D> m_RectBuffer2 = new List<Rectangle3D>(); private void InitRectangles() { if ( m_Rectangles != null ) return; // Test if area rectangles are overlapping, and in that case break them into smaller non overlapping rectangles for ( int i = 0; i < this.Area.Length; i++ ) { m_RectBuffer2.Add( this.Area[i] ); for ( int j = 0; j < m_RectBuffer1.Count && m_RectBuffer2.Count > 0; j++ ) { Rectangle3D comp = m_RectBuffer1[j]; for ( int k = m_RectBuffer2.Count - 1; k >= 0; k-- ) { Rectangle3D rect = m_RectBuffer2[k]; int l1 = rect.Start.X, r1 = rect.End.X, t1 = rect.Start.Y, b1 = rect.End.Y; int l2 = comp.Start.X, r2 = comp.End.X, t2 = comp.Start.Y, b2 = comp.End.Y; if ( l1 < r2 && r1 > l2 && t1 < b2 && b1 > t2 ) { m_RectBuffer2.RemoveAt( k ); int sz = rect.Start.Z; int ez = rect.End.X; if ( l1 < l2 ) { m_RectBuffer2.Add( new Rectangle3D( new Point3D( l1, t1, sz ), new Point3D( l2, b1, ez ) ) ); } if ( r1 > r2 ) { m_RectBuffer2.Add( new Rectangle3D( new Point3D( r2, t1, sz ), new Point3D( r1, b1, ez ) ) ); } if ( t1 < t2 ) { m_RectBuffer2.Add( new Rectangle3D( new Point3D( Math.Max( l1, l2 ), t1, sz ), new Point3D( Math.Min( r1, r2 ), t2, ez ) ) ); } if ( b1 > b2 ) { m_RectBuffer2.Add( new Rectangle3D( new Point3D( Math.Max( l1, l2 ), b2, sz ), new Point3D( Math.Min( r1, r2 ), b1, ez ) ) ); } } } } m_RectBuffer1.AddRange( m_RectBuffer2 ); m_RectBuffer2.Clear(); } m_Rectangles = m_RectBuffer1.ToArray(); m_RectBuffer1.Clear(); m_RectangleWeights = new int[m_Rectangles.Length]; for ( int i = 0; i < m_Rectangles.Length; i++ ) { Rectangle3D rect = m_Rectangles[i]; int weight = rect.Width * rect.Height; m_RectangleWeights[i] = weight; m_TotalWeight += weight; } } private static List<Int32> m_SpawnBuffer1 = new List<Int32>(); private static List<Item> m_SpawnBuffer2 = new List<Item>(); public Point3D RandomSpawnLocation( int spawnHeight, bool land, bool water, Point3D home, int range ) { Map map = this.Map; if ( map == Map.Internal ) return Point3D.Zero; InitRectangles(); if ( m_TotalWeight <= 0 ) return Point3D.Zero; for ( int i = 0; i < 10; i++ ) // Try 10 times { int x, y, minZ, maxZ; if ( home == Point3D.Zero ) { int rand = Utility.Random( m_TotalWeight ); x = int.MinValue; y = int.MinValue; minZ = int.MaxValue; maxZ = int.MinValue; for ( int j = 0; j < m_RectangleWeights.Length; j++ ) { int curWeight = m_RectangleWeights[j]; if ( rand < curWeight ) { Rectangle3D rect = m_Rectangles[j]; x = rect.Start.X + rand % rect.Width; y = rect.Start.Y + rand / rect.Width; minZ = rect.Start.Z; maxZ = rect.End.Z; break; } rand -= curWeight; } } else { x = Utility.RandomMinMax( home.X - range, home.X + range ); y = Utility.RandomMinMax( home.Y - range, home.Y + range ); minZ = int.MaxValue; maxZ = int.MinValue; for ( int j = 0; j < this.Area.Length; j++ ) { Rectangle3D rect = this.Area[j]; if ( x >= rect.Start.X && x < rect.End.X && y >= rect.Start.Y && y < rect.End.Y ) { minZ = rect.Start.Z; maxZ = rect.End.Z; break; } } if ( minZ == int.MaxValue ) continue; } if ( x < 0 || y < 0 || x >= map.Width || y >= map.Height ) continue; LandTile lt = map.Tiles.GetLandTile( x, y ); int ltLowZ = 0, ltAvgZ = 0, ltTopZ = 0; map.GetAverageZ( x, y, ref ltLowZ, ref ltAvgZ, ref ltTopZ ); TileFlag ltFlags = TileData.LandTable[lt.ID & TileData.MaxLandValue].Flags; bool ltImpassable = ( (ltFlags & TileFlag.Impassable) != 0 ); if ( !lt.Ignored && ltAvgZ >= minZ && ltAvgZ < maxZ ) if ( (ltFlags & TileFlag.Wet) != 0 ) { if ( water ) m_SpawnBuffer1.Add( ltAvgZ ); } else if ( land && !ltImpassable ) m_SpawnBuffer1.Add( ltAvgZ ); StaticTile[] staticTiles = map.Tiles.GetStaticTiles( x, y, true ); for ( int j = 0; j < staticTiles.Length; j++ ) { StaticTile tile = staticTiles[j]; ItemData id = TileData.ItemTable[tile.ID & TileData.MaxItemValue]; int tileZ = tile.Z + id.CalcHeight; if ( tileZ >= minZ && tileZ < maxZ ) if ( (id.Flags & TileFlag.Wet) != 0 ) { if ( water ) m_SpawnBuffer1.Add( tileZ ); } else if ( land && id.Surface && !id.Impassable ) m_SpawnBuffer1.Add( tileZ ); } Sector sector = map.GetSector( x, y ); for ( int j = 0; j < sector.Items.Count; j++ ) { Item item = sector.Items[j]; if ( !(item is BaseMulti) && item.ItemID <= TileData.MaxItemValue && item.AtWorldPoint( x, y ) ) { m_SpawnBuffer2.Add( item ); if ( !item.Movable ) { ItemData id = item.ItemData; int itemZ = item.Z + id.CalcHeight; if ( itemZ >= minZ && itemZ < maxZ ) if ( (id.Flags & TileFlag.Wet) != 0 ) { if ( water ) m_SpawnBuffer1.Add( itemZ ); } else if ( land && id.Surface && !id.Impassable ) m_SpawnBuffer1.Add( itemZ ); } } } if ( m_SpawnBuffer1.Count == 0 ) { m_SpawnBuffer1.Clear(); m_SpawnBuffer2.Clear(); continue; } int z; switch ( m_SpawnZLevel ) { case SpawnZLevel.Lowest: { z = int.MaxValue; for ( int j = 0; j < m_SpawnBuffer1.Count; j++ ) { int l = m_SpawnBuffer1[j]; if ( l < z ) z = l; } break; } case SpawnZLevel.Highest: { z = int.MinValue; for ( int j = 0; j < m_SpawnBuffer1.Count; j++ ) { int l = m_SpawnBuffer1[j]; if ( l > z ) z = l; } break; } default: // SpawnZLevel.Random { int index = Utility.Random( m_SpawnBuffer1.Count ); z = m_SpawnBuffer1[index]; break; } } m_SpawnBuffer1.Clear(); if ( !Region.Find( new Point3D( x, y, z ), map ).AcceptsSpawnsFrom( this ) ) { m_SpawnBuffer2.Clear(); continue; } int top = z + spawnHeight; bool ok = true; for ( int j = 0; j < m_SpawnBuffer2.Count; j++ ) { Item item = m_SpawnBuffer2[j]; ItemData id = item.ItemData; if ( ( id.Surface || id.Impassable ) && item.Z + id.CalcHeight > z && item.Z < top ) { ok = false; break; } } m_SpawnBuffer2.Clear(); if ( !ok ) continue; if ( ltImpassable && ltAvgZ > z && ltLowZ < top ) continue; for ( int j = 0; j < staticTiles.Length; j++ ) { StaticTile tile = staticTiles[j]; ItemData id = TileData.ItemTable[tile.ID & TileData.MaxItemValue]; if ( ( id.Surface || id.Impassable ) && tile.Z + id.CalcHeight > z && tile.Z < top ) { ok = false; break; } } if ( !ok ) continue; for ( int j = 0; j < sector.Mobiles.Count; j++ ) { Mobile m = sector.Mobiles[j]; if ( m.X == x && m.Y == y && ( m.AccessLevel == AccessLevel.Player || !m.Hidden ) ) if ( m.Z + 16 > z && m.Z < top ) { ok = false; break; } } if ( ok ) return new Point3D( x, y, z ); } return Point3D.Zero; } public override string ToString() { if ( this.Name != null ) return this.Name; else if ( this.RuneName != null ) return this.RuneName; else return this.GetType().Name; } public BaseRegion( string name, Map map, int priority, params Rectangle2D[] area ) : base( name, map, priority, area ) { } public BaseRegion( string name, Map map, int priority, params Rectangle3D[] area ) : base( name, map, priority, area ) { } public BaseRegion( string name, Map map, Region parent, params Rectangle2D[] area ) : base( name, map, parent, area ) { } public BaseRegion( string name, Map map, Region parent, params Rectangle3D[] area ) : base( name, map, parent, area ) { } public BaseRegion( XmlElement xml, Map map, Region parent ) : base( xml, map, parent ) { ReadString( xml["rune"], "name", ref m_RuneName, false ); bool logoutDelayActive = true; ReadBoolean( xml["logoutDelay"], "active", ref logoutDelayActive, false ); m_NoLogoutDelay = !logoutDelayActive; XmlElement spawning = xml["spawning"]; if ( spawning != null ) { ReadBoolean( spawning, "excludeFromParent", ref m_ExcludeFromParentSpawns, false ); SpawnZLevel zLevel = SpawnZLevel.Lowest; ReadEnum( spawning, "zLevel", ref zLevel, false ); m_SpawnZLevel = zLevel; List<SpawnEntry> list = new List<SpawnEntry>(); foreach ( XmlNode node in spawning.ChildNodes ) { XmlElement el = node as XmlElement; if ( el != null ) { SpawnDefinition def = SpawnDefinition.GetSpawnDefinition( el ); if ( def == null ) continue; int id = 0; if ( !ReadInt32( el, "id", ref id, true ) ) continue; int amount = 0; if ( !ReadInt32( el, "amount", ref amount, true ) ) continue; TimeSpan minSpawnTime = SpawnEntry.DefaultMinSpawnTime; ReadTimeSpan( el, "minSpawnTime", ref minSpawnTime, false ); TimeSpan maxSpawnTime = SpawnEntry.DefaultMaxSpawnTime; ReadTimeSpan( el, "maxSpawnTime", ref maxSpawnTime, false ); Point3D home = Point3D.Zero; int range = 0; XmlElement homeEl = el["home"]; if ( ReadPoint3D( homeEl, map, ref home, false ) ) ReadInt32( homeEl, "range", ref range, false ); Direction dir = SpawnEntry.InvalidDirection; ReadEnum( el["direction"], "value" , ref dir, false ); SpawnEntry entry = new SpawnEntry( id, this, home, range, dir, def, amount, minSpawnTime, maxSpawnTime ); list.Add( entry ); } } if ( list.Count > 0 ) { m_Spawns = list.ToArray(); } } } } }
using System; using System.Linq; using Mono.Cecil; using Mono.Cecil.Metadata; using NUnit.Framework; namespace Mono.Cecil.Tests { [TestFixture] public class MethodTests : BaseTestFixture { [Test] public void AbstractMethod () { TestCSharp ("Methods.cs", module => { var type = module.Types [1]; Assert.AreEqual ("Foo", type.Name); Assert.AreEqual (2, type.Methods.Count); var method = type.GetMethod ("Bar"); Assert.AreEqual ("Bar", method.Name); Assert.IsTrue (method.IsAbstract); Assert.IsNotNull (method.ReturnType); Assert.AreEqual (1, method.Parameters.Count); var parameter = method.Parameters [0]; Assert.AreEqual ("a", parameter.Name); Assert.AreEqual ("System.Int32", parameter.ParameterType.FullName); }); } [Test] public void SimplePInvoke () { TestCSharp ("Methods.cs", module => { var bar = module.GetType ("Bar"); var pan = bar.GetMethod ("Pan"); Assert.IsTrue (pan.IsPInvokeImpl); Assert.IsNotNull (pan.PInvokeInfo); Assert.AreEqual ("Pan", pan.PInvokeInfo.EntryPoint); Assert.IsNotNull (pan.PInvokeInfo.Module); Assert.AreEqual ("foo.dll", pan.PInvokeInfo.Module.Name); }); } [Test] public void GenericMethodDefinition () { TestCSharp ("Generics.cs", module => { var baz = module.GetType ("Baz"); var gazonk = baz.GetMethod ("Gazonk"); Assert.IsNotNull (gazonk); Assert.IsTrue (gazonk.HasGenericParameters); Assert.AreEqual (1, gazonk.GenericParameters.Count); Assert.AreEqual ("TBang", gazonk.GenericParameters [0].Name); }); } [Test] public void ReturnGenericInstance () { TestCSharp ("Generics.cs", module => { var bar = module.GetType ("Bar`1"); var self = bar.GetMethod ("Self"); Assert.IsNotNull (self); var bar_t = self.ReturnType; Assert.IsTrue (bar_t.IsGenericInstance); var bar_t_instance = (GenericInstanceType) bar_t; Assert.AreEqual (bar.GenericParameters [0], bar_t_instance.GenericArguments [0]); var self_str = bar.GetMethod ("SelfString"); Assert.IsNotNull (self_str); var bar_str = self_str.ReturnType; Assert.IsTrue (bar_str.IsGenericInstance); var bar_str_instance = (GenericInstanceType) bar_str; Assert.AreEqual ("System.String", bar_str_instance.GenericArguments [0].FullName); }); } [Test] public void ReturnGenericInstanceWithMethodParameter () { TestCSharp ("Generics.cs", module => { var baz = module.GetType ("Baz"); var gazoo = baz.GetMethod ("Gazoo"); Assert.IsNotNull (gazoo); var bar_bingo = gazoo.ReturnType; Assert.IsTrue (bar_bingo.IsGenericInstance); var bar_bingo_instance = (GenericInstanceType) bar_bingo; Assert.AreEqual (gazoo.GenericParameters [0], bar_bingo_instance.GenericArguments [0]); }); } [Test] public void SimpleOverrides () { TestCSharp ("Interfaces.cs", module => { var ibingo = module.GetType ("IBingo"); var ibingo_foo = ibingo.GetMethod ("Foo"); Assert.IsNotNull (ibingo_foo); var ibingo_bar = ibingo.GetMethod ("Bar"); Assert.IsNotNull (ibingo_bar); var bingo = module.GetType ("Bingo"); var foo = bingo.GetMethod ("IBingo.Foo"); Assert.IsNotNull (foo); Assert.IsTrue (foo.HasOverrides); Assert.AreEqual (ibingo_foo, foo.Overrides [0]); var bar = bingo.GetMethod ("IBingo.Bar"); Assert.IsNotNull (bar); Assert.IsTrue (bar.HasOverrides); Assert.AreEqual (ibingo_bar, bar.Overrides [0]); }); } [Test] public void VarArgs () { TestModule ("varargs.exe", module => { var module_type = module.Types [0]; Assert.AreEqual (3, module_type.Methods.Count); var bar = module_type.GetMethod ("Bar"); var baz = module_type.GetMethod ("Baz"); var foo = module_type.GetMethod ("Foo"); Assert.IsTrue (bar.IsVarArg ()); Assert.IsFalse (baz.IsVarArg ()); Assert.IsTrue (foo.IsVarArg ()); var foo_reference = (MethodReference) baz.Body.Instructions.First (i => i.Offset == 0x000a).Operand; Assert.IsTrue (foo_reference.IsVarArg ()); Assert.AreEqual (0, foo_reference.GetSentinelPosition ()); Assert.AreEqual (foo, foo_reference.Resolve ()); var bar_reference = (MethodReference) baz.Body.Instructions.First (i => i.Offset == 0x0023).Operand; Assert.IsTrue (bar_reference.IsVarArg ()); Assert.AreEqual (1, bar_reference.GetSentinelPosition ()); Assert.AreEqual (bar, bar_reference.Resolve ()); }); } [Test] public void GenericInstanceMethod () { TestCSharp ("Generics.cs", module => { var type = module.GetType ("It"); var method = type.GetMethod ("ReadPwow"); GenericInstanceMethod instance = null; foreach (var instruction in method.Body.Instructions) { instance = instruction.Operand as GenericInstanceMethod; if (instance != null) break; } Assert.IsNotNull (instance); Assert.AreEqual (TokenType.MethodSpec, instance.MetadataToken.TokenType); Assert.AreNotEqual (0, instance.MetadataToken.RID); }); } [Test] public void MethodRefDeclaredOnGenerics () { TestCSharp ("Generics.cs", module => { var type = module.GetType ("Tamtam"); var beta = type.GetMethod ("Beta"); var charlie = type.GetMethod ("Charlie"); // Note that the test depends on the C# compiler emitting the constructor call instruction as // the first instruction of the method body. This requires optimizations to be enabled. var new_list_beta = (MethodReference) beta.Body.Instructions [0].Operand; var new_list_charlie = (MethodReference) charlie.Body.Instructions [0].Operand; Assert.AreEqual ("System.Collections.Generic.List`1<TBeta>", new_list_beta.DeclaringType.FullName); Assert.AreEqual ("System.Collections.Generic.List`1<TCharlie>", new_list_charlie.DeclaringType.FullName); }); } [Test] public void ReturnParameterMethod () { var method = typeof (MethodTests).ToDefinition ().GetMethod ("ReturnParameterMethod"); Assert.IsNotNull (method); Assert.AreEqual (method, method.MethodReturnType.Parameter.Method); } } }
// // Copyright (c) 2008-2019 the Urho3D project. // Copyright (c) 2017-2020 the rbfx project. // // 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.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace Urho3DNet { /// Four-dimensional vector. [StructLayout(LayoutKind.Sequential)] public struct Vector4 : IEquatable<Vector4> { /// Construct from a 3-dimensional vector and the W coordinate. public Vector4(in Vector3 vector, float w) { X = vector.X; Y = vector.Y; Z = vector.Z; W = w; } /// Construct from coordinates. public Vector4(float x = 0, float y = 0, float z = 0, float w = 0) { X = x; Y = y; Z = z; W = w; } /// Construct from a float array. public Vector4(IReadOnlyList<float> data) { X = data[0]; Y = data[1]; Z = data[2]; W = data[3]; } /// Test for equality with another vector without epsilon. public static bool operator ==(in Vector4 lhs, in Vector4 rhs) { return lhs.X == rhs.X && lhs.Y == rhs.Y && lhs.Z == rhs.Z && lhs.W == rhs.W; } /// Test for inequality with another vector without epsilon. public static bool operator !=(in Vector4 lhs, in Vector4 rhs) { return lhs.X != rhs.X || lhs.Y != rhs.Y || lhs.Z != rhs.Z || lhs.W != rhs.W; } /// Add a vector. public static Vector4 operator +(in Vector4 lhs, in Vector4 rhs) { return new Vector4(lhs.X + rhs.X, lhs.Y + rhs.Y, lhs.Z + rhs.Z, lhs.W + rhs.W); } /// Return negation. public static Vector4 operator -(in Vector4 rhs) { return new Vector4(-rhs.X, -rhs.Y, -rhs.Z, -rhs.W); } /// Subtract a vector. public static Vector4 operator -(in Vector4 lhs, in Vector4 rhs) { return new Vector4(lhs.X - rhs.X, lhs.Y - rhs.Y, lhs.Z - rhs.Z, lhs.W - rhs.W); } /// Multiply with a scalar. public static Vector4 operator *(in Vector4 lhs, float rhs) { return new Vector4(lhs.X * rhs, lhs.Y * rhs, lhs.Z * rhs, lhs.W * rhs); } /// Multiply with a vector. public static Vector4 operator *(in Vector4 lhs, in Vector4 rhs) { return new Vector4(lhs.X * rhs.X, lhs.Y * rhs.Y, lhs.Z * rhs.Z, lhs.W * rhs.W); } /// Divide by a scalar. public static Vector4 operator /(in Vector4 lhs, float rhs) { return new Vector4(lhs.X / rhs, lhs.Y / rhs, lhs.Z / rhs, lhs.W / rhs); } /// Divide by a vector. public static Vector4 operator /(in Vector4 lhs, in Vector4 rhs) { return new Vector4(lhs.X / rhs.X, lhs.Y / rhs.Y, lhs.Z / rhs.Z, lhs.W / rhs.W); } /// Return value by index. public float this[int index] { get { if (index < 0 || index > 3) throw new IndexOutOfRangeException(); unsafe { fixed (float* p = &X) { return p[index]; } } } set { if (index < 0 || index > 3) throw new IndexOutOfRangeException(); unsafe { fixed (float* p = &X) { p[index] = value; } } } } /// Calculate dot product. float DotProduct(in Vector4 rhs) { return X * rhs.X + Y * rhs.Y + Z * rhs.Z + W * rhs.W; } /// Calculate absolute dot product. float AbsDotProduct(in Vector4 rhs) { return Math.Abs(X * rhs.X) + Math.Abs(Y * rhs.Y) + Math.Abs(Z * rhs.Z) + Math.Abs(W * rhs.W); } /// Project vector onto axis. float ProjectOntoAxis(in Vector3 axis) { return DotProduct(new Vector4(axis.Normalized, 0.0f)); } /// Return absolute vector. Vector4 Abs => new Vector4(Math.Abs(X), Math.Abs(Y), Math.Abs(Z), Math.Abs(W)); /// Linear interpolation with another vector. Vector4 Lerp(in Vector4 rhs, float t) { return this * (1.0f - t) + rhs * t; } /// Test for equality with another vector with epsilon. public bool Equals(Vector4 rhs) { return MathDefs.Equals(X, rhs.X) && MathDefs.Equals(Y, rhs.Y) && MathDefs.Equals(Z, rhs.Z) && MathDefs.Equals(W, rhs.W); } public override bool Equals(object obj) { return obj is Vector4 other && Equals(other); } /// Return whether is NaN. bool IsNaN => float.IsNaN(X) || float.IsNaN(Y) || float.IsNaN(Z) || float.IsNaN(W); /// Return float data. float[] Data => new float[] {X, Y, Z, W}; /// Return as string. public override string ToString() { return $"{X} {Y} {Z} {W}"; } /// Return hash value for HashSet & HashMap. public override int GetHashCode() { uint hash = 37; hash = 37 * hash + MathDefs.FloatToRawIntBits(X); hash = 37 * hash + MathDefs.FloatToRawIntBits(Y); hash = 37 * hash + MathDefs.FloatToRawIntBits(Z); hash = 37 * hash + MathDefs.FloatToRawIntBits(W); return (int) hash; } /// Multiply Vector4 with a scalar. [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector4 operator *(float lhs, in Vector4 rhs) { return rhs * lhs; } /// Per-component linear interpolation between two 4-vectors. [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector4 Lerp(in Vector4 lhs, in Vector4 rhs, in Vector4 t) { return lhs + (rhs - lhs) * t; } /// Per-component min of two 4-vectors. [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector4 Min(in Vector4 lhs, in Vector4 rhs) { return new Vector4(Math.Min(lhs.X, rhs.X), Math.Min(lhs.Y, rhs.Y), Math.Min(lhs.Z, rhs.Z), Math.Min(lhs.W, rhs.W)); } /// Per-component max of two 4-vectors. [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector4 Max(in Vector4 lhs, in Vector4 rhs) { return new Vector4(Math.Max(lhs.X, rhs.X), Math.Max(lhs.Y, rhs.Y), Math.Max(lhs.Z, rhs.Z), Math.Max(lhs.W, rhs.W)); } /// Per-component floor of 4-vector. [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector4 Floor(in Vector4 vec) { return new Vector4((float) Math.Floor(vec.X), (float) Math.Floor(vec.Y), (float) Math.Floor(vec.Z), (float) Math.Floor(vec.W)); } /// Per-component round of 4-vector. [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector4 Round(in Vector4 vec) { return new Vector4((float) Math.Round(vec.X), (float) Math.Round(vec.Y), (float) Math.Round(vec.Z), (float) Math.Round(vec.W)); } /// Per-component ceil of 4-vector. [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector4 Ceil(in Vector4 vec) { return new Vector4((float) Math.Ceiling(vec.X), (float) Math.Ceiling(vec.Y), (float) Math.Ceiling(vec.Z), (float) Math.Ceiling(vec.W)); } public Vector2 Xy => new Vector2(X, Y); public Vector2 Zw => new Vector2(Z, W); /// X coordinate. public float X; /// Y coordinate. public float Y; /// Z coordinate. public float Z; /// W coordinate. public float W; /// Zero vector. static Vector4 Zero; /// (1,1,1,1) vector. static Vector4 One = new Vector4(1, 1, 1, 1); }; }
// 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.CompilerServices; using System.Runtime.InteropServices; using System.Text; using Xunit; namespace System.IO.MemoryMappedFiles.Tests { /// <summary>Base class from which all of the memory mapped files test classes derive.</summary> public abstract partial class MemoryMappedFilesTestBase : FileCleanupTestBase { /// <summary>Gets whether named maps are supported by the current platform.</summary> protected static bool MapNamesSupported { get { return RuntimeInformation.IsOSPlatform(OSPlatform.Windows); } } /// <summary>Creates a map name guaranteed to be unique.</summary> protected static string CreateUniqueMapName() { return Guid.NewGuid().ToString("N"); } /// <summary>Creates a map name guaranteed to be unique and contain only whitespace characters.</summary> protected static string CreateUniqueWhitespaceMapName() { var data = Guid.NewGuid().ToByteArray(); Span<char> s = stackalloc char[data.Length * 4]; for (int i = 0; i < data.Length; i++) { byte b = data[i]; s[i] = s_fourWhitespaceCharacters[b & 0x3]; s[i + 1] = s_fourWhitespaceCharacters[(b & 0xC) >> 2]; s[i + 2] = s_fourWhitespaceCharacters[(b & 0x30) >> 4]; s[i + 3] = s_fourWhitespaceCharacters[(b & 0xC0) >> 6]; } return new string(s); } /// <summary>An array of four whitespace characters.</summary> private static readonly char[] s_fourWhitespaceCharacters = { ' ', '\t', '\r', '\n' }; /// <summary>Creates a set of valid map names to use to test various map creation scenarios.</summary> public static IEnumerable<object[]> CreateValidMapNames() // often used with [MemberData] { // Normal name yield return new object[] { CreateUniqueMapName() }; // Name that's entirely whitespace yield return new object[] { CreateUniqueWhitespaceMapName() }; // Names with prefixes recognized by Windows yield return new object[] { "local/" + CreateUniqueMapName() }; yield return new object[] { "global/" + CreateUniqueMapName() }; // Very long name yield return new object[] { CreateUniqueMapName() + new string('a', 1000) }; } /// <summary> /// Creates and yields a variety of different maps, suitable for a wide range of testing of /// views created from maps. /// </summary> protected IEnumerable<MemoryMappedFile> CreateSampleMaps( int capacity = 4096, MemoryMappedFileAccess access = MemoryMappedFileAccess.ReadWrite, [CallerMemberName]string fileName = null, [CallerLineNumber] int lineNumber = 0) { yield return MemoryMappedFile.CreateNew(null, capacity, access); yield return MemoryMappedFile.CreateFromFile(Path.Combine(TestDirectory, Guid.NewGuid().ToString("N")), FileMode.CreateNew, null, capacity, access); if (MapNamesSupported) { yield return MemoryMappedFile.CreateNew(CreateUniqueMapName(), capacity, access); yield return MemoryMappedFile.CreateFromFile(GetTestFilePath(null, fileName, lineNumber), FileMode.CreateNew, CreateUniqueMapName(), capacity, access); } } /// <summary>Performs basic verification on a map.</summary> /// <param name="mmf">The map.</param> /// <param name="expectedCapacity">The capacity that was specified to create the map.</param> /// <param name="expectedAccess">The access specified to create the map.</param> /// <param name="expectedInheritability">The inheritability specified to create the map.</param> protected static void ValidateMemoryMappedFile(MemoryMappedFile mmf, long expectedCapacity, MemoryMappedFileAccess expectedAccess = MemoryMappedFileAccess.ReadWrite, HandleInheritability expectedInheritability = HandleInheritability.None) { // Validate that we got a MemoryMappedFile object and that its handle is valid Assert.NotNull(mmf); Assert.NotNull(mmf.SafeMemoryMappedFileHandle); Assert.Same(mmf.SafeMemoryMappedFileHandle, mmf.SafeMemoryMappedFileHandle); Assert.False(mmf.SafeMemoryMappedFileHandle.IsClosed); Assert.False(mmf.SafeMemoryMappedFileHandle.IsInvalid); AssertInheritability(mmf.SafeMemoryMappedFileHandle, expectedInheritability); // Create and validate one or more views from the map if (IsReadable(expectedAccess) && IsWritable(expectedAccess)) { CreateAndValidateViews(mmf, expectedCapacity, MemoryMappedFileAccess.Read); CreateAndValidateViews(mmf, expectedCapacity, MemoryMappedFileAccess.Write); CreateAndValidateViews(mmf, expectedCapacity, MemoryMappedFileAccess.ReadWrite); } else if (IsWritable(expectedAccess)) { CreateAndValidateViews(mmf, expectedCapacity, MemoryMappedFileAccess.Write); } else if (IsReadable(expectedAccess)) { CreateAndValidateViews(mmf, expectedCapacity, MemoryMappedFileAccess.Read); } else { Assert.Throws<UnauthorizedAccessException>(() => mmf.CreateViewAccessor(0, expectedCapacity, MemoryMappedFileAccess.Read)); Assert.Throws<UnauthorizedAccessException>(() => mmf.CreateViewAccessor(0, expectedCapacity, MemoryMappedFileAccess.Write)); Assert.Throws<UnauthorizedAccessException>(() => mmf.CreateViewAccessor(0, expectedCapacity, MemoryMappedFileAccess.ReadWrite)); } } /// <summary>Creates and validates a view accessor and a view stream from the map.</summary> /// <param name="mmf">The map.</param> /// <param name="capacity">The capacity to use when creating the view.</param> /// <param name="access">The access to use when creating the view.</param> private static void CreateAndValidateViews(MemoryMappedFile mmf, long capacity, MemoryMappedFileAccess access) { using (MemoryMappedViewAccessor accessor = mmf.CreateViewAccessor(0, capacity, access)) { ValidateMemoryMappedViewAccessor(accessor, capacity, access); } using (MemoryMappedViewStream stream = mmf.CreateViewStream(0, capacity, access)) { ValidateMemoryMappedViewStream(stream, capacity, access); } } /// <summary>Performs validation on a view accessor.</summary> /// <param name="accessor">The accessor to validate.</param> /// <param name="capacity">The capacity specified when creating the accessor.</param> /// <param name="access">The access specified when creating the accessor.</param> protected static void ValidateMemoryMappedViewAccessor(MemoryMappedViewAccessor accessor, long capacity, MemoryMappedFileAccess access) { // Validate the accessor and its handle Assert.NotNull(accessor); Assert.NotNull(accessor.SafeMemoryMappedViewHandle); Assert.Same(accessor.SafeMemoryMappedViewHandle, accessor.SafeMemoryMappedViewHandle); // Ensure its properties match the criteria specified when it was created Assert.InRange(capacity, 0, accessor.Capacity); // the capacity may be rounded up to page size, so all we guarantee is that the accessor's capacity >= capacity Assert.Equal(0, accessor.PointerOffset); // If it's supposed to be readable, try to read from it. // Otherwise, verify we can't. if (IsReadable(access)) { Assert.True(accessor.CanRead); Assert.Equal(0, accessor.ReadByte(0)); Assert.Equal(0, accessor.ReadByte(capacity - 1)); } else { Assert.False(accessor.CanRead); Assert.Throws<NotSupportedException>(() => accessor.ReadByte(0)); } // If it's supposed to be writable, try to write to it if (IsWritable(access) || access == MemoryMappedFileAccess.CopyOnWrite) { Assert.True(accessor.CanWrite); // Write some data accessor.Write(0, (byte)42); accessor.Write(capacity - 1, (byte)42); // If possible, ensure we can read it back if (IsReadable(access)) { Assert.Equal(42, accessor.ReadByte(0)); Assert.Equal(42, accessor.ReadByte(capacity - 1)); } // Write 0 back where we wrote data accessor.Write(0, (byte)0); accessor.Write(capacity - 1, (byte)0); } else { Assert.False(accessor.CanWrite); Assert.Throws<NotSupportedException>(() => accessor.Write(0, (byte)0)); } } /// <summary>Performs validation on a view stream.</summary> /// <param name="stream">The stream to verify.</param> /// <param name="capacity">The capacity specified when the stream was created.</param> /// <param name="access">The access specified when the stream was created.</param> protected static void ValidateMemoryMappedViewStream(MemoryMappedViewStream stream, long capacity, MemoryMappedFileAccess access) { // Validate the stream and its handle Assert.NotNull(stream); Assert.NotNull(stream.SafeMemoryMappedViewHandle); Assert.Same(stream.SafeMemoryMappedViewHandle, stream.SafeMemoryMappedViewHandle); // Validate its properties report the values they should Assert.InRange(capacity, 0, stream.Length); // the capacity may be rounded up to page size, so all we guarantee is that the stream's length >= capacity // If it's supposed to be readable, read from it. if (IsReadable(access)) { Assert.True(stream.CanRead); // Seek to the beginning stream.Position = 0; Assert.Equal(0, stream.Position); // Read a byte Assert.Equal(0, stream.ReadByte()); Assert.Equal(1, stream.Position); // Seek to just before the end Assert.Equal(capacity - 1, stream.Seek(capacity - 1, SeekOrigin.Begin)); // Read another byte Assert.Equal(0, stream.ReadByte()); Assert.Equal(capacity, stream.Position); } else { Assert.False(stream.CanRead); } // If it's supposed to be writable, try to write to it. if (IsWritable(access) || access == MemoryMappedFileAccess.CopyOnWrite) { Assert.True(stream.CanWrite); // Seek to the beginning, write a byte, seek to the almost end, write a byte stream.Position = 0; stream.WriteByte(42); stream.Position = stream.Length - 1; stream.WriteByte(42); // Verify the written bytes if possible if (IsReadable(access)) { stream.Position = 0; Assert.Equal(42, stream.ReadByte()); stream.Position = stream.Length - 1; Assert.Equal(42, stream.ReadByte()); } // Reset the written bytes stream.Position = 0; stream.WriteByte(0); stream.Position = stream.Length - 1; stream.WriteByte(0); } else { Assert.False(stream.CanWrite); } } /// <summary>Gets whether the specified access implies writability.</summary> protected static bool IsWritable(MemoryMappedFileAccess access) { switch (access) { case MemoryMappedFileAccess.Write: case MemoryMappedFileAccess.ReadWrite: case MemoryMappedFileAccess.ReadWriteExecute: return true; default: return false; } } /// <summary>Gets whether the specified access implies readability.</summary> protected static bool IsReadable(MemoryMappedFileAccess access) { switch (access) { case MemoryMappedFileAccess.CopyOnWrite: case MemoryMappedFileAccess.Read: case MemoryMappedFileAccess.ReadExecute: case MemoryMappedFileAccess.ReadWrite: case MemoryMappedFileAccess.ReadWriteExecute: return true; default: return false; } } } }
/* * 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 log4net.Config; using NUnit.Framework; using NUnit.Framework.Constraints; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Tests.Common; using System.Data.Common; using log4net; // DBMS-specific: using MySql.Data.MySqlClient; using OpenSim.Data.MySQL; using Mono.Data.Sqlite; using OpenSim.Data.SQLite; namespace OpenSim.Data.Tests { [TestFixture(Description = "Asset store tests (SQLite)")] public class SQLiteAssetTests : AssetTests<SqliteConnection, SQLiteAssetData> { } [TestFixture(Description = "Asset store tests (MySQL)")] public class MySqlAssetTests : AssetTests<MySqlConnection, MySQLAssetData> { } public class AssetTests<TConn, TAssetData> : BasicDataServiceTest<TConn, TAssetData> where TConn : DbConnection, new() where TAssetData : AssetDataBase, new() { TAssetData m_db; public UUID uuid1 = UUID.Random(); public UUID uuid2 = UUID.Random(); public UUID uuid3 = UUID.Random(); public string critter1 = UUID.Random().ToString(); public string critter2 = UUID.Random().ToString(); public string critter3 = UUID.Random().ToString(); public byte[] data1 = new byte[100]; PropertyScrambler<AssetBase> scrambler = new PropertyScrambler<AssetBase>() .DontScramble(x => x.ID) .DontScramble(x => x.Type) .DontScramble(x => x.FullID) .DontScramble(x => x.Metadata.ID) .DontScramble(x => x.Metadata.CreatorID) .DontScramble(x => x.Metadata.ContentType) .DontScramble(x => x.Metadata.FullID) .DontScramble(x => x.Data); protected override void InitService(object service) { ClearDB(); m_db = (TAssetData)service; m_db.Initialise(m_connStr); } private void ClearDB() { DropTables("assets"); ResetMigrations("AssetStore"); } [Test] public void T001_LoadEmpty() { TestHelpers.InMethod(); bool[] exist = m_db.AssetsExist(new[] { uuid1, uuid2, uuid3 }); Assert.IsFalse(exist[0]); Assert.IsFalse(exist[1]); Assert.IsFalse(exist[2]); } [Test] public void T010_StoreReadVerifyAssets() { TestHelpers.InMethod(); AssetBase a1 = new AssetBase(uuid1, "asset one", (sbyte)AssetType.Texture, critter1.ToString()); AssetBase a2 = new AssetBase(uuid2, "asset two", (sbyte)AssetType.Texture, critter2.ToString()); AssetBase a3 = new AssetBase(uuid3, "asset three", (sbyte)AssetType.Texture, critter3.ToString()); a1.Data = data1; a2.Data = data1; a3.Data = data1; scrambler.Scramble(a1); scrambler.Scramble(a2); scrambler.Scramble(a3); m_db.StoreAsset(a1); m_db.StoreAsset(a2); m_db.StoreAsset(a3); AssetBase a1a = m_db.GetAsset(uuid1); Assert.That(a1a, Constraints.PropertyCompareConstraint(a1)); AssetBase a2a = m_db.GetAsset(uuid2); Assert.That(a2a, Constraints.PropertyCompareConstraint(a2)); AssetBase a3a = m_db.GetAsset(uuid3); Assert.That(a3a, Constraints.PropertyCompareConstraint(a3)); scrambler.Scramble(a1a); scrambler.Scramble(a2a); scrambler.Scramble(a3a); m_db.StoreAsset(a1a); m_db.StoreAsset(a2a); m_db.StoreAsset(a3a); AssetBase a1b = m_db.GetAsset(uuid1); Assert.That(a1b, Constraints.PropertyCompareConstraint(a1a)); AssetBase a2b = m_db.GetAsset(uuid2); Assert.That(a2b, Constraints.PropertyCompareConstraint(a2a)); AssetBase a3b = m_db.GetAsset(uuid3); Assert.That(a3b, Constraints.PropertyCompareConstraint(a3a)); bool[] exist = m_db.AssetsExist(new[] { uuid1, uuid2, uuid3 }); Assert.IsTrue(exist[0]); Assert.IsTrue(exist[1]); Assert.IsTrue(exist[2]); List<AssetMetadata> metadatas = m_db.FetchAssetMetadataSet(0, 1000); Assert.That(metadatas.Count >= 3, "FetchAssetMetadataSet() should have returned at least 3 assets!"); // It is possible that the Asset table is filled with data, in which case we don't try to find "our" // assets there: if (metadatas.Count < 1000) { AssetMetadata metadata = metadatas.Find(x => x.FullID == uuid1); Assert.That(metadata.Name, Is.EqualTo(a1b.Name)); Assert.That(metadata.Description, Is.EqualTo(a1b.Description)); Assert.That(metadata.Type, Is.EqualTo(a1b.Type)); Assert.That(metadata.Temporary, Is.EqualTo(a1b.Temporary)); Assert.That(metadata.FullID, Is.EqualTo(a1b.FullID)); } } [Test] public void T020_CheckForWeirdCreatorID() { TestHelpers.InMethod(); // It is expected that eventually the CreatorID might be an arbitrary string (an URI) // rather than a valid UUID (?). This test is to make sure that the database layer does not // attempt to convert CreatorID to GUID, but just passes it both ways as a string. AssetBase a1 = new AssetBase(uuid1, "asset one", (sbyte)AssetType.Texture, critter1); AssetBase a2 = new AssetBase(uuid2, "asset two", (sbyte)AssetType.Texture, "This is not a GUID!"); AssetBase a3 = new AssetBase(uuid3, "asset three", (sbyte)AssetType.Texture, ""); a1.Data = data1; a2.Data = data1; a3.Data = data1; m_db.StoreAsset(a1); m_db.StoreAsset(a2); m_db.StoreAsset(a3); AssetBase a1a = m_db.GetAsset(uuid1); Assert.That(a1a, Constraints.PropertyCompareConstraint(a1)); AssetBase a2a = m_db.GetAsset(uuid2); Assert.That(a2a, Constraints.PropertyCompareConstraint(a2)); AssetBase a3a = m_db.GetAsset(uuid3); Assert.That(a3a, Constraints.PropertyCompareConstraint(a3)); } } }
// ******************************************************************************************************** // Product Name: DotSpatial.Plugins.ShapeEditor.dll // Description: The data access libraries for the DotSpatial project. // ******************************************************************************************************** // The contents of this file are subject to the MIT License (MIT) // you may not use this file except in compliance with the License. You may obtain a copy of the License at // http://dotspatial.codeplex.com/license // // Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF // ANY KIND, either expressed or implied. See the License for the specific language governing rights and // limitations under the License. // // The Original Code is MapWindow.dll // // The Initial Developer of this Original Code is Ted Dunsford. Created 4/10/2009 5:10:05 PM // // Contributor(s): (Open source contributors should list themselves and their modifications here). // // ******************************************************************************************************** using System; using System.Windows.Forms; using DotSpatial.Data; namespace DotSpatial.Plugins.ShapeEditor { /// <summary> /// A Dialog that displays options for feature type when creating a new feature. /// </summary> public class FeatureTypeDialog : Form { private Button _btnCancel; private Button _btnOk; private CheckBox _chkM; private CheckBox _chkZ; private Label label1; private TextBox _tbFilename; private Label label2; private Button _btnSelectFilename; private SaveFileDialog _sfdFilename; private ComboBox _cmbFeatureType; #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FeatureTypeDialog)); this._btnOk = new System.Windows.Forms.Button(); this._btnCancel = new System.Windows.Forms.Button(); this._cmbFeatureType = new System.Windows.Forms.ComboBox(); this._chkM = new System.Windows.Forms.CheckBox(); this._chkZ = new System.Windows.Forms.CheckBox(); this.label1 = new System.Windows.Forms.Label(); this._tbFilename = new System.Windows.Forms.TextBox(); this.label2 = new System.Windows.Forms.Label(); this._btnSelectFilename = new System.Windows.Forms.Button(); this._sfdFilename = new System.Windows.Forms.SaveFileDialog(); this.SuspendLayout(); // // _btnOk // resources.ApplyResources(this._btnOk, "_btnOk"); this._btnOk.DialogResult = System.Windows.Forms.DialogResult.OK; this._btnOk.Name = "_btnOk"; this._btnOk.UseVisualStyleBackColor = true; this._btnOk.Click += new System.EventHandler(this.OkButton_Click); // // _btnCancel // resources.ApplyResources(this._btnCancel, "_btnCancel"); this._btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; this._btnCancel.Name = "_btnCancel"; this._btnCancel.UseVisualStyleBackColor = true; this._btnCancel.Click += new System.EventHandler(this.CancelButton_Click); // // _cmbFeatureType // resources.ApplyResources(this._cmbFeatureType, "_cmbFeatureType"); this._cmbFeatureType.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this._cmbFeatureType.FormattingEnabled = true; this._cmbFeatureType.Items.AddRange(new object[] { resources.GetString("_cmbFeatureType.Items"), resources.GetString("_cmbFeatureType.Items1"), resources.GetString("_cmbFeatureType.Items2"), resources.GetString("_cmbFeatureType.Items3")}); this._cmbFeatureType.Name = "_cmbFeatureType"; // // _chkM // resources.ApplyResources(this._chkM, "_chkM"); this._chkM.Name = "_chkM"; this._chkM.UseVisualStyleBackColor = true; // // _chkZ // resources.ApplyResources(this._chkZ, "_chkZ"); this._chkZ.Name = "_chkZ"; this._chkZ.UseVisualStyleBackColor = true; // // label1 // resources.ApplyResources(this.label1, "label1"); this.label1.Name = "label1"; // // _tbFilename // resources.ApplyResources(this._tbFilename, "_tbFilename"); this._tbFilename.Name = "_tbFilename"; // // label2 // resources.ApplyResources(this.label2, "label2"); this.label2.Name = "label2"; // // _btnSelectFilename // resources.ApplyResources(this._btnSelectFilename, "_btnSelectFilename"); this._btnSelectFilename.Name = "_btnSelectFilename"; this._btnSelectFilename.UseVisualStyleBackColor = true; this._btnSelectFilename.Click += new System.EventHandler(this._btnSelectFilename_Click); // // _sfdFilename // this._sfdFilename.DefaultExt = "*.shp"; resources.ApplyResources(this._sfdFilename, "_sfdFilename"); // // FeatureTypeDialog // resources.ApplyResources(this, "$this"); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Controls.Add(this._btnSelectFilename); this.Controls.Add(this._tbFilename); this.Controls.Add(this.label2); this.Controls.Add(this.label1); this.Controls.Add(this._chkZ); this.Controls.Add(this._chkM); this.Controls.Add(this._cmbFeatureType); this.Controls.Add(this._btnCancel); this.Controls.Add(this._btnOk); this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "FeatureTypeDialog"; this.ShowIcon = false; this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide; this.ResumeLayout(false); this.PerformLayout(); } #endregion #region Constructors /// <summary> /// Initializes a new instance of the FeatureTypeDialog class. /// </summary> public FeatureTypeDialog() { InitializeComponent(); _cmbFeatureType.SelectedIndex = 0; } #endregion #region Methods #endregion #region Properties /// <summary> /// Gets the feature type chosen by this dialog. /// </summary> public FeatureType FeatureType { get { switch (_cmbFeatureType.SelectedIndex) { case 0: return FeatureType.Point; case 1: return FeatureType.Line; case 2: return FeatureType.Polygon; case 3: return FeatureType.MultiPoint; } return FeatureType.Unspecified; } } /// <summary> /// Gets the Coordinate type for this dialog. /// </summary> public CoordinateType CoordinateType { get { if (_chkZ.Checked) { return CoordinateType.Z; } if (_chkM.Checked) { return CoordinateType.M; } return CoordinateType.Regular; } } /// <summary> /// Gets the filename which should be used to save the layer to file. /// </summary> public String Filename { get { return _tbFilename.Text.Trim(); } } #endregion #region Events #endregion #region Event Handlers private void OkButton_Click(object sender, EventArgs e) { if (!string.IsNullOrWhiteSpace(_tbFilename.Text) && !_tbFilename.Text.ToLower().EndsWith(".shp")) _tbFilename.Text += ".shp"; Close(); } private void CancelButton_Click(object sender, EventArgs e) { Close(); } /// <summary> /// Opens the SafeFileDialog and copys the selected filename to _tbFilename. /// </summary> private void _btnSelectFilename_Click(object sender, EventArgs e) { if (_sfdFilename.ShowDialog() == DialogResult.OK && !String.IsNullOrWhiteSpace(_sfdFilename.FileName)) { _tbFilename.Text = _sfdFilename.FileName; } } #endregion } }
#region PDFsharp - A .NET library for processing PDF // // Authors: // Stefan Lange (mailto:Stefan.Lange@pdfsharp.com) // // Copyright (c) 2005-2009 empira Software GmbH, Cologne (Germany) // // http://www.pdfsharp.com // http://sourceforge.net/projects/pdfsharp // // 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.Diagnostics; using System.Runtime.InteropServices; using System.ComponentModel; using System.IO; #if GDI using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging; #endif #if WPF using System.Windows.Media; #endif using PdfSharp.Internal; using PdfSharp.Drawing.Pdf; using PdfSharp.Fonts.OpenType; using PdfSharp.Pdf; using PdfSharp.Pdf.IO; using PdfSharp.Pdf.Advanced; using PdfSharp.Pdf.Filters; using PdfSharp.Pdf.Internal; namespace PdfSharp.Drawing { /// <summary> /// Represents a so called 'PDF form external object', which is typically an imported page of an external /// PDF document. XPdfForm objects are used like images to draw an existing PDF page of an external /// document in the current document. XPdfForm objects can only be placed in PDF documents. If you try /// to draw them using a XGraphics based on an GDI+ context no action is taken if no placeholder image /// is specified. Otherwise the place holder is drawn. /// </summary> public class XPdfForm : XForm { /// <summary> /// Initializes a new instance of the XPdfForm class from the specified path to an external PDF document. /// Although PDFsharp internally caches XPdfForm objects it is recommended to reuse XPdfForm objects /// in your code and change the PageNumber property if more than one page is needed form the external /// document. Furthermore, because XPdfForm can occupy very much memory, it is recommended to /// dispose XPdfForm objects if not needed anymore. /// </summary> internal XPdfForm(string path) { int pageNumber; path = ExtractPageNumber(path, out pageNumber); path = Path.GetFullPath(path); if (!File.Exists(path)) throw new FileNotFoundException(PSSR.FileNotFound(path), path); if (PdfReader.TestPdfFile(path) == 0) throw new ArgumentException("The specified file has no valid PDF file header.", "path"); this.path = path; if (pageNumber != 0) PageNumber = pageNumber; } /// <summary> /// Initializes a new instance of the <see cref="XPdfForm"/> class from a stream. /// </summary> /// <param name="stream">The stream.</param> internal XPdfForm(Stream stream) { // Create a dummy unique path this.path = "*" + Guid.NewGuid().ToString("B"); if (PdfReader.TestPdfFile(stream) == 0) throw new ArgumentException("The specified stream has no valid PDF file header.", "stream"); this.externalDocument = PdfReader.Open(stream); } /// <summary> /// Creates an XPdfForm from a file. /// </summary> public static new XPdfForm FromFile(string path) { // TODO: Same file should return same object (that's why the function is static). return new XPdfForm(path); } /// <summary> /// Creates an XPdfForm from a stream. /// </summary> public static XPdfForm FromStream(Stream stream) { return new XPdfForm(stream); } /* void Initialize() { // ImageFormat has no overridden Equals... } */ /// <summary> /// Sets the form in the state FormState.Finished. /// </summary> internal override void Finish() { if (this.formState == FormState.NotATemplate || this.formState == FormState.Finished) return; base.Finish(); //if (this.gfx.metafile != null) // this.image = this.gfx.metafile; //Debug.Assert(this.fromState == FormState.Created || this.fromState == FormState.UnderConstruction); //this.fromState = FormState.Finished; //this.gfx.Dispose(); //this.gfx = null; //if (this.pdfRenderer != null) //{ // this.pdfForm.Stream = new PdfDictionary.PdfStream(PdfEncoders.RawEncoding.GetBytes(this.pdfRenderer.GetContent()), this.pdfForm); // if (this.document.Options.CompressContentStreams) // { // this.pdfForm.Stream.Value = Filtering.FlateDecode.Encode(this.pdfForm.Stream.Value); // this.pdfForm.Elements["/Filter"] = new PdfName("/FlateDecode"); // } // int length = this.pdfForm.Stream.Length; // this.pdfForm.Elements.SetInteger("/Length", length); //} } /// <summary> /// Frees the memory occupied by the underlying imported PDF document, even if other XPdfForm objects /// refer to this document. A reuse of this object doesn't fail, because the underlying PDF document /// is re-imported if necessary. /// </summary> // TODO: NYI: Dispose protected override void Dispose(bool disposing) { if (!this.disposed) { this.disposed = true; try { if (disposing) { //... } if (this.externalDocument != null) PdfDocument.Tls.DetachDocument(this.externalDocument.Handle); //... } finally { base.Dispose(disposing); } } } bool disposed; /// <summary> /// Gets or sets an image that is used for drawing if the current XGraphics object cannot handle /// PDF forms. A place holder is useful for showing a preview of a page on the display, because /// PDFsharp cannot render native PDF objects. /// </summary> public XImage PlaceHolder { get { return this.placeHolder; } set { this.placeHolder = value; } } XImage placeHolder; /// <summary> /// Gets the underlying PdfPage (if one exists). /// </summary> public PdfPage Page { get { if (IsTemplate) return null; PdfPage page = ExternalDocument.Pages[this.pageNumber - 1]; return page; } } /// <summary> /// Gets the number of pages in the PDF form. /// </summary> public int PageCount { get { if (IsTemplate) return 1; if (this.pageCount == -1) this.pageCount = ExternalDocument.Pages.Count; return this.pageCount; } } int pageCount = -1; /// <summary> /// Gets the width in point of the page identified by the property PageNumber. /// </summary> //[Obsolete("Use either PixelWidth or PointWidth. Temporarily obsolete because of rearrangements for WPF.")] //public override double Width //{ // get // { // PdfPage page = ExternalDocument.Pages[this.pageNumber - 1]; // return page.Width; // } //} /// <summary> /// Gets the height in point of the page identified by the property PageNumber. /// </summary> //[Obsolete("Use either PixelHeight or PointHeight. Temporarily obsolete because of rearrangements for WPF.")] //public override double Height //{ // get // { // PdfPage page = ExternalDocument.Pages[this.pageNumber - 1]; // return page.Height; // } //} /// <summary> /// Gets the width in point of the page identified by the property PageNumber. /// </summary> public override double PointWidth { get { PdfPage page = ExternalDocument.Pages[this.pageNumber - 1]; return page.Width; } } /// <summary> /// Gets the height in point of the page identified by the property PageNumber. /// </summary> public override double PointHeight { get { PdfPage page = ExternalDocument.Pages[this.pageNumber - 1]; return page.Height; } } /// <summary> /// Gets the width in point of the page identified by the property PageNumber. /// </summary> public override int PixelWidth { get { //PdfPage page = ExternalDocument.Pages[this.pageNumber - 1]; //return (int)page.Width; return DoubleUtil.DoubleToInt(PointWidth); } } /// <summary> /// Gets the height in point of the page identified by the property PageNumber. /// </summary> public override int PixelHeight { get { //PdfPage page = ExternalDocument.Pages[this.pageNumber - 1]; //return (int)page.Height; return DoubleUtil.DoubleToInt(PointHeight); } } /// <summary> /// Get the size of the page identified by the property PageNumber. /// </summary> public override XSize Size { get { PdfPage page = ExternalDocument.Pages[this.pageNumber - 1]; return new XSize(page.Width, page.Height); } } /// <summary> /// Gets or sets the transformation matrix. /// </summary> public override XMatrix Transform { get { return this.transform; } set { if (this.transform != value) { // discard PdfFromXObject when Transform changed this.pdfForm = null; this.transform = value; } } } /// <summary> /// Gets or sets the page number in the external PDF document this object refers to. The page number /// is one-based, i.e. it is in the range from 1 to PageCount. The default value is 1. /// </summary> public int PageNumber { get { return this.pageNumber; } set { if (IsTemplate) throw new InvalidOperationException("The page number of an XPdfForm template cannot be modified."); if (this.pageNumber != value) { this.pageNumber = value; // dispose PdfFromXObject when number has changed this.pdfForm = null; } } } int pageNumber = 1; /// <summary> /// Gets or sets the page index in the external PDF document this object refers to. The page index /// is zero-based, i.e. it is in the range from 0 to PageCount - 1. The default value is 0. /// </summary> public int PageIndex { get { return PageNumber - 1; } set { PageNumber = value + 1; } } /// <summary> /// Gets the underlying document from which pages are imported. /// </summary> internal PdfDocument ExternalDocument { // The problem is that you can ask an XPdfForm about the number of its pages before it was // drawn the first time. At this moment the XPdfForm doesn't know the document where it will // be later draw on one of its pages. To prevent the import of the same document more than // once, all imported documents of a thread are cached. The cache is local to the current // thread and not to the appdomain, because I won't get problems in a multi-thread environment // that I don't understand. get { if (IsTemplate) throw new InvalidOperationException("This XPdfForm is a template and not an imported PDF page; therefore it has no external document."); if (this.externalDocument == null) this.externalDocument = PdfDocument.Tls.GetDocument(path); return this.externalDocument; } } internal PdfDocument externalDocument; /// <summary> /// Extracts the page number if the path has the form 'MyFile.pdf#123' and returns /// the actual path without the number sign and the following digits. /// </summary> public static string ExtractPageNumber(string path, out int pageNumber) { if (path == null) throw new ArgumentNullException("path"); pageNumber = 0; int length = path.Length; if (length != 0) { length--; if (Char.IsDigit(path, length)) { while (Char.IsDigit(path, length) && length >= 0) length--; if (length > 0 && path[length] == '#') { // must have at least one dot left of colon to distinguish from e.g. '#123' if (path.IndexOf('.') != -1) { pageNumber = Int32.Parse(path.Substring(length + 1)); path = path.Substring(0, length); } } } } return path; } } }
#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) using System; using Org.BouncyCastle.Crypto.Macs; using Org.BouncyCastle.Crypto.Modes.Gcm; using Org.BouncyCastle.Crypto.Parameters; using Org.BouncyCastle.Crypto.Utilities; using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Crypto.Modes { /// <summary> /// Implements the Galois/Counter mode (GCM) detailed in /// NIST Special Publication 800-38D. /// </summary> public class GcmBlockCipher : IAeadBlockCipher { private const int BlockSize = 16; private readonly IBlockCipher cipher; private readonly IGcmMultiplier multiplier; private IGcmExponentiator exp; // These fields are set by Init and not modified by processing private bool forEncryption; private int macSize; private byte[] nonce; private byte[] initialAssociatedText; private byte[] H; private byte[] J0; // These fields are modified during processing private byte[] bufBlock; private byte[] macBlock; private byte[] S, S_at, S_atPre; private byte[] counter; private int bufOff; private ulong totalLength; private byte[] atBlock; private int atBlockPos; private ulong atLength; private ulong atLengthPre; public GcmBlockCipher( IBlockCipher c) : this(c, null) { } public GcmBlockCipher( IBlockCipher c, IGcmMultiplier m) { if (c.GetBlockSize() != BlockSize) throw new ArgumentException("cipher required with a block size of " + BlockSize + "."); if (m == null) { // TODO Consider a static property specifying default multiplier m = new Tables8kGcmMultiplier(); } this.cipher = c; this.multiplier = m; } public virtual string AlgorithmName { get { return cipher.AlgorithmName + "/GCM"; } } public IBlockCipher GetUnderlyingCipher() { return cipher; } public virtual int GetBlockSize() { return BlockSize; } /// <remarks> /// MAC sizes from 32 bits to 128 bits (must be a multiple of 8) are supported. The default is 128 bits. /// Sizes less than 96 are not recommended, but are supported for specialized applications. /// </remarks> public virtual void Init( bool forEncryption, ICipherParameters parameters) { this.forEncryption = forEncryption; this.macBlock = null; KeyParameter keyParam; if (parameters is AeadParameters) { AeadParameters param = (AeadParameters)parameters; nonce = param.GetNonce(); initialAssociatedText = param.GetAssociatedText(); int macSizeBits = param.MacSize; if (macSizeBits < 32 || macSizeBits > 128 || macSizeBits % 8 != 0) { throw new ArgumentException("Invalid value for MAC size: " + macSizeBits); } macSize = macSizeBits / 8; keyParam = param.Key; } else if (parameters is ParametersWithIV) { ParametersWithIV param = (ParametersWithIV)parameters; nonce = param.GetIV(); initialAssociatedText = null; macSize = 16; keyParam = (KeyParameter)param.Parameters; } else { throw new ArgumentException("invalid parameters passed to GCM"); } int bufLength = forEncryption ? BlockSize : (BlockSize + macSize); this.bufBlock = new byte[bufLength]; if (nonce == null || nonce.Length < 1) { throw new ArgumentException("IV must be at least 1 byte"); } // TODO Restrict macSize to 16 if nonce length not 12? // Cipher always used in forward mode // if keyParam is null we're reusing the last key. if (keyParam != null) { cipher.Init(true, keyParam); this.H = new byte[BlockSize]; cipher.ProcessBlock(H, 0, H, 0); // if keyParam is null we're reusing the last key and the multiplier doesn't need re-init multiplier.Init(H); exp = null; } else if (this.H == null) { throw new ArgumentException("Key must be specified in initial init"); } this.J0 = new byte[BlockSize]; if (nonce.Length == 12) { Array.Copy(nonce, 0, J0, 0, nonce.Length); this.J0[BlockSize - 1] = 0x01; } else { gHASH(J0, nonce, nonce.Length); byte[] X = new byte[BlockSize]; Pack.UInt64_To_BE((ulong)nonce.Length * 8UL, X, 8); gHASHBlock(J0, X); } this.S = new byte[BlockSize]; this.S_at = new byte[BlockSize]; this.S_atPre = new byte[BlockSize]; this.atBlock = new byte[BlockSize]; this.atBlockPos = 0; this.atLength = 0; this.atLengthPre = 0; this.counter = Arrays.Clone(J0); this.bufOff = 0; this.totalLength = 0; if (initialAssociatedText != null) { ProcessAadBytes(initialAssociatedText, 0, initialAssociatedText.Length); } } public virtual byte[] GetMac() { return Arrays.Clone(macBlock); } public virtual int GetOutputSize( int len) { int totalData = len + bufOff; if (forEncryption) { return totalData + macSize; } return totalData < macSize ? 0 : totalData - macSize; } public virtual int GetUpdateOutputSize( int len) { int totalData = len + bufOff; if (!forEncryption) { if (totalData < macSize) { return 0; } totalData -= macSize; } return totalData - totalData % BlockSize; } public virtual void ProcessAadByte(byte input) { atBlock[atBlockPos] = input; if (++atBlockPos == BlockSize) { // Hash each block as it fills gHASHBlock(S_at, atBlock); atBlockPos = 0; atLength += BlockSize; } } public virtual void ProcessAadBytes(byte[] inBytes, int inOff, int len) { for (int i = 0; i < len; ++i) { atBlock[atBlockPos] = inBytes[inOff + i]; if (++atBlockPos == BlockSize) { // Hash each block as it fills gHASHBlock(S_at, atBlock); atBlockPos = 0; atLength += BlockSize; } } } private void InitCipher() { if (atLength > 0) { Array.Copy(S_at, 0, S_atPre, 0, BlockSize); atLengthPre = atLength; } // Finish hash for partial AAD block if (atBlockPos > 0) { gHASHPartial(S_atPre, atBlock, 0, atBlockPos); atLengthPre += (uint)atBlockPos; } if (atLengthPre > 0) { Array.Copy(S_atPre, 0, S, 0, BlockSize); } } public virtual int ProcessByte( byte input, byte[] output, int outOff) { bufBlock[bufOff] = input; if (++bufOff == bufBlock.Length) { OutputBlock(output, outOff); return BlockSize; } return 0; } public virtual int ProcessBytes( byte[] input, int inOff, int len, byte[] output, int outOff) { if (input.Length < (inOff + len)) throw new DataLengthException("Input buffer too short"); int resultLen = 0; for (int i = 0; i < len; ++i) { bufBlock[bufOff] = input[inOff + i]; if (++bufOff == bufBlock.Length) { OutputBlock(output, outOff + resultLen); resultLen += BlockSize; } } return resultLen; } private void OutputBlock(byte[] output, int offset) { Check.OutputLength(output, offset, BlockSize, "Output buffer too short"); if (totalLength == 0) { InitCipher(); } gCTRBlock(bufBlock, output, offset); if (forEncryption) { bufOff = 0; } else { Array.Copy(bufBlock, BlockSize, bufBlock, 0, macSize); bufOff = macSize; } } public int DoFinal(byte[] output, int outOff) { if (totalLength == 0) { InitCipher(); } int extra = bufOff; if (forEncryption) { Check.OutputLength(output, outOff, extra + macSize, "Output buffer too short"); } else { if (extra < macSize) throw new InvalidCipherTextException("data too short"); extra -= macSize; Check.OutputLength(output, outOff, extra, "Output buffer too short"); } if (extra > 0) { gCTRPartial(bufBlock, 0, extra, output, outOff); } atLength += (uint)atBlockPos; if (atLength > atLengthPre) { /* * Some AAD was sent after the cipher started. We determine the difference b/w the hash value * we actually used when the cipher started (S_atPre) and the final hash value calculated (S_at). * Then we carry this difference forward by multiplying by H^c, where c is the number of (full or * partial) cipher-text blocks produced, and adjust the current hash. */ // Finish hash for partial AAD block if (atBlockPos > 0) { gHASHPartial(S_at, atBlock, 0, atBlockPos); } // Find the difference between the AAD hashes if (atLengthPre > 0) { GcmUtilities.Xor(S_at, S_atPre); } // Number of cipher-text blocks produced long c = (long)(((totalLength * 8) + 127) >> 7); // Calculate the adjustment factor byte[] H_c = new byte[16]; if (exp == null) { exp = new Tables1kGcmExponentiator(); exp.Init(H); } exp.ExponentiateX(c, H_c); // Carry the difference forward GcmUtilities.Multiply(S_at, H_c); // Adjust the current hash GcmUtilities.Xor(S, S_at); } // Final gHASH byte[] X = new byte[BlockSize]; Pack.UInt64_To_BE(atLength * 8UL, X, 0); Pack.UInt64_To_BE(totalLength * 8UL, X, 8); gHASHBlock(S, X); // T = MSBt(GCTRk(J0,S)) byte[] tag = new byte[BlockSize]; cipher.ProcessBlock(J0, 0, tag, 0); GcmUtilities.Xor(tag, S); int resultLen = extra; // We place into macBlock our calculated value for T this.macBlock = new byte[macSize]; Array.Copy(tag, 0, macBlock, 0, macSize); if (forEncryption) { // Append T to the message Array.Copy(macBlock, 0, output, outOff + bufOff, macSize); resultLen += macSize; } else { // Retrieve the T value from the message and compare to calculated one byte[] msgMac = new byte[macSize]; Array.Copy(bufBlock, extra, msgMac, 0, macSize); if (!Arrays.ConstantTimeAreEqual(this.macBlock, msgMac)) throw new InvalidCipherTextException("mac check in GCM failed"); } Reset(false); return resultLen; } public virtual void Reset() { Reset(true); } private void Reset( bool clearMac) { cipher.Reset(); S = new byte[BlockSize]; S_at = new byte[BlockSize]; S_atPre = new byte[BlockSize]; atBlock = new byte[BlockSize]; atBlockPos = 0; atLength = 0; atLengthPre = 0; counter = Arrays.Clone(J0); bufOff = 0; totalLength = 0; if (bufBlock != null) { Arrays.Fill(bufBlock, 0); } if (clearMac) { macBlock = null; } if (initialAssociatedText != null) { ProcessAadBytes(initialAssociatedText, 0, initialAssociatedText.Length); } } private void gCTRBlock(byte[] block, byte[] output, int outOff) { byte[] tmp = GetNextCounterBlock(); GcmUtilities.Xor(tmp, block); Array.Copy(tmp, 0, output, outOff, BlockSize); gHASHBlock(S, forEncryption ? tmp : block); totalLength += BlockSize; } private void gCTRPartial(byte[] buf, int off, int len, byte[] output, int outOff) { byte[] tmp = GetNextCounterBlock(); GcmUtilities.Xor(tmp, buf, off, len); Array.Copy(tmp, 0, output, outOff, len); gHASHPartial(S, forEncryption ? tmp : buf, 0, len); totalLength += (uint)len; } private void gHASH(byte[] Y, byte[] b, int len) { for (int pos = 0; pos < len; pos += BlockSize) { int num = System.Math.Min(len - pos, BlockSize); gHASHPartial(Y, b, pos, num); } } private void gHASHBlock(byte[] Y, byte[] b) { GcmUtilities.Xor(Y, b); multiplier.MultiplyH(Y); } private void gHASHPartial(byte[] Y, byte[] b, int off, int len) { GcmUtilities.Xor(Y, b, off, len); multiplier.MultiplyH(Y); } private byte[] GetNextCounterBlock() { for (int i = 15; i >= 12; --i) { if (++counter[i] != 0) break; } byte[] tmp = new byte[BlockSize]; // TODO Sure would be nice if ciphers could operate on int[] cipher.ProcessBlock(counter, 0, tmp, 0); return tmp; } } } #endif
using System; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Xml; using System.Xml.Serialization; using SubSonic; using SubSonic.Utilities; namespace DalSic { /// <summary> /// Strongly-typed collection for the PnPacPap class. /// </summary> [Serializable] public partial class PnPacPapCollection : ActiveList<PnPacPap, PnPacPapCollection> { public PnPacPapCollection() {} /// <summary> /// Filters an existing collection based on the set criteria. This is an in-memory filter /// Thanks to developingchris for this! /// </summary> /// <returns>PnPacPapCollection</returns> public PnPacPapCollection Filter() { for (int i = this.Count - 1; i > -1; i--) { PnPacPap o = this[i]; foreach (SubSonic.Where w in this.wheres) { bool remove = false; System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName); if (pi.CanRead) { object val = pi.GetValue(o, null); switch (w.Comparison) { case SubSonic.Comparison.Equals: if (!val.Equals(w.ParameterValue)) { remove = true; } break; } } if (remove) { this.Remove(o); break; } } } return this; } } /// <summary> /// This is an ActiveRecord class which wraps the PN_pac_pap table. /// </summary> [Serializable] public partial class PnPacPap : ActiveRecord<PnPacPap>, IActiveRecord { #region .ctors and Default Settings public PnPacPap() { SetSQLProps(); InitSetDefaults(); MarkNew(); } private void InitSetDefaults() { SetDefaults(); } public PnPacPap(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) ForceDefaults(); MarkNew(); } public PnPacPap(object keyID) { SetSQLProps(); InitSetDefaults(); LoadByKey(keyID); } public PnPacPap(string columnName, object columnValue) { SetSQLProps(); InitSetDefaults(); LoadByParam(columnName,columnValue); } protected static void SetSQLProps() { GetTableSchema(); } #endregion #region Schema and Query Accessor public static Query CreateQuery() { return new Query(Schema); } public static TableSchema.Table Schema { get { if (BaseSchema == null) SetSQLProps(); return BaseSchema; } } private static void GetTableSchema() { if(!IsSchemaInitialized) { //Schema declaration TableSchema.Table schema = new TableSchema.Table("PN_pac_pap", TableType.Table, DataService.GetInstance("sicProvider")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarIdPacPap = new TableSchema.TableColumn(schema); colvarIdPacPap.ColumnName = "id_pac_pap"; colvarIdPacPap.DataType = DbType.Int32; colvarIdPacPap.MaxLength = 0; colvarIdPacPap.AutoIncrement = true; colvarIdPacPap.IsNullable = false; colvarIdPacPap.IsPrimaryKey = true; colvarIdPacPap.IsForeignKey = false; colvarIdPacPap.IsReadOnly = false; colvarIdPacPap.DefaultSetting = @""; colvarIdPacPap.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdPacPap); TableSchema.TableColumn colvarIdNoConformidad = new TableSchema.TableColumn(schema); colvarIdNoConformidad.ColumnName = "id_no_conformidad"; colvarIdNoConformidad.DataType = DbType.Int32; colvarIdNoConformidad.MaxLength = 0; colvarIdNoConformidad.AutoIncrement = false; colvarIdNoConformidad.IsNullable = false; colvarIdNoConformidad.IsPrimaryKey = false; colvarIdNoConformidad.IsForeignKey = false; colvarIdNoConformidad.IsReadOnly = false; colvarIdNoConformidad.DefaultSetting = @""; colvarIdNoConformidad.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdNoConformidad); TableSchema.TableColumn colvarDescripcion = new TableSchema.TableColumn(schema); colvarDescripcion.ColumnName = "descripcion"; colvarDescripcion.DataType = DbType.AnsiString; colvarDescripcion.MaxLength = -1; colvarDescripcion.AutoIncrement = false; colvarDescripcion.IsNullable = true; colvarDescripcion.IsPrimaryKey = false; colvarDescripcion.IsForeignKey = false; colvarDescripcion.IsReadOnly = false; colvarDescripcion.DefaultSetting = @""; colvarDescripcion.ForeignKeyTableName = ""; schema.Columns.Add(colvarDescripcion); TableSchema.TableColumn colvarAccionCorrectiva = new TableSchema.TableColumn(schema); colvarAccionCorrectiva.ColumnName = "accion_correctiva"; colvarAccionCorrectiva.DataType = DbType.AnsiString; colvarAccionCorrectiva.MaxLength = -1; colvarAccionCorrectiva.AutoIncrement = false; colvarAccionCorrectiva.IsNullable = true; colvarAccionCorrectiva.IsPrimaryKey = false; colvarAccionCorrectiva.IsForeignKey = false; colvarAccionCorrectiva.IsReadOnly = false; colvarAccionCorrectiva.DefaultSetting = @""; colvarAccionCorrectiva.ForeignKeyTableName = ""; schema.Columns.Add(colvarAccionCorrectiva); TableSchema.TableColumn colvarEvaluacionEficacia = new TableSchema.TableColumn(schema); colvarEvaluacionEficacia.ColumnName = "evaluacion_eficacia"; colvarEvaluacionEficacia.DataType = DbType.AnsiString; colvarEvaluacionEficacia.MaxLength = -1; colvarEvaluacionEficacia.AutoIncrement = false; colvarEvaluacionEficacia.IsNullable = true; colvarEvaluacionEficacia.IsPrimaryKey = false; colvarEvaluacionEficacia.IsForeignKey = false; colvarEvaluacionEficacia.IsReadOnly = false; colvarEvaluacionEficacia.DefaultSetting = @""; colvarEvaluacionEficacia.ForeignKeyTableName = ""; schema.Columns.Add(colvarEvaluacionEficacia); TableSchema.TableColumn colvarTipo = new TableSchema.TableColumn(schema); colvarTipo.ColumnName = "tipo"; colvarTipo.DataType = DbType.Int16; colvarTipo.MaxLength = 0; colvarTipo.AutoIncrement = false; colvarTipo.IsNullable = true; colvarTipo.IsPrimaryKey = false; colvarTipo.IsForeignKey = false; colvarTipo.IsReadOnly = false; colvarTipo.DefaultSetting = @""; colvarTipo.ForeignKeyTableName = ""; schema.Columns.Add(colvarTipo); TableSchema.TableColumn colvarFecha = new TableSchema.TableColumn(schema); colvarFecha.ColumnName = "fecha"; colvarFecha.DataType = DbType.DateTime; colvarFecha.MaxLength = 0; colvarFecha.AutoIncrement = false; colvarFecha.IsNullable = true; colvarFecha.IsPrimaryKey = false; colvarFecha.IsForeignKey = false; colvarFecha.IsReadOnly = false; colvarFecha.DefaultSetting = @""; colvarFecha.ForeignKeyTableName = ""; schema.Columns.Add(colvarFecha); TableSchema.TableColumn colvarArea = new TableSchema.TableColumn(schema); colvarArea.ColumnName = "area"; colvarArea.DataType = DbType.AnsiString; colvarArea.MaxLength = -1; colvarArea.AutoIncrement = false; colvarArea.IsNullable = true; colvarArea.IsPrimaryKey = false; colvarArea.IsForeignKey = false; colvarArea.IsReadOnly = false; colvarArea.DefaultSetting = @""; colvarArea.ForeignKeyTableName = ""; schema.Columns.Add(colvarArea); TableSchema.TableColumn colvarFechaCierre = new TableSchema.TableColumn(schema); colvarFechaCierre.ColumnName = "fecha_cierre"; colvarFechaCierre.DataType = DbType.DateTime; colvarFechaCierre.MaxLength = 0; colvarFechaCierre.AutoIncrement = false; colvarFechaCierre.IsNullable = true; colvarFechaCierre.IsPrimaryKey = false; colvarFechaCierre.IsForeignKey = false; colvarFechaCierre.IsReadOnly = false; colvarFechaCierre.DefaultSetting = @""; colvarFechaCierre.ForeignKeyTableName = ""; schema.Columns.Add(colvarFechaCierre); TableSchema.TableColumn colvarAccionInmediata = new TableSchema.TableColumn(schema); colvarAccionInmediata.ColumnName = "accion_inmediata"; colvarAccionInmediata.DataType = DbType.AnsiString; colvarAccionInmediata.MaxLength = -1; colvarAccionInmediata.AutoIncrement = false; colvarAccionInmediata.IsNullable = true; colvarAccionInmediata.IsPrimaryKey = false; colvarAccionInmediata.IsForeignKey = false; colvarAccionInmediata.IsReadOnly = false; colvarAccionInmediata.DefaultSetting = @""; colvarAccionInmediata.ForeignKeyTableName = ""; schema.Columns.Add(colvarAccionInmediata); TableSchema.TableColumn colvarCausaNc = new TableSchema.TableColumn(schema); colvarCausaNc.ColumnName = "causa_nc"; colvarCausaNc.DataType = DbType.AnsiString; colvarCausaNc.MaxLength = -1; colvarCausaNc.AutoIncrement = false; colvarCausaNc.IsNullable = true; colvarCausaNc.IsPrimaryKey = false; colvarCausaNc.IsForeignKey = false; colvarCausaNc.IsReadOnly = false; colvarCausaNc.DefaultSetting = @""; colvarCausaNc.ForeignKeyTableName = ""; schema.Columns.Add(colvarCausaNc); TableSchema.TableColumn colvarVerificacion = new TableSchema.TableColumn(schema); colvarVerificacion.ColumnName = "verificacion"; colvarVerificacion.DataType = DbType.Int16; colvarVerificacion.MaxLength = 0; colvarVerificacion.AutoIncrement = false; colvarVerificacion.IsNullable = true; colvarVerificacion.IsPrimaryKey = false; colvarVerificacion.IsForeignKey = false; colvarVerificacion.IsReadOnly = false; colvarVerificacion.DefaultSetting = @""; colvarVerificacion.ForeignKeyTableName = ""; schema.Columns.Add(colvarVerificacion); TableSchema.TableColumn colvarFechaVerificacion = new TableSchema.TableColumn(schema); colvarFechaVerificacion.ColumnName = "fecha_verificacion"; colvarFechaVerificacion.DataType = DbType.DateTime; colvarFechaVerificacion.MaxLength = 0; colvarFechaVerificacion.AutoIncrement = false; colvarFechaVerificacion.IsNullable = true; colvarFechaVerificacion.IsPrimaryKey = false; colvarFechaVerificacion.IsForeignKey = false; colvarFechaVerificacion.IsReadOnly = false; colvarFechaVerificacion.DefaultSetting = @""; colvarFechaVerificacion.ForeignKeyTableName = ""; schema.Columns.Add(colvarFechaVerificacion); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["sicProvider"].AddSchema("PN_pac_pap",schema); } } #endregion #region Props [XmlAttribute("IdPacPap")] [Bindable(true)] public int IdPacPap { get { return GetColumnValue<int>(Columns.IdPacPap); } set { SetColumnValue(Columns.IdPacPap, value); } } [XmlAttribute("IdNoConformidad")] [Bindable(true)] public int IdNoConformidad { get { return GetColumnValue<int>(Columns.IdNoConformidad); } set { SetColumnValue(Columns.IdNoConformidad, value); } } [XmlAttribute("Descripcion")] [Bindable(true)] public string Descripcion { get { return GetColumnValue<string>(Columns.Descripcion); } set { SetColumnValue(Columns.Descripcion, value); } } [XmlAttribute("AccionCorrectiva")] [Bindable(true)] public string AccionCorrectiva { get { return GetColumnValue<string>(Columns.AccionCorrectiva); } set { SetColumnValue(Columns.AccionCorrectiva, value); } } [XmlAttribute("EvaluacionEficacia")] [Bindable(true)] public string EvaluacionEficacia { get { return GetColumnValue<string>(Columns.EvaluacionEficacia); } set { SetColumnValue(Columns.EvaluacionEficacia, value); } } [XmlAttribute("Tipo")] [Bindable(true)] public short? Tipo { get { return GetColumnValue<short?>(Columns.Tipo); } set { SetColumnValue(Columns.Tipo, value); } } [XmlAttribute("Fecha")] [Bindable(true)] public DateTime? Fecha { get { return GetColumnValue<DateTime?>(Columns.Fecha); } set { SetColumnValue(Columns.Fecha, value); } } [XmlAttribute("Area")] [Bindable(true)] public string Area { get { return GetColumnValue<string>(Columns.Area); } set { SetColumnValue(Columns.Area, value); } } [XmlAttribute("FechaCierre")] [Bindable(true)] public DateTime? FechaCierre { get { return GetColumnValue<DateTime?>(Columns.FechaCierre); } set { SetColumnValue(Columns.FechaCierre, value); } } [XmlAttribute("AccionInmediata")] [Bindable(true)] public string AccionInmediata { get { return GetColumnValue<string>(Columns.AccionInmediata); } set { SetColumnValue(Columns.AccionInmediata, value); } } [XmlAttribute("CausaNc")] [Bindable(true)] public string CausaNc { get { return GetColumnValue<string>(Columns.CausaNc); } set { SetColumnValue(Columns.CausaNc, value); } } [XmlAttribute("Verificacion")] [Bindable(true)] public short? Verificacion { get { return GetColumnValue<short?>(Columns.Verificacion); } set { SetColumnValue(Columns.Verificacion, value); } } [XmlAttribute("FechaVerificacion")] [Bindable(true)] public DateTime? FechaVerificacion { get { return GetColumnValue<DateTime?>(Columns.FechaVerificacion); } set { SetColumnValue(Columns.FechaVerificacion, value); } } #endregion //no foreign key tables defined (0) //no ManyToMany tables defined (0) #region ObjectDataSource support /// <summary> /// Inserts a record, can be used with the Object Data Source /// </summary> public static void Insert(int varIdNoConformidad,string varDescripcion,string varAccionCorrectiva,string varEvaluacionEficacia,short? varTipo,DateTime? varFecha,string varArea,DateTime? varFechaCierre,string varAccionInmediata,string varCausaNc,short? varVerificacion,DateTime? varFechaVerificacion) { PnPacPap item = new PnPacPap(); item.IdNoConformidad = varIdNoConformidad; item.Descripcion = varDescripcion; item.AccionCorrectiva = varAccionCorrectiva; item.EvaluacionEficacia = varEvaluacionEficacia; item.Tipo = varTipo; item.Fecha = varFecha; item.Area = varArea; item.FechaCierre = varFechaCierre; item.AccionInmediata = varAccionInmediata; item.CausaNc = varCausaNc; item.Verificacion = varVerificacion; item.FechaVerificacion = varFechaVerificacion; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } /// <summary> /// Updates a record, can be used with the Object Data Source /// </summary> public static void Update(int varIdPacPap,int varIdNoConformidad,string varDescripcion,string varAccionCorrectiva,string varEvaluacionEficacia,short? varTipo,DateTime? varFecha,string varArea,DateTime? varFechaCierre,string varAccionInmediata,string varCausaNc,short? varVerificacion,DateTime? varFechaVerificacion) { PnPacPap item = new PnPacPap(); item.IdPacPap = varIdPacPap; item.IdNoConformidad = varIdNoConformidad; item.Descripcion = varDescripcion; item.AccionCorrectiva = varAccionCorrectiva; item.EvaluacionEficacia = varEvaluacionEficacia; item.Tipo = varTipo; item.Fecha = varFecha; item.Area = varArea; item.FechaCierre = varFechaCierre; item.AccionInmediata = varAccionInmediata; item.CausaNc = varCausaNc; item.Verificacion = varVerificacion; item.FechaVerificacion = varFechaVerificacion; item.IsNew = false; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } #endregion #region Typed Columns public static TableSchema.TableColumn IdPacPapColumn { get { return Schema.Columns[0]; } } public static TableSchema.TableColumn IdNoConformidadColumn { get { return Schema.Columns[1]; } } public static TableSchema.TableColumn DescripcionColumn { get { return Schema.Columns[2]; } } public static TableSchema.TableColumn AccionCorrectivaColumn { get { return Schema.Columns[3]; } } public static TableSchema.TableColumn EvaluacionEficaciaColumn { get { return Schema.Columns[4]; } } public static TableSchema.TableColumn TipoColumn { get { return Schema.Columns[5]; } } public static TableSchema.TableColumn FechaColumn { get { return Schema.Columns[6]; } } public static TableSchema.TableColumn AreaColumn { get { return Schema.Columns[7]; } } public static TableSchema.TableColumn FechaCierreColumn { get { return Schema.Columns[8]; } } public static TableSchema.TableColumn AccionInmediataColumn { get { return Schema.Columns[9]; } } public static TableSchema.TableColumn CausaNcColumn { get { return Schema.Columns[10]; } } public static TableSchema.TableColumn VerificacionColumn { get { return Schema.Columns[11]; } } public static TableSchema.TableColumn FechaVerificacionColumn { get { return Schema.Columns[12]; } } #endregion #region Columns Struct public struct Columns { public static string IdPacPap = @"id_pac_pap"; public static string IdNoConformidad = @"id_no_conformidad"; public static string Descripcion = @"descripcion"; public static string AccionCorrectiva = @"accion_correctiva"; public static string EvaluacionEficacia = @"evaluacion_eficacia"; public static string Tipo = @"tipo"; public static string Fecha = @"fecha"; public static string Area = @"area"; public static string FechaCierre = @"fecha_cierre"; public static string AccionInmediata = @"accion_inmediata"; public static string CausaNc = @"causa_nc"; public static string Verificacion = @"verificacion"; public static string FechaVerificacion = @"fecha_verificacion"; } #endregion #region Update PK Collections #endregion #region Deep Save #endregion } }
using System; using System.Threading; using System.Threading.Tasks; using System.Diagnostics; using STM.Implementation.Lockbased; using System.Collections.Immutable; using System.Collections.Generic; using Evaluation.Common; namespace LanguagedBasedHashMap { public class Program { public static void Main() { var map = new StmHashMap<int, int>(); TestMap(map); map = new StmHashMap<int, int>(); TestMapConcurrent(map); } private static void TestMapConcurrent(IMap<int, int> map) { const int t1From = 0; const int t1To = 1000; const int t2From = -1000; const int t2To = 0; const int expectedSize = 2000; var t1 = new Thread(() => MapAdd(map, t1From, t1To)); var t2 = new Thread(() => MapAdd(map, t2From, t2To)); t1.Start(); t2.Start(); t1.Join(); t2.Join(); Debug.Assert(expectedSize == map.Count); t1 = new Thread(() => MapAddIfAbsent(map, t1From, t1To)); t2 = new Thread(() => MapAddIfAbsent(map, t2From, t2To)); t1.Start(); t2.Start(); t1.Join(); t2.Join(); Debug.Assert(expectedSize == map.Count); t1 = new Thread(() => MapGet(map, t1From, t1To)); t2 = new Thread(() => MapGet(map, t2From, t2To)); t1.Start(); t2.Start(); t1.Join(); t2.Join(); t1 = new Thread(() => MapForeach(map)); t2 = new Thread(() => MapForeach(map)); t1.Start(); t2.Start(); t1.Join(); t2.Join(); t1 = new Thread(() => MapRemove(map, t1From, t1To)); t2 = new Thread(() => MapRemove(map, t2From, t2To)); t1.Start(); t2.Start(); t1.Join(); t2.Join(); Debug.Assert(0 == map.Count); } private static void TestMap(IMap<int, int> map) { const int from = -50; const int to = 50; Debug.Assert(map.Count == 0); MapAdd(map, from, to); Debug.Assert(map.Count == 100); MapAddIfAbsent(map, from, to); Debug.Assert(map.Count == 100); MapGet(map, from, to); MapRemove(map, from, to); Debug.Assert(map.Count == 0); } public static void MapAdd(IMap<int, int> map, int from, int to) { for (var i = from; i < to; i++) { map[i] = i; } } public static void MapAddIfAbsent(IMap<int, int> map, int from, int to) { for (var i = from; i < to; i++) { map.AddIfAbsent(i, i); } } public static void MapRemove(IMap<int, int> map, int from, int to) { for (var i = from; i < to; i++) { map.Remove(i); } } public static void MapGet(IMap<int, int> map, int from, int to) { for (var i = from; i < to; i++) { Debug.Assert(i == map.Get(i)); } } public static void MapForeach(IMap<int, int> map) { foreach (var kvPair in map) { Debug.Assert(kvPair.Key == kvPair.Value); } } } public class StmHashMap<K,V> : BaseHashMap<K,V> { private Bucket[] _buckets; private int _threshold; private int _size; public StmHashMap() : this(DefaultNrBuckets) { } public StmHashMap(int nrBuckets) { _buckets = MakeBuckets(nrBuckets); _threshold = CalculateThreshold(nrBuckets); } private Bucket[] MakeBuckets(int nrBuckets) { var temp = new Bucket[nrBuckets]; for (int i = 0; i < nrBuckets; i++) { temp[i] = new Bucket(); } return temp; } #region Utility private Node CreateNode(K key, V value) { return new Node(key, value); } private int GetBucketIndex(K key) { return GetBucketIndex(_buckets.Length, key); } private Node FindNode(K key) { return FindNode(key, GetBucketIndex(key)); } private Node FindNode(K key, int bucketIndex) { return FindNode(key, _buckets[bucketIndex].Value); } private Node FindNode(K key, Node node) { while (node != null && !key.Equals(node.Key)) node = node.Next; return node; } private void InsertInBucket(Bucket bucketVar, Node node) { var curNode = bucketVar.Value; if (curNode != null) { node.Next = curNode; } bucketVar.Value = node; } #endregion Utility public override bool ContainsKey(K key) { return FindNode(key) != null; } public override V Get(K key) { atomic { var node = FindNode(key); if(node == null) { //If node == null key is not present in dictionary throw new KeyNotFoundException("Key not found. Key: " + key); } return node.Value; } } public override void Add(K key, V value) { atomic { var bucketIndex = GetBucketIndex(key); //TMVar wrapping the immutable chain list var bucketVar = _buckets[bucketIndex]; var node = FindNode(key, bucketVar.Value); if (node != null) { //If node is not null key exist in map. Update the value node.Value = value; } else { //Else insert the node InsertInBucket(bucketVar, CreateNode(key, value)); _size++; ResizeIfNeeded(); } } } public override bool AddIfAbsent(K key, V value) { atomic { var bucketIndex = GetBucketIndex(key); //TMVar wrapping the immutable chain list var bucketVar = _buckets[bucketIndex]; var node = FindNode(key, bucketVar.Value); if (node == null) { //If node is not found key does not exist so insert InsertInBucket(bucketVar, CreateNode(key, value)); _size++; ResizeIfNeeded(); return true; } return false; } } private void ResizeIfNeeded() { if (_size >= _threshold) { Resize(); } } private void Resize() { atomic { //Construct new backing array var newBucketSize = _buckets.Length * 2; var newBuckets = MakeBuckets(newBucketSize); //For each key in the map rehash for (var i = 0; i < _buckets.Length; i++) { var bucket = _buckets[i]; var node = bucket.Value; while (node != null) { var bucketIndex = GetBucketIndex(newBucketSize, node.Key); InsertInBucket(newBuckets[bucketIndex], CreateNode(node.Key, node.Value)); node = node.Next; } } //Calculate new resize threshold and assign the rehashed backing array _threshold = CalculateThreshold(newBucketSize); _buckets = newBuckets; } } public override bool Remove(K key) { atomic { var bucketIndex = GetBucketIndex(key); //TMVar wrapping the immutable chain list var bucketVar = _buckets[bucketIndex]; var firstNode = bucketVar.Value; return RemoveNode(key, firstNode, bucketVar); } } private bool RemoveNode(K key, Node node, Bucket bucketVar) { if (node == null) { return false; } if (node.Key.Equals(key)) { _size--; bucketVar.Value = node.Next; return true; } while (node.Next != null && !key.Equals(node.Next.Key)) node = node.Next; //node.Next == null || node.Next.Key == key if (node.Next == null) return false; _size--; node.Next = node.Next.Next; return true; } public override IEnumerator<KeyValuePair<K, V>> GetEnumerator() { atomic { var list = new List<KeyValuePair<K, V>>(_size); for (var i = 0; i < _buckets.Length; i++) { var bucket = _buckets[i]; var node = bucket.Value; while (node != null) { var keyValuePair = new KeyValuePair<K, V>(node.Key, node.Value); list.Add(keyValuePair); node = node.Next; } } return list.GetEnumerator(); } } public override V this[K key] { get { return Get(key); } set { Add(key, value); } } public override int Count { get { return _size; } } private class Bucket { public Node Value { get; set; } } private class Node { public K Key { get; private set; } public V Value { get; set; } public Node Next { get; set; } public Node(K key, V value) { Key = key; Value = value; } } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. extern alias WORKSPACES; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using System.Runtime.Remoting; using System.Runtime.Remoting.Channels; using System.Runtime.Remoting.Channels.Ipc; using System.Runtime.Remoting.Messaging; using System.Runtime.Serialization.Formatters; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; using Microsoft.CodeAnalysis.Scripting; using Microsoft.CodeAnalysis.Scripting.Hosting; using Roslyn.Utilities; using RuntimeMetadataReferenceResolver = WORKSPACES::Microsoft.CodeAnalysis.Scripting.Hosting.RuntimeMetadataReferenceResolver; using GacFileResolver = WORKSPACES::Microsoft.CodeAnalysis.Scripting.Hosting.GacFileResolver; namespace Microsoft.CodeAnalysis.Interactive { internal partial class InteractiveHost { /// <summary> /// A remote singleton server-activated object that lives in the interactive host process and controls it. /// </summary> internal sealed class Service : MarshalByRefObject, IDisposable { private static readonly ManualResetEventSlim s_clientExited = new ManualResetEventSlim(false); private static TaskScheduler s_UIThreadScheduler; private InteractiveAssemblyLoader _assemblyLoader; private MetadataShadowCopyProvider _metadataFileProvider; private ReplServiceProvider _replServiceProvider; private readonly InteractiveHostObject _hostObject; private ObjectFormattingOptions _formattingOptions; // Session is not thread-safe by itself, and the compilation // and execution of scripts are asynchronous operations. // However since the operations are executed serially, it // is sufficient to lock when creating the async tasks. private readonly object _lastTaskGuard = new object(); private Task<EvaluationState> _lastTask; private struct EvaluationState { internal ImmutableArray<string> SourceSearchPaths; internal ImmutableArray<string> ReferenceSearchPaths; internal string WorkingDirectory; internal readonly ScriptState<object> ScriptStateOpt; internal readonly ScriptOptions ScriptOptions; internal EvaluationState( ScriptState<object> scriptState, ScriptOptions scriptOptions, ImmutableArray<string> sourceSearchPaths, ImmutableArray<string> referenceSearchPaths, string workingDirectory) { ScriptStateOpt = scriptState; ScriptOptions = scriptOptions; SourceSearchPaths = sourceSearchPaths; ReferenceSearchPaths = referenceSearchPaths; WorkingDirectory = workingDirectory; } internal EvaluationState WithScriptState(ScriptState<object> state) { return new EvaluationState( state, ScriptOptions, SourceSearchPaths, ReferenceSearchPaths, WorkingDirectory); } internal EvaluationState WithOptions(ScriptOptions options) { return new EvaluationState( ScriptStateOpt, options, SourceSearchPaths, ReferenceSearchPaths, WorkingDirectory); } } private static readonly ImmutableArray<string> s_systemNoShadowCopyDirectories = ImmutableArray.Create( FileUtilities.NormalizeDirectoryPath(Environment.GetFolderPath(Environment.SpecialFolder.Windows)), FileUtilities.NormalizeDirectoryPath(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles)), FileUtilities.NormalizeDirectoryPath(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86)), FileUtilities.NormalizeDirectoryPath(RuntimeEnvironment.GetRuntimeDirectory())); #region Setup public Service() { _formattingOptions = new ObjectFormattingOptions( memberFormat: MemberDisplayFormat.Inline, quoteStrings: true, useHexadecimalNumbers: false, maxOutputLength: 200, memberIndentation: " "); _hostObject = new InteractiveHostObject(); var initialState = new EvaluationState( scriptState: null, scriptOptions: ScriptOptions.Default, sourceSearchPaths: ImmutableArray<string>.Empty, referenceSearchPaths: ImmutableArray<string>.Empty, workingDirectory: Directory.GetCurrentDirectory()); _lastTask = Task.FromResult(initialState); Console.OutputEncoding = Encoding.UTF8; // We want to be sure to delete the shadow-copied files when the process goes away. Frankly // there's nothing we can do if the process is forcefully quit or goes down in a completely // uncontrolled manner (like a stack overflow). When the process goes down in a controlled // manned, we should generally expect this event to be called. AppDomain.CurrentDomain.ProcessExit += HandleProcessExit; } private void HandleProcessExit(object sender, EventArgs e) { Dispose(); AppDomain.CurrentDomain.ProcessExit -= HandleProcessExit; } public void Dispose() { _metadataFileProvider.Dispose(); } public override object InitializeLifetimeService() { return null; } public void Initialize(Type replServiceProviderType, string cultureName) { Debug.Assert(replServiceProviderType != null); Debug.Assert(cultureName != null); Debug.Assert(_metadataFileProvider == null); Debug.Assert(_assemblyLoader == null); Debug.Assert(_replServiceProvider == null); // TODO (tomat): we should share the copied files with the host _metadataFileProvider = new MetadataShadowCopyProvider( Path.Combine(Path.GetTempPath(), "InteractiveHostShadow"), noShadowCopyDirectories: s_systemNoShadowCopyDirectories, documentationCommentsCulture: new CultureInfo(cultureName)); _assemblyLoader = new InteractiveAssemblyLoader(_metadataFileProvider); _replServiceProvider = (ReplServiceProvider)Activator.CreateInstance(replServiceProviderType); } private MetadataReferenceResolver CreateMetadataReferenceResolver(ImmutableArray<string> searchPaths, string baseDirectory) { return new RuntimeMetadataReferenceResolver( new RelativePathResolver(searchPaths, baseDirectory), null, GacFileResolver.IsAvailable ? new GacFileResolver(preferredCulture: CultureInfo.CurrentCulture) : null, (path, properties) => new ShadowCopyReference(_metadataFileProvider, path, properties)); } private SourceReferenceResolver CreateSourceReferenceResolver(ImmutableArray<string> searchPaths, string baseDirectory) { return new SourceFileResolver(searchPaths, baseDirectory); } private static bool AttachToClientProcess(int clientProcessId) { Process clientProcess; try { clientProcess = Process.GetProcessById(clientProcessId); } catch (ArgumentException) { return false; } clientProcess.EnableRaisingEvents = true; clientProcess.Exited += new EventHandler((_, __) => { s_clientExited.Set(); }); return clientProcess.IsAlive(); } // for testing purposes public void EmulateClientExit() { s_clientExited.Set(); } internal static void RunServer(string[] args) { if (args.Length != 3) { throw new ArgumentException("Expecting arguments: <server port> <semaphore name> <client process id>"); } RunServer(args[0], args[1], int.Parse(args[2], CultureInfo.InvariantCulture)); } /// <summary> /// Implements remote server. /// </summary> private static void RunServer(string serverPort, string semaphoreName, int clientProcessId) { if (!AttachToClientProcess(clientProcessId)) { return; } // Disables Windows Error Reporting for the process, so that the process fails fast. // Unfortunately, this doesn't work on Windows Server 2008 (OS v6.0), Vista (OS v6.0) and XP (OS v5.1) // Note that GetErrorMode is not available on XP at all. if (Environment.OSVersion.Version >= new Version(6, 1, 0, 0)) { SetErrorMode(GetErrorMode() | ErrorMode.SEM_FAILCRITICALERRORS | ErrorMode.SEM_NOOPENFILEERRORBOX | ErrorMode.SEM_NOGPFAULTERRORBOX); } IpcServerChannel serverChannel = null; IpcClientChannel clientChannel = null; try { using (var semaphore = Semaphore.OpenExisting(semaphoreName)) { // DEBUG: semaphore.WaitOne(); var serverProvider = new BinaryServerFormatterSinkProvider(); serverProvider.TypeFilterLevel = TypeFilterLevel.Full; var clientProvider = new BinaryClientFormatterSinkProvider(); clientChannel = new IpcClientChannel(GenerateUniqueChannelLocalName(), clientProvider); ChannelServices.RegisterChannel(clientChannel, ensureSecurity: false); serverChannel = new IpcServerChannel(GenerateUniqueChannelLocalName(), serverPort, serverProvider); ChannelServices.RegisterChannel(serverChannel, ensureSecurity: false); RemotingConfiguration.RegisterWellKnownServiceType( typeof(Service), ServiceName, WellKnownObjectMode.Singleton); using (var resetEvent = new ManualResetEventSlim(false)) { var uiThread = new Thread(() => { var c = new Control(); c.CreateControl(); s_UIThreadScheduler = TaskScheduler.FromCurrentSynchronizationContext(); resetEvent.Set(); Application.Run(); }); uiThread.SetApartmentState(ApartmentState.STA); uiThread.IsBackground = true; uiThread.Start(); resetEvent.Wait(); } // the client can instantiate interactive host now: semaphore.Release(); } s_clientExited.Wait(); } finally { if (serverChannel != null) { ChannelServices.UnregisterChannel(serverChannel); } if (clientChannel != null) { ChannelServices.UnregisterChannel(clientChannel); } } // force exit even if there are foreground threads running: Environment.Exit(0); } internal static string ServiceName { get { return typeof(Service).Name; } } private static string GenerateUniqueChannelLocalName() { return typeof(Service).FullName + Guid.NewGuid(); } #endregion #region Remote Async Entry Points // Used by ResetInteractive - consider improving (we should remember the parameters for auto-reset, e.g.) [OneWay] public void SetPathsAsync( RemoteAsyncOperation<RemoteExecutionResult> operation, string[] referenceSearchPaths, string[] sourceSearchPaths, string baseDirectory) { Debug.Assert(operation != null); Debug.Assert(referenceSearchPaths != null); Debug.Assert(sourceSearchPaths != null); Debug.Assert(baseDirectory != null); lock (_lastTaskGuard) { _lastTask = SetPathsAsync(_lastTask, operation, referenceSearchPaths, sourceSearchPaths, baseDirectory); } } private async Task<EvaluationState> SetPathsAsync( Task<EvaluationState> lastTask, RemoteAsyncOperation<RemoteExecutionResult> operation, string[] referenceSearchPaths, string[] sourceSearchPaths, string baseDirectory) { var state = await ReportUnhandledExceptionIfAny(lastTask).ConfigureAwait(false); try { Directory.SetCurrentDirectory(baseDirectory); _hostObject.ReferencePaths.Clear(); _hostObject.ReferencePaths.AddRange(referenceSearchPaths); _hostObject.SourcePaths.Clear(); _hostObject.SourcePaths.AddRange(sourceSearchPaths); } finally { state = CompleteExecution(state, operation, success: true); } return state; } /// <summary> /// Reads given initialization file (.rsp) and loads and executes all assembly references and files, respectively specified in it. /// Execution is performed on the UI thread. /// </summary> [OneWay] public void InitializeContextAsync(RemoteAsyncOperation<RemoteExecutionResult> operation, string initializationFile, bool isRestarting) { Debug.Assert(operation != null); lock (_lastTaskGuard) { _lastTask = InitializeContextAsync(_lastTask, operation, initializationFile, isRestarting); } } /// <summary> /// Adds an assembly reference to the current session. /// </summary> [OneWay] public void AddReferenceAsync(RemoteAsyncOperation<bool> operation, string reference) { Debug.Assert(operation != null); Debug.Assert(reference != null); lock (_lastTaskGuard) { _lastTask = AddReferenceAsync(_lastTask, operation, reference); } } private async Task<EvaluationState> AddReferenceAsync(Task<EvaluationState> lastTask, RemoteAsyncOperation<bool> operation, string reference) { var state = await ReportUnhandledExceptionIfAny(lastTask).ConfigureAwait(false); bool success = false; try { var resolvedReferences = state.ScriptOptions.MetadataResolver.ResolveReference(reference, baseFilePath: null, properties: MetadataReferenceProperties.Assembly); if (!resolvedReferences.IsDefaultOrEmpty) { state = state.WithOptions(state.ScriptOptions.AddReferences(resolvedReferences)); success = true; } else { Console.Error.WriteLine(string.Format(FeaturesResources.CannotResolveReference, reference)); } } catch (Exception e) { ReportUnhandledException(e); } finally { operation.Completed(success); } return state; } /// <summary> /// Executes given script snippet on the UI thread in the context of the current session. /// </summary> [OneWay] public void ExecuteAsync(RemoteAsyncOperation<RemoteExecutionResult> operation, string text) { Debug.Assert(operation != null); Debug.Assert(text != null); lock (_lastTaskGuard) { _lastTask = ExecuteAsync(_lastTask, operation, text); } } private async Task<EvaluationState> ExecuteAsync(Task<EvaluationState> lastTask, RemoteAsyncOperation<RemoteExecutionResult> operation, string text) { var state = await ReportUnhandledExceptionIfAny(lastTask).ConfigureAwait(false); bool success = false; try { Script<object> script = TryCompile(state.ScriptStateOpt?.Script, text, null, state.ScriptOptions); if (script != null) { // successful if compiled success = true; var newScriptState = await ExecuteOnUIThread(script, state.ScriptStateOpt).ConfigureAwait(false); if (newScriptState != null) { DisplaySubmissionResult(newScriptState); state = state.WithScriptState(newScriptState); } } } catch (Exception e) { ReportUnhandledException(e); } finally { state = CompleteExecution(state, operation, success); } return state; } private void DisplaySubmissionResult(ScriptState<object> state) { bool hasValue; var resultType = state.Script.GetCompilation().GetSubmissionResultType(out hasValue); if (hasValue) { if (resultType != null && resultType.SpecialType == SpecialType.System_Void) { Console.Out.WriteLine(_replServiceProvider.ObjectFormatter.VoidDisplayString); } else { Console.Out.WriteLine(_replServiceProvider.ObjectFormatter.FormatObject(state.ReturnValue, _formattingOptions)); } } } /// <summary> /// Executes given script file on the UI thread in the context of the current session. /// </summary> [OneWay] public void ExecuteFileAsync(RemoteAsyncOperation<RemoteExecutionResult> operation, string path) { Debug.Assert(operation != null); Debug.Assert(path != null); lock (_lastTaskGuard) { _lastTask = ExecuteFileAsync(operation, _lastTask, path); } } private EvaluationState CompleteExecution(EvaluationState state, RemoteAsyncOperation<RemoteExecutionResult> operation, bool success) { // send any updates to the host object and current directory back to the client: var currentSourcePaths = _hostObject.SourcePaths.List.ToArray(); var currentReferencePaths = _hostObject.ReferencePaths.List.ToArray(); var currentWorkingDirectory = Directory.GetCurrentDirectory(); var changedSourcePaths = currentSourcePaths.SequenceEqual(state.SourceSearchPaths) ? null : currentSourcePaths; var changedReferencePaths = currentSourcePaths.SequenceEqual(state.ReferenceSearchPaths) ? null : currentReferencePaths; var changedWorkingDirectory = currentWorkingDirectory == state.WorkingDirectory ? null : currentWorkingDirectory; operation.Completed(new RemoteExecutionResult(success, changedSourcePaths, changedReferencePaths, changedWorkingDirectory)); // no changes in resolvers: if (changedReferencePaths == null && changedSourcePaths == null && changedWorkingDirectory == null) { return state; } var newSourcePaths = ImmutableArray.CreateRange(currentSourcePaths); var newReferencePaths = ImmutableArray.CreateRange(currentReferencePaths); var newWorkingDirectory = currentWorkingDirectory; ScriptOptions newOptions = state.ScriptOptions; if (changedReferencePaths != null || changedWorkingDirectory != null) { newOptions = newOptions.WithCustomMetadataResolution(CreateMetadataReferenceResolver(newReferencePaths, newWorkingDirectory)); } if (changedSourcePaths != null || changedWorkingDirectory != null) { newOptions = newOptions.WithCustomSourceResolution(CreateSourceReferenceResolver(newSourcePaths, newWorkingDirectory)); } return new EvaluationState( state.ScriptStateOpt, newOptions, newSourcePaths, newReferencePaths, workingDirectory: newWorkingDirectory); } private static async Task<EvaluationState> ReportUnhandledExceptionIfAny(Task<EvaluationState> lastTask) { try { return await lastTask.ConfigureAwait(false); } catch (Exception e) { ReportUnhandledException(e); return lastTask.Result; } } private static void ReportUnhandledException(Exception e) { Console.Error.WriteLine("Unexpected error:"); Console.Error.WriteLine(e); Debug.Fail("Unexpected error"); Debug.WriteLine(e); } #endregion #region Operations // TODO (tomat): testing only public void SetTestObjectFormattingOptions() { _formattingOptions = new ObjectFormattingOptions( memberFormat: MemberDisplayFormat.Inline, quoteStrings: true, useHexadecimalNumbers: false, maxOutputLength: int.MaxValue, memberIndentation: " "); } /// <summary> /// Loads references, set options and execute files specified in the initialization file. /// Also prints logo unless <paramref name="isRestarting"/> is true. /// </summary> private async Task<EvaluationState> InitializeContextAsync( Task<EvaluationState> lastTask, RemoteAsyncOperation<RemoteExecutionResult> operation, string initializationFileOpt, bool isRestarting) { Debug.Assert(initializationFileOpt == null || PathUtilities.IsAbsolute(initializationFileOpt)); var state = await ReportUnhandledExceptionIfAny(lastTask).ConfigureAwait(false); try { // TODO (tomat): this is also done in CommonInteractiveEngine, perhaps we can pass the parsed command lines to here? if (!isRestarting) { Console.Out.WriteLine(_replServiceProvider.Logo); } if (File.Exists(initializationFileOpt)) { Console.Out.WriteLine(string.Format(FeaturesResources.LoadingContextFrom, Path.GetFileName(initializationFileOpt))); var parser = _replServiceProvider.CommandLineParser; // The base directory for relative paths is the directory that contains the .rsp file. // Note that .rsp files included by this .rsp file will share the base directory (Dev10 behavior of csc/vbc). var rspDirectory = Path.GetDirectoryName(initializationFileOpt); var args = parser.Parse(new[] { "@" + initializationFileOpt }, rspDirectory, RuntimeEnvironment.GetRuntimeDirectory(), null /* TODO: pass a valid value*/); foreach (var error in args.Errors) { var writer = (error.Severity == DiagnosticSeverity.Error) ? Console.Error : Console.Out; writer.WriteLine(error.GetMessage(CultureInfo.CurrentCulture)); } if (args.Errors.Length == 0) { // TODO (tomat): other arguments // TODO (tomat): parse options var metadataResolver = CreateMetadataReferenceResolver(args.ReferencePaths, rspDirectory); _hostObject.ReferencePaths.Clear(); _hostObject.ReferencePaths.AddRange(args.ReferencePaths); _hostObject.SourcePaths.Clear(); var metadataReferences = new List<PortableExecutableReference>(); foreach (CommandLineReference cmdLineReference in args.MetadataReferences) { // interactive command line parser doesn't accept modules or linked assemblies Debug.Assert(cmdLineReference.Properties.Kind == MetadataImageKind.Assembly && !cmdLineReference.Properties.EmbedInteropTypes); var resolvedReferences = metadataResolver.ResolveReference(cmdLineReference.Reference, baseFilePath: null, properties: MetadataReferenceProperties.Assembly); if (!resolvedReferences.IsDefaultOrEmpty) { metadataReferences.AddRange(resolvedReferences); } } // only search for scripts next to the .rsp file: var sourceSearchPaths = ImmutableArray<string>.Empty; var rspState = new EvaluationState( state.ScriptStateOpt, state.ScriptOptions.AddReferences(metadataReferences), sourceSearchPaths, args.ReferencePaths, rspDirectory); foreach (CommandLineSourceFile file in args.SourceFiles) { // execute all files as scripts (matches csi/vbi semantics) string fullPath = ResolveRelativePath(file.Path, rspDirectory, sourceSearchPaths, displayPath: true); if (fullPath != null) { var newScriptState = await ExecuteFileAsync(rspState, fullPath).ConfigureAwait(false); if (newScriptState != null) { rspState = rspState.WithScriptState(newScriptState); } } } state = new EvaluationState( rspState.ScriptStateOpt, rspState.ScriptOptions, ImmutableArray<string>.Empty, args.ReferencePaths, state.WorkingDirectory); } } if (!isRestarting) { Console.Out.WriteLine(FeaturesResources.TypeHelpForMoreInformation); } } catch (Exception e) { ReportUnhandledException(e); } finally { state = CompleteExecution(state, operation, success: true); } return state; } private string ResolveRelativePath(string path, string baseDirectory, ImmutableArray<string> searchPaths, bool displayPath) { List<string> attempts = new List<string>(); Func<string, bool> fileExists = file => { attempts.Add(file); return File.Exists(file); }; string fullPath = FileUtilities.ResolveRelativePath(path, null, baseDirectory, searchPaths, fileExists); if (fullPath == null) { if (displayPath) { Console.Error.WriteLine(FeaturesResources.SpecifiedFileNotFoundFormat, path); } else { Console.Error.WriteLine(FeaturesResources.SpecifiedFileNotFound); } if (attempts.Count > 0) { DisplaySearchPaths(Console.Error, attempts); } } return fullPath; } private void LoadReference(PortableExecutableReference resolvedReference, bool suppressWarnings) { AssemblyLoadResult result; try { result = _assemblyLoader.LoadFromPath(resolvedReference.FilePath); } catch (FileNotFoundException e) { Console.Error.WriteLine(e.Message); return; } catch (ArgumentException e) { Console.Error.WriteLine((e.InnerException ?? e).Message); return; } catch (TargetInvocationException e) { // The user might have hooked AssemblyResolve event, which might have thrown an exception. // Display stack trace in this case. Console.Error.WriteLine(e.InnerException.ToString()); return; } if (!result.IsSuccessful && !suppressWarnings) { Console.Out.WriteLine(string.Format(CultureInfo.CurrentCulture, FeaturesResources.RequestedAssemblyAlreadyLoaded, result.OriginalPath)); } } private Script<object> TryCompile(Script previousScript, string code, string path, ScriptOptions options) { Script script; var scriptOptions = options.WithPath(path).WithIsInteractive(path == null); if (previousScript != null) { script = previousScript.ContinueWith(code, scriptOptions); } else { script = _replServiceProvider.CreateScript<object>(code, scriptOptions, _hostObject.GetType(), _assemblyLoader); } // force build so exception is thrown now if errors are found. try { script.Build(); } catch (CompilationErrorException e) { DisplayInteractiveErrors(e.Diagnostics, Console.Error); return null; } // TODO: Do we want to do this? // Pros: immediate feedback for assemblies that can't be loaded. // Cons: maybe we won't need them //foreach (PortableExecutableReference reference in script.GetCompilation().DirectiveReferences) //{ // LoadReference(reference, suppressWarnings: false); //} return (Script<object>)script; } private async Task<EvaluationState> ExecuteFileAsync( RemoteAsyncOperation<RemoteExecutionResult> operation, Task<EvaluationState> lastTask, string path) { var state = await ReportUnhandledExceptionIfAny(lastTask).ConfigureAwait(false); var success = false; try { var fullPath = ResolveRelativePath(path, state.WorkingDirectory, state.SourceSearchPaths, displayPath: false); var newScriptState = await ExecuteFileAsync(state, fullPath).ConfigureAwait(false); if (newScriptState != null) { success = true; state = state.WithScriptState(newScriptState); } } finally { state = CompleteExecution(state, operation, success); } return state; } /// <summary> /// Executes specified script file as a submission. /// </summary> /// <returns>True if the code has been executed. False if the code doesn't compile.</returns> /// <remarks> /// All errors are written to the error output stream. /// Uses source search paths to resolve unrooted paths. /// </remarks> private async Task<ScriptState<object>> ExecuteFileAsync(EvaluationState state, string fullPath) { string content = null; if (fullPath != null) { Debug.Assert(PathUtilities.IsAbsolute(fullPath)); try { content = File.ReadAllText(fullPath); } catch (Exception e) { Console.Error.WriteLine(e.Message); } } ScriptState<object> newScriptState = null; if (content != null) { Script<object> script = TryCompile(state.ScriptStateOpt?.Script, content, fullPath, state.ScriptOptions); if (script != null) { newScriptState = await ExecuteOnUIThread(script, state.ScriptStateOpt).ConfigureAwait(false); } } return newScriptState; } private static void DisplaySearchPaths(TextWriter writer, List<string> attemptedFilePaths) { var directories = attemptedFilePaths.Select(path => Path.GetDirectoryName(path)).ToArray(); var uniqueDirectories = new HashSet<string>(directories); writer.WriteLine(uniqueDirectories.Count == 1 ? FeaturesResources.SearchedInDirectory : FeaturesResources.SearchedInDirectories); foreach (string directory in directories) { if (uniqueDirectories.Remove(directory)) { writer.Write(" "); writer.WriteLine(directory); } } } private async Task<ScriptState<object>> ExecuteOnUIThread(Script<object> script, ScriptState<object> stateOpt) { return await Task.Factory.StartNew(async () => { try { var task = (stateOpt == null) ? script.RunAsync(_hostObject, CancellationToken.None) : script.ContinueAsync(stateOpt, CancellationToken.None); return await task.ConfigureAwait(false); } catch (Exception e) { // TODO (tomat): format exception Console.Error.WriteLine(e); return null; } }, CancellationToken.None, TaskCreationOptions.None, s_UIThreadScheduler).Unwrap().ConfigureAwait(false); } private void DisplayInteractiveErrors(ImmutableArray<Diagnostic> diagnostics, TextWriter output) { var displayedDiagnostics = new List<Diagnostic>(); const int MaxErrorCount = 5; for (int i = 0, n = Math.Min(diagnostics.Length, MaxErrorCount); i < n; i++) { displayedDiagnostics.Add(diagnostics[i]); } displayedDiagnostics.Sort((d1, d2) => d1.Location.SourceSpan.Start - d2.Location.SourceSpan.Start); var formatter = _replServiceProvider.DiagnosticFormatter; foreach (var diagnostic in displayedDiagnostics) { output.WriteLine(formatter.Format(diagnostic, output.FormatProvider as CultureInfo)); } if (diagnostics.Length > MaxErrorCount) { int notShown = diagnostics.Length - MaxErrorCount; output.WriteLine(string.Format(output.FormatProvider, FeaturesResources.PlusAdditional, notShown, (notShown == 1) ? "error" : "errors")); } } #endregion #region Win32 API [DllImport("kernel32", PreserveSig = true)] internal static extern ErrorMode SetErrorMode(ErrorMode mode); [DllImport("kernel32", PreserveSig = true)] internal static extern ErrorMode GetErrorMode(); [Flags] internal enum ErrorMode : int { /// <summary> /// Use the system default, which is to display all error dialog boxes. /// </summary> SEM_FAILCRITICALERRORS = 0x0001, /// <summary> /// The system does not display the critical-error-handler message box. Instead, the system sends the error to the calling process. /// Best practice is that all applications call the process-wide SetErrorMode function with a parameter of SEM_FAILCRITICALERRORS at startup. /// This is to prevent error mode dialogs from hanging the application. /// </summary> SEM_NOGPFAULTERRORBOX = 0x0002, /// <summary> /// The system automatically fixes memory alignment faults and makes them invisible to the application. /// It does this for the calling process and any descendant processes. This feature is only supported by /// certain processor architectures. For more information, see the Remarks section. /// After this value is set for a process, subsequent attempts to clear the value are ignored. /// </summary> SEM_NOALIGNMENTFAULTEXCEPT = 0x0004, /// <summary> /// The system does not display a message box when it fails to find a file. Instead, the error is returned to the calling process. /// </summary> SEM_NOOPENFILEERRORBOX = 0x8000, } #endregion #region Testing // TODO(tomat): remove when the compiler supports events // For testing purposes only! public void HookMaliciousAssemblyResolve() { AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler((_, __) => { int i = 0; while (true) { if (i < 10) { i = i + 1; } else if (i == 10) { Console.Error.WriteLine("in the loop"); i = i + 1; } } }); } public void RemoteConsoleWrite(byte[] data, bool isError) { using (var stream = isError ? Console.OpenStandardError() : Console.OpenStandardOutput()) { stream.Write(data, 0, data.Length); stream.Flush(); } } public bool IsShadowCopy(string path) { return _metadataFileProvider.IsShadowCopy(path); } #endregion } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Kernel_alpha; using Kernel_alpha.Lib; using Kernel_alpha.Lib.Encoding; namespace Kernel_alpha { public unsafe class Elf { elfHeaders el = new elfHeaders(); public byte[] ParseELF(byte[] xData) { el.ident = new char[16]; byte[] xReadData = null; if (ReadHeader(xData, el) == 0) { Console.WriteLine("ELF file found"); xReadData = ParseELFData(xData, el); } return xReadData; } private byte[] ParseELFData(byte[] xData, elfHeaders el) { // starting with core program programHeader ph = new programHeader(); Exe_Format exeFormat = new Exe_Format(); exeFormat.entryAddr = el.entry; Console.WriteLine("Entry address : " + exeFormat.entryAddr.ToString()); exeFormat.numSegments = el.phnum; exeFormat.segmentList = new Exe_Segment[el.phnum]; byte[] xReadData = null; int temp = 0; for (int i = 0; i < el.phnum; i++) { ph.type = BitConverter.ToUInt16(xData, 0x34 + (0x20 * i)); exeFormat.segmentList[i].offsetInFile = ph.offset = BitConverter.ToUInt16(xData, 0x34 + (temp = +4) + (0x20 * i)); exeFormat.segmentList[i].startAddress = ph.vaddr = BitConverter.ToUInt32(xData, 0x34 + (temp = +4) + (0x20 * i)); ph.paddr = BitConverter.ToUInt32(xData, 0x34 + (temp = +4) + (0x20 * i)); exeFormat.segmentList[i].lengthInFile = ph.fileSize = BitConverter.ToUInt16(xData, 0x34 + (temp = +4) + (0x20 * i)); exeFormat.segmentList[i].sizeInMemory = ph.memSize = BitConverter.ToUInt16(xData, 0x34 + (temp = +4) + (0x20 * i)); exeFormat.segmentList[i].protFlags = ph.flags = BitConverter.ToUInt16(xData, 0x34 + (temp = +4) + (0x20 * i)); ph.alignment = BitConverter.ToUInt16(xData, BitConverter.ToUInt16(xData, 0x34 + (temp = +4) + (0x20 * i))); if (ph.type == 1) { //xReadData = new byte[exeFormat.segmentList[i].lengthInFile]; //for (int j = (int)exeFormat.entryAddr; j < exeFormat.entryAddr + exeFormat.segmentList[i].lengthInFile; j++) //{ // xReadData[j - (int)exeFormat.entryAddr] = xData[j]; //} //break; } } // Reading section header sectionHeader sh = new sectionHeader(); temp = 0; for (int i = 0; i < el.shnum; i++) { sh.sh_name = BitConverter.ToUInt16(xData, (int)el.sphoff + (el.shentsize * i)); sh.sh_type = BitConverter.ToUInt16(xData, (int)el.sphoff + 4 + (el.shentsize * i)); sh.sh_flags = BitConverter.ToUInt16(xData, (int)el.sphoff + 8 + (el.shentsize * i)); sh.sh_Addr = BitConverter.ToUInt32(xData, (int)el.sphoff + 12 + (el.shentsize * i)); sh.sh_offset = BitConverter.ToUInt32(xData, (int)el.sphoff + 16 + (el.shentsize * i)); sh.sh_size = BitConverter.ToUInt16(xData, (int)el.sphoff + 20 + (el.shentsize * i)); sh.sh_link = BitConverter.ToUInt16(xData, (int)el.sphoff + 24 + (el.shentsize * i)); sh.sh_info = BitConverter.ToUInt16(xData, (int)el.sphoff + 28 + (el.shentsize * i)); sh.sh_addralign = BitConverter.ToUInt16(xData, (int)el.sphoff + 32 + (el.shentsize * i)); sh.sh_entsize = BitConverter.ToUInt16(xData, (int)el.sphoff + 36 + (el.shentsize * i)); } //xReadData = new byte[0x180]; //for (int j = 0x2F0; j < 0x470; j++) //{ // xReadData[j - 0x2F0] = xData[j]; //} return xReadData; } public UInt16 StartOfStringTable(byte[] xData) { return BitConverter.ToUInt16(xData, (int)el.sphoff + 16 + (el.shentsize * el.shstrndx)); } public int ReadHeader(byte[] xData, elfHeaders el) { // Reading Magic Number for (int i = 0; i < 4; i++) { el.ident[i] = (char)xData[i]; } // Reading architecture format el.ident[4] = (char)xData[4]; // Endian identifier el.ident[5] = (char)xData[5]; // original version for ELF el.ident[6] = (char)xData[6]; el.ident[10] = (char)xData[16]; // checking whether the elf is executable or relocatable or shared el.type = BitConverter.ToUInt16(xData, 16); // instruction set architecture el.machine = BitConverter.ToUInt16(xData, 18); // version el.version = BitConverter.ToUInt32(xData, 20); // memory address entry point el.entry = BitConverter.ToUInt32(xData, 24); // changes from here... el.phoff = BitConverter.ToUInt32(xData, (int)elfEnum.phoff); el.sphoff = BitConverter.ToUInt32(xData, (int)elfEnum.sphoff); el.flag = BitConverter.ToUInt32(xData, (int)elfEnum.flag); el.ehsize = BitConverter.ToUInt16(xData, (int)elfEnum.ehsize); el.phentsize = BitConverter.ToUInt16(xData, (int)elfEnum.phentsize); el.phnum = BitConverter.ToUInt16(xData, (int)elfEnum.phnum); el.shentsize = BitConverter.ToUInt16(xData, (int)elfEnum.shentsize); el.shnum = BitConverter.ToUInt16(xData, (int)elfEnum.shnum); el.shstrndx = BitConverter.ToUInt16(xData, (int)elfEnum.shstrndx); if (el.ident[0] != '\x7F' || el.ident[1] != 'E' || el.ident[2] != 'L' || el.ident[3] != 'F') return -1; if (el.ident[4] == 2) return -1; // not targetting x64 at this time :) return 0; } } public class elfHeaders { public char[] ident { get; set; } public ushort type { get; set; } public ushort machine { get; set; } public uint version { get; set; } public UInt32 entry { get; set; } public UInt32 phoff { get; set; } public UInt32 sphoff { get; set; } public uint flag { get; set; } public ushort ehsize { get; set; } public ushort phentsize { get; set; } public ushort phnum { get; set; } public ushort shentsize { get; set; } public ushort shnum { get; set; } public ushort shstrndx { get; set; } } public class programHeader { public uint type { get; set; } public uint offset { get; set; } public UInt32 vaddr { get; set; } public UInt32 paddr { get; set; } public uint fileSize { get; set; } public uint memSize { get; set; } public uint flags { get; set; } public uint alignment { get; set; } } public class sectionHeader { public uint sh_name { get; set; } public uint sh_type { get; set; } public uint sh_flags { get; set; } public UInt32 sh_Addr { get; set; } public UInt32 sh_offset { get; set; } public uint sh_size { get; set; } public uint sh_link { get; set; } public uint sh_info { get; set; } public uint sh_addralign { get; set; } public uint sh_entsize { get; set; } } public class Exe_Segment { public uint offsetInFile { get; set; } /* Offset of segment in executable file */ public uint lengthInFile { get; set; } /* Length of segment data in executable file */ public UInt32 startAddress { get; set; } /* Start address of segment in user memory */ public uint sizeInMemory { get; set; } /* Size of segment in memory */ public uint protFlags { get; set; } /* VM protection flags; combination of VM_READ,VM_WRITE,VM_EXEC */ } public class Exe_Format { public Exe_Segment[] segmentList { get; set; } /* Definition of segments */ public int numSegments { get; set; } /* Number of segments contained in the executable */ public uint entryAddr { get; set; } /* Code entry point address */ } // targetting x86 enum elfEnum : int { ident, type = 16, machine = 18, version = 20, entry = 24, phoff = 28, sphoff = 32, flag = 36, ehsize = 40, phentsize = 42, phnum = 44, shentsize = 46, shnum = 48, shstrndx = 50 } }
// 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 OLEDB.Test.ModuleCore; using System.Collections.Generic; using System.IO; using WebData.BaseLib; using XmlCoreTest.Common; namespace System.Xml.Tests { [TestCase(Name = "Conformance Settings", Desc = "Conformance Settings")] public partial class TCConformanceSettings : TCXMLReaderBaseGeneral { public string GetSimpleInvalidXml() { string invalidCharString = StringGen.GetIllegalXmlString(10, true); ManagedNodeWriter mn = new ManagedNodeWriter(); mn.PutDecl(); mn.OpenElement("&#xd800;"); mn.CloseElement(); mn.PutText(invalidCharString); mn.PutEndElement(); return mn.GetNodes(); } //[Variation("Wrapping Tests: CR with CR", Pri = 2, Params = new object[] { "Auto", "Auto", "<root/>", "true" })] //[Variation("Wrapping Tests: CR with CR", Pri = 2, Params = new object[] { "Auto", "Auto", "<root/><root/>", "true" })] //[Variation("Wrapping Tests: CR with CR", Pri = 2, Params = new object[] { "Fragment", "Auto", "<root/><root/>", "true" })] //[Variation("Wrapping Tests: CR with CR", Pri = 2, Params = new object[] { "Document", "Auto", "<root/>", "true" })] //[Variation("Wrapping Tests: CR with CR", Pri = 2, Params = new object[] { "Auto", "Fragment", "<root/>", "false" })] //[Variation("Wrapping Tests: CR with CR", Pri = 2, Params = new object[] { "Fragment", "Fragment", "<root/>", "true" })] //[Variation("Wrapping Tests: CR with CR", Pri = 2, Params = new object[] { "Fragment", "Fragment", "<root/><root/>", "true" })] //[Variation("Wrapping Tests: CR with CR", Pri = 2, Params = new object[] { "Document", "Fragment", "<root/>", "false" })] //[Variation("Wrapping Tests: CR with CR", Pri = 2, Params = new object[] { "Auto", "Document", "<root/>", "false" })] //[Variation("Wrapping Tests: CR with CR", Pri = 2, Params = new object[] { "Fragment", "Document", "<root/><root/>", "false" })] //[Variation("Wrapping Tests: CR with CR", Pri = 2, Params = new object[] { "Document", "Document", "<root/>", "true" })] public int wrappingTests() { string underlyingReaderLevel = this.CurVariation.Params[0].ToString(); string wrappingReaderLevel = this.CurVariation.Params[1].ToString(); string conformanceXml = this.CurVariation.Params[2].ToString(); bool valid = this.CurVariation.Params[3].ToString() == "true"; CError.WriteLine(underlyingReaderLevel); CError.WriteLine(wrappingReaderLevel); CError.WriteLine(conformanceXml); CError.WriteLine("IsValid = " + valid); try { XmlReaderSettings rsU = new XmlReaderSettings(); rsU.ConformanceLevel = (ConformanceLevel)Enum.Parse(typeof(ConformanceLevel), underlyingReaderLevel); XmlReader rU = ReaderHelper.Create(new StringReader(conformanceXml), rsU, (string)null); XmlReaderSettings rsW = new XmlReaderSettings(); rsW.ConformanceLevel = (ConformanceLevel)Enum.Parse(typeof(ConformanceLevel), wrappingReaderLevel); XmlReader rW = ReaderHelper.Create(rU, rsW); CError.Compare(rW.ReadState, ReadState.Initial, "ReadState not initial"); } catch (InvalidOperationException ioe) { CError.WriteLineIgnore(ioe.ToString()); if (valid) throw new CTestFailedException("Valid case throws InvalidOperation"); else return TEST_PASS; } if (!valid) throw new CTestFailedException("Invalid case doesnt throw InvalidOperation"); else return TEST_PASS; } [Variation("Default Values", Pri = 0)] public int v1() { XmlReaderSettings rs = new XmlReaderSettings(); CError.Compare(rs.CheckCharacters, true, "CheckCharacters not true"); CError.Compare(rs.ConformanceLevel, ConformanceLevel.Document, "Conformance Level not document by default"); return TEST_PASS; } //[Variation("Default Reader, Check Characters On and pass invalid characters", Pri = 0, Params = new object[]{"CoreValidatingReader"})] //[Variation("Default Reader, Check Characters On and pass invalid characters", Pri = 0, Params = new object[]{"CoreReader"})] public int v2() { string readerType = (string)this.CurVariation.Params[0]; bool exceptionThrown = false; string invalidCharXml = GetSimpleInvalidXml(); XmlReaderSettings rs = new XmlReaderSettings(); rs.CheckCharacters = true; XmlReader reader = ReaderHelper.CreateReader(readerType, new StringReader(invalidCharXml), false, null, rs); try { while (reader.Read()) ; } catch (XmlException xe) { CError.WriteLine(xe.Message); exceptionThrown = true; } reader.Dispose(); if (!exceptionThrown) return TEST_FAIL; return TEST_PASS; } //[Variation("Default Reader, Check Characters Off and pass invalid characters in text", Pri = 0, Params = new object[] { "CoreValidatingReader" })] //[Variation("Default Reader, Check Characters Off and pass invalid characters in text", Pri = 0, Params = new object[]{"CoreReader"})] public int v3() { string readerType = (string)this.CurVariation.Params[0]; ManagedNodeWriter mn = new ManagedNodeWriter(); mn.PutDecl(); mn.OpenElement(); mn.CloseElement(); //This is an invalid char in XML. mn.PutText("&#xd800;"); mn.PutEndElement(); string invalidCharXml = mn.GetNodes(); XmlReaderSettings rs = new XmlReaderSettings(); rs.CheckCharacters = false; using (XmlReader reader = ReaderHelper.CreateReader(readerType, new StringReader(invalidCharXml), false, null, rs)) { try { while (reader.Read()) ; } catch (XmlException xe) { CError.WriteIgnore(invalidCharXml); CError.WriteLine(xe.Message); CError.WriteLine(xe.StackTrace); return TEST_FAIL; } } return TEST_PASS; } //[Variation("Default Reader, Check Characters Off and pass invalid characters in element", Pri = 0, Params = new object[] { "CoreValidatingReader" })] //[Variation("Default Reader, Check Characters Off and pass invalid characters in element", Pri = 0, Params = new object[] {"CoreReader"})] public int v4() { string readerType = (string)this.CurVariation.Params[0]; bool exceptionThrown = false; ManagedNodeWriter mn = new ManagedNodeWriter(); mn.PutDecl(); mn.OpenElement("&#xd800;"); mn.CloseEmptyElement(); XmlReaderSettings rs = new XmlReaderSettings(); rs.CheckCharacters = false; XmlReader reader = ReaderHelper.CreateReader(readerType, new StringReader(mn.GetNodes()), false, null, rs); try { while (reader.Read()) ; } catch (XmlException xe) { CError.WriteIgnore(xe.Message + "\n"); exceptionThrown = true; } mn.Close(); reader.Dispose(); if (!exceptionThrown) return TEST_FAIL; return TEST_PASS; } //[Variation("Default Reader, Check Characters On and pass invalid characters in text", Pri = 0, Params = new object[] { "CoreValidatingReader" })] //[Variation("Default Reader, Check Characters On and pass invalid characters in text", Pri = 0, Params = new object[] { "CoreReader" })] public int v5() { string readerType = (string)this.CurVariation.Params[0]; bool exceptionThrown = false; ManagedNodeWriter mn = new ManagedNodeWriter(); mn.PutDecl(); mn.OpenElement(); mn.CloseElement(); mn.PutText("&#xd800;"); //This is invalid char in XML. mn.PutEndElement(); string invalidCharXml = mn.GetNodes(); XmlReaderSettings rs = new XmlReaderSettings(); rs.CheckCharacters = true; XmlReader reader = ReaderHelper.CreateReader(readerType, new StringReader(invalidCharXml), false, null, rs); try { while (reader.Read()) ; } catch (XmlException xe) { CError.WriteIgnore(invalidCharXml); CError.WriteLine(xe.Message); CError.WriteLine(xe.StackTrace); exceptionThrown = true; } mn.Close(); reader.Dispose(); if (!exceptionThrown) return TEST_FAIL; return TEST_PASS; } public string GetPatternXml(string pattern) { ManagedNodeWriter mn = new ManagedNodeWriter(); mn.PutPattern(pattern); CError.WriteLine("'" + mn.GetNodes() + "'"); return mn.GetNodes(); } private static bool[] s_pri0ExpectedNone = { false, false, false, false, false, true, true, true, true, true, false }; private static bool[] s_pri0ExpectedFragment = { false, false, false, false, false, true, true, true, true, true, false }; private static bool[] s_pri0ExpectedDocument = { true, true, false, true, true, true, true, true, true, true, false }; public object[] GetAllPri0ConformanceTestXmlStrings() { /* The following XML Strings will be created : 1 Text at Top Level 2 More than one element at top level 3 WhiteSpace at Top level 4 Top Level Attribute 5 Multiple Contiguous Text Nodes. 6 Same Prefix declared twice. 7 xml:space contains wrong value 8 Invalid Name for element 9 Invalid Name for attribute 10 Prefix Xml matched with wrong namespace URI. 11 prefix Xml missing Namepace URI 12 prefix or localname xmlns matches with wrong namespace URI 13 prefix or localname xmlns missing namespace uri. */ List<string> list = new List<string>(); ManagedNodeWriter mn = null; list.Add(GetPatternXml("T")); //1 list.Add(GetPatternXml("XEMEM"));//2 list.Add(GetPatternXml("WEM"));//3 list.Add(GetPatternXml("TPT"));//4 list.Add(GetPatternXml("A"));//5 //6 mn = new ManagedNodeWriter(); mn.PutPattern("XE"); mn.PutAttribute("xmlns:a", "http://www.foo.com"); mn.PutAttribute("xmlns:a", "http://www.foo.com"); mn.PutPattern("M"); CError.WriteLine(mn.GetNodes()); list.Add(mn.GetNodes()); mn.Close(); //7 mn = new ManagedNodeWriter(); mn.PutPattern("XE"); mn.PutAttribute("xml:space", "rubbish"); mn.PutPattern("M"); CError.WriteLine(mn.GetNodes()); list.Add(mn.GetNodes()); mn.Close(); //8 mn = new ManagedNodeWriter(); mn.PutPattern("X"); mn.OpenElement(UnicodeCharHelper.GetInvalidCharacters(CharType.XmlChar)); mn.PutPattern("M"); CError.WriteLine(mn.GetNodes()); list.Add(mn.GetNodes()); mn.Close(); //9 mn = new ManagedNodeWriter(); mn.PutPattern("XE"); mn.PutAttribute(UnicodeCharHelper.GetInvalidCharacters(CharType.XmlChar), UnicodeCharHelper.GetInvalidCharacters(CharType.XmlChar)); mn.PutPattern("M"); CError.WriteLine(mn.GetNodes()); list.Add(mn.GetNodes()); mn.Close(); //10 mn = new ManagedNodeWriter(); mn.PutPattern("XE"); mn.PutAttribute("xmlns:xml", "http://wrong"); mn.PutPattern("M"); CError.WriteLine(mn.GetNodes()); list.Add(mn.GetNodes()); mn.Close(); //11 mn = new ManagedNodeWriter(); mn.PutPattern("XE"); mn.PutAttribute("xml:space", "default"); mn.PutPattern("M"); CError.WriteLine(mn.GetNodes()); list.Add(mn.GetNodes()); mn.Close(); return list.ToArray(); } //Conformance-level tests [Variation("Conformance Level to Auto and test various scenarios from test plan", Pri = 0)] public int CAuto() { XmlReaderSettings rs = new XmlReaderSettings(); rs.ConformanceLevel = ConformanceLevel.Auto; object[] xml = GetAllPri0ConformanceTestXmlStrings(); if (xml.Length > s_pri0ExpectedNone.Length) { CError.WriteLine("Invalid Compare attempted"); return TEST_FAIL; } bool failed = false; for (int i = 0; i < xml.Length; i++) { XmlReader reader = ReaderHelper.Create(new StringReader((string)xml[i]), rs, (string)null); bool actual = false; try { while (reader.Read()) ; } catch (XmlException xe) { CError.Write("Case : " + (i + 1)); CError.WriteLine(xe.Message); actual = true; } if (actual != s_pri0ExpectedNone[i]) { CError.WriteLine("ConformanceLevel = Auto"); CError.WriteLine("Test Failed for Case : " + (i + 1)); CError.WriteLine((string)xml[i]); failed = true; } }//end for if (failed) return TEST_FAIL; return TEST_PASS; }//end variation [Variation("Conformance Level to Fragment and test various scenarios from test plan", Pri = 0)] public int CFragment() { XmlReaderSettings rs = new XmlReaderSettings(); rs.ConformanceLevel = ConformanceLevel.Fragment; object[] xml = GetAllPri0ConformanceTestXmlStrings(); if (xml.Length > s_pri0ExpectedFragment.Length) { CError.WriteLine("Invalid Compare attempted"); return TEST_FAIL; } bool failed = false; for (int i = 0; i < xml.Length; i++) { XmlReader reader = ReaderHelper.Create(new StringReader((string)xml[i]), rs, (string)null); bool actual = false; try { while (reader.Read()) ; } catch (XmlException xe) { CError.Write("Case : " + (i + 1)); CError.WriteLine(xe.Message); actual = true; } if (actual != s_pri0ExpectedFragment[i]) { CError.WriteLine("ConformanceLevel = Fragment"); CError.WriteLine("Test Failed for Case" + (i + 1)); CError.WriteLine((string)xml[i]); failed = true; } }//end for if (failed) return TEST_FAIL; return TEST_PASS; }//end variation [Variation("Conformance Level to Document and test various scenarios from test plan", Pri = 0)] public int CDocument() { XmlReaderSettings rs = new XmlReaderSettings(); rs.ConformanceLevel = ConformanceLevel.Document; object[] xml = GetAllPri0ConformanceTestXmlStrings(); if (xml.Length > s_pri0ExpectedDocument.Length) { CError.WriteLine("Invalid Compare attempted"); return TEST_FAIL; } bool failed = false; for (int i = 0; i < xml.Length; i++) { XmlReader reader = ReaderHelper.Create(new StringReader((string)xml[i]), rs, (string)null); bool actual = false; try { while (reader.Read()) ; } catch (XmlException xe) { CError.Write("Case : " + (i + 1)); CError.WriteLine(xe.Message); actual = true; } if (actual != s_pri0ExpectedDocument[i]) { CError.WriteLine("ConformanceLevel = Document"); CError.WriteLine("Test Failed for Case" + (i + 1)); CError.WriteLine("|" + (string)xml[i] + "|"); failed = true; } } if (failed) return TEST_FAIL; return TEST_PASS; } [Variation("Test Invalid Value Range for enum properties", Pri = 1)] public int InvalidValueRange() { XmlReaderSettings settings = null; try { settings = new XmlReaderSettings(); settings.ConformanceLevel = (ConformanceLevel)666; return TEST_FAIL; } catch (ArgumentOutOfRangeException) { } return TEST_PASS; } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; namespace OnPoolCommon { // [DebuggerStepThrough] public class Message { public long ToClient { get; set; } = -1; public string ToPool { get; set; } public long From { get; set; } = -1; public MessageType Type { get; set; } public MessageDirection Direction { get; set; } public ResponseOptions ResponseOptions { get; set; } public string Method { get; set; } public long RequestKey { get; set; } public string Json { get; set; } public int PoolAllCount { get; set; } = -1; public Message() { } public Message AddJson<T>(T obj) { Json = obj.ToJson(); return this; } public byte[] GetBytes() { const int lengthOfPayload = 4, enums = 4, from = 8, toClient = 8, toPoolLen = 4, methodLen = 4, jsonLen = 4, requestKey = 8, poolAllCount = 4; var byteLen = 0; byteLen += lengthOfPayload; byteLen += enums; byteLen += from; switch (Type) { case MessageType.Client: byteLen += toClient; break; case MessageType.ClientPool: byteLen += toClient; byteLen += toPoolLen; if (ToPool != null) byteLen += ToPool.Length; break; case MessageType.Pool: case MessageType.PoolAll: byteLen += toPoolLen; if (ToPool != null) byteLen += ToPool.Length; break; } byteLen += methodLen; byteLen += Method.Length; byteLen += jsonLen; if (Json != null) { byteLen += Json.Length; } byteLen += requestKey; byteLen += poolAllCount; var bytes = new byte[byteLen]; int cur = 0; WriteBytes(byteLen, bytes, cur); cur += 4; bytes[cur++] = (byte)Direction; bytes[cur++] = (byte)Type; bytes[cur++] = (byte)ResponseOptions; WriteBytes(From, bytes, cur); cur += 8; switch (Type) { case MessageType.Client: WriteBytes(ToClient, bytes, cur); cur += 8; break; case MessageType.ClientPool: WriteBytes(ToClient, bytes, cur); cur += 8; if (ToPool != null) { WriteBytes(ToPool.Length, bytes, cur); } cur += 4; if (ToPool != null) { Encoding.UTF8.GetBytes(ToPool, 0, ToPool.Length, bytes, cur); cur += ToPool.Length; } break; case MessageType.Pool: case MessageType.PoolAll: if (ToPool != null) { WriteBytes(ToPool.Length, bytes, cur); } cur += 4; if (ToPool != null) { Encoding.UTF8.GetBytes(ToPool, 0, ToPool.Length, bytes, cur); cur += ToPool.Length; } break; } WriteBytes(Method.Length, bytes, cur); cur += 4; Encoding.UTF8.GetBytes(Method, 0, Method.Length, bytes, cur); cur += Method.Length; if (Json != null) { WriteBytes(Json.Length, bytes, cur); cur += 4; Encoding.UTF8.GetBytes(Json, 0, Json.Length, bytes, cur); cur += Json.Length; } else { cur += 4; } WriteBytes(RequestKey, bytes, cur); cur += 8; WriteBytes(PoolAllCount, bytes, cur); cur += 4; if (bytes.Length > 1024 * 1024 * 5) { throw new ArgumentException("The message is longer than 5mb."); } return bytes; } private static unsafe void WriteBytes(int value, byte[] buffer, int offset) { fixed (byte* numPtr = &buffer[offset]) *(int*)numPtr = value; } private static unsafe void WriteBytes(long value, byte[] buffer, int offset) { fixed (byte* numPtr = &buffer[offset]) *(long*)numPtr = value; } public static Message Parse(byte[] bytes) { try { var message = new Message(); int cur = 4; message.Direction = (MessageDirection)bytes[cur++]; message.Type = (MessageType)bytes[cur++]; message.ResponseOptions = (ResponseOptions)bytes[cur++]; message.From = BitConverter.ToInt64(bytes, cur); cur += 8; switch (message.Type) { case MessageType.Client: { message.ToClient = BitConverter.ToInt64(bytes, cur); cur += 8; break; } case MessageType.ClientPool: { message.ToClient = BitConverter.ToInt64(bytes, cur); cur += 8; var toPoolLength = BitConverter.ToInt32(bytes, cur); cur += 4; message.ToPool = Encoding.UTF8.GetString(bytes, cur, toPoolLength); cur += toPoolLength; break; } case MessageType.Pool: case MessageType.PoolAll: { var toPoolLength = BitConverter.ToInt32(bytes, cur); cur += 4; message.ToPool = Encoding.UTF8.GetString(bytes, cur, toPoolLength); cur += toPoolLength; break; } } var methodLength = BitConverter.ToInt32(bytes, cur); cur += 4; message.Method = Encoding.UTF8.GetString(bytes, cur, methodLength); cur += methodLength; var jsonLength = BitConverter.ToInt32(bytes, cur); cur += 4; if (jsonLength > 0) { message.Json = Encoding.UTF8.GetString(bytes, cur, jsonLength); cur += jsonLength; } message.RequestKey = BitConverter.ToInt64(bytes, cur); cur += 8; message.PoolAllCount = BitConverter.ToInt32(bytes, cur); cur += 4; return message; } catch (Exception ex) { Console.WriteLine("Failed Receive message:"); Console.WriteLine($"{Encoding.UTF8.GetString(bytes)}"); Console.WriteLine($"{ex}"); return null; } } public T GetJson<T>() { if (Json != null) return Json.FromJson<T>(); return default(T); } public static Message BuildServerRequest(string method, ResponseOptions options = ResponseOptions.SingleResponse) { return new Message() { Method = method, Direction = MessageDirection.Request, Type = MessageType.Server, ResponseOptions = options }; } public static Message BuildServerResponse(string method, ResponseOptions options = ResponseOptions.SingleResponse) { return new Message() { Method = method, Direction = MessageDirection.Response, Type = MessageType.Client, ResponseOptions = options }; } } public enum ResponseOptions { SingleResponse = 1, OpenResponse = 2 } public enum MessageDirection { Request = 1, Response = 2 } public enum MessageType { Client = 1, ClientPool=2, Pool = 3, PoolAll = 4, Server = 5 } }
/* * * (c) Copyright Ascensio System Limited 2010-2021 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.Mime.vCard { /// <summary> /// vCard delivery address implementation. /// </summary> public class DeliveryAddress { #region Members private readonly Item m_pItem; private string m_Country = ""; private string m_ExtendedAddress = ""; private string m_Locality = ""; private string m_PostalCode = ""; private string m_PostOfficeAddress = ""; private string m_Region = ""; private string m_Street = ""; private DeliveryAddressType_enum m_Type = DeliveryAddressType_enum.Ineternational | DeliveryAddressType_enum.Postal | DeliveryAddressType_enum.Parcel | DeliveryAddressType_enum.Work; #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="item">Owner vCard item.</param> /// <param name="addressType">Address type. Note: This value can be flagged value !</param> /// <param name="postOfficeAddress">Post office address.</param> /// <param name="extendedAddress">Extended address.</param> /// <param name="street">Street name.</param> /// <param name="locality">Locality(city).</param> /// <param name="region">Region.</param> /// <param name="postalCode">Postal code.</param> /// <param name="country">Country.</param> internal DeliveryAddress(Item item, DeliveryAddressType_enum addressType, string postOfficeAddress, string extendedAddress, string street, string locality, string region, string postalCode, string country) { m_pItem = item; m_Type = addressType; m_PostOfficeAddress = postOfficeAddress; m_ExtendedAddress = extendedAddress; m_Street = street; m_Locality = locality; m_Region = region; m_PostalCode = postalCode; m_Country = country; } #endregion #region Properties /// <summary> /// Gets or sets address type. Note: This property can be flagged value ! /// </summary> public DeliveryAddressType_enum AddressType { get { return m_Type; } set { m_Type = value; Changed(); } } /// <summary> /// Gets or sets country. /// </summary> public string Country { get { return m_Country; } set { m_Country = value; Changed(); } } /// <summary> /// Gests or sets extended address. /// </summary> public string ExtendedAddress { get { return m_ExtendedAddress; } set { m_ExtendedAddress = value; Changed(); } } /// <summary> /// Gets underlaying vCrad item. /// </summary> public Item Item { get { return m_pItem; } } /// <summary> /// Gets or sets locality(city). /// </summary> public string Locality { get { return m_Locality; } set { m_Locality = value; Changed(); } } /// <summary> /// Gets or sets postal code. /// </summary> public string PostalCode { get { return m_PostalCode; } set { m_PostalCode = value; Changed(); } } /// <summary> /// Gets or sets post office address. /// </summary> public string PostOfficeAddress { get { return m_PostOfficeAddress; } set { m_PostOfficeAddress = value; Changed(); } } /// <summary> /// Gets or sets region. /// </summary> public string Region { get { return m_Region; } set { m_Region = value; Changed(); } } /// <summary> /// Gets or sets street. /// </summary> public string Street { get { return m_Street; } set { m_Street = value; Changed(); } } #endregion #region Internal methods /// <summary> /// Parses delivery address from vCard ADR structure string. /// </summary> /// <param name="item">vCard ADR item.</param> internal static DeliveryAddress Parse(Item item) { DeliveryAddressType_enum type = DeliveryAddressType_enum.NotSpecified; if (item.ParametersString.ToUpper().IndexOf("PREF") != -1) { type |= DeliveryAddressType_enum.Preferred; } if (item.ParametersString.ToUpper().IndexOf("DOM") != -1) { type |= DeliveryAddressType_enum.Domestic; } if (item.ParametersString.ToUpper().IndexOf("INTL") != -1) { type |= DeliveryAddressType_enum.Ineternational; } if (item.ParametersString.ToUpper().IndexOf("POSTAL") != -1) { type |= DeliveryAddressType_enum.Postal; } if (item.ParametersString.ToUpper().IndexOf("PARCEL") != -1) { type |= DeliveryAddressType_enum.Parcel; } if (item.ParametersString.ToUpper().IndexOf("HOME") != -1) { type |= DeliveryAddressType_enum.Home; } if (item.ParametersString.ToUpper().IndexOf("WORK") != -1) { type |= DeliveryAddressType_enum.Work; } string[] items = item.DecodedValue.Split(';'); return new DeliveryAddress(item, type, items.Length >= 1 ? items[0] : "", items.Length >= 2 ? items[1] : "", items.Length >= 3 ? items[2] : "", items.Length >= 4 ? items[3] : "", items.Length >= 5 ? items[4] : "", items.Length >= 6 ? items[5] : "", items.Length >= 7 ? items[6] : ""); } /// <summary> /// Converts DeliveryAddressType_enum to vCard item parameters string. /// </summary> /// <param name="type">Value to convert.</param> /// <returns></returns> internal static string AddressTypeToString(DeliveryAddressType_enum type) { string retVal = ""; if ((type & DeliveryAddressType_enum.Domestic) != 0) { retVal += "DOM,"; } if ((type & DeliveryAddressType_enum.Home) != 0) { retVal += "HOME,"; } if ((type & DeliveryAddressType_enum.Ineternational) != 0) { retVal += "INTL,"; } if ((type & DeliveryAddressType_enum.Parcel) != 0) { retVal += "PARCEL,"; } if ((type & DeliveryAddressType_enum.Postal) != 0) { retVal += "POSTAL,"; } if ((type & DeliveryAddressType_enum.Preferred) != 0) { retVal += "Preferred,"; } if ((type & DeliveryAddressType_enum.Work) != 0) { retVal += "Work,"; } if (retVal.EndsWith(",")) { retVal = retVal.Substring(0, retVal.Length - 1); } return retVal; } #endregion #region Utility methods /// <summary> /// This method is called when some property has changed, we need to update underlaying vCard item. /// </summary> private void Changed() { string value = "" + m_PostOfficeAddress + ";" + m_ExtendedAddress + ";" + m_Street + ";" + m_Locality + ";" + m_Region + ";" + m_PostalCode + ";" + m_Country; m_pItem.ParametersString = AddressTypeToString(m_Type); m_pItem.SetDecodedValue(value); } #endregion } }
namespace QarnotSDK.UnitTests { using System; using System.Collections.Generic; using NUnit.Framework; using QarnotSDK; [TestFixture] public class DataDetailTests { [Test] public void GetPropertyInfoInvalidReturnTypeShouldFail() { Exception ex = Assert.Throws<ArgumentException>(() => DataDetailHelper.GetAPIFilterPropertyName<QTask, string>(t => "basic string")); Assert.IsNotNull(ex); } [Test] public void GetPropertyInfoNullFuncShouldFail() { Exception ex = Assert.Throws<ArgumentNullException>(() => DataDetailHelper.GetAPIFilterPropertyName<QTask, string>(null)); Assert.IsNotNull(ex); } [Test] public void GetAPIFilterPoolPropertyNameAsUuidReturnTheGoodStringValue() { var value = DataDetailHelper.GetAPIFilterPropertyName<QPool, Guid>(t => t.Uuid); Assert.AreEqual(value, "Uuid"); } [Test] public void GetAPISelectPoolPropertyNameAsUuidReturnTheGoodStringValue() { var value = DataDetailHelper.GetAPISelectPropertyName<QPool, Guid>(t => t.Uuid); Assert.AreEqual(value, "Uuid"); } [Test] public void GetAPIFilterPropertyNameForPoolConnectionShouldFail() { Exception ex = Assert.Throws<Exception>(() => DataDetailHelper.GetAPIFilterPropertyName<QPool, Connection>(t => t.Connection)); Assert.IsNotNull(ex); } [Test] public void GetAPISelectPropertyNameForPoolConnectionShouldFail() { Exception ex = Assert.Throws<Exception>(() => DataDetailHelper.GetAPISelectPropertyName<QPool, Connection>(t => t.Connection)); Assert.IsNotNull(ex); } [Test] public void GetAPIFilterPropertyNameForTaskUuidReturnTheGoodStringValue() { var value = DataDetailHelper.GetAPIFilterPropertyName<QTask, Guid>(t => t.Uuid); Assert.AreEqual(value, "Uuid"); } [Test] public void GetAPISelectPropertyNameForTaskUuidReturnTheGoodStringValue() { var value = DataDetailHelper.GetAPISelectPropertyName<QTask, Guid>(t => t.Uuid); Assert.AreEqual(value, "Uuid"); } [Test] public void GetAPIFilterPropertyNameForTaskConnectionShouldFail() { Exception ex = Assert.Throws<Exception>(() => DataDetailHelper.GetAPIFilterPropertyName<QTask, Connection>(t => t.Connection)); Assert.IsNotNull(ex); } [Test] public void GetAPISelectPropertyNameForTaskConnectionShouldFail() { Exception ex = Assert.Throws<Exception>(() => DataDetailHelper.GetAPISelectPropertyName<QTask, Connection>(t => t.Connection)); Assert.IsNotNull(ex); } [Test] public void GetAPIFilterPropertyNameForJobPoolShouldFail() { Exception ex = Assert.Throws<Exception>(() => DataDetailHelper.GetAPIFilterPropertyName<QJob, QPool>(t => t.Pool)); Assert.IsNotNull(ex); } [Test] public void GetAPISelectPropertyNameForJobPoolShouldFail() { Exception ex = Assert.Throws<Exception>(() => DataDetailHelper.GetAPISelectPropertyName<QJob, QPool>(t => t.Pool)); Assert.IsNotNull(ex); } [Test] public void GetAPIFilterPropertyNameForMaxWallTimeShouldFail() { Exception ex = Assert.Throws<Exception>(() => DataDetailHelper.GetAPIFilterPropertyName<QJob, TimeSpan>(t => t.MaximumWallTime)); Assert.IsNotNull(ex); } [Test] public void GetAPISelectPropertyNameForMaxWallTimeShouldFail() { Exception ex = Assert.Throws<Exception>(() => DataDetailHelper.GetAPISelectPropertyName<QJob, TimeSpan>(t => t.MaximumWallTime)); Assert.IsNotNull(ex); } [Test] public void GetAPIFilterPropertyNameForJobUseDependenciesReturnTheGoodStringValue() { var value = DataDetailHelper.GetAPIFilterPropertyName<QJob, bool>(t => t.UseDependencies); Assert.AreEqual(value, "UseDependencies"); } [Test] public void GetAPISelectPropertyNameForJobUseDependenciesReturnTheGoodStringValue() { var value = DataDetailHelper.GetAPISelectPropertyName<QJob, bool>(t => t.UseDependencies); Assert.AreEqual(value, "UseDependencies"); } [Test] public void GetAPIFilterPropertyNameForJobLastModifiedReturnTheGoodStringValue() { var value = DataDetailHelper.GetAPIFilterPropertyName<QJob, System.DateTime?>(t => t.LastModified); Assert.AreEqual(value, "LastModified"); } [Test] public void GetAPISelectPropertyNameForJobLastModifiedReturnTheGoodStringValue() { var value = DataDetailHelper.GetAPISelectPropertyName<QJob, System.DateTime?>(t => t.LastModified); Assert.AreEqual(value, "LastModified"); } [Test] public void GetAPIFilterPropertyNameForJobCreationDateReturnTheGoodStringValue() { var value = DataDetailHelper.GetAPIFilterPropertyName<QJob, System.DateTime?>(t => t.CreationDate); Assert.AreEqual(value, "CreationDate"); } [Test] public void GetAPISelectPropertyNameForJobCreationDateReturnTheGoodStringValue() { var value = DataDetailHelper.GetAPISelectPropertyName<QJob, System.DateTime>(t => t.CreationDate); Assert.AreEqual(value, "CreationDate"); } [Test] public void GetAPIFilterPropertyNameForJobStateReturnTheGoodStringValue() { var value = DataDetailHelper.GetAPIFilterPropertyName<QJob, string>(t => t.State); Assert.AreEqual(value, "State"); } [Test] public void GetAPISelectPropertyNameForJobStateReturnTheGoodStringValue() { var value = DataDetailHelper.GetAPISelectPropertyName<QJob, string>(t => t.State); Assert.AreEqual(value, "State"); } [Test] public void GetAPIFilterPropertyNameForJobPoolUuidReturnTheGoodStringValue() { var value = DataDetailHelper.GetAPIFilterPropertyName<QJob, Guid>(t => t.PoolUuid); Assert.AreEqual(value, "PoolUuid"); } [Test] public void GetAPISelectPropertyNameForJobPoolUuidReturnTheGoodStringValue() { var value = DataDetailHelper.GetAPISelectPropertyName<QJob, Guid>(t => t.PoolUuid); Assert.AreEqual(value, "PoolUuid"); } [Test] public void GetAPIFilterPropertyNameForJobNameReturnTheGoodStringValue() { var value = DataDetailHelper.GetAPIFilterPropertyName<QJob, string>(t => t.Name); Assert.AreEqual(value, "Name"); } [Test] public void GetAPISelectPropertyNameForJobNameReturnTheGoodStringValue() { var value = DataDetailHelper.GetAPISelectPropertyName<QJob, string>(t => t.Name); Assert.AreEqual(value, "Name"); } [Test] public void GetAPIFilterPropertyNameForJobShortnameReturnTheGoodStringValue() { var value = DataDetailHelper.GetAPIFilterPropertyName<QJob, string>(t => t.Shortname); Assert.AreEqual(value, "Shortname"); } [Test] public void GetAPISelectPropertyNameForJobShortnameReturnTheGoodStringValue() { var value = DataDetailHelper.GetAPISelectPropertyName<QJob, string>(t => t.Shortname); Assert.AreEqual(value, "Shortname"); } [Test] public void GetAPIFilterPropertyNameForJobSelfUuidReturnTheGoodStringValue() { var value = DataDetailHelper.GetAPIFilterPropertyName<QJob, Guid>(t => t.Uuid); Assert.AreEqual(value, "Uuid"); } [Test] public void GetAPISelectPropertyNameForJobSelfUuidReturnTheGoodStringValue() { var value = DataDetailHelper.GetAPISelectPropertyName<QJob, Guid>(t => t.Uuid); Assert.AreEqual(value, "Uuid"); } [Test] public void GetAPIFilterPropertyNameForPoolElasticMinimumIdlingTimeReturnTheGoodStringValue() { var value = DataDetailHelper.GetAPIFilterPropertyName<QPool, uint>(t => t.ElasticMinimumIdlingTime); Assert.AreEqual(value, "ElasticProperty.MinIdleTimeSeconds"); } [Test] public void GetAPISelectPropertyNameForPoolElasticMinimumIdlingTimeReturnTheGoodStringValue() { var value = DataDetailHelper.GetAPISelectPropertyName<QPool, uint>(t => t.ElasticMinimumIdlingTime); Assert.AreEqual(value, "ElasticProperty.MinIdleTimeSeconds"); } [Test] public void GetAPIFilterPropertyNameForPoolElasticResizeFactorReturnTheGoodStringValue() { var value = DataDetailHelper.GetAPIFilterPropertyName<QPool, float>(t => t.ElasticResizeFactor); Assert.AreEqual(value, "ElasticProperty.RampResizeFactor"); } [Test] public void GetAPISelectPropertyNameForPoolElasticResizeFactorReturnTheGoodStringValue() { var value = DataDetailHelper.GetAPISelectPropertyName<QPool, float>(t => t.ElasticResizeFactor); Assert.AreEqual(value, "ElasticProperty.RampResizeFactor"); } [Test] public void GetAPIFilterPropertyNameForPoolElasticResizePeriodReturnTheGoodStringValue() { var value = DataDetailHelper.GetAPIFilterPropertyName<QPool, uint>(t => t.ElasticResizePeriod); Assert.AreEqual(value, "ElasticProperty.ResizePeriod"); } [Test] public void GetAPISelectPropertyNameForPoolElasticResizePeriodReturnTheGoodStringValue() { var value = DataDetailHelper.GetAPISelectPropertyName<QPool, uint>(t => t.ElasticResizePeriod); Assert.AreEqual(value, "ElasticProperty.ResizePeriod"); } [Test] public void GetAPIFilterPropertyNameForPoolElasticMinimumIdlingNodesReturnTheGoodStringValue() { var value = DataDetailHelper.GetAPIFilterPropertyName<QPool, uint>(t => t.ElasticMinimumIdlingNodes); Assert.AreEqual(value, "ElasticProperty.MinIdleSlots"); } [Test] public void GetAPISelectPropertyNameForPoolElasticMinimumIdlingNodesReturnTheGoodStringValue() { var value = DataDetailHelper.GetAPISelectPropertyName<QPool, uint>(t => t.ElasticMinimumIdlingNodes); Assert.AreEqual(value, "ElasticProperty.MinIdleSlots"); } [Test] public void GetAPIFilterPropertyNameForPoolElasticMaximumTotalNodesReturnTheGoodStringValue() { var value = DataDetailHelper.GetAPIFilterPropertyName<QPool, uint>(t => t.ElasticMaximumTotalNodes); Assert.AreEqual(value, "ElasticProperty.MaxTotalSlots"); } [Test] public void GetAPISelectPropertyNameForPoolElasticMaximumTotalNodesReturnTheGoodStringValue() { var value = DataDetailHelper.GetAPISelectPropertyName<QPool, uint>(t => t.ElasticMaximumTotalNodes); Assert.AreEqual(value, "ElasticProperty.MaxTotalSlots"); } [Test] public void GetAPIFilterPropertyNameForPoolElasticMinimumTotalNodesReturnTheGoodStringValue() { var value = DataDetailHelper.GetAPIFilterPropertyName<QPool, uint>(t => t.ElasticMinimumTotalNodes); Assert.AreEqual(value, "ElasticProperty.MinTotalSlots"); } [Test] public void GetAPISelectPropertyNameForPoolElasticMinimumTotalNodesReturnTheGoodStringValue() { var value = DataDetailHelper.GetAPISelectPropertyName<QPool, uint>(t => t.ElasticMinimumTotalNodes); Assert.AreEqual(value, "ElasticProperty.MinTotalSlots"); } [Test] public void GetAPISelectPropertyNameForPoolIsElasticReturnTheGoodStringValue() { var value = DataDetailHelper.GetAPISelectPropertyName<QPool, bool>(t => t.IsElastic); Assert.AreEqual(value, "ElasticProperty.IsElastic"); } [Test] public void GetAPIFilterPropertyNameForPoolPreparationCommandLineReturnTheGoodStringValue() { var value = DataDetailHelper.GetAPIFilterPropertyName<QPool, string>(t => t.PreparationCommandLine); Assert.AreEqual(value, "PreparationTask.CommandLine"); } [Test] public void GetAPIFilterPropertyNameForPoolConstraintsShouldFail() { Exception ex = Assert.Throws<Exception>(() => DataDetailHelper.GetAPIFilterPropertyName<QPool, Dictionary<string, string>>(t => t.Constraints)); Assert.IsNotNull(ex); } [Test] public void GetAPISelectPropertyNameForPoolConstraintsReturnTheGoodStringValue() { var value = DataDetailHelper.GetAPISelectPropertyName<QPool, Dictionary<string, string>>(t => t.Constraints); Assert.AreEqual(value, "Constraints"); } [Test] public void GetAPIFilterPropertyNameForPoolConstantsShouldFail() { Exception ex = Assert.Throws<Exception>(() => DataDetailHelper.GetAPIFilterPropertyName<QPool, Dictionary<string, string>>(t => t.Constants)); Assert.IsNotNull(ex); } [Test] public void GetAPISelectPropertyNameForPoolConstantsReturnTheGoodStringValue() { var value = DataDetailHelper.GetAPISelectPropertyName<QPool, Dictionary<string, string>>(t => t.Constants); Assert.AreEqual(value, "Constants"); } [Test] public void GetAPIFilterPropertyNameForPoolTagsReturnTheGoodStringValue() { var value = DataDetailHelper.GetAPIFilterPropertyName<QPool, List<string>>(t => t.Tags); Assert.AreEqual(value, "Tags"); } [Test] public void GetAPISelectPropertyNameForPoolTagsReturnTheGoodStringValue() { var value = DataDetailHelper.GetAPISelectPropertyName<QPool, List<string>>(t => t.Tags); Assert.AreEqual(value, "Tags"); } [Test] public void GetAPIFilterPropertyNameForPoolNodeCountReturnTheGoodStringValue() { var value = DataDetailHelper.GetAPIFilterPropertyName<QPool, uint>(t => t.NodeCount); Assert.AreEqual(value, "InstanceCount"); } [Test] public void GetAPISelectPropertyNameForPoolNodeCountReturnTheGoodStringValue() { var value = DataDetailHelper.GetAPISelectPropertyName<QPool, uint>(t => t.NodeCount); Assert.AreEqual(value, "InstanceCount"); } [Test] public void GetAPIFilterPropertyNameForPoolCreationDateReturnTheGoodStringValue() { var value = DataDetailHelper.GetAPIFilterPropertyName<QPool, System.DateTime>(t => t.CreationDate); Assert.AreEqual(value, "CreationDate"); } [Test] public void GetAPISelectPropertyNameForPoolCreationDateReturnTheGoodStringValue() { var value = DataDetailHelper.GetAPISelectPropertyName<QPool, System.DateTime>(t => t.CreationDate); Assert.AreEqual(value, "CreationDate"); } [Test] public void GetAPIFilterPropertyNameForPoolStatusShouldFail() { Exception ex = Assert.Throws<Exception>(() => DataDetailHelper.GetAPIFilterPropertyName<QPool, QarnotSDK.QPoolStatus>(t => t.Status)); Assert.IsNotNull(ex); } [Test] public void GetAPISelectPropertyNameForPoolStatusReturnTheGoodStringValue() { var value = DataDetailHelper.GetAPISelectPropertyName<QPool, QarnotSDK.QPoolStatus>(t => t.Status); Assert.AreEqual(value, "Status"); } [Test] public void GetAPIFilterPropertyNameForPoolErrorsShouldFail() { Exception ex = Assert.Throws<Exception>(() => DataDetailHelper.GetAPIFilterPropertyName<QPool, List<QarnotSDK.QPoolError>>(t => t.Errors)); Assert.IsNotNull(ex); } [Test] public void GetAPISelectPropertyNameForPoolErrorsReturnTheGoodStringValue() { var value = DataDetailHelper.GetAPISelectPropertyName<QPool, List<QarnotSDK.QPoolError>>(t => t.Errors); Assert.AreEqual(value, "Errors"); } [Test] public void GetAPIFilterPropertyNameForPoolStateReturnTheGoodStringValue() { var value = DataDetailHelper.GetAPIFilterPropertyName<QPool, string>(t => t.State); Assert.AreEqual(value, "State"); } [Test] public void GetAPISelectPropertyNameForPoolStateReturnTheGoodStringValue() { var value = DataDetailHelper.GetAPISelectPropertyName<QPool, string>(t => t.State); Assert.AreEqual(value, "State"); } [Test] public void GetAPIFilterPropertyNameForPoolResourcesShouldFail() { Exception ex = Assert.Throws<Exception>(() => DataDetailHelper.GetAPIFilterPropertyName<QPool, List<QarnotSDK.QAbstractStorage>>(t => t.Resources)); Assert.IsNotNull(ex); } [Test] public void GetAPISelectPropertyNameForPoolResourcesShouldFail() { Exception ex = Assert.Throws<Exception>(() => DataDetailHelper.GetAPISelectPropertyName<QPool, List<QarnotSDK.QAbstractStorage>>(t => t.Resources)); Assert.IsNotNull(ex); } [Test] public void GetAPIFilterPropertyNameForPoolProfileReturnTheGoodStringValue() { var value = DataDetailHelper.GetAPIFilterPropertyName<QPool, string>(t => t.Profile); Assert.AreEqual(value, "Profile"); } [Test] public void GetAPISelectPropertyNameForPoolProfileReturnTheGoodStringValue() { var value = DataDetailHelper.GetAPISelectPropertyName<QPool, string>(t => t.Profile); Assert.AreEqual(value, "Profile"); } [Test] public void GetAPIFilterPropertyNameForPoolNameReturnTheGoodStringValue() { var value = DataDetailHelper.GetAPIFilterPropertyName<QPool, string>(t => t.Name); Assert.AreEqual(value, "Name"); } [Test] public void GetAPISelectPropertyNameForPoolNameReturnTheGoodStringValue() { var value = DataDetailHelper.GetAPISelectPropertyName<QPool, string>(t => t.Name); Assert.AreEqual(value, "Name"); } [Test] public void GetAPIFilterPropertyNameForPoolShortnameReturnTheGoodStringValue() { var value = DataDetailHelper.GetAPIFilterPropertyName<QPool, string>(t => t.Shortname); Assert.AreEqual(value, "Shortname"); } [Test] public void GetAPISelectPropertyNameForPoolShortnameReturnTheGoodStringValue() { var value = DataDetailHelper.GetAPISelectPropertyName<QPool, string>(t => t.Shortname); Assert.AreEqual(value, "Shortname"); } [Test] public void GetAPIFilterPropertyNameForSnapshotBlacklistReturnTheGoodStringValue() { var value = DataDetailHelper.GetAPIFilterPropertyName<QTask, string>(t => t.SnapshotBlacklist); Assert.AreEqual(value, "SnapshotBlacklist"); } [Test] public void GetAPISelectPropertyNameForSnapshotBlacklistReturnTheGoodStringValue() { var value = DataDetailHelper.GetAPISelectPropertyName<QTask, string>(t => t.SnapshotBlacklist); Assert.AreEqual(value, "SnapshotBlacklist"); } [Test] public void GetAPIFilterPropertyNameForSnapshotWhitelistReturnTheGoodStringValue() { var value = DataDetailHelper.GetAPIFilterPropertyName<QTask, string>(t => t.SnapshotWhitelist); Assert.AreEqual(value, "SnapshotWhitelist"); } [Test] public void GetAPISelectPropertyNameForSnapshotWhitelistReturnTheGoodStringValue() { var value = DataDetailHelper.GetAPISelectPropertyName<QTask, string>(t => t.SnapshotWhitelist); Assert.AreEqual(value, "SnapshotWhitelist"); } [Test] public void GetAPIFilterPropertyNameForResultsBlacklistReturnTheGoodStringValue() { var value = DataDetailHelper.GetAPIFilterPropertyName<QTask, string>(t => t.ResultsBlacklist); Assert.AreEqual(value, "ResultsBlacklist"); } [Test] public void GetAPISelectPropertyNameForResultsBlacklistReturnTheGoodStringValue() { var value = DataDetailHelper.GetAPISelectPropertyName<QTask, string>(t => t.ResultsBlacklist); Assert.AreEqual(value, "ResultsBlacklist"); } [Test] public void GetAPIFilterPropertyNameForResultsWhitelistReturnTheGoodStringValue() { var value = DataDetailHelper.GetAPIFilterPropertyName<QTask, string>(t => t.ResultsWhitelist); Assert.AreEqual(value, "ResultsWhitelist"); } [Test] public void GetAPISelectPropertyNameForResultsWhitelistReturnTheGoodStringValue() { var value = DataDetailHelper.GetAPISelectPropertyName<QTask, string>(t => t.ResultsWhitelist); Assert.AreEqual(value, "ResultsWhitelist"); } [Test] public void GetAPIFilterPropertyNameForInstanceCountReturnTheGoodStringValue() { var value = DataDetailHelper.GetAPIFilterPropertyName<QTask, uint>(t => t.InstanceCount); Assert.AreEqual(value, "InstanceCount"); } [Test] public void GetAPISelectPropertyNameForInstanceCountReturnTheGoodStringValue() { var value = DataDetailHelper.GetAPISelectPropertyName<QTask, uint>(t => t.InstanceCount); Assert.AreEqual(value, "InstanceCount"); } [Test] public void GetAPIFilterPropertyNameForExecutingShouldFail() { Exception ex = Assert.Throws<Exception>(() => DataDetailHelper.GetAPIFilterPropertyName<QTask, bool>(t => t.Executing)); Assert.IsNotNull(ex); } [Test] public void GetAPISelectPropertyNameForExecutingShouldFail() { Exception ex = Assert.Throws<Exception>(() => DataDetailHelper.GetAPISelectPropertyName<QTask, bool>(t => t.Executing)); Assert.IsNotNull(ex); } [Test] public void GetAPIFilterPropertyNameForCompletedShouldFail() { Exception ex = Assert.Throws<Exception>(() => DataDetailHelper.GetAPIFilterPropertyName<QTask, bool>(t => t.Completed)); Assert.IsNotNull(ex); } [Test] public void GetAPISelectPropertyNameForCompletedShouldFail() { Exception ex = Assert.Throws<Exception>(() => DataDetailHelper.GetAPISelectPropertyName<QTask, bool>(t => t.Completed)); Assert.IsNotNull(ex); } [Test] public void GetAPIFilterPropertyNameForJobShouldFail() { Exception ex = Assert.Throws<Exception>(() => DataDetailHelper.GetAPIFilterPropertyName<QTask, QJob>(t => t.Job)); Assert.IsNotNull(ex); } [Test] public void GetAPISelectPropertyNameForJobShouldFail() { Exception ex = Assert.Throws<Exception>(() => DataDetailHelper.GetAPISelectPropertyName<QTask, QJob>(t => t.Job)); Assert.IsNotNull(ex); } [Test] public void GetAPIFilterPropertyNameForJobUuidReturnTheGoodStringValue() { var value = DataDetailHelper.GetAPIFilterPropertyName<QTask, System.Guid>(t => t.JobUuid); Assert.AreEqual(value, "JobUuid"); } [Test] public void GetAPISelectPropertyNameForJobUuidReturnTheGoodStringValue() { var value = DataDetailHelper.GetAPISelectPropertyName<QTask, System.Guid>(t => t.JobUuid); Assert.AreEqual(value, "JobUuid"); } [Test] public void GetAPIFilterPropertyNameForPoolShouldFail() { Exception ex = Assert.Throws<Exception>(() => DataDetailHelper.GetAPIFilterPropertyName<QTask, QPool>(t => t.Pool)); Assert.IsNotNull(ex); } [Test] public void GetAPISelectPropertyNameForPoolShouldFail() { Exception ex = Assert.Throws<Exception>(() => DataDetailHelper.GetAPISelectPropertyName<QTask, QPool>(t => t.Pool)); Assert.IsNotNull(ex); } [Test] public void GetAPIFilterPropertyNameForPoolUuidReturnTheGoodStringValue() { var value = DataDetailHelper.GetAPIFilterPropertyName<QTask, System.Guid>(t => t.PoolUuid); Assert.AreEqual(value, "PoolUuid"); } [Test] public void GetAPISelectPropertyNameForPoolUuidReturnTheGoodStringValue() { var value = DataDetailHelper.GetAPISelectPropertyName<QTask, System.Guid>(t => t.PoolUuid); Assert.AreEqual(value, "PoolUuid"); } [Test] public void GetAPIFilterPropertyNameForSnapshotIntervalReturnTheGoodStringValue() { var value = DataDetailHelper.GetAPIFilterPropertyName<QTask, int>(t => t.SnapshotInterval); Assert.AreEqual(value, "SnapshotInterval"); } [Test] public void GetAPISelectPropertyNameForSnapshotIntervalReturnTheGoodStringValue() { var value = DataDetailHelper.GetAPISelectPropertyName<QTask, int>(t => t.SnapshotInterval); Assert.AreEqual(value, "SnapshotInterval"); } [Test] public void GetAPIFilterPropertyNameForDependsOnReturnTheGoodStringValue() { var value = DataDetailHelper.GetAPIFilterPropertyName<QTask, List<System.Guid>>(t => t.DependsOn); Assert.AreEqual(value, "Dependencies.DependsOn"); } [Test] public void GetAPISelectPropertyNameForDependsOnReturnTheGoodStringValue() { var value = DataDetailHelper.GetAPISelectPropertyName<QTask, List<System.Guid>>(t => t.DependsOn); Assert.AreEqual(value, "Dependencies.DependsOn"); } [Test] public void GetAPIFilterPropertyNameForConstraintsReturnTheGoodStringValue() { var value = DataDetailHelper.GetAPIFilterPropertyName<QTask, Dictionary<string, string>>(t => t.Constraints); Assert.AreEqual(value, "Constraints"); } [Test] public void GetAPISelectPropertyNameForConstraintsReturnTheGoodStringValue() { var value = DataDetailHelper.GetAPISelectPropertyName<QTask, Dictionary<string, string>>(t => t.Constraints); Assert.AreEqual(value, "Constraints"); } [Test] public void GetAPIFilterPropertyNameForConstantsReturnTheGoodStringValue() { var value = DataDetailHelper.GetAPIFilterPropertyName<QTask, Dictionary<string, string>>(t => t.Constants); Assert.AreEqual(value, "Constants"); } [Test] public void GetAPISelectPropertyNameForConstantsReturnTheGoodStringValue() { var value = DataDetailHelper.GetAPISelectPropertyName<QTask, Dictionary<string, string>>(t => t.Constants); Assert.AreEqual(value, "Constants"); } [Test] public void GetAPIFilterPropertyNameForTagsReturnTheGoodStringValue() { var value = DataDetailHelper.GetAPIFilterPropertyName<QTask, List<string>>(t => t.Tags); Assert.AreEqual(value, "Tags"); } [Test] public void GetAPISelectPropertyNameForTagsReturnTheGoodStringValue() { var value = DataDetailHelper.GetAPISelectPropertyName<QTask, List<string>>(t => t.Tags); Assert.AreEqual(value, "Tags"); } [Test] public void GetAPIFilterPropertyNameForResultsCountReturnTheGoodStringValue() { var value = DataDetailHelper.GetAPIFilterPropertyName<QTask, uint>(t => t.ResultsCount); Assert.AreEqual(value, "ResultsCount"); } [Test] public void GetAPISelectPropertyNameForResultsCountReturnTheGoodStringValue() { var value = DataDetailHelper.GetAPISelectPropertyName<QTask, uint>(t => t.ResultsCount); Assert.AreEqual(value, "ResultsCount"); } [Test] public void GetAPIFilterPropertyNameForCreationDateReturnTheGoodStringValue() { var value = DataDetailHelper.GetAPIFilterPropertyName<QTask, System.DateTime>(t => t.CreationDate); Assert.AreEqual(value, "CreationDate"); } [Test] public void GetAPISelectPropertyNameForCreationDateReturnTheGoodStringValue() { var value = DataDetailHelper.GetAPISelectPropertyName<QTask, System.DateTime>(t => t.CreationDate); Assert.AreEqual(value, "CreationDate"); } [Test] public void GetAPIFilterPropertyNameForStatusShouldFail() { Exception ex = Assert.Throws<Exception>(() => DataDetailHelper.GetAPIFilterPropertyName<QTask, QarnotSDK.QTaskStatus>(t => t.Status)); Assert.IsNotNull(ex); } [Test] public void GetAPISelectPropertyNameForStatusReturnTheGoodStringValue() { var value = DataDetailHelper.GetAPISelectPropertyName<QTask, QarnotSDK.QTaskStatus>(t => t.Status); Assert.AreEqual(value, "Status"); } [Test] public void GetAPIFilterPropertyNameForErrorsShouldFail() { Exception ex = Assert.Throws<Exception>(() => DataDetailHelper.GetAPIFilterPropertyName<QTask, List<QarnotSDK.QTaskError>>(t => t.Errors)); Assert.IsNotNull(ex); } [Test] public void GetAPISelectPropertyNameForErrorsReturnTheGoodStringValue() { var value = DataDetailHelper.GetAPISelectPropertyName<QTask, List<QarnotSDK.QTaskError>>(t => t.Errors); Assert.AreEqual(value, "Errors"); } [Test] public void GetAPIFilterPropertyNameForStateReturnTheGoodStringValue() { var value = DataDetailHelper.GetAPIFilterPropertyName<QTask, string>(t => t.State); Assert.AreEqual(value, "State"); } [Test] public void GetAPISelectPropertyNameForStateReturnTheGoodStringValue() { var value = DataDetailHelper.GetAPISelectPropertyName<QTask, string>(t => t.State); Assert.AreEqual(value, "State"); } [Test] public void GetAPIFilterPropertyNameForResultBucketReturnTheGoodStringValue() { var value = DataDetailHelper.GetAPIFilterPropertyName<QTask, QBucket>(t => t.ResultsBucket); Assert.AreEqual(value, "ResultBucket"); } [Test] public void GetAPISelectPropertyNameForResultBucketReturnTheGoodStringValue() { var value = DataDetailHelper.GetAPISelectPropertyName<QTask, QBucket>(t => t.ResultsBucket); Assert.AreEqual(value, "ResultBucket"); } [Test] public void GetAPIFilterPropertyNameForResultsShouldFail() { Exception ex = Assert.Throws<Exception>(() => DataDetailHelper.GetAPIFilterPropertyName<QTask, QarnotSDK.QAbstractStorage>(t => t.Results)); Assert.IsNotNull(ex); } [Test] public void GetAPISelectPropertyNameForResultsShouldFail() { Exception ex = Assert.Throws<Exception>(() => DataDetailHelper.GetAPISelectPropertyName<QTask, QarnotSDK.QAbstractStorage>(t => t.Results)); Assert.IsNotNull(ex); } [Test] public void GetAPIFilterPropertyNameForResourcesBucketsShouldFail() { Exception ex = Assert.Throws<Exception>(() => DataDetailHelper.GetAPIFilterPropertyName<QTask, IEnumerable<QarnotSDK.QBucket>>(t => t.ResourcesBuckets)); Assert.IsNotNull(ex); } [Test] public void GetAPISelectPropertyNameForResourcesBucketsReturnTheGoodStringValue() { var value = DataDetailHelper.GetAPISelectPropertyName<QTask, IEnumerable<QarnotSDK.QBucket>>(t => t.ResourcesBuckets); Assert.AreEqual(value, "ResourceBuckets"); } [Test] public void GetAPIFilterPropertyNameForResourcesShouldFail() { Exception ex = Assert.Throws<Exception>(() => DataDetailHelper.GetAPIFilterPropertyName<QTask, List<QarnotSDK.QAbstractStorage>>(t => t.Resources)); Assert.IsNotNull(ex); } [Test] public void GetAPISelectPropertyNameForResourcesShouldFail() { Exception ex = Assert.Throws<Exception>(() => DataDetailHelper.GetAPISelectPropertyName<QTask, List<QarnotSDK.QAbstractStorage>>(t => t.Resources)); Assert.IsNotNull(ex); } [Test] public void GetAPIFilterPropertyNameForProfileReturnTheGoodStringValue() { var value = DataDetailHelper.GetAPIFilterPropertyName<QTask, string>(t => t.Profile); Assert.AreEqual(value, "Profile"); } [Test] public void GetAPISelectPropertyNameForProfileReturnTheGoodStringValue() { var value = DataDetailHelper.GetAPISelectPropertyName<QTask, string>(t => t.Profile); Assert.AreEqual(value, "Profile"); } [Test] public void GetAPIFilterPropertyNameForShortnameReturnTheGoodStringValue() { var value = DataDetailHelper.GetAPIFilterPropertyName<QTask, string>(t => t.Shortname); Assert.AreEqual(value, "Shortname"); } [Test] public void GetAPISelectPropertyNameForShortnameReturnTheGoodStringValue() { var value = DataDetailHelper.GetAPISelectPropertyName<QTask, string>(t => t.Shortname); Assert.AreEqual(value, "Shortname"); } [Test] public void GetAPIFilterPropertyNameForNameReturnTheGoodStringValue() { var value = DataDetailHelper.GetAPIFilterPropertyName<QTask, string>(t => t.Name); Assert.AreEqual(value, "Name"); } [Test] public void GetAPISelectPropertyNameForNameReturnTheGoodStringValue() { var value = DataDetailHelper.GetAPISelectPropertyName<QTask, string>(t => t.Name); Assert.AreEqual(value, "Name"); } } [TestFixture] public class UnitTestQSelect { [Test] public void SelectIncludeAllTest() { var select = QSelect<QPool>.Select() .Include(t => t.Name) .Include(t => t.Uuid) .Include(t => t.Constants) .Include(t => t.Constraints) .Include(t => t.CreationDate) .Include(t => t.ElasticMaximumTotalNodes) .Include(t => t.ElasticMinimumIdlingNodes) .Include(t => t.ElasticMinimumIdlingTime) .Include(t => t.ElasticMinimumTotalNodes) .Include(t => t.ElasticResizeFactor) .Include(t => t.ElasticResizePeriod) .Include(t => t.Errors) .Include(t => t.IsElastic) .Include(t => t.NodeCount) .Include(t => t.Profile) .Include(t => t.ResourcesBuckets) .Include(t => t.Shortname) .Include(t => t.State) .Include(t => t.Status) .Include(t => t.Tags) .Include(t => t.Uuid); string tostring = select.ToString(); string waitstring = "<Fields: Name,Uuid,Constants,Constraints,CreationDate,ElasticProperty.MaxTotalSlots,ElasticProperty.MinIdleSlots,ElasticProperty.MinIdleTimeSeconds,ElasticProperty.MinTotalSlots,ElasticProperty.RampResizeFactor,ElasticProperty.ResizePeriod,Errors,ElasticProperty.IsElastic,InstanceCount,Profile,ResourceBuckets,Shortname,State,Status,Tags,Uuid>"; Assert.AreEqual(tostring, waitstring); var select2 = QSelect<QTask>.Select() .Include(t => t.Name) .Include(t => t.Uuid) .Include(t => t.Constants) .Include(t => t.Constraints) .Include(t => t.CreationDate) .Include(t => t.Errors) .Include(t => t.Profile) .Include(t => t.ResourcesBuckets) .Include(t => t.Shortname) .Include(t => t.State) .Include(t => t.Status) .Include(t => t.Tags) .Include(t => t.Uuid); tostring = select2.ToString(); waitstring = "<Fields: Name,Uuid,Constants,Constraints,CreationDate,Errors,Profile,ResourceBuckets,Shortname,State,Status,Tags,Uuid>"; Assert.AreEqual(tostring, waitstring); } [Test] public void SelectIncludeBasicTest() { var select = QSelect<QTask>.Select() .Include(t => t.Name) .Include(t => t.Uuid) .Include(t => t.State); select.Include(t => t.Status); string tostring = select.ToString(); string waitstring = "<Fields: Name,Uuid,State,Status>"; Assert.AreEqual(tostring, waitstring); } [Test] public void SelectSimpleBasicTest() { var select = QSelect<QTask>.Select(); select = QSelect<QTask>.Select(t => t.Name); string tostring = select.ToString(); string waitstring = "<Fields: Name>"; Assert.AreEqual(tostring, waitstring); } } [TestFixture] public class UnitTestQDataDetail { [Test] public void DataDetailTests() { var regexDetails = new QDataDetail<QTask>(); regexDetails = new QDataDetail<QTask>() { Filter = QFilter<QTask>.And(new[] { QFilter<QTask>.Or( QFilter<QTask>.Eq(t => t.State, QTaskStates.Submitted), QFilter<QTask>.Eq(t => t.State, QTaskStates.Cancelled), QFilter<QTask>.Eq(t => t.State, QTaskStates.Failure), QFilter<QTask>.In(t => t.State, new[] { QTaskStates.FullyExecuting, QTaskStates.PartiallyDispatched })), QFilter<QTask>.Eq<string>(t => t.Name, "sample11-task1"), QFilter<QTask>.Lte<uint>(t => t.InstanceCount, 10), }), Select = QSelect<QTask>.Select() .Include(t => t.Name) .Include(t => t.Uuid) .Include(t => t.State) .Include(t => t.Status), MaximumResults = 2, }; string teststring = $"{regexDetails}"; regexDetails.Filter = QFilter<QTask>.Eq(t => t.State, QTaskStates.Submitted); regexDetails.Select = QSelect<QTask>.Select(); regexDetails.MaximumResults = 5; } } [TestFixture] public class UnitTestQFilter { [Test] public void AndOrBigNestedTests() { var regexDetails = new QDataDetail<QTask>() { Filter = QFilter<QTask>.And(new[] { QFilter<QTask>.Or( QFilter<QTask>.And(new[] { QFilter<QTask>.Or(new[] { QFilter<QTask>.And(new[] { QFilter<QTask>.Or(new[] { QFilter<QTask>.And(new[] { QFilter<QTask>.Or(new[] { QFilter<QTask>.And(new[] { QFilter<QTask>.Eq(t => t.State, QTaskStates.Submitted), QFilter<QTask>.Eq(t => t.State, QTaskStates.Submitted), }), QFilter<QTask>.Eq(t => t.State, QTaskStates.Submitted), QFilter<QTask>.Or(new[] { QFilter<QTask>.Eq(t => t.State, QTaskStates.Submitted), QFilter<QTask>.Eq(t => t.State, QTaskStates.Submitted), }), QFilter<QTask>.Eq(t => t.State, QTaskStates.Submitted), QFilter<QTask>.And(new[] { QFilter<QTask>.Eq(t => t.State, QTaskStates.Submitted), QFilter<QTask>.Eq(t => t.State, QTaskStates.Submitted), }), QFilter<QTask>.Eq(t => t.State, QTaskStates.Submitted), }), QFilter<QTask>.Eq<string>(t => t.Name, "sample11-task1"), }), QFilter<QTask>.Eq<string>(t => t.Name, "sample11-task1"), }), QFilter<QTask>.Eq<string>(t => t.Name, "sample11-task1"), }), QFilter<QTask>.Eq<string>(t => t.Name, "sample11-task1"), }), QFilter<QTask>.Eq<string>(t => t.Name, "sample11-task1"), }), QFilter<QTask>.Eq(t => t.State, QTaskStates.Submitted), QFilter<QTask>.Eq(t => t.State, QTaskStates.Cancelled), QFilter<QTask>.Eq(t => t.State, QTaskStates.Failure), QFilter<QTask>.In(t => t.State, new[] { QTaskStates.FullyExecuting, QTaskStates.PartiallyDispatched })), QFilter<QTask>.Eq<string>(t => t.Name, "sample11-task1"), QFilter<QTask>.Lte<uint>(t => t.InstanceCount, 10), }), Select = QSelect<QTask>.Select() .Include(t => t.Status), MaximumResults = 2, }; } [Test] public void AndFilterSimpleTest() { string value1 = "sample-name15489"; string value2 = "sample-name87654"; string subOp1 = "Equal"; string subOp2 = "Like"; string theOperator = "And"; string field1 = "Name"; string field2 = "Profile"; var regexDetails = new QDataDetail<QTask>() { Filter = QFilter<QTask>.And( QFilter<QTask>.Eq(t => t.Name, value1), QFilter<QTask>.Like(t => t.Profile, value2)), }; var filters = (Node<QTask>)regexDetails.Filter._filterApi; UnitValueLeaf<QTask, string> firstValueAdd = (UnitValueLeaf<QTask, string>)filters.Filters[0]; UnitValueLeaf<QTask, string> secondValueAdd = (UnitValueLeaf<QTask, string>)filters.Filters[1]; Assert.AreEqual(filters.Operator, theOperator); Assert.AreEqual(firstValueAdd.Value, value1); Assert.AreEqual(secondValueAdd.Value, value2); Assert.AreEqual(firstValueAdd.Operator, subOp1); Assert.AreEqual(secondValueAdd.Operator, subOp2); Assert.AreEqual(firstValueAdd.Field, field1); Assert.AreEqual(secondValueAdd.Field, field2); } [Test] public void OrFilterSimpleTest() { string value1 = "sample-name15489"; string value2 = "sample-name87654"; string subOp1 = "Equal"; string subOp2 = "Like"; string theOperator = "Or"; string field1 = "Name"; string field2 = "Profile"; var regexDetails = new QDataDetail<QTask>() { Filter = QFilter<QTask>.Or( QFilter<QTask>.Eq(t => t.Name, value1), QFilter<QTask>.Like(t => t.Profile, value2)), }; var filters = (Node<QTask>)regexDetails.Filter._filterApi; UnitValueLeaf<QTask, string> firstValueAdd = (UnitValueLeaf<QTask, string>)filters.Filters[0]; UnitValueLeaf<QTask, string> secondValueAdd = (UnitValueLeaf<QTask, string>)filters.Filters[1]; Assert.AreEqual(filters.Operator, theOperator); Assert.AreEqual(firstValueAdd.Value, value1); Assert.AreEqual(secondValueAdd.Value, value2); Assert.AreEqual(firstValueAdd.Operator, subOp1); Assert.AreEqual(secondValueAdd.Operator, subOp2); Assert.AreEqual(firstValueAdd.Field, field1); Assert.AreEqual(secondValueAdd.Field, field2); } [Test] public void EqFilterSimpleTest() { int max = 2; string value = "sample-name15489"; string theOperator = "Equal"; string field = "Name"; var regexDetails = new QDataDetail<QTask>() { Filter = QFilter<QTask>.Eq(t => t.Name, value), MaximumResults = max, }; Assert.AreEqual(regexDetails.MaximumResults, max); Assert.AreEqual(((UnitValueLeaf<QTask, string>)regexDetails.Filter._filterApi).Value, value); Assert.AreEqual(((UnitValueLeaf<QTask, string>)regexDetails.Filter._filterApi).Operator, theOperator); Assert.AreEqual(((UnitValueLeaf<QTask, string>)regexDetails.Filter._filterApi).Field, field); } [Test] public void EqFilterArrayValues() { string value = "tag_45"; string theOperator = "Equal"; string field = "Tags"; var regexDetails = new QDataDetail<QTask>() { Filter = QFilter<QTask>.Contains(t => t.Tags, value), }; Assert.AreEqual(((UnitValueLeaf<QTask, string>)regexDetails.Filter._filterApi).Value, value); Assert.AreEqual(((UnitValueLeaf<QTask, string>)regexDetails.Filter._filterApi).Operator, theOperator); Assert.AreEqual(((UnitValueLeaf<QTask, string>)regexDetails.Filter._filterApi).Field, field); } [Test] public void NeqFilterSimpleTest() { int max = 2; string value = "sample-name15489"; string theOperator = "NotEqual"; string field = "Name"; var regexDetails = new QDataDetail<QTask>() { Filter = QFilter<QTask>.Neq(t => t.Name, value), MaximumResults = max, }; Assert.AreEqual(regexDetails.MaximumResults, max); Assert.AreEqual(((UnitValueLeaf<QTask, string>)regexDetails.Filter._filterApi).Value, value); Assert.AreEqual(((UnitValueLeaf<QTask, string>)regexDetails.Filter._filterApi).Operator, theOperator); Assert.AreEqual(((UnitValueLeaf<QTask, string>)regexDetails.Filter._filterApi).Field, field); } [Test] public void NeqFilterArrayValues() { string value = "tag_45"; string theOperator = "NotEqual"; string field = "Tags"; var regexDetails = new QDataDetail<QTask>() { Filter = QFilter<QTask>.NotContains(t => t.Tags, value) }; Assert.AreEqual(((UnitValueLeaf<QTask, string>)regexDetails.Filter._filterApi).Value, value); Assert.AreEqual(((UnitValueLeaf<QTask, string>)regexDetails.Filter._filterApi).Operator, theOperator); Assert.AreEqual(((UnitValueLeaf<QTask, string>)regexDetails.Filter._filterApi).Field, field); } [Test] public void InFilterSimpleTest() { int max = 2; string value = "sample-name15489"; string theOperator = "In"; string field = "Name"; var regexDetails = new QDataDetail<QTask>() { Filter = QFilter<QTask>.In(t => t.Name, value), MaximumResults = max, }; Assert.AreEqual(regexDetails.MaximumResults, max); Assert.AreEqual(((MultipleValueLeaf<QTask, string>)regexDetails.Filter._filterApi).Values[0], value); Assert.AreEqual(((MultipleValueLeaf<QTask, string>)regexDetails.Filter._filterApi).Operator, theOperator); Assert.AreEqual(((MultipleValueLeaf<QTask, string>)regexDetails.Filter._filterApi).Field, field); } [Test] public void NinFilterSimpleTest() { int max = 2; string value = "sample-name15489"; string theOperator = "NotIn"; string field = "Name"; var regexDetails = new QDataDetail<QTask>() { Filter = QFilter<QTask>.Nin(t => t.Name, value), MaximumResults = max, }; Assert.AreEqual(regexDetails.MaximumResults, max); Assert.AreEqual(((MultipleValueLeaf<QTask, string>)regexDetails.Filter._filterApi).Values[0], value); Assert.AreEqual(((MultipleValueLeaf<QTask, string>)regexDetails.Filter._filterApi).Operator, theOperator); Assert.AreEqual(((MultipleValueLeaf<QTask, string>)regexDetails.Filter._filterApi).Field, field); } [Test] public void LtFilterSimpleTest() { int max = 2; string value = "sample-name15489"; string theOperator = "LessThan"; string field = "Name"; var regexDetails = new QDataDetail<QTask>() { Filter = QFilter<QTask>.Lt(t => t.Name, value), MaximumResults = max, }; Assert.AreEqual(regexDetails.MaximumResults, max); Assert.AreEqual(((UnitValueLeaf<QTask, string>)regexDetails.Filter._filterApi).Value, value); Assert.AreEqual(((UnitValueLeaf<QTask, string>)regexDetails.Filter._filterApi).Operator, theOperator); Assert.AreEqual(((UnitValueLeaf<QTask, string>)regexDetails.Filter._filterApi).Field, field); } [Test] public void LteFilterSimpleTest() { int max = 2; string value = "sample-name15489"; string theOperator = "LessThanOrEqual"; string field = "Name"; var regexDetails = new QDataDetail<QTask>() { Filter = QFilter<QTask>.Lte(t => t.Name, value), MaximumResults = max, }; Assert.AreEqual(regexDetails.MaximumResults, max); Assert.AreEqual(((UnitValueLeaf<QTask, string>)regexDetails.Filter._filterApi).Value, value); Assert.AreEqual(((UnitValueLeaf<QTask, string>)regexDetails.Filter._filterApi).Operator, theOperator); Assert.AreEqual(((UnitValueLeaf<QTask, string>)regexDetails.Filter._filterApi).Field, field); } [Test] public void GteFilterSimpleTest() { int max = 2; string value = "sample-name15489"; string theOperator = "GreaterThanOrEqual"; string field = "Name"; var regexDetails = new QDataDetail<QTask>() { Filter = QFilter<QTask>.Gte(t => t.Name, value), MaximumResults = max, }; Assert.AreEqual(regexDetails.MaximumResults, max); Assert.AreEqual(((UnitValueLeaf<QTask, string>)regexDetails.Filter._filterApi).Value, value); Assert.AreEqual(((UnitValueLeaf<QTask, string>)regexDetails.Filter._filterApi).Operator, theOperator); Assert.AreEqual(((UnitValueLeaf<QTask, string>)regexDetails.Filter._filterApi).Field, field); } [Test] public void LikeFilterSimpleTest() { int max = 2; string value = "sample-name15489"; string theOperator = "Like"; string field = "Name"; var regexDetails = new QDataDetail<QTask>() { Filter = QFilter<QTask>.Like(t => t.Name, value), MaximumResults = max, }; Assert.AreEqual(regexDetails.MaximumResults, max); Assert.AreEqual(((UnitValueLeaf<QTask, string>)regexDetails.Filter._filterApi).Value, value); Assert.AreEqual(((UnitValueLeaf<QTask, string>)regexDetails.Filter._filterApi).Operator, theOperator); Assert.AreEqual(((UnitValueLeaf<QTask, string>)regexDetails.Filter._filterApi).Field, field); } [Test] public void GtFilterSimpleTest() { int max = 2; string value = "sample-name15489"; string theOperator = "GreaterThan"; string field = "Name"; var regexDetails = new QDataDetail<QTask>() { Filter = QFilter<QTask>.Gt(t => t.Name, value), MaximumResults = max, }; Assert.AreEqual(regexDetails.MaximumResults, max); Assert.AreEqual(((UnitValueLeaf<QTask, string>)regexDetails.Filter._filterApi).Value, value); Assert.AreEqual(((UnitValueLeaf<QTask, string>)regexDetails.Filter._filterApi).Operator, theOperator); Assert.AreEqual(((UnitValueLeaf<QTask, string>)regexDetails.Filter._filterApi).Field, field); } } }
// ReSharper disable once CheckNamespace namespace Fluent { using System; using System.Linq; using System.Windows; using System.Windows.Automation.Peers; using System.Windows.Controls; using System.Windows.Input; using System.Windows.Media; using Fluent.Extensions; using Fluent.Helpers; using Fluent.Internal; using Fluent.Internal.KnownBoxes; using WindowChrome = ControlzEx.Windows.Shell.WindowChrome; /// <summary> /// Represents title bar /// </summary> [StyleTypedProperty(Property = nameof(ItemContainerStyle), StyleTargetType = typeof(RibbonContextualTabGroup))] [TemplatePart(Name = "PART_QuickAccessToolbarHolder", Type = typeof(FrameworkElement))] [TemplatePart(Name = "PART_HeaderHolder", Type = typeof(FrameworkElement))] [TemplatePart(Name = "PART_ItemsContainer", Type = typeof(Panel))] public class RibbonTitleBar : HeaderedItemsControl { #region Fields // Quick access toolbar holder private FrameworkElement quickAccessToolbarHolder; // Header holder private FrameworkElement headerHolder; // Items container private Panel itemsContainer; // Quick access toolbar rect private Rect quickAccessToolbarRect; // Header rect private Rect headerRect; // Items rect private Rect itemsRect; private Size lastMeasureConstraint; #endregion #region Properties /// <summary> /// Gets or sets quick access toolbar /// </summary> public FrameworkElement QuickAccessToolBar { get { return (FrameworkElement)this.GetValue(QuickAccessToolBarProperty); } set { this.SetValue(QuickAccessToolBarProperty, value); } } /// <summary>Identifies the <see cref="QuickAccessToolBar"/> dependency property.</summary> public static readonly DependencyProperty QuickAccessToolBarProperty = DependencyProperty.Register(nameof(QuickAccessToolBar), typeof(FrameworkElement), typeof(RibbonTitleBar), new PropertyMetadata(OnQuickAccessToolBarChanged)); private static void OnQuickAccessToolBarChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var titleBar = (RibbonTitleBar)d; titleBar.ForceMeasureAndArrange(); } /// <summary> /// Gets or sets header alignment /// </summary> public HorizontalAlignment HeaderAlignment { get { return (HorizontalAlignment)this.GetValue(HeaderAlignmentProperty); } set { this.SetValue(HeaderAlignmentProperty, value); } } /// <summary>Identifies the <see cref="HeaderAlignment"/> dependency property.</summary> public static readonly DependencyProperty HeaderAlignmentProperty = DependencyProperty.Register(nameof(HeaderAlignment), typeof(HorizontalAlignment), typeof(RibbonTitleBar), new FrameworkPropertyMetadata(HorizontalAlignment.Center, FrameworkPropertyMetadataOptions.AffectsArrange | FrameworkPropertyMetadataOptions.AffectsMeasure)); /// <summary> /// Defines whether title bar is collapsed /// </summary> public bool IsCollapsed { get { return (bool)this.GetValue(IsCollapsedProperty); } set { this.SetValue(IsCollapsedProperty, value); } } /// <summary>Identifies the <see cref="IsCollapsed"/> dependency property.</summary> public static readonly DependencyProperty IsCollapsedProperty = DependencyProperty.Register(nameof(IsCollapsed), typeof(bool), typeof(RibbonTitleBar), new FrameworkPropertyMetadata(BooleanBoxes.FalseBox, FrameworkPropertyMetadataOptions.AffectsArrange | FrameworkPropertyMetadataOptions.AffectsMeasure)); private bool isAtLeastOneRequiredControlPresent; /// <summary>Identifies the <see cref="HideContextTabs"/> dependency property.</summary> public static readonly DependencyProperty HideContextTabsProperty = DependencyProperty.Register(nameof(HideContextTabs), typeof(bool), typeof(RibbonTitleBar), new FrameworkPropertyMetadata(BooleanBoxes.FalseBox, FrameworkPropertyMetadataOptions.AffectsArrange | FrameworkPropertyMetadataOptions.AffectsMeasure)); /// <summary> /// Gets or sets whether context tabs are hidden. /// </summary> public bool HideContextTabs { get { return (bool)this.GetValue(HideContextTabsProperty); } set { this.SetValue(HideContextTabsProperty, value); } } #endregion #region Initialize /// <summary> /// Static constructor /// </summary> static RibbonTitleBar() { DefaultStyleKeyProperty.OverrideMetadata(typeof(RibbonTitleBar), new FrameworkPropertyMetadata(typeof(RibbonTitleBar))); HeaderProperty.OverrideMetadata(typeof(RibbonTitleBar), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.AffectsArrange | FrameworkPropertyMetadataOptions.AffectsMeasure)); } /// <summary> /// Creates a new instance. /// </summary> public RibbonTitleBar() { WindowChrome.SetIsHitTestVisibleInChrome(this, true); } #endregion #region Overrides /// <inheritdoc /> protected override HitTestResult HitTestCore(PointHitTestParameters hitTestParameters) { var baseResult = base.HitTestCore(hitTestParameters); if (baseResult is null) { return new PointHitTestResult(this, hitTestParameters.HitPoint); } return baseResult; } /// <inheritdoc /> protected override void OnMouseRightButtonUp(MouseButtonEventArgs e) { base.OnMouseRightButtonUp(e); if (e.Handled || this.IsMouseDirectlyOver == false) { return; } WindowSteeringHelper.ShowSystemMenu(this, e); } /// <inheritdoc /> protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e) { base.OnMouseLeftButtonDown(e); if (e.Handled) { return; } // Contextual groups shall handle mouse events if (e.Source is RibbonContextualGroupsContainer || e.Source is RibbonContextualTabGroup) { return; } WindowSteeringHelper.HandleMouseLeftButtonDown(e, true, true); } /// <inheritdoc /> protected override DependencyObject GetContainerForItemOverride() { return new RibbonContextualTabGroup(); } /// <inheritdoc /> protected override bool IsItemItsOwnContainerOverride(object item) { return item is RibbonContextualTabGroup; } /// <inheritdoc /> public override void OnApplyTemplate() { base.OnApplyTemplate(); this.quickAccessToolbarHolder = this.GetTemplateChild("PART_QuickAccessToolbarHolder") as FrameworkElement; this.headerHolder = this.GetTemplateChild("PART_HeaderHolder") as FrameworkElement; this.itemsContainer = this.GetTemplateChild("PART_ItemsContainer") as Panel; this.isAtLeastOneRequiredControlPresent = this.quickAccessToolbarHolder != null || this.headerHolder != null || this.itemsContainer != null; if (this.quickAccessToolbarHolder != null) { WindowChrome.SetIsHitTestVisibleInChrome(this.quickAccessToolbarHolder, true); } } /// <inheritdoc /> protected override Size MeasureOverride(Size constraint) { if (this.isAtLeastOneRequiredControlPresent == false) { return base.MeasureOverride(constraint); } this.lastMeasureConstraint = constraint; var resultSize = constraint; if (double.IsPositiveInfinity(resultSize.Width) || double.IsPositiveInfinity(resultSize.Height)) { resultSize = base.MeasureOverride(resultSize); } this.Update(resultSize); this.itemsContainer.Measure(this.itemsRect.Size); this.headerHolder.Measure(this.headerRect.Size); this.quickAccessToolbarHolder.Measure(this.quickAccessToolbarRect.Size); var maxHeight = Math.Max(Math.Max(this.itemsRect.Height, this.headerRect.Height), this.quickAccessToolbarRect.Height); var width = this.quickAccessToolbarRect.Width + this.headerRect.Width + this.itemsRect.Width; return new Size(width, maxHeight); } /// <inheritdoc /> protected override Size ArrangeOverride(Size arrangeBounds) { if (this.isAtLeastOneRequiredControlPresent == false) { return base.ArrangeOverride(arrangeBounds); } // If the last measure constraint and the arrangeBounds are not equal we have to update again. // This can happen if the window is set to auto-size it's width. // As Update also does some things that are related to an arrange pass we have to update again. // It would be way better if Update wouldn't handle parts of the arrange pass, but that would be very difficult to implement... if (arrangeBounds.Equals(this.lastMeasureConstraint) == false) { this.Update(arrangeBounds); this.itemsContainer.Measure(this.itemsRect.Size); this.headerHolder.Measure(this.headerRect.Size); this.quickAccessToolbarHolder.Measure(this.quickAccessToolbarRect.Size); } this.itemsContainer.Arrange(this.itemsRect); this.headerHolder.Arrange(this.headerRect); this.quickAccessToolbarHolder.Arrange(this.quickAccessToolbarRect); this.EnsureCorrectLayoutAfterArrange(); return arrangeBounds; } #endregion #region Private methods /// <summary> /// Sometimes the relative position only changes after the arrange phase. /// To compensate such sitiations we issue a second layout pass by invalidating our measure. /// This situation can occur if, for example, the icon of a ribbon window has it's visibility changed. /// </summary> private void EnsureCorrectLayoutAfterArrange() { var currentRelativePosition = this.GetCurrentRelativePosition(); this.RunInDispatcherAsync(() => this.CheckPosition(currentRelativePosition, this.GetCurrentRelativePosition())); } private void CheckPosition(Point previousRelativePosition, Point currentRelativePositon) { if (previousRelativePosition != currentRelativePositon) { this.InvalidateMeasure(); } } private Point GetCurrentRelativePosition() { var parentUIElement = this.Parent as UIElement; if (parentUIElement is null) { return default; } return this.TranslatePoint(default, parentUIElement); } // Update items size and positions private void Update(Size constraint) { var visibleGroups = this.Items.OfType<RibbonContextualTabGroup>() .Where(group => group.InnerVisibility == Visibility.Visible && group.Items.Count > 0) .ToList(); var canRibbonTabControlScroll = false; // Defensively try to find out if the RibbonTabControl can scroll if (visibleGroups.Count > 0) { var firstVisibleItem = visibleGroups.First().FirstVisibleItem; canRibbonTabControlScroll = UIHelper.GetParent<RibbonTabControl>(firstVisibleItem)?.CanScroll == true; } if (this.IsCollapsed) { // Collapse QuickAccessToolbar this.quickAccessToolbarRect = new Rect(0, 0, 0, 0); // Collapse itemRect this.itemsRect = new Rect(0, 0, 0, 0); this.headerHolder.Measure(new Size(constraint.Width, constraint.Height)); this.headerRect = new Rect(0, 0, this.headerHolder.DesiredSize.Width, constraint.Height); } else if (visibleGroups.Count == 0 || canRibbonTabControlScroll) { // Collapse itemRect this.itemsRect = new Rect(0, 0, 0, 0); // Set quick launch toolbar and header position and size this.quickAccessToolbarHolder.Measure(SizeConstants.Infinite); if (constraint.Width <= this.quickAccessToolbarHolder.DesiredSize.Width + 50) { this.quickAccessToolbarRect = new Rect(0, 0, Math.Max(0, constraint.Width - 50), this.quickAccessToolbarHolder.DesiredSize.Height); this.quickAccessToolbarHolder.Measure(this.quickAccessToolbarRect.Size); } if (constraint.Width > this.quickAccessToolbarHolder.DesiredSize.Width + 50) { this.quickAccessToolbarRect = new Rect(0, 0, this.quickAccessToolbarHolder.DesiredSize.Width, this.quickAccessToolbarHolder.DesiredSize.Height); this.headerHolder.Measure(SizeConstants.Infinite); var allTextWidth = constraint.Width - this.quickAccessToolbarHolder.DesiredSize.Width; if (this.HeaderAlignment == HorizontalAlignment.Left) { this.headerRect = new Rect(this.quickAccessToolbarHolder.DesiredSize.Width, 0, Math.Min(allTextWidth, this.headerHolder.DesiredSize.Width), constraint.Height); } else if (this.HeaderAlignment == HorizontalAlignment.Center) { this.headerRect = new Rect(this.quickAccessToolbarHolder.DesiredSize.Width + Math.Max(0, (allTextWidth / 2) - (this.headerHolder.DesiredSize.Width / 2)), 0, Math.Min(allTextWidth, this.headerHolder.DesiredSize.Width), constraint.Height); } else if (this.HeaderAlignment == HorizontalAlignment.Right) { this.headerRect = new Rect(this.quickAccessToolbarHolder.DesiredSize.Width + Math.Max(0, allTextWidth - this.headerHolder.DesiredSize.Width), 0, Math.Min(allTextWidth, this.headerHolder.DesiredSize.Width), constraint.Height); } else if (this.HeaderAlignment == HorizontalAlignment.Stretch) { this.headerRect = new Rect(this.quickAccessToolbarHolder.DesiredSize.Width, 0, allTextWidth, constraint.Height); } } else { this.headerRect = new Rect(Math.Max(0, constraint.Width - 50), 0, 50, constraint.Height); } } else { var pointZero = default(Point); // get initial StartX value var startX = visibleGroups.First().FirstVisibleItem.TranslatePoint(pointZero, this).X; var endX = 0D; //Get minimum x point (workaround) foreach (var group in visibleGroups) { var currentStartX = group.FirstVisibleItem.TranslatePoint(pointZero, this).X; if (currentStartX < startX) { startX = currentStartX; } var lastItem = group.LastVisibleItem; var currentEndX = lastItem.TranslatePoint(new Point(lastItem.DesiredSize.Width, 0), this).X; if (currentEndX > endX) { endX = currentEndX; } } // Ensure that startX and endX are never negative startX = Math.Max(0, startX); endX = Math.Max(0, endX); // Ensure that startX respect min width of QuickAccessToolBar startX = Math.Max(startX, this.QuickAccessToolBar?.MinWidth ?? 0); // Set contextual groups position and size this.itemsContainer.Measure(SizeConstants.Infinite); var itemsRectWidth = Math.Min(this.itemsContainer.DesiredSize.Width, Math.Max(0, Math.Min(endX, constraint.Width) - startX)); this.itemsRect = new Rect(startX, 0, itemsRectWidth, constraint.Height); // Set quick launch toolbar position and size this.quickAccessToolbarHolder.Measure(SizeConstants.Infinite); var quickAccessToolbarWidth = this.quickAccessToolbarHolder.DesiredSize.Width; this.quickAccessToolbarRect = new Rect(0, 0, Math.Min(quickAccessToolbarWidth, startX), this.quickAccessToolbarHolder.DesiredSize.Height); if (quickAccessToolbarWidth > startX) { this.quickAccessToolbarHolder.Measure(this.quickAccessToolbarRect.Size); this.quickAccessToolbarRect = new Rect(0, 0, this.quickAccessToolbarHolder.DesiredSize.Width, this.quickAccessToolbarHolder.DesiredSize.Height); quickAccessToolbarWidth = this.quickAccessToolbarHolder.DesiredSize.Width; } // Set header this.headerHolder.Measure(SizeConstants.Infinite); switch (this.HeaderAlignment) { case HorizontalAlignment.Left: { if (startX - quickAccessToolbarWidth > 150) { var allTextWidth = startX - quickAccessToolbarWidth; this.headerRect = new Rect(this.quickAccessToolbarRect.Width, 0, Math.Min(allTextWidth, this.headerHolder.DesiredSize.Width), constraint.Height); } else { var allTextWidth = Math.Max(0, constraint.Width - endX); this.headerRect = new Rect(Math.Min(endX, constraint.Width), 0, Math.Min(allTextWidth, this.headerHolder.DesiredSize.Width), constraint.Height); } } break; case HorizontalAlignment.Center: { var allTextWidthRight = Math.Max(0, constraint.Width - endX); var allTextWidthLeft = Math.Max(0, startX - quickAccessToolbarWidth); var fitsRightButNotLeft = allTextWidthRight >= this.headerHolder.DesiredSize.Width && allTextWidthLeft < this.headerHolder.DesiredSize.Width; if (((startX - quickAccessToolbarWidth < 150 || fitsRightButNotLeft) && (startX - quickAccessToolbarWidth > 0) && (startX - quickAccessToolbarWidth < constraint.Width - endX)) || (endX < constraint.Width / 2)) { this.headerRect = new Rect(Math.Min(Math.Max(endX, (constraint.Width / 2) - (this.headerHolder.DesiredSize.Width / 2)), constraint.Width), 0, Math.Min(allTextWidthRight, this.headerHolder.DesiredSize.Width), constraint.Height); } else { this.headerRect = new Rect(this.quickAccessToolbarHolder.DesiredSize.Width + Math.Max(0, (allTextWidthLeft / 2) - (this.headerHolder.DesiredSize.Width / 2)), 0, Math.Min(allTextWidthLeft, this.headerHolder.DesiredSize.Width), constraint.Height); } } break; case HorizontalAlignment.Right: { if (startX - quickAccessToolbarWidth > 150) { var allTextWidth = Math.Max(0, startX - quickAccessToolbarWidth); this.headerRect = new Rect(this.quickAccessToolbarHolder.DesiredSize.Width + Math.Max(0, allTextWidth - this.headerHolder.DesiredSize.Width), 0, Math.Min(allTextWidth, this.headerHolder.DesiredSize.Width), constraint.Height); } else { var allTextWidth = Math.Max(0, constraint.Width - endX); this.headerRect = new Rect(Math.Min(Math.Max(endX, constraint.Width - this.headerHolder.DesiredSize.Width), constraint.Width), 0, Math.Min(allTextWidth, this.headerHolder.DesiredSize.Width), constraint.Height); } } break; case HorizontalAlignment.Stretch: { if (startX - quickAccessToolbarWidth > 150) { var allTextWidth = startX - quickAccessToolbarWidth; this.headerRect = new Rect(this.quickAccessToolbarRect.Width, 0, allTextWidth, constraint.Height); } else { var allTextWidth = Math.Max(0, constraint.Width - endX); this.headerRect = new Rect(Math.Min(endX, constraint.Width), 0, allTextWidth, constraint.Height); } } break; } } this.headerRect.Width += 2; } #endregion /// <inheritdoc /> protected override AutomationPeer OnCreateAutomationPeer() => new Fluent.Automation.Peers.RibbonTitleBarAutomationPeer(this); } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using System.IO; using System.Threading.Tasks; using osu.Framework.Allocation; using osu.Framework.Audio; using osu.Framework.Audio.Sample; using osu.Framework.Bindables; using osu.Framework.Graphics.OpenGL.Textures; using osu.Framework.Graphics.Shaders; using osu.Framework.Graphics.Textures; using osu.Framework.IO.Stores; using osu.Framework.Platform; using osu.Game.Rulesets.Configuration; namespace osu.Game.Rulesets.UI { public class DrawableRulesetDependencies : DependencyContainer, IDisposable { /// <summary> /// The texture store to be used for the ruleset. /// </summary> public TextureStore TextureStore { get; } /// <summary> /// The sample store to be used for the ruleset. /// </summary> /// <remarks> /// This is the local sample store pointing to the ruleset sample resources, /// the cached sample store (<see cref="FallbackSampleStore"/>) retrieves from /// this store and falls back to the parent store if this store doesn't have the requested sample. /// </remarks> public ISampleStore SampleStore { get; } /// <summary> /// The shader manager to be used for the ruleset. /// </summary> public ShaderManager ShaderManager { get; } /// <summary> /// The ruleset config manager. /// </summary> public IRulesetConfigManager RulesetConfigManager { get; private set; } public DrawableRulesetDependencies(Ruleset ruleset, IReadOnlyDependencyContainer parent) : base(parent) { var resources = ruleset.CreateResourceStore(); if (resources != null) { TextureStore = new TextureStore(parent.Get<GameHost>().CreateTextureLoaderStore(new NamespacedResourceStore<byte[]>(resources, @"Textures"))); CacheAs(TextureStore = new FallbackTextureStore(TextureStore, parent.Get<TextureStore>())); SampleStore = parent.Get<AudioManager>().GetSampleStore(new NamespacedResourceStore<byte[]>(resources, @"Samples")); SampleStore.PlaybackConcurrency = OsuGameBase.SAMPLE_CONCURRENCY; CacheAs(SampleStore = new FallbackSampleStore(SampleStore, parent.Get<ISampleStore>())); ShaderManager = new ShaderManager(new NamespacedResourceStore<byte[]>(resources, @"Shaders")); CacheAs(ShaderManager = new FallbackShaderManager(ShaderManager, parent.Get<ShaderManager>())); } RulesetConfigManager = parent.Get<RulesetConfigCache>().GetConfigFor(ruleset); if (RulesetConfigManager != null) Cache(RulesetConfigManager); } #region Disposal ~DrawableRulesetDependencies() { // required to potentially clean up sample store from audio hierarchy. Dispose(false); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } private bool isDisposed; protected void Dispose(bool disposing) { if (isDisposed) return; isDisposed = true; SampleStore?.Dispose(); TextureStore?.Dispose(); ShaderManager?.Dispose(); RulesetConfigManager = null; } #endregion /// <summary> /// A sample store which adds a fallback source and prevents disposal of the fallback source. /// </summary> private class FallbackSampleStore : ISampleStore { private readonly ISampleStore primary; private readonly ISampleStore fallback; public FallbackSampleStore(ISampleStore primary, ISampleStore fallback) { this.primary = primary; this.fallback = fallback; } public Sample Get(string name) => primary.Get(name) ?? fallback.Get(name); public Task<Sample> GetAsync(string name) => primary.GetAsync(name) ?? fallback.GetAsync(name); public Stream GetStream(string name) => primary.GetStream(name) ?? fallback.GetStream(name); public IEnumerable<string> GetAvailableResources() => throw new NotSupportedException(); public void AddAdjustment(AdjustableProperty type, IBindable<double> adjustBindable) => throw new NotSupportedException(); public void RemoveAdjustment(AdjustableProperty type, IBindable<double> adjustBindable) => throw new NotSupportedException(); public void RemoveAllAdjustments(AdjustableProperty type) => throw new NotSupportedException(); public void BindAdjustments(IAggregateAudioAdjustment component) => throw new NotImplementedException(); public void UnbindAdjustments(IAggregateAudioAdjustment component) => throw new NotImplementedException(); public BindableNumber<double> Volume => throw new NotSupportedException(); public BindableNumber<double> Balance => throw new NotSupportedException(); public BindableNumber<double> Frequency => throw new NotSupportedException(); public BindableNumber<double> Tempo => throw new NotSupportedException(); public IBindable<double> AggregateVolume => throw new NotSupportedException(); public IBindable<double> AggregateBalance => throw new NotSupportedException(); public IBindable<double> AggregateFrequency => throw new NotSupportedException(); public IBindable<double> AggregateTempo => throw new NotSupportedException(); public int PlaybackConcurrency { get => throw new NotSupportedException(); set => throw new NotSupportedException(); } public void Dispose() { primary?.Dispose(); } } /// <summary> /// A texture store which adds a fallback source and prevents disposal of the fallback source. /// </summary> private class FallbackTextureStore : TextureStore { private readonly TextureStore primary; private readonly TextureStore fallback; public FallbackTextureStore(TextureStore primary, TextureStore fallback) { this.primary = primary; this.fallback = fallback; } public override Texture Get(string name, WrapMode wrapModeS, WrapMode wrapModeT) => primary.Get(name, wrapModeS, wrapModeT) ?? fallback.Get(name, wrapModeS, wrapModeT); protected override void Dispose(bool disposing) { base.Dispose(disposing); primary?.Dispose(); } } private class FallbackShaderManager : ShaderManager { private readonly ShaderManager primary; private readonly ShaderManager fallback; public FallbackShaderManager(ShaderManager primary, ShaderManager fallback) : base(new ResourceStore<byte[]>()) { this.primary = primary; this.fallback = fallback; } public override byte[] LoadRaw(string name) => primary.LoadRaw(name) ?? fallback.LoadRaw(name); protected override void Dispose(bool disposing) { base.Dispose(disposing); primary?.Dispose(); } } } }
/* New BSD License ------------------------------------------------------------------------------- Copyright (c) 2006-2012, EntitySpaces, LLC All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the EntitySpaces, LLC nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL EntitySpaces, LLC 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.Data; using System.Data.SQLite; using Tiraggo.DynamicQuery; using Tiraggo.Interfaces; namespace Tiraggo.SQLiteProvider { class Shared { static public SQLiteCommand BuildDynamicInsertCommand(tgDataRequest request, tgEntitySavePacket packet) { string sql = String.Empty; string defaults = String.Empty; string into = String.Empty; string values = String.Empty; string comma = String.Empty; string defaultComma = String.Empty; string where = String.Empty; string whereComma = String.Empty; PropertyCollection props = new PropertyCollection(); Dictionary<string, SQLiteParameter> types = Cache.GetParameters(request); SQLiteCommand cmd = new SQLiteCommand(); if (request.CommandTimeout != null) cmd.CommandTimeout = request.CommandTimeout.Value; tgColumnMetadataCollection cols = request.Columns; foreach (tgColumnMetadata col in cols) { bool isModified = packet.ModifiedColumns == null ? false : packet.ModifiedColumns.Contains(col.Name); if (isModified && (!col.IsAutoIncrement && !col.IsConcurrency && !col.IsTiraggoConcurrency)) { SQLiteParameter p = types[col.Name]; cmd.Parameters.Add(CloneParameter(p)); into += comma + Delimiters.ColumnOpen + col.Name + Delimiters.ColumnClose; values += comma + p.ParameterName; comma = ", "; } else if (col.IsAutoIncrement) { props["AutoInc"] = col.Name; props["Source"] = request.ProviderMetadata.Source; } else if (col.IsConcurrency) { props["Timestamp"] = col.Name; props["Source"] = request.ProviderMetadata.Source; } else if (col.IsTiraggoConcurrency) { props["EntitySpacesConcurrency"] = col.Name; SQLiteParameter p = types[col.Name]; into += comma + Delimiters.ColumnOpen + col.Name + Delimiters.ColumnClose; values += comma + "1"; comma = ", "; SQLiteParameter clone = CloneParameter(p); clone.Value = 1; cmd.Parameters.Add(clone); } else if (col.IsComputed) { // Do nothing but leave this here } else if (cols.IsSpecialColumn(col)) { // Do nothing but leave this here } else if (col.HasDefault) { defaults += defaultComma + Delimiters.ColumnOpen + col.Name + Delimiters.ColumnClose; defaultComma = ","; } if (col.IsInPrimaryKey) { where += whereComma + col.Name; whereComma = ","; } } #region Special Columns if (cols.DateAdded != null && cols.DateAdded.IsServerSide && cols.FindByColumnName(cols.DateAdded.ColumnName) != null) { into += comma + Delimiters.ColumnOpen + cols.DateAdded.ColumnName + Delimiters.ColumnClose; values += comma + request.ProviderMetadata["DateAdded.ServerSideText"]; comma = ", "; defaults += defaultComma + Delimiters.ColumnOpen + cols.DateAdded.ColumnName + Delimiters.ColumnClose; defaultComma = ","; } if (cols.DateModified != null && cols.DateModified.IsServerSide && cols.FindByColumnName(cols.DateModified.ColumnName) != null) { into += comma + Delimiters.ColumnOpen + cols.DateModified.ColumnName + Delimiters.ColumnClose; values += comma + request.ProviderMetadata["DateModified.ServerSideText"]; comma = ", "; defaults += defaultComma + Delimiters.ColumnOpen + cols.DateModified.ColumnName + Delimiters.ColumnClose; defaultComma = ","; } if (cols.AddedBy != null && cols.AddedBy.IsServerSide && cols.FindByColumnName(cols.AddedBy.ColumnName) != null) { into += comma + Delimiters.ColumnOpen + cols.AddedBy.ColumnName + Delimiters.ColumnClose; values += comma + request.ProviderMetadata["AddedBy.ServerSideText"]; comma = ", "; defaults += defaultComma + Delimiters.ColumnOpen + cols.AddedBy.ColumnName + Delimiters.ColumnClose; defaultComma = ","; } if (cols.ModifiedBy != null && cols.ModifiedBy.IsServerSide && cols.FindByColumnName(cols.ModifiedBy.ColumnName) != null) { into += comma + Delimiters.ColumnOpen + cols.ModifiedBy.ColumnName + Delimiters.ColumnClose; values += comma + request.ProviderMetadata["ModifiedBy.ServerSideText"]; comma = ", "; defaults += defaultComma + Delimiters.ColumnOpen + cols.ModifiedBy.ColumnName + Delimiters.ColumnClose; defaultComma = ","; } #endregion if (defaults.Length > 0) { comma = String.Empty; props["Defaults"] = defaults; props["Where"] = where; } sql += " INSERT INTO " + CreateFullName(request); if (into.Length != 0) { sql += "(" + into + ") VALUES (" + values + ")"; } else { sql += "DEFAULT VALUES"; } request.Properties = props; cmd.CommandText = sql; cmd.CommandType = CommandType.Text; return cmd; } static public SQLiteCommand BuildDynamicUpdateCommand(tgDataRequest request, tgEntitySavePacket packet) { string where = String.Empty; string scomma = String.Empty; string wcomma = String.Empty; string defaults = String.Empty; string defaultsWhere = String.Empty; string defaultsComma = String.Empty; string defaultsWhereComma = String.Empty; string sql = "UPDATE " + CreateFullName(request) + " SET "; PropertyCollection props = new PropertyCollection(); Dictionary<string, SQLiteParameter> types = Cache.GetParameters(request); SQLiteCommand cmd = new SQLiteCommand(); if (request.CommandTimeout != null) cmd.CommandTimeout = request.CommandTimeout.Value; tgColumnMetadataCollection cols = request.Columns; foreach (tgColumnMetadata col in cols) { bool isModified = packet.ModifiedColumns == null ? false : packet.ModifiedColumns.Contains(col.Name); if (isModified && (!col.IsAutoIncrement && !col.IsConcurrency && !col.IsTiraggoConcurrency)) { SQLiteParameter p = types[col.Name]; cmd.Parameters.Add(CloneParameter(p)); sql += scomma; sql += Delimiters.ColumnOpen + col.Name + Delimiters.ColumnClose + " = " + p.ParameterName; scomma = ", "; } else if (col.IsAutoIncrement) { // Nothing to do but leave this here } else if (col.IsConcurrency) { SQLiteParameter p = types[col.Name]; p = CloneParameter(p); p.SourceVersion = DataRowVersion.Original; cmd.Parameters.Add(p); where += wcomma; where += Delimiters.ColumnOpen + col.Name + Delimiters.ColumnClose + " = " + p.ParameterName; wcomma = " AND "; } else if (col.IsTiraggoConcurrency) { props["EntitySpacesConcurrency"] = col.Name; SQLiteParameter p = types[col.Name]; p = CloneParameter(p); p.SourceVersion = DataRowVersion.Original; cmd.Parameters.Add(p); sql += scomma; sql += Delimiters.ColumnOpen + col.Name + Delimiters.ColumnClose + " = " + Delimiters.ColumnOpen + col.Name + Delimiters.ColumnClose + " + 1"; scomma = ", "; where += wcomma; where += Delimiters.ColumnOpen + col.Name + Delimiters.ColumnClose + " = " + p.ParameterName; wcomma = " AND "; } else if (col.IsComputed) { // Do nothing but leave this here } else if (cols.IsSpecialColumn(col)) { // Do nothing but leave this here } else if (col.HasDefault) { // defaults += defaultsComma + Delimiters.ColumnOpen + col.Name + Delimiters.ColumnClose; // defaultsComma = ","; } if (col.IsInPrimaryKey) { SQLiteParameter p = types[col.Name]; p = CloneParameter(p); p.SourceVersion = DataRowVersion.Original; cmd.Parameters.Add(p); where += wcomma; where += Delimiters.ColumnOpen + col.Name + Delimiters.ColumnClose + " = " + p.ParameterName; wcomma = " AND "; defaultsWhere += defaultsWhereComma + col.Name; defaultsWhereComma = ","; } } #region Special Columns if (cols.DateModified != null && cols.DateModified.IsServerSide && cols.FindByColumnName(cols.DateModified.ColumnName) != null) { sql += scomma; sql += Delimiters.ColumnOpen + cols.DateModified.ColumnName + Delimiters.ColumnClose + " = " + request.ProviderMetadata["DateModified.ServerSideText"]; scomma = ", "; defaults += defaultsComma + Delimiters.ColumnOpen + cols.DateModified.ColumnName + Delimiters.ColumnClose; defaultsComma = ","; } if (cols.ModifiedBy != null && cols.ModifiedBy.IsServerSide && cols.FindByColumnName(cols.ModifiedBy.ColumnName) != null) { sql += scomma; sql += Delimiters.ColumnOpen + cols.ModifiedBy.ColumnName + Delimiters.ColumnClose + " = " + request.ProviderMetadata["ModifiedBy.ServerSideText"]; scomma = ", "; defaults += defaultsComma + Delimiters.ColumnOpen + cols.ModifiedBy.ColumnName + Delimiters.ColumnClose; defaultsComma = ","; } #endregion if (defaults.Length > 0) { props["Defaults"] = defaults; props["Where"] = defaultsWhere; } sql += " WHERE (" + where + ")"; request.Properties = props; cmd.CommandText = sql; cmd.CommandType = CommandType.Text; return cmd; } static public SQLiteCommand BuildDynamicDeleteCommand(tgDataRequest request) { Dictionary<string, SQLiteParameter> types = Cache.GetParameters(request); SQLiteCommand cmd = new SQLiteCommand(); if (request.CommandTimeout != null) cmd.CommandTimeout = request.CommandTimeout.Value; string sql = "DELETE FROM " + CreateFullName(request) + " "; string comma = String.Empty; comma = String.Empty; sql += " WHERE "; foreach (tgColumnMetadata col in request.Columns) { if (col.IsInPrimaryKey || col.IsTiraggoConcurrency) { SQLiteParameter p = types[col.Name]; cmd.Parameters.Add(CloneParameter(p)); sql += comma; sql += Delimiters.ColumnOpen + col.Name + Delimiters.ColumnClose + " = " + p.ParameterName; comma = " AND "; } } cmd.CommandText = sql; cmd.CommandType = CommandType.Text; return cmd; } static public SQLiteCommand BuildStoredProcInsertCommand(tgDataRequest request) { return null; } static public SQLiteCommand BuildStoredProcUpdateCommand(tgDataRequest request) { return null; } static public SQLiteCommand BuildStoredProcDeleteCommand(tgDataRequest request) { return null; } static public void PopulateStoredProcParameters(SQLiteCommand cmd, tgDataRequest request) { Dictionary<string, SQLiteParameter> types = Cache.GetParameters(request); SQLiteParameter p; foreach (tgColumnMetadata col in request.Columns) { p = types[col.Name]; p = CloneParameter(p); p.SourceVersion = DataRowVersion.Current; if (col.IsComputed && col.CharacterMaxLength > 0) { p.Size = (int)col.CharacterMaxLength; } cmd.Parameters.Add(p); } } static private SQLiteParameter CloneParameter(SQLiteParameter p) { ICloneable param = p as ICloneable; return param.Clone() as SQLiteParameter; } static public string CreateFullName(tgDynamicQuerySerializable query) { IDynamicQuerySerializableInternal iQuery = query as IDynamicQuerySerializableInternal; tgProviderSpecificMetadata providerMetadata = iQuery.ProviderMetadata as tgProviderSpecificMetadata; string name = String.Empty; name += Delimiters.TableOpen; if (query.tg.QuerySource != null) name += query.tg.QuerySource; else name += providerMetadata.Destination; name += Delimiters.TableClose; return name; } static public string CreateFullName(tgDataRequest request) { string name = String.Empty; name += Delimiters.TableOpen; if(request.DynamicQuery != null && request.DynamicQuery.tg.QuerySource != null) name += request.DynamicQuery.tg.QuerySource; else name += request.QueryText != null ? request.QueryText : request.ProviderMetadata.Destination; name += Delimiters.TableClose; return name; } static public string CreateFullName(tgProviderSpecificMetadata providerMetadata) { return Delimiters.TableOpen + providerMetadata.Destination + Delimiters.TableClose; } static public tgConcurrencyException CheckForConcurrencyException(SQLiteException ex) { tgConcurrencyException ce = null; return ce; } static public void AddParameters(SQLiteCommand cmd, tgDataRequest request) { if (request.QueryType == tgQueryType.Text && request.QueryText != null && request.QueryText.Contains("{0}")) { int i = 0; string token = String.Empty; string sIndex = String.Empty; string param = String.Empty; foreach (tgParameter esParam in request.Parameters) { sIndex = i.ToString(); token = '{' + sIndex + '}'; param = Delimiters.Param + "p" + sIndex; request.QueryText = request.QueryText.Replace(token, param); i++; cmd.Parameters.AddWithValue(Delimiters.Param + esParam.Name, esParam.Value); } } else { SQLiteParameter param; foreach (tgParameter esParam in request.Parameters) { param = cmd.Parameters.AddWithValue(Delimiters.Param + esParam.Name, esParam.Value); switch (esParam.Direction) { case tgParameterDirection.InputOutput: param.Direction = ParameterDirection.InputOutput; break; case tgParameterDirection.Output: param.Direction = ParameterDirection.Output; param.DbType = esParam.DbType; param.Size = esParam.Size; break; case tgParameterDirection.ReturnValue: param.Direction = ParameterDirection.ReturnValue; break; // The default is ParameterDirection.Input; } } } } static public void GatherReturnParameters(SQLiteCommand cmd, tgDataRequest request, tgDataResponse response) { if (cmd.Parameters.Count > 0) { if (request.Parameters != null && request.Parameters.Count > 0) { response.Parameters = new tgParameters(); foreach (tgParameter esParam in request.Parameters) { if (esParam.Direction != tgParameterDirection.Input) { response.Parameters.Add(esParam); SQLiteParameter p = cmd.Parameters[Delimiters.Param + esParam.Name]; esParam.Value = p.Value; } } } } } } }
// ZipConstants.cs // // Copyright (C) 2001 Mike Krueger // Copyright (C) 2004 John Reilly // // 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. // HISTORY // 22-12-2009 DavidPierson Added AES support using System; using System.Threading; #if UNITY_WINRT && !UNITY_EDITOR using System.Text.Reign; #else using System.Text; #endif #if NETCF_1_0 || NETCF_2_0 || UNITY_WINRT using System.Globalization; #endif namespace ICSharpCode.SharpZipLib.Zip { #region Enumerations /// <summary> /// Determines how entries are tested to see if they should use Zip64 extensions or not. /// </summary> public enum UseZip64 { /// <summary> /// Zip64 will not be forced on entries during processing. /// </summary> /// <remarks>An entry can have this overridden if required <see cref="ZipEntry.ForceZip64"></see></remarks> Off, /// <summary> /// Zip64 should always be used. /// </summary> On, /// <summary> /// #ZipLib will determine use based on entry values when added to archive. /// </summary> Dynamic, } /// <summary> /// The kind of compression used for an entry in an archive /// </summary> public enum CompressionMethod { /// <summary> /// A direct copy of the file contents is held in the archive /// </summary> Stored = 0, /// <summary> /// Common Zip compression method using a sliding dictionary /// of up to 32KB and secondary compression from Huffman/Shannon-Fano trees /// </summary> Deflated = 8, /// <summary> /// An extension to deflate with a 64KB window. Not supported by #Zip currently /// </summary> Deflate64 = 9, /// <summary> /// BZip2 compression. Not supported by #Zip. /// </summary> BZip2 = 11, /// <summary> /// WinZip special for AES encryption, Now supported by #Zip. /// </summary> WinZipAES = 99, } /// <summary> /// Identifies the encryption algorithm used for an entry /// </summary> public enum EncryptionAlgorithm { /// <summary> /// No encryption has been used. /// </summary> None = 0, /// <summary> /// Encrypted using PKZIP 2.0 or 'classic' encryption. /// </summary> PkzipClassic = 1, /// <summary> /// DES encryption has been used. /// </summary> Des = 0x6601, /// <summary> /// RCS encryption has been used for encryption. /// </summary> RC2 = 0x6602, /// <summary> /// Triple DES encryption with 168 bit keys has been used for this entry. /// </summary> TripleDes168 = 0x6603, /// <summary> /// Triple DES with 112 bit keys has been used for this entry. /// </summary> TripleDes112 = 0x6609, /// <summary> /// AES 128 has been used for encryption. /// </summary> Aes128 = 0x660e, /// <summary> /// AES 192 has been used for encryption. /// </summary> Aes192 = 0x660f, /// <summary> /// AES 256 has been used for encryption. /// </summary> Aes256 = 0x6610, /// <summary> /// RC2 corrected has been used for encryption. /// </summary> RC2Corrected = 0x6702, /// <summary> /// Blowfish has been used for encryption. /// </summary> Blowfish = 0x6720, /// <summary> /// Twofish has been used for encryption. /// </summary> Twofish = 0x6721, /// <summary> /// RC4 has been used for encryption. /// </summary> RC4 = 0x6801, /// <summary> /// An unknown algorithm has been used for encryption. /// </summary> Unknown = 0xffff } /// <summary> /// Defines the contents of the general bit flags field for an archive entry. /// </summary> [Flags] public enum GeneralBitFlags : int { /// <summary> /// Bit 0 if set indicates that the file is encrypted /// </summary> Encrypted = 0x0001, /// <summary> /// Bits 1 and 2 - Two bits defining the compression method (only for Method 6 Imploding and 8,9 Deflating) /// </summary> Method = 0x0006, /// <summary> /// Bit 3 if set indicates a trailing data desciptor is appended to the entry data /// </summary> Descriptor = 0x0008, /// <summary> /// Bit 4 is reserved for use with method 8 for enhanced deflation /// </summary> ReservedPKware4 = 0x0010, /// <summary> /// Bit 5 if set indicates the file contains Pkzip compressed patched data. /// Requires version 2.7 or greater. /// </summary> Patched = 0x0020, /// <summary> /// Bit 6 if set indicates strong encryption has been used for this entry. /// </summary> StrongEncryption = 0x0040, /// <summary> /// Bit 7 is currently unused /// </summary> Unused7 = 0x0080, /// <summary> /// Bit 8 is currently unused /// </summary> Unused8 = 0x0100, /// <summary> /// Bit 9 is currently unused /// </summary> Unused9 = 0x0200, /// <summary> /// Bit 10 is currently unused /// </summary> Unused10 = 0x0400, /// <summary> /// Bit 11 if set indicates the filename and /// comment fields for this file must be encoded using UTF-8. /// </summary> UnicodeText = 0x0800, /// <summary> /// Bit 12 is documented as being reserved by PKware for enhanced compression. /// </summary> EnhancedCompress = 0x1000, /// <summary> /// Bit 13 if set indicates that values in the local header are masked to hide /// their actual values, and the central directory is encrypted. /// </summary> /// <remarks> /// Used when encrypting the central directory contents. /// </remarks> HeaderMasked = 0x2000, /// <summary> /// Bit 14 is documented as being reserved for use by PKware /// </summary> ReservedPkware14 = 0x4000, /// <summary> /// Bit 15 is documented as being reserved for use by PKware /// </summary> ReservedPkware15 = 0x8000 } #endregion /// <summary> /// This class contains constants used for Zip format files /// </summary> public sealed class ZipConstants { #region Versions /// <summary> /// The version made by field for entries in the central header when created by this library /// </summary> /// <remarks> /// This is also the Zip version for the library when comparing against the version required to extract /// for an entry. See <see cref="ZipEntry.CanDecompress"/>. /// </remarks> public const int VersionMadeBy = 51; // was 45 before AES /// <summary> /// The version made by field for entries in the central header when created by this library /// </summary> /// <remarks> /// This is also the Zip version for the library when comparing against the version required to extract /// for an entry. See <see cref="ZipInputStream.CanDecompressEntry">ZipInputStream.CanDecompressEntry</see>. /// </remarks> [Obsolete("Use VersionMadeBy instead")] public const int VERSION_MADE_BY = 51; /// <summary> /// The minimum version required to support strong encryption /// </summary> public const int VersionStrongEncryption = 50; /// <summary> /// The minimum version required to support strong encryption /// </summary> [Obsolete("Use VersionStrongEncryption instead")] public const int VERSION_STRONG_ENCRYPTION = 50; /// <summary> /// Version indicating AES encryption /// </summary> public const int VERSION_AES = 51; /// <summary> /// The version required for Zip64 extensions (4.5 or higher) /// </summary> public const int VersionZip64 = 45; #endregion #region Header Sizes /// <summary> /// Size of local entry header (excluding variable length fields at end) /// </summary> public const int LocalHeaderBaseSize = 30; /// <summary> /// Size of local entry header (excluding variable length fields at end) /// </summary> [Obsolete("Use LocalHeaderBaseSize instead")] public const int LOCHDR = 30; /// <summary> /// Size of Zip64 data descriptor /// </summary> public const int Zip64DataDescriptorSize = 24; /// <summary> /// Size of data descriptor /// </summary> public const int DataDescriptorSize = 16; /// <summary> /// Size of data descriptor /// </summary> [Obsolete("Use DataDescriptorSize instead")] public const int EXTHDR = 16; /// <summary> /// Size of central header entry (excluding variable fields) /// </summary> public const int CentralHeaderBaseSize = 46; /// <summary> /// Size of central header entry /// </summary> [Obsolete("Use CentralHeaderBaseSize instead")] public const int CENHDR = 46; /// <summary> /// Size of end of central record (excluding variable fields) /// </summary> public const int EndOfCentralRecordBaseSize = 22; /// <summary> /// Size of end of central record (excluding variable fields) /// </summary> [Obsolete("Use EndOfCentralRecordBaseSize instead")] public const int ENDHDR = 22; /// <summary> /// Size of 'classic' cryptographic header stored before any entry data /// </summary> public const int CryptoHeaderSize = 12; /// <summary> /// Size of cryptographic header stored before entry data /// </summary> [Obsolete("Use CryptoHeaderSize instead")] public const int CRYPTO_HEADER_SIZE = 12; #endregion #region Header Signatures /// <summary> /// Signature for local entry header /// </summary> public const int LocalHeaderSignature = 'P' | ('K' << 8) | (3 << 16) | (4 << 24); /// <summary> /// Signature for local entry header /// </summary> [Obsolete("Use LocalHeaderSignature instead")] public const int LOCSIG = 'P' | ('K' << 8) | (3 << 16) | (4 << 24); /// <summary> /// Signature for spanning entry /// </summary> public const int SpanningSignature = 'P' | ('K' << 8) | (7 << 16) | (8 << 24); /// <summary> /// Signature for spanning entry /// </summary> [Obsolete("Use SpanningSignature instead")] public const int SPANNINGSIG = 'P' | ('K' << 8) | (7 << 16) | (8 << 24); /// <summary> /// Signature for temporary spanning entry /// </summary> public const int SpanningTempSignature = 'P' | ('K' << 8) | ('0' << 16) | ('0' << 24); /// <summary> /// Signature for temporary spanning entry /// </summary> [Obsolete("Use SpanningTempSignature instead")] public const int SPANTEMPSIG = 'P' | ('K' << 8) | ('0' << 16) | ('0' << 24); /// <summary> /// Signature for data descriptor /// </summary> /// <remarks> /// This is only used where the length, Crc, or compressed size isnt known when the /// entry is created and the output stream doesnt support seeking. /// The local entry cannot be 'patched' with the correct values in this case /// so the values are recorded after the data prefixed by this header, as well as in the central directory. /// </remarks> public const int DataDescriptorSignature = 'P' | ('K' << 8) | (7 << 16) | (8 << 24); /// <summary> /// Signature for data descriptor /// </summary> /// <remarks> /// This is only used where the length, Crc, or compressed size isnt known when the /// entry is created and the output stream doesnt support seeking. /// The local entry cannot be 'patched' with the correct values in this case /// so the values are recorded after the data prefixed by this header, as well as in the central directory. /// </remarks> [Obsolete("Use DataDescriptorSignature instead")] public const int EXTSIG = 'P' | ('K' << 8) | (7 << 16) | (8 << 24); /// <summary> /// Signature for central header /// </summary> [Obsolete("Use CentralHeaderSignature instead")] public const int CENSIG = 'P' | ('K' << 8) | (1 << 16) | (2 << 24); /// <summary> /// Signature for central header /// </summary> public const int CentralHeaderSignature = 'P' | ('K' << 8) | (1 << 16) | (2 << 24); /// <summary> /// Signature for Zip64 central file header /// </summary> public const int Zip64CentralFileHeaderSignature = 'P' | ('K' << 8) | (6 << 16) | (6 << 24); /// <summary> /// Signature for Zip64 central file header /// </summary> [Obsolete("Use Zip64CentralFileHeaderSignature instead")] public const int CENSIG64 = 'P' | ('K' << 8) | (6 << 16) | (6 << 24); /// <summary> /// Signature for Zip64 central directory locator /// </summary> public const int Zip64CentralDirLocatorSignature = 'P' | ('K' << 8) | (6 << 16) | (7 << 24); /// <summary> /// Signature for archive extra data signature (were headers are encrypted). /// </summary> public const int ArchiveExtraDataSignature = 'P' | ('K' << 8) | (6 << 16) | (7 << 24); /// <summary> /// Central header digitial signature /// </summary> public const int CentralHeaderDigitalSignature = 'P' | ('K' << 8) | (5 << 16) | (5 << 24); /// <summary> /// Central header digitial signature /// </summary> [Obsolete("Use CentralHeaderDigitalSignaure instead")] public const int CENDIGITALSIG = 'P' | ('K' << 8) | (5 << 16) | (5 << 24); /// <summary> /// End of central directory record signature /// </summary> public const int EndOfCentralDirectorySignature = 'P' | ('K' << 8) | (5 << 16) | (6 << 24); /// <summary> /// End of central directory record signature /// </summary> [Obsolete("Use EndOfCentralDirectorySignature instead")] public const int ENDSIG = 'P' | ('K' << 8) | (5 << 16) | (6 << 24); #endregion #if UNITY_WINRT && !UNITY_EDITOR static int defaultCodePage = System.Text.Reign.CultureInfo.ANSICodePage(); #elif NETCF_1_0 || NETCF_2_0 // This isnt so great but is better than nothing. // Trying to work out an appropriate OEM code page would be good. // 850 is a good default for english speakers particularly in Europe. static int defaultCodePage = CultureInfo.CurrentCulture.TextInfo.ANSICodePage; #else static int defaultCodePage = Thread.CurrentThread.CurrentCulture.TextInfo.OEMCodePage; #endif /// <summary> /// Default encoding used for string conversion. 0 gives the default system OEM code page. /// Dont use unicode encodings if you want to be Zip compatible! /// Using the default code page isnt the full solution neccessarily /// there are many variable factors, codepage 850 is often a good choice for /// European users, however be careful about compatability. /// </summary> public static int DefaultCodePage { get { return defaultCodePage; } set { defaultCodePage = value; } } /// <summary> /// Convert a portion of a byte array to a string. /// </summary> /// <param name="data"> /// Data to convert to string /// </param> /// <param name="count"> /// Number of bytes to convert starting from index 0 /// </param> /// <returns> /// data[0]..data[length - 1] converted to a string /// </returns> public static string ConvertToString(byte[] data, int count) { if ( data == null ) { return string.Empty; } return Encoding.GetEncoding(DefaultCodePage).GetString(data, 0, count); } /// <summary> /// Convert a byte array to string /// </summary> /// <param name="data"> /// Byte array to convert /// </param> /// <returns> /// <paramref name="data">data</paramref>converted to a string /// </returns> public static string ConvertToString(byte[] data) { if ( data == null ) { return string.Empty; } return ConvertToString(data, data.Length); } /// <summary> /// Convert a byte array to string /// </summary> /// <param name="flags">The applicable general purpose bits flags</param> /// <param name="data"> /// Byte array to convert /// </param> /// <param name="count">The number of bytes to convert.</param> /// <returns> /// <paramref name="data">data</paramref>converted to a string /// </returns> public static string ConvertToStringExt(int flags, byte[] data, int count) { if ( data == null ) { return string.Empty; } if ( (flags & (int)GeneralBitFlags.UnicodeText) != 0 ) { return Encoding.UTF8.GetString(data, 0, count); } else { return ConvertToString(data, count); } } /// <summary> /// Convert a byte array to string /// </summary> /// <param name="data"> /// Byte array to convert /// </param> /// <param name="flags">The applicable general purpose bits flags</param> /// <returns> /// <paramref name="data">data</paramref>converted to a string /// </returns> public static string ConvertToStringExt(int flags, byte[] data) { if ( data == null ) { return string.Empty; } if ( (flags & (int)GeneralBitFlags.UnicodeText) != 0 ) { return Encoding.UTF8.GetString(data, 0, data.Length); } else { return ConvertToString(data, data.Length); } } /// <summary> /// Convert a string to a byte array /// </summary> /// <param name="str"> /// String to convert to an array /// </param> /// <returns>Converted array</returns> public static byte[] ConvertToArray(string str) { if ( str == null ) { return new byte[0]; } return Encoding.GetEncoding(DefaultCodePage).GetBytes(str); } /// <summary> /// Convert a string to a byte array /// </summary> /// <param name="flags">The applicable <see cref="GeneralBitFlags">general purpose bits flags</see></param> /// <param name="str"> /// String to convert to an array /// </param> /// <returns>Converted array</returns> public static byte[] ConvertToArray(int flags, string str) { if (str == null) { return new byte[0]; } if ((flags & (int)GeneralBitFlags.UnicodeText) != 0) { return Encoding.UTF8.GetBytes(str); } else { return ConvertToArray(str); } } /// <summary> /// Initialise default instance of <see cref="ZipConstants">ZipConstants</see> /// </summary> /// <remarks> /// Private to prevent instances being created. /// </remarks> ZipConstants() { // Do nothing } } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // File System.Windows.Media.PathSegmentCollection.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.Windows.Media { sealed public partial class PathSegmentCollection : System.Windows.Media.Animation.Animatable, System.Collections.IList, System.Collections.ICollection, IList<PathSegment>, ICollection<PathSegment>, IEnumerable<PathSegment>, System.Collections.IEnumerable { #region Methods and constructors public void Add(PathSegment value) { } public void Clear() { } public PathSegmentCollection Clone() { return default(PathSegmentCollection); } protected override void CloneCore(System.Windows.Freezable source) { } public PathSegmentCollection CloneCurrentValue() { return default(PathSegmentCollection); } protected override void CloneCurrentValueCore(System.Windows.Freezable source) { } public bool Contains(PathSegment value) { return default(bool); } public void CopyTo(PathSegment[] array, int index) { } protected override System.Windows.Freezable CreateInstanceCore() { return default(System.Windows.Freezable); } protected override bool FreezeCore(bool isChecking) { return default(bool); } protected override void GetAsFrozenCore(System.Windows.Freezable source) { } protected override void GetCurrentValueAsFrozenCore(System.Windows.Freezable source) { } public PathSegmentCollection.Enumerator GetEnumerator() { return default(PathSegmentCollection.Enumerator); } public int IndexOf(PathSegment value) { return default(int); } public void Insert(int index, PathSegment value) { } public PathSegmentCollection() { } public PathSegmentCollection(IEnumerable<PathSegment> collection) { } public PathSegmentCollection(int capacity) { } public bool Remove(PathSegment value) { return default(bool); } public void RemoveAt(int index) { } IEnumerator<PathSegment> System.Collections.Generic.IEnumerable<System.Windows.Media.PathSegment>.GetEnumerator() { return default(IEnumerator<PathSegment>); } void System.Collections.ICollection.CopyTo(Array array, int index) { } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return default(System.Collections.IEnumerator); } int System.Collections.IList.Add(Object value) { return default(int); } bool System.Collections.IList.Contains(Object value) { return default(bool); } int System.Collections.IList.IndexOf(Object value) { return default(int); } void System.Collections.IList.Insert(int index, Object value) { } void System.Collections.IList.Remove(Object value) { } #endregion #region Properties and indexers public int Count { get { return default(int); } } public PathSegment this [int index] { get { return default(PathSegment); } set { } } bool System.Collections.Generic.ICollection<System.Windows.Media.PathSegment>.IsReadOnly { get { return default(bool); } } bool System.Collections.ICollection.IsSynchronized { get { return default(bool); } } Object System.Collections.ICollection.SyncRoot { get { return default(Object); } } bool System.Collections.IList.IsFixedSize { get { return default(bool); } } bool System.Collections.IList.IsReadOnly { get { return default(bool); } } Object System.Collections.IList.this [int index] { get { return default(Object); } set { } } #endregion } }
using System; using System.Windows.Forms; using System.Collections.Specialized; using System.Data; using System.Data.OleDb; using System.Reflection; using C1.Win.C1Preview; using PCSComUtils.Common; using PCSUtils.Utils; namespace ItemListReport { [Serializable] public class ItemListReport : MarshalByRefObject, IDynamicReport { public ItemListReport() { } #region IDynamicReport Members private bool mUseReportViewerRenderEngine = false; private string mConnectionString; private ReportBuilder mReportBuilder; private C1PrintPreviewControl mReportViewer; private object mResult; /// <summary> /// ConnectionString, provide for the Dynamic Report /// ALlow Dynamic Report to access the DataBase of PCS /// </summary> public string PCSConnectionString { get { return mConnectionString; } set { mConnectionString = value; } } /// <summary> /// Report Builder Utility Object /// Dynamic Report can use this object to render, modify, layout the report /// </summary> public ReportBuilder PCSReportBuilder { get { return mReportBuilder; } set { mReportBuilder = value; } } /// <summary> /// ReportViewer Object, provide for the DynamicReport, /// allow Dynamic Report to manipulate with the REportViewer, /// modify the report after rendered if needed /// </summary> public C1PrintPreviewControl PCSReportViewer { get { return mReportViewer; } set { mReportViewer = value; } } /// <summary> /// Store other result if any. Ussually we store return DataTable here to display on the ReportViewer Form's Grid /// </summary> public object Result { get { return mResult; } set { mResult = value; } } /// <summary> /// Notify PCS whether the rendering report process is run by /// this IDynamicReport or the ReportViewer Engine (in the ReportViewer form) /// </summary> public bool UseReportViewerRenderEngine { get { return mUseReportViewerRenderEngine; } set { mUseReportViewerRenderEngine = value; } } private string mstrReportDefinitionFolder = string.Empty; /// <summary> /// Inform External Process where to find out the ReportLayout ( the PCS' ReportDefinition Folder Path ) /// </summary> public string ReportDefinitionFolder { get { return mstrReportDefinitionFolder; } set { mstrReportDefinitionFolder = value; } } private string mstrReportLayoutFile = string.Empty; /// <summary> /// Inform External Process about the Layout file /// in which PCS instruct to use /// (PCS will assign this property while ReportViewer Form execute, /// ReportVIewer form will use the layout file in the report config entry to put in this property) /// </summary> public string ReportLayoutFile { get { return mstrReportLayoutFile; } set { mstrReportLayoutFile = value; } } #endregion #region Private Method private DataTable GetItemListData(string pstrCCN, string pstrCategory, string pstrModel, string pstrSource, string pstrType, string pstrMakeItem) { OleDbConnection cn = new OleDbConnection(mConnectionString); DataTable dtbItemData = new DataTable(); try { //Build WHERE clause string strWhereClause = " WHERE MST_CCN.Code ='" + pstrCCN.Replace("'", "''") + "'"; //Category if(pstrCategory != null && pstrCategory != string.Empty) { strWhereClause += " AND ITM_Category.Code IN (" + pstrCategory + ")"; } //Model if(pstrModel != null && pstrModel != string.Empty) { strWhereClause += " AND ITM_Product.Revision IN (" + pstrModel + ")"; } //Source if(pstrSource != null && pstrSource != string.Empty) { strWhereClause += " AND ITM_Source.Code ='" + pstrSource.Replace("'", "''") + "'"; } //Type if(pstrType != null && pstrType != string.Empty) { strWhereClause += " AND ITM_ProductType.Code ='" + pstrType.Replace("'", "''") + "'"; } //Make Item if(pstrMakeItem != null && pstrMakeItem != string.Empty) { if(pstrMakeItem.ToUpper().Equals("TRUE") || pstrMakeItem == "1") { strWhereClause += " AND ITM_Product.MakeItem =1"; } else { strWhereClause += " AND (ITM_Product.MakeItem = 0 OR ITM_Product.MakeItem IS NULL )"; } } //Build SQL string string strSql = "SELECT ITM_Category.Code as CategoryCode,"; strSql += " ITM_Product.Code as PartNumber,"; strSql += " ITM_Product.Description as PartName,"; strSql += " ITM_Product.Revision as PartModel,"; strSql += " Case ITM_Product.SafetyStock"; strSql += " When 0 then NULL"; strSql += " Else ITM_Product.SafetyStock"; strSql += " End as SafetyStock,"; strSql += " Case ITM_Product.ScrapPercent"; strSql += " When 0 then NULL"; strSql += " Else ITM_Product.ScrapPercent"; strSql += " End as ScrapPercent,"; strSql += " Case ITM_Product.MakeItem"; strSql += " When 1 then 'x'"; strSql += " Else ''"; strSql += " End as MakeItem,"; strSql += " MST_UnitOfMeasure.Code AS UMCode,"; strSql += " ITM_Source.Code AS SourceCode,"; strSql += " ITM_ProductType.Code AS ProductTypeCode,"; strSql += " MST_Party.Code AS PartyCode, "; strSql += " Case "; strSql += " When Len(MST_Party.Name) <= 45 then MST_Party.Name"; strSql += " Else LEFT(MST_Party.Name, 42) + '...'"; strSql += " End as PartyName,"; strSql += " MST_MasterLocation.Code AS MasLocCode,"; strSql += " MST_Location.Code AS LocationCode,"; strSql += " MST_CCN.Code as CCNCode"; strSql += " FROM ITM_Product"; strSql += " INNER JOIN MST_CCN ON MST_CCN.CCNID = ITM_Product.CCNID"; strSql += " INNER JOIN MST_UnitOfMeasure ON ITM_Product.StockUMID = MST_UnitOfMeasure.UnitOfMeasureID"; strSql += " LEFT JOIN MST_MasterLocation ON ITM_Product.MasterLocationID = MST_MasterLocation.MasterLocationID"; strSql += " LEFT JOIN MST_Location ON ITM_Product.LocationID = MST_Location.LocationID"; strSql += " LEFT JOIN ITM_ProductType ON ITM_ProductType.ProductTypeID = ITM_Product.ProductTypeID"; strSql += " LEFT JOIN MST_Party ON ITM_Product.PrimaryVendorID = MST_Party.PartyID"; strSql += " LEFT JOIN ITM_Source ON ITM_Product.SourceID = ITM_Source.SourceID"; strSql += " LEFT JOIN ITM_Category ON ITM_Product.CategoryID = ITM_Category.CategoryID"; //Add WHERE clause strSql += strWhereClause; //Add ORDER clause strSql += " ORDER BY CategoryCode, PartName ASC"; OleDbDataAdapter odad = new OleDbDataAdapter(strSql, cn); odad.Fill(dtbItemData); } catch (Exception ex) { throw ex; } finally { if (cn != null) if (cn.State != ConnectionState.Closed) cn.Close(); } return dtbItemData; } #endregion Private Method #region Public Method public object Invoke(string pstrMethod, object[] pobjParameters) { return this.GetType().InvokeMember(pstrMethod, BindingFlags.InvokeMethod, null, this, pobjParameters); } public DataTable ExecuteReport(string pstrCCN, string pstrCategory, string pstrModel, string pstrSource, string pstrType, string pstrMakeItem) { try { //const char UNCHECK_SQUARE_CHAR = (char)111; //const char CHECK_SQUARE_CHAR = (char)120; //const char SPACE_CHAR = (char)32; //Report name const string REPORT_NAME = "ItemListReport"; const string REPORT_LAYOUT = "ItemListReport.xml"; const string RPT_HEADER = "Header"; //Report field names const string RPT_TITLE_FIELD = "fldTitle"; //Report field names const string RPT_CCN = "CCN"; const string RPT_CATEGORY = "Category"; const string RPT_MODEL = "Model"; const string RPT_SOURCE = "Source"; const string RPT_TYPE = "Type"; const string RPT_MAKE_ITEM = "Make"; DataTable dtbItemList = GetItemListData(pstrCCN, pstrCategory, pstrModel, pstrSource, pstrType, pstrMakeItem); //Create builder object ReportWithSubReportBuilder reportBuilder = new ReportWithSubReportBuilder(); //Set report name reportBuilder.ReportName = REPORT_NAME; //Set Datasource reportBuilder.SourceDataTable = dtbItemList; //Set report layout location reportBuilder.ReportDefinitionFolder = mstrReportDefinitionFolder; reportBuilder.ReportLayoutFile = REPORT_LAYOUT; reportBuilder.UseLayoutFile = true; reportBuilder.MakeDataTableForRender(); // and show it in preview dialog PCSUtils.Framework.ReportFrame.C1PrintPreviewDialog printPreview = new PCSUtils.Framework.ReportFrame.C1PrintPreviewDialog(); //Attach report viewer reportBuilder.ReportViewer = printPreview.ReportViewer; reportBuilder.RenderReport(); //Draw parameters System.Collections.Specialized.NameValueCollection arrParamAndValue = new System.Collections.Specialized.NameValueCollection(); arrParamAndValue.Add(RPT_CCN, pstrCCN); if(pstrCategory != string.Empty) { arrParamAndValue.Add(RPT_CATEGORY, pstrCategory); } if(pstrModel != string.Empty) { arrParamAndValue.Add(RPT_MODEL, pstrModel); } if(pstrSource != string.Empty) { arrParamAndValue.Add(RPT_SOURCE, pstrSource); } if(pstrType != string.Empty) { arrParamAndValue.Add(RPT_TYPE, pstrType); } if(pstrMakeItem.ToUpper().Equals("TRUE") || pstrMakeItem.Equals("1")) { arrParamAndValue.Add(RPT_MAKE_ITEM, "x"); } //Anchor the Parameter drawing canvas cordinate to the fldTitle C1.C1Report.Field fldTitle = reportBuilder.GetFieldByName(RPT_TITLE_FIELD); double dblStartX = fldTitle.Left; double dblStartY = fldTitle.Top + 1.3 * fldTitle.RenderHeight; reportBuilder.GetSectionByName(RPT_HEADER).CanGrow = true; reportBuilder.DrawParameters(reportBuilder.GetSectionByName(RPT_HEADER), dblStartX, dblStartY, arrParamAndValue, reportBuilder.Report.Font.Size); try { printPreview.FormTitle = reportBuilder.GetFieldByName(RPT_TITLE_FIELD).Text; } catch{} //Show report reportBuilder.RefreshReport(); printPreview.Show(); return dtbItemList; } catch (Exception ex) { throw ex; } } #endregion Public Method } }
// // 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 Microsoft.Azure.Commands.Compute.Automation.Models; using Microsoft.Azure.Management.Compute; using Microsoft.Azure.Management.Compute.Models; using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Management.Automation; using System.Reflection; namespace Microsoft.Azure.Commands.Compute.Automation { public abstract class ComputeAutomationBaseCmdlet : Microsoft.Azure.Commands.Compute.ComputeClientBaseCmdlet { public override void ExecuteCmdlet() { base.ExecuteCmdlet(); } protected static PSArgument[] ConvertFromObjectsToArguments(string[] names, object[] objects) { var arguments = new PSArgument[objects.Length]; for (int index = 0; index < objects.Length; index++) { arguments[index] = new PSArgument { Name = names[index], Type = objects[index].GetType(), Value = objects[index] }; } return arguments; } protected static object[] ConvertFromArgumentsToObjects(object[] arguments) { if (arguments == null) { return null; } var objects = new object[arguments.Length]; for (int index = 0; index < arguments.Length; index++) { if (arguments[index] is PSArgument) { objects[index] = ((PSArgument)arguments[index]).Value; } else { objects[index] = arguments[index]; } } return objects; } public IAvailabilitySetsOperations AvailabilitySetsClient { get { return ComputeClient.ComputeManagementClient.AvailabilitySets; } } public IContainerServicesOperations ContainerServicesClient { get { return ComputeClient.ComputeManagementClient.ContainerServices; } } public IDisksOperations DisksClient { get { return ComputeClient.ComputeManagementClient.Disks; } } public IImagesOperations ImagesClient { get { return ComputeClient.ComputeManagementClient.Images; } } public IResourceSkusOperations ResourceSkusClient { get { return ComputeClient.ComputeManagementClient.ResourceSkus; } } public ISnapshotsOperations SnapshotsClient { get { return ComputeClient.ComputeManagementClient.Snapshots; } } public IVirtualMachineRunCommandsOperations VirtualMachineRunCommandsClient { get { return ComputeClient.ComputeManagementClient.VirtualMachineRunCommands; } } public IVirtualMachineScaleSetRollingUpgradesOperations VirtualMachineScaleSetRollingUpgradesClient { get { return ComputeClient.ComputeManagementClient.VirtualMachineScaleSetRollingUpgrades; } } public IVirtualMachineScaleSetsOperations VirtualMachineScaleSetsClient { get { return ComputeClient.ComputeManagementClient.VirtualMachineScaleSets; } } public IVirtualMachineScaleSetVMsOperations VirtualMachineScaleSetVMsClient { get { return ComputeClient.ComputeManagementClient.VirtualMachineScaleSetVMs; } } public IVirtualMachinesOperations VirtualMachinesClient { get { return ComputeClient.ComputeManagementClient.VirtualMachines; } } public static string FormatObject(Object obj) { var objType = obj.GetType(); System.Reflection.PropertyInfo[] pros = objType.GetProperties(); string result = "\n"; var resultTuples = new List<Tuple<string, string, int>>(); var totalTab = GetTabLength(obj, 0, 0, resultTuples) + 1; foreach (var t in resultTuples) { string preTab = new string(' ', t.Item3 * 2); string postTab = new string(' ', totalTab - t.Item3 * 2 - t.Item1.Length); result += preTab + t.Item1 + postTab + ": " + t.Item2 + "\n"; } return result; } private static int GetTabLength(Object obj, int max, int depth, List<Tuple<string, string, int>> tupleList) { var objType = obj.GetType(); var propertySet = new List<PropertyInfo>(); if (objType.BaseType != null) { foreach (var property in objType.BaseType.GetProperties()) { propertySet.Add(property); } } foreach (var property in objType.GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public)) { propertySet.Add(property); } foreach (var property in propertySet) { Object childObject = property.GetValue(obj, null); var isJObject = childObject as Newtonsoft.Json.Linq.JObject; if (isJObject != null) { var objStringValue = Newtonsoft.Json.JsonConvert.SerializeObject(childObject); int i = objStringValue.IndexOf("xmlCfg"); if (i >= 0) { var xmlCfgString = objStringValue.Substring(i + 7); int start = xmlCfgString.IndexOf('"'); int end = xmlCfgString.IndexOf('"', start + 1); xmlCfgString = xmlCfgString.Substring(start + 1, end - start - 1); objStringValue = objStringValue.Replace(xmlCfgString, "..."); } tupleList.Add(MakeTuple(property.Name, objStringValue, depth)); max = Math.Max(max, depth * 2 + property.Name.Length); } else { var elem = childObject as IList; if (elem != null) { if (elem.Count != 0) { max = Math.Max(max, depth * 2 + property.Name.Length + 4); for (int i = 0; i < elem.Count; i++) { Type propType = elem[i].GetType(); if (propType.IsSerializable || propType.Equals(typeof(Newtonsoft.Json.Linq.JObject))) { tupleList.Add(MakeTuple(property.Name + "[" + i + "]", elem[i].ToString(), depth)); } else { tupleList.Add(MakeTuple(property.Name + "[" + i + "]", "", depth)); max = Math.Max(max, GetTabLength((Object)elem[i], max, depth + 1, tupleList)); } } } } else { if (property.PropertyType.IsSerializable) { if (childObject != null) { tupleList.Add(MakeTuple(property.Name, childObject.ToString(), depth)); max = Math.Max(max, depth * 2 + property.Name.Length); } } else { var isDictionary = childObject as IDictionary; if (isDictionary != null) { tupleList.Add(MakeTuple(property.Name, Newtonsoft.Json.JsonConvert.SerializeObject(childObject), depth)); max = Math.Max(max, depth * 2 + property.Name.Length); } else if (childObject != null) { tupleList.Add(MakeTuple(property.Name, "", depth)); max = Math.Max(max, GetTabLength(childObject, max, depth + 1, tupleList)); } } } } } return max; } private static Tuple<string, string, int> MakeTuple(string key, string value, int depth) { return new Tuple<string, string, int>(key, value, depth); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.Linq; using Xunit; namespace System.Collections.Immutable.Tests { public class ImmutableSortedSetBuilderTest : ImmutablesTestBase { [Fact] public void CreateBuilder() { ImmutableSortedSet<string>.Builder builder = ImmutableSortedSet.CreateBuilder<string>(); Assert.NotNull(builder); builder = ImmutableSortedSet.CreateBuilder<string>(StringComparer.OrdinalIgnoreCase); Assert.Same(StringComparer.OrdinalIgnoreCase, builder.KeyComparer); } [Fact] public void ToBuilder() { var builder = ImmutableSortedSet<int>.Empty.ToBuilder(); Assert.True(builder.Add(3)); Assert.True(builder.Add(5)); Assert.False(builder.Add(5)); Assert.Equal(2, builder.Count); Assert.True(builder.Contains(3)); Assert.True(builder.Contains(5)); Assert.False(builder.Contains(7)); var set = builder.ToImmutable(); Assert.Equal(builder.Count, set.Count); Assert.True(builder.Add(8)); Assert.Equal(3, builder.Count); Assert.Equal(2, set.Count); Assert.True(builder.Contains(8)); Assert.False(set.Contains(8)); } [Fact] public void BuilderFromSet() { var set = ImmutableSortedSet<int>.Empty.Add(1); var builder = set.ToBuilder(); Assert.True(builder.Contains(1)); Assert.True(builder.Add(3)); Assert.True(builder.Add(5)); Assert.False(builder.Add(5)); Assert.Equal(3, builder.Count); Assert.True(builder.Contains(3)); Assert.True(builder.Contains(5)); Assert.False(builder.Contains(7)); var set2 = builder.ToImmutable(); Assert.Equal(builder.Count, set2.Count); Assert.True(set2.Contains(1)); Assert.True(builder.Add(8)); Assert.Equal(4, builder.Count); Assert.Equal(3, set2.Count); Assert.True(builder.Contains(8)); Assert.False(set.Contains(8)); Assert.False(set2.Contains(8)); } [Fact] public void EnumerateBuilderWhileMutating() { var builder = ImmutableSortedSet<int>.Empty.Union(Enumerable.Range(1, 10)).ToBuilder(); Assert.Equal(Enumerable.Range(1, 10), builder); var enumerator = builder.GetEnumerator(); Assert.True(enumerator.MoveNext()); builder.Add(11); // Verify that a new enumerator will succeed. Assert.Equal(Enumerable.Range(1, 11), builder); // Try enumerating further with the previous enumerable now that we've changed the collection. Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext()); enumerator.Reset(); enumerator.MoveNext(); // resetting should fix the problem. // Verify that by obtaining a new enumerator, we can enumerate all the contents. Assert.Equal(Enumerable.Range(1, 11), builder); } [Fact] public void BuilderReusesUnchangedImmutableInstances() { var collection = ImmutableSortedSet<int>.Empty.Add(1); var builder = collection.ToBuilder(); Assert.Same(collection, builder.ToImmutable()); // no changes at all. builder.Add(2); var newImmutable = builder.ToImmutable(); Assert.NotSame(collection, newImmutable); // first ToImmutable with changes should be a new instance. Assert.Same(newImmutable, builder.ToImmutable()); // second ToImmutable without changes should be the same instance. } [Fact] public void GetEnumeratorTest() { var builder = ImmutableSortedSet.Create("a", "B").WithComparer(StringComparer.Ordinal).ToBuilder(); IEnumerable<string> enumerable = builder; using (var enumerator = enumerable.GetEnumerator()) { Assert.True(enumerator.MoveNext()); Assert.Equal("B", enumerator.Current); Assert.True(enumerator.MoveNext()); Assert.Equal("a", enumerator.Current); Assert.False(enumerator.MoveNext()); } } [Fact] public void MaxMin() { var builder = ImmutableSortedSet.Create(1, 2, 3).ToBuilder(); Assert.Equal(1, builder.Min); Assert.Equal(3, builder.Max); } [Fact] public void Clear() { var set = ImmutableSortedSet<int>.Empty.Add(1); var builder = set.ToBuilder(); builder.Clear(); Assert.Equal(0, builder.Count); } [Fact] public void KeyComparer() { var builder = ImmutableSortedSet.Create("a", "B").ToBuilder(); Assert.Same(Comparer<string>.Default, builder.KeyComparer); Assert.True(builder.Contains("a")); Assert.False(builder.Contains("A")); builder.KeyComparer = StringComparer.OrdinalIgnoreCase; Assert.Same(StringComparer.OrdinalIgnoreCase, builder.KeyComparer); Assert.Equal(2, builder.Count); Assert.True(builder.Contains("a")); Assert.True(builder.Contains("A")); var set = builder.ToImmutable(); Assert.Same(StringComparer.OrdinalIgnoreCase, set.KeyComparer); } [Fact] public void KeyComparerCollisions() { var builder = ImmutableSortedSet.Create("a", "A").ToBuilder(); builder.KeyComparer = StringComparer.OrdinalIgnoreCase; Assert.Equal(1, builder.Count); Assert.True(builder.Contains("a")); var set = builder.ToImmutable(); Assert.Same(StringComparer.OrdinalIgnoreCase, set.KeyComparer); Assert.Equal(1, set.Count); Assert.True(set.Contains("a")); } [Fact] public void KeyComparerEmptyCollection() { var builder = ImmutableSortedSet.Create<string>().ToBuilder(); Assert.Same(Comparer<string>.Default, builder.KeyComparer); builder.KeyComparer = StringComparer.OrdinalIgnoreCase; Assert.Same(StringComparer.OrdinalIgnoreCase, builder.KeyComparer); var set = builder.ToImmutable(); Assert.Same(StringComparer.OrdinalIgnoreCase, set.KeyComparer); } [Fact] public void UnionWith() { var builder = ImmutableSortedSet.Create(1, 2, 3).ToBuilder(); Assert.Throws<ArgumentNullException>("other", () => builder.UnionWith(null)); builder.UnionWith(new[] { 2, 3, 4 }); Assert.Equal(new[] { 1, 2, 3, 4 }, builder); } [Fact] public void ExceptWith() { var builder = ImmutableSortedSet.Create(1, 2, 3).ToBuilder(); Assert.Throws<ArgumentNullException>("other", () => builder.ExceptWith(null)); builder.ExceptWith(new[] { 2, 3, 4 }); Assert.Equal(new[] { 1 }, builder); } [Fact] public void SymmetricExceptWith() { var builder = ImmutableSortedSet.Create(1, 2, 3).ToBuilder(); Assert.Throws<ArgumentNullException>("other", () => builder.SymmetricExceptWith(null)); builder.SymmetricExceptWith(new[] { 2, 3, 4 }); Assert.Equal(new[] { 1, 4 }, builder); } [Fact] public void IntersectWith() { var builder = ImmutableSortedSet.Create(1, 2, 3).ToBuilder(); Assert.Throws<ArgumentNullException>("other", () => builder.IntersectWith(null)); builder.IntersectWith(new[] { 2, 3, 4 }); Assert.Equal(new[] { 2, 3 }, builder); } [Fact] public void IsProperSubsetOf() { var builder = ImmutableSortedSet.CreateRange(Enumerable.Range(1, 3)).ToBuilder(); Assert.Throws<ArgumentNullException>("other", () => builder.IsProperSubsetOf(null)); Assert.False(builder.IsProperSubsetOf(Enumerable.Range(1, 3))); Assert.True(builder.IsProperSubsetOf(Enumerable.Range(1, 5))); } [Fact] public void IsProperSupersetOf() { var builder = ImmutableSortedSet.CreateRange(Enumerable.Range(1, 3)).ToBuilder(); Assert.Throws<ArgumentNullException>("other", () => builder.IsProperSupersetOf(null)); Assert.False(builder.IsProperSupersetOf(Enumerable.Range(1, 3))); Assert.True(builder.IsProperSupersetOf(Enumerable.Range(1, 2))); } [Fact] public void IsSubsetOf() { var builder = ImmutableSortedSet.CreateRange(Enumerable.Range(1, 3)).ToBuilder(); Assert.Throws<ArgumentNullException>("other", () => builder.IsSubsetOf(null)); Assert.False(builder.IsSubsetOf(Enumerable.Range(1, 2))); Assert.True(builder.IsSubsetOf(Enumerable.Range(1, 3))); Assert.True(builder.IsSubsetOf(Enumerable.Range(1, 5))); } [Fact] public void IsSupersetOf() { var builder = ImmutableSortedSet.CreateRange(Enumerable.Range(1, 3)).ToBuilder(); Assert.Throws<ArgumentNullException>("other", () => builder.IsSupersetOf(null)); Assert.False(builder.IsSupersetOf(Enumerable.Range(1, 4))); Assert.True(builder.IsSupersetOf(Enumerable.Range(1, 3))); Assert.True(builder.IsSupersetOf(Enumerable.Range(1, 2))); } [Fact] public void Overlaps() { var builder = ImmutableSortedSet.CreateRange(Enumerable.Range(1, 3)).ToBuilder(); Assert.Throws<ArgumentNullException>("other", () => builder.Overlaps(null)); Assert.True(builder.Overlaps(Enumerable.Range(3, 2))); Assert.False(builder.Overlaps(Enumerable.Range(4, 3))); } [Fact] public void Remove() { var builder = ImmutableSortedSet.Create("a").ToBuilder(); Assert.Throws<ArgumentNullException>("key", () => builder.Remove(null)); Assert.False(builder.Remove("b")); Assert.True(builder.Remove("a")); } [Fact] public void Reverse() { var builder = ImmutableSortedSet.Create("a", "b").ToBuilder(); Assert.Equal(new[] { "b", "a" }, builder.Reverse()); } [Fact] public void SetEquals() { var builder = ImmutableSortedSet.Create("a").ToBuilder(); Assert.Throws<ArgumentNullException>("other", () => builder.SetEquals(null)); Assert.False(builder.SetEquals(new[] { "b" })); Assert.True(builder.SetEquals(new[] { "a" })); Assert.True(builder.SetEquals(builder)); } [Fact] public void ICollectionOfTMethods() { ICollection<string> builder = ImmutableSortedSet.Create("a").ToBuilder(); builder.Add("b"); Assert.True(builder.Contains("b")); var array = new string[3]; builder.CopyTo(array, 1); Assert.Equal(new[] { null, "a", "b" }, array); Assert.False(builder.IsReadOnly); Assert.Equal(new[] { "a", "b" }, builder.ToArray()); // tests enumerator } [Fact] public void ICollectionMethods() { ICollection builder = ImmutableSortedSet.Create("a").ToBuilder(); var array = new string[builder.Count + 1]; builder.CopyTo(array, 1); Assert.Equal(new[] { null, "a" }, array); Assert.False(builder.IsSynchronized); Assert.NotNull(builder.SyncRoot); Assert.Same(builder.SyncRoot, builder.SyncRoot); } [Fact] public void Indexer() { var builder = ImmutableSortedSet.Create(1, 3, 2).ToBuilder(); Assert.Equal(1, builder[0]); Assert.Equal(2, builder[1]); Assert.Equal(3, builder[2]); Assert.Throws<ArgumentOutOfRangeException>("index", () => builder[-1]); Assert.Throws<ArgumentOutOfRangeException>("index", () => builder[3]); } [Fact] public void DebuggerAttributesValid() { DebuggerAttributes.ValidateDebuggerDisplayReferences(ImmutableSortedSet.CreateBuilder<string>()); DebuggerAttributes.ValidateDebuggerTypeProxyProperties(ImmutableSortedSet.CreateBuilder<int>()); } } }
using System; using System.Collections.Generic; using System.Security.Cryptography; using System.Text; using DeOps.Implementation.Protocol; namespace DeOps.Services.Board { public class BoardPacket { public const byte PostHeader = 0x10; public const byte PostInfo = 0x20; public const byte PostFile = 0x30; } public class PostHeader : G2Packet { const byte Packet_Source = 0x10; const byte Packet_Target = 0x20; const byte Packet_ProjectID = 0x30; const byte Packet_PostID = 0x40; const byte Packet_ParentID = 0x50; const byte Packet_Time = 0x60; const byte Packet_Scope = 0x70; const byte Packet_FileKey = 0x80; const byte Packet_FileHash = 0x90; const byte Packet_FileSize = 0xA0; const byte Packet_FileStart = 0xB0; const byte Packet_EditTime = 0xC0; const byte Packet_Version = 0xD0; const byte Packet_Archived = 0xE0; public byte[] Source; public byte[] Target; public uint ProjectID; public uint PostID; public uint ParentID; public DateTime Time; public ScopeType Scope; public bool Archived; public ushort Version; public DateTime EditTime; public byte[] FileKey; public byte[] FileHash; public long FileSize; public long FileStart; public ulong SourceID; public ulong TargetID; // cant write local info (read) because post is re-transmitted public override byte[] Encode(G2Protocol protocol) { lock (protocol.WriteSection) { G2Frame header = protocol.WritePacket(null, BoardPacket.PostHeader, null); protocol.WritePacket(header, Packet_Source, Source); protocol.WritePacket(header, Packet_Target, Target); protocol.WritePacket(header, Packet_ProjectID, BitConverter.GetBytes(ProjectID)); protocol.WritePacket(header, Packet_PostID, BitConverter.GetBytes(PostID)); protocol.WritePacket(header, Packet_ParentID, BitConverter.GetBytes(ParentID)); protocol.WritePacket(header, Packet_Time, BitConverter.GetBytes(Time.ToBinary())); protocol.WritePacket(header, Packet_Scope, new byte[] { (byte)Scope }); protocol.WritePacket(header, Packet_Version, BitConverter.GetBytes(Version)); protocol.WritePacket(header, Packet_EditTime, BitConverter.GetBytes(EditTime.ToBinary())); protocol.WritePacket(header, Packet_Archived, BitConverter.GetBytes(Archived)); protocol.WritePacket(header, Packet_FileKey, FileKey); protocol.WritePacket(header, Packet_FileHash, FileHash); protocol.WritePacket(header, Packet_FileSize, BitConverter.GetBytes(FileSize)); protocol.WritePacket(header, Packet_FileStart, BitConverter.GetBytes(FileStart)); return protocol.WriteFinish(); } } public static PostHeader Decode(G2Header root) { PostHeader header = new PostHeader(); G2Header child = new G2Header(root.Data); while (G2Protocol.ReadNextChild(root, child) == G2ReadResult.PACKET_GOOD) { if (!G2Protocol.ReadPayload(child)) continue; switch (child.Name) { case Packet_Source: header.Source = Utilities.ExtractBytes(child.Data, child.PayloadPos, child.PayloadSize); header.SourceID = Utilities.KeytoID(header.Source); break; case Packet_Target: header.Target = Utilities.ExtractBytes(child.Data, child.PayloadPos, child.PayloadSize); header.TargetID = Utilities.KeytoID(header.Target); break; case Packet_ProjectID: header.ProjectID = BitConverter.ToUInt32(child.Data, child.PayloadPos); break; case Packet_PostID: header.PostID = BitConverter.ToUInt32(child.Data, child.PayloadPos); break; case Packet_ParentID: header.ParentID = BitConverter.ToUInt32(child.Data, child.PayloadPos); break; case Packet_Time: header.Time = DateTime.FromBinary(BitConverter.ToInt64(child.Data, child.PayloadPos)); break; case Packet_EditTime: header.EditTime = DateTime.FromBinary(BitConverter.ToInt64(child.Data, child.PayloadPos)); break; case Packet_Archived: header.Archived = BitConverter.ToBoolean(child.Data, child.PayloadPos); break; case Packet_Version: header.Version = BitConverter.ToUInt16(child.Data, child.PayloadPos); break; case Packet_Scope: header.Scope = (ScopeType)child.Data[child.PayloadPos]; break; case Packet_FileKey: header.FileKey = Utilities.ExtractBytes(child.Data, child.PayloadPos, child.PayloadSize); break; case Packet_FileHash: header.FileHash = Utilities.ExtractBytes(child.Data, child.PayloadPos, child.PayloadSize); break; case Packet_FileSize: header.FileSize = BitConverter.ToInt64(child.Data, child.PayloadPos); break; case Packet_FileStart: header.FileStart = BitConverter.ToInt64(child.Data, child.PayloadPos); break; } } return header; } public PostHeader Copy() { PostHeader copy = new PostHeader(); copy.Source = Source; copy.Target = Target; copy.ProjectID = ProjectID; copy.PostID = PostID; copy.ParentID = ParentID; copy.Time = Time; copy.Scope = Scope; copy.Archived = Archived; copy.Version = Version; copy.EditTime = EditTime; copy.FileKey = FileKey; copy.FileHash = FileHash; copy.FileSize = FileSize; copy.FileStart = FileStart; copy.SourceID = SourceID; copy.TargetID = TargetID; return copy; } } public class PostInfo : G2Packet { const byte Packet_Subject = 0x10; const byte Packet_Format = 0x20; const byte Packet_Unique = 0x30; const byte Packet_Quip = 0x40; public string Subject; public TextFormat Format; public string Quip; int Unique; // ensures file hash is unique public PostInfo() { } public PostInfo(string subject, TextFormat format, string quip, Random gen) { Subject = subject; Quip = quip; Unique = gen.Next(); Format = format; } public override byte[] Encode(G2Protocol protocol) { lock (protocol.WriteSection) { G2Frame info = protocol.WritePacket(null, BoardPacket.PostInfo, null); protocol.WritePacket(info, Packet_Subject, UTF8Encoding.UTF8.GetBytes(Subject)); protocol.WritePacket(info, Packet_Format, CompactNum.GetBytes((int)Format)); protocol.WritePacket(info, Packet_Quip, UTF8Encoding.UTF8.GetBytes(Quip)); protocol.WritePacket(info, Packet_Unique, BitConverter.GetBytes(Unique)); return protocol.WriteFinish(); } } public static PostInfo Decode(G2Header root) { PostInfo info = new PostInfo(); G2Header child = new G2Header(root.Data); while (G2Protocol.ReadNextChild(root, child) == G2ReadResult.PACKET_GOOD) { if (!G2Protocol.ReadPayload(child)) continue; switch (child.Name) { case Packet_Subject: info.Subject = UTF8Encoding.UTF8.GetString(child.Data, child.PayloadPos, child.PayloadSize); break; case Packet_Format: info.Format = (TextFormat)CompactNum.ToInt32(child.Data, child.PayloadPos, child.PayloadSize); break; case Packet_Quip: info.Quip = UTF8Encoding.UTF8.GetString(child.Data, child.PayloadPos, child.PayloadSize); break; case Packet_Unique: info.Unique = BitConverter.ToInt32(child.Data, child.PayloadPos); break; } } return info; } } public class PostFile : G2Packet { const byte Packet_Name = 0x10; const byte Packet_Size = 0x20; public string Name; public long Size; public PostFile() { } public PostFile(string name, long size) { Name = name; Size = size; } public override byte[] Encode(G2Protocol protocol) { lock (protocol.WriteSection) { G2Frame file = protocol.WritePacket(null, BoardPacket.PostFile, null); protocol.WritePacket(file, Packet_Name, UTF8Encoding.UTF8.GetBytes(Name)); protocol.WritePacket(file, Packet_Size, CompactNum.GetBytes(Size)); return protocol.WriteFinish(); } } public static PostFile Decode(G2Header root) { PostFile file = new PostFile(); G2Header child = new G2Header(root.Data); while (G2Protocol.ReadNextChild(root, child) == G2ReadResult.PACKET_GOOD) { if (!G2Protocol.ReadPayload(child)) continue; switch (child.Name) { case Packet_Name: file.Name = UTF8Encoding.UTF8.GetString(child.Data, child.PayloadPos, child.PayloadSize); break; case Packet_Size: file.Size = CompactNum.ToInt64(child.Data, child.PayloadPos, child.PayloadSize); break; } } return file; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Security.Cryptography.X509Certificates; using System.Threading; using Microsoft.Win32.SafeHandles; namespace Internal.Cryptography.Pal { internal sealed class CachedSystemStoreProvider : IStorePal { // These intervals are mostly arbitrary. // Prior to this refreshing cache the system collections were read just once per process, on the // assumption that system trust changes would happen before the process start (or would come // followed by a reboot for a kernel update, etc). // Customers requested something more often than "never" and 5 minutes seems like a reasonable // balance. // // Note that on Ubuntu the LastWrite test always fails, because the system default for SSL_CERT_DIR // is a symlink, so the LastWrite value is always just when the symlink was created (and Ubuntu does // not provide the single-file version at SSL_CERT_FILE, so the file update does not trigger) -- // meaning the "assume invalid" interval is Ubuntu's only refresh. private static readonly TimeSpan s_lastWriteRecheckInterval = TimeSpan.FromSeconds(5); private static readonly TimeSpan s_assumeInvalidInterval = TimeSpan.FromMinutes(5); private static readonly Stopwatch s_recheckStopwatch = new Stopwatch(); private static readonly DirectoryInfo s_rootStoreDirectoryInfo = SafeOpenRootDirectoryInfo(); private static readonly FileInfo s_rootStoreFileInfo = SafeOpenRootFileInfo(); // Use non-Value-Tuple so that it's an atomic update. private static Tuple<SafeX509StackHandle,SafeX509StackHandle> s_nativeCollections; private static DateTime s_directoryCertsLastWrite; private static DateTime s_fileCertsLastWrite; private readonly bool _isRoot; private CachedSystemStoreProvider(bool isRoot) { _isRoot = isRoot; } internal static CachedSystemStoreProvider MachineRoot { get; } = new CachedSystemStoreProvider(true); internal static CachedSystemStoreProvider MachineIntermediate { get; } = new CachedSystemStoreProvider(false); public void Dispose() { // No-op } public void CloneTo(X509Certificate2Collection collection) { Tuple<SafeX509StackHandle, SafeX509StackHandle> nativeColls = GetCollections(); SafeX509StackHandle nativeColl = _isRoot ? nativeColls.Item1 : nativeColls.Item2; int count = Interop.Crypto.GetX509StackFieldCount(nativeColl); for (int i = 0; i < count; i++) { X509Certificate2 clone = new X509Certificate2(Interop.Crypto.GetX509StackField(nativeColl, i)); collection.Add(clone); } } internal static void GetNativeCollections(out SafeX509StackHandle root, out SafeX509StackHandle intermediate) { Tuple<SafeX509StackHandle, SafeX509StackHandle> nativeColls = GetCollections(); root = nativeColls.Item1; intermediate = nativeColls.Item2; } public void Add(ICertificatePal cert) { // These stores can only be opened in ReadOnly mode. throw new InvalidOperationException(); } public void Remove(ICertificatePal cert) { // These stores can only be opened in ReadOnly mode. throw new InvalidOperationException(); } public SafeHandle SafeHandle => null; private static Tuple<SafeX509StackHandle, SafeX509StackHandle> GetCollections() { TimeSpan elapsed = s_recheckStopwatch.Elapsed; Tuple<SafeX509StackHandle, SafeX509StackHandle> ret = s_nativeCollections; if (ret == null || elapsed > s_lastWriteRecheckInterval) { lock (s_recheckStopwatch) { FileInfo fileInfo = s_rootStoreFileInfo; DirectoryInfo dirInfo = s_rootStoreDirectoryInfo; fileInfo?.Refresh(); dirInfo?.Refresh(); if (ret == null || elapsed > s_assumeInvalidInterval || (fileInfo != null && fileInfo.Exists && fileInfo.LastWriteTimeUtc != s_fileCertsLastWrite) || (dirInfo != null && dirInfo.Exists && dirInfo.LastWriteTimeUtc != s_directoryCertsLastWrite)) { ret = LoadMachineStores(dirInfo, fileInfo); } } } Debug.Assert(ret != null); return ret; } private static Tuple<SafeX509StackHandle, SafeX509StackHandle> LoadMachineStores( DirectoryInfo rootStorePath, FileInfo rootStoreFile) { Debug.Assert( Monitor.IsEntered(s_recheckStopwatch), "LoadMachineStores assumes a lock(s_recheckStopwatch)"); IEnumerable<FileInfo> trustedCertFiles; DateTime newFileTime = default; DateTime newDirTime = default; if (rootStorePath != null && rootStorePath.Exists) { trustedCertFiles = rootStorePath.EnumerateFiles(); newDirTime = rootStorePath.LastWriteTimeUtc; } else { trustedCertFiles = Array.Empty<FileInfo>(); } if (rootStoreFile != null && rootStoreFile.Exists) { trustedCertFiles = trustedCertFiles.Prepend(rootStoreFile); newFileTime = rootStoreFile.LastWriteTimeUtc; } SafeX509StackHandle rootStore = Interop.Crypto.NewX509Stack(); Interop.Crypto.CheckValidOpenSslHandle(rootStore); SafeX509StackHandle intermedStore = Interop.Crypto.NewX509Stack(); Interop.Crypto.CheckValidOpenSslHandle(intermedStore); HashSet<X509Certificate2> uniqueRootCerts = new HashSet<X509Certificate2>(); HashSet<X509Certificate2> uniqueIntermediateCerts = new HashSet<X509Certificate2>(); foreach (FileInfo file in trustedCertFiles) { using (SafeBioHandle fileBio = Interop.Crypto.BioNewFile(file.FullName, "rb")) { // The handle may be invalid, for example when we don't have read permission for the file. if (fileBio.IsInvalid) { Interop.Crypto.ErrClearError(); continue; } ICertificatePal pal; // Some distros ship with two variants of the same certificate. // One is the regular format ('BEGIN CERTIFICATE') and the other // contains additional AUX-data ('BEGIN TRUSTED CERTIFICATE'). // The additional data contains the appropriate usage (e.g. emailProtection, serverAuth, ...). // Because corefx doesn't validate for a specific usage, derived certificates are rejected. // For now, we skip the certificates with AUX data and use the regular certificates. while (OpenSslX509CertificateReader.TryReadX509PemNoAux(fileBio, out pal) || OpenSslX509CertificateReader.TryReadX509Der(fileBio, out pal)) { X509Certificate2 cert = new X509Certificate2(pal); // The HashSets are just used for uniqueness filters, they do not survive this method. if (StringComparer.Ordinal.Equals(cert.Subject, cert.Issuer)) { if (uniqueRootCerts.Add(cert)) { using (SafeX509Handle tmp = Interop.Crypto.X509UpRef(pal.Handle)) { if (!Interop.Crypto.PushX509StackField(rootStore, tmp)) { throw Interop.Crypto.CreateOpenSslCryptographicException(); } // The ownership has been transferred to the stack tmp.SetHandleAsInvalid(); } continue; } } else { if (uniqueIntermediateCerts.Add(cert)) { using (SafeX509Handle tmp = Interop.Crypto.X509UpRef(pal.Handle)) { if (!Interop.Crypto.PushX509StackField(intermedStore, tmp)) { throw Interop.Crypto.CreateOpenSslCryptographicException(); } // The ownership has been transferred to the stack tmp.SetHandleAsInvalid(); } continue; } } // There's a good chance we'll encounter duplicates on systems that have both one-cert-per-file // and one-big-file trusted certificate stores. Anything that wasn't unique will end up here. cert.Dispose(); } } } foreach (X509Certificate2 cert in uniqueRootCerts) { cert.Dispose(); } foreach (X509Certificate2 cert in uniqueIntermediateCerts) { cert.Dispose(); } Tuple<SafeX509StackHandle, SafeX509StackHandle> newCollections = Tuple.Create(rootStore, intermedStore); Debug.Assert( Monitor.IsEntered(s_recheckStopwatch), "LoadMachineStores assumes a lock(s_recheckStopwatch)"); // The existing collections are not Disposed here, intentionally. // They could be in the gap between when they are returned from this method and not yet used // in a P/Invoke, which would result in exceptions being thrown. // In order to maintain "finalization-free" the GetNativeCollections method would need to // DangerousAddRef, and the callers would need to DangerousRelease, adding more interlocked operations // on every call. Volatile.Write(ref s_nativeCollections, newCollections); s_directoryCertsLastWrite = newDirTime; s_fileCertsLastWrite = newFileTime; s_recheckStopwatch.Restart(); return newCollections; } private static FileInfo SafeOpenRootFileInfo() { string rootFile = Interop.Crypto.GetX509RootStoreFile(); if (!string.IsNullOrEmpty(rootFile)) { try { return new FileInfo(rootFile); } catch (ArgumentException) { // If SSL_CERT_FILE is set to the empty string, or anything else which gives // "The path is not of a legal form", then the GetX509RootStoreFile value is ignored. } } return null; } private static DirectoryInfo SafeOpenRootDirectoryInfo() { string rootDirectory = Interop.Crypto.GetX509RootStorePath(); if (!string.IsNullOrEmpty(rootDirectory)) { try { return new DirectoryInfo(rootDirectory); } catch (ArgumentException) { // If SSL_CERT_DIR is set to the empty string, or anything else which gives // "The path is not of a legal form", then the GetX509RootStoreFile value is ignored. } } return null; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Azuria.Api.Builder; using Azuria.ErrorHandling; using Azuria.Middleware; using Azuria.Requests; using Azuria.Requests.Builder; using NUnit.Framework; namespace Azuria.Test.Middleware { public class PipelineTest { private readonly IApiRequestBuilder _apiRequestBuilder; public PipelineTest() { IProxerClient client = ProxerClient.Create(new char[32]); this._apiRequestBuilder = client.CreateRequest(); } [Test] public void Constructor_SetsFieldsTest() { var middleware = new IMiddleware[] {new ErrorMiddleware()}; var pipeline = new Pipeline(middleware); Assert.AreEqual(middleware, pipeline.Middlewares); } [Test] public async Task BuildPipeline_BuildsEmptyPipelineTest() { var pipeline = new Pipeline(new IMiddleware[0]); MiddlewareAction action = pipeline.BuildPipeline(); Assert.NotNull(action); IRequestBuilder request = this._apiRequestBuilder.FromUrl(new Uri("https://proxer.me/api/v1")); IProxerResult result = await action.Invoke(request); Assert.NotNull(result); Assert.True(result.Success); } [Test] public async Task BuildPipeline_BuildsPipeline() { var pipeline = new Pipeline(new IMiddleware[] {new TestMiddleware(null)}); MiddlewareAction action = pipeline.BuildPipeline(); Assert.NotNull(action); IRequestBuilder request = this._apiRequestBuilder.FromUrl(new Uri("https://proxer.me/api/v1")); IProxerResult result = await action.Invoke(request); Assert.NotNull(result); Assert.True(result.Success); Assert.IsInstanceOf<ProxerApiResponse>(result); Assert.AreEqual("TestMiddleware", (result as ProxerApiResponse)?.Message); } [Test] public async Task BuildPipelineWithResult_BuildsEmptyPipelineTest() { var pipeline = new Pipeline(new IMiddleware[0]); MiddlewareAction<object> action = pipeline.BuildPipelineWithResult<object>(); Assert.NotNull(action); IRequestBuilderWithResult<object> request = this._apiRequestBuilder.FromUrl(new Uri("https://proxer.me/api/v1")).WithResult<object>(); IProxerResult<object> result = await action.Invoke(request); Assert.NotNull(result); Assert.True(result.Success); } [Test] public async Task BuildPipelineWithResult_BuildsPipeline() { var pipeline = new Pipeline(new IMiddleware[] {new TestMiddleware("TestPipeline")}); MiddlewareAction<string> action = pipeline.BuildPipelineWithResult<string>(); Assert.NotNull(action); IRequestBuilderWithResult<string> request = this._apiRequestBuilder.FromUrl(new Uri("https://proxer.me/api/v1")).WithResult<string>(); IProxerResult<string> result = await action.Invoke(request); Assert.NotNull(result); Assert.True(result.Success); Assert.IsInstanceOf<ProxerApiResponse<string>>(result); Assert.AreEqual("TestMiddleware", (result as ProxerApiResponse<string>)?.Message); Assert.AreEqual("TestPipeline", (result as ProxerApiResponse<string>)?.Result); } [Test] public void InsertMiddlewareAfter_DoesNotInsertIfEmpty() { var pipeline = new Pipeline(new IMiddleware[0]); bool inserted = pipeline.InsertMiddlewareAfter(typeof(HttpJsonRequestMiddleware), new TestMiddleware(null)); Assert.False(inserted); Assert.AreEqual(0, pipeline.Middlewares.Count()); } [Test] public void InsertMiddlewareAfter_DoesNotInsertIfNotFound() { var pipeline = new Pipeline(new IMiddleware[] {new ErrorMiddleware()}); bool inserted = pipeline.InsertMiddlewareAfter(typeof(HttpJsonRequestMiddleware), new TestMiddleware(null)); Assert.False(inserted); Assert.AreEqual(1, pipeline.Middlewares.Count()); Assert.IsInstanceOf<ErrorMiddleware>(pipeline.Middlewares.FirstOrDefault()); } [Test] public void InsertMiddlewareAfter_InsertsAfterEachInstancesOfType() { var pipeline = new Pipeline(new IMiddleware[] {new ErrorMiddleware(), new ErrorMiddleware()}); bool inserted = pipeline.InsertMiddlewareAfter(typeof(ErrorMiddleware), new TestMiddleware(null)); Assert.True(inserted); IMiddleware[] middlewares = pipeline.Middlewares.ToArray(); Assert.AreEqual(4, middlewares.Length); Assert.IsInstanceOf<ErrorMiddleware>(middlewares[0]); Assert.IsInstanceOf<TestMiddleware>(middlewares[1]); Assert.IsInstanceOf<ErrorMiddleware>(middlewares[2]); Assert.IsInstanceOf<TestMiddleware>(middlewares[3]); } [Test] public void InsertMiddlewareAfter_InsertsBeforeInstancesOfOtherTypes() { var pipeline = new Pipeline(new IMiddleware[] {new ErrorMiddleware(), new StaticHeaderMiddleware(new Dictionary<string, string>())}); bool inserted = pipeline.InsertMiddlewareAfter(typeof(ErrorMiddleware), new TestMiddleware(null)); Assert.True(inserted); IMiddleware[] middlewares = pipeline.Middlewares.ToArray(); Assert.AreEqual(3, middlewares.Length); Assert.IsInstanceOf<ErrorMiddleware>(middlewares[0]); Assert.IsInstanceOf<TestMiddleware>(middlewares[1]); Assert.IsInstanceOf<StaticHeaderMiddleware>(middlewares[2]); } [Test] public void InsertMiddlewareBefore_DoesNotInsertIfEmpty() { var pipeline = new Pipeline(new IMiddleware[0]); bool inserted = pipeline.InsertMiddlewareBefore(typeof(HttpJsonRequestMiddleware), new TestMiddleware(null)); Assert.False(inserted); Assert.AreEqual(0, pipeline.Middlewares.Count()); } [Test] public void InsertMiddlewareBefore_DoesNotInsertIfNotFound() { var pipeline = new Pipeline(new IMiddleware[] {new ErrorMiddleware()}); bool inserted = pipeline.InsertMiddlewareBefore(typeof(HttpJsonRequestMiddleware), new TestMiddleware(null)); Assert.False(inserted); Assert.AreEqual(1, pipeline.Middlewares.Count()); Assert.IsInstanceOf<ErrorMiddleware>(pipeline.Middlewares.FirstOrDefault()); } [Test] public void InsertMiddlewareBefore_InsertsBeforeEachInstancesOfType() { var pipeline = new Pipeline(new IMiddleware[] {new ErrorMiddleware(), new ErrorMiddleware()}); bool inserted = pipeline.InsertMiddlewareBefore(typeof(ErrorMiddleware), new TestMiddleware(null)); Assert.True(inserted); IMiddleware[] middlewares = pipeline.Middlewares.ToArray(); Assert.AreEqual(4, middlewares.Length); Assert.IsInstanceOf<TestMiddleware>(middlewares[0]); Assert.IsInstanceOf<ErrorMiddleware>(middlewares[1]); Assert.IsInstanceOf<TestMiddleware>(middlewares[2]); Assert.IsInstanceOf<ErrorMiddleware>(middlewares[3]); } [Test] public void InsertMiddlewareBefore_InsertsAfterInstancesOfOtherTypes() { var pipeline = new Pipeline(new IMiddleware[] {new StaticHeaderMiddleware(new Dictionary<string, string>()), new ErrorMiddleware()}); bool inserted = pipeline.InsertMiddlewareBefore(typeof(ErrorMiddleware), new TestMiddleware(null)); Assert.True(inserted); IMiddleware[] middlewares = pipeline.Middlewares.ToArray(); Assert.AreEqual(3, middlewares.Length); Assert.IsInstanceOf<StaticHeaderMiddleware>(middlewares[0]); Assert.IsInstanceOf<TestMiddleware>(middlewares[1]); Assert.IsInstanceOf<ErrorMiddleware>(middlewares[2]); } [Test] public void MiddlewaresProperty_OverridesMiddlewaresInSet() { var pipeline = new Pipeline(new IMiddleware[] {new ErrorMiddleware(), new StaticHeaderMiddleware(new Dictionary<string, string>())}); pipeline.Middlewares = new IMiddleware[] {new TestMiddleware(null)}; IMiddleware[] middlewares = pipeline.Middlewares.ToArray(); Assert.NotNull(middlewares); Assert.AreEqual(1, middlewares.Length); Assert.IsInstanceOf<TestMiddleware>(middlewares[0]); } [Test] public void MiddlewaresProperty_ReturnsMiddlewares() { var pipeline = new Pipeline(new IMiddleware[] {new ErrorMiddleware(), new StaticHeaderMiddleware(new Dictionary<string, string>())}); IMiddleware[] middlewares = pipeline.Middlewares.ToArray(); Assert.NotNull(middlewares); Assert.AreEqual(2, middlewares.Length); Assert.IsInstanceOf<ErrorMiddleware>(middlewares[0]); Assert.IsInstanceOf<StaticHeaderMiddleware>(middlewares[1]); } [Test] public void RemoveMiddleware_DoesNotRemoveIfEmpty() { var pipeline = new Pipeline(new IMiddleware[0]); bool removed = pipeline.RemoveMiddleware(typeof(HttpJsonRequestMiddleware)); Assert.False(removed); Assert.AreEqual(0, pipeline.Middlewares.Count()); } [Test] public void RemoveMiddleware_DoesNotRemoveIfNotFound() { var pipeline = new Pipeline(new IMiddleware[] {new ErrorMiddleware()}); bool removed = pipeline.RemoveMiddleware(typeof(StaticHeaderMiddleware)); Assert.False(removed); Assert.AreEqual(1, pipeline.Middlewares.Count()); Assert.IsInstanceOf<ErrorMiddleware>(pipeline.Middlewares.FirstOrDefault()); } [Test] public void RemoveMiddleware_RemovesAllInstancesOfType() { var pipeline = new Pipeline(new IMiddleware[] { new ErrorMiddleware(), new StaticHeaderMiddleware(new Dictionary<string, string>()), new ErrorMiddleware() }); bool removed = pipeline.RemoveMiddleware(typeof(ErrorMiddleware)); Assert.True(removed); Assert.AreEqual(1, pipeline.Middlewares.Count()); Assert.IsInstanceOf<StaticHeaderMiddleware>(pipeline.Middlewares.FirstOrDefault()); } [Test] public void ReplaceMiddleware_DoesNotReplaceIfEmpty() { var pipeline = new Pipeline(new IMiddleware[0]); bool replaced = pipeline.ReplaceMiddleware(typeof(HttpJsonRequestMiddleware), new TestMiddleware(null)); Assert.False(replaced); Assert.AreEqual(0, pipeline.Middlewares.Count()); } [Test] public void ReplaceMiddleware_DoesNotReplaceIfNotFound() { var pipeline = new Pipeline(new IMiddleware[] {new ErrorMiddleware()}); bool replaced = pipeline.ReplaceMiddleware(typeof(StaticHeaderMiddleware), new TestMiddleware(null)); Assert.False(replaced); Assert.AreEqual(1, pipeline.Middlewares.Count()); Assert.IsInstanceOf<ErrorMiddleware>(pipeline.Middlewares.FirstOrDefault()); } [Test] public void ReplaceMiddleware_ReplacesAllInstancesOfType() { var pipeline = new Pipeline(new IMiddleware[] { new ErrorMiddleware(), new StaticHeaderMiddleware(new Dictionary<string, string>()), new ErrorMiddleware() }); bool replaced = pipeline.ReplaceMiddleware(typeof(ErrorMiddleware), new TestMiddleware(null)); Assert.True(replaced); IMiddleware[] middlewares = pipeline.Middlewares.ToArray(); Assert.AreEqual(3, middlewares.Length); Assert.IsInstanceOf<TestMiddleware>(middlewares[0]); Assert.IsInstanceOf<StaticHeaderMiddleware>(middlewares[1]); Assert.IsInstanceOf<TestMiddleware>(middlewares[2]); } } }
// 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.Concurrent; using System.Collections.Generic; using System.Threading; using Xunit; namespace System.Linq.Parallel.Tests { public class ExchangeTests { private static readonly ParallelMergeOptions[] Options = new[] { ParallelMergeOptions.AutoBuffered, ParallelMergeOptions.Default, ParallelMergeOptions.FullyBuffered, ParallelMergeOptions.NotBuffered }; /// <summary> /// Get a set of ranges, running for each count in `counts`, with 1, 2, and 4 counts for partitions. /// </summary> /// <param name="counts">The sizes of ranges to return.</param> /// <returns>Entries for test data. /// The first element is the Labeled{ParallelQuery{int}} range, /// the second element is the count, and the third is the number of partitions or degrees of parallelism to use.</returns> public static IEnumerable<object[]> PartitioningData(int[] counts) { foreach (object[] results in Sources.Ranges(counts.Cast<int>(), x => new[] { 1, 2, 4 })) { yield return results; } } // For each source, run with each buffering option. /// <summary> /// Get a set of ranges, and running for each count in `counts`, with each possible ParallelMergeOption /// </summary> /// <param name="counts">The sizes of ranges to return.</param> /// <returns>Entries for test data. /// The first element is the Labeled{ParallelQuery{int}} range, /// the second element is the count, and the third is the ParallelMergeOption to use.</returns> public static IEnumerable<object[]> MergeData(int[] counts) { foreach (object[] results in Sources.Ranges(counts.Cast<int>(), x => Options)) { yield return results; } } /// <summary> ///For each count, return an Enumerable source that fails (throws an exception) on that count, with each buffering option. /// </summary> /// <param name="counts">The sizes of ranges to return.</param> /// <returns>Entries for test data. /// The first element is the Labeled{ParallelQuery{int}} range, /// the second element is the count, and the third is the ParallelMergeOption to use.</returns> public static IEnumerable<object[]> ThrowOnCount_AllMergeOptions_MemberData(int[] counts) { foreach (int count in counts.Cast<int>()) { var labeled = Labeled.Label("ThrowOnEnumeration " + count, Enumerables<int>.ThrowOnEnumeration(count).AsParallel().AsOrdered()); foreach (ParallelMergeOptions option in Options) { yield return new object[] { labeled, count, option }; } } } /// <summary> /// Return merge option combinations, for testing multiple calls to WithMergeOptions /// </summary> /// <returns>Entries for test data.</returns> public static IEnumerable<object[]> AllMergeOptions_Multiple() { foreach (ParallelMergeOptions first in Options) { foreach (ParallelMergeOptions second in Options) { yield return new object[] { first, second }; } } } // The following tests attempt to test internal behavior, // but there doesn't appear to be a way to reliably (or automatically) observe it. // The basic tests are covered elsewhere, although without WithDegreeOfParallelism // or WithMergeOptions [Theory] [MemberData(nameof(PartitioningData), (object)(new int[] { 0, 1, 2, 16, 1024 }))] public static void Partitioning_Default(Labeled<ParallelQuery<int>> labeled, int count, int partitions) { int seen = 0; foreach (int i in labeled.Item.WithDegreeOfParallelism(partitions).Select(i => i)) { Assert.Equal(seen++, i); } } [Theory] [OuterLoop] [MemberData(nameof(PartitioningData), (object)(new int[] { 1024 * 4, 1024 * 1024 }))] public static void Partitioning_Default_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int partitions) { Partitioning_Default(labeled, count, partitions); } [Theory] [MemberData(nameof(PartitioningData), (object)(new int[] { 0, 1, 2, 16, 1024 }))] public static void Partitioning_Striped(Labeled<ParallelQuery<int>> labeled, int count, int partitions) { int seen = 0; foreach (int i in labeled.Item.WithDegreeOfParallelism(partitions).Take(count).Select(i => i)) { Assert.Equal(seen++, i); } } [Theory] [OuterLoop] [MemberData(nameof(PartitioningData), (object)(new int[] { 1024 * 4, 1024 * 1024 }))] public static void Partitioning_Striped_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int partitions) { Partitioning_Striped(labeled, count, partitions); } [Theory] [MemberData(nameof(MergeData), (object)(new int[] { 0, 1, 2, 16, 1024 }))] public static void Merge_Ordered(Labeled<ParallelQuery<int>> labeled, int count, ParallelMergeOptions options) { int seen = 0; foreach (int i in labeled.Item.WithMergeOptions(options).Select(i => i)) { Assert.Equal(seen++, i); } } [Theory] [OuterLoop] [MemberData(nameof(MergeData), (object)(new int[] { 1024 * 4, 1024 * 1024 }))] public static void Merge_Ordered_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, ParallelMergeOptions options) { Merge_Ordered(labeled, count, options); } [Theory] [MemberData(nameof(ThrowOnCount_AllMergeOptions_MemberData), (object)(new int[] { 4, 8 }))] // FailingMergeData has enumerables that throw errors when attempting to perform the nth enumeration. // This test checks whether the query runs in a pipelined or buffered fashion. public static void Merge_Ordered_Pipelining(Labeled<ParallelQuery<int>> labeled, int count, ParallelMergeOptions options) { Assert.Equal(0, labeled.Item.WithDegreeOfParallelism(count - 1).WithMergeOptions(options).First()); } [Theory] [MemberData(nameof(MergeData), (object)(new int[] { 4, 8 }))] // This test checks whether the query runs in a pipelined or buffered fashion. public static void Merge_Ordered_Pipelining_Select(Labeled<ParallelQuery<int>> labeled, int count, ParallelMergeOptions options) { int countdown = count; Func<int, int> down = i => { if (Interlocked.Decrement(ref countdown) == 0) throw new DeliberateTestException(); return i; }; Assert.Equal(0, labeled.Item.WithDegreeOfParallelism(count - 1).WithMergeOptions(options).Select(down).First()); } [Theory] [MemberData(nameof(Sources.Ranges), (object)(new int[] { 2 }), MemberType = typeof(UnorderedSources))] public static void Merge_ArgumentException(Labeled<ParallelQuery<int>> labeled, int count) { ParallelQuery<int> query = labeled.Item; Assert.Throws<ArgumentException>(() => query.WithMergeOptions((ParallelMergeOptions)4)); } [Theory] [MemberData(nameof(AllMergeOptions_Multiple))] public static void WithMergeOptions_Multiple(ParallelMergeOptions first, ParallelMergeOptions second) { Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Range(0, 1).WithMergeOptions(first).WithMergeOptions(second)); } [Fact] public static void Merge_ArgumentNullException() { Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<int>)null).WithMergeOptions(ParallelMergeOptions.AutoBuffered)); } // The plinq chunk partitioner takes an IEnumerator over the source, and disposes the // enumerator when it is finished. If an exception occurs, the calling enumerator disposes // the source enumerator... but then other worker threads may generate ODEs. // This test verifies any such ODEs are not reflected in the output exception. [Theory] [MemberData(nameof(UnorderedSources.BinaryRanges), new int[] { 16 }, new int[] { 16 }, MemberType = typeof(UnorderedSources))] public static void PlinqChunkPartitioner_DontEnumerateAfterException(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { ParallelQuery<int> query = left.Item.WithExecutionMode(ParallelExecutionMode.ForceParallelism) .Select(x => { if (x == 4) throw new DeliberateTestException(); return x; }) .Zip(right.Item, (a, b) => a + b) .AsParallel().WithExecutionMode(ParallelExecutionMode.ForceParallelism); AggregateException ae = Assert.Throws<AggregateException>(() => query.ToArray()); Assert.Single(ae.InnerExceptions); Assert.All(ae.InnerExceptions, e => Assert.IsType<DeliberateTestException>(e)); } // The stand-alone chunk partitioner takes an IEnumerator over the source, and // disposes the enumerator when it is finished. If an exception occurs, the calling // enumerator disposes the source enumerator... but then other worker threads may generate ODEs. // This test verifies any such ODEs are not reflected in the output exception. [Theory] [MemberData(nameof(UnorderedSources.BinaryRanges), new int[] { 16 }, new int[] { 16 }, MemberType = typeof(UnorderedSources))] public static void ManualChunkPartitioner_DontEnumerateAfterException( Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { ParallelQuery<int> query = Partitioner.Create(left.Item.WithExecutionMode(ParallelExecutionMode.ForceParallelism) .Select(x => { if (x == 4) throw new DeliberateTestException(); return x; }) .Zip(right.Item, (a, b) => a + b)) .AsParallel(); AggregateException ae = Assert.Throws<AggregateException>(() => query.ToArray()); Assert.Single(ae.InnerExceptions); Assert.All(ae.InnerExceptions, e => Assert.IsType<DeliberateTestException>(e)); } } }
// Copyright (c) Charlie Poole, Rob Prouse and Contributors. MIT License - see LICENSE.txt #nullable enable using System; using System.ComponentModel; using NUnit.Framework.Constraints; using NUnit.Framework.Internal; namespace NUnit.Framework { /// <summary> /// Provides static methods to express conditions /// that must be met for the test to succeed. If /// any test fails, a warning is issued. /// </summary> public class Warn { #region Equals and ReferenceEquals /// <summary> /// DO NOT USE! /// The Equals method throws an InvalidOperationException. This is done /// to make sure there is no mistake by calling this function. /// </summary> /// <param name="a">The left object.</param> /// <param name="b">The right object.</param> /// <returns>Not applicable</returns> [EditorBrowsable(EditorBrowsableState.Never)] public static new bool Equals(object a, object b) { throw new InvalidOperationException("Warn.Equals should not be used."); } /// <summary> /// DO NOT USE! /// The ReferenceEquals method throws an InvalidOperationException. This is done /// to make sure there is no mistake by calling this function. /// </summary> /// <param name="a">The left object.</param> /// <param name="b">The right object.</param> [EditorBrowsable(EditorBrowsableState.Never)] public static new void ReferenceEquals(object a, object b) { throw new InvalidOperationException("Warn.ReferenceEquals should not be used."); } #endregion #region Warn.Unless #region ActualValueDelegate /// <summary> /// Apply a constraint to an actual value, succeeding if the constraint /// is satisfied and issuing a warning on failure. /// </summary> /// <typeparam name="TActual">The Type being compared.</typeparam> /// <param name="del">An ActualValueDelegate returning the value to be tested</param> /// <param name="expr">A Constraint expression to be applied</param> public static void Unless<TActual>(ActualValueDelegate<TActual> del, IResolveConstraint expr) { Warn.Unless(del, expr.Resolve(), null, null); } /// <summary> /// Apply a constraint to an actual value, succeeding if the constraint /// is satisfied and issuing a warning on failure. /// </summary> /// <typeparam name="TActual">The Type being compared.</typeparam> /// <param name="del">An ActualValueDelegate returning the value to be tested</param> /// <param name="expr">A Constraint expression to be applied</param> /// <param name="message">The message that will be displayed on failure</param> /// <param name="args">Arguments to be used in formatting the message</param> public static void Unless<TActual>(ActualValueDelegate<TActual> del, IResolveConstraint expr, string? message, params object?[]? args) { var constraint = expr.Resolve(); IncrementAssertCount(); var result = constraint.ApplyTo(del); if (!result.IsSuccess) IssueWarning(result, message, args); } private static void IssueWarning(ConstraintResult result, string? message, object?[]? args) { MessageWriter writer = new TextMessageWriter(message, args); result.WriteMessageTo(writer); Assert.Warn(writer.ToString()); } /// <summary> /// Apply a constraint to an actual value, succeeding if the constraint /// is satisfied and issuing a warning on failure. /// </summary> /// <typeparam name="TActual">The Type being compared.</typeparam> /// <param name="del">An ActualValueDelegate returning the value to be tested</param> /// <param name="expr">A Constraint expression to be applied</param> /// <param name="getExceptionMessage">A function to build the message included with the Exception</param> public static void Unless<TActual>( ActualValueDelegate<TActual> del, IResolveConstraint expr, Func<string?> getExceptionMessage) { var constraint = expr.Resolve(); IncrementAssertCount(); var result = constraint.ApplyTo(del); if (!result.IsSuccess) IssueWarning(result, getExceptionMessage(), null); } #endregion #region Boolean /// <summary> /// Asserts that a condition is true. If the condition is false, a warning is issued. /// </summary> /// <param name="condition">The evaluated condition</param> /// <param name="message">The message to display if the condition is false</param> /// <param name="args">Arguments to be used in formatting the message</param> public static void Unless(bool condition, string? message, params object?[]? args) { Warn.Unless(condition, Is.True, message, args); } /// <summary> /// Asserts that a condition is true. If the condition is false, a warning is issued. /// </summary> /// <param name="condition">The evaluated condition</param> public static void Unless(bool condition) { Warn.Unless(condition, Is.True, null, null); } /// <summary> /// Asserts that a condition is true. If the condition is false, a warning is issued. /// </summary> /// <param name="condition">The evaluated condition</param> /// <param name="getExceptionMessage">A function to build the message included with the Exception</param> public static void Unless(bool condition, Func<string?> getExceptionMessage) { Warn.Unless(condition, Is.True, getExceptionMessage); } #endregion #region Lambda returning Boolean /// <summary> /// Asserts that a condition is true. If the condition is false, a warning is issued. /// </summary> /// <param name="condition">A lambda that returns a Boolean</param> /// <param name="message">The message to display if the condition is false</param> /// <param name="args">Arguments to be used in formatting the message</param> public static void Unless(Func<bool> condition, string? message, params object?[]? args) { Warn.Unless(condition.Invoke(), Is.True, message, args); } /// <summary> /// Asserts that a condition is true. If the condition is false, a warning is issued. /// </summary> /// <param name="condition">A lambda that returns a Boolean</param> public static void Unless(Func<bool> condition) { Warn.Unless(condition.Invoke(), Is.True, null, null); } /// <summary> /// Asserts that a condition is true. If the condition is false, a warning is issued. /// </summary> /// <param name="condition">A lambda that returns a Boolean</param> /// <param name="getExceptionMessage">A function to build the message included with the Exception</param> public static void Unless(Func<bool> condition, Func<string?> getExceptionMessage) { Warn.Unless(condition.Invoke(), Is.True, getExceptionMessage); } #endregion #region TestDelegate /// <summary> /// Asserts that the code represented by a delegate throws an exception /// that satisfies the constraint provided. /// </summary> /// <param name="code">A TestDelegate to be executed</param> /// <param name="constraint">A Constraint expression to be applied</param> public static void Unless(TestDelegate code, IResolveConstraint constraint) { Warn.Unless((object)code, constraint); } #endregion #region Generic /// <summary> /// Apply a constraint to an actual value, succeeding if the constraint /// is satisfied and issuing a warning on failure. /// </summary> /// <typeparam name="TActual">The Type being compared.</typeparam> /// <param name="actual">The actual value to test</param> /// <param name="expression">A Constraint expression to be applied</param> public static void Unless<TActual>(TActual actual, IResolveConstraint expression) { Warn.Unless(actual, expression, null, null); } /// <summary> /// Apply a constraint to an actual value, succeeding if the constraint /// is satisfied and issuing a warning on failure. /// </summary> /// <typeparam name="TActual">The Type being compared.</typeparam> /// <param name="actual">The actual value to test</param> /// <param name="expression">A Constraint expression to be applied</param> /// <param name="message">The message that will be displayed on failure</param> /// <param name="args">Arguments to be used in formatting the message</param> public static void Unless<TActual>(TActual actual, IResolveConstraint expression, string? message, params object?[]? args) { var constraint = expression.Resolve(); IncrementAssertCount(); var result = constraint.ApplyTo(actual); if (!result.IsSuccess) IssueWarning(result, message, args); } /// <summary> /// Apply a constraint to an actual value, succeeding if the constraint /// is satisfied and issuing a warning on failure. /// </summary> /// <typeparam name="TActual">The Type being compared.</typeparam> /// <param name="actual">The actual value to test</param> /// <param name="expression">A Constraint expression to be applied</param> /// <param name="getExceptionMessage">A function to build the message included with the Exception</param> public static void Unless<TActual>( TActual actual, IResolveConstraint expression, Func<string?> getExceptionMessage) { var constraint = expression.Resolve(); IncrementAssertCount(); var result = constraint.ApplyTo(actual); if (!result.IsSuccess) IssueWarning(result, getExceptionMessage(), null); } #endregion #endregion #region Warn.If #region ActualValueDelegate /// <summary> /// Apply a constraint to an actual value, succeeding if the constraint /// fails and issuing a warning on success. /// </summary> /// <typeparam name="TActual">The Type being compared.</typeparam> /// <param name="del">An ActualValueDelegate returning the value to be tested</param> /// <param name="expr">A Constraint expression to be applied</param> public static void If<TActual>(ActualValueDelegate<TActual> del, IResolveConstraint expr) { Warn.If(del, expr.Resolve(), null, null); } /// <summary> /// Apply a constraint to an actual value, succeeding if the constraint /// fails and issuing a warning on success. /// </summary> /// <typeparam name="TActual">The Type being compared.</typeparam> /// <param name="del">An ActualValueDelegate returning the value to be tested</param> /// <param name="expr">A Constraint expression to be applied</param> /// <param name="message">The message that will be displayed on failure</param> /// <param name="args">Arguments to be used in formatting the message</param> public static void If<TActual>(ActualValueDelegate<TActual> del, IResolveConstraint expr, string? message, params object?[]? args) { var constraint = new NotConstraint(expr.Resolve()); IncrementAssertCount(); var result = constraint.ApplyTo(del); if (!result.IsSuccess) IssueWarning(result, message, args); } //private static void IssueWarning(ConstraintResult result, string? message, object?[]? args) //{ // MessageWriter writer = new TextMessageWriter(message, args); // result.WriteMessageTo(writer); // Assert.Warn(writer.ToString()); //} /// <summary> /// Apply a constraint to an actual value, succeeding if the constraint /// fails and issuing a warning on failure. /// </summary> /// <typeparam name="TActual">The Type being compared.</typeparam> /// <param name="del">An ActualValueDelegate returning the value to be tested</param> /// <param name="expr">A Constraint expression to be applied</param> /// <param name="getExceptionMessage">A function to build the message included with the Exception</param> public static void If<TActual>( ActualValueDelegate<TActual> del, IResolveConstraint expr, Func<string?> getExceptionMessage) { var constraint = new NotConstraint(expr.Resolve()); IncrementAssertCount(); var result = constraint.ApplyTo(del); if (!result.IsSuccess) IssueWarning(result, getExceptionMessage(), null); } #endregion #region Boolean /// <summary> /// Asserts that a condition is false. If the condition is true, a warning is issued. /// </summary> /// <param name="condition">The evaluated condition</param> /// <param name="message">The message to display if the condition is false</param> /// <param name="args">Arguments to be used in formatting the message</param> public static void If(bool condition, string? message, params object?[]? args) { Warn.If(condition, Is.True, message, args); } /// <summary> /// Asserts that a condition is false. If the condition is true, a warning is issued. /// </summary> /// <param name="condition">The evaluated condition</param> public static void If(bool condition) { Warn.If(condition, Is.True, null, null); } /// <summary> /// Asserts that a condition is false. If the condition is true, a warning is issued. /// </summary> /// <param name="condition">The evaluated condition</param> /// <param name="getExceptionMessage">A function to build the message included with the Exception</param> public static void If(bool condition, Func<string?> getExceptionMessage) { Warn.If(condition, Is.True, getExceptionMessage); } #endregion #region Lambda returning Boolean /// <summary> /// Asserts that a condition is false. If the condition is true a warning is issued. /// </summary> /// <param name="condition">A lambda that returns a Boolean</param> /// <param name="message">The message to display if the condition is true</param> /// <param name="args">Arguments to be used in formatting the message</param> public static void If(Func<bool> condition, string? message, params object?[]? args) { Warn.If(condition.Invoke(), Is.True, message, args); } /// <summary> /// Asserts that a condition is false. If the condition is true a warning is issued. /// </summary> /// <param name="condition">A lambda that returns a Boolean</param> public static void If(Func<bool> condition) { Warn.If(condition.Invoke(), Is.True, null, null); } /// <summary> /// Asserts that a condition is false. If the condition is true a warning is issued. /// </summary> /// <param name="condition">A lambda that returns a Boolean</param> /// <param name="getExceptionMessage">A function to build the message included with the Exception</param> public static void If(Func<bool> condition, Func<string?> getExceptionMessage) { Warn.If(condition.Invoke(), Is.True, getExceptionMessage); } #endregion #region Generic /// <summary> /// Apply a constraint to an actual value, succeeding if the constraint /// fails and issuing a warning if it succeeds. /// </summary> /// <typeparam name="TActual">The Type being compared.</typeparam> /// <param name="actual">The actual value to test</param> /// <param name="expression">A Constraint expression to be applied</param> public static void If<TActual>(TActual actual, IResolveConstraint expression) { Warn.If(actual, expression, null, null); } /// <summary> /// Apply a constraint to an actual value, succeeding if the constraint /// fails and issuing a warning if it succeeds. /// </summary> /// <typeparam name="TActual">The Type being compared.</typeparam> /// <param name="actual">The actual value to test</param> /// <param name="expression">A Constraint expression to be applied</param> /// <param name="message">The message that will be displayed on failure</param> /// <param name="args">Arguments to be used in formatting the message</param> public static void If<TActual>(TActual actual, IResolveConstraint expression, string? message, params object?[]? args) { var constraint = new NotConstraint(expression.Resolve()); IncrementAssertCount(); var result = constraint.ApplyTo(actual); if (!result.IsSuccess) IssueWarning(result, message, args); } /// <summary> /// Apply a constraint to an actual value, succeeding if the constraint /// is satisfied and issuing a warning on failure. /// </summary> /// <typeparam name="TActual">The Type being compared.</typeparam> /// <param name="actual">The actual value to test</param> /// <param name="expression">A Constraint expression to be applied</param> /// <param name="getExceptionMessage">A function to build the message included with the Exception</param> public static void If<TActual>( TActual actual, IResolveConstraint expression, Func<string?> getExceptionMessage) { var constraint = new NotConstraint(expression.Resolve()); IncrementAssertCount(); var result = constraint.ApplyTo(actual); if (!result.IsSuccess) IssueWarning(result, getExceptionMessage(), null); } #endregion #endregion #region Helper Methods private static void IncrementAssertCount() { TestExecutionContext.CurrentContext.IncrementAssertCount(); } #endregion } }
using System; namespace Godot { public struct Color : IEquatable<Color> { public float r; public float g; public float b; public float a; public int r8 { get { return (int)(r * 255.0f); } } public int g8 { get { return (int)(g * 255.0f); } } public int b8 { get { return (int)(b * 255.0f); } } public int a8 { get { return (int)(a * 255.0f); } } public float h { get { float max = Math.Max(r, Math.Max(g, b)); float min = Math.Min(r, Math.Min(g, b)); float delta = max - min; if (delta == 0) return 0; float h; if (r == max) h = (g - b) / delta; // Between yellow & magenta else if (g == max) h = 2 + (b - r) / delta; // Between cyan & yellow else h = 4 + (r - g) / delta; // Between magenta & cyan h /= 6.0f; if (h < 0) h += 1.0f; return h; } set { this = FromHsv(value, s, v); } } public float s { get { float max = Math.Max(r, Math.Max(g, b)); float min = Math.Min(r, Math.Min(g, b)); float delta = max - min; return max != 0 ? delta / max : 0; } set { this = FromHsv(h, value, v); } } public float v { get { return Math.Max(r, Math.Max(g, b)); } set { this = FromHsv(h, s, value); } } private static readonly Color black = new Color(0f, 0f, 0f); public Color Black { get { return black; } } public float this [int index] { get { switch (index) { case 0: return r; case 1: return g; case 2: return b; case 3: return a; default: throw new IndexOutOfRangeException(); } } set { switch (index) { case 0: r = value; return; case 1: g = value; return; case 2: b = value; return; case 3: a = value; return; default: throw new IndexOutOfRangeException(); } } } public static void ToHsv(Color color, out float hue, out float saturation, out float value) { int max = Mathf.Max(color.r8, Mathf.Max(color.g8, color.b8)); int min = Mathf.Min(color.r8, Mathf.Min(color.g8, color.b8)); float delta = max - min; if (delta == 0) { hue = 0; } else { if (color.r == max) hue = (color.g - color.b) / delta; // Between yellow & magenta else if (color.g == max) hue = 2 + (color.b - color.r) / delta; // Between cyan & yellow else hue = 4 + (color.r - color.g) / delta; // Between magenta & cyan hue /= 6.0f; if (hue < 0) hue += 1.0f; } saturation = max == 0 ? 0 : 1f - 1f * min / max; value = max / 255f; } public static Color FromHsv(float hue, float saturation, float value, float alpha = 1.0f) { if (saturation == 0) { // acp_hromatic (grey) return new Color(value, value, value, alpha); } int i; float f, p, q, t; hue *= 6.0f; hue %= 6f; i = (int)hue; f = hue - i; p = value * (1 - saturation); q = value * (1 - saturation * f); t = value * (1 - saturation * (1 - f)); switch (i) { case 0: // Red is the dominant color return new Color(value, t, p, alpha); case 1: // Green is the dominant color return new Color(q, value, p, alpha); case 2: return new Color(p, value, t, alpha); case 3: // Blue is the dominant color return new Color(p, q, value, alpha); case 4: return new Color(t, p, value, alpha); default: // (5) Red is the dominant color return new Color(value, p, q, alpha); } } public Color Blend(Color over) { Color res; float sa = 1.0f - over.a; res.a = a * sa + over.a; if (res.a == 0) { return new Color(0, 0, 0, 0); } res.r = (r * a * sa + over.r * over.a) / res.a; res.g = (g * a * sa + over.g * over.a) / res.a; res.b = (b * a * sa + over.b * over.a) / res.a; return res; } public Color Contrasted() { return new Color( (r + 0.5f) % 1.0f, (g + 0.5f) % 1.0f, (b + 0.5f) % 1.0f ); } public Color Darkened(float amount) { Color res = this; res.r = res.r * (1.0f - amount); res.g = res.g * (1.0f - amount); res.b = res.b * (1.0f - amount); return res; } public Color Inverted() { return new Color( 1.0f - r, 1.0f - g, 1.0f - b ); } public Color Lightened(float amount) { Color res = this; res.r = res.r + (1.0f - res.r) * amount; res.g = res.g + (1.0f - res.g) * amount; res.b = res.b + (1.0f - res.b) * amount; return res; } public Color LinearInterpolate(Color c, float t) { var res = this; res.r += t * (c.r - r); res.g += t * (c.g - g); res.b += t * (c.b - b); res.a += t * (c.a - a); return res; } public int ToAbgr32() { int c = (byte)Math.Round(a * 255); c <<= 8; c |= (byte)Math.Round(b * 255); c <<= 8; c |= (byte)Math.Round(g * 255); c <<= 8; c |= (byte)Math.Round(r * 255); return c; } public long ToAbgr64() { long c = (ushort)Math.Round(a * 65535); c <<= 16; c |= (ushort)Math.Round(b * 65535); c <<= 16; c |= (ushort)Math.Round(g * 65535); c <<= 16; c |= (ushort)Math.Round(r * 65535); return c; } public int ToArgb32() { int c = (byte)Math.Round(a * 255); c <<= 8; c |= (byte)Math.Round(r * 255); c <<= 8; c |= (byte)Math.Round(g * 255); c <<= 8; c |= (byte)Math.Round(b * 255); return c; } public long ToArgb64() { long c = (ushort)Math.Round(a * 65535); c <<= 16; c |= (ushort)Math.Round(r * 65535); c <<= 16; c |= (ushort)Math.Round(g * 65535); c <<= 16; c |= (ushort)Math.Round(b * 65535); return c; } public int ToRgba32() { int c = (byte)Math.Round(r * 255); c <<= 8; c |= (byte)Math.Round(g * 255); c <<= 8; c |= (byte)Math.Round(b * 255); c <<= 8; c |= (byte)Math.Round(a * 255); return c; } public long ToRgba64() { long c = (ushort)Math.Round(r * 65535); c <<= 16; c |= (ushort)Math.Round(g * 65535); c <<= 16; c |= (ushort)Math.Round(b * 65535); c <<= 16; c |= (ushort)Math.Round(a * 65535); return c; } public string ToHtml(bool include_alpha = true) { var txt = string.Empty; txt += ToHex32(r); txt += ToHex32(g); txt += ToHex32(b); if (include_alpha) txt = ToHex32(a) + txt; return txt; } // Constructors public Color(float r, float g, float b, float a = 1.0f) { this.r = r; this.g = g; this.b = b; this.a = a; } public Color(int rgba) { a = (rgba & 0xFF) / 255.0f; rgba >>= 8; b = (rgba & 0xFF) / 255.0f; rgba >>= 8; g = (rgba & 0xFF) / 255.0f; rgba >>= 8; r = (rgba & 0xFF) / 255.0f; } public Color(long rgba) { a = (rgba & 0xFFFF) / 65535.0f; rgba >>= 16; b = (rgba & 0xFFFF) / 65535.0f; rgba >>= 16; g = (rgba & 0xFFFF) / 65535.0f; rgba >>= 16; r = (rgba & 0xFFFF) / 65535.0f; } private static int ParseCol8(string str, int ofs) { int ig = 0; for (int i = 0; i < 2; i++) { int c = str[i + ofs]; int v; if (c >= '0' && c <= '9') { v = c - '0'; } else if (c >= 'a' && c <= 'f') { v = c - 'a'; v += 10; } else if (c >= 'A' && c <= 'F') { v = c - 'A'; v += 10; } else { return -1; } if (i == 0) ig += v * 16; else ig += v; } return ig; } private String ToHex32(float val) { int v = Mathf.RoundToInt(Mathf.Clamp(val * 255, 0, 255)); var ret = string.Empty; for (int i = 0; i < 2; i++) { char[] c = { (char)0, (char)0 }; int lv = v & 0xF; if (lv < 10) c[0] = (char)('0' + lv); else c[0] = (char)('a' + lv - 10); v >>= 4; ret = c + ret; } return ret; } internal static bool HtmlIsValid(string color) { if (color.Length == 0) return false; if (color[0] == '#') color = color.Substring(1, color.Length - 1); bool alpha; if (color.Length == 8) alpha = true; else if (color.Length == 6) alpha = false; else return false; if (alpha) { if (ParseCol8(color, 0) < 0) return false; } int from = alpha ? 2 : 0; if (ParseCol8(color, from + 0) < 0) return false; if (ParseCol8(color, from + 2) < 0) return false; if (ParseCol8(color, from + 4) < 0) return false; return true; } public static Color Color8(byte r8, byte g8, byte b8, byte a8) { return new Color(r8 / 255f, g8 / 255f, b8 / 255f, a8 / 255f); } public Color(string rgba) { if (rgba.Length == 0) { r = 0f; g = 0f; b = 0f; a = 1.0f; return; } if (rgba[0] == '#') rgba = rgba.Substring(1); bool alpha; if (rgba.Length == 8) { alpha = true; } else if (rgba.Length == 6) { alpha = false; } else { throw new ArgumentOutOfRangeException("Invalid color code. Length is " + rgba.Length + " but a length of 6 or 8 is expected: " + rgba); } if (alpha) { a = ParseCol8(rgba, 0) / 255f; if (a < 0) throw new ArgumentOutOfRangeException("Invalid color code. Alpha part is not valid hexadecimal: " + rgba); } else { a = 1.0f; } int from = alpha ? 2 : 0; r = ParseCol8(rgba, from + 0) / 255f; if (r < 0) throw new ArgumentOutOfRangeException("Invalid color code. Red part is not valid hexadecimal: " + rgba); g = ParseCol8(rgba, from + 2) / 255f; if (g < 0) throw new ArgumentOutOfRangeException("Invalid color code. Green part is not valid hexadecimal: " + rgba); b = ParseCol8(rgba, from + 4) / 255f; if (b < 0) throw new ArgumentOutOfRangeException("Invalid color code. Blue part is not valid hexadecimal: " + rgba); } public static bool operator ==(Color left, Color right) { return left.Equals(right); } public static bool operator !=(Color left, Color right) { return !left.Equals(right); } public static bool operator <(Color left, Color right) { if (left.r == right.r) { if (left.g == right.g) { if (left.b == right.b) return left.a < right.a; return left.b < right.b; } return left.g < right.g; } return left.r < right.r; } public static bool operator >(Color left, Color right) { if (left.r == right.r) { if (left.g == right.g) { if (left.b == right.b) return left.a > right.a; return left.b > right.b; } return left.g > right.g; } return left.r > right.r; } public override bool Equals(object obj) { if (obj is Color) { return Equals((Color)obj); } return false; } public bool Equals(Color other) { return r == other.r && g == other.g && b == other.b && a == other.a; } public override int GetHashCode() { return r.GetHashCode() ^ g.GetHashCode() ^ b.GetHashCode() ^ a.GetHashCode(); } public override string ToString() { return String.Format("{0},{1},{2},{3}", r.ToString(), g.ToString(), b.ToString(), a.ToString()); } public string ToString(string format) { return String.Format("{0},{1},{2},{3}", r.ToString(format), g.ToString(format), b.ToString(format), a.ToString(format)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Runtime.InteropServices.WindowsRuntime; using System.Threading; using System.Threading.Tasks; using Windows.Web.Http.Headers; using RTHttpMethod = Windows.Web.Http.HttpMethod; using RTHttpRequestMessage = Windows.Web.Http.HttpRequestMessage; using RTHttpResponseMessage = Windows.Web.Http.HttpResponseMessage; using RTHttpBufferContent = Windows.Web.Http.HttpBufferContent; using RTHttpStreamContent = Windows.Web.Http.HttpStreamContent; using RTHttpVersion = Windows.Web.Http.HttpVersion; using RTIHttpContent = Windows.Web.Http.IHttpContent; using RTIInputStream = Windows.Storage.Streams.IInputStream; using RTHttpBaseProtocolFilter = Windows.Web.Http.Filters.HttpBaseProtocolFilter; namespace System.Net.Http { internal class HttpHandlerToFilter : HttpMessageHandler { private readonly RTHttpBaseProtocolFilter _next; private int _filterMaxVersionSet; internal HttpHandlerToFilter(RTHttpBaseProtocolFilter filter) { if (filter == null) { throw new ArgumentNullException(nameof(filter)); } _next = filter; _filterMaxVersionSet = 0; } protected internal override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancel) { if (request == null) { throw new ArgumentNullException(nameof(request)); } cancel.ThrowIfCancellationRequested(); RTHttpRequestMessage rtRequest = await ConvertRequestAsync(request).ConfigureAwait(false); RTHttpResponseMessage rtResponse = await _next.SendRequestAsync(rtRequest).AsTask(cancel).ConfigureAwait(false); // Update in case of redirects request.RequestUri = rtRequest.RequestUri; HttpResponseMessage response = ConvertResponse(rtResponse); response.RequestMessage = request; return response; } private async Task<RTHttpRequestMessage> ConvertRequestAsync(HttpRequestMessage request) { RTHttpRequestMessage rtRequest = new RTHttpRequestMessage(new RTHttpMethod(request.Method.Method), request.RequestUri); // We can only control the Version on the first request message since the WinRT API // has this property designed as a filter/handler property. In addition the overall design // of HTTP/2.0 is such that once the first request is using it, all the other requests // to the same endpoint will use it as well. if (Interlocked.Exchange(ref _filterMaxVersionSet, 1) == 0) { RTHttpVersion maxVersion; if (request.Version == HttpVersionInternal.Version20) { maxVersion = RTHttpVersion.Http20; } else if (request.Version == HttpVersionInternal.Version11) { maxVersion = RTHttpVersion.Http11; } else if (request.Version == HttpVersionInternal.Version10) { maxVersion = RTHttpVersion.Http10; } else { // TODO (#7878): We need to throw an exception here similar to .NET Desktop // throw new ArgumentException(SR.GetString(SR.net_wrongversion), "value"); // // But we need to do that checking in the HttpClientHandler object itself. // and we have that bug as well for the WinHttpHandler version also. maxVersion = RTHttpVersion.Http11; } // The default for WinRT HttpBaseProtocolFilter.MaxVersion is HttpVersion.Http20. // So, we only have to change it if we don't want HTTP/2.0. if (maxVersion != RTHttpVersion.Http20) { _next.MaxVersion = maxVersion; } } // Headers foreach (KeyValuePair<string, IEnumerable<string>> headerPair in request.Headers) { foreach (string value in headerPair.Value) { bool success = rtRequest.Headers.TryAppendWithoutValidation(headerPair.Key, value); Debug.Assert(success); } } // Properties foreach (KeyValuePair<string, object> propertyPair in request.Properties) { rtRequest.Properties.Add(propertyPair.Key, propertyPair.Value); } // Content if (request.Content != null) { rtRequest.Content = await CreateRequestContentAsync(request, rtRequest.Headers).ConfigureAwait(false); } return rtRequest; } private static async Task<RTIHttpContent> CreateRequestContentAsync(HttpRequestMessage request, HttpRequestHeaderCollection rtHeaderCollection) { HttpContent content = request.Content; RTIHttpContent rtContent; ArraySegment<byte> buffer; // If we are buffered already, it is more efficient to send the data directly using the buffer with the // WinRT HttpBufferContent class than using HttpStreamContent. This also avoids issues caused by // a design limitation in the System.Runtime.WindowsRuntime System.IO.NetFxToWinRtStreamAdapter. if (content.TryGetBuffer(out buffer)) { rtContent = new RTHttpBufferContent(buffer.Array.AsBuffer(), (uint)buffer.Offset, (uint)buffer.Count); } else { Stream contentStream = await content.ReadAsStreamAsync().ConfigureAwait(false); if (contentStream is RTIInputStream) { rtContent = new RTHttpStreamContent((RTIInputStream)contentStream); } else if (contentStream is MemoryStream) { var memStream = contentStream as MemoryStream; if (memStream.TryGetBuffer(out buffer)) { rtContent = new RTHttpBufferContent(buffer.Array.AsBuffer(), (uint)buffer.Offset, (uint)buffer.Count); } else { byte[] byteArray = memStream.ToArray(); rtContent = new RTHttpBufferContent(byteArray.AsBuffer(), 0, (uint) byteArray.Length); } } else { rtContent = new RTHttpStreamContent(contentStream.AsInputStream()); } } // RTHttpBufferContent constructor automatically adds a Content-Length header. RTHttpStreamContent does not. // Clear any 'Content-Length' header added by the RTHttp*Content objects. We need to clear that now // and decide later whether we need 'Content-Length' or 'Transfer-Encoding: chunked' headers based on the // .NET HttpRequestMessage and Content header collections. rtContent.Headers.ContentLength = null; // Deal with conflict between 'Content-Length' vs. 'Transfer-Encoding: chunked' semantics. // Desktop System.Net allows both headers to be specified but ends up stripping out // 'Content-Length' and using chunked semantics. The WinRT APIs throw an exception so // we need to manually strip out the conflicting header to maintain app compatibility. if (request.Headers.TransferEncodingChunked.HasValue && request.Headers.TransferEncodingChunked.Value) { content.Headers.ContentLength = null; } else { // Trigger delayed header generation via TryComputeLength. This code is needed due to an outstanding // bug in HttpContentHeaders.ContentLength. See GitHub Issue #5523. content.Headers.ContentLength = content.Headers.ContentLength; } foreach (KeyValuePair<string, IEnumerable<string>> headerPair in content.Headers) { foreach (string value in headerPair.Value) { if (!rtContent.Headers.TryAppendWithoutValidation(headerPair.Key, value)) { // rtContent headers are restricted to a white-list of allowed headers, while System.Net.HttpClient's content headers // will allow custom headers. If something is not successfully added to the content headers, try adding them to the standard headers. bool success = rtHeaderCollection.TryAppendWithoutValidation(headerPair.Key, value); Debug.Assert(success); } } } return rtContent; } private static HttpResponseMessage ConvertResponse(RTHttpResponseMessage rtResponse) { HttpResponseMessage response = new HttpResponseMessage((HttpStatusCode)rtResponse.StatusCode); response.ReasonPhrase = rtResponse.ReasonPhrase; // Version if (rtResponse.Version == RTHttpVersion.Http11) { response.Version = HttpVersionInternal.Version11; } else if (rtResponse.Version == RTHttpVersion.Http10) { response.Version = HttpVersionInternal.Version10; } else if (rtResponse.Version == RTHttpVersion.Http20) { response.Version = HttpVersionInternal.Version20; } else { response.Version = new Version(0,0); } bool success; // Headers foreach (KeyValuePair<string, string> headerPair in rtResponse.Headers) { if (headerPair.Key.Equals(HttpKnownHeaderNames.SetCookie, StringComparison.OrdinalIgnoreCase)) { // The Set-Cookie header always comes back with all of the cookies concatenated together. // For example if the response contains the following: // Set-Cookie A=1 // Set-Cookie B=2 // Then we will have a single header KeyValuePair of Key=Set-Cookie, Value=A=1, B=2. // However clients expect these headers to be separated(i.e. // httpResponseMessage.Headers.GetValues("Set-Cookie") should return two cookies not one // concatenated together). success = response.Headers.TryAddWithoutValidation(headerPair.Key, CookieHelper.GetCookiesFromHeader(headerPair.Value)); } else { success = response.Headers.TryAddWithoutValidation(headerPair.Key, headerPair.Value); } Debug.Assert(success); } // Content if (rtResponse.Content != null) { var rtResponseStream = rtResponse.Content.ReadAsInputStreamAsync().AsTask().Result; response.Content = new StreamContent(rtResponseStream.AsStreamForRead()); foreach (KeyValuePair<string, string> headerPair in rtResponse.Content.Headers) { success = response.Content.Headers.TryAddWithoutValidation(headerPair.Key, headerPair.Value); Debug.Assert(success); } } return response; } } }
using System; using System.Collections.Generic; using UnityEngine; using Random = UnityEngine.Random; public class RandomCity : MonoBehaviour { public List<Opening> openings; public IEnumerator<City> currentGenerator; [Serializable] public class Opening { public CityRow row; public Dir dir; public int x, y; } public TextAsset testOutput; public TextAsset[] sources; public CityToBlocks visualizer; public City CreateEmptyCity(int width = 10, int height = 10) { CityTile[,] grid = new CityTile[width, height]; return new City(grid); } public City StartCreatingRandomCity() { openings = new List<Opening>(); CityTile[,] grid = new CityTile[100, 100]; City city = new City(grid); List<City> allCities = new List<City>(); foreach (var source in sources) { allCities.Add(City.FromString(source)); } city = InsertInCity(city, allCities[0], 47, 47); currentGenerator = CityGenerator(city, allCities); city = showDebugOpenings(city); return city; } private IEnumerator<City> CityGenerator(City city, List<City> allCities) { int safety = 0; int insertions = 0; while (safety < 100 && insertions < 15 && openings.Count > 0) { string debug = "stepping generation next. Number of openings: " + openings.Count + ", insertions: " + insertions + ", safety: " + safety; safety++; Opening opening = openings.GetRandom(); City insert = FindMatching(opening, allCities); if (insert == null) { Debug.LogWarning("Found no matching city for an opening!"); continue; } var startX = opening.x; var startY = opening.y; if (opening.dir == Dir.Left) startX -= insert.width; else if (opening.dir == Dir.Up) startY -= insert.height; else if (opening.dir == Dir.Down) startY++; else if (opening.dir == Dir.Right) startX++; debug += "\nStarting at (" + startX + "/" + startY + ") \nInserting:\n"; debug += insert.ToString(); if (city.HasRoomFor(insert, startX, startY)) { insertions++; city = InsertInCity(city, insert, startX, startY); RemoveInvalidOpenings(city.cityGrid); debug += "\nInsert successfull!"; } else { debug += "\nInsert failed, no room!"; } Debug.Log(debug); city = showDebugOpenings(city); yield return city; } Debug.Log("Finished generation: Number of openings: " + openings.Count + ", insertions: " + insertions + ", safety: " + safety); } private void RemoveInvalidOpenings(CityTile[,] cityGrid) { //foreach (var opening in openings) { openings.RemoveAll(opening => { var xDir = opening.dir.X(); var yDir = opening.dir.Y(); var startX = opening.x + xDir; var startY = opening.y + yDir; //int x = opening.x + opening.dir.X(); //int y = opening.y + opening.dir.Y(); CityTile[] tiles = opening.row.tiles; string debug = "checking validity of opening " + tiles.PrettyPrint() + " as " + opening.x + "/" + opening.y + " in the direction " + opening.dir; for (int i = 0; i < tiles.Length; i++) { CityTile cityTile = cityGrid[startX + i * xDir, +startY + i * yDir]; debug += string.Format("\nChecking tile at {0}/{1}, it has the value {2}", startX + i * xDir, startY + i * yDir, cityTile); if (cityTile != CityTile.Empty) { i = tiles.Length; debug += "\nremoved it!"; Debug.Log(debug); return true; } } Debug.Log(debug); return false; }); } private City FindMatching(Opening opening, List<City> allCities) { int startCoordinate = Random.Range(0, allCities.Count); for (int i = 0; i < allCities.Count; i++) { City city = allCities[(i + startCoordinate) % allCities.Count]; if (Matches(opening, city)) { return city; } } return null; } private bool Matches(Opening opening, City city) { var openingRow = opening.row; var cityRow = city.GetBorder(opening.dir.Opposite()); return cityRow != null && cityRow.Matches(openingRow); } private City showDebugOpenings(City city) { CityTile[,] grid; grid = city.cityGrid; for (int x = 0; x < grid.GetLength(0); x++) { for (int y = 0; y < grid.GetLength(1); y++) { if(grid[x,y] == CityTile.DEBUG) grid[x,y] = CityTile.Street; //reset old debugs. } } foreach (var opening in openings) { var rowLength = opening.row.tiles.Length; for (int i = 0; i < rowLength; i++) { var tile = opening.row.tiles[i]; if (tile == CityTile.Street) { switch (opening.dir) { case Dir.Up: grid[opening.x + i, opening.y] = CityTile.DEBUG; break; case Dir.Down: grid[opening.x + i, opening.y] = CityTile.DEBUG; break; case Dir.Right: grid[opening.x, opening.y + i] = CityTile.DEBUG; break; case Dir.Left: grid[opening.x, opening.y + i] = CityTile.DEBUG; break; } } } } city = new City(grid); return city; } private City InsertInCity(City city, City insert, int startX, int startY) { CheckOpening(city, startX, startY, insert.up, Dir.Up); CheckOpening(city, startX, startY + insert.height - 1, insert.down, Dir.Down); CheckOpening(city, startX, startY, insert.left, Dir.Left); CheckOpening(city, startX + insert.width - 1, startY, insert.right, Dir.Right); return city.Insert(insert, startX, startY); } private void CheckOpening(City c, int startX, int startY, CityRow row, Dir dir) { if (row != null) { for (int i = 0; i < row.Length; i++) { if (!c.IsVacant(startX + dir.X(), startY + dir.Y())) return; } openings.Add(new Opening { dir = dir, row = row, x = startX, y = startY }); } } } public enum Dir { Up, Right, Down, Left } public static class DirExtension { public static Dir Opposite(this Dir dir) { switch (dir) { case Dir.Right: return Dir.Left; case Dir.Down: return Dir.Up; case Dir.Left: return Dir.Right; default: return Dir.Down; } } public static int X(this Dir dir) { switch (dir) { case Dir.Right: return 1; case Dir.Down: return 0; case Dir.Left: return -1; default: return 0; } } public static int Y(this Dir dir) { switch (dir) { case Dir.Right: return 0; case Dir.Down: return 1; case Dir.Left: return 0; default: return -1; } } }
using System; using System.Collections.Generic; using System.Runtime.CompilerServices; namespace Avalonia { /// <summary> /// Tracks registered <see cref="AvaloniaProperty"/> instances. /// </summary> public class AvaloniaPropertyRegistry { private readonly Dictionary<int, AvaloniaProperty> _properties = new Dictionary<int, AvaloniaProperty>(); private readonly Dictionary<Type, Dictionary<int, AvaloniaProperty>> _registered = new Dictionary<Type, Dictionary<int, AvaloniaProperty>>(); private readonly Dictionary<Type, Dictionary<int, AvaloniaProperty>> _attached = new Dictionary<Type, Dictionary<int, AvaloniaProperty>>(); private readonly Dictionary<Type, Dictionary<int, AvaloniaProperty>> _direct = new Dictionary<Type, Dictionary<int, AvaloniaProperty>>(); private readonly Dictionary<Type, List<AvaloniaProperty>> _registeredCache = new Dictionary<Type, List<AvaloniaProperty>>(); private readonly Dictionary<Type, List<AvaloniaProperty>> _attachedCache = new Dictionary<Type, List<AvaloniaProperty>>(); private readonly Dictionary<Type, List<AvaloniaProperty>> _directCache = new Dictionary<Type, List<AvaloniaProperty>>(); private readonly Dictionary<Type, List<AvaloniaProperty>> _inheritedCache = new Dictionary<Type, List<AvaloniaProperty>>(); /// <summary> /// Gets the <see cref="AvaloniaPropertyRegistry"/> instance /// </summary> public static AvaloniaPropertyRegistry Instance { get; } = new AvaloniaPropertyRegistry(); /// <summary> /// Gets a list of all registered properties. /// </summary> internal IReadOnlyCollection<AvaloniaProperty> Properties => _properties.Values; /// <summary> /// Gets all non-attached <see cref="AvaloniaProperty"/>s registered on a type. /// </summary> /// <param name="type">The type.</param> /// <returns>A collection of <see cref="AvaloniaProperty"/> definitions.</returns> public IReadOnlyList<AvaloniaProperty> GetRegistered(Type type) { Contract.Requires<ArgumentNullException>(type != null); if (_registeredCache.TryGetValue(type, out var result)) { return result; } var t = type; result = new List<AvaloniaProperty>(); while (t != null) { // Ensure the type's static ctor has been run. RuntimeHelpers.RunClassConstructor(t.TypeHandle); if (_registered.TryGetValue(t, out var registered)) { result.AddRange(registered.Values); } t = t.BaseType; } _registeredCache.Add(type, result); return result; } /// <summary> /// Gets all attached <see cref="AvaloniaProperty"/>s registered on a type. /// </summary> /// <param name="type">The type.</param> /// <returns>A collection of <see cref="AvaloniaProperty"/> definitions.</returns> public IReadOnlyList<AvaloniaProperty> GetRegisteredAttached(Type type) { Contract.Requires<ArgumentNullException>(type != null); if (_attachedCache.TryGetValue(type, out var result)) { return result; } var t = type; result = new List<AvaloniaProperty>(); while (t != null) { if (_attached.TryGetValue(t, out var attached)) { result.AddRange(attached.Values); } t = t.BaseType; } _attachedCache.Add(type, result); return result; } /// <summary> /// Gets all direct <see cref="AvaloniaProperty"/>s registered on a type. /// </summary> /// <param name="type">The type.</param> /// <returns>A collection of <see cref="AvaloniaProperty"/> definitions.</returns> public IReadOnlyList<AvaloniaProperty> GetRegisteredDirect(Type type) { Contract.Requires<ArgumentNullException>(type != null); if (_directCache.TryGetValue(type, out var result)) { return result; } var t = type; result = new List<AvaloniaProperty>(); while (t != null) { if (_direct.TryGetValue(t, out var direct)) { result.AddRange(direct.Values); } t = t.BaseType; } _directCache.Add(type, result); return result; } /// <summary> /// Gets all inherited <see cref="AvaloniaProperty"/>s registered on a type. /// </summary> /// <param name="type">The type.</param> /// <returns>A collection of <see cref="AvaloniaProperty"/> definitions.</returns> public IReadOnlyList<AvaloniaProperty> GetRegisteredInherited(Type type) { Contract.Requires<ArgumentNullException>(type != null); if (_inheritedCache.TryGetValue(type, out var result)) { return result; } result = new List<AvaloniaProperty>(); var visited = new HashSet<AvaloniaProperty>(); var registered = GetRegistered(type); var registeredCount = registered.Count; for (var i = 0; i < registeredCount; i++) { var property = registered[i]; if (property.Inherits) { result.Add(property); visited.Add(property); } } var registeredAttached = GetRegisteredAttached(type); var registeredAttachedCount = registeredAttached.Count; for (var i = 0; i < registeredAttachedCount; i++) { var property = registeredAttached[i]; if (property.Inherits) { if (!visited.Contains(property)) { result.Add(property); } } } _inheritedCache.Add(type, result); return result; } /// <summary> /// Gets all <see cref="AvaloniaProperty"/>s registered on a object. /// </summary> /// <param name="o">The object.</param> /// <returns>A collection of <see cref="AvaloniaProperty"/> definitions.</returns> public IReadOnlyList<AvaloniaProperty> GetRegistered(IAvaloniaObject o) { Contract.Requires<ArgumentNullException>(o != null); return GetRegistered(o.GetType()); } /// <summary> /// Finds a direct property as registered on an object. /// </summary> /// <param name="o">The object.</param> /// <param name="property">The direct property.</param> /// <returns> /// The registered property or null if no matching property found. /// </returns> public DirectPropertyBase<T> GetRegisteredDirect<T>( IAvaloniaObject o, DirectPropertyBase<T> property) { return FindRegisteredDirect(o, property) ?? throw new ArgumentException($"Property '{property.Name} not registered on '{o.GetType()}"); } /// <summary> /// Finds a registered property on a type by name. /// </summary> /// <param name="type">The type.</param> /// <param name="name">The property name.</param> /// <returns> /// The registered property or null if no matching property found. /// </returns> /// <exception cref="InvalidOperationException"> /// The property name contains a '.'. /// </exception> public AvaloniaProperty FindRegistered(Type type, string name) { Contract.Requires<ArgumentNullException>(type != null); Contract.Requires<ArgumentNullException>(name != null); if (name.Contains(".")) { throw new InvalidOperationException("Attached properties not supported."); } var registered = GetRegistered(type); var registeredCount = registered.Count; for (var i = 0; i < registeredCount; i++) { AvaloniaProperty x = registered[i]; if (x.Name == name) { return x; } } return null; } /// <summary> /// Finds a registered property on an object by name. /// </summary> /// <param name="o">The object.</param> /// <param name="name">The property name.</param> /// <returns> /// The registered property or null if no matching property found. /// </returns> /// <exception cref="InvalidOperationException"> /// The property name contains a '.'. /// </exception> public AvaloniaProperty FindRegistered(IAvaloniaObject o, string name) { Contract.Requires<ArgumentNullException>(o != null); Contract.Requires<ArgumentNullException>(name != null); return FindRegistered(o.GetType(), name); } /// <summary> /// Finds a direct property as registered on an object. /// </summary> /// <param name="o">The object.</param> /// <param name="property">The direct property.</param> /// <returns> /// The registered property or null if no matching property found. /// </returns> public DirectPropertyBase<T> FindRegisteredDirect<T>( IAvaloniaObject o, DirectPropertyBase<T> property) { if (property.Owner == o.GetType()) { return property; } var registeredDirect = GetRegisteredDirect(o.GetType()); var registeredDirectCount = registeredDirect.Count; for (var i = 0; i < registeredDirectCount; i++) { var p = registeredDirect[i]; if (p == property) { return (DirectPropertyBase<T>)p; } } return null; } /// <summary> /// Finds a registered property by Id. /// </summary> /// <param name="id">The property Id.</param> /// <returns>The registered property or null if no matching property found.</returns> internal AvaloniaProperty FindRegistered(int id) { return id < _properties.Count ? _properties[id] : null; } /// <summary> /// Checks whether a <see cref="AvaloniaProperty"/> is registered on a type. /// </summary> /// <param name="type">The type.</param> /// <param name="property">The property.</param> /// <returns>True if the property is registered, otherwise false.</returns> public bool IsRegistered(Type type, AvaloniaProperty property) { Contract.Requires<ArgumentNullException>(type != null); Contract.Requires<ArgumentNullException>(property != null); static bool ContainsProperty(IReadOnlyList<AvaloniaProperty> properties, AvaloniaProperty property) { var propertiesCount = properties.Count; for (var i = 0; i < propertiesCount; i++) { if (properties[i] == property) { return true; } } return false; } return ContainsProperty(Instance.GetRegistered(type), property) || ContainsProperty(Instance.GetRegisteredAttached(type), property); } /// <summary> /// Checks whether a <see cref="AvaloniaProperty"/> is registered on a object. /// </summary> /// <param name="o">The object.</param> /// <param name="property">The property.</param> /// <returns>True if the property is registered, otherwise false.</returns> public bool IsRegistered(object o, AvaloniaProperty property) { Contract.Requires<ArgumentNullException>(o != null); Contract.Requires<ArgumentNullException>(property != null); return IsRegistered(o.GetType(), property); } /// <summary> /// Registers a <see cref="AvaloniaProperty"/> on a type. /// </summary> /// <param name="type">The type.</param> /// <param name="property">The property.</param> /// <remarks> /// You won't usually want to call this method directly, instead use the /// <see cref="AvaloniaProperty.Register{TOwner, TValue}(string, TValue, bool, Data.BindingMode, Func{TValue, bool}, Func{IAvaloniaObject, TValue, TValue}, Action{IAvaloniaObject, bool})"/> /// method. /// </remarks> public void Register(Type type, AvaloniaProperty property) { Contract.Requires<ArgumentNullException>(type != null); Contract.Requires<ArgumentNullException>(property != null); if (!_registered.TryGetValue(type, out var inner)) { inner = new Dictionary<int, AvaloniaProperty>(); inner.Add(property.Id, property); _registered.Add(type, inner); } else if (!inner.ContainsKey(property.Id)) { inner.Add(property.Id, property); } if (property.IsDirect) { if (!_direct.TryGetValue(type, out inner)) { inner = new Dictionary<int, AvaloniaProperty>(); inner.Add(property.Id, property); _direct.Add(type, inner); } else if (!inner.ContainsKey(property.Id)) { inner.Add(property.Id, property); } _directCache.Clear(); } if (!_properties.ContainsKey(property.Id)) { _properties.Add(property.Id, property); } _registeredCache.Clear(); _inheritedCache.Clear(); } /// <summary> /// Registers an attached <see cref="AvaloniaProperty"/> on a type. /// </summary> /// <param name="type">The type.</param> /// <param name="property">The property.</param> /// <remarks> /// You won't usually want to call this method directly, instead use the /// <see cref="AvaloniaProperty.RegisterAttached{THost, TValue}(string, Type, TValue, bool, Data.BindingMode, Func{TValue, bool}, Func{IAvaloniaObject, TValue, TValue})"/> /// method. /// </remarks> public void RegisterAttached(Type type, AvaloniaProperty property) { Contract.Requires<ArgumentNullException>(type != null); Contract.Requires<ArgumentNullException>(property != null); if (!property.IsAttached) { throw new InvalidOperationException( "Cannot register a non-attached property as attached."); } if (!_attached.TryGetValue(type, out var inner)) { inner = new Dictionary<int, AvaloniaProperty>(); inner.Add(property.Id, property); _attached.Add(type, inner); } else { inner.Add(property.Id, property); } _attachedCache.Clear(); _inheritedCache.Clear(); } } }
using System; using System.Data; using Csla; using Csla.Data; using SelfLoadSoftDelete.DataAccess; using SelfLoadSoftDelete.DataAccess.ERLevel; namespace SelfLoadSoftDelete.Business.ERLevel { /// <summary> /// G03_SubContinentColl (editable child list).<br/> /// This is a generated base class of <see cref="G03_SubContinentColl"/> business object. /// </summary> /// <remarks> /// This class is child of <see cref="G02_Continent"/> editable root object.<br/> /// The items of the collection are <see cref="G04_SubContinent"/> objects. /// </remarks> [Serializable] public partial class G03_SubContinentColl : BusinessListBase<G03_SubContinentColl, G04_SubContinent> { #region Collection Business Methods /// <summary> /// Removes a <see cref="G04_SubContinent"/> item from the collection. /// </summary> /// <param name="subContinent_ID">The SubContinent_ID of the item to be removed.</param> public void Remove(int subContinent_ID) { foreach (var g04_SubContinent in this) { if (g04_SubContinent.SubContinent_ID == subContinent_ID) { Remove(g04_SubContinent); break; } } } /// <summary> /// Determines whether a <see cref="G04_SubContinent"/> item is in the collection. /// </summary> /// <param name="subContinent_ID">The SubContinent_ID of the item to search for.</param> /// <returns><c>true</c> if the G04_SubContinent is a collection item; otherwise, <c>false</c>.</returns> public bool Contains(int subContinent_ID) { foreach (var g04_SubContinent in this) { if (g04_SubContinent.SubContinent_ID == subContinent_ID) { return true; } } return false; } /// <summary> /// Determines whether a <see cref="G04_SubContinent"/> item is in the collection's DeletedList. /// </summary> /// <param name="subContinent_ID">The SubContinent_ID of the item to search for.</param> /// <returns><c>true</c> if the G04_SubContinent is a deleted collection item; otherwise, <c>false</c>.</returns> public bool ContainsDeleted(int subContinent_ID) { foreach (var g04_SubContinent in DeletedList) { if (g04_SubContinent.SubContinent_ID == subContinent_ID) { return true; } } return false; } #endregion #region Find Methods /// <summary> /// Finds a <see cref="G04_SubContinent"/> item of the <see cref="G03_SubContinentColl"/> collection, based on a given SubContinent_ID. /// </summary> /// <param name="subContinent_ID">The SubContinent_ID.</param> /// <returns>A <see cref="G04_SubContinent"/> object.</returns> public G04_SubContinent FindG04_SubContinentBySubContinent_ID(int subContinent_ID) { for (var i = 0; i < this.Count; i++) { if (this[i].SubContinent_ID.Equals(subContinent_ID)) { return this[i]; } } return null; } #endregion #region Factory Methods /// <summary> /// Factory method. Creates a new <see cref="G03_SubContinentColl"/> collection. /// </summary> /// <returns>A reference to the created <see cref="G03_SubContinentColl"/> collection.</returns> internal static G03_SubContinentColl NewG03_SubContinentColl() { return DataPortal.CreateChild<G03_SubContinentColl>(); } /// <summary> /// Factory method. Loads a <see cref="G03_SubContinentColl"/> collection, based on given parameters. /// </summary> /// <param name="parent_Continent_ID">The Parent_Continent_ID parameter of the G03_SubContinentColl to fetch.</param> /// <returns>A reference to the fetched <see cref="G03_SubContinentColl"/> collection.</returns> internal static G03_SubContinentColl GetG03_SubContinentColl(int parent_Continent_ID) { return DataPortal.FetchChild<G03_SubContinentColl>(parent_Continent_ID); } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="G03_SubContinentColl"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public G03_SubContinentColl() { // Use factory methods and do not use direct creation. // show the framework that this is a child object MarkAsChild(); var rlce = RaiseListChangedEvents; RaiseListChangedEvents = false; AllowNew = true; AllowEdit = true; AllowRemove = true; RaiseListChangedEvents = rlce; } #endregion #region Data Access /// <summary> /// Loads a <see cref="G03_SubContinentColl"/> collection from the database, based on given criteria. /// </summary> /// <param name="parent_Continent_ID">The Parent Continent ID.</param> protected void Child_Fetch(int parent_Continent_ID) { var args = new DataPortalHookArgs(parent_Continent_ID); OnFetchPre(args); using (var dalManager = DalFactorySelfLoadSoftDelete.GetManager()) { var dal = dalManager.GetProvider<IG03_SubContinentCollDal>(); var data = dal.Fetch(parent_Continent_ID); LoadCollection(data); } OnFetchPost(args); foreach (var item in this) { item.FetchChildren(); } } private void LoadCollection(IDataReader data) { using (var dr = new SafeDataReader(data)) { Fetch(dr); } } /// <summary> /// Loads all <see cref="G03_SubContinentColl"/> collection items from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> private void Fetch(SafeDataReader dr) { var rlce = RaiseListChangedEvents; RaiseListChangedEvents = false; while (dr.Read()) { Add(G04_SubContinent.GetG04_SubContinent(dr)); } RaiseListChangedEvents = rlce; } #endregion #region DataPortal Hooks /// <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); #endregion } }
/*! Copyright (C) 2003-2006 Kody Brown (kody@bricksoft.com). 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; using System.Diagnostics; using System.IO; using Bricksoft.PowerCode; namespace Bricksoft.Developer.DosToys.FastFileCopy { /// <summary> /// Summary description for fcopy. /// </summary> public class fcopy { private const int INVALIDARGUMENTS = 1; private CommandLine args = null; //private string[] cmdLine = new string[] { }; private static string source = ""; private string destination = ""; private string wildcard = ""; private bool testOnly = false; private bool showReason = false; private bool verbose = false; private bool forceAllChangedFiles = false; private bool pause = false; private bool recurse = false; private bool runSilent = false; private bool showProgress = false; private bool bIgnoreDateTime = false; private bool bDoOnlyDateTime = false; private bool bIgnoreSize = false; private bool bDoOnlySize = false; private bool bIgnoreVersion = false; private bool bDoOnlyVersion = false; public fcopy( string[] arguments ) { args = new CommandLine(arguments); if (args.Contains("debug")) { System.Threading.Thread.Sleep(10000); } //cmdLine = arguments; } public int Run() { #region Get the command-line arguments into local variables if (args.Contains("?") || args.Contains("h") || args.Contains("help") || args.Count == 0) { printUsage(); return 0; } else if (2 > args.Count) { Console.WriteLine("Error: invalid arguments\r\n"); printUsage(); return INVALIDARGUMENTS; } // exclude file date/time check if (args.Contains("xd") || args.Contains("xdatetime")) { bIgnoreDateTime = true; } // only perform file date/time check if (args.Contains("d") || args.Contains("datetime")) { bDoOnlyDateTime = true; bDoOnlySize = false; bDoOnlyVersion = false; } // exclude file size check if (args.Contains("xs") || args.Contains("xsize")) { bIgnoreSize = true; } // only perform file size check if (args.Contains("s") || args.Contains("size")) { bDoOnlyDateTime = false; bDoOnlySize = true; bDoOnlyVersion = false; } // exclude file version check if (args.Contains("xv") || args.Contains("xversion")) { bIgnoreVersion = true; } // only perform file version check if (args.Contains("v") || args.Contains("version")) { bDoOnlyDateTime = false; bDoOnlySize = false; bDoOnlyVersion = true; } if (args.Contains("verbose")) { verbose = true; } // force all different files if (args.Contains("f") || args.Contains("force")) { forceAllChangedFiles = true; } if (args.Contains("p") || args.Contains("pause")) { pause = true; } if (args.Contains("recurse")) { recurse = true; } // hidden options!! if (args.Contains("t") || args.Contains("test")) { // test run: do everything except actually copying the file testOnly = true; } if (args.Contains("r") || args.Contains("reason")) { // shows why a file was copied showReason = true; verbose = true; } if (bDoOnlyDateTime || bDoOnlySize || bDoOnlyVersion) forceAllChangedFiles = true; // shows progress (cannot be used in visual studio buildevents) if (args.Contains("progress")) { showProgress = true; verbose = true; } // silent. no output if (args.Contains("silent")) { runSilent = true; verbose = false; } #endregion #region Get the source folder wildcard = "*.*"; if (args.Contains("source")) { source = args.GetString(string.Empty, "source"); } else { Console.WriteLine("invalid or missing source folder\r\n"); printUsage(); return INVALIDARGUMENTS; } if (source.IndexOf("*") > -1 || source.IndexOf("?") > -1) { // has a wildcard wildcard = source.Substring(source.LastIndexOf("\\") + 1); source = source.Substring(0, source.LastIndexOf("\\")); } else { if (!Directory.Exists(source)) { if (File.Exists(source)) { wildcard = source.Substring(source.LastIndexOf("\\") + 1); source = source.Substring(0, source.LastIndexOf("\\")); } else { Console.WriteLine("invalid source folder|file|wildcard: {0}\r\n", source); printUsage(); return INVALIDARGUMENTS; } } } if (source.EndsWith("\\")) { source = source.Substring(0, source.Length - 1); } #endregion #region Get the destination folder if (args.Contains("dest")) { destination = args.GetString(string.Empty, "dest"); } else if (args.Contains("destination")) { destination = args.GetString(string.Empty, "destination"); } else { Console.WriteLine("invalid or missing destination folder\r\nnote: if your destination folder ends with a \\\", you must use \\\\\""); printUsage(); return INVALIDARGUMENTS; } if (destination.EndsWith("\\")) { destination = destination.Substring(0, destination.Length - 1); } if (!Directory.Exists(destination)) { Console.WriteLine("invalid destination folder: {0}\r\n", destination); printUsage(); return INVALIDARGUMENTS; } #endregion #region Output what it will do if (!runSilent) { Console.WriteLine("fcopy.exe, beta version 0.93"); } if (verbose && !runSilent) { Console.WriteLine("Bricksoft Developer DosToys, http://www.bricksoft.com/"); } if (!runSilent) { Console.WriteLine("Copyright (c) 2006-2012 Bricksoft.com. All Rights Reserved.\r\n"); } if (verbose && !runSilent) { if (testOnly) { Console.WriteLine("/t : do everything but actually copying the file(s)"); } if (showReason) { Console.WriteLine("/r : shows why a file was copied (applies /v)"); } if (forceAllChangedFiles) { Console.WriteLine("/f : forcing all changed files"); } if (!bIgnoreDateTime && !bDoOnlySize && !bDoOnlyVersion) { Console.WriteLine(" : comparing date/time"); } if (!bIgnoreSize && !bDoOnlyDateTime && !bDoOnlyVersion) { Console.WriteLine(" : comparing size"); } if (!bIgnoreVersion && !bDoOnlyDateTime && !bDoOnlySize) { Console.WriteLine(" : comparing version"); } } if (!runSilent) { Console.WriteLine(""); } #endregion // // Compare the folders // int fileCount = 0; int copyCount = 0; int startPos = source.Length; string[] sourcefiles = new string[] { }; decimal percVar = 0; if (recurse) { sourcefiles = Directory.GetFiles(source, wildcard, SearchOption.AllDirectories); } else { sourcefiles = Directory.GetFiles(source, wildcard, SearchOption.TopDirectoryOnly); } if (0 < sourcefiles.Length) { percVar = Math.Round(100 / (decimal)sourcefiles.Length, 3); } if (verbose && !runSilent) { Console.WriteLine("Comparing {0} files", sourcefiles.Length); } foreach (string fullFileName in sourcefiles) { FileInfo f1 = new FileInfo(fullFileName); FileInfo f2 = new FileInfo(Path.Combine(destination, fullFileName.Substring(startPos + 1))); string details = ""; bool copyIt = CheckFile(f1, f2, ref details); if (copyIt) { if (!runSilent && (showReason || verbose)) { if (showProgress) { Console.CursorLeft = 0; // overwrite progress line } if (showReason) { Console.WriteLine("copying: {0} --> ({1})", f1.Name, details); } else if (verbose) { Console.WriteLine("copying: {0}", f1.Name); } } if (!testOnly) { File.Copy(f1.FullName, f2.FullName, true); } copyCount++; } fileCount++; if (showProgress && !runSilent) { Console.CursorLeft = 0; Console.Write("{0}% complete ", Math.Min(Math.Round(fileCount * percVar, 2), 100)); System.Threading.Thread.Sleep(1); } } if (showProgress && !runSilent) { Console.CursorLeft = 0; Console.WriteLine("100.00% complete "); Console.WriteLine("Copied {0} file{1}..", copyCount, copyCount == 1 ? "" : "s"); } if (pause && !runSilent) { Console.ReadKey(true); } return 0; } private bool CheckFile( FileInfo f1, FileInfo f2, ref string details ) { bool copyIt = false; if (forceAllChangedFiles) { details += "+f"; } if (f2.Exists) { if (!bIgnoreDateTime && !bDoOnlySize && !bDoOnlyVersion) { if (forceAllChangedFiles && f1.LastWriteTime != f2.LastWriteTime) { copyIt = true; details += "+d"; } else if (f1.LastWriteTime > f2.LastWriteTime) { copyIt = true; details += "+d"; } } if (!bIgnoreSize && !bDoOnlyDateTime && !bDoOnlyVersion) { if (forceAllChangedFiles && f1.Length != f2.Length) { copyIt = true; details += "+s"; } } if (!bIgnoreVersion && !bDoOnlyDateTime && !bDoOnlySize) { if (f1.Extension.Equals(".exe") || f1.Extension.Equals(".dll")) { FileVersionInfo fv1 = FileVersionInfo.GetVersionInfo(f1.FullName); FileVersionInfo fv2 = FileVersionInfo.GetVersionInfo(f2.FullName); if (fv1.FileMajorPart > fv2.FileMajorPart) { copyIt = true; details += "+v1"; } else if (forceAllChangedFiles && fv1.FileMajorPart != fv2.FileMajorPart) { copyIt = true; } else { if (fv1.FileMinorPart > fv2.FileMinorPart) { copyIt = true; details += "+v2"; } else if (forceAllChangedFiles && fv1.FileMinorPart != fv2.FileMinorPart) { copyIt = true; } else { if (fv1.FileBuildPart > fv2.FileBuildPart) { copyIt = true; details += "+v3"; } else if (forceAllChangedFiles && fv1.FileBuildPart != fv2.FileBuildPart) { copyIt = true; } else { if (fv1.FilePrivatePart > fv2.FilePrivatePart) { copyIt = true; details += "+v4"; } else if (forceAllChangedFiles && fv1.FilePrivatePart != fv2.FilePrivatePart) { copyIt = true; } else { // file version is the same or older } } } } } } } else { // destination file does not exist copyIt = true; details += "+x"; } return copyIt; } private static void printUsage() { Console.WriteLine("fcopy.exe, beta version 0.91"); Console.WriteLine(" "); Console.WriteLine("Bricksoft Developer DosToys, http://www.bricksoft.com/"); Console.WriteLine("Copyright (c) 2006 Bricksoft.com. All Rights Reserved."); Console.WriteLine(" "); Console.WriteLine("Fast File Copy"); Console.WriteLine(" This will copy newer and/or missing files from the source folder"); Console.WriteLine(" to the destination folder."); Console.WriteLine(" "); Console.WriteLine("Usage: fcopy -source folder[\\file|\\wildcard] -dest folder [options]"); Console.WriteLine(" (be sure to use quotes (\") to enclose paths with spaces in it)"); Console.WriteLine(" "); Console.WriteLine("general options:"); Console.WriteLine(" /verbose show detailed output"); Console.WriteLine(" /force force any changed file to be copied"); Console.WriteLine(" /pause pause when finished"); Console.WriteLine(" /test do everything but actually copying the file"); Console.WriteLine(" /reason explains why the file was copied"); Console.WriteLine(" /silent does not produce any output, overrides all others"); Console.WriteLine(" "); Console.WriteLine("filter options:"); Console.WriteLine(" -xd don't compare file date/time stamps"); Console.WriteLine(" -d compare only file date/time stamps (excludes other filters and applies /f)"); Console.WriteLine(" -xs don't compare file size"); Console.WriteLine(" -s compare only file size (excludes other filters and applies /f)"); Console.WriteLine(" -xv don't compare file version"); Console.WriteLine(" -v compare only file version (excludes other filters and applies /f)"); } } }
namespace EIDSS.Reports.Document.Lim.Case { partial class TestReport { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(TestReport)); this.DetailReportTest = new DevExpress.XtraReports.UI.DetailReportBand(); this.DetailTest = new DevExpress.XtraReports.UI.DetailBand(); this.xrTable1 = new DevExpress.XtraReports.UI.XRTable(); this.xrTableRow1 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell4 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell5 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell1 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell6 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell7 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell2 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell8 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell9 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell3 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTable2 = new DevExpress.XtraReports.UI.XRTable(); this.xrTableRow2 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell11 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTable5 = new DevExpress.XtraReports.UI.XRTable(); this.xrTableRow5 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell21 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell10 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableRow10 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell22 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell24 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell12 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell13 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell14 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell15 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell16 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell17 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell18 = new DevExpress.XtraReports.UI.XRTableCell(); this.ReportHeaderTest = new DevExpress.XtraReports.UI.ReportHeaderBand(); this.xrLabel3 = new DevExpress.XtraReports.UI.XRLabel(); this.sp_rep_LIM_CaseTestsTableAdapter1 = new EIDSS.Reports.Document.Lim.Case.CaseTestDataSetTableAdapters.spRepLimCaseTestsTableAdapter(); this.caseTestDataSet1 = new EIDSS.Reports.Document.Lim.Case.CaseTestDataSet(); this.xrTableCell20 = new DevExpress.XtraReports.UI.XRTableCell(); this.DetailReport = new DevExpress.XtraReports.UI.DetailReportBand(); this.Detail1 = new DevExpress.XtraReports.UI.DetailBand(); this.xrSubreport1 = new DevExpress.XtraReports.UI.XRSubreport(); this.testValidationReport1 = new EIDSS.Reports.Document.Lim.Case.TestValidationReport(); ((System.ComponentModel.ISupportInitialize)(this.m_BaseDataSet)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.tableBaseHeader)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.xrTable1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.xrTable2)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.xrTable5)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.caseTestDataSet1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.testValidationReport1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this)).BeginInit(); // // cellLanguage // this.cellLanguage.StylePriority.UseTextAlignment = false; // // lblReportName // resources.ApplyResources(this.lblReportName, "lblReportName"); this.lblReportName.StylePriority.UseBorders = false; this.lblReportName.StylePriority.UseBorderWidth = false; this.lblReportName.StylePriority.UseFont = false; this.lblReportName.StylePriority.UseTextAlignment = false; // // Detail // this.Detail.Expanded = false; this.Detail.StylePriority.UseFont = false; this.Detail.StylePriority.UsePadding = false; // // PageHeader // this.PageHeader.Expanded = false; this.PageHeader.StylePriority.UseFont = false; this.PageHeader.StylePriority.UsePadding = false; // // PageFooter // resources.ApplyResources(this.PageFooter, "PageFooter"); this.PageFooter.StylePriority.UseBorders = false; // // ReportHeader // resources.ApplyResources(this.ReportHeader, "ReportHeader"); // // xrPageInfo1 // resources.ApplyResources(this.xrPageInfo1, "xrPageInfo1"); this.xrPageInfo1.StylePriority.UseBorders = false; // // cellReportHeader // this.cellReportHeader.StylePriority.UseBorders = false; this.cellReportHeader.StylePriority.UseFont = false; this.cellReportHeader.StylePriority.UseTextAlignment = false; this.cellReportHeader.Weight = 2.4334737611816486; // // cellBaseSite // this.cellBaseSite.StylePriority.UseBorders = false; this.cellBaseSite.StylePriority.UseFont = false; this.cellBaseSite.StylePriority.UseTextAlignment = false; this.cellBaseSite.Weight = 2.9090210436034161; // // cellBaseCountry // this.cellBaseCountry.Weight = 1.0796091999487354; // // cellBaseLeftHeader // this.cellBaseLeftHeader.Weight = 0.90214643196245714; // // tableBaseHeader // resources.ApplyResources(this.tableBaseHeader, "tableBaseHeader"); this.tableBaseHeader.StylePriority.UseBorders = false; this.tableBaseHeader.StylePriority.UseBorderWidth = false; this.tableBaseHeader.StylePriority.UseFont = false; this.tableBaseHeader.StylePriority.UsePadding = false; this.tableBaseHeader.StylePriority.UseTextAlignment = false; // // DetailReportTest // this.DetailReportTest.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] { this.DetailTest, this.ReportHeaderTest}); this.DetailReportTest.DataAdapter = this.sp_rep_LIM_CaseTestsTableAdapter1; this.DetailReportTest.DataMember = "spRepLimCaseTests"; this.DetailReportTest.DataSource = this.caseTestDataSet1; resources.ApplyResources(this.DetailReportTest, "DetailReportTest"); this.DetailReportTest.Level = 0; this.DetailReportTest.Name = "DetailReportTest"; this.DetailReportTest.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 2, 2, 100F); // // DetailTest // this.DetailTest.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Right) | DevExpress.XtraPrinting.BorderSide.Bottom))); this.DetailTest.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] { this.xrTable1, this.xrTable2}); resources.ApplyResources(this.DetailTest, "DetailTest"); this.DetailTest.Name = "DetailTest"; this.DetailTest.StylePriority.UseBorders = false; this.DetailTest.StylePriority.UseTextAlignment = false; // // xrTable1 // this.xrTable1.Borders = ((DevExpress.XtraPrinting.BorderSide)((((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top) | DevExpress.XtraPrinting.BorderSide.Right) | DevExpress.XtraPrinting.BorderSide.Bottom))); resources.ApplyResources(this.xrTable1, "xrTable1"); this.xrTable1.Name = "xrTable1"; this.xrTable1.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] { this.xrTableRow1}); this.xrTable1.StylePriority.UseBorders = false; // // xrTableRow1 // this.xrTableRow1.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell4, this.xrTableCell5, this.xrTableCell1, this.xrTableCell6, this.xrTableCell7, this.xrTableCell2, this.xrTableCell8, this.xrTableCell9, this.xrTableCell3}); this.xrTableRow1.Name = "xrTableRow1"; this.xrTableRow1.Weight = 2.5399999999999996; // // xrTableCell4 // this.xrTableCell4.Multiline = true; this.xrTableCell4.Name = "xrTableCell4"; resources.ApplyResources(this.xrTableCell4, "xrTableCell4"); this.xrTableCell4.Weight = 0.34612796684408575; this.xrTableCell4.BeforePrint += new System.Drawing.Printing.PrintEventHandler(this.xrTableCell4_BeforePrint); // // xrTableCell5 // this.xrTableCell5.Name = "xrTableCell5"; resources.ApplyResources(this.xrTableCell5, "xrTableCell5"); this.xrTableCell5.Weight = 0.34612807612816132; // // xrTableCell1 // this.xrTableCell1.Name = "xrTableCell1"; resources.ApplyResources(this.xrTableCell1, "xrTableCell1"); this.xrTableCell1.Weight = 0.33460161145926587; // // xrTableCell6 // this.xrTableCell6.Name = "xrTableCell6"; resources.ApplyResources(this.xrTableCell6, "xrTableCell6"); this.xrTableCell6.Weight = 0.33616830796777081; // // xrTableCell7 // this.xrTableCell7.Name = "xrTableCell7"; resources.ApplyResources(this.xrTableCell7, "xrTableCell7"); this.xrTableCell7.Weight = 0.26745747538048342; // // xrTableCell2 // this.xrTableCell2.Name = "xrTableCell2"; resources.ApplyResources(this.xrTableCell2, "xrTableCell2"); this.xrTableCell2.Weight = 0.33460161145926587; // // xrTableCell8 // this.xrTableCell8.Name = "xrTableCell8"; resources.ApplyResources(this.xrTableCell8, "xrTableCell8"); this.xrTableCell8.Weight = 0.33616830796777081; // // xrTableCell9 // this.xrTableCell9.Name = "xrTableCell9"; resources.ApplyResources(this.xrTableCell9, "xrTableCell9"); this.xrTableCell9.Weight = 0.2688003581020591; // // xrTableCell3 // this.xrTableCell3.Name = "xrTableCell3"; resources.ApplyResources(this.xrTableCell3, "xrTableCell3"); this.xrTableCell3.Weight = 0.42994628469113705; // // xrTable2 // this.xrTable2.Borders = ((DevExpress.XtraPrinting.BorderSide)((((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top) | DevExpress.XtraPrinting.BorderSide.Right) | DevExpress.XtraPrinting.BorderSide.Bottom))); resources.ApplyResources(this.xrTable2, "xrTable2"); this.xrTable2.Name = "xrTable2"; this.xrTable2.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] { this.xrTableRow2}); this.xrTable2.StylePriority.UseBorders = false; // // xrTableRow2 // this.xrTableRow2.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell11, this.xrTableCell12, this.xrTableCell13, this.xrTableCell14, this.xrTableCell15, this.xrTableCell16, this.xrTableCell17, this.xrTableCell18}); this.xrTableRow2.Name = "xrTableRow2"; this.xrTableRow2.Weight = 1.3399999999999999; // // xrTableCell11 // this.xrTableCell11.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] { this.xrTable5}); this.xrTableCell11.Name = "xrTableCell11"; this.xrTableCell11.Weight = 0.69225604297224708; // // xrTable5 // this.xrTable5.Borders = DevExpress.XtraPrinting.BorderSide.None; resources.ApplyResources(this.xrTable5, "xrTable5"); this.xrTable5.Name = "xrTable5"; this.xrTable5.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] { this.xrTableRow5, this.xrTableRow10}); this.xrTable5.StylePriority.UseBorders = false; // // xrTableRow5 // this.xrTableRow5.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell21, this.xrTableCell10}); this.xrTableRow5.Name = "xrTableRow5"; this.xrTableRow5.Weight = 1; // // xrTableCell21 // this.xrTableCell21.Borders = ((DevExpress.XtraPrinting.BorderSide)((DevExpress.XtraPrinting.BorderSide.Right | DevExpress.XtraPrinting.BorderSide.Bottom))); this.xrTableCell21.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepLimCaseTests.strFieldBarcode")}); this.xrTableCell21.Name = "xrTableCell21"; this.xrTableCell21.StylePriority.UseBorders = false; resources.ApplyResources(this.xrTableCell21, "xrTableCell21"); this.xrTableCell21.Weight = 1.5; // // xrTableCell10 // this.xrTableCell10.Borders = ((DevExpress.XtraPrinting.BorderSide)((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Bottom))); this.xrTableCell10.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepLimCaseTests.SpecimenType")}); this.xrTableCell10.Name = "xrTableCell10"; this.xrTableCell10.StylePriority.UseBorders = false; resources.ApplyResources(this.xrTableCell10, "xrTableCell10"); this.xrTableCell10.Weight = 1.5; // // xrTableRow10 // this.xrTableRow10.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell22, this.xrTableCell24}); this.xrTableRow10.Name = "xrTableRow10"; this.xrTableRow10.Weight = 1; // // xrTableCell22 // this.xrTableCell22.Borders = DevExpress.XtraPrinting.BorderSide.Right; this.xrTableCell22.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepLimCaseTests.LabBarcode")}); this.xrTableCell22.Name = "xrTableCell22"; this.xrTableCell22.StylePriority.UseBorders = false; resources.ApplyResources(this.xrTableCell22, "xrTableCell22"); this.xrTableCell22.Weight = 1.5; // // xrTableCell24 // this.xrTableCell24.Borders = DevExpress.XtraPrinting.BorderSide.Left; this.xrTableCell24.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepLimCaseTests.AnimalName")}); this.xrTableCell24.Name = "xrTableCell24"; this.xrTableCell24.StylePriority.UseBorders = false; resources.ApplyResources(this.xrTableCell24, "xrTableCell24"); this.xrTableCell24.Weight = 1.5; // // xrTableCell12 // this.xrTableCell12.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepLimCaseTests.TestName")}); this.xrTableCell12.Name = "xrTableCell12"; this.xrTableCell12.Weight = 0.33460161145926587; // // xrTableCell13 // this.xrTableCell13.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepLimCaseTests.TestRunID")}); this.xrTableCell13.Name = "xrTableCell13"; this.xrTableCell13.Weight = 0.33616830796777081; // // xrTableCell14 // this.xrTableCell14.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepLimCaseTests.DateTested", "{0:dd/MM/yyyy}")}); this.xrTableCell14.Name = "xrTableCell14"; this.xrTableCell14.Weight = 0.26745747538048342; // // xrTableCell15 // this.xrTableCell15.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepLimCaseTests.FunctionalArea")}); this.xrTableCell15.Name = "xrTableCell15"; this.xrTableCell15.Weight = 0.33460161145926587; // // xrTableCell16 // this.xrTableCell16.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepLimCaseTests.TestType")}); this.xrTableCell16.Name = "xrTableCell16"; this.xrTableCell16.Weight = 0.33616830796777081; // // xrTableCell17 // this.xrTableCell17.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepLimCaseTests.TestStatus")}); this.xrTableCell17.Name = "xrTableCell17"; this.xrTableCell17.Weight = 0.2688003581020591; // // xrTableCell18 // this.xrTableCell18.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepLimCaseTests.TestResult")}); this.xrTableCell18.Name = "xrTableCell18"; this.xrTableCell18.Weight = 0.42994628469113705; // // ReportHeaderTest // this.ReportHeaderTest.Borders = ((DevExpress.XtraPrinting.BorderSide)((((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top) | DevExpress.XtraPrinting.BorderSide.Right) | DevExpress.XtraPrinting.BorderSide.Bottom))); this.ReportHeaderTest.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] { this.xrLabel3}); resources.ApplyResources(this.ReportHeaderTest, "ReportHeaderTest"); this.ReportHeaderTest.Name = "ReportHeaderTest"; this.ReportHeaderTest.StylePriority.UseBorders = false; this.ReportHeaderTest.StylePriority.UseFont = false; this.ReportHeaderTest.StylePriority.UseTextAlignment = false; // // xrLabel3 // this.xrLabel3.Borders = DevExpress.XtraPrinting.BorderSide.Bottom; resources.ApplyResources(this.xrLabel3, "xrLabel3"); this.xrLabel3.Name = "xrLabel3"; this.xrLabel3.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F); this.xrLabel3.StylePriority.UseBorders = false; this.xrLabel3.StylePriority.UseFont = false; this.xrLabel3.StylePriority.UseTextAlignment = false; // // sp_rep_LIM_CaseTestsTableAdapter1 // this.sp_rep_LIM_CaseTestsTableAdapter1.ClearBeforeFill = true; // // caseTestDataSet1 // this.caseTestDataSet1.DataSetName = "CaseTestDataSet"; this.caseTestDataSet1.SchemaSerializationMode = System.Data.SchemaSerializationMode.IncludeSchema; // // xrTableCell20 // this.xrTableCell20.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepLimCaseTests.LabBarcode")}); this.xrTableCell20.Name = "xrTableCell20"; this.xrTableCell20.Weight = 3; // // DetailReport // this.DetailReport.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] { this.Detail1}); this.DetailReport.Level = 1; this.DetailReport.Name = "DetailReport"; // // Detail1 // this.Detail1.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] { this.xrSubreport1}); resources.ApplyResources(this.Detail1, "Detail1"); this.Detail1.Name = "Detail1"; this.Detail1.PageBreak = DevExpress.XtraReports.UI.PageBreak.BeforeBand; // // xrSubreport1 // resources.ApplyResources(this.xrSubreport1, "xrSubreport1"); this.xrSubreport1.Name = "xrSubreport1"; this.xrSubreport1.ReportSource = this.testValidationReport1; // // TestReport // this.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] { this.Detail, this.PageHeader, this.PageFooter, this.ReportHeader, this.DetailReportTest, this.DetailReport}); this.ExportOptions.Xls.SheetName = resources.GetString("TestReport.ExportOptions.Xls.SheetName"); this.ExportOptions.Xlsx.SheetName = resources.GetString("TestReport.ExportOptions.Xlsx.SheetName"); this.Landscape = true; this.PageHeight = 827; this.PageWidth = 1169; this.Version = "10.1"; this.Controls.SetChildIndex(this.DetailReport, 0); this.Controls.SetChildIndex(this.DetailReportTest, 0); this.Controls.SetChildIndex(this.ReportHeader, 0); this.Controls.SetChildIndex(this.PageFooter, 0); this.Controls.SetChildIndex(this.PageHeader, 0); this.Controls.SetChildIndex(this.Detail, 0); ((System.ComponentModel.ISupportInitialize)(this.m_BaseDataSet)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.tableBaseHeader)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.xrTable1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.xrTable2)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.xrTable5)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.caseTestDataSet1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.testValidationReport1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this)).EndInit(); } #endregion private DevExpress.XtraReports.UI.DetailReportBand DetailReportTest; private DevExpress.XtraReports.UI.DetailBand DetailTest; private DevExpress.XtraReports.UI.ReportHeaderBand ReportHeaderTest; private CaseTestDataSet caseTestDataSet1; private CaseTestDataSetTableAdapters.spRepLimCaseTestsTableAdapter sp_rep_LIM_CaseTestsTableAdapter1; private DevExpress.XtraReports.UI.XRLabel xrLabel3; private DevExpress.XtraReports.UI.XRTable xrTable1; private DevExpress.XtraReports.UI.XRTableRow xrTableRow1; private DevExpress.XtraReports.UI.XRTableCell xrTableCell4; private DevExpress.XtraReports.UI.XRTableCell xrTableCell5; private DevExpress.XtraReports.UI.XRTableCell xrTableCell1; private DevExpress.XtraReports.UI.XRTableCell xrTableCell6; private DevExpress.XtraReports.UI.XRTableCell xrTableCell7; private DevExpress.XtraReports.UI.XRTableCell xrTableCell2; private DevExpress.XtraReports.UI.XRTableCell xrTableCell8; private DevExpress.XtraReports.UI.XRTableCell xrTableCell9; private DevExpress.XtraReports.UI.XRTableCell xrTableCell3; private DevExpress.XtraReports.UI.XRTable xrTable2; private DevExpress.XtraReports.UI.XRTableRow xrTableRow2; private DevExpress.XtraReports.UI.XRTableCell xrTableCell11; private DevExpress.XtraReports.UI.XRTableCell xrTableCell12; private DevExpress.XtraReports.UI.XRTableCell xrTableCell13; private DevExpress.XtraReports.UI.XRTableCell xrTableCell14; private DevExpress.XtraReports.UI.XRTableCell xrTableCell15; private DevExpress.XtraReports.UI.XRTableCell xrTableCell16; private DevExpress.XtraReports.UI.XRTableCell xrTableCell17; private DevExpress.XtraReports.UI.XRTableCell xrTableCell18; private DevExpress.XtraReports.UI.XRTableCell xrTableCell20; private DevExpress.XtraReports.UI.XRTable xrTable5; private DevExpress.XtraReports.UI.XRTableRow xrTableRow5; private DevExpress.XtraReports.UI.XRTableCell xrTableCell21; private DevExpress.XtraReports.UI.XRTableRow xrTableRow10; private DevExpress.XtraReports.UI.XRTableCell xrTableCell22; private DevExpress.XtraReports.UI.DetailReportBand DetailReport; private DevExpress.XtraReports.UI.DetailBand Detail1; private DevExpress.XtraReports.UI.XRSubreport xrSubreport1; private TestValidationReport testValidationReport1; private DevExpress.XtraReports.UI.XRTableCell xrTableCell10; private DevExpress.XtraReports.UI.XRTableCell xrTableCell24; } }
using System; using System.Linq; using GeneticSharp.Domain.Chromosomes; using System.Collections.Generic; using GeneticSharp.Domain.Randomizations; namespace GeneticSharp.Domain.Crossovers { /// <summary> /// Synapsing Variable Length Crossover /// </summary> public class SVLC : CrossoverBase { #pragma warning disable 162 private bool _debugging = false; private System.Diagnostics.Stopwatch timer = new System.Diagnostics.Stopwatch(); private const int MinimumCommonLength = 10; private const int MaxNumCommonParts = 5; private const int MinimumCrossoverPoints = 2; private const int MaximumCrossoverPoints = 5; private List<int[]> CommonParts; /// <summary> /// Initializes a new instance of the <see cref="GeneticSharp.Domain.Crossovers.SVLC"/> class. /// </summary> /// <param name="parentsNumber">Parents number.</param> /// <param name="childrenNumber">Children number.</param> public SVLC(int parentsNumber, int childrenNumber) : base(parentsNumber, childrenNumber) { } /// <summary> /// Performs the cross with specified parents generating the children. /// </summary> /// <param name="parents">The parents chromosomes.</param> /// <returns>The offspring (children) of the parents.</returns> protected override IList<IChromosome> PerformCross(IList<IChromosome> parents) { if (_debugging) { Console.WriteLine ("Performing SVLC on {0} parents", parents.Count); if(parents.Count == 2) Console.WriteLine ("Getting synapsing parts on parent lengths: {0} {1}", parents[0].Length, parents[1].Length); timer.Start (); } List<IChromosome> children = new List<IChromosome>(); // Find LCSS of at least n length CommonParts = GetSynapsingParts(parents); if (_debugging) { Console.WriteLine ("Got {0} synapsing parts. Took {1}", CommonParts.Count, timer.Elapsed); timer.Stop (); } if(CommonParts.Count == 0) { // No LCSS found - what then? //return parents; if (_debugging) { Console.WriteLine ("# parents: {0}", parents.Count); if(parents.Count == 2) { Console.Write("p0 ({0}) : ", parents [0].Length); foreach(Gene _g in parents[0].GetGenes()) { List<int> _gl = _g.Value as List<int>; if(_gl == null) Console.Write("{0} ", _g.Value); else _gl.ForEach(h => Console.Write("|{0}",h)); } Console.WriteLine (" "); Console.Write("p1 ({0})", parents [1].Length); foreach(Gene _g in parents[1].GetGenes()) { List<int> _gl = _g.Value as List<int>; if(_gl == null) Console.Write("{0} ", _g.Value); else _gl.ForEach(h => Console.Write("|{0}",h)); } Console.WriteLine (" "); } } int randomLength = MinimumCommonLength; if (MinimumCommonLength >= Math.Min (parents [0].Length, parents [1].Length)) { randomLength = 1; } int rpoint1 = RandomizationProvider.Current.GetInt (0, parents [0].Length - randomLength - 1); int rpoint2 = RandomizationProvider.Current.GetInt (0, parents [1].Length - randomLength - 1); int[] rs = new int[3]; rs [0] = randomLength; rs [1] = rpoint1; rs [2] = rpoint2; CommonParts.Add (rs); // Generate X random crossover points //int cpoints = RandomizationProvider.Current.GetInt(MinimumCrossoverPoints, MaximumCrossoverPoints); //for (int i = 0; i < cpoints; i++) { // //} if(_debugging) Console.WriteLine("Found no synapsing parts. Added |l:{0},i:{1},o:{2}|", randomLength, rpoint1, rpoint2); } if (CommonParts.Count > MaxNumCommonParts) { if (_debugging) { Console.WriteLine ("More common parts than maximum. What do?"); } // remove from smallest parts //List<int[]> sorted = CommonParts.Sort( while (CommonParts.Count > MaxNumCommonParts) { int rand = RandomizationProvider.Current.GetInt (0, CommonParts.Count - 1); CommonParts.RemoveAt (rand); } } // Select n random points // order by length and choose those more often? Choose all? // Number of children (yah, it's a crapload.... :S ) int listSize = (int) Math.Pow(2, CommonParts.Count + 1); if (_debugging) Console.WriteLine ("Creating {0} children", listSize); for( int i = 0; i < listSize; i++) { // 0 and listSize are 00000 and 11111 meaning exact copies // // // Create offspring #i IChromosome offspring = CreateOffspring(parents[0], parents[1], i); // Check if it equals parents? will it ever? // Add to children if(offspring != null) children.Add(offspring); } // min pop size // while (children.Count < 10) { // children.Add (parents [RandomizationProvider.Current.GetInt (0, parents.Count - 1)]); // } if (_debugging) Console.WriteLine ("SVLC returning {0} children", children.Count); return children; } private IChromosome CreateOffspring(IChromosome p1, IChromosome p2, int bitPattern) { // LSB signifies which parent the first variable part comes from // 0 = p1, 1 = p2 // Shift right and continue, n+1 times // Return resulting chromosome Gene[] p1_genes = p1.GetGenes(); Gene[] p2_genes = p2.GetGenes(); List<Gene> child = new List<Gene>(); if (_debugging && false) { Console.WriteLine ("creating offspring from parents. Bitpattern: {0}", bitPattern); } // Copy the correct parts from either parent into child for(int i = 0; i <= CommonParts.Count; i++) { // indices where we cut (crossover points) int index_1; int index_2; // Is LSB 1? if((bitPattern & 1) > 0) { // Take from p2 if(i == 0) { // at start // Copy from 0 to first synapsing parts index_1 = 0; // First item in non-synapsing part } else { //end of last synapsing part + 1 = fist item in non-synapsing part index_1 = CommonParts[i-1][2] + 1; if (index_1 >= p2_genes.GetLength(0)) { // We're done here, no more genes to add break; } } if (i < CommonParts.Count) { // First item in synapsing part index_2 = Math.Max(CommonParts[i][2] - CommonParts[i][0] + 1,0); } else { // We're beyond the list of common parts, copy till end index_2 = p2_genes.GetLength(0); } // Get slice of p2 ArraySegment<Gene> a = new ArraySegment<Gene> (p2_genes, index_1, index_2 - index_1); // Put it into a list List<Gene> tl = new List<Gene>(); foreach (Gene _g in a.Array) { tl.Add (_g); } // Add them to the child child.AddRange (tl); if (_debugging && false) { Console.Write ("Added to child ({0},{1}):", index_1, index_2 - index_1); foreach(Gene _g in tl) { List<int> _gl = _g.Value as List<int>; if(_gl == null) Console.Write("{0} ", _g.Value); else _gl.ForEach(h => Console.Write("|{0}",h)); } Console.WriteLine (" "); } } else { // Take from p1 if(i == 0) { // at start // Copy from 0 to first synapsing parts index_1 = 0; // First item in non-synapsing part } else { //end of last synapsing part + 1 = fist item in non-synapsing part index_1 = CommonParts[i-1][1] + 1; if (index_1 >= p1_genes.GetLength(0)) { // We're done here, no more genes to add break; } } if (i < CommonParts.Count) { // First item in synapsing part index_2 = Math.Max(CommonParts[i][1] - CommonParts[i][0] + 1,0); } else { // We're beyond the list of common parts, copy till end index_2 = p1_genes.GetLength(0); } // Get slice of p1 ArraySegment<Gene> a = new ArraySegment<Gene> (p1_genes, index_1, index_2 - index_1); // Put it into a list List<Gene> tl = new List<Gene>(); foreach (Gene _g in a.Array) { tl.Add (_g); } // Add them to the child child.AddRange (tl); if (_debugging && false) { Console.Write ("Added to child ({0},{1}):", index_1, index_2 - index_1); foreach(Gene _g in tl) { List<int> _gl = _g.Value as List<int>; if(_gl == null) Console.Write("{0} ", _g.Value); else _gl.ForEach(h => Console.Write("|{0}",h)); } Console.WriteLine (" "); } } // shift pattern right bitPattern = bitPattern >> 1; if (_debugging && false) { Console.Write("Child so far:"); foreach(Gene _g in child) { List<int> _gl = _g.Value as List<int>; if(_gl == null) Console.Write("{0} ", _g.Value); else _gl.ForEach(h => Console.Write("|{0}",h)); } Console.WriteLine (" "); } } if (child.Count < 2) return null; // Create chromosomes from genes IChromosome rchild = p1.CreateNew(); if (child.Count < 2 && _debugging) { Console.WriteLine ("About to break. Added this as bp"); } rchild.Resize(child.Count); rchild.ReplaceGenes(0, child.ToArray()); return rchild; } private List<int[]> GetSynapsingParts( IList<IChromosome> parents) { if (_debugging) { Console.WriteLine ("Creating LCSS table"); } // Calculate common substring var table = LCSSTable(parents); if (_debugging) { Console.WriteLine ("Getting synapsing parts from LCSS table"); } // Extract, recursively, the locations (in both parent 0 and parent 1) and lengths {len, loc 0, loc 1} var parts = SynapsingParts(table); if (_debugging) { Console.WriteLine ("Got synapsing parts!"); } return parts; } // Calculate table used for finding longest common substring private int[,] LCSSTable(IList<IChromosome> parents) { int[,] table = new int[parents[0].Length, parents[1].Length]; for(int i = 0; i < parents[0].Length; i++) { for(int o = 0; o < parents[1].Length; o++) { if(parents[0].GetGene(i) != parents[1].GetGene(o)) { table[i,o] = 0; } else { if(i == 0 || o == 0) { table[i,o] = 0; } else { table[i,o] = 1 + table[i-1,o-1]; } } } } return table; } // Recursive function to find similar parts. Returns list // ordered so the first parts are first in the last private List<int[]> SynapsingParts( int[,] Table) { int maxI = 0; int maxO = 0; int maxLen = 0; List<int[]> results = new List<int[]>(); for(int i = 0; i < Table.GetLength(0); i++) { for(int o = 0; o < Table.GetLength(1); o++) { // correct value, so it holds true for subtables too var tValue = Math.Min (Table [i, o], Math.Min (i, o) + 1); if(tValue > maxLen) { maxLen = tValue; maxI = i; maxO = o; } } } if(maxLen > MinimumCommonLength) { int LTSize_i = maxI - maxLen + 1; int LTSize_o = maxO - maxLen + 1; // Check if Left side is big enough for recursion if(LTSize_i >= MinimumCommonLength && LTSize_o >= MinimumCommonLength) { // Copy top-left part of table int[,] leftTable = new int[LTSize_i, LTSize_o]; for(int i = 0; i < LTSize_i; i++) { for(int o = 0; o < LTSize_o; o++) { leftTable[i,o] = Table[i,o]; } } // Append recursively results.AddRange(SynapsingParts(leftTable)); } // Add the longest part from the "middle" results.Add(new int[3] {maxLen, maxI, maxO}); // Check if Right side is big enough for recursion int RTSize_i = Table.GetLength(0) - maxI - 1; int RTSize_o = Table.GetLength (1) - maxO - 1; if(RTSize_i >= MinimumCommonLength && RTSize_o >= MinimumCommonLength) { // Copy bottom-right part of table int[,] rightTable = new int[RTSize_i,RTSize_o]; for(int i = 0; i < RTSize_i; i++) { for(int o = 0; o < RTSize_o; o++) { try { rightTable[i,o] = Table[maxI + i + 1,maxO + o + 1]; } catch{ Console.WriteLine ("Broke. This is a bp"); }; } } // Append recursively - correct to fit within this table coordinae var RTableResults = SynapsingParts(rightTable); foreach (var RTres in RTableResults) { //RTres[0] = .. same RTres [1] += maxI + 1; // RTable pos + the range up till that (same as loop above) RTres [2] += maxO + 1; // ---- || ---- } results.AddRange(RTableResults); } } return results; } } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: AddInController ** ** Purpose: Allows you to shut down an add-in, which may unload ** an AppDomain or kill an out-of-process add-in. ** ===========================================================*/ using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using System.Reflection; using System.Runtime.ConstrainedExecution; using System.Runtime.Remoting; using System.Runtime.Remoting.Lifetime; using System.Runtime.Serialization; using System.Security.Permissions; using System.Security; using System.Diagnostics; using System.AddIn.Contract; using System.AddIn.Pipeline; using System.Diagnostics.Contracts; namespace System.AddIn.Hosting { // The lifetime of an add-in is controlled by remoting's leases, and users // who do essentially ref counting by obtaining a lease. No one has solved // the distributed (cross-machine) garbage collector problem yet, but leases // appear to be the best approximation we currently have. internal sealed class AddInControllerImpl { // Maps host add-in views (precisely, instances of host adapters typed // as their base type) to the associated add-in controllers. private static HAVControllerPair _havList; private static readonly Object _havLock = new Object(); //private AppDomain _appDomain; private bool _unloadDomainOnExit; private AddInToken _token; private AddInEnvironment _addInEnvironment; private static int _addInCountSinceLastPrune; private const int AddInCountSinceLastPruneLimit = 25; // Note that keeping this reference to the transparentProxy // prevents it from being GC'd in the same sweep as the HAV. Indeed, it cannot // be GC'd until we remove its HAVController pair. This is good, // since it allows us to call into the TransparentProxy from the finalize method // of LifetimeTokenHandle internal IContract _contract; // Contract or a Transparent Proxy to the contract private ActivationWorker _activationWorker; private WeakReference _havReference; internal AddInControllerImpl(AddInEnvironment environment, bool unloadDomainOnExit, AddInToken token) { System.Diagnostics.Contracts.Contract.Requires(environment != null); System.Diagnostics.Contracts.Contract.Requires(token != null); _unloadDomainOnExit = unloadDomainOnExit; _token = token; _addInEnvironment = environment; } // Takes a host add-in view (HAV) and maps that to an add-in controller. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] internal static AddInController GetAddInController(Object addIn) { if (addIn == null) throw new ArgumentNullException("addIn"); System.Diagnostics.Contracts.Contract.EndContractBlock(); AddInControllerImpl controllerImpl = FindController(addIn, false); //return new wrapper if (controllerImpl != null) { // Try and increase the ref count on the addin. If we fail, perhaps // because the user already called Dispose() on the HVA, that's OK. Still allow // them to use the AddInController to examine the AddInToken ContractHandle handle = null; try { handle = new ContractHandle(controllerImpl._contract); } catch (Exception) {} return new AddInController(controllerImpl, addIn, handle); } throw new ArgumentException(Res.ControllerNotFound); } // Find the controller given the HAV (addIn), optionally also removing it. // This code also removes any stale HAVControllerPairs that it finds, as // may happen when a HAV is garbage collected. private static AddInControllerImpl FindController(Object addIn, bool remove) { System.Diagnostics.Contracts.Contract.Requires(addIn != null); lock (_havLock) { HAVControllerPair current = _havList; HAVControllerPair last = null; while(current != null) { Object o = current._HAV.Target; if (o == null) { // this one has been GC'd. Clean up the WR if (last == null) { _havList = current._next; continue; } else { last._next = current._next; current = current._next; continue; } } else { if (addIn.Equals(o)) { AddInControllerImpl value = current._controller; if (remove) { if (last == null) _havList = current._next; else last._next = current._next; } return value; } } last = current; current = current._next; } } return null; } // Requires the HAV and the transparent proxy to the add-in adapter, // which implements System.AddIn.Contract.IContract. internal void AssociateWithHostAddinView(Object hostAddinView, IContract contract) { System.Diagnostics.Contracts.Contract.Requires(hostAddinView != null); _contract = contract; // add weak reference on the HAV to our list _havReference = new WeakReference(hostAddinView); lock (_havLock) { HAVControllerPair havRef = new HAVControllerPair(hostAddinView, this); havRef._next = _havList; _havList = havRef; // clean up the list every so often _addInCountSinceLastPrune++; if (_addInCountSinceLastPrune == AddInCountSinceLastPruneLimit) { // searching for a non-exiting addin will have the desired effect // of pruning the list of any stale references. FindController(new Object(), false); _addInCountSinceLastPrune = 0; } } } internal ActivationWorker ActivationWorker { set { System.Diagnostics.Contracts.Contract.Requires(value != null); _activationWorker = value; } } //<SecurityKernel Critical="True" Ring="0"> //<ReferencesCritical Name="Method: ActivationWorker.CreateAddInAdapter(System.Object,System.Reflection.Assembly):System.AddIn.Contract.IContract" Ring="1" /> //<Asserts Name="Imperative: System.Security.PermissionSet" /> //</SecurityKernel> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2103:ReviewImperativeSecurity", Justification = "Reviewed"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2001:AvoidCallingProblematicMethods", MessageId = "System.Reflection.Assembly.LoadFrom", Justification = "LoadFrom was designed for addins")] [System.Security.SecuritySafeCritical] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2128:SecurityTransparentCodeShouldNotAssert", Justification = "This is a SecurityRules.Level1 assembly, in which this rule is being incorrectly applied")] internal IContract GetContract() { if (_contract != null) return _contract; // in direct connect, the contract has not been created. Create it now. Object hav = _havReference.Target; if (hav == null) throw new InvalidOperationException(Res.AddInNoLongerAvailable); // Assert permission to the contracts, AddInSideAdapters, AddInViews and specific Addin directories only. PermissionSet permissionSet = new PermissionSet(PermissionState.None); permissionSet.AddPermission(new FileIOPermission(FileIOPermissionAccess.Read | FileIOPermissionAccess.PathDiscovery, Path.Combine(_token.PipelineRootDirectory, AddInStore.ContractsDirName))); permissionSet.AddPermission(new FileIOPermission(FileIOPermissionAccess.Read | FileIOPermissionAccess.PathDiscovery, Path.Combine(_token.PipelineRootDirectory, AddInStore.AddInAdaptersDirName))); permissionSet.Assert(); Assembly.LoadFrom(_token._contract.Location); Assembly addinAdapterAssembly = Assembly.LoadFrom(_token._addinAdapter.Location); CodeAccessPermission.RevertAssert(); // Create the AddIn adapter for the addin ActivationWorker worker = new ActivationWorker(_token); _contract = worker.CreateAddInAdapter(hav, addinAdapterAssembly); return _contract; } // <SecurityKernel Critical="True" Ring="1"> // <ReferencesCritical Name="Method: ActivationWorker.Dispose():System.Void" Ring="1" /> // </SecurityKernel> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2001:AvoidCallingProblematicMethods", MessageId = "System.GC.Collect", Justification = "Recommended by GC team")] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] public void Shutdown() { // Disables usage of the add-in, by breaking the pipeline. // Also, if we own the appdomain, we unload it. lock (this) // Ensure multiple threads racing on Shutdown don't collide. { AddInEnvironment environment = _addInEnvironment; if (environment != null) { try { if (_contract != null) { Object hav = _havReference.Target; IDisposable disposableHAV = hav as IDisposable; if (disposableHAV != null) { try { disposableHAV.Dispose(); } catch (AppDomainUnloadedException e) { Log(e.ToString()); } catch (RemotingException re) { Log(re.ToString()); } catch (SerializationException se) { Log(se.ToString()); } } IDisposable disposableContract = _contract as IDisposable; if (disposableContract != null) { try { disposableContract.Dispose(); } catch (AppDomainUnloadedException e) { Log(e.ToString()); } catch (RemotingException re) { Log(re.ToString()); } catch (SerializationException se) { Log(se.ToString()); } } _contract = null; } if (_activationWorker != null) { // Unhook an assembly resolve event in the target appdomain. // However, if one of the adapters implemented IDisposable and cleaned // up the appropriate lifetime tokens, this appdomain may be unloading // already (we launch another thread to do this, so we are guaranteed // to have a benign race condition). We should catch an // AppDomainUnloadedException here. try { _activationWorker.Dispose(); } catch (AppDomainUnloadedException) { } catch (RemotingException) { } catch (SerializationException) { } _activationWorker = null; } } finally { if (_unloadDomainOnExit) { // AppDomain.Unload will block until we have finalized all // objects within the appdomain. Also, this may already // have been unloaded. try { environment.UnloadAppDomain(); } catch (AppDomainUnloadedException) { } catch (RemotingException) { } // Using the transparent proxy will now cause exceptions, // as managed threads are not allowed to enter this appdomain. } } _addInEnvironment = null; // eagerly remove from list lock (_havLock) { Object addin = _havReference.Target; if (addin != null) FindController(addin, true); } // The perf team recommends doing a GC after a large amount of memory has // been dereferenced. We wait for the finalizers to complete first // becase some references in the addin are not released until finalization. // Also, if an addin is buggy and causes the finalizer thread to hang, // waiting here makes it fail deterministically. System.GC.WaitForPendingFinalizers(); System.GC.Collect(); } // end if domain != null else { throw new InvalidOperationException(Res.AppDomainNull); } } } // This will not be usable for OOP scenarios. internal AppDomain AppDomain { get { if (_addInEnvironment == null) throw new ObjectDisposedException("appdomain"); return _addInEnvironment.AppDomain; } } internal AddInToken Token { get { return _token; } } internal AddInEnvironment AddInEnvironment { get { return _addInEnvironment; } } private static void Log(String message) { Debugger.Log(0, "AddInController", message); } internal sealed class HAVControllerPair { internal WeakReference _HAV; internal AddInControllerImpl _controller; internal HAVControllerPair _next; public HAVControllerPair(Object hav, AddInControllerImpl controller) { _HAV = new WeakReference(hav); _controller = controller; } } } }
using System; using System.IO; using System.Text; using System.Collections; using System.Xml; using System.Diagnostics; class Script { static string htmlDir = @"../"; static string helpTitle = ""; static string firstTopicFile = ""; const string usage = "Usage: csc update [/t:title] [/c:<HH content file>] [/nw]...\n"+ "Converts HTML Help Workshop project (.hhp) to HTML Help.\n"+ "Project has to be located one level above in the directory tree with respect to location of the update.cs script.\n"+ "title - optional title for the Oline Help page\n"+ "/c - optional .hhc (content) file to parse. By default the very first .hhc file found is used.\n"+ "/nw - 'no wait' mode"; [STAThread] static public void Main(string[] args) { if (args.Length == 1 && (args[0] == "?" || args[0] == "/?" || args[0] == "-?" || args[0].ToLower() == "help")) { Console.WriteLine(usage); } else { bool wait = true; try { //prepare input data string contentFile = ""; foreach (string arg in args) { if (arg.StartsWith("/t")) helpTitle = arg.Substring(3); else if (arg.StartsWith("/c")) contentFile = arg.Substring(3); else if (arg.ToLower() == "/nw") wait = false; } if (contentFile == "") { string[] files = Directory.GetFiles(htmlDir, "*.hhc"); if (files.Length == 0) { Console.WriteLine("Cannot find any *.hhc file"); return; } contentFile = files[0]; } if (helpTitle == "") helpTitle = Path.GetFileNameWithoutExtension(contentFile)+" Online Help"; //parse content file Console.WriteLine("Parsing "+contentFile+"..."); ArrayList items = ParseHHC(contentFile); //prepare content.html using (StreamWriter sw = new StreamWriter("contents.html")) { sw.Write(contentTemplate.Replace("HHP2HTML_TREE", ComposeHTMLTree(items))); } //prepare index.html using (StreamWriter sw = new StreamWriter("index.html")) { sw.Write(indexTemplate.Replace("HHP2HTML_DEFAULT_TOPIC", firstTopicFile).Replace("HHP2HTML_TITLE", helpTitle)); } //prepare indexNoFrame.html using (StreamWriter sw = new StreamWriter("indexNoFrame.html")) { sw.Write(indexNoFrameTemplate.Replace("HHP2HTML_TITLE", helpTitle).Replace("HHP2HTML_NO_FRAME_TREE", ComposeHTMLNoFrameTree(items))); } Console.WriteLine("'"+helpTitle+"' has been prepared: "+Path.GetFullPath("index.html")+"\n"); Process.Start(Path.GetFullPath("index.html")); } catch (Exception e) { Console.WriteLine(e); } if (wait) { Console.WriteLine("Press Enter to continue..."); Console.ReadLine(); } } } static string Multiply(string str, int times) { string retval = ""; for(int i = 0; i < times; i++) { retval += str; } return retval; } static string ComposeHTMLTree(ArrayList items) { string htmlItemLink = "\t<img src=\"treenodeplus.gif\" class=\"treeLinkImage\" onclick=\"expandCollapse(this.parentNode)\" />"+ "\t<a href=\"HHP2HTML_FILE\" target=\"main\" class=\"treeUnselected\" onclick=\"clickAnchor(this)\">HHP2HTML_NAME</a>\n"; string htmlItem = "\t<img src=\"treenodedot.gif\" class=\"treeNoLinkImage\" />"+ "<a href=\"HHP2HTML_FILE\" target=\"main\" class=\"treeUnselected\" onclick=\"clickAnchor(this)\">HHP2HTML_NAME</a>\n"; StringBuilder sb = new StringBuilder(); for(int i = 0; i < items.Count; i++) { HelpItem item = (HelpItem)items[i]; sb.Append(Multiply("\t", item.depth) + "<div class=\"treeNode\">\n"); if (items.Count > (i+1)) //therea are some more items { HelpItem nextItem = (HelpItem)items[i+1]; if (nextItem.depth > item.depth) //has a child { sb.Append(Multiply("\t", item.depth) + htmlItemLink.Replace("HHP2HTML_NAME", item.name).Replace("HHP2HTML_FILE", item.file)); sb.Append(Multiply("\t", item.depth) + "\t<div class=\"treeSubnodesHidden\">\n"); } else { sb.Append(Multiply("\t", item.depth) + htmlItem.Replace("HHP2HTML_NAME", item.name).Replace("HHP2HTML_FILE", item.file)); sb.Append(Multiply("\t", item.depth) + "</div>\n"); } if (nextItem.depth < item.depth) //is a last child { sb.Append(Multiply("\t", item.depth-1) + "</div>\n"); sb.Append(Multiply("\t", item.depth-1) + "</div>\n"); } } else { sb.Append(Multiply("\t", item.depth) + htmlItem.Replace("HHP2HTML_NAME", item.name).Replace("HHP2HTML_FILE", item.file)); sb.Append(Multiply("\t", item.depth) + "</div>\n"); sb.Append(Multiply("\t", item.depth-1) + "</div>\n"); sb.Append(Multiply("\t", item.depth-1) + "</div>\n"); } } return sb.ToString(); } static string ComposeHTMLNoFrameTree(ArrayList items) { //string htmlItemLink = "\t<img src=\"treenodeplus.gif\" class=\"treeLinkImage\" onclick=\"expandCollapse(this.parentNode)\" />"+ // "\t<a href=\"HHP2HTML_FILE\" target=\"main\" class=\"treeUnselected\" onclick=\"clickAnchor(this)\">HHP2HTML_NAME</a>\n"; //string htmlItem = "\t<img src=\"treenodedot.gif\" class=\"treeNoLinkImage\" />"+ // "<a href=\"HHP2HTML_FILE\" target=\"main\" class=\"treeUnselected\" onclick=\"clickAnchor(this)\">HHP2HTML_NAME</a>\n"; string htmlItem = "<a href=\"HHP2HTML_FILE\">HHP2HTML_NAME</a><br>"; StringBuilder sb = new StringBuilder(); for(int i = 0; i < items.Count; i++) { HelpItem item = (HelpItem)items[i]; //sb.Append(Multiply("&nbsp;", item.depth*4) + htmlItem.Replace("HHP2HTML_NAME", item.name).Replace("HHP2HTML_FILE", item.file)); if (items.Count > (i+1)) //therea are some more items { HelpItem nextItem = (HelpItem)items[i+1]; if (nextItem.depth > item.depth) //has a child { sb.Append(Multiply("&nbsp;", item.depth*4) + htmlItem.Replace("HHP2HTML_NAME", item.name).Replace("HHP2HTML_FILE", item.file)); } else { sb.Append(Multiply("&nbsp;", item.depth*4) + htmlItem.Replace("HHP2HTML_NAME", item.name).Replace("HHP2HTML_FILE", item.file)); } if (nextItem.depth < item.depth) //is a last child { //sb.Append(Multiply("&nbsp;", item.depth*4) + htmlItem.Replace("HHP2HTML_NAME", item.name).Replace("HHP2HTML_FILE", item.file)); } } else { sb.Append(Multiply("&nbsp;", item.depth*4) + htmlItem.Replace("HHP2HTML_NAME", item.name).Replace("HHP2HTML_FILE", item.file)); } } return sb.ToString(); } class HelpItem { public HelpItem(string name, string file, int depth) { this.name = name; this.file = Path.Combine(htmlDir, Path.GetFileName(file)); this.depth = depth; } public string name = ""; public string file = ""; public int depth = 0; } static HelpItem ParseHHCItem(string data, int depth) { string tag = "<param name=\"Name\" value=\""; int posStart = data.IndexOf(tag); int posEnd = data.IndexOf("\"", posStart + tag.Length); string name = data.Substring(posStart + tag.Length, posEnd - (posStart + tag.Length)); tag = "<param name=\"Local\" value=\""; posStart = data.IndexOf(tag); posEnd = data.IndexOf("\"", posStart + tag.Length); string file = data.Substring(posStart + tag.Length, posEnd- (posStart + tag.Length)); return new HelpItem(name, file, depth); } static public ArrayList ParseHHC(string file) { string text = ""; using (StreamReader sr = new StreamReader(file)) { text = sr.ReadToEnd(); } string startTag = "<OBJECT type=\"text/sitemap\">"; string endTag = "</OBJECT>"; int itemStart = -1, itemEnd = -1, currentSearchPos = text.IndexOf(startTag), currDepth = 0; ArrayList items = new ArrayList(); while (true) { itemStart = text.IndexOf(startTag, currentSearchPos); if (itemStart == -1) break; itemEnd = text.IndexOf(endTag, currentSearchPos); string itemData = text.Substring(itemStart + startTag.Length, itemEnd - (itemStart + startTag.Length)); string interItemData = text.Substring(currentSearchPos, itemStart - currentSearchPos); if (interItemData.IndexOf("<UL>") != -1) currDepth++; if (interItemData.IndexOf("</UL>") != -1) currDepth--; HelpItem item = ParseHHCItem(itemData, currDepth); if (item.file == @"..\CSScript.html") { currentSearchPos = itemEnd + endTag.Length; continue; } if (firstTopicFile == "") { firstTopicFile = item.file; } items.Add(item); for (int i = 0; i < currDepth; i++) Console.Write("\t"); Console.WriteLine(item.name); currentSearchPos = itemEnd + endTag.Length; } return items; } static string indexTemplate = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Frameset//EN\">\n"+ " <html>\n"+ " <head>\n"+ " <meta name=\"Robots\" content=\"noindex\">\n"+ " <title>HHP2HTML_TITLE</title>\n"+ " <script language=\"JavaScript\">\n"+ " // ensure this page is not loaded inside another frame\n"+ " if (top.location != self.location)\n"+ " {\n"+ " top.location = self.location;\n"+ " }\n"+ " </script>\n"+ " </head>\n"+ " <frameset cols=\"250,*\" framespacing=\"6\" bordercolor=\"#6699CC\">\n"+ " <frame name=\"contents\" src=\"contents.html\" frameborder=\"0\" scrolling=\"no\">\n"+ " <frame name=\"main\" src=\"HHP2HTML_DEFAULT_TOPIC\" frameborder=\"1\">\n"+ " <noframes>\n"+ " <p>This page requires frames, but your browser does not support them.</p>\n"+ " </noframes>\n"+ " </frameset>\n"+ "</html>"; static string indexNoFrameTemplate = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n"+ "<html>\n"+ "<head>\n"+ "<body>\n"+ "<div style=\"margin: 6px 4px 8px 2px; font-family: verdana; font-size: 8pt; cursor: pointer; text-decoration: none; text-align: left;\"><span style=\"font-weight: bold;\">HHP2HTML_TITLE</span><br>\n"+ "</div>\n"+ "<title>Contents</title>\n"+ "<meta name=\"vs_targetSchema\" content=\"http://schemas.microsoft.com/intellisense/ie5\">\n"+ "<link rel=\"stylesheet\" type=\"text/css\" href=\"tree.css\">\n"+ "</head>\n"+ "<div style=\"margin: 6px 4px 8px 2px; font-family: verdana; font-size: 8pt; cursor: pointer; text-align: right; text-decoration: none;\" ><br></div>\n"+ "<div id=\"tree\" style=\"top: 35px; left: 0px;\" class=\"treeDiv\">\n"+ "</span>\n"+ //"&nbsp;&nbsp;&nbsp;&nbsp;Introduction<br>\n"+ "HHP2HTML_NO_FRAME_TREE\n"+ "</span></div>\n"+ "</div>\n"+ "</body>\n"+ "</html>"; static string contentTemplate = "<html>\n"+ " <head>\n"+ " <title>Contents</title>\n"+ " <meta name=\"vs_targetSchema\" content=\"http://schemas.microsoft.com/intellisense/ie5\" />\n"+ " <link rel=\"stylesheet\" type=\"text/css\" href=\"tree.css\" />\n"+ " <script src=\"tree.js\" language=\"javascript\" type=\"text/javascript\">\n"+ " </script>\n"+ " </head>\n"+ " <body id=\"docBody\" style=\"background-color: #6699CC; color: White; margin: 0px 0px 0px 0px;\" onload=\"resizeTree()\" onresize=\"resizeTree()\" onselectstart=\"return false;\">\n"+ " <table style=\"width:100%\">\n"+ " <tr>\n"+ " <td>\n"+ " &nbsp;\n"+ " <a style=\"font-family: verdana; font-size: 8pt; cursor: pointer; text-align: left\" \n"+ " onmouseover=\"this.style.textDecoration='underline'\" \n"+ " onmouseout=\"this.style.textDecoration='none'; this.style.background-color='red';\"\n"+ " href=\"../../search.aspx\" target=\"main\" ><img style=\"width: 20px; height: 16px;\" alt=\"\" src=\"search.bmp\"></a>\n"+ " </td>\n"+ " <td>\n"+ " <div style=\"font-family: verdana; font-size: 8pt; cursor: pointer; margin: 6 4 8 2; text-align: right\" \n"+ " onmouseover=\"this.style.textDecoration='underline'\" \n"+ " onmouseout=\"this.style.textDecoration='none'\" \n"+ " onclick=\"syncTree(window.parent.frames[1].document.URL)\">sync toc <img style=\"width: 16px; height: 16px;\" alt=\"\" src=\"synch.bmp\"></div>\n"+ " </td>\n"+ " </tr>\n"+ " </table>\n"+ " <div id=\"tree\" style=\"top: 35px; left: 0px;\" class=\"treeDiv\">\n"+ " <div id=\"treeRoot\" onselectstart=\"return false\" ondragstart=\"return false\">\n"+ " HHP2HTML_TREE\n"+ " </div>\n"+ " </div>\n"+ " </div>\n"+ " </body>\n"+ "</html>"; }
using System; using Server.Engines.VeteranRewards; namespace Server.Items { public abstract class BaseOuterTorso : BaseClothing { public BaseOuterTorso( int itemID ) : this( itemID, 0 ) { } public BaseOuterTorso( int itemID, int hue ) : base( itemID, Layer.OuterTorso, hue ) { } public BaseOuterTorso( Serial serial ) : base( serial ) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( (int) 0 ); // version } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadInt(); } } [Flipable( 0x230E, 0x230D )] public class GildedDress : BaseOuterTorso { [Constructable] public GildedDress() : this( 0 ) { } [Constructable] public GildedDress( int hue ) : base( 0x230E, hue ) { Weight = 3.0; } public GildedDress( Serial serial ) : base( serial ) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( (int) 0 ); // version } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadInt(); } } [Flipable( 0x1F00, 0x1EFF )] public class FancyDress : BaseOuterTorso { [Constructable] public FancyDress() : this( 0 ) { } [Constructable] public FancyDress( int hue ) : base( 0x1F00, hue ) { Weight = 3.0; } public FancyDress( Serial serial ) : base( serial ) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( (int) 0 ); // version } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadInt(); } } public class DeathRobe : Robe { private Timer m_DecayTimer; private DateTime m_DecayTime; private static TimeSpan m_DefaultDecayTime = TimeSpan.FromMinutes(1.0); public override bool DisplayLootType { get { return false; } } [Constructable] public DeathRobe() { LootType = LootType.Newbied; Hue = 2301; BeginDecay(m_DefaultDecayTime); } public new bool Scissor(Mobile from, Scissors scissors) { from.SendLocalizedMessage(502440); // Scissors can not be used on that to produce anything. return false; } public void BeginDecay() { BeginDecay(m_DefaultDecayTime); } private void BeginDecay(TimeSpan delay) { if (m_DecayTimer != null) m_DecayTimer.Stop(); m_DecayTime = DateTime.Now + delay; m_DecayTimer = new InternalTimer(this, delay); m_DecayTimer.Start(); } public override bool OnDroppedToWorld(Mobile from, Point3D p) { BeginDecay(m_DefaultDecayTime); return true; } public override bool OnDroppedToMobile(Mobile from, Mobile target) { if (m_DecayTimer != null) { m_DecayTimer.Stop(); m_DecayTimer = null; } return true; } public override void OnAfterDelete() { if (m_DecayTimer != null) m_DecayTimer.Stop(); m_DecayTimer = null; } private class InternalTimer : Timer { private DeathRobe m_Robe; public InternalTimer(DeathRobe c, TimeSpan delay) : base(delay) { m_Robe = c; Priority = TimerPriority.FiveSeconds; } protected override void OnTick() { if (m_Robe.Parent != null || m_Robe.IsLockedDown) Stop(); else m_Robe.Delete(); } } public DeathRobe(Serial serial) : base(serial) { } public override void Serialize(GenericWriter writer) { base.Serialize(writer); writer.Write((int)2); // version writer.Write(m_DecayTimer != null); if (m_DecayTimer != null) writer.WriteDeltaTime(m_DecayTime); } public override void Deserialize(GenericReader reader) { base.Deserialize(reader); int version = reader.ReadInt(); switch (version) { case 2: { if (reader.ReadBool()) { m_DecayTime = reader.ReadDeltaTime(); BeginDecay(m_DecayTime - DateTime.Now); } break; } case 1: case 0: { if (Parent == null) BeginDecay(m_DefaultDecayTime); break; } } if (version < 1 && Hue == 0) Hue = 2301; } } [Flipable] public class RewardRobe : BaseOuterTorso, IRewardItem { private int m_LabelNumber; private bool m_IsRewardItem; [CommandProperty( AccessLevel.GameMaster )] public bool IsRewardItem { get{ return m_IsRewardItem; } set{ m_IsRewardItem = value; } } [CommandProperty( AccessLevel.GameMaster )] public int Number { get{ return m_LabelNumber; } set{ m_LabelNumber = value; InvalidateProperties(); } } public override int LabelNumber { get { if ( m_LabelNumber > 0 ) return m_LabelNumber; return base.LabelNumber; } } public override int BasePhysicalResistance{ get{ return 3; } } public override void OnAdded( object parent ) { base.OnAdded( parent ); if ( parent is Mobile ) ((Mobile)parent).VirtualArmorMod += 2; } public override void OnRemoved(object parent) { base.OnRemoved( parent ); if ( parent is Mobile ) ((Mobile)parent).VirtualArmorMod -= 2; } public override bool Dye( Mobile from, DyeTub sender ) { from.SendLocalizedMessage( sender.FailMessage ); return false; } public override void GetProperties( ObjectPropertyList list ) { base.GetProperties( list ); if ( Core.ML && m_IsRewardItem ) list.Add( RewardSystem.GetRewardYearLabel( this, new object[]{ Hue, m_LabelNumber } ) ); // X Year Veteran Reward } public override bool CanEquip( Mobile m ) { if ( !base.CanEquip( m ) ) return false; return !m_IsRewardItem || RewardSystem.CheckIsUsableBy( m, this, new object[]{ Hue, m_LabelNumber } ); } [Constructable] public RewardRobe() : this( 0 ) { } [Constructable] public RewardRobe( int hue ) : this( hue, 0 ) { } [Constructable] public RewardRobe( int hue, int labelNumber ) : base( 0x1F03, hue ) { Weight = 3.0; LootType = LootType.Blessed; m_LabelNumber = labelNumber; } public RewardRobe( Serial serial ) : base( serial ) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( (int) 0 ); // version writer.Write( (int) m_LabelNumber ); writer.Write( (bool) m_IsRewardItem ); } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadInt(); switch ( version ) { case 0: { m_LabelNumber = reader.ReadInt(); m_IsRewardItem = reader.ReadBool(); break; } } if ( Parent is Mobile ) ((Mobile)Parent).VirtualArmorMod += 2; } } [Flipable] public class RewardDress : BaseOuterTorso, IRewardItem { private int m_LabelNumber; private bool m_IsRewardItem; [CommandProperty( AccessLevel.GameMaster )] public bool IsRewardItem { get{ return m_IsRewardItem; } set{ m_IsRewardItem = value; } } [CommandProperty( AccessLevel.GameMaster )] public int Number { get{ return m_LabelNumber; } set{ m_LabelNumber = value; InvalidateProperties(); } } public override int LabelNumber { get { if ( m_LabelNumber > 0 ) return m_LabelNumber; return base.LabelNumber; } } public override int BasePhysicalResistance{ get{ return 3; } } public override void OnAdded( object parent ) { base.OnAdded( parent ); if ( parent is Mobile ) ((Mobile)parent).VirtualArmorMod += 2; } public override void OnRemoved(object parent) { base.OnRemoved( parent ); if ( parent is Mobile ) ((Mobile)parent).VirtualArmorMod -= 2; } public override bool Dye( Mobile from, DyeTub sender ) { from.SendLocalizedMessage( sender.FailMessage ); return false; } public override void GetProperties( ObjectPropertyList list ) { base.GetProperties( list ); if ( m_IsRewardItem ) list.Add( RewardSystem.GetRewardYearLabel( this, new object[]{ Hue, m_LabelNumber } ) ); // X Year Veteran Reward } public override bool CanEquip( Mobile m ) { if ( !base.CanEquip( m ) ) return false; return !m_IsRewardItem || RewardSystem.CheckIsUsableBy( m, this, new object[]{ Hue, m_LabelNumber } ); } [Constructable] public RewardDress() : this( 0 ) { } [Constructable] public RewardDress( int hue ) : this( hue, 0 ) { } [Constructable] public RewardDress( int hue, int labelNumber ) : base( 0x1F01, hue ) { Weight = 2.0; LootType = LootType.Blessed; m_LabelNumber = labelNumber; } public RewardDress( Serial serial ) : base( serial ) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( (int) 0 ); // version writer.Write( (int) m_LabelNumber ); writer.Write( (bool) m_IsRewardItem ); } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadInt(); switch ( version ) { case 0: { m_LabelNumber = reader.ReadInt(); m_IsRewardItem = reader.ReadBool(); break; } } if ( Parent is Mobile ) ((Mobile)Parent).VirtualArmorMod += 2; } } [Flipable] public class Robe : BaseOuterTorso, IArcaneEquip { #region Arcane Impl private int m_MaxArcaneCharges, m_CurArcaneCharges; [CommandProperty( AccessLevel.GameMaster )] public int MaxArcaneCharges { get{ return m_MaxArcaneCharges; } set{ m_MaxArcaneCharges = value; InvalidateProperties(); Update(); } } [CommandProperty( AccessLevel.GameMaster )] public int CurArcaneCharges { get{ return m_CurArcaneCharges; } set{ m_CurArcaneCharges = value; InvalidateProperties(); Update(); } } [CommandProperty( AccessLevel.GameMaster )] public bool IsArcane { get{ return ( m_MaxArcaneCharges > 0 && m_CurArcaneCharges >= 0 ); } } public void Update() { if ( IsArcane ) ItemID = 0x26AE; else if ( ItemID == 0x26AE ) ItemID = 0x1F04; if ( IsArcane && CurArcaneCharges == 0 ) Hue = 0; } public override void GetProperties( ObjectPropertyList list ) { base.GetProperties( list ); if ( IsArcane ) list.Add( 1061837, "{0}\t{1}", m_CurArcaneCharges, m_MaxArcaneCharges ); // arcane charges: ~1_val~ / ~2_val~ } public override void OnSingleClick( Mobile from ) { base.OnSingleClick( from ); if ( IsArcane ) LabelTo( from, 1061837, String.Format( "{0}\t{1}", m_CurArcaneCharges, m_MaxArcaneCharges ) ); } public void Flip() { if ( ItemID == 0x1F03 ) ItemID = 0x1F04; else if ( ItemID == 0x1F04 ) ItemID = 0x1F03; } #endregion [Constructable] public Robe() : this( 0 ) { } [Constructable] public Robe( int hue ) : base( 0x1F03, hue ) { Weight = 3.0; } public Robe( Serial serial ) : base( serial ) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( (int) 1 ); // version if ( IsArcane ) { writer.Write( true ); writer.Write( (int) m_CurArcaneCharges ); writer.Write( (int) m_MaxArcaneCharges ); } else { writer.Write( false ); } } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadInt(); switch ( version ) { case 1: { if ( reader.ReadBool() ) { m_CurArcaneCharges = reader.ReadInt(); m_MaxArcaneCharges = reader.ReadInt(); if ( Hue == 2118 ) Hue = ArcaneGem.DefaultArcaneHue; } break; } } } } public class MonkRobe : BaseOuterTorso { [Constructable] public MonkRobe() : this( 0x21E ) { } [Constructable] public MonkRobe( int hue ) : base( 0x2687, hue ) { Weight = 1.0; StrRequirement = 0; } public override int LabelNumber{ get{ return 1076584; } } // A monk's robe public override bool CanBeBlessed { get { return false; } } public override bool Dye( Mobile from, DyeTub sender ) { from.SendLocalizedMessage( sender.FailMessage ); return false; } public MonkRobe( Serial serial ) : base( serial ) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( (int) 0 ); // version } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadInt(); } } [Flipable( 0x1f01, 0x1f02 )] public class PlainDress : BaseOuterTorso { [Constructable] public PlainDress() : this( 0 ) { } [Constructable] public PlainDress( int hue ) : base( 0x1F01, hue ) { Weight = 2.0; } public PlainDress( Serial serial ) : base( serial ) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( (int) 0 ); // version } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadInt(); if ( Weight == 3.0 ) Weight = 2.0; } } [Flipable( 0x2799, 0x27E4 )] public class Kamishimo : BaseOuterTorso { [Constructable] public Kamishimo() : this( 0 ) { } [Constructable] public Kamishimo( int hue ) : base( 0x2799, hue ) { Weight = 3.0; } public Kamishimo( Serial serial ) : base( serial ) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( (int) 0 ); // version } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadInt(); } } [Flipable( 0x279C, 0x27E7 )] public class HakamaShita : BaseOuterTorso { [Constructable] public HakamaShita() : this( 0 ) { } [Constructable] public HakamaShita( int hue ) : base( 0x279C, hue ) { Weight = 3.0; } public HakamaShita( Serial serial ) : base( serial ) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( (int) 0 ); // version } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadInt(); } } [Flipable( 0x2782, 0x27CD )] public class MaleKimono : BaseOuterTorso { [Constructable] public MaleKimono() : this( 0 ) { } [Constructable] public MaleKimono( int hue ) : base( 0x2782, hue ) { Weight = 3.0; } public override bool AllowFemaleWearer{ get{ return false; } } public MaleKimono( Serial serial ) : base( serial ) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( (int) 0 ); // version } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadInt(); } } [Flipable( 0x2783, 0x27CE )] public class FemaleKimono : BaseOuterTorso { [Constructable] public FemaleKimono() : this( 0 ) { } [Constructable] public FemaleKimono( int hue ) : base( 0x2783, hue ) { Weight = 3.0; } public override bool AllowMaleWearer{ get{ return false; } } public FemaleKimono( Serial serial ) : base( serial ) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( (int) 0 ); // version } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadInt(); } } [Flipable( 0x2FB9, 0x3173 )] public class MaleElvenRobe : BaseOuterTorso { //public override Race RequiredRace { get { return Race.Elf; } } [Constructable] public MaleElvenRobe() : this( 0 ) { } [Constructable] public MaleElvenRobe( int hue ) : base( 0x2FB9, hue ) { Weight = 2.0; Name = "Robe exotique"; } public MaleElvenRobe( Serial serial ) : base( serial ) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.WriteEncodedInt( 0 ); // version } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadEncodedInt(); } } [Flipable( 0x2FBA, 0x3174 )] public class FemaleElvenRobe : BaseOuterTorso { //public override Race RequiredRace { get { return Race.Elf; } } [Constructable] public FemaleElvenRobe() : this( 0 ) { } [Constructable] public FemaleElvenRobe( int hue ) : base( 0x2FBA, hue ) { Weight = 2.0; Name = "Robe exotique"; } public override bool AllowMaleWearer{ get{ return false; } } public FemaleElvenRobe( Serial serial ) : base( serial ) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.WriteEncodedInt( 0 ); // version } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadEncodedInt(); } } }
// 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. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // // // Public type to communicate multiple failures to an end-user. // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Globalization; using System.Runtime.ExceptionServices; using System.Runtime.Serialization; using System.Security; using System.Text; using System.Threading; namespace System { /// <summary>Represents one or more errors that occur during application execution.</summary> /// <remarks> /// <see cref="AggregateException"/> is used to consolidate multiple failures into a single, throwable /// exception object. /// </remarks> [Serializable] [DebuggerDisplay("Count = {InnerExceptionCount}")] public class AggregateException : Exception { private ReadOnlyCollection<Exception> m_innerExceptions; // Complete set of exceptions. /// <summary> /// Initializes a new instance of the <see cref="AggregateException"/> class. /// </summary> public AggregateException() : base(Environment.GetResourceString("AggregateException_ctor_DefaultMessage")) { m_innerExceptions = new ReadOnlyCollection<Exception>(new Exception[0]); } /// <summary> /// Initializes a new instance of the <see cref="AggregateException"/> class with /// a specified error message. /// </summary> /// <param name="message">The error message that explains the reason for the exception.</param> public AggregateException(string message) : base(message) { m_innerExceptions = new ReadOnlyCollection<Exception>(new Exception[0]); } /// <summary> /// Initializes a new instance of the <see cref="AggregateException"/> class with a specified error /// message and a reference to the inner exception that is the cause of this exception. /// </summary> /// <param name="message">The error message that explains the reason for the exception.</param> /// <param name="innerException">The exception that is the cause of the current exception.</param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="innerException"/> argument /// is null.</exception> public AggregateException(string message, Exception innerException) : base(message, innerException) { if (innerException == null) { throw new ArgumentNullException(nameof(innerException)); } m_innerExceptions = new ReadOnlyCollection<Exception>(new Exception[] { innerException }); } /// <summary> /// Initializes a new instance of the <see cref="AggregateException"/> class with /// references to the inner exceptions that are the cause of this exception. /// </summary> /// <param name="innerExceptions">The exceptions that are the cause of the current exception.</param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="innerExceptions"/> argument /// is null.</exception> /// <exception cref="T:System.ArgumentException">An element of <paramref name="innerExceptions"/> is /// null.</exception> public AggregateException(IEnumerable<Exception> innerExceptions) : this(Environment.GetResourceString("AggregateException_ctor_DefaultMessage"), innerExceptions) { } /// <summary> /// Initializes a new instance of the <see cref="AggregateException"/> class with /// references to the inner exceptions that are the cause of this exception. /// </summary> /// <param name="innerExceptions">The exceptions that are the cause of the current exception.</param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="innerExceptions"/> argument /// is null.</exception> /// <exception cref="T:System.ArgumentException">An element of <paramref name="innerExceptions"/> is /// null.</exception> public AggregateException(params Exception[] innerExceptions) : this(Environment.GetResourceString("AggregateException_ctor_DefaultMessage"), innerExceptions) { } /// <summary> /// Initializes a new instance of the <see cref="AggregateException"/> class with a specified error /// message and references to the inner exceptions that are the cause of this exception. /// </summary> /// <param name="message">The error message that explains the reason for the exception.</param> /// <param name="innerExceptions">The exceptions that are the cause of the current exception.</param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="innerExceptions"/> argument /// is null.</exception> /// <exception cref="T:System.ArgumentException">An element of <paramref name="innerExceptions"/> is /// null.</exception> public AggregateException(string message, IEnumerable<Exception> innerExceptions) // If it's already an IList, pass that along (a defensive copy will be made in the delegated ctor). If it's null, just pass along // null typed correctly. Otherwise, create an IList from the enumerable and pass that along. : this(message, innerExceptions as IList<Exception> ?? (innerExceptions == null ? (List<Exception>)null : new List<Exception>(innerExceptions))) { } /// <summary> /// Initializes a new instance of the <see cref="AggregateException"/> class with a specified error /// message and references to the inner exceptions that are the cause of this exception. /// </summary> /// <param name="message">The error message that explains the reason for the exception.</param> /// <param name="innerExceptions">The exceptions that are the cause of the current exception.</param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="innerExceptions"/> argument /// is null.</exception> /// <exception cref="T:System.ArgumentException">An element of <paramref name="innerExceptions"/> is /// null.</exception> public AggregateException(string message, params Exception[] innerExceptions) : this(message, (IList<Exception>)innerExceptions) { } /// <summary> /// Allocates a new aggregate exception with the specified message and list of inner exceptions. /// </summary> /// <param name="message">The error message that explains the reason for the exception.</param> /// <param name="innerExceptions">The exceptions that are the cause of the current exception.</param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="innerExceptions"/> argument /// is null.</exception> /// <exception cref="T:System.ArgumentException">An element of <paramref name="innerExceptions"/> is /// null.</exception> private AggregateException(string message, IList<Exception> innerExceptions) : base(message, innerExceptions != null && innerExceptions.Count > 0 ? innerExceptions[0] : null) { if (innerExceptions == null) { throw new ArgumentNullException(nameof(innerExceptions)); } // Copy exceptions to our internal array and validate them. We must copy them, // because we're going to put them into a ReadOnlyCollection which simply reuses // the list passed in to it. We don't want callers subsequently mutating. Exception[] exceptionsCopy = new Exception[innerExceptions.Count]; for (int i = 0; i < exceptionsCopy.Length; i++) { exceptionsCopy[i] = innerExceptions[i]; if (exceptionsCopy[i] == null) { throw new ArgumentException(Environment.GetResourceString("AggregateException_ctor_InnerExceptionNull")); } } m_innerExceptions = new ReadOnlyCollection<Exception>(exceptionsCopy); } /// <summary> /// Initializes a new instance of the <see cref="AggregateException"/> class with /// references to the inner exception dispatch info objects that represent the cause of this exception. /// </summary> /// <param name="innerExceptionInfos"> /// Information about the exceptions that are the cause of the current exception. /// </param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="innerExceptionInfos"/> argument /// is null.</exception> /// <exception cref="T:System.ArgumentException">An element of <paramref name="innerExceptionInfos"/> is /// null.</exception> internal AggregateException(IEnumerable<ExceptionDispatchInfo> innerExceptionInfos) : this(Environment.GetResourceString("AggregateException_ctor_DefaultMessage"), innerExceptionInfos) { } /// <summary> /// Initializes a new instance of the <see cref="AggregateException"/> class with a specified error /// message and references to the inner exception dispatch info objects that represent the cause of /// this exception. /// </summary> /// <param name="message">The error message that explains the reason for the exception.</param> /// <param name="innerExceptionInfos"> /// Information about the exceptions that are the cause of the current exception. /// </param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="innerExceptionInfos"/> argument /// is null.</exception> /// <exception cref="T:System.ArgumentException">An element of <paramref name="innerExceptionInfos"/> is /// null.</exception> internal AggregateException(string message, IEnumerable<ExceptionDispatchInfo> innerExceptionInfos) // If it's already an IList, pass that along (a defensive copy will be made in the delegated ctor). If it's null, just pass along // null typed correctly. Otherwise, create an IList from the enumerable and pass that along. : this(message, innerExceptionInfos as IList<ExceptionDispatchInfo> ?? (innerExceptionInfos == null ? (List<ExceptionDispatchInfo>)null : new List<ExceptionDispatchInfo>(innerExceptionInfos))) { } /// <summary> /// Allocates a new aggregate exception with the specified message and list of inner /// exception dispatch info objects. /// </summary> /// <param name="message">The error message that explains the reason for the exception.</param> /// <param name="innerExceptionInfos"> /// Information about the exceptions that are the cause of the current exception. /// </param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="innerExceptionInfos"/> argument /// is null.</exception> /// <exception cref="T:System.ArgumentException">An element of <paramref name="innerExceptionInfos"/> is /// null.</exception> private AggregateException(string message, IList<ExceptionDispatchInfo> innerExceptionInfos) : base(message, innerExceptionInfos != null && innerExceptionInfos.Count > 0 && innerExceptionInfos[0] != null ? innerExceptionInfos[0].SourceException : null) { if (innerExceptionInfos == null) { throw new ArgumentNullException(nameof(innerExceptionInfos)); } // Copy exceptions to our internal array and validate them. We must copy them, // because we're going to put them into a ReadOnlyCollection which simply reuses // the list passed in to it. We don't want callers subsequently mutating. Exception[] exceptionsCopy = new Exception[innerExceptionInfos.Count]; for (int i = 0; i < exceptionsCopy.Length; i++) { var edi = innerExceptionInfos[i]; if (edi != null) exceptionsCopy[i] = edi.SourceException; if (exceptionsCopy[i] == null) { throw new ArgumentException(Environment.GetResourceString("AggregateException_ctor_InnerExceptionNull")); } } m_innerExceptions = new ReadOnlyCollection<Exception>(exceptionsCopy); } /// <summary> /// Initializes a new instance of the <see cref="AggregateException"/> class with serialized data. /// </summary> /// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo"/> that holds /// the serialized object data about the exception being thrown.</param> /// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext"/> that /// contains contextual information about the source or destination. </param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="info"/> argument is null.</exception> /// <exception cref="T:System.Runtime.Serialization.SerializationException">The exception could not be deserialized correctly.</exception> [SecurityCritical] protected AggregateException(SerializationInfo info, StreamingContext context) : base(info, context) { if (info == null) { throw new ArgumentNullException(nameof(info)); } Exception[] innerExceptions = info.GetValue("InnerExceptions", typeof(Exception[])) as Exception[]; if (innerExceptions == null) { throw new SerializationException(Environment.GetResourceString("AggregateException_DeserializationFailure")); } m_innerExceptions = new ReadOnlyCollection<Exception>(innerExceptions); } /// <summary> /// Sets the <see cref="T:System.Runtime.Serialization.SerializationInfo"/> with information about /// the exception. /// </summary> /// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo"/> that holds /// the serialized object data about the exception being thrown.</param> /// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext"/> that /// contains contextual information about the source or destination. </param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="info"/> argument is null.</exception> [SecurityCritical] public override void GetObjectData(SerializationInfo info, StreamingContext context) { if (info == null) { throw new ArgumentNullException(nameof(info)); } base.GetObjectData(info, context); Exception[] innerExceptions = new Exception[m_innerExceptions.Count]; m_innerExceptions.CopyTo(innerExceptions, 0); info.AddValue("InnerExceptions", innerExceptions, typeof(Exception[])); } /// <summary> /// Returns the <see cref="System.AggregateException"/> that is the root cause of this exception. /// </summary> public override Exception GetBaseException() { // Returns the first inner AggregateException that contains more or less than one inner exception // Recursively traverse the inner exceptions as long as the inner exception of type AggregateException and has only one inner exception Exception back = this; AggregateException backAsAggregate = this; while (backAsAggregate != null && backAsAggregate.InnerExceptions.Count == 1) { back = back.InnerException; backAsAggregate = back as AggregateException; } return back; } /// <summary> /// Gets a read-only collection of the <see cref="T:System.Exception"/> instances that caused the /// current exception. /// </summary> public ReadOnlyCollection<Exception> InnerExceptions { get { return m_innerExceptions; } } /// <summary> /// Invokes a handler on each <see cref="T:System.Exception"/> contained by this <see /// cref="AggregateException"/>. /// </summary> /// <param name="predicate">The predicate to execute for each exception. The predicate accepts as an /// argument the <see cref="T:System.Exception"/> to be processed and returns a Boolean to indicate /// whether the exception was handled.</param> /// <remarks> /// Each invocation of the <paramref name="predicate"/> returns true or false to indicate whether the /// <see cref="T:System.Exception"/> was handled. After all invocations, if any exceptions went /// unhandled, all unhandled exceptions will be put into a new <see cref="AggregateException"/> /// which will be thrown. Otherwise, the <see cref="Handle"/> method simply returns. If any /// invocations of the <paramref name="predicate"/> throws an exception, it will halt the processing /// of any more exceptions and immediately propagate the thrown exception as-is. /// </remarks> /// <exception cref="AggregateException">An exception contained by this <see /// cref="AggregateException"/> was not handled.</exception> /// <exception cref="T:System.ArgumentNullException">The <paramref name="predicate"/> argument is /// null.</exception> public void Handle(Func<Exception, bool> predicate) { if (predicate == null) { throw new ArgumentNullException(nameof(predicate)); } List<Exception> unhandledExceptions = null; for (int i = 0; i < m_innerExceptions.Count; i++) { // If the exception was not handled, lazily allocate a list of unhandled // exceptions (to be rethrown later) and add it. if (!predicate(m_innerExceptions[i])) { if (unhandledExceptions == null) { unhandledExceptions = new List<Exception>(); } unhandledExceptions.Add(m_innerExceptions[i]); } } // If there are unhandled exceptions remaining, throw them. if (unhandledExceptions != null) { throw new AggregateException(Message, unhandledExceptions); } } /// <summary> /// Flattens an <see cref="AggregateException"/> instances into a single, new instance. /// </summary> /// <returns>A new, flattened <see cref="AggregateException"/>.</returns> /// <remarks> /// If any inner exceptions are themselves instances of /// <see cref="AggregateException"/>, this method will recursively flatten all of them. The /// inner exceptions returned in the new <see cref="AggregateException"/> /// will be the union of all of the the inner exceptions from exception tree rooted at the provided /// <see cref="AggregateException"/> instance. /// </remarks> public AggregateException Flatten() { // Initialize a collection to contain the flattened exceptions. List<Exception> flattenedExceptions = new List<Exception>(); // Create a list to remember all aggregates to be flattened, this will be accessed like a FIFO queue List<AggregateException> exceptionsToFlatten = new List<AggregateException>(); exceptionsToFlatten.Add(this); int nDequeueIndex = 0; // Continue removing and recursively flattening exceptions, until there are no more. while (exceptionsToFlatten.Count > nDequeueIndex) { // dequeue one from exceptionsToFlatten IList<Exception> currentInnerExceptions = exceptionsToFlatten[nDequeueIndex++].InnerExceptions; for (int i = 0; i < currentInnerExceptions.Count; i++) { Exception currentInnerException = currentInnerExceptions[i]; if (currentInnerException == null) { continue; } AggregateException currentInnerAsAggregate = currentInnerException as AggregateException; // If this exception is an aggregate, keep it around for later. Otherwise, // simply add it to the list of flattened exceptions to be returned. if (currentInnerAsAggregate != null) { exceptionsToFlatten.Add(currentInnerAsAggregate); } else { flattenedExceptions.Add(currentInnerException); } } } return new AggregateException(Message, flattenedExceptions); } /// <summary>Gets a message that describes the exception.</summary> public override string Message { get { if (m_innerExceptions.Count == 0) { return base.Message; } StringBuilder sb = StringBuilderCache.Acquire(); sb.Append(base.Message); sb.Append(' '); for (int i = 0; i < m_innerExceptions.Count; i++) { sb.Append('('); sb.Append(m_innerExceptions[i].Message); sb.Append(") "); } sb.Length -= 1; return StringBuilderCache.GetStringAndRelease(sb); } } /// <summary> /// Creates and returns a string representation of the current <see cref="AggregateException"/>. /// </summary> /// <returns>A string representation of the current exception.</returns> public override string ToString() { string text = base.ToString(); for (int i = 0; i < m_innerExceptions.Count; i++) { text = String.Format( CultureInfo.InvariantCulture, Environment.GetResourceString("AggregateException_ToString"), text, Environment.NewLine, i, m_innerExceptions[i].ToString(), "<---", Environment.NewLine); } return text; } /// <summary> /// This helper property is used by the DebuggerDisplay. /// /// Note that we don't want to remove this property and change the debugger display to {InnerExceptions.Count} /// because DebuggerDisplay should be a single property access or parameterless method call, so that the debugger /// can use a fast path without using the expression evaluator. /// /// See http://msdn.microsoft.com/en-us/library/x810d419.aspx /// </summary> private int InnerExceptionCount { get { return InnerExceptions.Count; } } } }
using System; using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; namespace Invoices.Business { /// <summary> /// ProductTypeDynaItem (dynamic root object).<br/> /// This is a generated <see cref="ProductTypeDynaItem"/> business object. /// </summary> /// <remarks> /// This class is an item of <see cref="ProductTypeDynaColl"/> collection. /// </remarks> [Serializable] public partial class ProductTypeDynaItem : BusinessBase<ProductTypeDynaItem> { #region Static Fields private static int _lastId; #endregion #region Business Properties /// <summary> /// Maintains metadata about <see cref="ProductTypeId"/> property. /// </summary> [NotUndoable] public static readonly PropertyInfo<int> ProductTypeIdProperty = RegisterProperty<int>(p => p.ProductTypeId, "Product Type Id"); /// <summary> /// Gets the Product Type Id. /// </summary> /// <value>The Product Type Id.</value> public int ProductTypeId { get { return GetProperty(ProductTypeIdProperty); } } /// <summary> /// Maintains metadata about <see cref="Name"/> property. /// </summary> public static readonly PropertyInfo<string> NameProperty = RegisterProperty<string>(p => p.Name, "Name"); /// <summary> /// Gets or sets the Name. /// </summary> /// <value>The Name.</value> public string Name { get { return GetProperty(NameProperty); } set { SetProperty(NameProperty, value); } } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="ProductTypeDynaItem"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public ProductTypeDynaItem() { // Use factory methods and do not use direct creation. Saved += OnProductTypeDynaItemSaved; ProductTypeDynaItemSaved += ProductTypeDynaItemSavedHandler; } #endregion #region Cache Invalidation // TODO: edit "ProductTypeDynaItem.cs", uncomment the "OnDeserialized" method and add the following line: // TODO: ProductTypeDynaItemSaved += ProductTypeDynaItemSavedHandler; private void ProductTypeDynaItemSavedHandler(object sender, Csla.Core.SavedEventArgs e) { // this runs on the client ProductTypeCachedList.InvalidateCache(); ProductTypeCachedNVL.InvalidateCache(); } /// <summary> /// Called by the server-side DataPortal after calling the requested DataPortal_XYZ method. /// </summary> /// <param name="e">The DataPortalContext object passed to the DataPortal.</param> protected override void DataPortal_OnDataPortalInvokeComplete(Csla.DataPortalEventArgs e) { if (ApplicationContext.ExecutionLocation == ApplicationContext.ExecutionLocations.Server && e.Operation == DataPortalOperations.Update) { // this runs on the server ProductTypeCachedNVL.InvalidateCache(); } } #endregion #region Data Access /// <summary> /// Loads default values for the <see cref="ProductTypeDynaItem"/> object properties. /// </summary> [RunLocal] protected override void DataPortal_Create() { LoadProperty(ProductTypeIdProperty, System.Threading.Interlocked.Decrement(ref _lastId)); var args = new DataPortalHookArgs(); OnCreate(args); base.DataPortal_Create(); } /// <summary> /// Loads a <see cref="ProductTypeDynaItem"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> private void DataPortal_Fetch(SafeDataReader dr) { // Value properties LoadProperty(ProductTypeIdProperty, dr.GetInt32("ProductTypeId")); LoadProperty(NameProperty, dr.GetString("Name")); var args = new DataPortalHookArgs(dr); OnFetchRead(args); // check all object rules and property rules BusinessRules.CheckRules(); } /// <summary> /// Inserts a new <see cref="ProductTypeDynaItem"/> object in the database. /// </summary> [Transactional(TransactionalTypes.TransactionScope)] protected override void DataPortal_Insert() { using (var ctx = ConnectionManager<SqlConnection>.GetManager("Invoices")) { using (var cmd = new SqlCommand("dbo.AddProductTypeDynaItem", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@ProductTypeId", ReadProperty(ProductTypeIdProperty)).Direction = ParameterDirection.Output; cmd.Parameters.AddWithValue("@Name", ReadProperty(NameProperty)).DbType = DbType.String; var args = new DataPortalHookArgs(cmd); OnInsertPre(args); cmd.ExecuteNonQuery(); OnInsertPost(args); LoadProperty(ProductTypeIdProperty, (int) cmd.Parameters["@ProductTypeId"].Value); } } } /// <summary> /// Updates in the database all changes made to the <see cref="ProductTypeDynaItem"/> object. /// </summary> [Transactional(TransactionalTypes.TransactionScope)] protected override void DataPortal_Update() { using (var ctx = ConnectionManager<SqlConnection>.GetManager("Invoices")) { using (var cmd = new SqlCommand("dbo.UpdateProductTypeDynaItem", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@ProductTypeId", ReadProperty(ProductTypeIdProperty)).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@Name", ReadProperty(NameProperty)).DbType = DbType.String; var args = new DataPortalHookArgs(cmd); OnUpdatePre(args); cmd.ExecuteNonQuery(); OnUpdatePost(args); } } } /// <summary> /// Self deletes the <see cref="ProductTypeDynaItem"/> object. /// </summary> protected override void DataPortal_DeleteSelf() { DataPortal_Delete(ProductTypeId); } /// <summary> /// Deletes the <see cref="ProductTypeDynaItem"/> object from database. /// </summary> /// <param name="productTypeId">The delete criteria.</param> [Transactional(TransactionalTypes.TransactionScope)] protected void DataPortal_Delete(int productTypeId) { using (var ctx = ConnectionManager<SqlConnection>.GetManager("Invoices")) { using (var cmd = new SqlCommand("dbo.DeleteProductTypeDynaItem", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@ProductTypeId", productTypeId).DbType = DbType.Int32; var args = new DataPortalHookArgs(cmd, productTypeId); OnDeletePre(args); cmd.ExecuteNonQuery(); OnDeletePost(args); } } } #endregion #region Saved Event // TODO: edit "ProductTypeDynaItem.cs", uncomment the "OnDeserialized" method and add the following line: // TODO: Saved += OnProductTypeDynaItemSaved; private void OnProductTypeDynaItemSaved(object sender, Csla.Core.SavedEventArgs e) { if (ProductTypeDynaItemSaved != null) ProductTypeDynaItemSaved(sender, e); } /// <summary> Use this event to signal a <see cref="ProductTypeDynaItem"/> object was saved.</summary> public static event EventHandler<Csla.Core.SavedEventArgs> ProductTypeDynaItemSaved; #endregion #region DataPortal Hooks /// <summary> /// Occurs after setting all defaults for object creation. /// </summary> partial void OnCreate(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation. /// </summary> partial void OnDeletePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after the delete operation, before Commit(). /// </summary> partial void OnDeletePost(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the fetch operation. /// </summary> partial void OnFetchPre(DataPortalHookArgs args); /// <summary> /// Occurs after the fetch operation (object or collection is fully loaded and set up). /// </summary> partial void OnFetchPost(DataPortalHookArgs args); /// <summary> /// Occurs after the low level fetch operation, before the data reader is destroyed. /// </summary> partial void OnFetchRead(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the update operation. /// </summary> partial void OnUpdatePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit(). /// </summary> partial void OnUpdatePost(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation. /// </summary> partial void OnInsertPre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit(). /// </summary> partial void OnInsertPost(DataPortalHookArgs args); #endregion } }
using System; namespace g3 { // interval [a,b] on Real line. // TODO: should check that a <= b !! public struct Interval1d { public double a; public double b; public Interval1d(double f) { a = b = f; } public Interval1d(double x, double y) { this.a = x; this.b = y; } public Interval1d(double[] v2) { a = v2[0]; b = v2[1]; } public Interval1d(float f) { a = b = f; } public Interval1d(float x, float y) { this.a = x; this.b = y; } public Interval1d(float[] v2) { a = v2[0]; b = v2[1]; } public Interval1d(Interval1d copy) { a = copy.a; b = copy.b; } static public readonly Interval1d Zero = new Interval1d(0.0f, 0.0f); static public readonly Interval1d Empty = new Interval1d(double.MaxValue, -double.MaxValue); static public readonly Interval1d Infinite = new Interval1d(-double.MaxValue, double.MaxValue); public static Interval1d Unsorted(double x, double y) { return (x < y) ? new Interval1d(x, y) : new Interval1d(y, x); } public double this[int key] { get { return (key == 0) ? a : b; } set { if (key == 0) { a = value; } else { b = value; } } } public double LengthSquared { get { return (a - b) * (a - b); } } public double Length { get { return b - a; } } public bool IsConstant { get { return b == a; } } public double Center { get { return (b + a) * 0.5; } } public void Contain(double d) { if (d < a) { a = d; } if (d > b) { b = d; } } public bool Contains(double d) { return d >= a && d <= b; } public bool Overlaps(Interval1d o) { return !(o.a > b || o.b < a); } public double SquaredDist(Interval1d o) { if (b < o.a) { return (o.a - b) * (o.a - b); } else if (a > o.b) { return (a - o.b) * (a - o.b); } else { return 0; } } public double Dist(Interval1d o) { if (b < o.a) { return o.a - b; } else if (a > o.b) { return a - o.b; } else { return 0; } } public Interval1d IntersectionWith(ref Interval1d o) { if (o.a > b || o.b < a) { return Interval1d.Empty; } return new Interval1d(Math.Max(a, o.a), Math.Min(b, o.b)); } /// <summary> /// clamp value f to interval [a,b] /// </summary> public double Clamp(double f) { return (f < a) ? a : (f > b) ? b : f; } /// <summary> /// interpolate between a and b using value t in range [0,1] /// </summary> public double Interpolate(double t) { return (1 - t) * a + (t) * b; } /// <summary> /// Convert value into (clamped) t value in range [0,1] /// </summary> public double GetT(double value) { if (value <= a) { return 0; } else if (value >= b) { return 1; } else if (a == b) { return 0.5; } else { return (value - a) / (b - a); } } public void Set(Interval1d o) { a = o.a; b = o.b; } public void Set(double fA, double fB) { a = fA; b = fB; } public static Interval1d operator -(Interval1d v) { return new Interval1d(-v.a, -v.b); } public static Interval1d operator +(Interval1d a, double f) { return new Interval1d(a.a + f, a.b + f); } public static Interval1d operator -(Interval1d a, double f) { return new Interval1d(a.a - f, a.b - f); } public static Interval1d operator *(Interval1d a, double f) { return new Interval1d(a.a * f, a.b * f); } public override string ToString() { return string.Format("[{0:F8},{1:F8}]", a, b); } } }
namespace SpriteFont_Generator { partial class FrmMain { /// <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 Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FrmMain)); this.menuBar = new System.Windows.Forms.MenuStrip(); this.fileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.openToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.saveAsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItemSep1 = new System.Windows.Forms.ToolStripSeparator(); this.exitToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.actionToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.generateToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem1 = new System.Windows.Forms.ToolStripSeparator(); this.automationToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.statusStrip = new System.Windows.Forms.StatusStrip(); this.toolStripStatusLabel = new System.Windows.Forms.ToolStripStatusLabel(); this.pnlImage = new System.Windows.Forms.Panel(); this.pictureBox = new System.Windows.Forms.PictureBox(); this.menuBar.SuspendLayout(); this.statusStrip.SuspendLayout(); this.pnlImage.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox)).BeginInit(); this.SuspendLayout(); // // menuBar // this.menuBar.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.fileToolStripMenuItem, this.actionToolStripMenuItem}); this.menuBar.Location = new System.Drawing.Point(0, 0); this.menuBar.Name = "menuBar"; this.menuBar.Size = new System.Drawing.Size(792, 24); this.menuBar.TabIndex = 0; this.menuBar.Text = "menuBar"; // // fileToolStripMenuItem // this.fileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.openToolStripMenuItem, this.saveAsToolStripMenuItem, this.toolStripMenuItemSep1, this.exitToolStripMenuItem}); this.fileToolStripMenuItem.Name = "fileToolStripMenuItem"; this.fileToolStripMenuItem.Size = new System.Drawing.Size(35, 20); this.fileToolStripMenuItem.Text = "File"; // // openToolStripMenuItem // this.openToolStripMenuItem.Image = global::SpriteFont_Generator.Properties.Resources.OpenIcon; this.openToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Fuchsia; this.openToolStripMenuItem.Name = "openToolStripMenuItem"; this.openToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.O))); this.openToolStripMenuItem.Size = new System.Drawing.Size(174, 22); this.openToolStripMenuItem.Text = "Open"; this.openToolStripMenuItem.Click += new System.EventHandler(this.Open_Click); // // saveAsToolStripMenuItem // this.saveAsToolStripMenuItem.Image = global::SpriteFont_Generator.Properties.Resources.SaveIcon; this.saveAsToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Fuchsia; this.saveAsToolStripMenuItem.Name = "saveAsToolStripMenuItem"; this.saveAsToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.S))); this.saveAsToolStripMenuItem.Size = new System.Drawing.Size(174, 22); this.saveAsToolStripMenuItem.Text = "Save As..."; this.saveAsToolStripMenuItem.Click += new System.EventHandler(this.SaveAs_Click); // // toolStripMenuItemSep1 // this.toolStripMenuItemSep1.Name = "toolStripMenuItemSep1"; this.toolStripMenuItemSep1.Size = new System.Drawing.Size(171, 6); // // exitToolStripMenuItem // this.exitToolStripMenuItem.Image = global::SpriteFont_Generator.Properties.Resources.ExitIcon; this.exitToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Fuchsia; this.exitToolStripMenuItem.Name = "exitToolStripMenuItem"; this.exitToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Alt | System.Windows.Forms.Keys.F4))); this.exitToolStripMenuItem.Size = new System.Drawing.Size(174, 22); this.exitToolStripMenuItem.Text = "Exit"; this.exitToolStripMenuItem.Click += new System.EventHandler(this.Exit_Click); // // actionToolStripMenuItem // this.actionToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.generateToolStripMenuItem, this.toolStripMenuItem1, this.automationToolStripMenuItem}); this.actionToolStripMenuItem.Name = "actionToolStripMenuItem"; this.actionToolStripMenuItem.Size = new System.Drawing.Size(49, 20); this.actionToolStripMenuItem.Text = "Action"; // // generateToolStripMenuItem // this.generateToolStripMenuItem.Image = global::SpriteFont_Generator.Properties.Resources.GenerateIcon; this.generateToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Fuchsia; this.generateToolStripMenuItem.Name = "generateToolStripMenuItem"; this.generateToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.G))); this.generateToolStripMenuItem.Size = new System.Drawing.Size(179, 22); this.generateToolStripMenuItem.Text = "Generate"; this.generateToolStripMenuItem.Click += new System.EventHandler(this.Generate_Click); // // toolStripMenuItem1 // this.toolStripMenuItem1.Name = "toolStripMenuItem1"; this.toolStripMenuItem1.Size = new System.Drawing.Size(176, 6); // // automationToolStripMenuItem // this.automationToolStripMenuItem.Image = global::SpriteFont_Generator.Properties.Resources.AutomationIcon; this.automationToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Fuchsia; this.automationToolStripMenuItem.Name = "automationToolStripMenuItem"; this.automationToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.A))); this.automationToolStripMenuItem.Size = new System.Drawing.Size(179, 22); this.automationToolStripMenuItem.Text = "Automation"; this.automationToolStripMenuItem.Click += new System.EventHandler(this.Automation_Click); // // statusStrip // this.statusStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.toolStripStatusLabel}); this.statusStrip.Location = new System.Drawing.Point(0, 544); this.statusStrip.Name = "statusStrip"; this.statusStrip.Size = new System.Drawing.Size(792, 22); this.statusStrip.TabIndex = 2; this.statusStrip.Text = "statusStrip1"; // // toolStripStatusLabel // this.toolStripStatusLabel.Name = "toolStripStatusLabel"; this.toolStripStatusLabel.Size = new System.Drawing.Size(42, 17); this.toolStripStatusLabel.Text = "Ready."; // // pnlImage // this.pnlImage.AutoScroll = true; this.pnlImage.BackColor = System.Drawing.SystemColors.AppWorkspace; this.pnlImage.Controls.Add(this.pictureBox); this.pnlImage.Dock = System.Windows.Forms.DockStyle.Fill; this.pnlImage.Location = new System.Drawing.Point(0, 24); this.pnlImage.Name = "pnlImage"; this.pnlImage.Size = new System.Drawing.Size(792, 520); this.pnlImage.TabIndex = 3; // // pictureBox // this.pictureBox.Location = new System.Drawing.Point(3, 3); this.pictureBox.Name = "pictureBox"; this.pictureBox.Size = new System.Drawing.Size(10, 10); this.pictureBox.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize; this.pictureBox.TabIndex = 0; this.pictureBox.TabStop = false; // // FrmMain // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(792, 566); this.Controls.Add(this.pnlImage); this.Controls.Add(this.statusStrip); this.Controls.Add(this.menuBar); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.MainMenuStrip = this.menuBar; this.Name = "FrmMain"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "SpriteFont Generator"; this.menuBar.ResumeLayout(false); this.menuBar.PerformLayout(); this.statusStrip.ResumeLayout(false); this.statusStrip.PerformLayout(); this.pnlImage.ResumeLayout(false); this.pnlImage.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.MenuStrip menuBar; private System.Windows.Forms.ToolStripMenuItem fileToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem openToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem saveAsToolStripMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripMenuItemSep1; private System.Windows.Forms.ToolStripMenuItem exitToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem actionToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem generateToolStripMenuItem; private System.Windows.Forms.StatusStrip statusStrip; private System.Windows.Forms.Panel pnlImage; private System.Windows.Forms.PictureBox pictureBox; private System.Windows.Forms.ToolStripSeparator toolStripMenuItem1; private System.Windows.Forms.ToolStripMenuItem automationToolStripMenuItem; private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel; } }