context
stringlengths
2.52k
185k
gt
stringclasses
1 value
/* * Copyright (c) 2015, Wisconsin Robotics * 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 Wisconsin Robotics 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 WISCONSIN ROBOTICS 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; namespace BadgerJaus.Messages { public class JausCommandCode { public const int NONE = 0x0000; public const int SET_AUTHORITY = 0x0001; public const int SHUTDOWN = 0x0002; public const int STANDBY = 0x0003; public const int RESUME = 0x0004; public const int RESET = 0x0005; public const int SET_EMERGENCY = 0x0006; public const int CLEAR_EMERGENCY = 0x0007; public const int CREATE_SERVICE_CONNECTION = 0x0008; public const int CONFIRM_SERVICE_CONNECTION = 0x0009; public const int ACTIVATE_SERVICE_CONNECTION = 0x000A; public const int SUSPEND_SERVICE_CONNECTION = 0x000B; public const int TERMINATE_SERVICE_CONNECTION = 0x000C; public const int REQUEST_CONTROL = 0x000D; public const int RELEASE_CONTROL = 0x000E; public const int CONFIRM_CONTROL = 0x000F; public const int REJECT_CONTROL = 0x0010; public const int SET_TIME = 0x0011; public const int CREATE_EVENT = 0x01F0; public const int UPDATE_EVENT = 0x01F1; public const int CANCEL_EVENT = 0x01F2; public const int CONFIRM_EVENT = 0x01F3; public const int REJECT_EVENT = 0x01F4; public const int SET_DATA_LINK_STATUS = 0x0200; public const int SET_DATA_LINK_SELECT = 0x0201; public const int SET_GLOBAL_POSE = 0x0402; public const int SET_LOCAL_POSE = 0x0403; public const int SET_WRENCH_EFFORT = 0x0405; public const int SET_DISCRETE_DEVICES = 0x0406; public const int SET_GLOBAL_VECTOR = 0x0407; public const int SET_LOCAL_VECTOR = 0x0408; public const int SET_TRAVEL_SPEED = 0x040A; public const int SET_GLOBAL_WAYPOINT = 0x040C; public const int SET_LOCAL_WAYPOINT = 0x040D; public const int SET_GLOBAL_PATH_SEGMENT = 0x040F; public const int SET_LOCAL_PATH_SEGMENT = 0x0410; public const int SET_GEOMAGNETIC_PROPERTY = 0x0412; public const int SET_VELOCITY_COMMAND = 0x0415; public const int SET_ACCELERATION_LIMIT = 0x0416; public const int SET_ELEMENT = 0x041A; public const int DELETE_ELEMENT = 0x041B; public const int CONFIRM_ELEMENT_REQUEST = 0x041C; public const int REJECT_ELEMENT_REQUEST = 0x041D; public const int EXECUTE_LIST = 0x041E; public const int SET_JOINT_EFFORTS = 0x0601; public const int SET_JOINT_POSITIONS = 0x0602; public const int SET_JOINT_VELOCITIES = 0x0603; public const int SET_TOOL_POINT = 0x0604; public const int SET_END_EFFECTOR_VELOCITY_STATE = 0x0606; public const int SET_JOINT_MOTION = 0x0607; public const int SET_END_EFFECTOR_PATH_MOTION = 0x0608; public const int SET_END_EFFECTOR_POSE = 0x0610; public const int SET_PAN_TILT_JOINT_EFFORT = 0x0621; public const int SET_PAN_TILT_JOINT_VELOCITY = 0x0623; public const int SET_CAMERA_POSE = 0x0801; public const int SELECT_CAMERA = 0x0802; public const int SET_CAMERA_CAPABILITIES = 0x0805; public const int SET_CAMERA_FORMAT_OPTIONS = 0x0806; public const int REGISTER_SERVICES = 0x0B00; public const int SET_TOOL_OFFSET = 0x0604; // JAUS Query Class Messages public const int QUERY_AUTHORITY = 0x2001; public const int QUERY_STATUS = 0x2002; public const int QUERY_TIMEOUT = 0x2003; public const int QUERY_TIME = 0x2011; public const int QUERY_CONTROL = 0x200D; public const int QUERY_EVENTS = 0x21F0; public const int QUERY_DATA_LINK_STATUS = 0x2200; public const int QUERY_SELECTED_DATA_LINK_STATUS = 0x2201; public const int QUERY_HEARTBEAT_PULSE = 0x2202; public const int QUERY_PLATFORM_SPECIFICATIONS = 0x2400; public const int QUERY_PLATFORM_OPERATIONAL_DATA = 0x2401; public const int QUERY_GLOBAL_POSE = 0x2402; public const int QUERY_LOCAL_POSE = 0x2403; public const int QUERY_VELOCITY_STATE = 0x2404; public const int QUERY_WRENCH_EFFORT = 0x2405; public const int QUERY_DISCRETE_DEVICES = 0x2406; public const int QUERY_GLOBAL_VECTOR = 0x2407; public const int QUERY_LOCAL_VECTOR = 0x2408; public const int QUERY_TRAVEL_SPEED = 0x240A; public const int QUERY_WAYPOINT_COUNT = 0x240B; public const int QUERY_GLOBAL_WAYPOINT = 0x240C; public const int QUERY_LOCAL_WAYPOINT = 0x240D; public const int QUERY_PATH_SEGMENT_COUNT = 0x240E; public const int QUERY_GLOBAL_PATH_SEGMENT = 0x240F; public const int QUERY_LOCAL_PATH_SEGMENT = 0x2410; public const int QUERY_GEOMAGNETIC_PROPERTY = 0x2412; public const int QUERY_VELOCITY_COMMAND = 0x2415; public const int QUERY_ACCELERATION_LIMIT = 0x2416; public const int QUERY_ELEMENT = 0x241A; public const int QUERY_ELEMENT_LIST = 0x241B; public const int QUERY_ELEMENT_COUNT = 0x241C; public const int QUERY_ACTIVE_ELEMENT = 0x241E; public const int QUERY_MANIPULATOR_SPECIFICATIONS = 0x2600; public const int QUERY_JOINT_EFFORTS = 0x2601; public const int QUERY_JOINT_POSITIONS = 0x2602; public const int QUERY_JOINT_VELOCITIES = 0x2603; public const int QUERY_TOOL_POINT = 0x2604; public const int QUERY_JOINT_FORCE_TORQUES = 0x2605; public const int QUERY_COMMANDED_END_EFFECTOR_POSE = 0x2610; public const int QUERY_END_EFFECTOR_POSE = 0x2615; public const int QUERY_PAN_TILT_JOINT_EFFORT = 0x2621; public const int QUERY_PAN_TILT_JOINT_VELOCITY = 0x2623; public const int QUERY_COMMANDED_PAN_TILT_JOINT_VELOCITY = 0x2631; public const int QUERY_CAMERA_POSE = 0x2800; public const int QUERY_CAMERA_COUNT = 0x2801; public const int QUERY_RELATIVE_OBJECT_POSITION = 0x2802; public const int QUERY_SELECTED_CAMERA = 0x2804; public const int QUERY_CAMERA_CAPABILITIES = 0x2805; public const int QUERY_CAMERA_FORMAT_OPTIONS = 0x2806; public const int QUERY_IMAGE = 0x2807; public const int QUERY_IDENTIFICATION = 0x2B00; public const int QUERY_CONFIGURATION = 0x2B01; public const int QUERY_SUBSYSTEM_LIST = 0x2B02; public const int QUERY_SERVICES = 0x2B03; // JAUS Inform Class Messages public const int REPORT_AUTHORITY = 0x4001; public const int REPORT_STATUS = 0x4002; public const int REPORT_TIMEOUT = 0x4003; public const int REPORT_TIME = 0x4011; public const int REPORT_CONTROL = 0x400D; public const int REPORT_EVENTS = 0x41F0; public const int EVENT = 0x41F1; public const int REPORT_DATA_LINK_STATUS = 0x4200; public const int REPORT_SELECTED_DATA_LINK_STATUS = 0x4201; public const int REPORT_HEARTBEAT_PULSE = 0x4202; public const int REPORT_PLATFORM_SPECIFICATIONS = 0x4400; public const int REPORT_PLATFORM_OPERATIONAL_DATA = 0x4401; public const int REPORT_GLOBAL_POSE = 0x4402; public const int REPORT_LOCAL_POSE = 0x4403; public const int REPORT_VELOCITY_STATE = 0x4404; public const int REPORT_WRENCH_EFFORT = 0x4405; public const int REPORT_DISCRETE_DEVICES = 0x4406; public const int REPORT_GLOBAL_VECTOR = 0x4407; public const int REPORT_LOCAL_VECTOR = 0x4408; public const int REPORT_TRAVEL_SPEED = 0x440A; public const int REPORT_WAYPOINT_COUNT = 0x440B; public const int REPORT_GLOBAL_WAYPOINT = 0x440C; public const int REPORT_LOCAL_WAYPOINT = 0x440D; public const int REPORT_PATH_SEGMENT_COUNT = 0x440E; public const int REPORT_GLOBAL_PATH_SEGMENT = 0x440F; public const int REPORT_LOCAL_PATH_SEGMENT = 0x4410; public const int REPORT_GEOMAGNETIC_PROPERTY = 0x4412; public const int REPORT_VELOCITY_COMMAND = 0x4415; public const int REPORT_ACCELERATION_LIMIT = 0x4416; public const int REPORT_ELEMENT = 0x441A; public const int REPORT_ELEMENT_LIST = 0x441B; public const int REPORT_ELEMENT_COUNT = 0x441C; public const int REPORT_ACTIVE_ELEMENT = 0x441E; public const int REPORT_MANIPULATOR_SPECIFICATIONS = 0x4600; public const int REPORT_JOINT_EFFORTS = 0x4601; public const int REPORT_JOINT_POSITIONS = 0x4602; public const int REPORT_JOINT_VELOCITIES = 0x4603; public const int REPORT_TOOL_POINT = 0x4604; public const int REPORT_JOINT_FORCE_TORQUES = 0x4605; public const int REPORT_COMMANDED_END_EFFECTOR_POSE = 0x4610; public const int REPORT_END_EFFECTOR_POSE = 0x4615; public const int REPORT_PAN_TILT_JOINT_EFFORT = 0x4621; public const int REPORT_PAN_TILT_JOINT_VELOCITY = 0x4623; public const int REPORT_COMMANDED_PAN_TILT_JOINT_VELOCITY = 0x4631; public const int REPORT_CAMERA_POSE = 0x4800; public const int REPORT_CAMERA_COUNT = 0x4801; public const int REPORT_RELATIVE_OBJECT_POSITION = 0x4802; public const int REPORT_SELECTED_CAMERA = 0x4804; public const int REPORT_CAMERA_CAPABILITIES = 0x4805; public const int REPORT_CAMERA_FORMAT_OPTIONS = 0x4806; public const int REPORT_IMAGE = 0x4807; public const int REPORT_IDENTIFICATION = 0x4B00; public const int REPORT_CONFIGURATION = 0x4B01; public const int REPORT_SUBSYSTEM_LIST = 0x4B02; public const int REPORT_SERVICES = 0x4B03; //@ Deprecated public const int CONFIGURATION_CHANGED_EVENT_SETUP = 0xD6A8; //@ Deprecated public const int CONFIGURATION_CHANGED_EVENT_NOTIFICATION = 0xD8A8; // Message Type Enum /* public enum MessageType { COMMAND, QUERY, INFORM }*/ //private static HashMap<Integer, String> commandCodes = null; private static Dictionary<Int32, String> commandCodes = null; public static String Lookup(int code) { if (commandCodes == null) { commandCodes = new Dictionary<Int32, String>(); commandCodes.Add(NONE, "NONE"); commandCodes.Add(SET_AUTHORITY, "SET_AUTHORITY"); commandCodes.Add(SHUTDOWN, "SHUTDOWN"); commandCodes.Add(STANDBY, "STANDBY"); commandCodes.Add(RESUME, "RESUME"); commandCodes.Add(RESET, "RESET"); commandCodes.Add(SET_EMERGENCY, "SET_EMERGENCY"); commandCodes.Add(CLEAR_EMERGENCY, "CLEAR_EMERGENCY"); commandCodes.Add(CREATE_SERVICE_CONNECTION, "CREATE_SERVICE_CONNECTION"); commandCodes.Add(CONFIRM_SERVICE_CONNECTION, "CONFIRM_SERVICE_CONNECTION"); commandCodes.Add(ACTIVATE_SERVICE_CONNECTION, "ACTIVATE_SERVICE_CONNECTION"); commandCodes.Add(SUSPEND_SERVICE_CONNECTION, "SUSPEND_SERVICE_CONNECTION"); commandCodes.Add(TERMINATE_SERVICE_CONNECTION, "TERMINATE_SERVICE_CONNECTION"); commandCodes.Add(REQUEST_CONTROL, "REQUEST_CONTROL"); commandCodes.Add(RELEASE_CONTROL, "RELEASE_CONTROL"); commandCodes.Add(CONFIRM_CONTROL, "CONFIRM_CONTROL"); commandCodes.Add(REJECT_CONTROL, "REJECT_CONTROL"); commandCodes.Add(SET_TIME, "SET_TIME"); commandCodes.Add(CREATE_EVENT, "CREATE_EVENT"); commandCodes.Add(UPDATE_EVENT, "UPDATE_EVENT"); commandCodes.Add(CANCEL_EVENT, "CANCEL_EVENT"); commandCodes.Add(CONFIRM_EVENT, "CONFIRM_EVENT"); commandCodes.Add(REJECT_EVENT, "REJECT_EVENT"); commandCodes.Add(SET_DATA_LINK_STATUS, "SET_DATA_LINK_STATUS"); commandCodes.Add(SET_DATA_LINK_SELECT, "SET_DATA_LINK_SELECT"); commandCodes.Add(SET_GLOBAL_POSE, "SET_GLOBAL_POSE"); commandCodes.Add(SET_LOCAL_POSE, "SET_LOCAL_POSE"); commandCodes.Add(SET_WRENCH_EFFORT, "SET_WRENCH_EFFORT"); commandCodes.Add(SET_DISCRETE_DEVICES, "SET_DISCRETE_DEVICES"); commandCodes.Add(SET_GLOBAL_VECTOR, "SET_GLOBAL_VECTOR"); commandCodes.Add(SET_LOCAL_VECTOR, "SET_LOCAL_VECTOR"); commandCodes.Add(SET_TRAVEL_SPEED, "SET_TRAVEL_SPEED"); commandCodes.Add(SET_GLOBAL_WAYPOINT, "SET_GLOBAL_WAYPOINT"); commandCodes.Add(SET_LOCAL_WAYPOINT, "SET_LOCAL_WAYPOINT"); commandCodes.Add(SET_GLOBAL_PATH_SEGMENT, "SET_GLOBAL_PATH_SEGMENT"); commandCodes.Add(SET_GEOMAGNETIC_PROPERTY, "SET_GEOMAGNETIC_PROPERTY"); commandCodes.Add(SET_VELOCITY_COMMAND, "SET_VELOCITY_COMMAND"); commandCodes.Add(SET_ACCELERATION_LIMIT, "SET_ACCELERATION_LIMIT"); commandCodes.Add(SET_LOCAL_PATH_SEGMENT, "SET_LOCAL_PATH_SEGMENT"); commandCodes.Add(SET_ELEMENT, "SET_ELEMENT"); commandCodes.Add(DELETE_ELEMENT, "DELETE_ELEMENT"); commandCodes.Add(CONFIRM_ELEMENT_REQUEST, "CONFIRM_ELEMENT_REQUEST"); commandCodes.Add(REJECT_ELEMENT_REQUEST, "REJECT_ELEMENT_REQUEST"); commandCodes.Add(EXECUTE_LIST, "EXECUTE_LIST"); commandCodes.Add(SET_JOINT_EFFORTS, "SET_JOINT_EFFORTS"); commandCodes.Add(SET_JOINT_POSITIONS, "SET_JOINT_POSITIONS"); commandCodes.Add(SET_JOINT_VELOCITIES, "SET_JOINT_VELOCITIES"); commandCodes.Add(SET_TOOL_POINT, "SET_TOOL_POINT"); commandCodes.Add(SET_END_EFFECTOR_POSE, "SET_END_EFFECTOR_POSE"); commandCodes.Add(SET_END_EFFECTOR_VELOCITY_STATE, "SET_END_EFFECTOR_VELOCITY_STATE"); commandCodes.Add(SET_JOINT_MOTION, "SET_JOINT_MOTION"); commandCodes.Add(SET_END_EFFECTOR_PATH_MOTION, "SET_END_EFFECTOR_PATH_MOTION"); commandCodes.Add(SET_CAMERA_POSE, "SET_CAMERA_POSE"); commandCodes.Add(SELECT_CAMERA, "SELECT_CAMERA"); commandCodes.Add(SET_CAMERA_CAPABILITIES, "SET_CAMERA_CAPABILITIES"); commandCodes.Add(SET_CAMERA_FORMAT_OPTIONS, "SET_CAMERA_FORMAT_OPTIONS"); commandCodes.Add(REGISTER_SERVICES, "REGISTER_SERVICES"); // JAUS Query Class Messages commandCodes.Add(QUERY_AUTHORITY, "QUERY_AUTHORITY"); commandCodes.Add(QUERY_STATUS, "QUERY_STATUS"); commandCodes.Add(QUERY_TIMEOUT, "QUERY_TIMEOUT"); commandCodes.Add(QUERY_TIME, "QUERY_TIME"); commandCodes.Add(QUERY_CONTROL, "QUERY_CONTROL"); commandCodes.Add(QUERY_EVENTS, "QUERY_EVENTS"); commandCodes.Add(QUERY_DATA_LINK_STATUS, "QUERY_DATA_LINK_STATUS"); commandCodes.Add(QUERY_SELECTED_DATA_LINK_STATUS, "QUERY_SELECTED_DATA_LINK_STATUS"); commandCodes.Add(QUERY_HEARTBEAT_PULSE, "QUERY_HEARTBEAT_PULSE"); commandCodes.Add(QUERY_PLATFORM_SPECIFICATIONS, "QUERY_PLATFORM_SPECIFICATIONS"); commandCodes.Add(QUERY_PLATFORM_OPERATIONAL_DATA, "QUERY_PLATFORM_OPERATIONAL_DATA"); commandCodes.Add(QUERY_GLOBAL_POSE, "QUERY_GLOBAL_POSE"); commandCodes.Add(QUERY_LOCAL_POSE, "QUERY_LOCAL_POSE"); commandCodes.Add(QUERY_VELOCITY_STATE, "QUERY_VELOCITY_STATE"); commandCodes.Add(QUERY_WRENCH_EFFORT, "QUERY_WRENCH_EFFORT"); commandCodes.Add(QUERY_DISCRETE_DEVICES, "QUERY_DISCRETE_DEVICES"); commandCodes.Add(QUERY_GLOBAL_VECTOR, "QUERY_GLOBAL_VECTOR"); commandCodes.Add(QUERY_LOCAL_VECTOR, "QUERY_LOCAL_VECTOR"); //commandCodes.Add(QUERY_LOCAL_VECTOR, "QUERY_LOCAL_VECTOR"); commandCodes.Add(QUERY_WAYPOINT_COUNT, "QUERY_WAYPOINT_COUNT"); commandCodes.Add(QUERY_GLOBAL_WAYPOINT, "QUERY_GLOBAL_WAYPOINT"); commandCodes.Add(QUERY_LOCAL_WAYPOINT, "QUERY_LOCAL_WAYPOINT"); commandCodes.Add(QUERY_PATH_SEGMENT_COUNT, "QUERY_PATH_SEGMENT_COUNT"); commandCodes.Add(QUERY_GLOBAL_PATH_SEGMENT, "QUERY_GLOBAL_PATH_SEGMENT"); commandCodes.Add(QUERY_LOCAL_PATH_SEGMENT, "QUERY_LOCAL_PATH_SEGMENT"); commandCodes.Add(QUERY_GEOMAGNETIC_PROPERTY, "QUERY_GEOMAGNETIC_PROPERTY"); commandCodes.Add(QUERY_VELOCITY_COMMAND, "QUERY_VELOCITY_COMMAND"); commandCodes.Add(QUERY_ACCELERATION_LIMIT, "QUERY_ACCELERATION_LIMIT"); commandCodes.Add(QUERY_ELEMENT, "QUERY_ELEMENT"); commandCodes.Add(QUERY_ELEMENT_LIST, "QUERY_ELEMENT_LIST"); commandCodes.Add(QUERY_ELEMENT_COUNT, "QUERY_ELEMENT_COUNT"); commandCodes.Add(QUERY_ACTIVE_ELEMENT, "QUERY_ACTIVE_ELEMENT"); commandCodes.Add(QUERY_MANIPULATOR_SPECIFICATIONS, "QUERY_MANIPULATOR_SPECIFICATIONS"); commandCodes.Add(QUERY_JOINT_EFFORTS, "QUERY_JOINT_EFFORTS"); commandCodes.Add(QUERY_JOINT_POSITIONS, "QUERY_JOINT_POSITIONS"); commandCodes.Add(QUERY_JOINT_VELOCITIES, "QUERY_JOINT_VELOCITIES"); commandCodes.Add(QUERY_TOOL_POINT, "QUERY_TOOL_POINT"); commandCodes.Add(QUERY_JOINT_FORCE_TORQUES, "QUERY_JOINT_FORCE_TORQUES"); commandCodes.Add(QUERY_CAMERA_POSE, "QUERY_CAMERA_POSE"); commandCodes.Add(QUERY_CAMERA_COUNT, "QUERY_CAMERA_COUNT"); commandCodes.Add(QUERY_RELATIVE_OBJECT_POSITION, "QUERY_RELATIVE_OBJECT_POSITION"); commandCodes.Add(QUERY_SELECTED_CAMERA, "QUERY_SELECTED_CAMERA"); commandCodes.Add(QUERY_CAMERA_CAPABILITIES, "QUERY_CAMERA_CAPABILITIES"); commandCodes.Add(QUERY_CAMERA_FORMAT_OPTIONS, "QUERY_CAMERA_FORMAT_OPTIONS"); commandCodes.Add(QUERY_IMAGE, "QUERY_IMAGE"); commandCodes.Add(QUERY_IDENTIFICATION, "QUERY_IDENTIFICATION"); commandCodes.Add(QUERY_CONFIGURATION, "QUERY_CONFIGURATION"); commandCodes.Add(QUERY_SUBSYSTEM_LIST, "QUERY_SUBSYSTEM_LIST"); commandCodes.Add(QUERY_SERVICES, "QUERY_SERVICES"); // JAUS Inform Class Messages commandCodes.Add(REPORT_AUTHORITY, "REPORT_AUTHORITY"); commandCodes.Add(REPORT_STATUS, "REPORT_STATUS"); commandCodes.Add(REPORT_TIMEOUT, "REPORT_TIMEOUT"); commandCodes.Add(REPORT_TIME, "REPORT_TIME"); commandCodes.Add(REPORT_CONTROL, "REPORT_CONTROL"); commandCodes.Add(REPORT_EVENTS, "REPORT_EVENTS"); commandCodes.Add(EVENT, "EVENT"); commandCodes.Add(REPORT_DATA_LINK_STATUS, "REPORT_DATA_LINK_STATUS"); commandCodes.Add(REPORT_SELECTED_DATA_LINK_STATUS, "REPORT_SELECTED_DATA_LINK_STATUS"); commandCodes.Add(REPORT_HEARTBEAT_PULSE, "REPORT_HEARTBEAT_PULSE"); commandCodes.Add(REPORT_PLATFORM_SPECIFICATIONS, "REPORT_PLATFORM_SPECIFICATIONS"); commandCodes.Add(REPORT_PLATFORM_OPERATIONAL_DATA, "REPORT_PLATFORM_OPERATIONAL_DATA"); commandCodes.Add(REPORT_GLOBAL_POSE, "REPORT_GLOBAL_POSE"); commandCodes.Add(REPORT_LOCAL_POSE, "REPORT_LOCAL_POSE"); commandCodes.Add(REPORT_VELOCITY_STATE, "REPORT_VELOCITY_STATE"); commandCodes.Add(REPORT_WRENCH_EFFORT, "REPORT_WRENCH_EFFORT"); commandCodes.Add(REPORT_DISCRETE_DEVICES, "REPORT_DISCRETE_DEVICES"); commandCodes.Add(REPORT_GLOBAL_VECTOR, "REPORT_GLOBAL_VECTOR"); commandCodes.Add(REPORT_LOCAL_VECTOR, "REPORT_LOCAL_VECTOR"); commandCodes.Add(REPORT_TRAVEL_SPEED, "REPORT_TRAVEL_SPEED"); commandCodes.Add(REPORT_WAYPOINT_COUNT, "REPORT_WAYPOINT_COUNT"); commandCodes.Add(REPORT_GLOBAL_WAYPOINT, "REPORT_GLOBAL_WAYPOINT"); commandCodes.Add(REPORT_LOCAL_WAYPOINT, "REPORT_LOCAL_WAYPOINT"); commandCodes.Add(REPORT_PATH_SEGMENT_COUNT, "REPORT_PATH_SEGMENT_COUNT"); commandCodes.Add(REPORT_GLOBAL_PATH_SEGMENT, "REPORT_GLOBAL_PATH_SEGMENT"); commandCodes.Add(REPORT_LOCAL_PATH_SEGMENT, "REPORT_LOCAL_PATH_SEGMENT"); commandCodes.Add(REPORT_GEOMAGNETIC_PROPERTY, "REPORT_GEOMAGNETIC_PROPERTY"); commandCodes.Add(REPORT_VELOCITY_COMMAND, "REPORT_VELOCITY_COMMAND"); commandCodes.Add(REPORT_ACCELERATION_LIMIT, "REPORT_ACCELERATION_LIMIT"); commandCodes.Add(REPORT_ELEMENT, "REPORT_ELEMENT"); commandCodes.Add(REPORT_ELEMENT_LIST, "REPORT_ELEMENT_LIST"); commandCodes.Add(REPORT_ELEMENT_COUNT, "REPORT_ELEMENT_COUNT"); commandCodes.Add(REPORT_ACTIVE_ELEMENT, "REPORT_ACTIVE_ELEMENT"); commandCodes.Add(REPORT_MANIPULATOR_SPECIFICATIONS, "REPORT_MANIPULATOR_SPECIFICATIONS"); commandCodes.Add(REPORT_JOINT_EFFORTS, "REPORT_JOINT_EFFORTS"); commandCodes.Add(REPORT_JOINT_POSITIONS, "REPORT_JOINT_POSITIONS"); commandCodes.Add(REPORT_JOINT_VELOCITIES, "REPORT_JOINT_VELOCITIES"); commandCodes.Add(REPORT_TOOL_POINT, "REPORT_TOOL_POINT"); commandCodes.Add(REPORT_JOINT_FORCE_TORQUES, "REPORT_JOINT_FORCE_TORQUES"); commandCodes.Add(REPORT_CAMERA_POSE, "REPORT_CAMERA_POSE"); commandCodes.Add(REPORT_CAMERA_COUNT, "REPORT_CAMERA_COUNT"); commandCodes.Add(REPORT_RELATIVE_OBJECT_POSITION, "REPORT_RELATIVE_OBJECT_POSITION"); commandCodes.Add(REPORT_SELECTED_CAMERA, "REPORT_SELECTED_CAMERA"); commandCodes.Add(REPORT_CAMERA_CAPABILITIES, "REPORT_CAMERA_CAPABILITIES"); commandCodes.Add(REPORT_CAMERA_FORMAT_OPTIONS, "REPORT_CAMERA_FORMAT_OPTIONS"); commandCodes.Add(REPORT_IMAGE, "REPORT_IMAGE"); commandCodes.Add(REPORT_IDENTIFICATION, "REPORT_IDENTIFICATION"); commandCodes.Add(REPORT_CONFIGURATION, "REPORT_CONFIGURATION"); commandCodes.Add(REPORT_SUBSYSTEM_LIST, "REPORT_SUBSYSTEM_LIST"); commandCodes.Add(REPORT_SERVICES, "REPORT_SERVICES"); } String output; commandCodes.TryGetValue(code, out output); return output; } } }
// ----------------------------------------------------------------------- // Licensed to The .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // ----------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Kerberos.NET; using Kerberos.NET.Crypto; using Kerberos.NET.Entities; using Kerberos.NET.Entities.Pac; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Tests.Kerberos.NET { [TestClass] public class NdrTests : BaseTest { private const string S4UProxyTicket = "boIF3zCCBdugAwIBBaEDAgEOogcDBQAgAAAAo4IFEGGCBQwwggUIoAMCAQWhHxsdQ09SUC5JREVOVElUWUlOVEVSVkVOVElPTi5DT02iGDAWoAMC" + "AQOhDzANGwRob3N0GwVkb3duMqOCBMQwggTAoAMCARehAwIBAqKCBLIEggSuLAxrwUFytLsDOwttiF/jwzkkbMeWkExGskLBYsvZdIBkW0LxtO4DaUURhfc0MOo2xLN7RdrWZthmAcZmyhHtas" + "rWH/Y0ZhpA53pnV9XibrvlMyrCT9xx8PitMIIwOVTvZnMG+sH6BcwbmXtQ+zfst6wrmKJcKtMn7gNEkW75v0CMFN6k6w7jZVuJBJNHsfIANgNBhsiS50wNsgtMCdqp11qWK582gNdWq2dCfFVE" + "HgCxV2cWK+jNJTR7wMlq/ov4au4udZaLVcbVB+QKbLbqWcwwKcNVqAeTsCatWXPxEprvGNjyiG+bz+MzHiNsqQYsLU5Kp7MxjPF3PYVVdSkp9eJKNsWFMkgTzEDFvAYIwRDKMzs7YxmVvklTt7" + "KUCLE3VYakRaFCCs5nQZ+ReXtZQHEAMCKnYJaLjeAvpeMINcpykINkocDMOn328UK56GGrYN7v2AEYdeo1PEmv5DLOQXcKHIoKbwY2VtI+yPFR/y9kit1pHsZMrhvDvCaQZxTunQFBO6EkX/86" + "MLJXNnPuo7byTHVJvc3BaGPQ7KXWXMBkgbVnT+dStjR9M7M+Pxtgn0rfPEg1S6l7fx5atoWVQLuZ9kJzpMPo5A5mKyrnMz6o8XRtcibBd7Jn00LrZc64ZAWDvipR5MRAWOEimcPZWMZWp+AM3Q" + "rR4uRCbi4ACIEf1cStUDh1AiFrBm7k18NFI3U5fKK8XOCKCwraflnGaZn7GCZSiQzB5gJHEpdJULnNtXWeGy9AUYQVqWFN0gnX3vUYW/lZKDmJZrEjcmS4/X/I+At6HF1GFQJ353iYFXfbSxx1" + "Nit3ADAzlndH5EmBN+stmJLH6LlPY6tVzOWwjLhGscFtndIPGZPQppOOn5WHhBz7zWE7B0d1owYD0e6s2J2lUcoYcsuOtKpPRUXLfLthnorCs+wucaCujAVydAMzXNWkOHA9iIlZTMwGQGpjwN" + "Q1iJ8z12hgMefpC1QGWcNMButfZaTW461lSAWL70diYIps8Z993AZ2Gx+Mlnr3OXebpFenqTCoicakNZ6FpKBcYF+DCJ6k69ZE5HAYxIdmqM4LtfEhfrHGfK56KDTAKqhubm+RPgDNdzFz5m+Y" + "yOLN29/oAFBMlXtMUq3lBwOmbt+Eg/LlkbKBIgbNXhCaIPqi+RJdU7hDkJEP17ZUbFWCjxVHWOg3rcW0+Hm31MEq9iteGHGkTjiRpG8Ob+9xWWUaJ6Cj7RJp6Td3CXNf7h9UxDXVpJc9Sd1c+q" + "7Y/4KfWq7MqQEcYEi7Q5lKHPGf+rZlOUdi+59g0MVGW2SrpIWV8XWvtZsS9fEcEnG0hhlUr/rFMq4kIZhdBun5VJlZqOv5Ptirzn9xn/0g98pUltRQXnIi1r2O2hglWySOifIfX+gzH98+9310" + "Y1B5B/iEXp4hwNTsUiozw+CwTu78f+mpV2HBx31cV5VIScdZrqgYa3D51+CaBYsLSOe5gZkMBme+eNHzIRW95OCkpsY1K7F4nuNO0pwO73GvX22eliqOEuVPa1/82fgyD9y0rXjNwHbTHRrmef" + "QpXsMxbf8OTdTpPUjM+YO15nLKpyU1OkLkPG2OotRgIp0NoeKcyaSBsTCBrqADAgEXooGmBIGj24IhfgqoJAvOcADQ4hEiN9rrnB1iG43jBJqvsZlPtiy60LMNDKQEiQrW5yNca11V8ZJP0iPG" + "xEmequOqPQvcSAk4I3EpzYH7wcdvBN/Cie0xUC6nrLJAoO1sScn7iiR2xKwBwOLWSvJzUa5XZ7OlelLQjYCp2r3+I6TMPf8OUEvuhzSfKm5rBiHpR9owA83+RsGtXTAQsFZ8bghEsO8Q9QRq9A=="; private static async Task<PrivilegedAttributeCertificate> GeneratePac(bool includeClaims) { DecryptedKrbApReq result = null; if (includeClaims) { result = await GeneratePacContainingClaims(); } else { result = await GeneratePacWithoutClaims(); } var pacData = result.Ticket.AuthorizationData .Where(d => d.Type == AuthorizationDataType.AdIfRelevant) .Select(d => d.DecodeAdIfRelevant() .Where(a => a.Type == AuthorizationDataType.AdWin2kPac) ).First(); var pac = new PrivilegedAttributeCertificate(new KrbAuthorizationData { Type = AuthorizationDataType.AdWin2kPac, Data = pacData.First().Data }); Assert.AreEqual(0, pac.DecodingErrors.Count()); return pac; } private static async Task<DecryptedKrbApReq> GeneratePacContainingClaims() { var validator = new KerberosValidator(new KerberosKey("P@ssw0rd!")) { ValidateAfterDecrypt = DefaultActions }; var result = await validator.Validate(Convert.FromBase64String(RC4TicketClaims)); return result; } private static async Task<DecryptedKrbApReq> GeneratePacWithoutClaims() { var validator = new KerberosValidator( new KeyTable( new KerberosKey( "P@ssw0rd!", principalName: new PrincipalName( PrincipalNameType.NT_PRINCIPAL, "CORP.IDENTITYINTERVENTION.com", new[] { "[email protected]" } ), saltType: SaltType.ActiveDirectoryUser ) ) ) { ValidateAfterDecrypt = DefaultActions }; return await validator.Validate(Convert.FromBase64String(S4UProxyTicket)); } private static T TestPacEncoding<T>(T thing) where T : PacObject, new() { var encoded = thing.Marshal(); var decodedThing = new T(); decodedThing.Unmarshal(encoded.ToArray()); return decodedThing; } [TestMethod] public async Task PacDelegationInfo() { var pac = await GeneratePac(false); var deleg = pac.DelegationInformation; Assert.AreEqual("host/down2\0", deleg.S4U2ProxyTarget.ToString()); } [TestMethod] public async Task PacDelegationInfoRoundtrip() { var pac = await GeneratePac(false); var deleg = pac.DelegationInformation; Assert.AreEqual("host/down2\0", deleg.S4U2ProxyTarget.ToString()); var decoded = TestPacEncoding(deleg); Assert.IsNotNull(decoded); Assert.AreEqual(deleg.S4U2ProxyTarget, decoded.S4U2ProxyTarget); for (var i = 0; i < deleg.S4UTransitedServices.Count(); i++) { Assert.AreEqual(deleg.S4UTransitedServices.ElementAt(i), decoded.S4UTransitedServices.ElementAt(i)); } } [TestMethod] public async Task PacClientInfoRoundtrip() { var pac = await GeneratePac(true); var client = pac.ClientInformation; var clientDecoded = TestPacEncoding(client); Assert.AreEqual("Administrator", clientDecoded.Name); } [TestMethod] public async Task PacServerSignatureRoundtrip() { var pac = await GeneratePac(true); var signature = pac.ServerSignature; var signatureDecoded = TestPacEncoding(signature); Assert.IsTrue(signature.Signature.Span.SequenceEqual(signatureDecoded.Signature.Span)); } // [TestMethod] // public async Task NdrClaimsRoundtrip() // { // var pac = await GeneratePac(true); // var claims = pac.ClientClaims; // var claimsDecoded = TestPacEncoding(claims); // Assert.IsNotNull(claimsDecoded); // Assert.AreEqual(claims.ClaimsSet.ClaimsArray.Count(), claimsDecoded.ClaimsSet.ClaimsArray.Count()); // for (var i = 0; i < claims.ClaimsSet.ClaimsArray.Count(); i++) // { // var left = claims.ClaimsSet.ClaimsArray.ElementAt(i); // var right = claimsDecoded.ClaimsSet.ClaimsArray.ElementAt(i); // Assert.AreEqual(left.ClaimSource, right.ClaimSource); // Assert.AreEqual(left.ClaimEntries.Count(), right.ClaimEntries.Count()); // for (var c = 0; c < left.ClaimEntries.Count(); c++) // { // var claimLeft = left.ClaimEntries.ElementAt(c); // var claimRight = right.ClaimEntries.ElementAt(c); // Assert.AreEqual(claimLeft.Type, claimRight.Type); // Assert.AreEqual(claimLeft.Id, claimRight.Id); // Assert.AreEqual(claimLeft.Values.Count(), claimRight.Values.Count()); // Assert.IsTrue(claimLeft.Values.SequenceEqual(claimRight.Values)); // } // } // } [TestMethod] public async Task NdrLogonInfoRoundtrip() { var pac = await GeneratePac(true); var logonInfo = pac.LogonInfo; var logonInfoDecoded = TestPacEncoding(logonInfo); Assert.IsNotNull(logonInfoDecoded); AssertEqualLogonInfo(logonInfo, logonInfoDecoded); } [TestMethod] public async Task NdrUpnInfoRoundtrip() { var pac = await GeneratePac(true); var upnInfo = pac.UpnDomainInformation; var upnInfoDecoded = TestPacEncoding(upnInfo); Assert.IsNotNull(upnInfoDecoded); Assert.AreEqual("[email protected]", upnInfoDecoded.Upn); } private static void AssertEqualLogonInfo(PacLogonInfo left, PacLogonInfo right) { Assert.AreEqual(left.DomainName, right.DomainName); Assert.AreEqual(left.UserName, right.UserName); AssertSidsAreEqual(left.DomainSid, right.DomainSid); AssertSidsAreEqual(left.UserSid, right.UserSid); Assert.AreEqual(left.GroupSids.Count(), right.GroupSids.Count()); AssertSidsAreEqual(left.GroupSids, right.GroupSids); Assert.AreEqual(left.ExtraSids.Count(), right.ExtraSids.Count()); AssertSidsAreEqual(left.ExtraSids, right.ExtraSids); } private static void AssertSidsAreEqual(IEnumerable<SecurityIdentifier> leftSids, IEnumerable<SecurityIdentifier> rightSids) { for (var i = 0; i < leftSids.Count(); i++) { var leftSid = leftSids.ElementAt(i); var rightSid = rightSids.ElementAt(i); AssertSidsAreEqual(leftSid, rightSid); } } private static void AssertSidsAreEqual(SecurityIdentifier leftSid, SecurityIdentifier rightSid) { Assert.AreEqual(leftSid.Value, rightSid.Value); Assert.AreEqual(leftSid.Attributes, rightSid.Attributes); } } }
// ---------------------------------------------------------------------------- // <copyright file="PhotonEditor.cs" company="Exit Games GmbH"> // PhotonNetwork Framework for Unity - Copyright (C) 2011 Exit Games GmbH // </copyright> // <summary> // MenuItems and in-Editor scripts for PhotonNetwork. // </summary> // <author>[email protected]</author> // ---------------------------------------------------------------------------- //#define PHOTON_VOICE using System; using System.Collections.Generic; using System.IO; using System.Reflection; using UnityEditor; using UnityEditorInternal; using UnityEngine; public class PunWizardText { public string WindowTitle = "PUN Wizard"; public string SetupWizardWarningTitle = "Warning"; public string SetupWizardWarningMessage = "You have not yet run the Photon setup wizard! Your game won't be able to connect. See Windows -> Photon Unity Networking."; public string MainMenuButton = "Main Menu"; public string SetupWizardTitle = "PUN Setup"; public string SetupWizardInfo = "Thanks for importing Photon Unity Networking.\nThis window should set you up.\n\n<b>-</b> To use an existing Photon Cloud App, enter your AppId.\n<b>-</b> To register an account or access an existing one, enter the account's mail address.\n<b>-</b> To use Photon OnPremise, skip this step."; public string EmailOrAppIdLabel = "AppId or Email"; public string AlreadyRegisteredInfo = "The email is registered so we can't fetch your AppId (without password).\n\nPlease login online to get your AppId and paste it above."; public string SkipRegistrationInfo = "Skipping? No problem:\nEdit your server settings in the PhotonServerSettings file."; public string RegisteredNewAccountInfo = "We created a (free) account and fetched you an AppId.\nWelcome. Your PUN project is setup."; public string AppliedToSettingsInfo = "Your AppId is now applied to this project."; public string SetupCompleteInfo = "<b>Done!</b>\nAll connection settings can be edited in the <b>PhotonServerSettings</b> now.\nHave a look."; public string CloseWindowButton = "Close"; public string SkipButton = "Skip"; public string SetupButton = "Setup Project"; public string MobileExportNoteLabel = "Build for mobiles impossible. Get PUN+ or Unity Pro for mobile or use Unity 5."; public string MobilePunPlusExportNoteLabel = "PUN+ available. Using native sockets for iOS/Android."; public string CancelButton = "Cancel"; public string PUNWizardLabel = "PUN Wizard"; public string SettingsButton = "Settings"; public string SetupServerCloudLabel = "Setup wizard for setting up your own server or the cloud."; public string WarningPhotonDisconnect = ""; public string ConverterLabel = "Converter"; public string StartButton = "Start"; public string UNtoPUNLabel = "Converts pure Unity Networking to Photon Unity Networking."; public string LocateSettingsButton = "Locate PhotonServerSettings"; public string SettingsHighlightLabel = "Highlights the used photon settings file in the project."; public string DocumentationLabel = "Documentation"; public string OpenPDFText = "Reference PDF"; public string OpenPDFTooltip = "Opens the local documentation pdf."; public string OpenDevNetText = "DevNet / Manual"; public string OpenDevNetTooltip = "Online documentation for Photon."; public string OpenCloudDashboardText = "Cloud Dashboard Login"; public string OpenCloudDashboardTooltip = "Review Cloud App information and statistics."; public string OpenForumText = "Open Forum"; public string OpenForumTooltip = "Online support for Photon."; public string OkButton = "Ok"; public string OwnHostCloudCompareLabel = "I am not quite sure how 'my own host' compares to 'cloud'."; public string ComparisonPageButton = "Cloud versus OnPremise"; public string ConnectionTitle = "Connecting"; public string ConnectionInfo = "Connecting to the account service..."; public string ErrorTextTitle = "Error"; public string IncorrectRPCListTitle = "Warning: RPC-list becoming incompatible!"; public string IncorrectRPCListLabel = "Your project's RPC-list is full, so we can't add some RPCs just compiled.\n\nBy removing outdated RPCs, the list will be long enough but incompatible with older client builds!\n\nMake sure you change the game version where you use PhotonNetwork.ConnectUsingSettings()."; public string RemoveOutdatedRPCsLabel = "Remove outdated RPCs"; public string FullRPCListTitle = "Warning: RPC-list is full!"; public string FullRPCListLabel = "Your project's RPC-list is too long for PUN.\n\nYou can change PUN's source to use short-typed RPC index. Look for comments 'LIMITS RPC COUNT'\n\nAlternatively, remove some RPC methods (use more parameters per RPC maybe).\n\nAfter a RPC-list refresh, make sure you change the game version where you use PhotonNetwork.ConnectUsingSettings()."; public string SkipRPCListUpdateLabel = "Skip RPC-list update"; public string PUNNameReplaceTitle = "Warning: RPC-list Compatibility"; public string PUNNameReplaceLabel = "PUN replaces RPC names with numbers by using the RPC-list. All clients must use the same list for that.\n\nClearing it most likely makes your client incompatible with previous versions! Change your game version or make sure the RPC-list matches other clients."; public string RPCListCleared = "Clear RPC-list"; public string ServerSettingsCleanedWarning = "Cleared the PhotonServerSettings.RpcList! This makes new builds incompatible with older ones. Better change game version in PhotonNetwork.ConnectUsingSettings()."; public string RpcFoundMessage = "Some code uses the obsolete RPC attribute. PUN now requires the PunRPC attribute to mark remote-callable methods.\nThe Editor can search and replace that code which will modify your source."; public string RpcFoundDialogTitle = "RPC Attribute Outdated"; public string RpcReplaceButton = "Replace. I got a backup."; public string RpcSkipReplace = "Not now."; public string WizardMainWindowInfo = "This window should help you find important settings for PUN, as well as documentation."; } [InitializeOnLoad] public class PhotonEditor : EditorWindow { protected static Type WindowType = typeof (PhotonEditor); protected Vector2 scrollPos = Vector2.zero; private readonly Vector2 preferredSize = new Vector2(350, 400); private static Texture2D BackgroundImage; public static PunWizardText CurrentLang = new PunWizardText(); protected static AccountService.Origin RegisterOrigin = AccountService.Origin.Pun; protected static string DocumentationLocation = "Assets/Photon Unity Networking/PhotonNetwork-Documentation.pdf"; protected static string UrlFreeLicense = "https://www.photonengine.com/dashboard/OnPremise"; protected static string UrlDevNet = "http://doc.photonengine.com/en/pun/current"; protected static string UrlForum = "http://forum.exitgames.com"; protected static string UrlCompare = "http://doc.photonengine.com/en/realtime/current/getting-started/onpremise-or-saas"; protected static string UrlHowToSetup = "http://doc.photonengine.com/en/onpremise/current/getting-started/photon-server-in-5min"; protected static string UrlAppIDExplained = "http://doc.photonengine.com/en/realtime/current/getting-started/obtain-your-app-id"; protected static string UrlAccountPage = "https://www.photonengine.com/Account/SignIn?email="; // opened in browser protected static string UrlCloudDashboard = "https://www.photonengine.com/dashboard?email="; private enum PhotonSetupStates { MainUi, RegisterForPhotonCloud, EmailAlreadyRegistered, GoEditPhotonServerSettings } private bool isSetupWizard = false; private PhotonSetupStates photonSetupState = PhotonSetupStates.RegisterForPhotonCloud; private bool minimumInput = false; private bool useMail = false; private bool useAppId = false; private bool useSkip = false; private bool highlightedSettings = false; private bool close = false; private string mailOrAppId = string.Empty; private static double lastWarning = 0; private static bool postCompileActionsDone; private static bool isPunPlus; private static bool androidLibExists; private static bool iphoneLibExists; // setup once on load static PhotonEditor() { EditorApplication.projectWindowChanged += EditorUpdate; EditorApplication.hierarchyWindowChanged += EditorUpdate; EditorApplication.playmodeStateChanged += PlaymodeStateChanged; EditorApplication.update += OnUpdate; // detect optional packages PhotonEditor.CheckPunPlus(); } // setup per window public PhotonEditor() { minSize = this.preferredSize; } [MenuItem("Window/Photon Unity Networking/PUN Wizard &p", false, 0)] protected static void MenuItemOpenWizard() { PhotonEditor win = GetWindow(WindowType, false, CurrentLang.WindowTitle, true) as PhotonEditor; win.photonSetupState = PhotonSetupStates.MainUi; win.isSetupWizard = false; } [MenuItem("Window/Photon Unity Networking/Highlight Server Settings %#&p", false, 1)] protected static void MenuItemHighlightSettings() { HighlightSettings(); } /// <summary>Creates an Editor window, showing the cloud-registration wizard for Photon (entry point to setup PUN).</summary> protected static void ShowRegistrationWizard() { PhotonEditor win = GetWindow(WindowType, false, CurrentLang.WindowTitle, true) as PhotonEditor; win.photonSetupState = PhotonSetupStates.RegisterForPhotonCloud; win.isSetupWizard = true; } // called 100 times / sec private static void OnUpdate() { // after a compile, check RPCs to create a cache-list if (!postCompileActionsDone && !EditorApplication.isCompiling && !EditorApplication.isPlayingOrWillChangePlaymode && PhotonNetwork.PhotonServerSettings != null) { #if UNITY_4_2 || UNITY_4_3 || UNITY_4_4 || UNITY_4_5 || UNITY_4_6 || UNITY_4_7 || UNITY_5 || UNITY_5_0 if (EditorApplication.isUpdating) { return; } #endif PhotonEditor.UpdateRpcList(); postCompileActionsDone = true; // on compile, this falls back to false (without actively doing anything) #if UNITY_4_2 || UNITY_4_3 || UNITY_4_4 || UNITY_4_5 || UNITY_4_6 || UNITY_4_7 || UNITY_5 || UNITY_5_0 PhotonEditor.ImportWin8Support(); #endif } } // called in editor, opens wizard for initial setup, keeps scene PhotonViews up to date and closes connections when compiling (to avoid issues) private static void EditorUpdate() { if (PhotonNetwork.PhotonServerSettings == null) { PhotonNetwork.CreateSettings(); } if (PhotonNetwork.PhotonServerSettings == null) { return; } // serverSetting is null when the file gets deleted. otherwise, the wizard should only run once and only if hosting option is not (yet) set if (!PhotonNetwork.PhotonServerSettings.DisableAutoOpenWizard && PhotonNetwork.PhotonServerSettings.HostType == ServerSettings.HostingOption.NotSet) { ShowRegistrationWizard(); PhotonNetwork.PhotonServerSettings.DisableAutoOpenWizard = true; PhotonEditor.SaveSettings(); } // Workaround for TCP crash. Plus this surpresses any other recompile errors. if (EditorApplication.isCompiling) { if (PhotonNetwork.connected) { if (lastWarning > EditorApplication.timeSinceStartup - 3) { // Prevent error spam Debug.LogWarning(CurrentLang.WarningPhotonDisconnect); lastWarning = EditorApplication.timeSinceStartup; } PhotonNetwork.Disconnect(); } } } // called in editor on change of play-mode (used to show a message popup that connection settings are incomplete) private static void PlaymodeStateChanged() { if (EditorApplication.isPlaying || !EditorApplication.isPlayingOrWillChangePlaymode) { return; } if (PhotonNetwork.PhotonServerSettings.HostType == ServerSettings.HostingOption.NotSet) { EditorUtility.DisplayDialog(CurrentLang.SetupWizardWarningTitle, CurrentLang.SetupWizardWarningMessage, CurrentLang.OkButton); } } #region GUI and Wizard // Window Update() callback. On-demand, when Window is open protected void Update() { if (this.close) { Close(); } } protected virtual void OnGUI() { if (BackgroundImage == null) { BackgroundImage = AssetDatabase.LoadAssetAtPath("Assets/Photon Unity Networking/Editor/PhotonNetwork/background.jpg", typeof(Texture2D)) as Texture2D; } PhotonSetupStates oldGuiState = this.photonSetupState; // used to fix an annoying Editor input field issue: wont refresh until focus is changed. GUI.SetNextControlName(""); this.scrollPos = GUILayout.BeginScrollView(this.scrollPos); if (this.photonSetupState == PhotonSetupStates.MainUi) { UiMainWizard(); } else { UiSetupApp(); } GUILayout.EndScrollView(); if (oldGuiState != this.photonSetupState) { GUI.FocusControl(""); } } protected virtual void UiSetupApp() { GUI.skin.label.wordWrap = true; if (!this.isSetupWizard) { GUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); if (GUILayout.Button(CurrentLang.MainMenuButton, GUILayout.ExpandWidth(false))) { this.photonSetupState = PhotonSetupStates.MainUi; } GUILayout.EndHorizontal(); } // setup header UiTitleBox(CurrentLang.SetupWizardTitle, BackgroundImage); // setup info text GUI.skin.label.richText = true; GUILayout.Label(CurrentLang.SetupWizardInfo); // input of appid or mail EditorGUILayout.Separator(); GUILayout.Label(CurrentLang.EmailOrAppIdLabel); this.mailOrAppId = EditorGUILayout.TextField(this.mailOrAppId).Trim(); // note: we trim all input if (this.mailOrAppId.Contains("@")) { // this should be a mail address this.minimumInput = (this.mailOrAppId.Length >= 5 && this.mailOrAppId.Contains(".")); this.useMail = this.minimumInput; this.useAppId = false; } else { // this should be an appId this.minimumInput = ServerSettingsInspector.IsAppId(this.mailOrAppId); this.useMail = false; this.useAppId = this.minimumInput; } // button to skip setup GUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); if (GUILayout.Button(CurrentLang.SkipButton, GUILayout.Width(100))) { this.photonSetupState = PhotonSetupStates.GoEditPhotonServerSettings; this.useSkip = true; this.useMail = false; this.useAppId = false; } // SETUP button EditorGUI.BeginDisabledGroup(!this.minimumInput); if (GUILayout.Button(CurrentLang.SetupButton, GUILayout.Width(100))) { this.useSkip = false; GUIUtility.keyboardControl = 0; if (this.useMail) { RegisterWithEmail(this.mailOrAppId); // sets state } if (this.useAppId) { this.photonSetupState = PhotonSetupStates.GoEditPhotonServerSettings; Undo.RecordObject(PhotonNetwork.PhotonServerSettings, "Update PhotonServerSettings for PUN"); PhotonNetwork.PhotonServerSettings.UseCloud(this.mailOrAppId); PhotonEditor.SaveSettings(); } } EditorGUI.EndDisabledGroup(); GUILayout.FlexibleSpace(); GUILayout.EndHorizontal(); // existing account needs to fetch AppId online if (this.photonSetupState == PhotonSetupStates.EmailAlreadyRegistered) { // button to open dashboard and get the AppId GUILayout.Space(15); GUILayout.Label(CurrentLang.AlreadyRegisteredInfo); GUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); if (GUILayout.Button(new GUIContent(CurrentLang.OpenCloudDashboardText, CurrentLang.OpenCloudDashboardTooltip), GUILayout.Width(205))) { Application.OpenURL(UrlCloudDashboard + Uri.EscapeUriString(this.mailOrAppId)); this.mailOrAppId = ""; } GUILayout.FlexibleSpace(); GUILayout.EndHorizontal(); } if (this.photonSetupState == PhotonSetupStates.GoEditPhotonServerSettings) { if (!this.highlightedSettings) { this.highlightedSettings = true; HighlightSettings(); } GUILayout.Space(15); if (this.useSkip) { GUILayout.Label(CurrentLang.SkipRegistrationInfo); } else if (this.useMail) { GUILayout.Label(CurrentLang.RegisteredNewAccountInfo); } else if (this.useAppId) { GUILayout.Label(CurrentLang.AppliedToSettingsInfo); } // setup-complete info GUILayout.Space(15); GUILayout.Label(CurrentLang.SetupCompleteInfo); // close window (done) GUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); if (GUILayout.Button(CurrentLang.CloseWindowButton, GUILayout.Width(205))) { this.close = true; } GUILayout.FlexibleSpace(); GUILayout.EndHorizontal(); } GUI.skin.label.richText = false; } private void UiTitleBox(string title, Texture2D bgIcon) { GUIStyle bgStyle = new GUIStyle(GUI.skin.GetStyle("Label")); bgStyle.normal.background = bgIcon; bgStyle.fontSize = 22; bgStyle.fontStyle = FontStyle.Bold; EditorGUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); EditorGUILayout.EndHorizontal(); Rect scale = GUILayoutUtility.GetLastRect(); scale.height = 30; GUI.Label(scale, title, bgStyle); GUILayout.Space(scale.height+5); } protected virtual void UiMainWizard() { GUILayout.Space(15); // title UiTitleBox(CurrentLang.PUNWizardLabel, BackgroundImage); // wizard info text GUILayout.Label(CurrentLang.WizardMainWindowInfo); GUILayout.Space(15); // pun+ info if (isPunPlus) { GUILayout.Label(CurrentLang.MobilePunPlusExportNoteLabel); GUILayout.Space(15); } #if !(UNITY_5_0 || UNITY_5) else if (!InternalEditorUtility.HasAdvancedLicenseOnBuildTarget(BuildTarget.Android) || !InternalEditorUtility.HasAdvancedLicenseOnBuildTarget(BuildTarget.iPhone)) { GUILayout.Label(CurrentLang.MobileExportNoteLabel); GUILayout.Space(15); } #endif // settings button GUILayout.BeginHorizontal(); GUILayout.Label(CurrentLang.SettingsButton, EditorStyles.boldLabel, GUILayout.Width(100)); GUILayout.BeginVertical(); if (GUILayout.Button(new GUIContent(CurrentLang.LocateSettingsButton, CurrentLang.SettingsHighlightLabel))) { HighlightSettings(); } if (GUILayout.Button(new GUIContent(CurrentLang.OpenCloudDashboardText, CurrentLang.OpenCloudDashboardTooltip))) { Application.OpenURL(UrlCloudDashboard + Uri.EscapeUriString(this.mailOrAppId)); } if (GUILayout.Button(new GUIContent(CurrentLang.SetupButton, CurrentLang.SetupServerCloudLabel))) { this.photonSetupState = PhotonSetupStates.RegisterForPhotonCloud; } GUILayout.EndVertical(); GUILayout.EndHorizontal(); GUILayout.Space(15); // converter GUILayout.BeginHorizontal(); GUILayout.Label(CurrentLang.ConverterLabel, EditorStyles.boldLabel, GUILayout.Width(100)); if (GUILayout.Button(new GUIContent(CurrentLang.StartButton, CurrentLang.UNtoPUNLabel))) { PhotonConverter.RunConversion(); } GUILayout.EndHorizontal(); EditorGUILayout.Separator(); // documentation GUILayout.BeginHorizontal(); GUILayout.Label(CurrentLang.DocumentationLabel, EditorStyles.boldLabel, GUILayout.Width(100)); GUILayout.BeginVertical(); if (GUILayout.Button(new GUIContent(CurrentLang.OpenPDFText, CurrentLang.OpenPDFTooltip))) { EditorUtility.OpenWithDefaultApp(DocumentationLocation); } if (GUILayout.Button(new GUIContent(CurrentLang.OpenDevNetText, CurrentLang.OpenDevNetTooltip))) { Application.OpenURL(UrlDevNet); } GUI.skin.label.wordWrap = true; GUILayout.Label(CurrentLang.OwnHostCloudCompareLabel); if (GUILayout.Button(CurrentLang.ComparisonPageButton)) { Application.OpenURL(UrlCompare); } if (GUILayout.Button(new GUIContent(CurrentLang.OpenForumText, CurrentLang.OpenForumTooltip))) { Application.OpenURL(UrlForum); } GUILayout.EndVertical(); GUILayout.EndHorizontal(); } #endregion protected virtual void RegisterWithEmail(string email) { EditorUtility.DisplayProgressBar(CurrentLang.ConnectionTitle, CurrentLang.ConnectionInfo, 0.5f); string accountServiceType = string.Empty; #if PHOTON_VOICE accountServiceType = "voice"; #endif AccountService client = new AccountService(); client.RegisterByEmail(email, RegisterOrigin, accountServiceType); // this is the synchronous variant using the static RegisterOrigin. "result" is in the client EditorUtility.ClearProgressBar(); if (client.ReturnCode == 0) { this.mailOrAppId = client.AppId; PhotonNetwork.PhotonServerSettings.UseCloud(this.mailOrAppId, 0); #if PHOTON_VOICE PhotonNetwork.PhotonServerSettings.VoiceAppID = client.AppId2; #endif PhotonEditor.SaveSettings(); this.photonSetupState = PhotonSetupStates.GoEditPhotonServerSettings; } else { PhotonNetwork.PhotonServerSettings.HostType = ServerSettings.HostingOption.PhotonCloud; PhotonEditor.SaveSettings(); Debug.LogWarning(client.Message + " ReturnCode: " + client.ReturnCode); if (client.Message.Contains("registered")) { this.photonSetupState = PhotonSetupStates.EmailAlreadyRegistered; } else { EditorUtility.DisplayDialog(CurrentLang.ErrorTextTitle, client.Message, CurrentLang.OkButton); this.photonSetupState = PhotonSetupStates.RegisterForPhotonCloud; } } } protected internal static bool CheckPunPlus() { androidLibExists = File.Exists("Assets/Plugins/Android/armeabi-v7a/libPhotonSocketPlugin.so") && File.Exists("Assets/Plugins/Android/x86/libPhotonSocketPlugin.so"); iphoneLibExists = File.Exists("Assets/Plugins/IOS/libPhotonSocketPlugin.a"); isPunPlus = androidLibExists || iphoneLibExists; return isPunPlus; } private static void ImportWin8Support() { if (EditorApplication.isCompiling || EditorApplication.isPlayingOrWillChangePlaymode) { return; // don't import while compiling } #if UNITY_4_2 || UNITY_4_3 || UNITY_4_4 || UNITY_4_5 || UNITY_4_6 || UNITY_4_7 || UNITY_5 || UNITY_5_0 const string win8Package = "Assets/Plugins/Photon3Unity3D-Win8.unitypackage"; bool win8LibsExist = File.Exists("Assets/Plugins/WP8/Photon3Unity3D.dll") && File.Exists("Assets/Plugins/Metro/Photon3Unity3D.dll"); if (!win8LibsExist && File.Exists(win8Package)) { AssetDatabase.ImportPackage(win8Package, false); } #endif } // Pings PhotonServerSettings and makes it selected (show in Inspector) private static void HighlightSettings() { Selection.objects = new UnityEngine.Object[] { PhotonNetwork.PhotonServerSettings }; EditorGUIUtility.PingObject(PhotonNetwork.PhotonServerSettings); } // Marks settings object as dirty, so it gets saved. // unity 5.3 changes the usecase for SetDirty(). but here we don't modify a scene object! so it's ok to use private static void SaveSettings() { EditorUtility.SetDirty(PhotonNetwork.PhotonServerSettings); } #region RPC List Handling public static void UpdateRpcList() { List<string> additionalRpcs = new List<string>(); HashSet<string> currentRpcs = new HashSet<string>(); var types = GetAllSubTypesInScripts(typeof(MonoBehaviour)); int countOldRpcs = 0; foreach (var mono in types) { MethodInfo[] methods = mono.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); foreach (MethodInfo method in methods) { bool isOldRpc = false; #pragma warning disable 618 // we let the Editor check for outdated RPC attributes in code. that should not cause a compile warning if (method.IsDefined(typeof (RPC), false)) { countOldRpcs++; isOldRpc = true; } #pragma warning restore 618 if (isOldRpc || method.IsDefined(typeof(PunRPC), false)) { currentRpcs.Add(method.Name); if (!additionalRpcs.Contains(method.Name) && !PhotonNetwork.PhotonServerSettings.RpcList.Contains(method.Name)) { additionalRpcs.Add(method.Name); } } } } if (additionalRpcs.Count > 0) { // LIMITS RPC COUNT if (additionalRpcs.Count + PhotonNetwork.PhotonServerSettings.RpcList.Count >= byte.MaxValue) { if (currentRpcs.Count <= byte.MaxValue) { bool clearList = EditorUtility.DisplayDialog(CurrentLang.IncorrectRPCListTitle, CurrentLang.IncorrectRPCListLabel, CurrentLang.RemoveOutdatedRPCsLabel, CurrentLang.CancelButton); if (clearList) { PhotonNetwork.PhotonServerSettings.RpcList.Clear(); PhotonNetwork.PhotonServerSettings.RpcList.AddRange(currentRpcs); } else { return; } } else { EditorUtility.DisplayDialog(CurrentLang.FullRPCListTitle, CurrentLang.FullRPCListLabel, CurrentLang.SkipRPCListUpdateLabel); return; } } additionalRpcs.Sort(); Undo.RecordObject(PhotonNetwork.PhotonServerSettings, "Update PUN RPC-list"); PhotonNetwork.PhotonServerSettings.RpcList.AddRange(additionalRpcs); PhotonEditor.SaveSettings(); } if (countOldRpcs > 0) { bool convertRPCs = EditorUtility.DisplayDialog(CurrentLang.RpcFoundDialogTitle, CurrentLang.RpcFoundMessage, CurrentLang.RpcReplaceButton, CurrentLang.RpcSkipReplace); if (convertRPCs) { PhotonConverter.ConvertRpcAttribute(""); } } } public static void ClearRpcList() { bool clearList = EditorUtility.DisplayDialog(CurrentLang.PUNNameReplaceTitle, CurrentLang.PUNNameReplaceLabel, CurrentLang.RPCListCleared, CurrentLang.CancelButton); if (clearList) { PhotonNetwork.PhotonServerSettings.RpcList.Clear(); Debug.LogWarning(CurrentLang.ServerSettingsCleanedWarning); } } public static System.Type[] GetAllSubTypesInScripts(System.Type aBaseClass) { var result = new System.Collections.Generic.List<System.Type>(); System.Reflection.Assembly[] AS = System.AppDomain.CurrentDomain.GetAssemblies(); foreach (var A in AS) { // this skips all but the Unity-scripted assemblies for RPC-list creation. You could remove this to search all assemblies in project if (!A.FullName.StartsWith("Assembly-")) { // Debug.Log("Skipping Assembly: " + A); continue; } //Debug.Log("Assembly: " + A.FullName); System.Type[] types = A.GetTypes(); foreach (var T in types) { if (T.IsSubclassOf(aBaseClass)) { result.Add(T); } } } return result.ToArray(); } #endregion }
using System; using System.Collections.Generic; using System.Globalization; using System.IO; #if !HAVE_LINQ using Newtonsoft.Json.Utilities.LinqBridge; #else using System.Linq; #endif using Newtonsoft.Json.Utilities; namespace Newtonsoft.Json.Linq.JsonPath { internal enum QueryOperator { None = 0, Equals = 1, NotEquals = 2, Exists = 3, LessThan = 4, LessThanOrEquals = 5, GreaterThan = 6, GreaterThanOrEquals = 7, And = 8, Or = 9 } internal abstract class QueryExpression { public QueryOperator Operator { get; set; } public abstract bool IsMatch(JToken root, JToken t); } internal class CompositeExpression : QueryExpression { public List<QueryExpression> Expressions { get; set; } public CompositeExpression() { Expressions = new List<QueryExpression>(); } public override bool IsMatch(JToken root, JToken t) { switch (Operator) { case QueryOperator.And: foreach (QueryExpression e in Expressions) { if (!e.IsMatch(root, t)) { return false; } } return true; case QueryOperator.Or: foreach (QueryExpression e in Expressions) { if (e.IsMatch(root, t)) { return true; } } return false; default: throw new ArgumentOutOfRangeException(); } } } internal class BooleanQueryExpression : QueryExpression { public object Left { get; set; } public object Right { get; set; } private IEnumerable<JToken> GetResult(JToken root, JToken t, object o) { if (o is JToken resultToken) { return new[] { resultToken }; } if (o is List<PathFilter> pathFilters) { return JPath.Evaluate(pathFilters, root, t, false); } return CollectionUtils.ArrayEmpty<JToken>(); } public override bool IsMatch(JToken root, JToken t) { if (Operator == QueryOperator.Exists) { return GetResult(root, t, Left).Any(); } using (IEnumerator<JToken> leftResults = GetResult(root, t, Left).GetEnumerator()) { if (leftResults.MoveNext()) { IEnumerable<JToken> rightResultsEn = GetResult(root, t, Right); ICollection<JToken> rightResults = rightResultsEn as ICollection<JToken> ?? rightResultsEn.ToList(); do { JToken leftResult = leftResults.Current; foreach (JToken rightResult in rightResults) { if (MatchTokens(leftResult, rightResult)) { return true; } } } while (leftResults.MoveNext()); } } return false; } private bool MatchTokens(JToken leftResult, JToken rightResult) { if (leftResult is JValue leftValue && rightResult is JValue rightValue) { switch (Operator) { case QueryOperator.Equals: if (EqualsWithStringCoercion(leftValue, rightValue)) { return true; } break; case QueryOperator.NotEquals: if (!EqualsWithStringCoercion(leftValue, rightValue)) { return true; } break; case QueryOperator.GreaterThan: if (leftValue.CompareTo(rightValue) > 0) { return true; } break; case QueryOperator.GreaterThanOrEquals: if (leftValue.CompareTo(rightValue) >= 0) { return true; } break; case QueryOperator.LessThan: if (leftValue.CompareTo(rightValue) < 0) { return true; } break; case QueryOperator.LessThanOrEquals: if (leftValue.CompareTo(rightValue) <= 0) { return true; } break; case QueryOperator.Exists: return true; } } else { switch (Operator) { case QueryOperator.Exists: // you can only specify primitive types in a comparison // notequals will always be true case QueryOperator.NotEquals: return true; } } return false; } private bool EqualsWithStringCoercion(JValue value, JValue queryValue) { if (value.Equals(queryValue)) { return true; } if (queryValue.Type != JTokenType.String) { return false; } string queryValueString = (string)queryValue.Value; string currentValueString; // potential performance issue with converting every value to string? switch (value.Type) { case JTokenType.Date: using (StringWriter writer = StringUtils.CreateStringWriter(64)) { #if HAVE_DATE_TIME_OFFSET if (value.Value is DateTimeOffset offset) { DateTimeUtils.WriteDateTimeOffsetString(writer, offset, DateFormatHandling.IsoDateFormat, null, CultureInfo.InvariantCulture); } else #endif { DateTimeUtils.WriteDateTimeString(writer, (DateTime)value.Value, DateFormatHandling.IsoDateFormat, null, CultureInfo.InvariantCulture); } currentValueString = writer.ToString(); } break; case JTokenType.Bytes: currentValueString = Convert.ToBase64String((byte[])value.Value); break; case JTokenType.Guid: case JTokenType.TimeSpan: currentValueString = value.Value.ToString(); break; case JTokenType.Uri: currentValueString = ((Uri)value.Value).OriginalString; break; default: return false; } return string.Equals(currentValueString, queryValueString, StringComparison.Ordinal); } } }
//----------------------------------------------------------------------- // <copyright file="MotionStereoDepthDataSource.cs" company="Google LLC"> // // Copyright 2020 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 // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // </copyright> //----------------------------------------------------------------------- using System; using UnityEngine; using UnityEngine.XR.ARFoundation; using UnityEngine.XR.ARSubsystems; using Object = UnityEngine.Object; /// <summary> /// Contains the CPU images and Texture2D related to depth estimation. /// </summary> public class MotionStereoDepthDataSource : IDepthDataSource { private Texture2D _confidenceTexture = Texture2D.blackTexture; private Matrix4x4 _depthDisplayMatrix = Matrix4x4.identity; private short[] _depthArray = new short[0]; private byte[] _depthBuffer = new byte[0]; private byte[] _confidenceArray = new byte[0]; private int _depthHeight = 0; private int _depthWidth = 0; private bool _initialized = false; private bool _useRawDepth = false; private XRCameraIntrinsics _depthCameraIntrinsics; private ARCameraManager _cameraManager; private AROcclusionManager _occlusionManager; private ARCameraBackground _cameraBackground; private delegate bool AcquireDepthImageDelegate( IntPtr sessionHandle, IntPtr frameHandle, ref IntPtr depthImageHandle); public MotionStereoDepthDataSource() { InitializeCameraIntrinsics(); } /// <summary> /// Gets a value indicating whether this class is ready to serve its callers. /// </summary> public bool Initialized { get { if (!_initialized) { InitializeCameraIntrinsics(); } return _initialized; } } /// <summary> /// Gets the CPU array that always contains the latest depth data. /// </summary> public short[] DepthArray => _depthArray; /// <summary> /// Gets the CPU array that always contains the latest sparse depth confidence data. /// Each pixel is a 8-bit unsigned integer representing the estimated confidence of the /// corresponding pixel in the depth image. The confidence value is between 0 and 255, /// inclusive, with 0 representing 0% confidence and 255 representing 100% confidence in the /// measured depth values. /// </summary> public byte[] ConfidenceArray => _confidenceArray; /// <summary> /// Gets the display matrix used to covert depth texture UV to display coordinates. /// </summary> public Matrix4x4 DepthDisplayMatrix => _depthDisplayMatrix; /// <summary> /// Gets the focal length in pixels. /// Focal length is conventionally represented in pixels. For a detailed /// explanation, please see /// http://ksimek.github.io/2013/08/13/intrinsic. /// Pixels-to-meters conversion can use SENSOR_INFO_PHYSICAL_SIZE and /// SENSOR_INFO_PIXEL_ARRAY_SIZE in the Android CameraCharacteristics API. /// </summary> public Vector2 FocalLength => _depthCameraIntrinsics.focalLength; /// <summary> /// Gets the principal point in pixels. /// </summary> public Vector2 PrincipalPoint => _depthCameraIntrinsics.principalPoint; /// <summary> /// Gets the intrinsic's width and height in pixels. /// </summary> public Vector2Int ImageDimensions => _depthCameraIntrinsics.resolution; /// <summary> /// Updates the texture with the latest depth data from ARCore. /// </summary> /// <param name="depthTexture">The texture to update with depth data.</param> public void UpdateDepthTexture(ref Texture2D depthTexture) { depthTexture = _occlusionManager.environmentDepthTexture; } /// <summary> /// Switch to raw depth otherwise it uses smooth texture. /// </summary> /// <param name="useRawDepth">Indicates whether to use raw depth.</param> public void SwitchToRawDepth(bool useRawDepth) { // Enable smooth depth by default. _occlusionManager.environmentDepthTemporalSmoothingRequested = !_useRawDepth; } /// <summary> /// Updates the texture with the latest confidence image corresponding to the sparse depth data. /// Each pixel is a 8-bit unsigned integer representing the estimated confidence of the /// corresponding pixel in the depth image. The confidence value is between 0 and 255, /// inclusive, with 0 representing 0% confidence and 255 representing 100% confidence in the /// measured depth values. /// </summary> /// <param name="confidenceTexture">The texture to update with confidence data.</param> public void UpdateConfidenceTexture(ref Texture2D confidenceTexture) { confidenceTexture = _confidenceTexture; } /// <summary> /// Triggers the depth array to be updated. /// This is useful when UpdateDepthTexture(...) is not called frequently /// since the depth array is updated at each UpdateDepthTexture(...) call. /// </summary> /// <returns> /// Returns a reference to the depth array. /// </returns> public short[] UpdateDepthArray() { int bufferLength = _depthWidth * _depthHeight; if (_depthArray.Length != bufferLength) { _depthArray = new short[bufferLength]; } Buffer.BlockCopy(_depthBuffer, 0, _depthArray, 0, _depthBuffer.Length); return _depthArray; } /// <summary> /// Triggers the confidence array to be updated from ARCore. /// This is useful when UpdateConfidenceTexture(...) is not called frequently /// since the confidence array is updated at each UpdateConfidenceTexture(...) call. /// </summary> /// <returns> /// Returns a reference to the confidence array. /// </returns> public byte[] UpdateConfidenceArray() { _confidenceArray = _confidenceTexture.GetRawTextureData(); return _confidenceArray; } private void OnCameraFrameReceived(ARCameraFrameEventArgs eventArgs) { _depthDisplayMatrix = eventArgs.displayMatrix.GetValueOrDefault(); if (_cameraBackground.useCustomMaterial && _cameraBackground.customMaterial != null) { _cameraBackground.customMaterial.SetTexture(DepthSource.DepthTexturePropertyName, _occlusionManager.environmentDepthTexture); _cameraBackground.customMaterial.SetMatrix(DepthSource.DisplayTransformPropertyName, _depthDisplayMatrix); } UpdateEnvironmentDepthImage(); UpdateEnvironmentDepthConfidenceImage(); } /// <summary> /// Queries and correctly scales camera intrinsics for depth to vertex reprojection. /// </summary> private void InitializeCameraIntrinsics() { if (ARSession.state != ARSessionState.SessionTracking) { Debug.LogWarningFormat("ARSession is not ready yet: {0}", ARSession.state); return; } _cameraManager ??= Object.FindObjectOfType<ARCameraManager>(); Debug.Assert(_cameraManager); _cameraManager.frameReceived += OnCameraFrameReceived; _occlusionManager ??= Object.FindObjectOfType<AROcclusionManager>(); Debug.Assert(_occlusionManager); // Enable smooth depth by default. _occlusionManager.environmentDepthTemporalSmoothingRequested = !_useRawDepth; _cameraBackground ??= Object.FindObjectOfType<ARCameraBackground>(); Debug.Assert(_cameraBackground); // Gets the camera parameters to create the required number of vertices. if (!_cameraManager.TryGetIntrinsics(out XRCameraIntrinsics cameraIntrinsics)) { Debug.LogError("MotionStereoDepthDataSource: Failed to obtain camera intrinsics."); return; } // Scales camera intrinsics to the depth map size. Vector2 intrinsicsScale; intrinsicsScale.x = _depthWidth / (float)cameraIntrinsics.resolution.x; intrinsicsScale.y = _depthHeight / (float)cameraIntrinsics.resolution.y; var focalLength = Utilities.MultiplyVector2(cameraIntrinsics.focalLength, intrinsicsScale); var principalPoint = Utilities.MultiplyVector2(cameraIntrinsics.principalPoint, intrinsicsScale); var resolution = new Vector2Int(_depthWidth, _depthHeight); _depthCameraIntrinsics = new XRCameraIntrinsics(focalLength, principalPoint, resolution); if (_depthCameraIntrinsics.resolution != Vector2.zero) { _initialized = true; Debug.Log("MotionStereoDepthDataSource intrinsics initialized."); } } void UpdateEnvironmentDepthImage() { if (_occlusionManager && _occlusionManager.TryAcquireEnvironmentDepthCpuImage(out XRCpuImage image)) { using (image) { _depthWidth = image.width; _depthHeight = image.height; int numPixels = image.width * image.height; int numBytes = numPixels * image.GetPlane(0).pixelStride; if (_depthBuffer.Length != numBytes) { _depthBuffer = new byte[numBytes]; } image.GetPlane(0).data.CopyTo(_depthBuffer); } } } void UpdateEnvironmentDepthConfidenceImage() { if (_occlusionManager && _occlusionManager.TryAcquireEnvironmentDepthConfidenceCpuImage(out XRCpuImage image)) { using (image) { UpdateRawImage(ref _confidenceTexture, image, TextureFormat.R8, TextureFormat.R8); } } } static void UpdateRawImage(ref Texture2D texture, XRCpuImage cpuImage, TextureFormat conversionFormat, TextureFormat textureFormat) { if (texture == null || texture.width != cpuImage.width || texture.height != cpuImage.height) { texture = new Texture2D(cpuImage.width, cpuImage.height, textureFormat, false); } var conversionParams = new XRCpuImage.ConversionParams(cpuImage, conversionFormat); var rawTextureData = texture.GetRawTextureData<byte>(); cpuImage.Convert(conversionParams, rawTextureData); texture.Apply(); } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Xml; using System.IO; using System.Collections; using OLEDB.Test.ModuleCore; using XmlCoreTest.Common; namespace XmlReaderTest.Common { public enum EINTEGRITY { //DataReader BEFORE_READ, AFTER_READ_FALSE, AFTER_RESETSTATE, //DataWriter BEFORE_WRITE, AFTER_WRITE_FALSE, AFTER_CLEAR, AFTER_FLUSH, // Both DataWriter and DataReader AFTER_CLOSE, CLOSE_IN_THE_MIDDLE, }; //////////////////////////////////////////////////////////////// // TestCase TCXMLIntegrity // //////////////////////////////////////////////////////////////// [InheritRequired()] public partial class TCXMLIntegrityBase : CDataReaderTestCase { private EINTEGRITY _eEIntegrity; public EINTEGRITY IntegrityVer { get { return _eEIntegrity; } set { _eEIntegrity = value; } } private static string s_ATTR = "Attr1"; private static string s_NS = "Foo"; private static string s_NAME = "PLAY0"; public virtual void ReloadSource() { // load the reader string strFile = GetTestFileName(EREADER_TYPE.GENERIC); DataReader.Internal = XmlReader.Create(FilePathUtil.getStream(strFile)); // position the reader at the expected place InitReaderPointer(); } public int InitReaderPointer() { int iRetVal = TEST_PASS; CError.WriteLine("InitReaderPointer:{0}", GetDescription()); if (GetDescription() == "BeforeRead") { IntegrityVer = EINTEGRITY.BEFORE_READ; CError.Compare(DataReader.ReadState, ReadState.Initial, "ReadState=Initial"); CError.Compare(DataReader.EOF, false, "EOF==false"); } else if (GetDescription() == "AfterReadIsFalse") { IntegrityVer = EINTEGRITY.AFTER_READ_FALSE; while (DataReader.Read()) ; CError.Compare(DataReader.ReadState, ReadState.EndOfFile, "ReadState=EOF"); CError.Compare(DataReader.EOF, true, "EOF==true"); } else if (GetDescription() == "AfterClose") { IntegrityVer = EINTEGRITY.AFTER_CLOSE; while (DataReader.Read()) ; DataReader.Close(); CError.Compare(DataReader.ReadState, ReadState.Closed, "ReadState=Closed"); CError.Compare(DataReader.EOF, false, "EOF==true"); } else if (GetDescription() == "AfterCloseInTheMiddle") { IntegrityVer = EINTEGRITY.CLOSE_IN_THE_MIDDLE; for (int i = 0; i < 1; i++) { if (false == DataReader.Read()) iRetVal = TEST_FAIL; CError.Compare(DataReader.ReadState, ReadState.Interactive, "ReadState=Interactive"); } DataReader.Close(); CError.Compare(DataReader.ReadState, ReadState.Closed, "ReadState=Closed"); CError.Compare(DataReader.EOF, false, "EOF==true"); CError.WriteLine("EOF = " + DataReader.EOF); } else if (GetDescription() == "AfterResetState") { IntegrityVer = EINTEGRITY.AFTER_RESETSTATE; // position the reader somewhere in the middle of the file DataReader.PositionOnElement("elem1"); DataReader.ResetState(); CError.Compare(DataReader.ReadState, ReadState.Initial, "ReadState=Initial"); } CError.WriteLine("ReadState = " + (DataReader.ReadState).ToString()); return iRetVal; } [Variation("NodeType")] public int GetXmlReaderNodeType() { ReloadSource(); CError.Compare(DataReader.NodeType, XmlNodeType.None, CurVariation.Desc); CError.Compare(DataReader.NodeType, XmlNodeType.None, CurVariation.Desc); return TEST_PASS; } [Variation("Name")] public int GetXmlReaderName() { CError.Compare(DataReader.Name, String.Empty, CurVariation.Desc); CError.Compare(DataReader.Name, String.Empty, CurVariation.Desc); return TEST_PASS; } [Variation("LocalName")] public int GetXmlReaderLocalName() { CError.Compare(DataReader.LocalName, String.Empty, CurVariation.Desc); CError.Compare(DataReader.LocalName, String.Empty, CurVariation.Desc); return TEST_PASS; } [Variation("NamespaceURI")] public int Namespace() { CError.Compare(DataReader.NamespaceURI, String.Empty, CurVariation.Desc); CError.Compare(DataReader.NamespaceURI, String.Empty, CurVariation.Desc); return TEST_PASS; } [Variation("Prefix")] public int Prefix() { CError.Compare(DataReader.Prefix, String.Empty, CurVariation.Desc); CError.Compare(DataReader.Prefix, String.Empty, CurVariation.Desc); return TEST_PASS; } [Variation("HasValue")] public int HasValue() { CError.Compare(DataReader.HasValue, false, CurVariation.Desc); CError.Compare(DataReader.HasValue, false, CurVariation.Desc); return TEST_PASS; } [Variation("Value")] public int GetXmlReaderValue() { CError.Compare(DataReader.Value, String.Empty, CurVariation.Desc); CError.Compare(DataReader.Value, String.Empty, CurVariation.Desc); return TEST_PASS; } [Variation("Depth")] public int GetDepth() { CError.Compare(DataReader.Depth, 0, CurVariation.Desc); CError.Compare(DataReader.Depth, 0, CurVariation.Desc); return TEST_PASS; } [Variation("BaseURI")] public virtual int GetBaseURI() { return TEST_SKIPPED; } [Variation("IsEmptyElement")] public int IsEmptyElement() { CError.Compare(DataReader.IsEmptyElement, false, CurVariation.Desc); CError.Compare(DataReader.IsEmptyElement, false, CurVariation.Desc); return TEST_PASS; } [Variation("IsDefault")] public int IsDefault() { CError.Compare(DataReader.IsDefault, false, CurVariation.Desc); CError.Compare(DataReader.IsDefault, false, CurVariation.Desc); return TEST_PASS; } [Variation("XmlSpace")] public int GetXmlSpace() { CError.Compare(DataReader.XmlSpace, XmlSpace.None, CurVariation.Desc); CError.Compare(DataReader.XmlSpace, XmlSpace.None, CurVariation.Desc); return TEST_PASS; } [Variation("XmlLang")] public int GetXmlLang() { CError.Compare(DataReader.XmlLang, String.Empty, CurVariation.Desc); CError.Compare(DataReader.XmlLang, String.Empty, CurVariation.Desc); return TEST_PASS; } [Variation("AttributeCount")] public int AttributeCount() { CError.Compare(DataReader.AttributeCount, 0, CurVariation.Desc); CError.Compare(DataReader.AttributeCount, 0, CurVariation.Desc); return TEST_PASS; } [Variation("HasAttributes")] public int HasAttribute() { CError.Compare(DataReader.HasAttributes, false, CurVariation.Desc); CError.Compare(DataReader.HasAttributes, false, CurVariation.Desc); return TEST_PASS; } [Variation("GetAttributes(name)")] public int GetAttributeName() { CError.Compare(DataReader.GetAttribute(s_ATTR), null, "Compare the GetAttribute"); return TEST_PASS; } [Variation("GetAttribute(String.Empty)")] public int GetAttributeEmptyName() { CError.Compare(DataReader.GetAttribute(String.Empty), null, "Compare the GetAttribute"); return TEST_PASS; } [Variation("GetAttribute(name,ns)")] public int GetAttributeNameNamespace() { CError.Compare(DataReader.GetAttribute(s_ATTR, s_NS), null, "Compare the GetAttribute"); return TEST_PASS; } [Variation("GetAttribute(String.Empty, String.Empty)")] public int GetAttributeEmptyNameNamespace() { CError.Compare(DataReader.GetAttribute(String.Empty, String.Empty), null, "Compare the GetAttribute"); return TEST_PASS; } [Variation("GetAttribute(i)")] public int GetAttributeOrdinal() { try { DataReader.GetAttribute(0); } catch (ArgumentOutOfRangeException) { return TEST_PASS; } throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION); } [Variation("this[i]")] public int HelperThisOrdinal() { ReloadSource(); try { string str = DataReader[0]; } catch (ArgumentOutOfRangeException) { return TEST_PASS; } throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION); } [Variation("this[name]")] public int HelperThisName() { ReloadSource(); CError.Compare(DataReader[s_ATTR], null, "Compare the GetAttribute"); return TEST_PASS; } [Variation("this[name,namespace]")] public int HelperThisNameNamespace() { ReloadSource(); string str = DataReader[s_ATTR, s_NS]; CError.Compare(DataReader[s_ATTR, s_NS], null, "Compare the GetAttribute"); return TEST_PASS; } [Variation("MoveToAttribute(name)")] public int MoveToAttributeName() { ReloadSource(); CError.Compare(DataReader.MoveToAttribute(s_ATTR), false, CurVariation.Desc); CError.Compare(DataReader.MoveToAttribute(s_ATTR), false, CurVariation.Desc); return TEST_PASS; } [Variation("MoveToAttributeNameNamespace(name,ns)")] public int MoveToAttributeNameNamespace() { ReloadSource(); CError.Compare(DataReader.MoveToAttribute(s_ATTR, s_NS), false, CurVariation.Desc); CError.Compare(DataReader.MoveToAttribute(s_ATTR, s_NS), false, CurVariation.Desc); return TEST_PASS; } [Variation("MoveToAttribute(i)")] public int MoveToAttributeOrdinal() { ReloadSource(); try { DataReader.MoveToAttribute(0); } catch (ArgumentOutOfRangeException) { return TEST_PASS; } throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION); } [Variation("MoveToFirstAttribute()")] public int MoveToFirstAttribute() { ReloadSource(); CError.Compare(DataReader.MoveToFirstAttribute(), false, CurVariation.Desc); CError.Compare(DataReader.MoveToFirstAttribute(), false, CurVariation.Desc); return TEST_PASS; } [Variation("MoveToNextAttribute()")] public int MoveToNextAttribute() { ReloadSource(); CError.Compare(DataReader.MoveToNextAttribute(), false, CurVariation.Desc); CError.Compare(DataReader.MoveToNextAttribute(), false, CurVariation.Desc); return TEST_PASS; } [Variation("MoveToElement()")] public int MoveToElement() { ReloadSource(); CError.Compare(DataReader.MoveToElement(), false, CurVariation.Desc); CError.Compare(DataReader.MoveToElement(), false, CurVariation.Desc); return TEST_PASS; } [Variation("Read")] public int ReadTestAfterClose() { if (IntegrityVer == EINTEGRITY.BEFORE_READ || IntegrityVer == EINTEGRITY.AFTER_RESETSTATE) { // not interesting for test return TEST_SKIPPED; } else { CError.Compare(DataReader.Read(), false, CurVariation.Desc); CError.Compare(DataReader.Read(), false, CurVariation.Desc); } return TEST_PASS; } [Variation("GetEOF")] public int GetEOF() { ReloadSource(); if ((IntegrityVer == EINTEGRITY.AFTER_READ_FALSE)) { CError.Compare(DataReader.EOF, true, CurVariation.Desc); CError.Compare(DataReader.EOF, true, CurVariation.Desc); } else { CError.Compare(DataReader.EOF, false, CurVariation.Desc); CError.Compare(DataReader.EOF, false, CurVariation.Desc); } return TEST_PASS; } [Variation("GetReadState")] public int GetReadState() { ReloadSource(); ReadState iState = ReadState.Initial; // EndOfFile State if ((IntegrityVer == EINTEGRITY.AFTER_READ_FALSE)) { iState = ReadState.EndOfFile; } // Closed State if ((IntegrityVer == EINTEGRITY.AFTER_CLOSE) || (IntegrityVer == EINTEGRITY.CLOSE_IN_THE_MIDDLE)) { iState = ReadState.Closed; } CError.Compare(DataReader.ReadState, iState, CurVariation.Desc); CError.Compare(DataReader.ReadState, iState, CurVariation.Desc); return TEST_PASS; } [Variation("Skip")] public int XMLSkip() { ReloadSource(); DataReader.Skip(); DataReader.Skip(); return TEST_PASS; } [Variation("NameTable")] public int TestNameTable() { ReloadSource(); CError.Compare(DataReader.NameTable != null, "nt"); return TEST_PASS; } [Variation("ReadInnerXml")] public int ReadInnerXmlTestAfterClose() { ReloadSource(); XmlNodeType nt = DataReader.NodeType; string name = DataReader.Name; string value = DataReader.Value; CError.Compare(DataReader.ReadInnerXml(), String.Empty, CurVariation.Desc); CError.Compare(DataReader.VerifyNode(nt, name, value), "vn"); return TEST_PASS; } [Variation("ReadOuterXml")] public int TestReadOuterXml() { ReloadSource(); XmlNodeType nt = DataReader.NodeType; string name = DataReader.Name; string value = DataReader.Value; CError.Compare(DataReader.ReadOuterXml(), String.Empty, CurVariation.Desc); CError.Compare(DataReader.VerifyNode(nt, name, value), "vn"); return TEST_PASS; } [Variation("MoveToContent")] public int TestMoveToContent() { if (IntegrityVer == EINTEGRITY.BEFORE_READ || IntegrityVer == EINTEGRITY.AFTER_RESETSTATE) { // not interseting for test return TEST_SKIPPED; } else { CError.WriteLine("NodeType " + DataReader.NodeType); CError.Compare(DataReader.MoveToContent(), XmlNodeType.None, CurVariation.Desc); } return TEST_PASS; } [Variation("IsStartElement")] public int TestIsStartElement() { if (IntegrityVer == EINTEGRITY.BEFORE_READ || IntegrityVer == EINTEGRITY.AFTER_RESETSTATE) { // not interseting for test return TEST_SKIPPED; } else { CError.Compare(DataReader.IsStartElement(), false, CurVariation.Desc); } return TEST_PASS; } [Variation("IsStartElement(name)")] public int TestIsStartElementName() { if (IntegrityVer == EINTEGRITY.BEFORE_READ || IntegrityVer == EINTEGRITY.AFTER_RESETSTATE) { // not interseting for test return TEST_SKIPPED; } else { CError.Compare(DataReader.IsStartElement(s_NAME), false, CurVariation.Desc); } return TEST_PASS; } [Variation("IsStartElement(String.Empty)")] public int TestIsStartElementName2() { if (IntegrityVer == EINTEGRITY.BEFORE_READ || IntegrityVer == EINTEGRITY.AFTER_RESETSTATE) { // not interseting for test return TEST_SKIPPED; } else { CError.Compare(DataReader.IsStartElement(String.Empty), false, CurVariation.Desc); } return TEST_PASS; } [Variation("IsStartElement(name, ns)")] public int TestIsStartElementNameNs() { if (IntegrityVer == EINTEGRITY.BEFORE_READ || IntegrityVer == EINTEGRITY.AFTER_RESETSTATE) { // not interseting for test return TEST_SKIPPED; } else { CError.Compare(DataReader.IsStartElement(s_NAME, s_NS), false, CurVariation.Desc); } return TEST_PASS; } [Variation("IsStartElement(String.Empty,String.Empty)")] public int TestIsStartElementNameNs2() { if (IntegrityVer == EINTEGRITY.BEFORE_READ || IntegrityVer == EINTEGRITY.AFTER_RESETSTATE) { // not interseting for test return TEST_SKIPPED; } else { CError.Compare(DataReader.IsStartElement(String.Empty, String.Empty), false, CurVariation.Desc); } return TEST_PASS; } [Variation("ReadStartElement")] public int TestReadStartElement() { if (IntegrityVer == EINTEGRITY.BEFORE_READ || IntegrityVer == EINTEGRITY.AFTER_RESETSTATE) { // not interseting for test return TEST_SKIPPED; } else { try { DataReader.ReadStartElement(); } catch (XmlException) { return TEST_PASS; } throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION); } } [Variation("ReadStartElement(name)")] public int TestReadStartElementName() { if (IntegrityVer == EINTEGRITY.BEFORE_READ || IntegrityVer == EINTEGRITY.AFTER_RESETSTATE) { // not interseting for test return TEST_SKIPPED; } else { try { DataReader.ReadStartElement(s_NAME); } catch (XmlException) { return TEST_PASS; } throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION); } } [Variation("ReadStartElement(String.Empty)")] public int TestReadStartElementName2() { if (IntegrityVer == EINTEGRITY.BEFORE_READ || IntegrityVer == EINTEGRITY.AFTER_RESETSTATE) { // not interseting for test return TEST_SKIPPED; } else { try { DataReader.ReadStartElement(String.Empty); } catch (XmlException) { return TEST_PASS; } throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION); } } [Variation("ReadStartElement(name, ns)")] public int TestReadStartElementNameNs() { if (IntegrityVer == EINTEGRITY.BEFORE_READ || IntegrityVer == EINTEGRITY.AFTER_RESETSTATE) { // not interseting for test return TEST_SKIPPED; } else { try { DataReader.ReadStartElement(s_NAME, s_NS); } catch (XmlException) { return TEST_PASS; } throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION); } } [Variation("ReadStartElement(String.Empty,String.Empty)")] public int TestReadStartElementNameNs2() { if (IntegrityVer == EINTEGRITY.BEFORE_READ || IntegrityVer == EINTEGRITY.AFTER_RESETSTATE) { // not interseting for test return TEST_SKIPPED; } else { try { DataReader.ReadStartElement(String.Empty, String.Empty); } catch (XmlException) { return TEST_PASS; } throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION); } } [Variation("ReadEndElement")] public int TestReadEndElement() { if (IntegrityVer == EINTEGRITY.BEFORE_READ || IntegrityVer == EINTEGRITY.AFTER_RESETSTATE) { // not interseting for test return TEST_SKIPPED; } else { try { DataReader.ReadEndElement(); } catch (XmlException) { return TEST_PASS; } throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION); } } [Variation("LookupNamespace")] public int LookupNamespace() { ReloadSource(); string[] astr = { "a", "Foo", /*String.Empty,*/ "Foo1", "Foo_S" }; // for String.Empty XmlTextReader returns null, while xmlreader returns "" for (int i = 0; i < astr.Length; i++) { if (DataReader.LookupNamespace(astr[i]) != null) { CError.WriteLine("Not NULL " + i + " LookupNameSpace " + DataReader.LookupNamespace(astr[i]) + "," + DataReader.NodeType); } CError.Compare(DataReader.LookupNamespace(astr[i]), null, CurVariation.Desc); } return TEST_PASS; } [Variation("ResolveEntity")] public int ResolveEntity() { ReloadSource(); try { DataReader.ResolveEntity(); } catch (InvalidOperationException) { return TEST_PASS; } throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION); } [Variation("ReadAttributeValue")] public int ReadAttributeValue() { ReloadSource(); CError.Compare(DataReader.ReadAttributeValue(), false, CurVariation.Desc); CError.Compare(DataReader.ReadAttributeValue(), false, CurVariation.Desc); return TEST_PASS; } [Variation("Close")] public int CloseTest() { DataReader.Close(); DataReader.Close(); DataReader.Close(); return TEST_PASS; } } }
//--------------------------------------------------------------------------- // // <copyright file="TemplatedAdorner.cs" company="Microsoft"> // Copyright (C) 2005 by Microsoft Corporation. All rights reserved. // </copyright> // // // Description: // TemplatedAdorner applies the style provided in the ctor to a // control and provides a transform via GetDesiredTransform that // will cause the AdornedElementPlaceholder to be positioned directly // over the AdornedElement. // // See specs at http://avalon/connecteddata/Specs/Validation.mht // // History: // 02/01/2005 mharper: created. // //--------------------------------------------------------------------------- using System; using System.Collections; using System.Collections.Specialized; using System.ComponentModel; using System.Diagnostics; using System.Windows.Media; using System.Windows; using System.Windows.Data; using System.Windows.Controls; using System.Windows.Documents; using MS.Utility; namespace MS.Internal.Controls { /// <summary> /// This class is sealed because it calls OnVisualChildrenChanged virtual in the /// constructor and it does not override it, but derived classes could. /// </summary> internal sealed class TemplatedAdorner: Adorner { private Control _child; /// <summary> /// The clear the single child of a TemplatedAdorner /// </summary> public void ClearChild() { this.RemoveVisualChild(_child); _child = null; } public TemplatedAdorner(UIElement adornedElement, ControlTemplate adornerTemplate) : base(adornedElement) { Debug.Assert(adornedElement != null, "adornedElement should not be null"); Debug.Assert(adornerTemplate != null, "adornerTemplate should not be null"); Control control = new Control(); control.DataContext = Validation.GetErrors(adornedElement); //control.IsEnabled = false; // Hittest should not work on visual subtree control.IsTabStop = false; // Tab should not get into adorner layer control.Template = adornerTemplate; _child = control; this.AddVisualChild(_child); } /// <summary> /// Adorners don't always want to be transformed in the same way as the elements they /// adorn. Adorners which adorn points, such as resize handles, want to be translated /// and rotated but not scaled. Adorners adorning an object, like a marquee, may want /// all transforms. This method is called by AdornerLayer to allow the adorner to /// filter out the transforms it doesn't want and return a new transform with just the /// transforms it wants applied. An adorner can also add an additional translation /// transform at this time, allowing it to be positioned somewhere other than the upper /// left corner of its adorned element. /// </summary> /// <param name="transform">The transform applied to the object the adorner adorns</param> /// <returns>Transform to apply to the adorner</returns> public override GeneralTransform GetDesiredTransform(GeneralTransform transform) { if (ReferenceElement == null) return transform; GeneralTransformGroup group = new GeneralTransformGroup(); group.Children.Add(transform); GeneralTransform t = this.TransformToDescendant(ReferenceElement); if (t != null) { group.Children.Add(t); } return group; } public FrameworkElement ReferenceElement { get { return _referenceElement; } set { _referenceElement = value; } } /// <summary> /// Derived class must implement to support Visual children. The method must return /// the child at the specified index. Index must be between 0 and GetVisualChildrenCount-1. /// /// By default a Visual does not have any children. /// /// Remark: /// During this virtual call it is not valid to modify the Visual tree. /// </summary> protected override Visual GetVisualChild(int index) { if(_child == null || index != 0) { throw new ArgumentOutOfRangeException("index", index, SR.Get(SRID.Visual_ArgumentOutOfRange)); } return _child; } /// <summary> /// Derived classes override this property to enable the Visual code to enumerate /// the Visual children. Derived classes need to return the number of children /// from this method. /// /// By default a Visual does not have any children. /// /// Remark: During this virtual method the Visual tree must not be modified. /// </summary> protected override int VisualChildrenCount { get { return _child != null ? 1 : 0; } } /// <summary> /// Measure adorner. /// </summary> protected override Size MeasureOverride(Size constraint) { Debug.Assert(_child != null, "_child should not be null"); if (ReferenceElement != null && AdornedElement != null && AdornedElement.IsMeasureValid && !DoubleUtil.AreClose(ReferenceElement.DesiredSize, AdornedElement.DesiredSize) ) { ReferenceElement.InvalidateMeasure(); } (_child).Measure(new Size(Double.PositiveInfinity, Double.PositiveInfinity)); return (_child).DesiredSize; } /// <summary> /// Default control arrangement is to only arrange /// the first visual child. No transforms will be applied. /// </summary> protected override Size ArrangeOverride(Size size) { Size finalSize; finalSize = base.ArrangeOverride(size); if (_child != null) { _child.Arrange(new Rect(new Point(), finalSize)); } return finalSize; } internal override bool NeedsUpdate(Size oldSize) { bool result = base.NeedsUpdate(oldSize); Visibility desired = AdornedElement.IsVisible ? Visibility.Visible : Visibility.Collapsed; if (desired != this.Visibility) { this.Visibility = desired; result = true; } return result; } private FrameworkElement _referenceElement; } }
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // Template Source: Templates\CSharp\Requests\EntityCollectionRequest.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.Net.Http; using System.Threading; using System.Linq.Expressions; /// <summary> /// The type UserPhotosCollectionRequest. /// </summary> public partial class UserPhotosCollectionRequest : BaseRequest, IUserPhotosCollectionRequest { /// <summary> /// Constructs a new UserPhotosCollectionRequest. /// </summary> /// <param name="requestUrl">The URL for the built request.</param> /// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param> /// <param name="options">Query and header option name value pairs for the request.</param> public UserPhotosCollectionRequest( string requestUrl, IBaseClient client, IEnumerable<Option> options) : base(requestUrl, client, options) { } /// <summary> /// Adds the specified ProfilePhoto to the collection via POST. /// </summary> /// <param name="profilePhoto">The ProfilePhoto to add.</param> /// <returns>The created ProfilePhoto.</returns> public System.Threading.Tasks.Task<ProfilePhoto> AddAsync(ProfilePhoto profilePhoto) { return this.AddAsync(profilePhoto, CancellationToken.None); } /// <summary> /// Adds the specified ProfilePhoto to the collection via POST. /// </summary> /// <param name="profilePhoto">The ProfilePhoto to add.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The created ProfilePhoto.</returns> public System.Threading.Tasks.Task<ProfilePhoto> AddAsync(ProfilePhoto profilePhoto, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "POST"; return this.SendAsync<ProfilePhoto>(profilePhoto, cancellationToken); } /// <summary> /// Gets the collection page. /// </summary> /// <returns>The collection page.</returns> public System.Threading.Tasks.Task<IUserPhotosCollectionPage> GetAsync() { return this.GetAsync(CancellationToken.None); } /// <summary> /// Gets the collection page. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The collection page.</returns> public async System.Threading.Tasks.Task<IUserPhotosCollectionPage> GetAsync(CancellationToken cancellationToken) { this.Method = "GET"; var response = await this.SendAsync<UserPhotosCollectionResponse>(null, cancellationToken).ConfigureAwait(false); if (response != null && response.Value != null && response.Value.CurrentPage != null) { if (response.AdditionalData != null) { object nextPageLink; response.AdditionalData.TryGetValue("@odata.nextLink", out nextPageLink); var nextPageLinkString = nextPageLink as string; if (!string.IsNullOrEmpty(nextPageLinkString)) { response.Value.InitializeNextPageRequest( this.Client, nextPageLinkString); } // Copy the additional data collection to the page itself so that information is not lost response.Value.AdditionalData = response.AdditionalData; } return response.Value; } return null; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="value">The expand value.</param> /// <returns>The request object to send.</returns> public IUserPhotosCollectionRequest Expand(string value) { this.QueryOptions.Add(new QueryOption("$expand", value)); return this; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="expandExpression">The expression from which to calculate the expand value.</param> /// <returns>The request object to send.</returns> public IUserPhotosCollectionRequest Expand(Expression<Func<ProfilePhoto, object>> expandExpression) { if (expandExpression == null) { throw new ArgumentNullException(nameof(expandExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(expandExpression)); } else { this.QueryOptions.Add(new QueryOption("$expand", value)); } return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="value">The select value.</param> /// <returns>The request object to send.</returns> public IUserPhotosCollectionRequest Select(string value) { this.QueryOptions.Add(new QueryOption("$select", value)); return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="selectExpression">The expression from which to calculate the select value.</param> /// <returns>The request object to send.</returns> public IUserPhotosCollectionRequest Select(Expression<Func<ProfilePhoto, object>> selectExpression) { if (selectExpression == null) { throw new ArgumentNullException(nameof(selectExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(selectExpression)); } else { this.QueryOptions.Add(new QueryOption("$select", value)); } return this; } /// <summary> /// Adds the specified top value to the request. /// </summary> /// <param name="value">The top value.</param> /// <returns>The request object to send.</returns> public IUserPhotosCollectionRequest Top(int value) { this.QueryOptions.Add(new QueryOption("$top", value.ToString())); return this; } /// <summary> /// Adds the specified filter value to the request. /// </summary> /// <param name="value">The filter value.</param> /// <returns>The request object to send.</returns> public IUserPhotosCollectionRequest Filter(string value) { this.QueryOptions.Add(new QueryOption("$filter", value)); return this; } /// <summary> /// Adds the specified skip value to the request. /// </summary> /// <param name="value">The skip value.</param> /// <returns>The request object to send.</returns> public IUserPhotosCollectionRequest Skip(int value) { this.QueryOptions.Add(new QueryOption("$skip", value.ToString())); return this; } /// <summary> /// Adds the specified orderby value to the request. /// </summary> /// <param name="value">The orderby value.</param> /// <returns>The request object to send.</returns> public IUserPhotosCollectionRequest OrderBy(string value) { this.QueryOptions.Add(new QueryOption("$orderby", value)); return this; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.IO; using System.Runtime.ExceptionServices; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; namespace System.Net { internal sealed unsafe class HttpRequestStream : Stream { private readonly HttpListenerContext _httpContext; private uint _dataChunkOffset; private int _dataChunkIndex; private bool _closed; internal const int MaxReadSize = 0x20000; //http.sys recommends we limit reads to 128k private bool _inOpaqueMode; internal HttpRequestStream(HttpListenerContext httpContext) { if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"httpContextt:{httpContext}"); _httpContext = httpContext; } public override bool CanSeek { get { return false; } } public override bool CanWrite { get { return false; } } public override bool CanRead { get { return true; } } internal bool Closed { get { return _closed; } } internal bool BufferedDataChunksAvailable { get { return _dataChunkIndex > -1; } } // This low level API should only be consumed if the caller can make sure that the state is not corrupted // WebSocketHttpListenerDuplexStream (a duplex wrapper around HttpRequestStream/HttpResponseStream) // is currenlty the only consumer of this API internal HttpListenerContext InternalHttpContext { get { return _httpContext; } } public override void Flush() { } public override Task FlushAsync(CancellationToken cancellationToken) { return Task.CompletedTask; } public override long Length { get { throw new NotSupportedException(SR.net_noseek); } } public override long Position { get { throw new NotSupportedException(SR.net_noseek); } set { throw new NotSupportedException(SR.net_noseek); } } public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(SR.net_noseek); } public override void SetLength(long value) { throw new NotSupportedException(SR.net_noseek); } public override int Read(byte[] buffer, int offset, int size) { if (NetEventSource.IsEnabled) { NetEventSource.Enter(this); NetEventSource.Info(this, "size:" + size + " offset:" + offset); } if (buffer == null) { throw new ArgumentNullException(nameof(buffer)); } if (offset < 0 || offset > buffer.Length) { throw new ArgumentOutOfRangeException(nameof(offset)); } if (size < 0 || size > buffer.Length - offset) { throw new ArgumentOutOfRangeException(nameof(size)); } if (size == 0 || _closed) { if (NetEventSource.IsEnabled) NetEventSource.Exit(this, "dataRead:0"); return 0; } uint dataRead = 0; if (_dataChunkIndex != -1) { dataRead = Interop.HttpApi.GetChunks(_httpContext.Request.RequestBuffer, _httpContext.Request.OriginalBlobAddress, ref _dataChunkIndex, ref _dataChunkOffset, buffer, offset, size); } if (_dataChunkIndex == -1 && dataRead < size) { if (NetEventSource.IsEnabled) NetEventSource.Info(this, "size:" + size + " offset:" + offset); uint statusCode = 0; uint extraDataRead = 0; offset += (int)dataRead; size -= (int)dataRead; //the http.sys team recommends that we limit the size to 128kb if (size > MaxReadSize) { size = MaxReadSize; } fixed (byte* pBuffer = buffer) { // issue unmanaged blocking call if (NetEventSource.IsEnabled) NetEventSource.Info(this, "Calling Interop.HttpApi.HttpReceiveRequestEntityBody"); uint flags = 0; if (!_inOpaqueMode) { flags = (uint)Interop.HttpApi.HTTP_FLAGS.HTTP_RECEIVE_REQUEST_FLAG_COPY_BODY; } statusCode = Interop.HttpApi.HttpReceiveRequestEntityBody( _httpContext.RequestQueueHandle, _httpContext.RequestId, flags, (void*)(pBuffer + offset), (uint)size, out extraDataRead, null); dataRead += extraDataRead; if (NetEventSource.IsEnabled) NetEventSource.Info(this, "Call to Interop.HttpApi.HttpReceiveRequestEntityBody returned:" + statusCode + " dataRead:" + dataRead); } if (statusCode != Interop.HttpApi.ERROR_SUCCESS && statusCode != Interop.HttpApi.ERROR_HANDLE_EOF) { Exception exception = new HttpListenerException((int)statusCode); if (NetEventSource.IsEnabled) NetEventSource.Error(this, exception.ToString()); throw exception; } UpdateAfterRead(statusCode, dataRead); } if (NetEventSource.IsEnabled) { NetEventSource.DumpBuffer(this, buffer, offset, (int)dataRead); NetEventSource.Info(this, "returning dataRead:" + dataRead); NetEventSource.Exit(this, "dataRead:" + dataRead); } return (int)dataRead; } private void UpdateAfterRead(uint statusCode, uint dataRead) { if (NetEventSource.IsEnabled) NetEventSource.Info(this, "statusCode:" + statusCode + " _closed:" + _closed); if (statusCode == Interop.HttpApi.ERROR_HANDLE_EOF || dataRead == 0) { Close(); } if (NetEventSource.IsEnabled) NetEventSource.Info(this, "statusCode:" + statusCode + " _closed:" + _closed); } public override IAsyncResult BeginRead(byte[] buffer, int offset, int size, AsyncCallback callback, object state) { if (NetEventSource.IsEnabled) NetEventSource.Enter(this); if (NetEventSource.IsEnabled) NetEventSource.Info(this, "buffer.Length:" + buffer.Length + " size:" + size + " offset:" + offset); if (buffer == null) { throw new ArgumentNullException(nameof(buffer)); } if (offset < 0 || offset > buffer.Length) { throw new ArgumentOutOfRangeException(nameof(offset)); } if (size < 0 || size > buffer.Length - offset) { throw new ArgumentOutOfRangeException(nameof(size)); } if (size == 0 || _closed) { if (NetEventSource.IsEnabled) NetEventSource.Exit(this); HttpRequestStreamAsyncResult result = new HttpRequestStreamAsyncResult(this, state, callback); result.InvokeCallback((uint)0); return result; } HttpRequestStreamAsyncResult asyncResult = null; uint dataRead = 0; if (_dataChunkIndex != -1) { dataRead = Interop.HttpApi.GetChunks(_httpContext.Request.RequestBuffer, _httpContext.Request.OriginalBlobAddress, ref _dataChunkIndex, ref _dataChunkOffset, buffer, offset, size); if (_dataChunkIndex != -1 && dataRead == size) { asyncResult = new HttpRequestStreamAsyncResult(_httpContext.RequestQueueBoundHandle, this, state, callback, buffer, offset, (uint)size, 0); asyncResult.InvokeCallback(dataRead); } } if (_dataChunkIndex == -1 && dataRead < size) { if (NetEventSource.IsEnabled) NetEventSource.Info(this, "size:" + size + " offset:" + offset); uint statusCode = 0; offset += (int)dataRead; size -= (int)dataRead; //the http.sys team recommends that we limit the size to 128kb if (size > MaxReadSize) { size = MaxReadSize; } asyncResult = new HttpRequestStreamAsyncResult(_httpContext.RequestQueueBoundHandle, this, state, callback, buffer, offset, (uint)size, dataRead); uint bytesReturned; try { fixed (byte* pBuffer = buffer) { // issue unmanaged blocking call if (NetEventSource.IsEnabled) NetEventSource.Info(this, "Calling Interop.HttpApi.HttpReceiveRequestEntityBody"); uint flags = 0; if (!_inOpaqueMode) { flags = (uint)Interop.HttpApi.HTTP_FLAGS.HTTP_RECEIVE_REQUEST_FLAG_COPY_BODY; } statusCode = Interop.HttpApi.HttpReceiveRequestEntityBody( _httpContext.RequestQueueHandle, _httpContext.RequestId, flags, asyncResult._pPinnedBuffer, (uint)size, out bytesReturned, asyncResult._pOverlapped); if (NetEventSource.IsEnabled) NetEventSource.Info(this, "Call to Interop.HttpApi.HttpReceiveRequestEntityBody returned:" + statusCode + " dataRead:" + dataRead); } } catch (Exception e) { if (NetEventSource.IsEnabled) NetEventSource.Error(this, e.ToString()); asyncResult.InternalCleanup(); throw; } if (statusCode != Interop.HttpApi.ERROR_SUCCESS && statusCode != Interop.HttpApi.ERROR_IO_PENDING) { asyncResult.InternalCleanup(); if (statusCode == Interop.HttpApi.ERROR_HANDLE_EOF) { asyncResult = new HttpRequestStreamAsyncResult(this, state, callback, dataRead); asyncResult.InvokeCallback((uint)0); } else { Exception exception = new HttpListenerException((int)statusCode); if (NetEventSource.IsEnabled) NetEventSource.Error(this, exception.ToString()); asyncResult.InternalCleanup(); throw exception; } } else if (statusCode == Interop.HttpApi.ERROR_SUCCESS && HttpListener.SkipIOCPCallbackOnSuccess) { // IO operation completed synchronously - callback won't be called to signal completion. asyncResult.IOCompleted(statusCode, bytesReturned); } } if (NetEventSource.IsEnabled) NetEventSource.Exit(this); return asyncResult; } public override int EndRead(IAsyncResult asyncResult) { if (NetEventSource.IsEnabled) { NetEventSource.Enter(this); NetEventSource.Info(this, $"asyncResult: {asyncResult}"); } if (asyncResult == null) { throw new ArgumentNullException(nameof(asyncResult)); } HttpRequestStreamAsyncResult castedAsyncResult = asyncResult as HttpRequestStreamAsyncResult; if (castedAsyncResult == null || castedAsyncResult.AsyncObject != this) { throw new ArgumentException(SR.net_io_invalidasyncresult, nameof(asyncResult)); } if (castedAsyncResult.EndCalled) { throw new InvalidOperationException(SR.Format(SR.net_io_invalidendcall, nameof(EndRead))); } castedAsyncResult.EndCalled = true; // wait & then check for errors object returnValue = castedAsyncResult.InternalWaitForCompletion(); Exception exception = returnValue as Exception; if (exception != null) { if (NetEventSource.IsEnabled) { NetEventSource.Info(this, "Rethrowing exception:" + exception); NetEventSource.Error(this, exception.ToString()); } ExceptionDispatchInfo.Capture(exception).Throw(); } uint dataRead = (uint)returnValue; UpdateAfterRead((uint)castedAsyncResult.ErrorCode, dataRead); if (NetEventSource.IsEnabled) { NetEventSource.Info(this, $"returnValue:{returnValue}"); NetEventSource.Exit(this); } return (int)dataRead + (int)castedAsyncResult._dataAlreadyRead; } public override void Write(byte[] buffer, int offset, int size) { throw new InvalidOperationException(SR.net_readonlystream); } public override IAsyncResult BeginWrite(byte[] buffer, int offset, int size, AsyncCallback callback, object state) { throw new InvalidOperationException(SR.net_readonlystream); } public override void EndWrite(IAsyncResult asyncResult) { throw new InvalidOperationException(SR.net_readonlystream); } protected override void Dispose(bool disposing) { if (NetEventSource.IsEnabled) NetEventSource.Enter(this); try { if (NetEventSource.IsEnabled) NetEventSource.Info(this, "_closed:" + _closed); _closed = true; } finally { base.Dispose(disposing); } if (NetEventSource.IsEnabled) NetEventSource.Exit(this); } internal void SwitchToOpaqueMode() { if (NetEventSource.IsEnabled) NetEventSource.Info(this); _inOpaqueMode = true; } // This low level API should only be consumed if the caller can make sure that the state is not corrupted // WebSocketHttpListenerDuplexStream (a duplex wrapper around HttpRequestStream/HttpResponseStream) // is currenlty the only consumer of this API internal uint GetChunks(byte[] buffer, int offset, int size) { return Interop.HttpApi.GetChunks(_httpContext.Request.RequestBuffer, _httpContext.Request.OriginalBlobAddress, ref _dataChunkIndex, ref _dataChunkOffset, buffer, offset, size); } private sealed unsafe class HttpRequestStreamAsyncResult : LazyAsyncResult { private ThreadPoolBoundHandle _boundHandle; internal NativeOverlapped* _pOverlapped; internal void* _pPinnedBuffer; internal uint _dataAlreadyRead = 0; private static readonly IOCompletionCallback s_IOCallback = new IOCompletionCallback(Callback); internal HttpRequestStreamAsyncResult(object asyncObject, object userState, AsyncCallback callback) : base(asyncObject, userState, callback) { } internal HttpRequestStreamAsyncResult(object asyncObject, object userState, AsyncCallback callback, uint dataAlreadyRead) : base(asyncObject, userState, callback) { _dataAlreadyRead = dataAlreadyRead; } internal HttpRequestStreamAsyncResult(ThreadPoolBoundHandle boundHandle, object asyncObject, object userState, AsyncCallback callback, byte[] buffer, int offset, uint size, uint dataAlreadyRead) : base(asyncObject, userState, callback) { _dataAlreadyRead = dataAlreadyRead; _boundHandle = boundHandle; _pOverlapped = boundHandle.AllocateNativeOverlapped(s_IOCallback, state: this, pinData: buffer); _pPinnedBuffer = (void*)(Marshal.UnsafeAddrOfPinnedArrayElement(buffer, offset)); } internal void IOCompleted(uint errorCode, uint numBytes) { IOCompleted(this, errorCode, numBytes); } private static void IOCompleted(HttpRequestStreamAsyncResult asyncResult, uint errorCode, uint numBytes) { if (NetEventSource.IsEnabled) NetEventSource.Info(null, $"asyncResult: {asyncResult} errorCode:0x {errorCode.ToString("x8")} numBytes: {numBytes}"); object result = null; try { if (errorCode != Interop.HttpApi.ERROR_SUCCESS && errorCode != Interop.HttpApi.ERROR_HANDLE_EOF) { asyncResult.ErrorCode = (int)errorCode; result = new HttpListenerException((int)errorCode); } else { result = numBytes; if (NetEventSource.IsEnabled) NetEventSource.DumpBuffer(asyncResult, (IntPtr)asyncResult._pPinnedBuffer, (int)numBytes); } if (NetEventSource.IsEnabled) NetEventSource.Info(null, $"asyncResult: {asyncResult} calling Complete()"); } catch (Exception e) { result = e; } asyncResult.InvokeCallback(result); } private static unsafe void Callback(uint errorCode, uint numBytes, NativeOverlapped* nativeOverlapped) { HttpRequestStreamAsyncResult asyncResult = (HttpRequestStreamAsyncResult)ThreadPoolBoundHandle.GetNativeOverlappedState(nativeOverlapped); if (NetEventSource.IsEnabled) NetEventSource.Info(null, $"asyncResult: {asyncResult} errorCode:0x {errorCode.ToString("x8")} numBytes: {numBytes} nativeOverlapped:0x {((IntPtr)nativeOverlapped).ToString("x8")}"); IOCompleted(asyncResult, errorCode, numBytes); } // Will be called from the base class upon InvokeCallback() protected override void Cleanup() { base.Cleanup(); if (_pOverlapped != null) { _boundHandle.FreeNativeOverlapped(_pOverlapped); } } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // // Licensed under the MIT License. See LICENSE.txt in the project root for license information. using Microsoft.Graphics.Canvas; using Microsoft.Graphics.Canvas.Geometry; using Microsoft.Graphics.Canvas.UI.Xaml; using System; using System.Numerics; using Windows.Foundation; using Windows.UI; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; namespace ExampleGallery { public sealed partial class VectorArt : UserControl { int whichScene; bool isWireframe; int? randomSeed; CanvasDrawingSession currentDrawingSession; static Vector2[] sceneSizes = { new Vector2(1200, 900), new Vector2(960, 720), }; public VectorArt() { this.InitializeComponent(); sceneListBox.SelectedIndex = 0; } void Canvas_Draw(CanvasControl sender, CanvasDrawEventArgs args) { // Transform and clip so the scene will fit whatever size display we are running on. Vector2 sceneSize = sceneSizes[whichScene]; args.DrawingSession.Transform = Utils.GetDisplayTransform(sender.Size.ToVector2(), sceneSize); using (args.DrawingSession.CreateLayer(1f, new Rect(0, 0, sceneSize.X, sceneSize.Y))) { // Draw the vector art. currentDrawingSession = args.DrawingSession; switch (whichScene) { case 0: DrawScene0(); break; case 1: DrawScene1(randomSeed); break; } } } void SceneChanged(object sender, SelectionChangedEventArgs e) { whichScene = sceneListBox.SelectedIndex; randomSeed = null; randomizeButton.Visibility = (whichScene > 0) ? Visibility.Visible : Visibility.Collapsed; canvas.Invalidate(); } void WireframeChanged(object sender, RoutedEventArgs e) { isWireframe = wireframeButton.IsChecked.Value; if (isWireframe) { randomSeed = null; } canvas.Invalidate(); } void RandomizeButtonClick(object sender, RoutedEventArgs e) { randomSeed = new Random().Next(); wireframeButton.IsChecked = false; canvas.Invalidate(); } void Clear(Color color) { if (!isWireframe) { currentDrawingSession.Clear(color); } else { currentDrawingSession.Clear(Colors.White); } } void FillRectangle(Rect rect, Color color) { if (!isWireframe) { currentDrawingSession.FillRectangle(rect, color); } else { currentDrawingSession.DrawRectangle(rect, Colors.Black); } } void DrawLine(Vector2 p1, Vector2 p2, Color color, float strokeWidth) { if (!isWireframe) { currentDrawingSession.DrawLine(p1, p2, color, strokeWidth); } else { currentDrawingSession.DrawLine(p1, p2, Colors.Black); } } void DrawLine(Vector2 p1, Vector2 p2, Color color, float strokeWidth, CanvasStrokeStyle strokeStyle) { if (!isWireframe) { currentDrawingSession.DrawLine(p1, p2, color, strokeWidth, strokeStyle); } else { currentDrawingSession.DrawLine(p1, p2, Colors.Black); } } void FillEllipse(Vector2 center, float radiusX, float radiusY, Color color) { if (!isWireframe) { currentDrawingSession.FillEllipse(center, radiusX, radiusY, color); } else { currentDrawingSession.DrawEllipse(center, radiusX, radiusY, Colors.Black); } } void DrawEllipse(Vector2 center, float radiusX, float radiusY, Color color, float strokeWidth) { if (!isWireframe) { currentDrawingSession.DrawEllipse(center, radiusX, radiusY, color, strokeWidth); } else { currentDrawingSession.DrawEllipse(center, radiusX, radiusY, Colors.Black); } } void DrawEllipse(Vector2 center, float radiusX, float radiusY, Color color, float strokeWidth, CanvasStrokeStyle strokeStyle) { if (!isWireframe) { currentDrawingSession.DrawEllipse(center, radiusX, radiusY, color, strokeWidth, strokeStyle); } else { currentDrawingSession.DrawEllipse(center, radiusX, radiusY, Colors.Black); } } void FillCircle(Vector2 centerPoint, float radius, Color color) { if (!isWireframe) { currentDrawingSession.FillCircle(centerPoint, radius, color); } else { currentDrawingSession.DrawCircle(centerPoint, radius, Colors.Black); } } void DrawCircle(Vector2 centerPoint, float radius, Color color, float strokeWidth) { if (!isWireframe) { currentDrawingSession.DrawCircle(centerPoint, radius, color, strokeWidth); } else { currentDrawingSession.DrawCircle(centerPoint, radius, Colors.Black); } } void DrawCircle(Vector2 centerPoint, float radius, Color color, float strokeWidth, CanvasStrokeStyle strokeStyle) { if (!isWireframe) { currentDrawingSession.DrawCircle(centerPoint, radius, color, strokeWidth, strokeStyle); } else { currentDrawingSession.DrawCircle(centerPoint, radius, Colors.Black); } } private void control_Unloaded(object sender, RoutedEventArgs e) { // Explicitly remove references to allow the Win2D controls to get garbage collected canvas.RemoveFromVisualTree(); canvas = null; } } }
/*=============================================================================== Copyright (c) 2016 PTC Inc. All Rights Reserved. Copyright (c) 2012-2015 Qualcomm Connected Experiences, Inc. All Rights Reserved. Vuforia is a trademark of PTC Inc., registered in the United States and other countries. ===============================================================================*/ using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using Vuforia; /// <summary> /// A custom event handler for TextReco-events /// </summary> public class TextEventHandler : MonoBehaviour, ITextRecoEventHandler, IVideoBackgroundEventHandler { #region PRIVATE_MEMBERS // Size of text search area in percentage of screen private float mLoupeWidth = 0.9f; private float mLoupeHeight = 0.15f; // Line width of viusalized boxes around detected words private float mBBoxLineWidth = 3.0f; // Padding between detected words and visualized boxes private float mBBoxPadding = 0.0f; // Color of visualized boxes around detected words private Color mBBoxColor = new Color(1.0f, 0.447f, 0.0f, 1.0f); private Rect mDetectionAndTrackingRect; private Texture2D mBoundingBoxTexture; private Material mBoundingBoxMaterial; private bool mIsInitialized; private bool mVideoBackgroundChanged; private readonly List<WordResult> mSortedWords = new List<WordResult>(); private Text[] mDisplayedWords; [SerializeField] private Material boundingBoxMaterial = null; #endregion //PRIVATE_MEMBERS #region PUBLIC_MEMBERS public Canvas textRecoCanvas; #endregion //PUBLIC_MEMBERS #region MONOBEHAVIOUR_METHODS public void Start() { // create the texture for bounding boxes mBoundingBoxTexture = new Texture2D(1, 1, TextureFormat.ARGB32, false); mBoundingBoxTexture.SetPixel(0, 0, mBBoxColor); mBoundingBoxTexture.Apply(false); mBoundingBoxMaterial = new Material(boundingBoxMaterial); mBoundingBoxMaterial.SetTexture("_MainTex", mBoundingBoxTexture); // register to TextReco events var trBehaviour = GetComponent<TextRecoBehaviour>(); if (trBehaviour) { trBehaviour.RegisterTextRecoEventHandler(this); } // register for the OnVideoBackgroundConfigChanged event at the VuforiaBehaviour VuforiaARController.Instance.RegisterVideoBgEventHandler(this); mDisplayedWords = textRecoCanvas ? textRecoCanvas.GetComponentsInChildren<Text>(true) : new Text[0]; } void OnRenderObject() { DrawWordBoundingBoxes(); } void Update() { if (mIsInitialized) { // Once the text tracker has initialized and every time the video background changed, // set the region of interest if (mVideoBackgroundChanged) { TextTracker textTracker = TrackerManager.Instance.GetTracker<TextTracker>(); if (textTracker != null) { CalculateLoupeRegion(); textTracker.SetRegionOfInterest(mDetectionAndTrackingRect, mDetectionAndTrackingRect); } mVideoBackgroundChanged = false; } // Clear the content of the displayed words foreach (var dw in mDisplayedWords) { dw.text = ""; } // Update the list of words displayed int wordIndex = 0; foreach (var word in mSortedWords) { if (word.Word != null && wordIndex < mDisplayedWords.Length) { mDisplayedWords[wordIndex].text = word.Word.StringValue; } wordIndex++; } } } #endregion //MONOBEHAVIOUR_METHODS #region ITextRecoEventHandler_IMPLEMENTATION /// <summary> /// Called when text reco has finished initializing /// </summary> public void OnInitialized() { CalculateLoupeRegion(); mIsInitialized = true; } /// <summary> /// This method is called whenever a new word has been detected /// </summary> /// <param name="wordResult">New trackable with current pose</param> public void OnWordDetected(WordResult wordResult) { var word = wordResult.Word; if (ContainsWord(word)) Debug.LogError("Word was already detected before!"); Debug.Log("Text: New word: " + wordResult.Word.StringValue + "(" + wordResult.Word.ID + ")"); AddWord(wordResult); } /// <summary> /// This method is called whenever a tracked word has been lost and is not tracked anymore /// </summary> public void OnWordLost(Word word) { if (!ContainsWord(word)) Debug.LogError("Non-existing word was lost!"); Debug.Log("Text: Lost word: " + word.StringValue + "(" + word.ID + ")"); RemoveWord(word); } #endregion //PUBLIC_METHODS #region IVideoBackgroundEventHandler_IMPLEMENTATION // set a flag that the video background has changed. This means the region of interest has to be set again. public void OnVideoBackgroundConfigChanged() { mVideoBackgroundChanged = true; } #endregion // IVideoBackgroundEventHandler_IMPLEMENTATION #region PRIVATE_METHODS /// <summary> /// Draw a 3d bounding box around each currently tracked word /// </summary> private void DrawWordBoundingBoxes() { // render a quad around each currently tracked word foreach (var word in mSortedWords) { var pos = word.Position; var orientation = word.Orientation; var size = word.Word.Size; var pose = Matrix4x4.TRS(pos, orientation, new Vector3(size.x, 1, size.y)); var cornersObject = new[] { new Vector3(-0.5f, 0.0f, -0.5f), new Vector3(0.5f, 0.0f, -0.5f), new Vector3(0.5f, 0.0f, 0.5f), new Vector3(-0.5f, 0.0f, 0.5f) }; var corners = new Vector2[cornersObject.Length]; for (int i = 0; i < cornersObject.Length; i++) corners[i] = Camera.current.WorldToScreenPoint(pose.MultiplyPoint(cornersObject[i])); DrawBoundingBox(corners); } } private void DrawBoundingBox(Vector2[] corners) { var normals = new Vector2[4]; for (var i = 0; i < 4; i++) { var p0 = corners[i]; var p1 = corners[(i + 1)%4]; normals[i] = (p1 - p0).normalized; normals[i] = new Vector2(normals[i].y, -normals[i].x); } //add padding to inner corners corners = ExtendCorners(corners, normals, mBBoxPadding); //computer outer corners var outerCorners = ExtendCorners(corners, normals, mBBoxLineWidth); //create vertices in screen space var vertices = new Vector3[8]; float depth = 1.02f * Camera.current.nearClipPlane; for (var i = 0; i < 4; i++) { vertices[i] = new Vector3(corners[i].x, corners[i].y, depth); vertices[i + 4] = new Vector3(outerCorners[i].x, outerCorners[i].y, depth); } //transform vertices into world space for (int i = 0; i < 8; i++) vertices[i] = Camera.current.ScreenToWorldPoint(vertices[i]); var mesh = new Mesh() { vertices = vertices, uv = new Vector2[8], triangles = new[] { 0, 5, 4, 1, 5, 0, 1, 6, 5, 2, 6, 1, 2, 7, 6, 3, 7, 2, 3, 4, 7, 0, 4, 3 }, }; mBoundingBoxMaterial.SetPass(0); Graphics.DrawMeshNow(mesh, Matrix4x4.identity); Destroy(mesh); } private static Vector2[] ExtendCorners(Vector2[] corners, Vector2[] normals, float extension) { //compute positions along the outer side of the boundary var linePoints = new Vector2[corners.Length * 2]; for (var i = 0; i < corners.Length; i++) { var p0 = corners[i]; var p1 = corners[(i + 1) % 4]; var po0 = p0 + normals[i] * extension; var po1 = p1 + normals[i] * extension; linePoints[i * 2] = po0; linePoints[i * 2 + 1] = po1; } //compute corners of outer side of bounding box lines var outerCorners = new Vector2[corners.Length]; for (var i = 0; i < corners.Length; i++) { var i2 = i * 2; outerCorners[(i + 1) % 4] = IntersectLines(linePoints[i2], linePoints[i2 + 1], linePoints[(i2 + 2) % 8], linePoints[(i2 + 3) % 8]); } return outerCorners; } /// <summary> /// Intersect the line p1-p2 with the line p3-p4 /// </summary> private static Vector2 IntersectLines(Vector2 p1, Vector2 p2, Vector2 p3, Vector2 p4) { var denom = (p1.x - p2.x) * (p3.y - p4.y) - (p1.y - p2.y) * (p3.x - p4.x); var x = ((p1.x * p2.y - p1.y * p2.x) * (p3.x - p4.x) - (p1.x - p2.x) * (p3.x * p4.y - p3.y * p4.x)) / denom; var y = ((p1.x * p2.y - p1.y * p2.x) * (p3.y - p4.y) - (p1.y - p2.y) * (p3.x * p4.y - p3.y * p4.x)) / denom; return new Vector2(x, y); } private void AddWord(WordResult wordResult) { //add new word into sorted list var cmp = new ObbComparison(); int i = 0; while (i < mSortedWords.Count && cmp.Compare(mSortedWords[i], wordResult) < 0) { i++; } if (i < mSortedWords.Count) { mSortedWords.Insert(i, wordResult); } else { mSortedWords.Add(wordResult); } } private void RemoveWord(Word word) { for (int i = 0; i < mSortedWords.Count; i++) { if (mSortedWords[i].Word.ID == word.ID) { mSortedWords.RemoveAt(i); break; } } } private bool ContainsWord(Word word) { foreach (var w in mSortedWords) if (w.Word.ID == word.ID) return true; return false; } private void CalculateLoupeRegion() { // define area for text search var loupeWidth = mLoupeWidth * Screen.width; var loupeHeight = mLoupeHeight * Screen.height; var leftOffset = (Screen.width - loupeWidth) * 0.5f; var topOffset = leftOffset; mDetectionAndTrackingRect = new Rect(leftOffset, topOffset, loupeWidth, loupeHeight); } #endregion //PRIVATE_METHODS }
// 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.Globalization; using System.Reflection; namespace System.ComponentModel.DataAnnotations { /// <summary> /// Base class for all validation attributes. /// <para>Override <see cref="IsValid(object, ValidationContext)" /> to implement validation logic.</para> /// </summary> /// <remarks> /// The properties <see cref="ErrorMessageResourceType" /> and <see cref="ErrorMessageResourceName" /> are used to /// provide /// a localized error message, but they cannot be set if <see cref="ErrorMessage" /> is also used to provide a /// non-localized /// error message. /// </remarks> public abstract class ValidationAttribute : Attribute { #region Member Fields private string _errorMessage; private Func<string> _errorMessageResourceAccessor; private string _errorMessageResourceName; private Type _errorMessageResourceType; private volatile bool _hasBaseIsValid; private string _defaultErrorMessage; #endregion #region All Constructors /// <summary> /// Default constructor for any validation attribute. /// </summary> /// <remarks> /// This constructor chooses a very generic validation error message. /// Developers subclassing ValidationAttribute should use other constructors /// or supply a better message. /// </remarks> protected ValidationAttribute() : this(() => SR.ValidationAttribute_ValidationError) { } /// <summary> /// Constructor that accepts a fixed validation error message. /// </summary> /// <param name="errorMessage">A non-localized error message to use in <see cref="ErrorMessageString" />.</param> protected ValidationAttribute(string errorMessage) : this(() => errorMessage) { } /// <summary> /// Allows for providing a resource accessor function that will be used by the <see cref="ErrorMessageString" /> /// property to retrieve the error message. An example would be to have something like /// CustomAttribute() : base( () =&gt; MyResources.MyErrorMessage ) {}. /// </summary> /// <param name="errorMessageAccessor">The <see cref="Func{T}" /> that will return an error message.</param> protected ValidationAttribute(Func<string> errorMessageAccessor) { // If null, will later be exposed as lack of error message to be able to construct accessor _errorMessageResourceAccessor = errorMessageAccessor; } #endregion #region Internal Properties /// <summary> /// Sets the default error message string. /// This message will be used if the user has not set <see cref="ErrorMessage"/> /// or the <see cref="ErrorMessageResourceType"/> and <see cref="ErrorMessageResourceName"/> pair. /// This property was added after the public contract for DataAnnotations was created. /// It is internal to avoid changing the DataAnnotations contract. /// </summary> internal string DefaultErrorMessage { set { _defaultErrorMessage = value; _errorMessageResourceAccessor = null; CustomErrorMessageSet = true; } } #endregion #region Protected Properties /// <summary> /// Gets the localized error message string, coming either from <see cref="ErrorMessage" />, or from evaluating the /// <see cref="ErrorMessageResourceType" /> and <see cref="ErrorMessageResourceName" /> pair. /// </summary> protected string ErrorMessageString { get { SetupResourceAccessor(); return _errorMessageResourceAccessor(); } } /// <summary> /// A flag indicating whether a developer has customized the attribute's error message by setting any one of /// ErrorMessage, ErrorMessageResourceName, ErrorMessageResourceType or DefaultErrorMessage. /// </summary> internal bool CustomErrorMessageSet { get; private set; } /// <summary> /// A flag indicating that the attribute requires a non-null /// <see cref="ValidationContext" /> to perform validation. /// Base class returns false. Override in child classes as appropriate. /// </summary> public virtual bool RequiresValidationContext => false; #endregion #region Public Properties /// <summary> /// Gets or sets the explicit error message string. /// </summary> /// <value> /// This property is intended to be used for non-localizable error messages. Use /// <see cref="ErrorMessageResourceType" /> and <see cref="ErrorMessageResourceName" /> for localizable error messages. /// </value> public string ErrorMessage { // If _errorMessage is not set, return the default. This is done to preserve // behavior prior to the fix where ErrorMessage showed the non-null message to use. get => _errorMessage ?? _defaultErrorMessage; set { _errorMessage = value; _errorMessageResourceAccessor = null; CustomErrorMessageSet = true; // Explicitly setting ErrorMessage also sets DefaultErrorMessage if null. // This prevents subsequent read of ErrorMessage from returning default. if (value == null) { _defaultErrorMessage = null; } } } /// <summary> /// Gets or sets the resource name (property name) to use as the key for lookups on the resource type. /// </summary> /// <value> /// Use this property to set the name of the property within <see cref="ErrorMessageResourceType" /> /// that will provide a localized error message. Use <see cref="ErrorMessage" /> for non-localized error messages. /// </value> public string ErrorMessageResourceName { get => _errorMessageResourceName; set { _errorMessageResourceName = value; _errorMessageResourceAccessor = null; CustomErrorMessageSet = true; } } /// <summary> /// Gets or sets the resource type to use for error message lookups. /// </summary> /// <value> /// Use this property only in conjunction with <see cref="ErrorMessageResourceName" />. They are /// used together to retrieve localized error messages at runtime. /// <para> /// Use <see cref="ErrorMessage" /> instead of this pair if error messages are not localized. /// </para> /// </value> public Type ErrorMessageResourceType { get => _errorMessageResourceType; set { _errorMessageResourceType = value; _errorMessageResourceAccessor = null; CustomErrorMessageSet = true; } } #endregion #region Private Methods /// <summary> /// Validates the configuration of this attribute and sets up the appropriate error string accessor. /// This method bypasses all verification once the ResourceAccessor has been set. /// </summary> /// <exception cref="InvalidOperationException"> is thrown if the current attribute is malformed.</exception> private void SetupResourceAccessor() { if (_errorMessageResourceAccessor == null) { string localErrorMessage = ErrorMessage; bool resourceNameSet = !string.IsNullOrEmpty(_errorMessageResourceName); bool errorMessageSet = !string.IsNullOrEmpty(_errorMessage); bool resourceTypeSet = _errorMessageResourceType != null; bool defaultMessageSet = !string.IsNullOrEmpty(_defaultErrorMessage); // The following combinations are illegal and throw InvalidOperationException: // 1) Both ErrorMessage and ErrorMessageResourceName are set, or // 2) None of ErrorMessage, ErrorMessageResourceName, and DefaultErrorMessage are set. if ((resourceNameSet && errorMessageSet) || !(resourceNameSet || errorMessageSet || defaultMessageSet)) { throw new InvalidOperationException( SR.ValidationAttribute_Cannot_Set_ErrorMessage_And_Resource); } // Must set both or neither of ErrorMessageResourceType and ErrorMessageResourceName if (resourceTypeSet != resourceNameSet) { throw new InvalidOperationException( SR.ValidationAttribute_NeedBothResourceTypeAndResourceName); } // If set resource type (and we know resource name too), then go setup the accessor if (resourceNameSet) { SetResourceAccessorByPropertyLookup(); } else { // Here if not using resource type/name -- the accessor is just the error message string, // which we know is not empty to have gotten this far. // We captured error message to local in case it changes before accessor runs _errorMessageResourceAccessor = () => localErrorMessage; } } } private void SetResourceAccessorByPropertyLookup() { Debug.Assert(_errorMessageResourceType != null); Debug.Assert(!string.IsNullOrEmpty(_errorMessageResourceName)); var property = _errorMessageResourceType .GetTypeInfo().GetDeclaredProperty(_errorMessageResourceName); if (property != null && !ValidationAttributeStore.IsStatic(property)) { property = null; } if (property != null) { var propertyGetter = property.GetMethod; // We only support internal and public properties if (propertyGetter == null || (!propertyGetter.IsAssembly && !propertyGetter.IsPublic)) { // Set the property to null so the exception is thrown as if the property wasn't found property = null; } } if (property == null) { throw new InvalidOperationException( string.Format( CultureInfo.CurrentCulture, SR.ValidationAttribute_ResourceTypeDoesNotHaveProperty, _errorMessageResourceType.FullName, _errorMessageResourceName)); } if (property.PropertyType != typeof(string)) { throw new InvalidOperationException( string.Format( CultureInfo.CurrentCulture, SR.ValidationAttribute_ResourcePropertyNotStringType, property.Name, _errorMessageResourceType.FullName)); } _errorMessageResourceAccessor = () => (string)property.GetValue(null, null); } #endregion #region Protected & Public Methods /// <summary> /// Formats the error message to present to the user. /// </summary> /// <remarks> /// The error message will be re-evaluated every time this function is called. /// It applies the <paramref name="name" /> (for example, the name of a field) to the formated error message, resulting /// in something like "The field 'name' has an incorrect value". /// <para> /// Derived classes can override this method to customize how errors are generated. /// </para> /// <para> /// The base class implementation will use <see cref="ErrorMessageString" /> to obtain a localized /// error message from properties within the current attribute. If those have not been set, a generic /// error message will be provided. /// </para> /// </remarks> /// <param name="name">The user-visible name to include in the formatted message.</param> /// <returns>The localized string describing the validation error</returns> /// <exception cref="InvalidOperationException"> is thrown if the current attribute is malformed.</exception> public virtual string FormatErrorMessage(string name) => string.Format(CultureInfo.CurrentCulture, ErrorMessageString, name); /// <summary> /// Gets the value indicating whether or not the specified <paramref name="value" /> is valid /// with respect to the current validation attribute. /// <para> /// Derived classes should not override this method as it is only available for backwards compatibility. /// Instead, implement <see cref="IsValid(object, ValidationContext)" />. /// </para> /// </summary> /// <remarks> /// The preferred public entry point for clients requesting validation is the <see cref="GetValidationResult" /> /// method. /// </remarks> /// <param name="value">The value to validate</param> /// <returns><c>true</c> if the <paramref name="value" /> is acceptable, <c>false</c> if it is not acceptable</returns> /// <exception cref="InvalidOperationException"> is thrown if the current attribute is malformed.</exception> /// <exception cref="NotImplementedException"> /// is thrown when neither overload of IsValid has been implemented /// by a derived class. /// </exception> public virtual bool IsValid(object value) { if (!_hasBaseIsValid) { // track that this method overload has not been overridden. _hasBaseIsValid = true; } // call overridden method. return IsValid(value, null) == ValidationResult.Success; } /// <summary> /// Protected virtual method to override and implement validation logic. /// <para> /// Derived classes should override this method instead of <see cref="IsValid(object)" />, which is deprecated. /// </para> /// </summary> /// <param name="value">The value to validate.</param> /// <param name="validationContext"> /// A <see cref="ValidationContext" /> instance that provides /// context about the validation operation, such as the object and member being validated. /// </param> /// <returns> /// When validation is valid, <see cref="ValidationResult.Success" />. /// <para> /// When validation is invalid, an instance of <see cref="ValidationResult" />. /// </para> /// </returns> /// <exception cref="InvalidOperationException"> is thrown if the current attribute is malformed.</exception> /// <exception cref="NotImplementedException"> /// is thrown when <see cref="IsValid(object, ValidationContext)" /> /// has not been implemented by a derived class. /// </exception> protected virtual ValidationResult IsValid(object value, ValidationContext validationContext) { if (_hasBaseIsValid) { // this means neither of the IsValid methods has been overridden, throw. throw NotImplemented.ByDesignWithMessage( SR.ValidationAttribute_IsValid_NotImplemented); } var result = ValidationResult.Success; // call overridden method. if (!IsValid(value)) { string[] memberNames = validationContext.MemberName != null ? new string[] { validationContext.MemberName } : null; result = new ValidationResult(FormatErrorMessage(validationContext.DisplayName), memberNames); } return result; } /// <summary> /// Tests whether the given <paramref name="value" /> is valid with respect to the current /// validation attribute without throwing a <see cref="ValidationException" /> /// </summary> /// <remarks> /// If this method returns <see cref="ValidationResult.Success" />, then validation was successful, otherwise /// an instance of <see cref="ValidationResult" /> will be returned with a guaranteed non-null /// <see cref="ValidationResult.ErrorMessage" />. /// </remarks> /// <param name="value">The value to validate</param> /// <param name="validationContext"> /// A <see cref="ValidationContext" /> instance that provides /// context about the validation operation, such as the object and member being validated. /// </param> /// <returns> /// When validation is valid, <see cref="ValidationResult.Success" />. /// <para> /// When validation is invalid, an instance of <see cref="ValidationResult" />. /// </para> /// </returns> /// <exception cref="InvalidOperationException"> is thrown if the current attribute is malformed.</exception> /// <exception cref="ArgumentNullException">When <paramref name="validationContext" /> is null.</exception> /// <exception cref="NotImplementedException"> /// is thrown when <see cref="IsValid(object, ValidationContext)" /> /// has not been implemented by a derived class. /// </exception> public ValidationResult GetValidationResult(object value, ValidationContext validationContext) { if (validationContext == null) { throw new ArgumentNullException(nameof(validationContext)); } var result = IsValid(value, validationContext); // If validation fails, we want to ensure we have a ValidationResult that guarantees it has an ErrorMessage if (result != null) { if (string.IsNullOrEmpty(result.ErrorMessage)) { var errorMessage = FormatErrorMessage(validationContext.DisplayName); result = new ValidationResult(errorMessage, result.MemberNames); } } return result; } /// <summary> /// Validates the specified <paramref name="value" /> and throws <see cref="ValidationException" /> if it is not. /// <para> /// The overloaded <see cref="Validate(object, ValidationContext)" /> is the recommended entry point as it /// can provide additional context to the <see cref="ValidationAttribute" /> being validated. /// </para> /// </summary> /// <remarks> /// This base method invokes the <see cref="IsValid(object)" /> method to determine whether or not the /// <paramref name="value" /> is acceptable. If <see cref="IsValid(object)" /> returns <c>false</c>, this base /// method will invoke the <see cref="FormatErrorMessage" /> to obtain a localized message describing /// the problem, and it will throw a <see cref="ValidationException" /> /// </remarks> /// <param name="value">The value to validate</param> /// <param name="name">The string to be included in the validation error message if <paramref name="value" /> is not valid</param> /// <exception cref="ValidationException"> /// is thrown if <see cref="IsValid(object)" /> returns <c>false</c>. /// </exception> /// <exception cref="InvalidOperationException"> is thrown if the current attribute is malformed.</exception> public void Validate(object value, string name) { if (!IsValid(value)) { throw new ValidationException(FormatErrorMessage(name), this, value); } } /// <summary> /// Validates the specified <paramref name="value" /> and throws <see cref="ValidationException" /> if it is not. /// </summary> /// <remarks> /// This method invokes the <see cref="IsValid(object, ValidationContext)" /> method /// to determine whether or not the <paramref name="value" /> is acceptable given the /// <paramref name="validationContext" />. /// If that method doesn't return <see cref="ValidationResult.Success" />, this base method will throw /// a <see cref="ValidationException" /> containing the <see cref="ValidationResult" /> describing the problem. /// </remarks> /// <param name="value">The value to validate</param> /// <param name="validationContext">Additional context that may be used for validation. It cannot be null.</param> /// <exception cref="ValidationException"> /// is thrown if <see cref="IsValid(object, ValidationContext)" /> /// doesn't return <see cref="ValidationResult.Success" />. /// </exception> /// <exception cref="InvalidOperationException"> is thrown if the current attribute is malformed.</exception> /// <exception cref="NotImplementedException"> /// is thrown when <see cref="IsValid(object, ValidationContext)" /> /// has not been implemented by a derived class. /// </exception> public void Validate(object value, ValidationContext validationContext) { if (validationContext == null) { throw new ArgumentNullException(nameof(validationContext)); } ValidationResult result = GetValidationResult(value, validationContext); if (result != null) { // Convenience -- if implementation did not fill in an error message, throw new ValidationException(result, this, value); } } #endregion } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Drawing; using System.Drawing.Design; using System.Linq; using System.Runtime.Serialization; using System.Xml.Linq; using BASeCamp.BASeBlock.Particles; using BASeCamp.Elementizer; namespace BASeCamp.BASeBlock.Blocks { [Serializable] public class BuilderBlock : ImageBlock { //the "Builder" Block creates new blocks, moving existing blocks away from it. public enum BuilderBlockDirection { Left, Up, Right, Down } private Type _BuildBlock = typeof(StrongBlock); private int _MaxBuilds = 12; private int _Built = 0; private bool _Initialized = false; private BuilderBlockDirection _BuildDirection = BuilderBlockDirection.Up; [Editor(typeof(ItemTypeEditor<Block>),typeof(UITypeEditor))] public Type BuildBlock { get { return _BuildBlock; } set { _BuildBlock = value; } } /// <summary> /// sets/returns the Maximum builds this block can perform. If 0, this block /// will never 'run out' of blocks to build. /// </summary> public int MaxBuilds { get { return _MaxBuilds; } set { _MaxBuilds = value; } } /// <summary> /// Number of blocks this block has Built, or emitted. This does not count blocks that were in the builddirection /// when the block initialized. /// </summary> public int Built { get { return _Built; } set { _Built = value; } } public BuilderBlockDirection BuildDirection { get { return _BuildDirection; } set { _BuildDirection = value; } } public bool Initialized { get { return _Initialized; } } public BuilderBlock(RectangleF Blockrect) : base(Blockrect,"BUILDER") { } public BuilderBlock(BuilderBlock clonethis):base(clonethis) { _MaxBuilds = clonethis.MaxBuilds; _Built = clonethis.Built; _BuildDirection = clonethis.BuildDirection; _Initialized = clonethis.Initialized; } public BuilderBlock(SerializationInfo info, StreamingContext context):base(info,context) { _MaxBuilds = info.GetInt32("MaxBuilds"); _Built = info.GetInt32("Built"); _BuildDirection = info.GetValue<BuilderBlockDirection>("BuildDirection"); try {_BuildBlock= BCBlockGameState.FindClass(info.GetString("BuildBlock"));} catch(Exception exx) { _BuildBlock = typeof(NormalBlock);} } public override object Clone() { return new BuilderBlock(this); } public override void GetObjectData(SerializationInfo info, StreamingContext context) { base.GetObjectData(info, context); info.AddValue("MaxBuilds", _MaxBuilds); info.AddValue("Built", _Built); info.AddValue("BuildDirection", _BuildDirection); info.AddValue("BuildBlock", _BuildBlock.Name); } public BuilderBlock(XElement Source, Object pPersistenceData) :base(Source,pPersistenceData) { _MaxBuilds = Source.GetAttributeInt("MaxBuilds",_MaxBuilds); _Built = Source.GetAttributeInt("Built", _Built); _BuildDirection = (BuilderBlockDirection)Source.GetAttributeInt("BuildDirection"); String sFindType = Source.GetAttributeString("BuildBlock", typeof(NormalBlock).Name); BuildBlock = BCBlockGameState.FindClass(sFindType); } public override XElement GetXmlData(String pNodeName,Object pPersistenceData) { var Result = base.GetXmlData(pNodeName,pPersistenceData); Result.Add(new XAttribute("MaxBuilds",_MaxBuilds)); Result.Add(new XAttribute("Built",_Built)); Result.Add(new XAttribute("BuildDirection",(int)_BuildDirection)); Result.Add(new XAttribute("BuildBlock", _BuildBlock.Name)); return Result; } public override bool MustDestroy() { //true for when will break. return _MaxBuilds > 0; //bigger than 0 will break. } /// <summary> /// determine if the given block is relevant... or pushable. /// </summary> /// <param name="ourmover"></param> /// <param name="testblock"></param> /// <returns></returns> private bool isRelevant(Block ourmover, Block testblock,PointF offset) { PointF OurPoint = ourmover.BlockRectangle.CenterPoint(); PointF OtherPoint = testblock.BlockRectangle.CenterPoint(); //the new block has to be in the x or y direction of our offset. PointF diff = new PointF(OtherPoint.X - OurPoint.X, OtherPoint.Y - OurPoint.Y); Point Signs = new Point(Math.Sign(diff.X), Math.Sign(diff.Y)); return ((Math.Sign(offset.X)!=0 && Signs.X == Math.Sign(offset.X)) || (Math.Sign(offset.Y)!=0 && Signs.Y == Math.Sign(offset.Y))); } /// <summary> /// /// </summary> /// <param name="gstate"></param> /// <param name="source"></param> /// <param name="target"></param> /// <param name="offset"></param> /// <returns>true if this block "konga line" hit a wall. false otherwise.</returns> private bool OffsetBlock(BCBlockGameState gstate, Block target, PointF offset) { //FIRST: get a set of blocks that are intersecting target. var wasintersecting = from b in gstate.Blocks where target.BlockRectangle.IntersectsWith(b.BlockRectangle) select b; var notus = from bb in gstate.Blocks where target.BlockRectangle.IntersectsWith(bb.BlockRectangle) && bb != target select bb; if (!notus.Any()) { // target.BlockRectangle = new RectangleF(target.BlockRectangle.X + offset.X, target.BlockRectangle.Y + offset.Y, target.BlockRectangle.Width, target.BlockRectangle.Height); return true; } //offset the block's position target.BlockRectangle = new RectangleF(target.BlockRectangle.X + offset.X, target.BlockRectangle.Y + offset.Y, target.BlockRectangle.Width, target.BlockRectangle.Height); //if we are touching the edge of the gameplay area, return true to indicate we did so. if (!gstate.GameArea.Contains(target.BlockRectangle.ToRectangle())) return true; //now get another set of intersections. However, we //don't want intersections that we were already intersecting with. var newintersections = from b in gstate.Blocks where target.BlockRectangle.IntersectsWith(b.BlockRectangle) && !wasintersecting.Contains(b) select b; if (newintersections.Any()) { Debug.Print("intersection"); } //interesting note: newintersections will not contain any blocks that are "behind" us, because we won't //be touching them after moving anymore. It also won't include the target block. bool hadany = false; bool buildresult = false; foreach (var iterate in newintersections) { hadany = true; buildresult= buildresult || OffsetBlock(gstate, iterate, offset); } for (int i = 0; i < 2; i++) { DustParticle dp = new DustParticle(target.BlockRectangle.RandomSpot(BCBlockGameState.rgen),3,90,Color.Yellow); gstate.Particles.Add(dp); } //return true if no elements, buildresult otherwise. return hadany || buildresult; } public override string GetToolTipInfo(IEditorClient Client) { String b = base.GetToolTipInfo(Client); b = b + "\nDirection:" + _BuildDirection.ToString() + "\n" + "Type:" + _BuildBlock.Name + "\n" + "Number:" +( _MaxBuilds == 0 ? "(Infinite)" : _MaxBuilds.ToString()); return b; } private bool ProxyFrame(ProxyObject me, BCBlockGameState gstate) { bool valuereturn = false; //if _CurrentMoving is null, we are finished with movement now. if ((_CurrentMoving == null) ) { MovingProxy = null; immune = false; return true; } else { //move CurrentMoving in the appropriate direction. PointF useoffset = GetOffsetSpeed(); gstate.Forcerefresh = true; //task: we need to move _CurrentMoving, //and push any other blocks upward as it goes, unless a pushed block hits the edge. valuereturn = OffsetBlock(gstate, _CurrentMoving, useoffset); _CurrentMoving.hasChanged = true; if (valuereturn) { _CurrentMoving = null; immune = false; } } return valuereturn; } private PointF GetOffsetSpeed() { if (_BuildDirection == BuilderBlockDirection.Left) return new PointF(-1, 0); if (_BuildDirection == BuilderBlockDirection.Up) return new PointF(0, -1); if (_BuildDirection == BuilderBlockDirection.Right) return new PointF(1, 0); if (_BuildDirection == BuilderBlockDirection.Down) return new PointF(0, 1); return new PointF(0, -1); } private bool immune = false; private Block _CurrentMoving; //block we are currently moving. private ProxyObject MovingProxy = null; public override bool PerformBlockHit(BCBlockGameState parentstate, cBall ballhit) { //create a new instance of the buildblock at our location with our size. //set it to start moving via a ProxyGameObject. Each frame we will Move the first block; if the firstblock touches a block on the side it is moving, we move that block the same amount, if that one is touching a block, we move that, etc. //We keep going until we try to move a block outside the gamearea (so it doesn't contains() it) or until the first block no longer intersects with the factory block. //while we are doing this, we set the ignore hits to true. if (immune) return false; immune = true; Built++; if (Built == MaxBuilds) { base.PerformBlockHit(parentstate, ballhit); return true; } //create a buildblock. _CurrentMoving = (Block)Activator.CreateInstance(BuildBlock, BlockRectangle); //activate our proxy Object. MovingProxy = new ProxyObject(ProxyFrame, null); parentstate.NextFrameCalls.Enqueue(new BCBlockGameState.NextFrameStartup(() => { parentstate.Blocks.AddLast(_CurrentMoving); parentstate.GameObjects.AddFirst(MovingProxy); })); BCBlockGameState.Soundman.PlaySound("REVEL"); // go with revel for now. return false; //add code to play special building sound. } } }
// Copyright (c) Umbraco. // See LICENSE for more details. using System; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using NUnit.Framework; using Umbraco.Cms.Core.PropertyEditors; namespace Umbraco.Cms.Tests.UnitTests.Umbraco.Core.PropertyEditors { [TestFixture] public class NestedContentPropertyComponentTests { private static void AreEqualJson(string expected, string actual) { Assert.AreEqual(JToken.Parse(expected), JToken.Parse(actual)); } [Test] public void Invalid_Json() { var component = new NestedContentPropertyHandler(); Assert.DoesNotThrow(() => component.CreateNestedContentKeys("this is not json", true)); } [Test] public void No_Nesting() { Guid[] guids = new[] { Guid.NewGuid(), Guid.NewGuid() }; var guidCounter = 0; Guid GuidFactory() => guids[guidCounter++]; var json = @"[ {""key"":""04a6dba8-813c-4144-8aca-86a3f24ebf08"",""name"":""Item 1"",""ncContentTypeAlias"":""nested"",""text"":""woot""}, {""key"":""d8e214d8-c5a5-4b45-9b51-4050dd47f5fa"",""name"":""Item 2"",""ncContentTypeAlias"":""nested"",""text"":""zoot""} ]"; var expected = json .Replace("04a6dba8-813c-4144-8aca-86a3f24ebf08", guids[0].ToString()) .Replace("d8e214d8-c5a5-4b45-9b51-4050dd47f5fa", guids[1].ToString()); var component = new NestedContentPropertyHandler(); var actual = component.CreateNestedContentKeys(json, false, GuidFactory); AreEqualJson(expected, actual); } [Test] public void One_Level_Nesting_Unescaped() { Guid[] guids = new[] { Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid() }; var guidCounter = 0; Guid GuidFactory() => guids[guidCounter++]; var json = @"[{ ""key"": ""04a6dba8-813c-4144-8aca-86a3f24ebf08"", ""name"": ""Item 1"", ""ncContentTypeAlias"": ""text"", ""text"": ""woot"" }, { ""key"": ""d8e214d8-c5a5-4b45-9b51-4050dd47f5fa"", ""name"": ""Item 2"", ""ncContentTypeAlias"": ""list"", ""text"": ""zoot"", ""subItems"": [{ ""key"": ""dccf550c-3a05-469e-95e1-a8f560f788c2"", ""name"": ""Item 1"", ""ncContentTypeAlias"": ""text"", ""text"": ""woot"" }, { ""key"": ""fbde4288-8382-4e13-8933-ed9c160de050"", ""name"": ""Item 2"", ""ncContentTypeAlias"": ""text"", ""text"": ""zoot"" }] }]"; var expected = json .Replace("04a6dba8-813c-4144-8aca-86a3f24ebf08", guids[0].ToString()) .Replace("d8e214d8-c5a5-4b45-9b51-4050dd47f5fa", guids[1].ToString()) .Replace("dccf550c-3a05-469e-95e1-a8f560f788c2", guids[2].ToString()) .Replace("fbde4288-8382-4e13-8933-ed9c160de050", guids[3].ToString()); var component = new NestedContentPropertyHandler(); var actual = component.CreateNestedContentKeys(json, false, GuidFactory); AreEqualJson(expected, actual); } [Test] public void One_Level_Nesting_Escaped() { Guid[] guids = new[] { Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid() }; var guidCounter = 0; Guid GuidFactory() => guids[guidCounter++]; // we need to ensure the escaped json is consistent with how it will be re-escaped after parsing // and this is how to do that, the result will also include quotes around it. var subJsonEscaped = JsonConvert.ToString(JToken.Parse(@" [{ ""key"": ""dccf550c-3a05-469e-95e1-a8f560f788c2"", ""name"": ""Item 1"", ""ncContentTypeAlias"": ""text"", ""text"": ""woot"" }, { ""key"": ""fbde4288-8382-4e13-8933-ed9c160de050"", ""name"": ""Item 2"", ""ncContentTypeAlias"": ""text"", ""text"": ""zoot"" } ]").ToString(Formatting.None)); var json = @"[{ ""key"": ""04a6dba8-813c-4144-8aca-86a3f24ebf08"", ""name"": ""Item 1"", ""ncContentTypeAlias"": ""text"", ""text"": ""woot"" }, { ""key"": ""d8e214d8-c5a5-4b45-9b51-4050dd47f5fa"", ""name"": ""Item 2"", ""ncContentTypeAlias"": ""list"", ""text"": ""zoot"", ""subItems"":" + subJsonEscaped + @" } ]"; var expected = json .Replace("04a6dba8-813c-4144-8aca-86a3f24ebf08", guids[0].ToString()) .Replace("d8e214d8-c5a5-4b45-9b51-4050dd47f5fa", guids[1].ToString()) .Replace("dccf550c-3a05-469e-95e1-a8f560f788c2", guids[2].ToString()) .Replace("fbde4288-8382-4e13-8933-ed9c160de050", guids[3].ToString()); var component = new NestedContentPropertyHandler(); var actual = component.CreateNestedContentKeys(json, false, GuidFactory); AreEqualJson(expected, actual); } [Test] public void Nested_In_Complex_Editor_Escaped() { Guid[] guids = new[] { Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid() }; var guidCounter = 0; Guid GuidFactory() => guids[guidCounter++]; // we need to ensure the escaped json is consistent with how it will be re-escaped after parsing // and this is how to do that, the result will also include quotes around it. var subJsonEscaped = JsonConvert.ToString(JToken.Parse(@"[{ ""key"": ""dccf550c-3a05-469e-95e1-a8f560f788c2"", ""name"": ""Item 1"", ""ncContentTypeAlias"": ""text"", ""text"": ""woot"" }, { ""key"": ""fbde4288-8382-4e13-8933-ed9c160de050"", ""name"": ""Item 2"", ""ncContentTypeAlias"": ""text"", ""text"": ""zoot"" } ]").ToString(Formatting.None)); // Complex editor such as the grid var complexEditorJsonEscaped = @"{ ""name"": ""1 column layout"", ""sections"": [ { ""grid"": ""12"", ""rows"": [ { ""name"": ""Article"", ""id"": ""b4f6f651-0de3-ef46-e66a-464f4aaa9c57"", ""areas"": [ { ""grid"": ""4"", ""controls"": [ { ""value"": ""I am quote"", ""editor"": { ""alias"": ""quote"", ""view"": ""textstring"" }, ""styles"": null, ""config"": null }], ""styles"": null, ""config"": null }, { ""grid"": ""8"", ""controls"": [ { ""value"": ""Header"", ""editor"": { ""alias"": ""headline"", ""view"": ""textstring"" }, ""styles"": null, ""config"": null }, { ""value"": " + subJsonEscaped + @", ""editor"": { ""alias"": ""madeUpNestedContent"", ""view"": ""madeUpNestedContentInGrid"" }, ""styles"": null, ""config"": null }], ""styles"": null, ""config"": null }], ""styles"": null, ""config"": null }] }] }"; var json = @"[{ ""key"": ""04a6dba8-813c-4144-8aca-86a3f24ebf08"", ""name"": ""Item 1"", ""ncContentTypeAlias"": ""text"", ""text"": ""woot"" }, { ""key"": ""d8e214d8-c5a5-4b45-9b51-4050dd47f5fa"", ""name"": ""Item 2"", ""ncContentTypeAlias"": ""list"", ""text"": ""zoot"", ""subItems"":" + complexEditorJsonEscaped + @" } ]"; var expected = json .Replace("04a6dba8-813c-4144-8aca-86a3f24ebf08", guids[0].ToString()) .Replace("d8e214d8-c5a5-4b45-9b51-4050dd47f5fa", guids[1].ToString()) .Replace("dccf550c-3a05-469e-95e1-a8f560f788c2", guids[2].ToString()) .Replace("fbde4288-8382-4e13-8933-ed9c160de050", guids[3].ToString()); var component = new NestedContentPropertyHandler(); var actual = component.CreateNestedContentKeys(json, false, GuidFactory); AreEqualJson(expected, actual); } [Test] public void No_Nesting_Generates_Keys_For_Missing_Items() { Guid[] guids = new[] { Guid.NewGuid() }; var guidCounter = 0; Guid GuidFactory() => guids[guidCounter++]; var json = @"[ {""key"":""04a6dba8-813c-4144-8aca-86a3f24ebf08"",""name"":""Item 1 my key wont change"",""ncContentTypeAlias"":""nested"",""text"":""woot""}, {""name"":""Item 2 was copied and has no key prop"",""ncContentTypeAlias"":""nested"",""text"":""zoot""} ]"; var component = new NestedContentPropertyHandler(); var result = component.CreateNestedContentKeys(json, true, GuidFactory); // Ensure the new GUID is put in a key into the JSON Assert.IsTrue(result.Contains(guids[0].ToString())); // Ensure that the original key is NOT changed/modified & still exists Assert.IsTrue(result.Contains("04a6dba8-813c-4144-8aca-86a3f24ebf08")); } [Test] public void One_Level_Nesting_Escaped_Generates_Keys_For_Missing_Items() { Guid[] guids = new[] { Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid() }; var guidCounter = 0; Guid GuidFactory() => guids[guidCounter++]; // we need to ensure the escaped json is consistent with how it will be re-escaped after parsing // and this is how to do that, the result will also include quotes around it. var subJsonEscaped = JsonConvert.ToString(JToken.Parse(@"[{ ""name"": ""Item 1"", ""ncContentTypeAlias"": ""text"", ""text"": ""woot"" }, { ""name"": ""Nested Item 2 was copied and has no key"", ""ncContentTypeAlias"": ""text"", ""text"": ""zoot"" } ]").ToString(Formatting.None)); var json = @"[{ ""name"": ""Item 1 was copied and has no key"", ""ncContentTypeAlias"": ""text"", ""text"": ""woot"" }, { ""key"": ""d8e214d8-c5a5-4b45-9b51-4050dd47f5fa"", ""name"": ""Item 2"", ""ncContentTypeAlias"": ""list"", ""text"": ""zoot"", ""subItems"":" + subJsonEscaped + @" } ]"; var component = new NestedContentPropertyHandler(); var result = component.CreateNestedContentKeys(json, true, GuidFactory); // Ensure the new GUID is put in a key into the JSON for each item Assert.IsTrue(result.Contains(guids[0].ToString())); Assert.IsTrue(result.Contains(guids[1].ToString())); Assert.IsTrue(result.Contains(guids[2].ToString())); } [Test] public void Nested_In_Complex_Editor_Escaped_Generates_Keys_For_Missing_Items() { Guid[] guids = new[] { Guid.NewGuid(), Guid.NewGuid() }; var guidCounter = 0; Guid GuidFactory() => guids[guidCounter++]; // we need to ensure the escaped json is consistent with how it will be re-escaped after parsing // and this is how to do that, the result will also include quotes around it. var subJsonEscaped = JsonConvert.ToString(JToken.Parse(@"[{ ""key"": ""dccf550c-3a05-469e-95e1-a8f560f788c2"", ""name"": ""Item 1"", ""ncContentTypeAlias"": ""text"", ""text"": ""woot"" }, { ""name"": ""Nested Item 2 was copied and has no key"", ""ncContentTypeAlias"": ""text"", ""text"": ""zoot"" } ]").ToString(Formatting.None)); // Complex editor such as the grid var complexEditorJsonEscaped = @"{ ""name"": ""1 column layout"", ""sections"": [ { ""grid"": ""12"", ""rows"": [ { ""name"": ""Article"", ""id"": ""b4f6f651-0de3-ef46-e66a-464f4aaa9c57"", ""areas"": [ { ""grid"": ""4"", ""controls"": [ { ""value"": ""I am quote"", ""editor"": { ""alias"": ""quote"", ""view"": ""textstring"" }, ""styles"": null, ""config"": null }], ""styles"": null, ""config"": null }, { ""grid"": ""8"", ""controls"": [ { ""value"": ""Header"", ""editor"": { ""alias"": ""headline"", ""view"": ""textstring"" }, ""styles"": null, ""config"": null }, { ""value"": " + subJsonEscaped + @", ""editor"": { ""alias"": ""madeUpNestedContent"", ""view"": ""madeUpNestedContentInGrid"" }, ""styles"": null, ""config"": null }], ""styles"": null, ""config"": null }], ""styles"": null, ""config"": null }] }] }"; var json = @"[{ ""key"": ""04a6dba8-813c-4144-8aca-86a3f24ebf08"", ""name"": ""Item 1"", ""ncContentTypeAlias"": ""text"", ""text"": ""woot"" }, { ""name"": ""Item 2 was copied and has no key"", ""ncContentTypeAlias"": ""list"", ""text"": ""zoot"", ""subItems"":" + complexEditorJsonEscaped + @" } ]"; var component = new NestedContentPropertyHandler(); var result = component.CreateNestedContentKeys(json, true, GuidFactory); // Ensure the new GUID is put in a key into the JSON for each item Assert.IsTrue(result.Contains(guids[0].ToString())); Assert.IsTrue(result.Contains(guids[1].ToString())); } } }
/* ==================================================================== 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 NPOI.SS.Formula.PTG { using System; using System.Text; using NPOI.Util; using NPOI.SS.Util; using NPOI.SS.Formula.Constant; /** * ArrayPtg - handles arrays * * The ArrayPtg is a little weird, the size of the Ptg when parsing initially only * includes the Ptg sid and the reserved bytes. The next Ptg in the expression then follows. * It is only after the "size" of all the Ptgs is met, that the ArrayPtg data is actually * held after this. So Ptg.CreateParsedExpression keeps track of the number of * ArrayPtg elements and need to Parse the data upto the FORMULA record size. * * @author Jason Height (jheight at chariot dot net dot au) */ public class ArrayPtg : Ptg { public const byte sid = 0x20; private const int RESERVED_FIELD_LEN = 7; /** * The size of the plain tArray token written within the standard formula tokens * (not including the data which comes after all formula tokens) */ public const int PLAIN_TOKEN_SIZE = 1 + RESERVED_FIELD_LEN; //private static byte[] DEFAULT_RESERVED_DATA = new byte[RESERVED_FIELD_LEN]; // 7 bytes of data (stored as an int, short and byte here) private int _reserved0Int; private int _reserved1Short; private int _reserved2Byte; // data from these fields comes after the Ptg data of all tokens in current formula private int _nColumns; private int _nRows; private object[] _arrayValues; ArrayPtg(int reserved0, int reserved1, int reserved2, int nColumns, int nRows, object[] arrayValues) { _reserved0Int = reserved0; _reserved1Short = reserved1; _reserved2Byte = reserved2; _nColumns = nColumns; _nRows = nRows; _arrayValues = (object[])arrayValues.Clone(); } /** * @param values2d array values arranged in rows */ public ArrayPtg(Object[][] values2d) { int nColumns = values2d[0].Length; int nRows = values2d.Length; // convert 2-d to 1-d array (row by row according to getValueIndex()) _nColumns = (short)nColumns; _nRows = (short)nRows; Object[] vv = new Object[_nColumns * _nRows]; for (int r = 0; r < nRows; r++) { Object[] rowData = values2d[r]; for (int c = 0; c < nColumns; c++) { vv[GetValueIndex(c, r)] = rowData[c]; } } _arrayValues = vv; _reserved0Int = 0; _reserved1Short = 0; _reserved2Byte = 0; } public Object[][] GetTokenArrayValues() { if (_arrayValues == null) { throw new InvalidOperationException("array values not read yet"); } Object[][] result = new Object[_nRows][]; for (int r = 0; r < _nRows; r++) { result[r] = new object[_nColumns]; for (int c = 0; c < _nColumns; c++) { result[r][c] = _arrayValues[GetValueIndex(c, r)]; } } return result; } public override bool IsBaseToken { get { return false; } } public override String ToString() { StringBuilder buffer = new StringBuilder("[ArrayPtg]\n"); buffer.Append("columns = ").Append(ColumnCount).Append("\n"); buffer.Append("rows = ").Append(RowCount).Append("\n"); for (int x = 0; x < ColumnCount; x++) { for (int y = 0; y < RowCount; y++) { Object o = _arrayValues.GetValue(GetValueIndex(x, y)); buffer.Append("[").Append(x).Append("][").Append(y).Append("] = ").Append(o).Append("\n"); } } return buffer.ToString(); } /** * Note - (2D) array elements are stored column by column * @return the index into the internal 1D array for the specified column and row */ /* package */ public int GetValueIndex(int colIx, int rowIx) { if (colIx < 0 || colIx >= _nColumns) { throw new ArgumentException("Specified colIx (" + colIx + ") is outside the allowed range (0.." + (_nColumns - 1) + ")"); } if (rowIx < 0 || rowIx >= _nRows) { throw new ArgumentException("Specified rowIx (" + rowIx + ") is outside the allowed range (0.." + (_nRows - 1) + ")"); } return rowIx * _nColumns + colIx; } public override void Write(ILittleEndianOutput out1) { out1.WriteByte(sid + PtgClass); out1.WriteInt(_reserved0Int); out1.WriteShort(_reserved1Short); out1.WriteByte(_reserved2Byte); } public int WriteTokenValueBytes(ILittleEndianOutput out1) { out1.WriteByte(_nColumns - 1); out1.WriteShort(_nRows - 1); ConstantValueParser.Encode(out1, _arrayValues); return 3 + ConstantValueParser.GetEncodedSize(_arrayValues); } public int RowCount { get { return _nRows; } } public int ColumnCount { get { return _nColumns; } } /** This size includes the size of the array Ptg plus the Array Ptg Token value size*/ public override int Size { get { int size = 1 + 7 + 1 + 2; size += ConstantValueParser.GetEncodedSize(_arrayValues); return size; } } public override String ToFormulaString() { StringBuilder b = new StringBuilder(); b.Append("{"); for (int y = 0; y < _nRows; y++) { if (y > 0) { b.Append(";"); } for (int x = 0; x < _nColumns; x++) { if (x > 0) { b.Append(","); } Object o = _arrayValues.GetValue(GetValueIndex(x, y)); b.Append(GetConstantText(o)); } } b.Append("}"); return b.ToString(); } private static String GetConstantText(Object o) { if (o == null) { return ""; // TODO - how is 'empty value' represented in formulas? } if (o is String) { return "\"" + (String)o + "\""; } if (o is Double || o is double) { return NumberToTextConverter.ToText((Double)o); } if (o is bool || o is Boolean) { return ((bool)o).ToString().ToUpper(); } if (o is ErrorConstant) { return ((ErrorConstant)o).Text; } throw new ArgumentException("Unexpected constant class (" + o.GetType().Name + ")"); } public override byte DefaultOperandClass { get { return Ptg.CLASS_ARRAY; } } /** * Represents the initial plain tArray token (without the constant data that trails the whole * formula). Objects of this class are only temporary and cannot be used as {@link Ptg}s. * These temporary objects get converted to {@link ArrayPtg} by the * {@link #finishReading(LittleEndianInput)} method. */ public class Initial : Ptg { private int _reserved0; private int _reserved1; private int _reserved2; public Initial(ILittleEndianInput in1) { _reserved0 = in1.ReadInt(); _reserved1 = in1.ReadUShort(); _reserved2 = in1.ReadUByte(); } private static Exception Invalid() { throw new InvalidOperationException("This object is a partially initialised tArray, and cannot be used as a Ptg"); } public override byte DefaultOperandClass { get { throw Invalid(); } } public override int Size { get { return PLAIN_TOKEN_SIZE; } } public override bool IsBaseToken { get { return false; } } public override String ToFormulaString() { throw Invalid(); } public override void Write(ILittleEndianOutput out1) { throw Invalid(); } /** * Read in the actual token (array) values. This occurs * AFTER the last Ptg in the expression. * See page 304-305 of Excel97-2007BinaryFileFormat(xls)Specification.pdf */ public ArrayPtg FinishReading(ILittleEndianInput in1) { int nColumns = in1.ReadUByte(); short nRows = in1.ReadShort(); //The token_1_columns and token_2_rows do not follow the documentation. //The number of physical rows and columns is actually +1 of these values. //Which is not explicitly documented. nColumns++; nRows++; int totalCount = nRows * nColumns; Object[] arrayValues = ConstantValueParser.Parse(in1, totalCount); ArrayPtg result = new ArrayPtg(_reserved0, _reserved1, _reserved2, nColumns, nRows, arrayValues); result.PtgClass = this.PtgClass; return result; } } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Linq; using System.Net.Http; using Hyak.Common; using Microsoft.Azure; using Microsoft.Azure.Management.OperationalInsights; namespace Microsoft.Azure.Management.OperationalInsights { /// <summary> /// .Net client wrapper for the REST API for Azure Operational Insights /// </summary> public partial class OperationalInsightsManagementClient : ServiceClient<OperationalInsightsManagementClient>, IOperationalInsightsManagementClient { private string _apiVersion; /// <summary> /// Gets the API version. /// </summary> public string ApiVersion { get { return this._apiVersion; } } private Uri _baseUri; /// <summary> /// Gets the URI used as the base for all cloud service requests. /// </summary> public Uri BaseUri { get { return this._baseUri; } } private SubscriptionCloudCredentials _credentials; /// <summary> /// Gets subscription credentials which uniquely identify Microsoft /// Azure subscription. The subscription ID forms part of the URI for /// every service call. /// </summary> public SubscriptionCloudCredentials Credentials { get { return this._credentials; } } private int _longRunningOperationInitialTimeout; /// <summary> /// Gets or sets the initial timeout for Long Running Operations. /// </summary> public int LongRunningOperationInitialTimeout { get { return this._longRunningOperationInitialTimeout; } set { this._longRunningOperationInitialTimeout = value; } } private int _longRunningOperationRetryTimeout; /// <summary> /// Gets or sets the retry timeout for Long Running Operations. /// </summary> public int LongRunningOperationRetryTimeout { get { return this._longRunningOperationRetryTimeout; } set { this._longRunningOperationRetryTimeout = value; } } private IDataSourceOperations _dataSources; /// <summary> /// Operations for managing data sources under Workspaces. /// </summary> public virtual IDataSourceOperations DataSources { get { return this._dataSources; } } private ILinkedServiceOperations _linkedServices; /// <summary> /// Operations for managing Operational Insights linked services. /// </summary> public virtual ILinkedServiceOperations LinkedServices { get { return this._linkedServices; } } private ISearchOperations _search; /// <summary> /// Operations for using Operational Insights search. /// </summary> public virtual ISearchOperations Search { get { return this._search; } } private IStorageInsightOperations _storageInsights; /// <summary> /// Operations for managing storage insights. /// </summary> public virtual IStorageInsightOperations StorageInsights { get { return this._storageInsights; } } private IWorkspaceOperations _workspaces; /// <summary> /// Operations for managing Operational Insights workspaces. /// </summary> public virtual IWorkspaceOperations Workspaces { get { return this._workspaces; } } /// <summary> /// Initializes a new instance of the /// OperationalInsightsManagementClient class. /// </summary> public OperationalInsightsManagementClient() : base() { this._dataSources = new DataSourceOperations(this); this._linkedServices = new LinkedServiceOperations(this); this._search = new SearchOperations(this); this._storageInsights = new StorageInsightOperations(this); this._workspaces = new WorkspaceOperations(this); this._apiVersion = "2015-03-20"; this._longRunningOperationInitialTimeout = -1; this._longRunningOperationRetryTimeout = -1; this.HttpClient.Timeout = TimeSpan.FromSeconds(120); } /// <summary> /// Initializes a new instance of the /// OperationalInsightsManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Gets subscription credentials which uniquely identify /// Microsoft Azure subscription. The subscription ID forms part of /// the URI for every service call. /// </param> /// <param name='baseUri'> /// Optional. Gets the URI used as the base for all cloud service /// requests. /// </param> public OperationalInsightsManagementClient(SubscriptionCloudCredentials credentials, Uri baseUri) : this() { if (credentials == null) { throw new ArgumentNullException("credentials"); } if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this._credentials = credentials; this._baseUri = baseUri; this.Credentials.InitializeServiceClient(this); } /// <summary> /// Initializes a new instance of the /// OperationalInsightsManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Gets subscription credentials which uniquely identify /// Microsoft Azure subscription. The subscription ID forms part of /// the URI for every service call. /// </param> public OperationalInsightsManagementClient(SubscriptionCloudCredentials credentials) : this() { if (credentials == null) { throw new ArgumentNullException("credentials"); } this._credentials = credentials; this._baseUri = new Uri("https://management.azure.com"); this.Credentials.InitializeServiceClient(this); } /// <summary> /// Initializes a new instance of the /// OperationalInsightsManagementClient class. /// </summary> /// <param name='httpClient'> /// The Http client /// </param> public OperationalInsightsManagementClient(HttpClient httpClient) : base(httpClient) { this._dataSources = new DataSourceOperations(this); this._linkedServices = new LinkedServiceOperations(this); this._search = new SearchOperations(this); this._storageInsights = new StorageInsightOperations(this); this._workspaces = new WorkspaceOperations(this); this._apiVersion = "2015-03-20"; this._longRunningOperationInitialTimeout = -1; this._longRunningOperationRetryTimeout = -1; this.HttpClient.Timeout = TimeSpan.FromSeconds(120); } /// <summary> /// Initializes a new instance of the /// OperationalInsightsManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Gets subscription credentials which uniquely identify /// Microsoft Azure subscription. The subscription ID forms part of /// the URI for every service call. /// </param> /// <param name='baseUri'> /// Optional. Gets the URI used as the base for all cloud service /// requests. /// </param> /// <param name='httpClient'> /// The Http client /// </param> public OperationalInsightsManagementClient(SubscriptionCloudCredentials credentials, Uri baseUri, HttpClient httpClient) : this(httpClient) { if (credentials == null) { throw new ArgumentNullException("credentials"); } if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this._credentials = credentials; this._baseUri = baseUri; this.Credentials.InitializeServiceClient(this); } /// <summary> /// Initializes a new instance of the /// OperationalInsightsManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Gets subscription credentials which uniquely identify /// Microsoft Azure subscription. The subscription ID forms part of /// the URI for every service call. /// </param> /// <param name='httpClient'> /// The Http client /// </param> public OperationalInsightsManagementClient(SubscriptionCloudCredentials credentials, HttpClient httpClient) : this(httpClient) { if (credentials == null) { throw new ArgumentNullException("credentials"); } this._credentials = credentials; this._baseUri = new Uri("https://management.azure.com"); this.Credentials.InitializeServiceClient(this); } /// <summary> /// Clones properties from current instance to another /// OperationalInsightsManagementClient instance /// </summary> /// <param name='client'> /// Instance of OperationalInsightsManagementClient to clone to /// </param> protected override void Clone(ServiceClient<OperationalInsightsManagementClient> client) { base.Clone(client); if (client is OperationalInsightsManagementClient) { OperationalInsightsManagementClient clonedClient = ((OperationalInsightsManagementClient)client); clonedClient._credentials = this._credentials; clonedClient._baseUri = this._baseUri; clonedClient._apiVersion = this._apiVersion; clonedClient._longRunningOperationInitialTimeout = this._longRunningOperationInitialTimeout; clonedClient._longRunningOperationRetryTimeout = this._longRunningOperationRetryTimeout; clonedClient.Credentials.InitializeServiceClient(clonedClient); } } } }
#region License // Copyright (c) K2 Workflow (SourceCode Technology Holdings Inc.). All rights reserved. // Licensed under the MIT License. See LICENSE file in the project root for full license information. #endregion using System; using System.Collections.Generic; using System.Linq; using Xunit; namespace SourceCode.Chasm.Tests { public static class TreeNodeMapTests { #region Constants private static readonly TreeNode Node0 = new TreeNode(nameof(Node0), NodeKind.Tree, Sha1.Hash(nameof(Node0))); private static readonly TreeNode Node0Blob = new TreeNode(nameof(Node0), NodeKind.Blob, Sha1.Hash(nameof(Node0Blob))); private static readonly TreeNode Node1 = new TreeNode(nameof(Node1), NodeKind.Blob, Sha1.Hash(nameof(Node1))); private static readonly TreeNode Node2 = new TreeNode(nameof(Node2), NodeKind.Tree, Sha1.Hash(nameof(Node2))); private static readonly TreeNode Node3 = new TreeNode(nameof(Node3), NodeKind.Blob, Sha1.Hash(nameof(Node3))); #endregion #region Methods private static void AssertEmpty(TreeNodeMap treeNodeMap) { Assert.Empty(treeNodeMap); Assert.Equal(TreeNodeMap.Empty, treeNodeMap); // By design Assert.Equal(TreeNodeMap.Empty.GetHashCode(), treeNodeMap.GetHashCode()); Assert.Empty(treeNodeMap.Keys); Assert.Throws<IndexOutOfRangeException>(() => treeNodeMap[0]); Assert.Throws<KeyNotFoundException>(() => treeNodeMap["x"]); Assert.False(treeNodeMap.TryGetValue("x", out _)); Assert.False(treeNodeMap.TryGetValue("x", NodeKind.Blob, out _)); Assert.False(treeNodeMap.Equals(new object())); Assert.Contains("Count: 0", treeNodeMap.ToString()); Assert.Equal(-1, treeNodeMap.IndexOf(Guid.NewGuid().ToString())); } [Trait("Type", "Unit")] [Fact(DisplayName = nameof(TreeNodeMap_Empty))] public static void TreeNodeMap_Empty() { var noData = new TreeNodeMap(); AssertEmpty(noData); var nullData = new TreeNodeMap(null); AssertEmpty(nullData); var collData = new TreeNodeMap((IList<TreeNode>)null); AssertEmpty(collData); var emptyData = new TreeNodeMap(Array.Empty<TreeNode>()); AssertEmpty(emptyData); Assert.Empty(TreeNodeMap.Empty); Assert.Equal(default, TreeNodeMap.Empty); } [Trait("Type", "Unit")] [Fact(DisplayName = nameof(TreeNodeMap_Sorting))] public static void TreeNodeMap_Sorting() { var nodes = new[] { Node0, Node1 }; var tree0 = new TreeNodeMap(nodes.OrderBy(n => n.Sha1).ToArray()); var tree1 = new TreeNodeMap(nodes.OrderByDescending(n => n.Sha1).ToList()); // ICollection<T> Assert.Equal(tree0[0], tree1[0]); Assert.Equal(tree0[1], tree1[1]); Assert.True(tree1[Node0.Name] == Node0); Assert.True(tree1[Node1.Name] == Node1); Assert.False(tree1.ContainsKey("x")); Assert.True(tree1.ContainsKey(Node0.Name)); Assert.True(tree1.ContainsKey(Node1.Name)); Assert.False(tree1.TryGetValue("x", out _)); Assert.True(tree1.TryGetValue(Node0.Name, out var v20) && v20 == Node0); Assert.True(tree1.TryGetValue(Node1.Name, out var v21) && v21 == Node1); Assert.False(tree1.TryGetValue(Node0.Name, NodeKind.Blob, out _)); Assert.True(tree1.TryGetValue(Node0.Name, Node0.Kind, out _)); nodes = new[] { Node0, Node1, Node2 }; tree0 = new TreeNodeMap(nodes.OrderBy(n => n.Sha1).ToArray()); tree1 = new TreeNodeMap(nodes.OrderByDescending(n => n.Sha1).ToList()); // ICollection<T> Assert.True(tree1[Node0.Name] == Node0); Assert.True(tree1[Node1.Name] == Node1); Assert.True(tree1[Node2.Name] == Node2); Assert.False(tree1.ContainsKey("x")); Assert.True(tree1.ContainsKey(Node0.Name)); Assert.True(tree1.ContainsKey(Node1.Name)); Assert.True(tree1.ContainsKey(Node2.Name)); Assert.False(tree1.TryGetValue("x", out _)); Assert.True(tree1.TryGetValue(Node0.Name, out var v30) && v30 == Node0); Assert.True(tree1.TryGetValue(Node1.Name, out var v31) && v31 == Node1); Assert.True(tree1.TryGetValue(Node2.Name, out var v32) && v32 == Node2); Assert.Equal(tree0[0], tree1[0]); Assert.Equal(tree0[1], tree1[1]); Assert.Equal(tree0[2], tree1[2]); nodes = new[] { Node0, Node1, Node2, Node3 }; tree0 = new TreeNodeMap(nodes.OrderBy(n => n.Sha1).ToArray()); tree1 = new TreeNodeMap(nodes.OrderByDescending(n => n.Sha1).ToList()); // ICollection<T> Assert.True(tree1[Node0.Name] == Node0); Assert.True(tree1[Node1.Name] == Node1); Assert.True(tree1[Node2.Name] == Node2); Assert.True(tree1[Node3.Name] == Node3); Assert.False(tree1.ContainsKey("x")); Assert.True(tree1.ContainsKey(Node0.Name)); Assert.True(tree1.ContainsKey(Node1.Name)); Assert.True(tree1.ContainsKey(Node2.Name)); Assert.True(tree1.ContainsKey(Node3.Name)); Assert.False(tree1.TryGetValue("x", out _)); Assert.True(tree1.TryGetValue(Node0.Name, out var v40) && v40 == Node0); Assert.True(tree1.TryGetValue(Node1.Name, out var v41) && v41 == Node1); Assert.True(tree1.TryGetValue(Node2.Name, out var v42) && v42 == Node2); Assert.True(tree1.TryGetValue(Node3.Name, out var v43) && v43 == Node3); Assert.Equal(tree0[0], tree1[0]); Assert.Equal(tree0[1], tree1[1]); Assert.Equal(tree0[2], tree1[2]); Assert.Equal(tree0[3], tree1[3]); } [Trait("Type", "Unit")] [Fact(DisplayName = nameof(TreeNodeMap_Duplicate_Full_2))] public static void TreeNodeMap_Duplicate_Full_2() { var nodes = new[] { Node0, Node0 }; var tree = new TreeNodeMap(nodes); Assert.Collection<TreeNode>(tree, n => Assert.Equal(n, Node0)); tree = new TreeNodeMap(nodes.ToList()); // ICollection<T> Assert.Collection<TreeNode>(tree, n => Assert.Equal(n, Node0)); } [Trait("Type", "Unit")] [Fact(DisplayName = nameof(TreeNodeMap_Duplicate_Full_3))] public static void TreeNodeMap_Duplicate_Full_3() { var nodes = new[] { Node0, Node1, Node0 }; // Shuffled var tree = new TreeNodeMap(nodes); Assert.Collection<TreeNode>(tree, n => Assert.Equal(n, Node0), n => Assert.Equal(n, Node1)); tree = new TreeNodeMap(nodes.ToList()); // ICollection<T> Assert.Collection<TreeNode>(tree, n => Assert.Equal(n, Node0), n => Assert.Equal(n, Node1)); } [Trait("Type", "Unit")] [Fact(DisplayName = nameof(TreeNodeMap_Duplicate_Full_2_Exception))] public static void TreeNodeMap_Duplicate_Full_2_Exception() { // Arrange var nodes = new[] { Node0, Node0Blob }; // Shuffled // Action var ex = Assert.Throws<ArgumentException>(() => new TreeNodeMap(nodes)); // Assert Assert.Contains(Node0.Name, ex.Message); Assert.Contains(Node0.Sha1.ToString(), ex.Message); } [Trait("Type", "Unit")] [Fact(DisplayName = nameof(TreeNodeMap_Duplicate_Full_3_Exception))] public static void TreeNodeMap_Duplicate_Full_3_Exception() { // Arrange var nodes = new[] { Node0, Node0Blob, Node1 }; // Shuffled // Action var ex = Assert.Throws<ArgumentException>(() => new TreeNodeMap(nodes)); // Assert Assert.Contains(Node0.Name, ex.Message); Assert.Contains(Node0.Sha1.ToString(), ex.Message); } [Trait("Type", "Unit")] [Fact(DisplayName = nameof(TreeNodeMap_Duplicate_Full_4))] public static void TreeNodeMap_Duplicate_Full_4() { var nodes = new[] { Node0, Node2, Node1, Node0 }; // Shuffled var tree = new TreeNodeMap(nodes); Assert.Collection<TreeNode>(tree, n => Assert.Equal(n, Node0), n => Assert.Equal(n, Node1), n => Assert.Equal(n, Node2)); tree = new TreeNodeMap(nodes.ToList()); // ICollection<T> Assert.Collection<TreeNode>(tree, n => Assert.Equal(n, Node0), n => Assert.Equal(n, Node1), n => Assert.Equal(n, Node2)); } [Trait("Type", "Unit")] [Fact(DisplayName = nameof(TreeNodeMap_Duplicate_Full_N))] public static void TreeNodeMap_Duplicate_Full_N() { var nodes = new[] { Node3, Node1, Node2, Node0, Node3, Node0, Node1, Node0, Node1, Node2, Node0, Node3 }; // Shuffled var tree = new TreeNodeMap(nodes); Assert.Collection<TreeNode>(tree, n => Assert.Equal(n, Node0), n => Assert.Equal(n, Node1), n => Assert.Equal(n, Node2), n => Assert.Equal(n, Node3)); tree = new TreeNodeMap(nodes.ToList()); // ICollection<T> Assert.Collection<TreeNode>(tree, n => Assert.Equal(n, Node0), n => Assert.Equal(n, Node1), n => Assert.Equal(n, Node2), n => Assert.Equal(n, Node3)); } [Trait("Type", "Unit")] [Fact(DisplayName = nameof(TreeNodeMap_Duplicate_Name))] public static void TreeNodeMap_Duplicate_Name() { var nodes = new[] { new TreeNode(Node0.Name, NodeKind.Tree, Node1.Sha1), Node0 }; // Reversed Assert.Throws<ArgumentException>(() => new TreeNodeMap(nodes)); Assert.Throws<ArgumentException>(() => new TreeNodeMap(nodes.ToList())); // ICollection<T> } [Trait("Type", "Unit")] [Fact(DisplayName = nameof(TreeNodeMap_Duplicate_Sha1))] public static void TreeNodeMap_Duplicate_Sha1() { var nodes = new[] { new TreeNode(Node1.Name, NodeKind.Tree, Node0.Sha1), Node0 }; // Reversed var tree0 = new TreeNodeMap(nodes); Assert.Collection<TreeNode>(tree0, n => Assert.Equal(n, Node0), n => Assert.Equal(n, nodes[0])); tree0 = new TreeNodeMap(nodes.ToList()); // ICollection<T> Assert.Collection<TreeNode>(tree0, n => Assert.Equal(n, Node0), n => Assert.Equal(n, nodes[0])); } [Trait("Type", "Unit")] [Fact(DisplayName = nameof(TreeNodeMap_Equality))] public static void TreeNodeMap_Equality() { var expected = new TreeNodeMap(new[] { new TreeNode("c1", NodeKind.Blob, Sha1.Hash("c1")), new TreeNode("c2", NodeKind.Tree, Sha1.Hash("c2")) }); var node3 = new TreeNode("c3", NodeKind.Tree, Sha1.Hash("c3")); // Equal var actual = new TreeNodeMap().Merge(expected); Assert.Equal(expected, actual); Assert.Equal(expected.GetHashCode(), actual.GetHashCode()); Assert.True(actual.Equals((object)expected)); Assert.True(expected == actual); Assert.False(expected != actual); // Less Nodes actual = new TreeNodeMap().Merge(expected[0]); Assert.NotEqual(expected, actual); Assert.NotEqual(expected.GetHashCode(), actual.GetHashCode()); Assert.False(actual.Equals((object)expected)); Assert.False(expected == actual); Assert.True(expected != actual); // More Nodes actual = new TreeNodeMap().Merge(expected).Merge(node3); Assert.NotEqual(expected, actual); Assert.NotEqual(expected.GetHashCode(), actual.GetHashCode()); Assert.False(actual.Equals((object)expected)); Assert.False(expected == actual); Assert.True(expected != actual); // Different Nodes actual = new TreeNodeMap().Merge(expected[0]).Merge(node3); Assert.NotEqual(expected, actual); // hashcode is the same (node count) Assert.False(actual.Equals((object)expected)); Assert.False(expected == actual); Assert.True(expected != actual); } [Trait("Type", "Unit")] [Fact(DisplayName = nameof(TreeNodeMap_IndexOf))] public static void TreeNodeMap_IndexOf() { // Arrange var actual = new TreeNodeMap(new[] { Node0, Node1 }); // Action/Assert Assert.Equal(-1, actual.IndexOf(null)); Assert.True(actual.IndexOf(Guid.NewGuid().ToString()) < 0); Assert.Equal(0, actual.IndexOf(Node0.Name)); Assert.Equal(1, actual.IndexOf(Node1.Name)); } [Trait("Type", "Unit")] [Fact(DisplayName = nameof(TreeNodeMap_Merge_Empty))] public static void TreeNodeMap_Merge_Empty() { var emptyTreeNodeMap = new TreeNodeMap(); var node = new TreeNode("b", NodeKind.Blob, Sha1.Hash("Test1")); var list = new TreeNodeMap(node); // TreeNodeMap var merged = list.Merge(emptyTreeNodeMap); Assert.Equal(list, merged); merged = emptyTreeNodeMap.Merge(list); Assert.Equal(list, merged); // ICollection merged = list.Merge(Array.Empty<TreeNode>()); Assert.Equal(list, merged); merged = emptyTreeNodeMap.Merge(list.Values.ToArray()); Assert.Equal(list, merged); } [Trait("Type", "Unit")] [Fact(DisplayName = nameof(TreeNodeMap_Merge_Null))] public static void TreeNodeMap_Merge_Null() { // Arrange var list = new TreeNodeMap(Node0); // Action var merged = list.Merge(null); // Assert Assert.Equal(list, merged); } [Trait("Type", "Unit")] [Fact(DisplayName = nameof(TreeNodeMap_Merge_Single))] public static void TreeNodeMap_Merge_Single() { var list = new TreeNodeMap(); list = list.Merge(new TreeNode("b", NodeKind.Blob, Sha1.Hash("Test1"))); list = list.Merge(new TreeNode("a", NodeKind.Tree, Sha1.Hash("Test2"))); list = list.Merge(new TreeNode("c", NodeKind.Blob, Sha1.Hash("Test3"))); list = list.Merge(new TreeNode("d", NodeKind.Tree, Sha1.Hash("Test4"))); list = list.Merge(new TreeNode("g", NodeKind.Blob, Sha1.Hash("Test5"))); list = list.Merge(new TreeNode("e", NodeKind.Tree, Sha1.Hash("Test6"))); list = list.Merge(new TreeNode("f", NodeKind.Blob, Sha1.Hash("Test7"))); var prev = list.Keys.First(); foreach (var cur in list.Keys.Skip(1)) { Assert.True(string.CompareOrdinal(cur, prev) > 0); prev = cur; } } [Trait("Type", "Unit")] [Fact(DisplayName = nameof(TreeNodeMap_Merge_Single_Exist))] public static void TreeNodeMap_Merge_Single_Exist() { // Arrange var list = new TreeNodeMap(); var expectedName = Guid.NewGuid().ToString(); var expectedKind = NodeKind.Tree; var expectedSha1 = Sha1.Hash(Guid.NewGuid().ToString()); list = list.Merge(new TreeNode(expectedName, NodeKind.Blob, Sha1.Hash("Test1"))); // Action var actual = list.Merge(new TreeNode(expectedName, expectedKind, expectedSha1)); var actualNode = actual[expectedName]; // Assert Assert.Equal(expectedName, actualNode.Name); Assert.Equal(expectedKind, actualNode.Kind); Assert.Equal(expectedSha1, actualNode.Sha1); } [Trait("Type", "Unit")] [Fact(DisplayName = nameof(TreeNodeMap_Merge_TreeNodeMap))] public static void TreeNodeMap_Merge_TreeNodeMap() { var list1 = new TreeNodeMap(); list1 = list1.Merge(new TreeNode("d", NodeKind.Tree, Sha1.Hash("Test4"))); list1 = list1.Merge(new TreeNode("e", NodeKind.Tree, Sha1.Hash("Test5"))); list1 = list1.Merge(new TreeNode("f", NodeKind.Blob, Sha1.Hash("Test6"))); list1 = list1.Merge(new TreeNode("g", NodeKind.Blob, Sha1.Hash("Test7"))); var list2 = new TreeNodeMap(); list2 = list2.Merge(new TreeNode("a", NodeKind.Tree, Sha1.Hash("Test1"))); list2 = list2.Merge(new TreeNode("b", NodeKind.Blob, Sha1.Hash("Test2"))); list2 = list2.Merge(new TreeNode("c", NodeKind.Blob, Sha1.Hash("Test3"))); list2 = list2.Merge(new TreeNode("d", NodeKind.Tree, Sha1.Hash("Test4 Replace"))); list2 = list2.Merge(new TreeNode("g", NodeKind.Blob, Sha1.Hash("Test5 Replace"))); list2 = list2.Merge(new TreeNode("q", NodeKind.Tree, Sha1.Hash("Test8"))); list2 = list2.Merge(new TreeNode("r", NodeKind.Blob, Sha1.Hash("Test9"))); var list3 = list1.Merge(list2); Assert.Equal(9, list3.Count); Assert.Equal("a", list3[0].Name); Assert.Equal("b", list3[1].Name); Assert.Equal("c", list3[2].Name); Assert.Equal("d", list3[3].Name); Assert.Equal("e", list3[4].Name); Assert.Equal("f", list3[5].Name); Assert.Equal("g", list3[6].Name); Assert.Equal("q", list3[7].Name); Assert.Equal("r", list3[8].Name); Assert.Equal(list2[0].Sha1, list3[0].Sha1); Assert.Equal(list2[1].Sha1, list3[1].Sha1); Assert.Equal(list2[2].Sha1, list3[2].Sha1); Assert.Equal(list2[3].Sha1, list3[3].Sha1); Assert.Equal(list1[1].Sha1, list3[4].Sha1); Assert.Equal(list1[2].Sha1, list3[5].Sha1); Assert.Equal(list2[4].Sha1, list3[6].Sha1); Assert.Equal(list2[5].Sha1, list3[7].Sha1); Assert.Equal(list2[6].Sha1, list3[8].Sha1); } [Trait("Type", "Unit")] [Fact(DisplayName = nameof(TreeNodeMap_Merge_Collection))] public static void TreeNodeMap_Merge_Collection() { var list1 = new TreeNodeMap(); list1 = list1.Merge(new TreeNode("d", NodeKind.Tree, Sha1.Hash("Test4"))); list1 = list1.Merge(new TreeNode("e", NodeKind.Tree, Sha1.Hash("Test5"))); list1 = list1.Merge(new TreeNode("f", NodeKind.Blob, Sha1.Hash("Test6"))); list1 = list1.Merge(new TreeNode("g", NodeKind.Blob, Sha1.Hash("Test7"))); var list2 = new[] { new TreeNode("c", NodeKind.Blob, Sha1.Hash("Test3")), new TreeNode("a", NodeKind.Tree, Sha1.Hash("Test1")), new TreeNode("b", NodeKind.Blob, Sha1.Hash("Test2")), new TreeNode("d", NodeKind.Tree, Sha1.Hash("Test4 Replace")), new TreeNode("g", NodeKind.Blob, Sha1.Hash("Test5 Replace")), new TreeNode("q", NodeKind.Tree, Sha1.Hash("Test8")), new TreeNode("r", NodeKind.Blob, Sha1.Hash("Test9")), }; var list3 = list1.Merge(list2); Assert.Equal(9, list3.Count); Assert.Equal("a", list3[0].Name); Assert.Equal("b", list3[1].Name); Assert.Equal("c", list3[2].Name); Assert.Equal("d", list3[3].Name); Assert.Equal("e", list3[4].Name); Assert.Equal("f", list3[5].Name); Assert.Equal("g", list3[6].Name); Assert.Equal("q", list3[7].Name); Assert.Equal("r", list3[8].Name); Assert.Equal(list2[1].Sha1, list3[0].Sha1); Assert.Equal(list2[2].Sha1, list3[1].Sha1); Assert.Equal(list2[0].Sha1, list3[2].Sha1); Assert.Equal(list2[3].Sha1, list3[3].Sha1); Assert.Equal(list1[1].Sha1, list3[4].Sha1); Assert.Equal(list1[2].Sha1, list3[5].Sha1); Assert.Equal(list2[4].Sha1, list3[6].Sha1); Assert.Equal(list2[5].Sha1, list3[7].Sha1); Assert.Equal(list2[6].Sha1, list3[8].Sha1); var dupes = new[] { new TreeNode(list2[0].Name, list2[0].Kind, list2[1].Sha1), new TreeNode(list2[1].Name, list2[1].Kind, list2[2].Sha1), new TreeNode(list2[2].Name, list2[2].Kind, list2[3].Sha1), new TreeNode(list2[3].Name, list2[3].Kind, list2[0].Sha1) }; list3 = list3.Merge(dupes); } [Trait("Type", "Unit")] [Fact(DisplayName = nameof(TreeNodeMap_Delete))] public static void TreeNodeMap_Delete() { var sut = new TreeNodeMap( new TreeNode("a", NodeKind.Blob, Sha1.Hash("a")), new TreeNode("b", NodeKind.Blob, Sha1.Hash("b")), new TreeNode("c", NodeKind.Blob, Sha1.Hash("c")) ); var removed = sut.Delete("a"); Assert.Equal(2, removed.Count); Assert.Equal("b", removed[0].Name); Assert.Equal("c", removed[1].Name); removed = sut.Delete("b"); Assert.Equal(2, removed.Count); Assert.Equal("a", removed[0].Name); Assert.Equal("c", removed[1].Name); removed = sut.Delete("c"); Assert.Equal(2, removed.Count); Assert.Equal("a", removed[0].Name); Assert.Equal("b", removed[1].Name); } [Trait("Type", "Unit")] [Fact(DisplayName = nameof(TreeNodeMap_Delete_Predicate))] public static void TreeNodeMap_Delete_Predicate() { var sut = new TreeNodeMap( new TreeNode("a", NodeKind.Blob, Sha1.Hash("a")), new TreeNode("b", NodeKind.Blob, Sha1.Hash("b")), new TreeNode("c", NodeKind.Blob, Sha1.Hash("c")) ); var set = new HashSet<string>(StringComparer.Ordinal) { "a", "b", "d" }; var removed = sut.Delete(set.Contains); Assert.Single(removed); Assert.Equal("c", removed[0].Name); } [Trait("Type", "Unit")] [Fact(DisplayName = nameof(TreeNodeMap_IReadOnlyDictionary_Empty_GetEnumerator))] public static void TreeNodeMap_IReadOnlyDictionary_Empty_GetEnumerator() { // Arrange var treeNodeMap = new TreeNodeMap(); var readOnlyDictionary = treeNodeMap as IReadOnlyDictionary<string, TreeNode>; // Action var enumerator = readOnlyDictionary.GetEnumerator(); // Assert Assert.False(enumerator.MoveNext()); var current = enumerator.Current; Assert.Null(current.Key); Assert.Equal(TreeNode.Empty, current.Value); } [Trait("Type", "Unit")] [Fact(DisplayName = nameof(TreeNodeMap_IReadOnlyDictionary_GetEnumerator))] public static void TreeNodeMap_IReadOnlyDictionary_GetEnumerator() { // Arrange var nodes = new[] { Node0, Node1 }; var treeNodeMap = new TreeNodeMap(nodes); var readOnlyDictionary = treeNodeMap as IReadOnlyDictionary<string, TreeNode>; // Action var enumerator = readOnlyDictionary.GetEnumerator(); // Assert Assert.True(enumerator.MoveNext()); Assert.Equal(Node0, enumerator.Current.Value); Assert.True(enumerator.MoveNext()); Assert.Equal(Node1, enumerator.Current.Value); Assert.False(enumerator.MoveNext()); Assert.Equal(Node1, enumerator.Current.Value); } #endregion } }
using System; using Gnu.MP.BrickCoinProtocol.BouncyCastle.Utilities; namespace Gnu.MP.BrickCoinProtocol.BouncyCastle.Crypto.Digests { /** * implementation of RipeMD see, * http://www.esat.kuleuven.ac.be/~bosselae/ripemd160.html */ internal class RipeMD160Digest : GeneralDigest { private const int DigestLength = 20; private int H0, H1, H2, H3, H4; // IV's private int[] X = new int[16]; private int xOff; /** * Standard constructor */ public RipeMD160Digest() { Reset(); } /** * Copy constructor. This will copy the state of the provided * message digest. */ public RipeMD160Digest(RipeMD160Digest t) : base(t) { CopyIn(t); } private void CopyIn(RipeMD160Digest t) { base.CopyIn(t); H0 = t.H0; H1 = t.H1; H2 = t.H2; H3 = t.H3; H4 = t.H4; Array.Copy(t.X, 0, X, 0, t.X.Length); xOff = t.xOff; } public override string AlgorithmName { get { return "RIPEMD160"; } } public override int GetDigestSize() { return DigestLength; } internal override void ProcessWord( byte[] input, int inOff) { X[xOff++] = (input[inOff] & 0xff) | ((input[inOff + 1] & 0xff) << 8) | ((input[inOff + 2] & 0xff) << 16) | ((input[inOff + 3] & 0xff) << 24); if(xOff == 16) { ProcessBlock(); } } internal override void ProcessLength( long bitLength) { if(xOff > 14) { ProcessBlock(); } X[14] = (int)(bitLength & 0xffffffff); X[15] = (int)((ulong)bitLength >> 32); } private void UnpackWord( int word, byte[] outBytes, int outOff) { outBytes[outOff] = (byte)word; outBytes[outOff + 1] = (byte)((uint)word >> 8); outBytes[outOff + 2] = (byte)((uint)word >> 16); outBytes[outOff + 3] = (byte)((uint)word >> 24); } public override int DoFinal( byte[] output, int outOff) { Finish(); UnpackWord(H0, output, outOff); UnpackWord(H1, output, outOff + 4); UnpackWord(H2, output, outOff + 8); UnpackWord(H3, output, outOff + 12); UnpackWord(H4, output, outOff + 16); Reset(); return DigestLength; } /** * reset the chaining variables to the IV values. */ public override void Reset() { base.Reset(); H0 = unchecked((int)0x67452301); H1 = unchecked((int)0xefcdab89); H2 = unchecked((int)0x98badcfe); H3 = unchecked((int)0x10325476); H4 = unchecked((int)0xc3d2e1f0); xOff = 0; for(int i = 0; i != X.Length; i++) { X[i] = 0; } } /* * rotate int x left n bits. */ private int RL( int x, int n) { return (x << n) | (int)((uint)x >> (32 - n)); } /* * f1,f2,f3,f4,f5 are the basic RipeMD160 functions. */ /* * rounds 0-15 */ private int F1( int x, int y, int z) { return x ^ y ^ z; } /* * rounds 16-31 */ private int F2( int x, int y, int z) { return (x & y) | (~x & z); } /* * rounds 32-47 */ private int F3( int x, int y, int z) { return (x | ~y) ^ z; } /* * rounds 48-63 */ private int F4( int x, int y, int z) { return (x & z) | (y & ~z); } /* * rounds 64-79 */ private int F5( int x, int y, int z) { return x ^ (y | ~z); } internal override void ProcessBlock() { int a, aa; int b, bb; int c, cc; int d, dd; int e, ee; a = aa = H0; b = bb = H1; c = cc = H2; d = dd = H3; e = ee = H4; // // Rounds 1 - 16 // // left a = RL(a + F1(b, c, d) + X[0], 11) + e; c = RL(c, 10); e = RL(e + F1(a, b, c) + X[1], 14) + d; b = RL(b, 10); d = RL(d + F1(e, a, b) + X[2], 15) + c; a = RL(a, 10); c = RL(c + F1(d, e, a) + X[3], 12) + b; e = RL(e, 10); b = RL(b + F1(c, d, e) + X[4], 5) + a; d = RL(d, 10); a = RL(a + F1(b, c, d) + X[5], 8) + e; c = RL(c, 10); e = RL(e + F1(a, b, c) + X[6], 7) + d; b = RL(b, 10); d = RL(d + F1(e, a, b) + X[7], 9) + c; a = RL(a, 10); c = RL(c + F1(d, e, a) + X[8], 11) + b; e = RL(e, 10); b = RL(b + F1(c, d, e) + X[9], 13) + a; d = RL(d, 10); a = RL(a + F1(b, c, d) + X[10], 14) + e; c = RL(c, 10); e = RL(e + F1(a, b, c) + X[11], 15) + d; b = RL(b, 10); d = RL(d + F1(e, a, b) + X[12], 6) + c; a = RL(a, 10); c = RL(c + F1(d, e, a) + X[13], 7) + b; e = RL(e, 10); b = RL(b + F1(c, d, e) + X[14], 9) + a; d = RL(d, 10); a = RL(a + F1(b, c, d) + X[15], 8) + e; c = RL(c, 10); // right aa = RL(aa + F5(bb, cc, dd) + X[5] + unchecked((int)0x50a28be6), 8) + ee; cc = RL(cc, 10); ee = RL(ee + F5(aa, bb, cc) + X[14] + unchecked((int)0x50a28be6), 9) + dd; bb = RL(bb, 10); dd = RL(dd + F5(ee, aa, bb) + X[7] + unchecked((int)0x50a28be6), 9) + cc; aa = RL(aa, 10); cc = RL(cc + F5(dd, ee, aa) + X[0] + unchecked((int)0x50a28be6), 11) + bb; ee = RL(ee, 10); bb = RL(bb + F5(cc, dd, ee) + X[9] + unchecked((int)0x50a28be6), 13) + aa; dd = RL(dd, 10); aa = RL(aa + F5(bb, cc, dd) + X[2] + unchecked((int)0x50a28be6), 15) + ee; cc = RL(cc, 10); ee = RL(ee + F5(aa, bb, cc) + X[11] + unchecked((int)0x50a28be6), 15) + dd; bb = RL(bb, 10); dd = RL(dd + F5(ee, aa, bb) + X[4] + unchecked((int)0x50a28be6), 5) + cc; aa = RL(aa, 10); cc = RL(cc + F5(dd, ee, aa) + X[13] + unchecked((int)0x50a28be6), 7) + bb; ee = RL(ee, 10); bb = RL(bb + F5(cc, dd, ee) + X[6] + unchecked((int)0x50a28be6), 7) + aa; dd = RL(dd, 10); aa = RL(aa + F5(bb, cc, dd) + X[15] + unchecked((int)0x50a28be6), 8) + ee; cc = RL(cc, 10); ee = RL(ee + F5(aa, bb, cc) + X[8] + unchecked((int)0x50a28be6), 11) + dd; bb = RL(bb, 10); dd = RL(dd + F5(ee, aa, bb) + X[1] + unchecked((int)0x50a28be6), 14) + cc; aa = RL(aa, 10); cc = RL(cc + F5(dd, ee, aa) + X[10] + unchecked((int)0x50a28be6), 14) + bb; ee = RL(ee, 10); bb = RL(bb + F5(cc, dd, ee) + X[3] + unchecked((int)0x50a28be6), 12) + aa; dd = RL(dd, 10); aa = RL(aa + F5(bb, cc, dd) + X[12] + unchecked((int)0x50a28be6), 6) + ee; cc = RL(cc, 10); // // Rounds 16-31 // // left e = RL(e + F2(a, b, c) + X[7] + unchecked((int)0x5a827999), 7) + d; b = RL(b, 10); d = RL(d + F2(e, a, b) + X[4] + unchecked((int)0x5a827999), 6) + c; a = RL(a, 10); c = RL(c + F2(d, e, a) + X[13] + unchecked((int)0x5a827999), 8) + b; e = RL(e, 10); b = RL(b + F2(c, d, e) + X[1] + unchecked((int)0x5a827999), 13) + a; d = RL(d, 10); a = RL(a + F2(b, c, d) + X[10] + unchecked((int)0x5a827999), 11) + e; c = RL(c, 10); e = RL(e + F2(a, b, c) + X[6] + unchecked((int)0x5a827999), 9) + d; b = RL(b, 10); d = RL(d + F2(e, a, b) + X[15] + unchecked((int)0x5a827999), 7) + c; a = RL(a, 10); c = RL(c + F2(d, e, a) + X[3] + unchecked((int)0x5a827999), 15) + b; e = RL(e, 10); b = RL(b + F2(c, d, e) + X[12] + unchecked((int)0x5a827999), 7) + a; d = RL(d, 10); a = RL(a + F2(b, c, d) + X[0] + unchecked((int)0x5a827999), 12) + e; c = RL(c, 10); e = RL(e + F2(a, b, c) + X[9] + unchecked((int)0x5a827999), 15) + d; b = RL(b, 10); d = RL(d + F2(e, a, b) + X[5] + unchecked((int)0x5a827999), 9) + c; a = RL(a, 10); c = RL(c + F2(d, e, a) + X[2] + unchecked((int)0x5a827999), 11) + b; e = RL(e, 10); b = RL(b + F2(c, d, e) + X[14] + unchecked((int)0x5a827999), 7) + a; d = RL(d, 10); a = RL(a + F2(b, c, d) + X[11] + unchecked((int)0x5a827999), 13) + e; c = RL(c, 10); e = RL(e + F2(a, b, c) + X[8] + unchecked((int)0x5a827999), 12) + d; b = RL(b, 10); // right ee = RL(ee + F4(aa, bb, cc) + X[6] + unchecked((int)0x5c4dd124), 9) + dd; bb = RL(bb, 10); dd = RL(dd + F4(ee, aa, bb) + X[11] + unchecked((int)0x5c4dd124), 13) + cc; aa = RL(aa, 10); cc = RL(cc + F4(dd, ee, aa) + X[3] + unchecked((int)0x5c4dd124), 15) + bb; ee = RL(ee, 10); bb = RL(bb + F4(cc, dd, ee) + X[7] + unchecked((int)0x5c4dd124), 7) + aa; dd = RL(dd, 10); aa = RL(aa + F4(bb, cc, dd) + X[0] + unchecked((int)0x5c4dd124), 12) + ee; cc = RL(cc, 10); ee = RL(ee + F4(aa, bb, cc) + X[13] + unchecked((int)0x5c4dd124), 8) + dd; bb = RL(bb, 10); dd = RL(dd + F4(ee, aa, bb) + X[5] + unchecked((int)0x5c4dd124), 9) + cc; aa = RL(aa, 10); cc = RL(cc + F4(dd, ee, aa) + X[10] + unchecked((int)0x5c4dd124), 11) + bb; ee = RL(ee, 10); bb = RL(bb + F4(cc, dd, ee) + X[14] + unchecked((int)0x5c4dd124), 7) + aa; dd = RL(dd, 10); aa = RL(aa + F4(bb, cc, dd) + X[15] + unchecked((int)0x5c4dd124), 7) + ee; cc = RL(cc, 10); ee = RL(ee + F4(aa, bb, cc) + X[8] + unchecked((int)0x5c4dd124), 12) + dd; bb = RL(bb, 10); dd = RL(dd + F4(ee, aa, bb) + X[12] + unchecked((int)0x5c4dd124), 7) + cc; aa = RL(aa, 10); cc = RL(cc + F4(dd, ee, aa) + X[4] + unchecked((int)0x5c4dd124), 6) + bb; ee = RL(ee, 10); bb = RL(bb + F4(cc, dd, ee) + X[9] + unchecked((int)0x5c4dd124), 15) + aa; dd = RL(dd, 10); aa = RL(aa + F4(bb, cc, dd) + X[1] + unchecked((int)0x5c4dd124), 13) + ee; cc = RL(cc, 10); ee = RL(ee + F4(aa, bb, cc) + X[2] + unchecked((int)0x5c4dd124), 11) + dd; bb = RL(bb, 10); // // Rounds 32-47 // // left d = RL(d + F3(e, a, b) + X[3] + unchecked((int)0x6ed9eba1), 11) + c; a = RL(a, 10); c = RL(c + F3(d, e, a) + X[10] + unchecked((int)0x6ed9eba1), 13) + b; e = RL(e, 10); b = RL(b + F3(c, d, e) + X[14] + unchecked((int)0x6ed9eba1), 6) + a; d = RL(d, 10); a = RL(a + F3(b, c, d) + X[4] + unchecked((int)0x6ed9eba1), 7) + e; c = RL(c, 10); e = RL(e + F3(a, b, c) + X[9] + unchecked((int)0x6ed9eba1), 14) + d; b = RL(b, 10); d = RL(d + F3(e, a, b) + X[15] + unchecked((int)0x6ed9eba1), 9) + c; a = RL(a, 10); c = RL(c + F3(d, e, a) + X[8] + unchecked((int)0x6ed9eba1), 13) + b; e = RL(e, 10); b = RL(b + F3(c, d, e) + X[1] + unchecked((int)0x6ed9eba1), 15) + a; d = RL(d, 10); a = RL(a + F3(b, c, d) + X[2] + unchecked((int)0x6ed9eba1), 14) + e; c = RL(c, 10); e = RL(e + F3(a, b, c) + X[7] + unchecked((int)0x6ed9eba1), 8) + d; b = RL(b, 10); d = RL(d + F3(e, a, b) + X[0] + unchecked((int)0x6ed9eba1), 13) + c; a = RL(a, 10); c = RL(c + F3(d, e, a) + X[6] + unchecked((int)0x6ed9eba1), 6) + b; e = RL(e, 10); b = RL(b + F3(c, d, e) + X[13] + unchecked((int)0x6ed9eba1), 5) + a; d = RL(d, 10); a = RL(a + F3(b, c, d) + X[11] + unchecked((int)0x6ed9eba1), 12) + e; c = RL(c, 10); e = RL(e + F3(a, b, c) + X[5] + unchecked((int)0x6ed9eba1), 7) + d; b = RL(b, 10); d = RL(d + F3(e, a, b) + X[12] + unchecked((int)0x6ed9eba1), 5) + c; a = RL(a, 10); // right dd = RL(dd + F3(ee, aa, bb) + X[15] + unchecked((int)0x6d703ef3), 9) + cc; aa = RL(aa, 10); cc = RL(cc + F3(dd, ee, aa) + X[5] + unchecked((int)0x6d703ef3), 7) + bb; ee = RL(ee, 10); bb = RL(bb + F3(cc, dd, ee) + X[1] + unchecked((int)0x6d703ef3), 15) + aa; dd = RL(dd, 10); aa = RL(aa + F3(bb, cc, dd) + X[3] + unchecked((int)0x6d703ef3), 11) + ee; cc = RL(cc, 10); ee = RL(ee + F3(aa, bb, cc) + X[7] + unchecked((int)0x6d703ef3), 8) + dd; bb = RL(bb, 10); dd = RL(dd + F3(ee, aa, bb) + X[14] + unchecked((int)0x6d703ef3), 6) + cc; aa = RL(aa, 10); cc = RL(cc + F3(dd, ee, aa) + X[6] + unchecked((int)0x6d703ef3), 6) + bb; ee = RL(ee, 10); bb = RL(bb + F3(cc, dd, ee) + X[9] + unchecked((int)0x6d703ef3), 14) + aa; dd = RL(dd, 10); aa = RL(aa + F3(bb, cc, dd) + X[11] + unchecked((int)0x6d703ef3), 12) + ee; cc = RL(cc, 10); ee = RL(ee + F3(aa, bb, cc) + X[8] + unchecked((int)0x6d703ef3), 13) + dd; bb = RL(bb, 10); dd = RL(dd + F3(ee, aa, bb) + X[12] + unchecked((int)0x6d703ef3), 5) + cc; aa = RL(aa, 10); cc = RL(cc + F3(dd, ee, aa) + X[2] + unchecked((int)0x6d703ef3), 14) + bb; ee = RL(ee, 10); bb = RL(bb + F3(cc, dd, ee) + X[10] + unchecked((int)0x6d703ef3), 13) + aa; dd = RL(dd, 10); aa = RL(aa + F3(bb, cc, dd) + X[0] + unchecked((int)0x6d703ef3), 13) + ee; cc = RL(cc, 10); ee = RL(ee + F3(aa, bb, cc) + X[4] + unchecked((int)0x6d703ef3), 7) + dd; bb = RL(bb, 10); dd = RL(dd + F3(ee, aa, bb) + X[13] + unchecked((int)0x6d703ef3), 5) + cc; aa = RL(aa, 10); // // Rounds 48-63 // // left c = RL(c + F4(d, e, a) + X[1] + unchecked((int)0x8f1bbcdc), 11) + b; e = RL(e, 10); b = RL(b + F4(c, d, e) + X[9] + unchecked((int)0x8f1bbcdc), 12) + a; d = RL(d, 10); a = RL(a + F4(b, c, d) + X[11] + unchecked((int)0x8f1bbcdc), 14) + e; c = RL(c, 10); e = RL(e + F4(a, b, c) + X[10] + unchecked((int)0x8f1bbcdc), 15) + d; b = RL(b, 10); d = RL(d + F4(e, a, b) + X[0] + unchecked((int)0x8f1bbcdc), 14) + c; a = RL(a, 10); c = RL(c + F4(d, e, a) + X[8] + unchecked((int)0x8f1bbcdc), 15) + b; e = RL(e, 10); b = RL(b + F4(c, d, e) + X[12] + unchecked((int)0x8f1bbcdc), 9) + a; d = RL(d, 10); a = RL(a + F4(b, c, d) + X[4] + unchecked((int)0x8f1bbcdc), 8) + e; c = RL(c, 10); e = RL(e + F4(a, b, c) + X[13] + unchecked((int)0x8f1bbcdc), 9) + d; b = RL(b, 10); d = RL(d + F4(e, a, b) + X[3] + unchecked((int)0x8f1bbcdc), 14) + c; a = RL(a, 10); c = RL(c + F4(d, e, a) + X[7] + unchecked((int)0x8f1bbcdc), 5) + b; e = RL(e, 10); b = RL(b + F4(c, d, e) + X[15] + unchecked((int)0x8f1bbcdc), 6) + a; d = RL(d, 10); a = RL(a + F4(b, c, d) + X[14] + unchecked((int)0x8f1bbcdc), 8) + e; c = RL(c, 10); e = RL(e + F4(a, b, c) + X[5] + unchecked((int)0x8f1bbcdc), 6) + d; b = RL(b, 10); d = RL(d + F4(e, a, b) + X[6] + unchecked((int)0x8f1bbcdc), 5) + c; a = RL(a, 10); c = RL(c + F4(d, e, a) + X[2] + unchecked((int)0x8f1bbcdc), 12) + b; e = RL(e, 10); // right cc = RL(cc + F2(dd, ee, aa) + X[8] + unchecked((int)0x7a6d76e9), 15) + bb; ee = RL(ee, 10); bb = RL(bb + F2(cc, dd, ee) + X[6] + unchecked((int)0x7a6d76e9), 5) + aa; dd = RL(dd, 10); aa = RL(aa + F2(bb, cc, dd) + X[4] + unchecked((int)0x7a6d76e9), 8) + ee; cc = RL(cc, 10); ee = RL(ee + F2(aa, bb, cc) + X[1] + unchecked((int)0x7a6d76e9), 11) + dd; bb = RL(bb, 10); dd = RL(dd + F2(ee, aa, bb) + X[3] + unchecked((int)0x7a6d76e9), 14) + cc; aa = RL(aa, 10); cc = RL(cc + F2(dd, ee, aa) + X[11] + unchecked((int)0x7a6d76e9), 14) + bb; ee = RL(ee, 10); bb = RL(bb + F2(cc, dd, ee) + X[15] + unchecked((int)0x7a6d76e9), 6) + aa; dd = RL(dd, 10); aa = RL(aa + F2(bb, cc, dd) + X[0] + unchecked((int)0x7a6d76e9), 14) + ee; cc = RL(cc, 10); ee = RL(ee + F2(aa, bb, cc) + X[5] + unchecked((int)0x7a6d76e9), 6) + dd; bb = RL(bb, 10); dd = RL(dd + F2(ee, aa, bb) + X[12] + unchecked((int)0x7a6d76e9), 9) + cc; aa = RL(aa, 10); cc = RL(cc + F2(dd, ee, aa) + X[2] + unchecked((int)0x7a6d76e9), 12) + bb; ee = RL(ee, 10); bb = RL(bb + F2(cc, dd, ee) + X[13] + unchecked((int)0x7a6d76e9), 9) + aa; dd = RL(dd, 10); aa = RL(aa + F2(bb, cc, dd) + X[9] + unchecked((int)0x7a6d76e9), 12) + ee; cc = RL(cc, 10); ee = RL(ee + F2(aa, bb, cc) + X[7] + unchecked((int)0x7a6d76e9), 5) + dd; bb = RL(bb, 10); dd = RL(dd + F2(ee, aa, bb) + X[10] + unchecked((int)0x7a6d76e9), 15) + cc; aa = RL(aa, 10); cc = RL(cc + F2(dd, ee, aa) + X[14] + unchecked((int)0x7a6d76e9), 8) + bb; ee = RL(ee, 10); // // Rounds 64-79 // // left b = RL(b + F5(c, d, e) + X[4] + unchecked((int)0xa953fd4e), 9) + a; d = RL(d, 10); a = RL(a + F5(b, c, d) + X[0] + unchecked((int)0xa953fd4e), 15) + e; c = RL(c, 10); e = RL(e + F5(a, b, c) + X[5] + unchecked((int)0xa953fd4e), 5) + d; b = RL(b, 10); d = RL(d + F5(e, a, b) + X[9] + unchecked((int)0xa953fd4e), 11) + c; a = RL(a, 10); c = RL(c + F5(d, e, a) + X[7] + unchecked((int)0xa953fd4e), 6) + b; e = RL(e, 10); b = RL(b + F5(c, d, e) + X[12] + unchecked((int)0xa953fd4e), 8) + a; d = RL(d, 10); a = RL(a + F5(b, c, d) + X[2] + unchecked((int)0xa953fd4e), 13) + e; c = RL(c, 10); e = RL(e + F5(a, b, c) + X[10] + unchecked((int)0xa953fd4e), 12) + d; b = RL(b, 10); d = RL(d + F5(e, a, b) + X[14] + unchecked((int)0xa953fd4e), 5) + c; a = RL(a, 10); c = RL(c + F5(d, e, a) + X[1] + unchecked((int)0xa953fd4e), 12) + b; e = RL(e, 10); b = RL(b + F5(c, d, e) + X[3] + unchecked((int)0xa953fd4e), 13) + a; d = RL(d, 10); a = RL(a + F5(b, c, d) + X[8] + unchecked((int)0xa953fd4e), 14) + e; c = RL(c, 10); e = RL(e + F5(a, b, c) + X[11] + unchecked((int)0xa953fd4e), 11) + d; b = RL(b, 10); d = RL(d + F5(e, a, b) + X[6] + unchecked((int)0xa953fd4e), 8) + c; a = RL(a, 10); c = RL(c + F5(d, e, a) + X[15] + unchecked((int)0xa953fd4e), 5) + b; e = RL(e, 10); b = RL(b + F5(c, d, e) + X[13] + unchecked((int)0xa953fd4e), 6) + a; d = RL(d, 10); // right bb = RL(bb + F1(cc, dd, ee) + X[12], 8) + aa; dd = RL(dd, 10); aa = RL(aa + F1(bb, cc, dd) + X[15], 5) + ee; cc = RL(cc, 10); ee = RL(ee + F1(aa, bb, cc) + X[10], 12) + dd; bb = RL(bb, 10); dd = RL(dd + F1(ee, aa, bb) + X[4], 9) + cc; aa = RL(aa, 10); cc = RL(cc + F1(dd, ee, aa) + X[1], 12) + bb; ee = RL(ee, 10); bb = RL(bb + F1(cc, dd, ee) + X[5], 5) + aa; dd = RL(dd, 10); aa = RL(aa + F1(bb, cc, dd) + X[8], 14) + ee; cc = RL(cc, 10); ee = RL(ee + F1(aa, bb, cc) + X[7], 6) + dd; bb = RL(bb, 10); dd = RL(dd + F1(ee, aa, bb) + X[6], 8) + cc; aa = RL(aa, 10); cc = RL(cc + F1(dd, ee, aa) + X[2], 13) + bb; ee = RL(ee, 10); bb = RL(bb + F1(cc, dd, ee) + X[13], 6) + aa; dd = RL(dd, 10); aa = RL(aa + F1(bb, cc, dd) + X[14], 5) + ee; cc = RL(cc, 10); ee = RL(ee + F1(aa, bb, cc) + X[0], 15) + dd; bb = RL(bb, 10); dd = RL(dd + F1(ee, aa, bb) + X[3], 13) + cc; aa = RL(aa, 10); cc = RL(cc + F1(dd, ee, aa) + X[9], 11) + bb; ee = RL(ee, 10); bb = RL(bb + F1(cc, dd, ee) + X[11], 11) + aa; dd = RL(dd, 10); dd += c + H1; H1 = H2 + d + ee; H2 = H3 + e + aa; H3 = H4 + a + bb; H4 = H0 + b + cc; H0 = dd; // // reset the offset and clean out the word buffer. // xOff = 0; for(int i = 0; i != X.Length; i++) { X[i] = 0; } } public override IMemoable Copy() { return new RipeMD160Digest(this); } public override void Reset(IMemoable other) { RipeMD160Digest d = (RipeMD160Digest)other; CopyIn(d); } } }
//-- This is generated content, don't modify this file! using Flunity; using UnityEngine; namespace FlashBundles { public class SceneBundle : ContentBundle { public static readonly MovieClipResource McJack = new MovieClipResource("SceneBundle/McJack"); public static readonly MovieClipResource McJackJump = new MovieClipResource("SceneBundle/McJackJump"); public static readonly MovieClipResource McJackLight = new MovieClipResource("SceneBundle/McJackLight"); public static readonly MovieClipResource McJackRun = new MovieClipResource("SceneBundle/McJackRun"); public static readonly MovieClipResource McJackRunGo = new MovieClipResource("SceneBundle/McJackRunGo"); public static readonly MovieClipResource McLight = new MovieClipResource("SceneBundle/McLight"); public static readonly MovieClipResource McDemo_Animation = new MovieClipResource("SceneBundle/McDemo_Animation"); public static readonly MovieClipResource McDemo_TouchAndTween = new MovieClipResource("SceneBundle/McDemo_TouchAndTween"); public static readonly SpriteResource circle_sprite = new SpriteResource("SceneBundle/circle_sprite"); public static readonly FontResource default_font = new FontResource("SceneBundle/default_font"); public static readonly SpriteResource mcBody = new SpriteResource("SceneBundle/mcBody"); public static readonly SpriteResource mcEye = new SpriteResource("SceneBundle/mcEye"); public static readonly SpriteResource mcFootElement1 = new SpriteResource("SceneBundle/mcFootElement1"); public static readonly SpriteResource mcFootElement2 = new SpriteResource("SceneBundle/mcFootElement2"); public static readonly SpriteResource mcHeand = new SpriteResource("SceneBundle/mcHeand"); public static readonly SpriteResource mcLightElement = new SpriteResource("SceneBundle/mcLightElement"); public static readonly SpriteResource mcMouth = new SpriteResource("SceneBundle/mcMouth"); public static readonly SpriteResource mcShadow = new SpriteResource("SceneBundle/mcShadow"); public static readonly SceneBundle instance = new SceneBundle(); private SceneBundle() {} } public class McJack : MovieClip { protected override DisplayObject[] ConstructInstances() { var instances = new DisplayObject[14]; instances[0] = new FlashSprite(SceneBundle.mcHeand); instances[1] = new FlashSprite(SceneBundle.mcFootElement2); instances[2] = new FlashSprite(SceneBundle.mcFootElement2); instances[3] = new FlashSprite(SceneBundle.mcFootElement1); instances[4] = new FlashSprite(SceneBundle.mcFootElement2); instances[5] = new FlashSprite(SceneBundle.mcBody); instances[6] = new FlashSprite(SceneBundle.mcEye); instances[7] = new FlashSprite(SceneBundle.mcHeand); instances[8] = new FlashSprite(SceneBundle.mcFootElement2); instances[9] = new FlashSprite(SceneBundle.mcFootElement2); instances[10] = new FlashSprite(SceneBundle.mcFootElement1); instances[11] = new FlashSprite(SceneBundle.mcFootElement2); instances[12] = new FlashSprite(SceneBundle.mcMouth); instances[13] = new FlashSprite(SceneBundle.mcShadow); return instances; } public McJack() : base(SceneBundle.McJack) {} public McJack(DisplayContainer parent) : this() { this.parent = parent; } } public class McJackJump : MovieClip { protected override DisplayObject[] ConstructInstances() { var instances = new DisplayObject[14]; instances[0] = new FlashSprite(SceneBundle.mcShadow); instances[1] = new FlashSprite(SceneBundle.mcHeand); instances[2] = new FlashSprite(SceneBundle.mcFootElement2); instances[3] = new FlashSprite(SceneBundle.mcFootElement2); instances[4] = new FlashSprite(SceneBundle.mcFootElement1); instances[5] = new FlashSprite(SceneBundle.mcFootElement2); instances[6] = new FlashSprite(SceneBundle.mcBody); instances[7] = new FlashSprite(SceneBundle.mcEye); instances[8] = new FlashSprite(SceneBundle.mcHeand); instances[9] = new FlashSprite(SceneBundle.mcFootElement2); instances[10] = new FlashSprite(SceneBundle.mcFootElement2); instances[11] = new FlashSprite(SceneBundle.mcFootElement1); instances[12] = new FlashSprite(SceneBundle.mcFootElement2); instances[13] = new FlashSprite(SceneBundle.mcMouth); return instances; } public McJackJump() : base(SceneBundle.McJackJump) {} public McJackJump(DisplayContainer parent) : this() { this.parent = parent; } } public class McJackLight : MovieClip { protected override DisplayObject[] ConstructInstances() { var instances = new DisplayObject[15]; instances[0] = new FlashSprite(SceneBundle.mcHeand); instances[1] = new FlashSprite(SceneBundle.mcFootElement2); instances[2] = new FlashSprite(SceneBundle.mcFootElement2); instances[3] = new FlashSprite(SceneBundle.mcFootElement1); instances[4] = new FlashSprite(SceneBundle.mcFootElement2); instances[5] = new FlashSprite(SceneBundle.mcBody); instances[6] = new FlashSprite(SceneBundle.mcEye); instances[7] = new FlashSprite(SceneBundle.mcHeand); instances[8] = new FlashSprite(SceneBundle.mcFootElement2); instances[9] = new FlashSprite(SceneBundle.mcFootElement2); instances[10] = new FlashSprite(SceneBundle.mcFootElement1); instances[11] = new FlashSprite(SceneBundle.mcFootElement2); instances[12] = new FlashSprite(SceneBundle.mcMouth); instances[13] = new FlashSprite(SceneBundle.mcShadow); instances[14] = new McLight(); return instances; } public McJackLight() : base(SceneBundle.McJackLight) {} public McJackLight(DisplayContainer parent) : this() { this.parent = parent; } } public class McJackRun : MovieClip { protected override DisplayObject[] ConstructInstances() { var instances = new DisplayObject[14]; instances[0] = new FlashSprite(SceneBundle.mcShadow); instances[1] = new FlashSprite(SceneBundle.mcHeand); instances[2] = new FlashSprite(SceneBundle.mcFootElement2); instances[3] = new FlashSprite(SceneBundle.mcFootElement2); instances[4] = new FlashSprite(SceneBundle.mcFootElement1); instances[5] = new FlashSprite(SceneBundle.mcFootElement2); instances[6] = new FlashSprite(SceneBundle.mcBody); instances[7] = new FlashSprite(SceneBundle.mcEye); instances[8] = new FlashSprite(SceneBundle.mcHeand); instances[9] = new FlashSprite(SceneBundle.mcFootElement2); instances[10] = new FlashSprite(SceneBundle.mcFootElement2); instances[11] = new FlashSprite(SceneBundle.mcFootElement1); instances[12] = new FlashSprite(SceneBundle.mcFootElement2); instances[13] = new FlashSprite(SceneBundle.mcMouth); return instances; } public McJackRun() : base(SceneBundle.McJackRun) {} public McJackRun(DisplayContainer parent) : this() { this.parent = parent; } } public class McJackRunGo : MovieClip { protected override DisplayObject[] ConstructInstances() { var instances = new DisplayObject[1]; instances[0] = new McJackRun(); return instances; } public McJackRunGo() : base(SceneBundle.McJackRunGo) {} public McJackRunGo(DisplayContainer parent) : this() { this.parent = parent; } } public class McLight : MovieClip { protected override DisplayObject[] ConstructInstances() { var instances = new DisplayObject[3]; instances[0] = new FlashSprite(SceneBundle.mcLightElement); instances[1] = new FlashSprite(SceneBundle.mcLightElement); instances[2] = new FlashSprite(SceneBundle.mcLightElement); return instances; } public McLight() : base(SceneBundle.McLight) {} public McLight(DisplayContainer parent) : this() { this.parent = parent; } } public class McDemo_Animation : MovieClip { protected override DisplayObject[] ConstructInstances() { var instances = new DisplayObject[9]; instances[0] = new TextField("Arial", 24) { text = "Flash animation\n", textColor = new Color32(255, 255, 204, 255), hAlignment = HAlign.CENTER, size = new Vector2(944f, 30f), shadowColor = new Color32(0, 51, 102, 255), shadowOffset = new Vector2(1f, 1f), }; instances[1] = new McJack(); instances[2] = new McJackLight(); instances[3] = new McJackJump(); instances[4] = new McJackRunGo(); instances[5] = new McJackRunGo(); instances[6] = new McJack(); instances[7] = new McJackLight(); instances[8] = new McJackJump(); return instances; } public McDemo_Animation() : base(SceneBundle.McDemo_Animation) {} public McDemo_Animation(DisplayContainer parent) : this() { this.parent = parent; } } public class McDemo_TouchAndTween : MovieClip { protected override DisplayObject[] ConstructInstances() { var instances = new DisplayObject[6]; instances[0] = new TextField("Arial", 24) { text = "Tween animation: touch to activate\n", textColor = new Color32(255, 255, 204, 255), hAlignment = HAlign.CENTER, size = new Vector2(944f, 30f), shadowColor = new Color32(0, 51, 102, 255), shadowOffset = new Vector2(1f, 1f), }; instances[1] = new FlashSprite(SceneBundle.circle_sprite); instances[2] = new FlashSprite(SceneBundle.circle_sprite); instances[3] = new FlashSprite(SceneBundle.circle_sprite); instances[4] = new FlashSprite(SceneBundle.circle_sprite); instances[5] = new FlashSprite(SceneBundle.circle_sprite); return instances; } public McDemo_TouchAndTween() : base(SceneBundle.McDemo_TouchAndTween) {} public McDemo_TouchAndTween(DisplayContainer parent) : this() { this.parent = parent; } } }
// 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. // ------------------------------------------------------------------------------ // Changes to this file must follow the http://aka.ms/api-review process. // ------------------------------------------------------------------------------ namespace System.Management { public enum AuthenticationLevel { Unchanged = -1, Default = 0, None = 1, Connect = 2, Call = 3, Packet = 4, PacketIntegrity = 5, PacketPrivacy = 6, } public enum CimType { None = 0, SInt16 = 2, SInt32 = 3, Real32 = 4, Real64 = 5, String = 8, Boolean = 11, Object = 13, SInt8 = 16, UInt8 = 17, UInt16 = 18, UInt32 = 19, SInt64 = 20, UInt64 = 21, DateTime = 101, Reference = 102, Char16 = 103, } public enum CodeLanguage { CSharp = 0, JScript = 1, VB = 2, VJSharp = 3, Mcpp = 4, } [System.FlagsAttribute] public enum ComparisonSettings { IncludeAll = 0, IgnoreQualifiers = 1, IgnoreObjectSource = 2, IgnoreDefaultValues = 4, IgnoreClass = 8, IgnoreCase = 16, IgnoreFlavor = 32, } public partial class CompletedEventArgs : System.Management.ManagementEventArgs { internal CompletedEventArgs() { } public System.Management.ManagementStatus Status { get { throw null; } } public System.Management.ManagementBaseObject StatusObject { get { throw null; } } } public delegate void CompletedEventHandler(object sender, System.Management.CompletedEventArgs e); public partial class ConnectionOptions : System.Management.ManagementOptions { public ConnectionOptions() { } public ConnectionOptions(string locale, string username, System.Security.SecureString password, string authority, System.Management.ImpersonationLevel impersonation, System.Management.AuthenticationLevel authentication, bool enablePrivileges, System.Management.ManagementNamedValueCollection context, System.TimeSpan timeout) { } public ConnectionOptions(string locale, string username, string password, string authority, System.Management.ImpersonationLevel impersonation, System.Management.AuthenticationLevel authentication, bool enablePrivileges, System.Management.ManagementNamedValueCollection context, System.TimeSpan timeout) { } public System.Management.AuthenticationLevel Authentication { get { throw null; } set { } } public string Authority { get { throw null; } set { } } public bool EnablePrivileges { get { throw null; } set { } } public System.Management.ImpersonationLevel Impersonation { get { throw null; } set { } } public string Locale { get { throw null; } set { } } public string Password { set { } } public System.Security.SecureString SecurePassword { set { } } public string Username { get { throw null; } set { } } public override object Clone() { throw null; } } public partial class DeleteOptions : System.Management.ManagementOptions { public DeleteOptions() { } public DeleteOptions(System.Management.ManagementNamedValueCollection context, System.TimeSpan timeout) { } public override object Clone() { throw null; } } public partial class EnumerationOptions : System.Management.ManagementOptions { public EnumerationOptions() { } public EnumerationOptions(System.Management.ManagementNamedValueCollection context, System.TimeSpan timeout, int blockSize, bool rewindable, bool returnImmediatley, bool useAmendedQualifiers, bool ensureLocatable, bool prototypeOnly, bool directRead, bool enumerateDeep) { } public int BlockSize { get { throw null; } set { } } public bool DirectRead { get { throw null; } set { } } public bool EnsureLocatable { get { throw null; } set { } } public bool EnumerateDeep { get { throw null; } set { } } public bool PrototypeOnly { get { throw null; } set { } } public bool ReturnImmediately { get { throw null; } set { } } public bool Rewindable { get { throw null; } set { } } public bool UseAmendedQualifiers { get { throw null; } set { } } public override object Clone() { throw null; } } public partial class EventArrivedEventArgs : System.Management.ManagementEventArgs { internal EventArrivedEventArgs() { } public System.Management.ManagementBaseObject NewEvent { get { throw null; } } } public delegate void EventArrivedEventHandler(object sender, System.Management.EventArrivedEventArgs e); public partial class EventQuery : System.Management.ManagementQuery { public EventQuery() { } public EventQuery(string query) { } public EventQuery(string language, string query) { } public override object Clone() { throw null; } } public partial class EventWatcherOptions : System.Management.ManagementOptions { public EventWatcherOptions() { } public EventWatcherOptions(System.Management.ManagementNamedValueCollection context, System.TimeSpan timeout, int blockSize) { } public int BlockSize { get { throw null; } set { } } public override object Clone() { throw null; } } public enum ImpersonationLevel { Default = 0, Anonymous = 1, Identify = 2, Impersonate = 3, Delegate = 4, } public partial class InvokeMethodOptions : System.Management.ManagementOptions { public InvokeMethodOptions() { } public InvokeMethodOptions(System.Management.ManagementNamedValueCollection context, System.TimeSpan timeout) { } public override object Clone() { throw null; } } [System.ComponentModel.ToolboxItemAttribute(false)] public partial class ManagementBaseObject : System.ComponentModel.Component, System.ICloneable, System.Runtime.Serialization.ISerializable { protected ManagementBaseObject(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public virtual System.Management.ManagementPath ClassPath { get { throw null; } } public object this[string propertyName] { get { throw null; } set { } } public virtual System.Management.PropertyDataCollection Properties { get { throw null; } } public virtual System.Management.QualifierDataCollection Qualifiers { get { throw null; } } public virtual System.Management.PropertyDataCollection SystemProperties { get { throw null; } } public virtual object Clone() { throw null; } public bool CompareTo(System.Management.ManagementBaseObject otherObject, System.Management.ComparisonSettings settings) { throw null; } public new void Dispose() { } public override bool Equals(object obj) { throw null; } public override int GetHashCode() { throw null; } protected virtual void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public object GetPropertyQualifierValue(string propertyName, string qualifierName) { throw null; } public object GetPropertyValue(string propertyName) { throw null; } public object GetQualifierValue(string qualifierName) { throw null; } public string GetText(System.Management.TextFormat format) { throw null; } public static explicit operator System.IntPtr (System.Management.ManagementBaseObject managementObject) { throw null; } public void SetPropertyQualifierValue(string propertyName, string qualifierName, object qualifierValue) { } public void SetPropertyValue(string propertyName, object propertyValue) { } public void SetQualifierValue(string qualifierName, object qualifierValue) { } void System.Runtime.Serialization.ISerializable.GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } } public partial class ManagementClass : System.Management.ManagementObject { public ManagementClass() { } public ManagementClass(System.Management.ManagementPath path) { } public ManagementClass(System.Management.ManagementPath path, System.Management.ObjectGetOptions options) { } public ManagementClass(System.Management.ManagementScope scope, System.Management.ManagementPath path, System.Management.ObjectGetOptions options) { } protected ManagementClass(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public ManagementClass(string path) { } public ManagementClass(string path, System.Management.ObjectGetOptions options) { } public ManagementClass(string scope, string path, System.Management.ObjectGetOptions options) { } public System.Collections.Specialized.StringCollection Derivation { get { throw null; } } public System.Management.MethodDataCollection Methods { get { throw null; } } public override System.Management.ManagementPath Path { get { throw null; } set { } } public override object Clone() { throw null; } public System.Management.ManagementObject CreateInstance() { throw null; } public System.Management.ManagementClass Derive(string newClassName) { throw null; } public System.Management.ManagementObjectCollection GetInstances() { throw null; } public System.Management.ManagementObjectCollection GetInstances(System.Management.EnumerationOptions options) { throw null; } public void GetInstances(System.Management.ManagementOperationObserver watcher) { } public void GetInstances(System.Management.ManagementOperationObserver watcher, System.Management.EnumerationOptions options) { } protected override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public System.Management.ManagementObjectCollection GetRelatedClasses() { throw null; } public void GetRelatedClasses(System.Management.ManagementOperationObserver watcher) { } public void GetRelatedClasses(System.Management.ManagementOperationObserver watcher, string relatedClass) { } public void GetRelatedClasses(System.Management.ManagementOperationObserver watcher, string relatedClass, string relationshipClass, string relationshipQualifier, string relatedQualifier, string relatedRole, string thisRole, System.Management.EnumerationOptions options) { } public System.Management.ManagementObjectCollection GetRelatedClasses(string relatedClass) { throw null; } public System.Management.ManagementObjectCollection GetRelatedClasses(string relatedClass, string relationshipClass, string relationshipQualifier, string relatedQualifier, string relatedRole, string thisRole, System.Management.EnumerationOptions options) { throw null; } public System.Management.ManagementObjectCollection GetRelationshipClasses() { throw null; } public void GetRelationshipClasses(System.Management.ManagementOperationObserver watcher) { } public void GetRelationshipClasses(System.Management.ManagementOperationObserver watcher, string relationshipClass) { } public void GetRelationshipClasses(System.Management.ManagementOperationObserver watcher, string relationshipClass, string relationshipQualifier, string thisRole, System.Management.EnumerationOptions options) { } public System.Management.ManagementObjectCollection GetRelationshipClasses(string relationshipClass) { throw null; } public System.Management.ManagementObjectCollection GetRelationshipClasses(string relationshipClass, string relationshipQualifier, string thisRole, System.Management.EnumerationOptions options) { throw null; } public System.CodeDom.CodeTypeDeclaration GetStronglyTypedClassCode(bool includeSystemClassInClassDef, bool systemPropertyClass) { throw null; } public bool GetStronglyTypedClassCode(System.Management.CodeLanguage lang, string filePath, string classNamespace) { throw null; } public System.Management.ManagementObjectCollection GetSubclasses() { throw null; } public System.Management.ManagementObjectCollection GetSubclasses(System.Management.EnumerationOptions options) { throw null; } public void GetSubclasses(System.Management.ManagementOperationObserver watcher) { } public void GetSubclasses(System.Management.ManagementOperationObserver watcher, System.Management.EnumerationOptions options) { } } public sealed partial class ManagementDateTimeConverter { internal ManagementDateTimeConverter() { } public static System.DateTime ToDateTime(string dmtfDate) { throw null; } public static string ToDmtfDateTime(System.DateTime date) { throw null; } public static string ToDmtfTimeInterval(System.TimeSpan timespan) { throw null; } public static System.TimeSpan ToTimeSpan(string dmtfTimespan) { throw null; } } public abstract partial class ManagementEventArgs : System.EventArgs { internal ManagementEventArgs() { } public object Context { get { throw null; } } } [System.ComponentModel.ToolboxItemAttribute(false)] public partial class ManagementEventWatcher : System.ComponentModel.Component { public ManagementEventWatcher() { } public ManagementEventWatcher(System.Management.EventQuery query) { } public ManagementEventWatcher(System.Management.ManagementScope scope, System.Management.EventQuery query) { } public ManagementEventWatcher(System.Management.ManagementScope scope, System.Management.EventQuery query, System.Management.EventWatcherOptions options) { } public ManagementEventWatcher(string query) { } public ManagementEventWatcher(string scope, string query) { } public ManagementEventWatcher(string scope, string query, System.Management.EventWatcherOptions options) { } public System.Management.EventWatcherOptions Options { get { throw null; } set { } } public System.Management.EventQuery Query { get { throw null; } set { } } public System.Management.ManagementScope Scope { get { throw null; } set { } } public event System.Management.EventArrivedEventHandler EventArrived { add { } remove { } } public event System.Management.StoppedEventHandler Stopped { add { } remove { } } ~ManagementEventWatcher() { } public void Start() { } public void Stop() { } public System.Management.ManagementBaseObject WaitForNextEvent() { throw null; } } public partial class ManagementException : System.SystemException { public ManagementException() { } protected ManagementException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public ManagementException(string message) { } public ManagementException(string message, System.Exception innerException) { } public System.Management.ManagementStatus ErrorCode { get { throw null; } } public System.Management.ManagementBaseObject ErrorInformation { get { throw null; } } public override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } } public partial class ManagementNamedValueCollection : System.Collections.Specialized.NameObjectCollectionBase { public ManagementNamedValueCollection() { } protected ManagementNamedValueCollection(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public object this[string name] { get { throw null; } } public void Add(string name, object value) { } public System.Management.ManagementNamedValueCollection Clone() { throw null; } public void Remove(string name) { } public void RemoveAll() { } } public partial class ManagementObject : System.Management.ManagementBaseObject, System.ICloneable { public ManagementObject() : base (default(System.Runtime.Serialization.SerializationInfo), default(System.Runtime.Serialization.StreamingContext)) { } public ManagementObject(System.Management.ManagementPath path) : base (default(System.Runtime.Serialization.SerializationInfo), default(System.Runtime.Serialization.StreamingContext)) { } public ManagementObject(System.Management.ManagementPath path, System.Management.ObjectGetOptions options) : base (default(System.Runtime.Serialization.SerializationInfo), default(System.Runtime.Serialization.StreamingContext)) { } public ManagementObject(System.Management.ManagementScope scope, System.Management.ManagementPath path, System.Management.ObjectGetOptions options) : base (default(System.Runtime.Serialization.SerializationInfo), default(System.Runtime.Serialization.StreamingContext)) { } protected ManagementObject(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base (default(System.Runtime.Serialization.SerializationInfo), default(System.Runtime.Serialization.StreamingContext)) { } public ManagementObject(string path) : base (default(System.Runtime.Serialization.SerializationInfo), default(System.Runtime.Serialization.StreamingContext)) { } public ManagementObject(string path, System.Management.ObjectGetOptions options) : base (default(System.Runtime.Serialization.SerializationInfo), default(System.Runtime.Serialization.StreamingContext)) { } public ManagementObject(string scopeString, string pathString, System.Management.ObjectGetOptions options) : base (default(System.Runtime.Serialization.SerializationInfo), default(System.Runtime.Serialization.StreamingContext)) { } public override System.Management.ManagementPath ClassPath { get { throw null; } } public System.Management.ObjectGetOptions Options { get { throw null; } set { } } public virtual System.Management.ManagementPath Path { get { throw null; } set { } } public System.Management.ManagementScope Scope { get { throw null; } set { } } public override object Clone() { throw null; } public void CopyTo(System.Management.ManagementOperationObserver watcher, System.Management.ManagementPath path) { } public void CopyTo(System.Management.ManagementOperationObserver watcher, System.Management.ManagementPath path, System.Management.PutOptions options) { } public void CopyTo(System.Management.ManagementOperationObserver watcher, string path) { } public void CopyTo(System.Management.ManagementOperationObserver watcher, string path, System.Management.PutOptions options) { } public System.Management.ManagementPath CopyTo(System.Management.ManagementPath path) { throw null; } public System.Management.ManagementPath CopyTo(System.Management.ManagementPath path, System.Management.PutOptions options) { throw null; } public System.Management.ManagementPath CopyTo(string path) { throw null; } public System.Management.ManagementPath CopyTo(string path, System.Management.PutOptions options) { throw null; } public void Delete() { } public void Delete(System.Management.DeleteOptions options) { } public void Delete(System.Management.ManagementOperationObserver watcher) { } public void Delete(System.Management.ManagementOperationObserver watcher, System.Management.DeleteOptions options) { } public new void Dispose() { } public void Get() { } public void Get(System.Management.ManagementOperationObserver watcher) { } public System.Management.ManagementBaseObject GetMethodParameters(string methodName) { throw null; } protected override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public System.Management.ManagementObjectCollection GetRelated() { throw null; } public void GetRelated(System.Management.ManagementOperationObserver watcher) { } public void GetRelated(System.Management.ManagementOperationObserver watcher, string relatedClass) { } public void GetRelated(System.Management.ManagementOperationObserver watcher, string relatedClass, string relationshipClass, string relationshipQualifier, string relatedQualifier, string relatedRole, string thisRole, bool classDefinitionsOnly, System.Management.EnumerationOptions options) { } public System.Management.ManagementObjectCollection GetRelated(string relatedClass) { throw null; } public System.Management.ManagementObjectCollection GetRelated(string relatedClass, string relationshipClass, string relationshipQualifier, string relatedQualifier, string relatedRole, string thisRole, bool classDefinitionsOnly, System.Management.EnumerationOptions options) { throw null; } public System.Management.ManagementObjectCollection GetRelationships() { throw null; } public void GetRelationships(System.Management.ManagementOperationObserver watcher) { } public void GetRelationships(System.Management.ManagementOperationObserver watcher, string relationshipClass) { } public void GetRelationships(System.Management.ManagementOperationObserver watcher, string relationshipClass, string relationshipQualifier, string thisRole, bool classDefinitionsOnly, System.Management.EnumerationOptions options) { } public System.Management.ManagementObjectCollection GetRelationships(string relationshipClass) { throw null; } public System.Management.ManagementObjectCollection GetRelationships(string relationshipClass, string relationshipQualifier, string thisRole, bool classDefinitionsOnly, System.Management.EnumerationOptions options) { throw null; } public void InvokeMethod(System.Management.ManagementOperationObserver watcher, string methodName, System.Management.ManagementBaseObject inParameters, System.Management.InvokeMethodOptions options) { } public void InvokeMethod(System.Management.ManagementOperationObserver watcher, string methodName, object[] args) { } public System.Management.ManagementBaseObject InvokeMethod(string methodName, System.Management.ManagementBaseObject inParameters, System.Management.InvokeMethodOptions options) { throw null; } public object InvokeMethod(string methodName, object[] args) { throw null; } public System.Management.ManagementPath Put() { throw null; } public void Put(System.Management.ManagementOperationObserver watcher) { } public void Put(System.Management.ManagementOperationObserver watcher, System.Management.PutOptions options) { } public System.Management.ManagementPath Put(System.Management.PutOptions options) { throw null; } public override string ToString() { throw null; } } public partial class ManagementObjectCollection : System.Collections.ICollection, System.Collections.IEnumerable, System.IDisposable { internal ManagementObjectCollection() { } public int Count { get { throw null; } } public bool IsSynchronized { get { throw null; } } public object SyncRoot { get { throw null; } } public void CopyTo(System.Array array, int index) { } public void CopyTo(System.Management.ManagementBaseObject[] objectCollection, int index) { } public void Dispose() { } ~ManagementObjectCollection() { } public System.Management.ManagementObjectCollection.ManagementObjectEnumerator GetEnumerator() { throw null; } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } public partial class ManagementObjectEnumerator : System.Collections.IEnumerator, System.IDisposable { internal ManagementObjectEnumerator() { } public System.Management.ManagementBaseObject Current { get { throw null; } } object System.Collections.IEnumerator.Current { get { throw null; } } public void Dispose() { } ~ManagementObjectEnumerator() { } public bool MoveNext() { throw null; } public void Reset() { } } } [System.ComponentModel.ToolboxItemAttribute(false)] public partial class ManagementObjectSearcher : System.ComponentModel.Component { public ManagementObjectSearcher() { } public ManagementObjectSearcher(System.Management.ManagementScope scope, System.Management.ObjectQuery query) { } public ManagementObjectSearcher(System.Management.ManagementScope scope, System.Management.ObjectQuery query, System.Management.EnumerationOptions options) { } public ManagementObjectSearcher(System.Management.ObjectQuery query) { } public ManagementObjectSearcher(string queryString) { } public ManagementObjectSearcher(string scope, string queryString) { } public ManagementObjectSearcher(string scope, string queryString, System.Management.EnumerationOptions options) { } public System.Management.EnumerationOptions Options { get { throw null; } set { } } public System.Management.ObjectQuery Query { get { throw null; } set { } } public System.Management.ManagementScope Scope { get { throw null; } set { } } public System.Management.ManagementObjectCollection Get() { throw null; } public void Get(System.Management.ManagementOperationObserver watcher) { } } public partial class ManagementOperationObserver { public ManagementOperationObserver() { } public event System.Management.CompletedEventHandler Completed { add { } remove { } } public event System.Management.ObjectPutEventHandler ObjectPut { add { } remove { } } public event System.Management.ObjectReadyEventHandler ObjectReady { add { } remove { } } public event System.Management.ProgressEventHandler Progress { add { } remove { } } public void Cancel() { } } [System.ComponentModel.TypeConverterAttribute(typeof(System.ComponentModel.ExpandableObjectConverter))] public abstract partial class ManagementOptions : System.ICloneable { internal ManagementOptions() { } public static readonly System.TimeSpan InfiniteTimeout; public System.Management.ManagementNamedValueCollection Context { get { throw null; } set { } } public System.TimeSpan Timeout { get { throw null; } set { } } public abstract object Clone(); } public partial class ManagementPath : System.ICloneable { public ManagementPath() { } public ManagementPath(string path) { } [System.ComponentModel.RefreshPropertiesAttribute(System.ComponentModel.RefreshProperties.All)] public string ClassName { get { throw null; } set { } } public static System.Management.ManagementPath DefaultPath { get { throw null; } set { } } public bool IsClass { get { throw null; } } public bool IsInstance { get { throw null; } } public bool IsSingleton { get { throw null; } } [System.ComponentModel.RefreshPropertiesAttribute(System.ComponentModel.RefreshProperties.All)] public string NamespacePath { get { throw null; } set { } } [System.ComponentModel.RefreshPropertiesAttribute(System.ComponentModel.RefreshProperties.All)] public string Path { get { throw null; } set { } } [System.ComponentModel.RefreshPropertiesAttribute(System.ComponentModel.RefreshProperties.All)] public string RelativePath { get { throw null; } set { } } [System.ComponentModel.RefreshPropertiesAttribute(System.ComponentModel.RefreshProperties.All)] public string Server { get { throw null; } set { } } public System.Management.ManagementPath Clone() { throw null; } public void SetAsClass() { } public void SetAsSingleton() { } object System.ICloneable.Clone() { throw null; } public override string ToString() { throw null; } } public abstract partial class ManagementQuery : System.ICloneable { internal ManagementQuery() { } public virtual string QueryLanguage { get { throw null; } set { } } public virtual string QueryString { get { throw null; } set { } } public abstract object Clone(); protected internal virtual void ParseQuery(string query) { } } public partial class ManagementScope : System.ICloneable { public ManagementScope() { } public ManagementScope(System.Management.ManagementPath path) { } public ManagementScope(System.Management.ManagementPath path, System.Management.ConnectionOptions options) { } public ManagementScope(string path) { } public ManagementScope(string path, System.Management.ConnectionOptions options) { } public bool IsConnected { get { throw null; } } public System.Management.ConnectionOptions Options { get { throw null; } set { } } public System.Management.ManagementPath Path { get { throw null; } set { } } public System.Management.ManagementScope Clone() { throw null; } public void Connect() { } object System.ICloneable.Clone() { throw null; } } public enum ManagementStatus { Failed = -2147217407, NotFound = -2147217406, AccessDenied = -2147217405, ProviderFailure = -2147217404, TypeMismatch = -2147217403, OutOfMemory = -2147217402, InvalidContext = -2147217401, InvalidParameter = -2147217400, NotAvailable = -2147217399, CriticalError = -2147217398, InvalidStream = -2147217397, NotSupported = -2147217396, InvalidSuperclass = -2147217395, InvalidNamespace = -2147217394, InvalidObject = -2147217393, InvalidClass = -2147217392, ProviderNotFound = -2147217391, InvalidProviderRegistration = -2147217390, ProviderLoadFailure = -2147217389, InitializationFailure = -2147217388, TransportFailure = -2147217387, InvalidOperation = -2147217386, InvalidQuery = -2147217385, InvalidQueryType = -2147217384, AlreadyExists = -2147217383, OverrideNotAllowed = -2147217382, PropagatedQualifier = -2147217381, PropagatedProperty = -2147217380, Unexpected = -2147217379, IllegalOperation = -2147217378, CannotBeKey = -2147217377, IncompleteClass = -2147217376, InvalidSyntax = -2147217375, NondecoratedObject = -2147217374, ReadOnly = -2147217373, ProviderNotCapable = -2147217372, ClassHasChildren = -2147217371, ClassHasInstances = -2147217370, QueryNotImplemented = -2147217369, IllegalNull = -2147217368, InvalidQualifierType = -2147217367, InvalidPropertyType = -2147217366, ValueOutOfRange = -2147217365, CannotBeSingleton = -2147217364, InvalidCimType = -2147217363, InvalidMethod = -2147217362, InvalidMethodParameters = -2147217361, SystemProperty = -2147217360, InvalidProperty = -2147217359, CallCanceled = -2147217358, ShuttingDown = -2147217357, PropagatedMethod = -2147217356, UnsupportedParameter = -2147217355, MissingParameterID = -2147217354, InvalidParameterID = -2147217353, NonconsecutiveParameterIDs = -2147217352, ParameterIDOnRetval = -2147217351, InvalidObjectPath = -2147217350, OutOfDiskSpace = -2147217349, BufferTooSmall = -2147217348, UnsupportedPutExtension = -2147217347, UnknownObjectType = -2147217346, UnknownPacketType = -2147217345, MarshalVersionMismatch = -2147217344, MarshalInvalidSignature = -2147217343, InvalidQualifier = -2147217342, InvalidDuplicateParameter = -2147217341, TooMuchData = -2147217340, ServerTooBusy = -2147217339, InvalidFlavor = -2147217338, CircularReference = -2147217337, UnsupportedClassUpdate = -2147217336, CannotChangeKeyInheritance = -2147217335, CannotChangeIndexInheritance = -2147217328, TooManyProperties = -2147217327, UpdateTypeMismatch = -2147217326, UpdateOverrideNotAllowed = -2147217325, UpdatePropagatedMethod = -2147217324, MethodNotImplemented = -2147217323, MethodDisabled = -2147217322, RefresherBusy = -2147217321, UnparsableQuery = -2147217320, NotEventClass = -2147217319, MissingGroupWithin = -2147217318, MissingAggregationList = -2147217317, PropertyNotAnObject = -2147217316, AggregatingByObject = -2147217315, UninterpretableProviderQuery = -2147217313, BackupRestoreWinmgmtRunning = -2147217312, QueueOverflow = -2147217311, PrivilegeNotHeld = -2147217310, InvalidOperator = -2147217309, LocalCredentials = -2147217308, CannotBeAbstract = -2147217307, AmendedObject = -2147217306, ClientTooSlow = -2147217305, RegistrationTooBroad = -2147213311, RegistrationTooPrecise = -2147213310, NoError = 0, False = 1, ResetToDefault = 262146, Different = 262147, Timedout = 262148, NoMoreData = 262149, OperationCanceled = 262150, Pending = 262151, DuplicateObjects = 262152, PartialResults = 262160, } public partial class MethodData { internal MethodData() { } public System.Management.ManagementBaseObject InParameters { get { throw null; } } public string Name { get { throw null; } } public string Origin { get { throw null; } } public System.Management.ManagementBaseObject OutParameters { get { throw null; } } public System.Management.QualifierDataCollection Qualifiers { get { throw null; } } } public partial class MethodDataCollection : System.Collections.ICollection, System.Collections.IEnumerable { internal MethodDataCollection() { } public int Count { get { throw null; } } public bool IsSynchronized { get { throw null; } } public virtual System.Management.MethodData this[string methodName] { get { throw null; } } public object SyncRoot { get { throw null; } } public virtual void Add(string methodName) { } public virtual void Add(string methodName, System.Management.ManagementBaseObject inParameters, System.Management.ManagementBaseObject outParameters) { } public void CopyTo(System.Array array, int index) { } public void CopyTo(System.Management.MethodData[] methodArray, int index) { } public System.Management.MethodDataCollection.MethodDataEnumerator GetEnumerator() { throw null; } public virtual void Remove(string methodName) { } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } public partial class MethodDataEnumerator : System.Collections.IEnumerator { internal MethodDataEnumerator() { } public System.Management.MethodData Current { get { throw null; } } object System.Collections.IEnumerator.Current { get { throw null; } } public bool MoveNext() { throw null; } public void Reset() { } } } public partial class ObjectGetOptions : System.Management.ManagementOptions { public ObjectGetOptions() { } public ObjectGetOptions(System.Management.ManagementNamedValueCollection context) { } public ObjectGetOptions(System.Management.ManagementNamedValueCollection context, System.TimeSpan timeout, bool useAmendedQualifiers) { } public bool UseAmendedQualifiers { get { throw null; } set { } } public override object Clone() { throw null; } } public partial class ObjectPutEventArgs : System.Management.ManagementEventArgs { internal ObjectPutEventArgs() { } public System.Management.ManagementPath Path { get { throw null; } } } public delegate void ObjectPutEventHandler(object sender, System.Management.ObjectPutEventArgs e); public partial class ObjectQuery : System.Management.ManagementQuery { public ObjectQuery() { } public ObjectQuery(string query) { } public ObjectQuery(string language, string query) { } public override object Clone() { throw null; } } public partial class ObjectReadyEventArgs : System.Management.ManagementEventArgs { internal ObjectReadyEventArgs() { } public System.Management.ManagementBaseObject NewObject { get { throw null; } } } public delegate void ObjectReadyEventHandler(object sender, System.Management.ObjectReadyEventArgs e); public partial class ProgressEventArgs : System.Management.ManagementEventArgs { internal ProgressEventArgs() { } public int Current { get { throw null; } } public string Message { get { throw null; } } public int UpperBound { get { throw null; } } } public delegate void ProgressEventHandler(object sender, System.Management.ProgressEventArgs e); public partial class PropertyData { internal PropertyData() { } public bool IsArray { get { throw null; } } public bool IsLocal { get { throw null; } } public string Name { get { throw null; } } public string Origin { get { throw null; } } public System.Management.QualifierDataCollection Qualifiers { get { throw null; } } public System.Management.CimType Type { get { throw null; } } public object Value { get { throw null; } set { } } } public partial class PropertyDataCollection : System.Collections.ICollection, System.Collections.IEnumerable { internal PropertyDataCollection() { } public int Count { get { throw null; } } public bool IsSynchronized { get { throw null; } } public virtual System.Management.PropertyData this[string propertyName] { get { throw null; } } public object SyncRoot { get { throw null; } } public void Add(string propertyName, System.Management.CimType propertyType, bool isArray) { } public virtual void Add(string propertyName, object propertyValue) { } public void Add(string propertyName, object propertyValue, System.Management.CimType propertyType) { } public void CopyTo(System.Array array, int index) { } public void CopyTo(System.Management.PropertyData[] propertyArray, int index) { } public System.Management.PropertyDataCollection.PropertyDataEnumerator GetEnumerator() { throw null; } public virtual void Remove(string propertyName) { } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } public partial class PropertyDataEnumerator : System.Collections.IEnumerator { internal PropertyDataEnumerator() { } public System.Management.PropertyData Current { get { throw null; } } object System.Collections.IEnumerator.Current { get { throw null; } } public bool MoveNext() { throw null; } public void Reset() { } } } public partial class PutOptions : System.Management.ManagementOptions { public PutOptions() { } public PutOptions(System.Management.ManagementNamedValueCollection context) { } public PutOptions(System.Management.ManagementNamedValueCollection context, System.TimeSpan timeout, bool useAmendedQualifiers, System.Management.PutType putType) { } public System.Management.PutType Type { get { throw null; } set { } } public bool UseAmendedQualifiers { get { throw null; } set { } } public override object Clone() { throw null; } } public enum PutType { None = 0, UpdateOnly = 1, CreateOnly = 2, UpdateOrCreate = 3, } public partial class QualifierData { internal QualifierData() { } public bool IsAmended { get { throw null; } set { } } public bool IsLocal { get { throw null; } } public bool IsOverridable { get { throw null; } set { } } public string Name { get { throw null; } } public bool PropagatesToInstance { get { throw null; } set { } } public bool PropagatesToSubclass { get { throw null; } set { } } public object Value { get { throw null; } set { } } } public partial class QualifierDataCollection : System.Collections.ICollection, System.Collections.IEnumerable { internal QualifierDataCollection() { } public int Count { get { throw null; } } public bool IsSynchronized { get { throw null; } } public virtual System.Management.QualifierData this[string qualifierName] { get { throw null; } } public object SyncRoot { get { throw null; } } public virtual void Add(string qualifierName, object qualifierValue) { } public virtual void Add(string qualifierName, object qualifierValue, bool isAmended, bool propagatesToInstance, bool propagatesToSubclass, bool isOverridable) { } public void CopyTo(System.Array array, int index) { } public void CopyTo(System.Management.QualifierData[] qualifierArray, int index) { } public System.Management.QualifierDataCollection.QualifierDataEnumerator GetEnumerator() { throw null; } public virtual void Remove(string qualifierName) { } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } public partial class QualifierDataEnumerator : System.Collections.IEnumerator { internal QualifierDataEnumerator() { } public System.Management.QualifierData Current { get { throw null; } } object System.Collections.IEnumerator.Current { get { throw null; } } public bool MoveNext() { throw null; } public void Reset() { } } } public partial class RelatedObjectQuery : System.Management.WqlObjectQuery { public RelatedObjectQuery() { } public RelatedObjectQuery(bool isSchemaQuery, string sourceObject, string relatedClass, string relationshipClass, string relatedQualifier, string relationshipQualifier, string relatedRole, string thisRole) { } public RelatedObjectQuery(string queryOrSourceObject) { } public RelatedObjectQuery(string sourceObject, string relatedClass) { } public RelatedObjectQuery(string sourceObject, string relatedClass, string relationshipClass, string relatedQualifier, string relationshipQualifier, string relatedRole, string thisRole, bool classDefinitionsOnly) { } public bool ClassDefinitionsOnly { get { throw null; } set { } } public bool IsSchemaQuery { get { throw null; } set { } } public string RelatedClass { get { throw null; } set { } } public string RelatedQualifier { get { throw null; } set { } } public string RelatedRole { get { throw null; } set { } } public string RelationshipClass { get { throw null; } set { } } public string RelationshipQualifier { get { throw null; } set { } } public string SourceObject { get { throw null; } set { } } public string ThisRole { get { throw null; } set { } } protected internal void BuildQuery() { } public override object Clone() { throw null; } protected internal override void ParseQuery(string query) { } } public partial class RelationshipQuery : System.Management.WqlObjectQuery { public RelationshipQuery() { } public RelationshipQuery(bool isSchemaQuery, string sourceObject, string relationshipClass, string relationshipQualifier, string thisRole) { } public RelationshipQuery(string queryOrSourceObject) { } public RelationshipQuery(string sourceObject, string relationshipClass) { } public RelationshipQuery(string sourceObject, string relationshipClass, string relationshipQualifier, string thisRole, bool classDefinitionsOnly) { } public bool ClassDefinitionsOnly { get { throw null; } set { } } public bool IsSchemaQuery { get { throw null; } set { } } public string RelationshipClass { get { throw null; } set { } } public string RelationshipQualifier { get { throw null; } set { } } public string SourceObject { get { throw null; } set { } } public string ThisRole { get { throw null; } set { } } protected internal void BuildQuery() { } public override object Clone() { throw null; } protected internal override void ParseQuery(string query) { } } public partial class SelectQuery : System.Management.WqlObjectQuery { public SelectQuery() { } public SelectQuery(bool isSchemaQuery, string condition) { } public SelectQuery(string queryOrClassName) { } public SelectQuery(string className, string condition) { } public SelectQuery(string className, string condition, string[] selectedProperties) { } public string ClassName { get { throw null; } set { } } public string Condition { get { throw null; } set { } } public bool IsSchemaQuery { get { throw null; } set { } } public override string QueryString { get { throw null; } set { } } public System.Collections.Specialized.StringCollection SelectedProperties { get { throw null; } set { } } protected internal void BuildQuery() { } public override object Clone() { throw null; } protected internal override void ParseQuery(string query) { } } public partial class StoppedEventArgs : System.Management.ManagementEventArgs { internal StoppedEventArgs() { } public System.Management.ManagementStatus Status { get { throw null; } } } public delegate void StoppedEventHandler(object sender, System.Management.StoppedEventArgs e); public enum TextFormat { Mof = 0, CimDtd20 = 1, WmiDtd20 = 2, } public partial class WqlEventQuery : System.Management.EventQuery { public WqlEventQuery() { } public WqlEventQuery(string queryOrEventClassName) { } public WqlEventQuery(string eventClassName, string condition) { } public WqlEventQuery(string eventClassName, string condition, System.TimeSpan groupWithinInterval) { } public WqlEventQuery(string eventClassName, string condition, System.TimeSpan groupWithinInterval, string[] groupByPropertyList) { } public WqlEventQuery(string eventClassName, System.TimeSpan withinInterval) { } public WqlEventQuery(string eventClassName, System.TimeSpan withinInterval, string condition) { } public WqlEventQuery(string eventClassName, System.TimeSpan withinInterval, string condition, System.TimeSpan groupWithinInterval, string[] groupByPropertyList, string havingCondition) { } public string Condition { get { throw null; } set { } } public string EventClassName { get { throw null; } set { } } public System.Collections.Specialized.StringCollection GroupByPropertyList { get { throw null; } set { } } public System.TimeSpan GroupWithinInterval { get { throw null; } set { } } public string HavingCondition { get { throw null; } set { } } public override string QueryLanguage { get { throw null; } } public override string QueryString { get { throw null; } set { } } public System.TimeSpan WithinInterval { get { throw null; } set { } } protected internal void BuildQuery() { } public override object Clone() { throw null; } protected internal override void ParseQuery(string query) { } } public partial class WqlObjectQuery : System.Management.ObjectQuery { public WqlObjectQuery() { } public WqlObjectQuery(string query) { } public override string QueryLanguage { get { throw null; } } public override object Clone() { throw null; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.ObjectModel; using System.IdentityModel.Configuration; using System.IdentityModel.Tokens; using System.ServiceModel; using System.Xml; namespace System.IdentityModel.Selectors { public abstract class SecurityTokenResolver : ICustomIdentityConfiguration { public SecurityToken ResolveToken(SecurityKeyIdentifier keyIdentifier) { if (keyIdentifier == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("keyIdentifier"); } SecurityToken token; if (!this.TryResolveTokenCore(keyIdentifier, out token)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new InvalidOperationException(SR.Format(SR.UnableToResolveTokenReference, keyIdentifier))); } return token; } public bool TryResolveToken(SecurityKeyIdentifier keyIdentifier, out SecurityToken token) { if (keyIdentifier == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("keyIdentifier"); } return TryResolveTokenCore(keyIdentifier, out token); } public SecurityToken ResolveToken(SecurityKeyIdentifierClause keyIdentifierClause) { if (keyIdentifierClause == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("keyIdentifierClause"); } SecurityToken token; if (!this.TryResolveTokenCore(keyIdentifierClause, out token)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new InvalidOperationException(SR.Format(SR.UnableToResolveTokenReference, keyIdentifierClause))); } return token; } public bool TryResolveToken(SecurityKeyIdentifierClause keyIdentifierClause, out SecurityToken token) { if (keyIdentifierClause == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("keyIdentifierClause"); } return this.TryResolveTokenCore(keyIdentifierClause, out token); } public SecurityKey ResolveSecurityKey(SecurityKeyIdentifierClause keyIdentifierClause) { if (keyIdentifierClause == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("keyIdentifierClause"); } SecurityKey key; if (!this.TryResolveSecurityKeyCore(keyIdentifierClause, out key)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new InvalidOperationException(SR.Format(SR.UnableToResolveKeyReference, keyIdentifierClause))); } return key; } public bool TryResolveSecurityKey(SecurityKeyIdentifierClause keyIdentifierClause, out SecurityKey key) { if (keyIdentifierClause == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("keyIdentifierClause"); } return this.TryResolveSecurityKeyCore(keyIdentifierClause, out key); } /// <summary> /// Load custom configuration from Xml /// </summary> /// <param name="nodelist">Custom configuration elements</param> public virtual void LoadCustomConfiguration(XmlNodeList nodelist) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(NotImplemented.ByDesignWithMessage(SR.Format(SR.ID0023, this.GetType().AssemblyQualifiedName))); } // protected methods protected abstract bool TryResolveTokenCore(SecurityKeyIdentifier keyIdentifier, out SecurityToken token); protected abstract bool TryResolveTokenCore(SecurityKeyIdentifierClause keyIdentifierClause, out SecurityToken token); protected abstract bool TryResolveSecurityKeyCore(SecurityKeyIdentifierClause keyIdentifierClause, out SecurityKey key); public static SecurityTokenResolver CreateDefaultSecurityTokenResolver(ReadOnlyCollection<SecurityToken> tokens, bool canMatchLocalId) { return new SimpleTokenResolver(tokens, canMatchLocalId); } private class SimpleTokenResolver : SecurityTokenResolver { private ReadOnlyCollection<SecurityToken> _tokens; private bool _canMatchLocalId; public SimpleTokenResolver(ReadOnlyCollection<SecurityToken> tokens, bool canMatchLocalId) { if (tokens == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("tokens"); _tokens = tokens; _canMatchLocalId = canMatchLocalId; } protected override bool TryResolveSecurityKeyCore(SecurityKeyIdentifierClause keyIdentifierClause, out SecurityKey key) { if (keyIdentifierClause == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("keyIdentifierClause"); key = null; for (int i = 0; i < _tokens.Count; ++i) { SecurityKey securityKey = _tokens[i].ResolveKeyIdentifierClause(keyIdentifierClause); if (securityKey != null) { key = securityKey; return true; } } if (keyIdentifierClause is EncryptedKeyIdentifierClause) { EncryptedKeyIdentifierClause keyClause = (EncryptedKeyIdentifierClause)keyIdentifierClause; SecurityKeyIdentifier keyIdentifier = keyClause.EncryptingKeyIdentifier; if (keyIdentifier != null && keyIdentifier.Count > 0) { for (int i = 0; i < keyIdentifier.Count; i++) { SecurityKey unwrappingSecurityKey = null; if (TryResolveSecurityKey(keyIdentifier[i], out unwrappingSecurityKey)) { byte[] wrappedKey = keyClause.GetEncryptedKey(); string wrappingAlgorithm = keyClause.EncryptionMethod; byte[] unwrappedKey = unwrappingSecurityKey.DecryptKey(wrappingAlgorithm, wrappedKey); key = new InMemorySymmetricSecurityKey(unwrappedKey, false); return true; } } } } return key != null; } protected override bool TryResolveTokenCore(SecurityKeyIdentifier keyIdentifier, out SecurityToken token) { if (keyIdentifier == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("keyIdentifier"); token = null; for (int i = 0; i < keyIdentifier.Count; ++i) { SecurityToken securityToken = ResolveSecurityToken(keyIdentifier[i]); if (securityToken != null) { token = securityToken; break; } } return (token != null); } protected override bool TryResolveTokenCore(SecurityKeyIdentifierClause keyIdentifierClause, out SecurityToken token) { if (keyIdentifierClause == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("keyIdentifierClause"); token = null; SecurityToken securityToken = ResolveSecurityToken(keyIdentifierClause); if (securityToken != null) token = securityToken; return (token != null); } private SecurityToken ResolveSecurityToken(SecurityKeyIdentifierClause keyIdentifierClause) { if (keyIdentifierClause == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("keyIdentifierClause"); if (!_canMatchLocalId && keyIdentifierClause is LocalIdKeyIdentifierClause) return null; for (int i = 0; i < _tokens.Count; ++i) { if (_tokens[i].MatchesKeyIdentifierClause(keyIdentifierClause)) return _tokens[i]; } return null; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.Win32.SafeHandles; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Security; using System.Text; using System.Threading; namespace System.Diagnostics { public partial class Process : IDisposable { private static readonly UTF8Encoding s_utf8NoBom = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false); private static volatile bool s_sigchildHandlerRegistered = false; private static readonly object s_sigchildGate = new object(); private static readonly Interop.Sys.SigChldCallback s_sigChildHandler = OnSigChild; private static readonly ReaderWriterLockSlim s_processStartLock = new ReaderWriterLockSlim(); /// <summary> /// Puts a Process component in state to interact with operating system processes that run in a /// special mode by enabling the native property SeDebugPrivilege on the current thread. /// </summary> public static void EnterDebugMode() { // Nop. } /// <summary> /// Takes a Process component out of the state that lets it interact with operating system processes /// that run in a special mode. /// </summary> public static void LeaveDebugMode() { // Nop. } [CLSCompliant(false)] public static Process Start(string fileName, string userName, SecureString password, string domain) { throw new PlatformNotSupportedException(SR.ProcessStartWithPasswordAndDomainNotSupported); } [CLSCompliant(false)] public static Process Start(string fileName, string arguments, string userName, SecureString password, string domain) { throw new PlatformNotSupportedException(SR.ProcessStartWithPasswordAndDomainNotSupported); } /// <summary>Terminates the associated process immediately.</summary> public void Kill() { EnsureState(State.HaveNonExitedId); if (Interop.Sys.Kill(_processId, Interop.Sys.Signals.SIGKILL) != 0) { throw new Win32Exception(); // same exception as on Windows } } private IEnumerable<Exception> KillTree() { List<Exception> exceptions = null; KillTree(ref exceptions); return exceptions ?? Enumerable.Empty<Exception>(); } private void KillTree(ref List<Exception> exceptions) { // If the process has exited, we can no longer determine its children. if (HasExited) { return; } // Stop the process, so it won't start additional children. // This is best effort: kill can return before the process is stopped. int stopResult = Interop.Sys.Kill(_processId, Interop.Sys.Signals.SIGSTOP); if (stopResult != 0) { Interop.Error error = Interop.Sys.GetLastError(); // Ignore 'process no longer exists' error. if (error != Interop.Error.ESRCH) { AddException(ref exceptions, new Win32Exception()); } return; } IReadOnlyList<Process> children = GetChildProcesses(); int killResult = Interop.Sys.Kill(_processId, Interop.Sys.Signals.SIGKILL); if (killResult != 0) { Interop.Error error = Interop.Sys.GetLastError(); // Ignore 'process no longer exists' error. if (error != Interop.Error.ESRCH) { AddException(ref exceptions, new Win32Exception()); } } foreach (Process childProcess in children) { childProcess.KillTree(ref exceptions); childProcess.Dispose(); } void AddException(ref List<Exception> list, Exception e) { if (list == null) { list = new List<Exception>(); } list.Add(e); } } /// <summary>Discards any information about the associated process.</summary> private void RefreshCore() { // Nop. No additional state to reset. } /// <summary>Additional logic invoked when the Process is closed.</summary> private void CloseCore() { if (_waitStateHolder != null) { _waitStateHolder.Dispose(); _waitStateHolder = null; } } /// <summary>Additional configuration when a process ID is set.</summary> partial void ConfigureAfterProcessIdSet() { // Make sure that we configure the wait state holder for this process object, which we can only do once we have a process ID. Debug.Assert(_haveProcessId, $"{nameof(ConfigureAfterProcessIdSet)} should only be called once a process ID is set"); // Initialize WaitStateHolder for non-child processes GetWaitState(); } /// <devdoc> /// Make sure we are watching for a process exit. /// </devdoc> /// <internalonly/> private void EnsureWatchingForExit() { if (!_watchingForExit) { lock (this) { if (!_watchingForExit) { Debug.Assert(_haveProcessHandle, "Process.EnsureWatchingForExit called with no process handle"); Debug.Assert(Associated, "Process.EnsureWatchingForExit called with no associated process"); _watchingForExit = true; try { _waitHandle = new ProcessWaitHandle(GetWaitState()); _registeredWaitHandle = ThreadPool.RegisterWaitForSingleObject(_waitHandle, new WaitOrTimerCallback(CompletionCallback), _waitHandle, -1, true); } catch { _waitHandle?.Dispose(); _waitHandle = null; _watchingForExit = false; throw; } } } } } /// <summary> /// Instructs the Process component to wait the specified number of milliseconds for the associated process to exit. /// </summary> private bool WaitForExitCore(int milliseconds) { bool exited = GetWaitState().WaitForExit(milliseconds); Debug.Assert(exited || milliseconds != Timeout.Infinite); if (exited && milliseconds == Timeout.Infinite) // if we have a hard timeout, we cannot wait for the streams { if (_output != null) { _output.WaitUtilEOF(); } if (_error != null) { _error.WaitUtilEOF(); } } return exited; } /// <summary>Gets the main module for the associated process.</summary> public ProcessModule MainModule { get { ProcessModuleCollection pmc = Modules; return pmc.Count > 0 ? pmc[0] : null; } } /// <summary>Checks whether the process has exited and updates state accordingly.</summary> private void UpdateHasExited() { int? exitCode; _exited = GetWaitState().GetExited(out exitCode, refresh: true); if (_exited && exitCode != null) { _exitCode = exitCode.Value; } } /// <summary>Gets the time that the associated process exited.</summary> private DateTime ExitTimeCore { get { return GetWaitState().ExitTime; } } /// <summary> /// Gets or sets a value indicating whether the associated process priority /// should be temporarily boosted by the operating system when the main window /// has focus. /// </summary> private bool PriorityBoostEnabledCore { get { return false; } //Nop set { } // Nop } /// <summary> /// Gets or sets the overall priority category for the associated process. /// </summary> private ProcessPriorityClass PriorityClassCore { // This mapping is relatively arbitrary. 0 is normal based on the man page, // and the other values above and below are simply distributed evenly. get { EnsureState(State.HaveNonExitedId); int pri = 0; int errno = Interop.Sys.GetPriority(Interop.Sys.PriorityWhich.PRIO_PROCESS, _processId, out pri); if (errno != 0) // Interop.Sys.GetPriority returns GetLastWin32Error() { throw new Win32Exception(errno); // match Windows exception } Debug.Assert(pri >= -20 && pri <= 20); return pri < -15 ? ProcessPriorityClass.RealTime : pri < -10 ? ProcessPriorityClass.High : pri < -5 ? ProcessPriorityClass.AboveNormal : pri == 0 ? ProcessPriorityClass.Normal : pri <= 10 ? ProcessPriorityClass.BelowNormal : ProcessPriorityClass.Idle; } set { EnsureState(State.HaveNonExitedId); int pri = 0; // Normal switch (value) { case ProcessPriorityClass.RealTime: pri = -19; break; case ProcessPriorityClass.High: pri = -11; break; case ProcessPriorityClass.AboveNormal: pri = -6; break; case ProcessPriorityClass.BelowNormal: pri = 10; break; case ProcessPriorityClass.Idle: pri = 19; break; default: Debug.Assert(value == ProcessPriorityClass.Normal, "Input should have been validated by caller"); break; } int result = Interop.Sys.SetPriority(Interop.Sys.PriorityWhich.PRIO_PROCESS, _processId, pri); if (result == -1) { throw new Win32Exception(); // match Windows exception } } } /// <summary>Gets the ID of the current process.</summary> private static int GetCurrentProcessId() { return Interop.Sys.GetPid(); } /// <summary>Checks whether the argument is a direct child of this process.</summary> private bool IsParentOf(Process possibleChildProcess) => Id == possibleChildProcess.ParentProcessId; private bool Equals(Process process) => Id == process.Id; partial void ThrowIfExited(bool refresh) { // Don't allocate a ProcessWaitState.Holder unless we're refreshing. if (_waitStateHolder == null && !refresh) { return; } if (GetWaitState().GetExited(out _, refresh)) { throw new InvalidOperationException(SR.Format(SR.ProcessHasExited, _processId.ToString())); } } /// <summary> /// Gets a short-term handle to the process, with the given access. If a handle exists, /// then it is reused. If the process has exited, it throws an exception. /// </summary> private SafeProcessHandle GetProcessHandle() { if (_haveProcessHandle) { ThrowIfExited(refresh: true); return _processHandle; } EnsureState(State.HaveNonExitedId | State.IsLocal); return new SafeProcessHandle(_processId); } /// <summary> /// Starts the process using the supplied start info. /// With UseShellExecute option, we'll try the shell tools to launch it(e.g. "open fileName") /// </summary> /// <param name="startInfo">The start info with which to start the process.</param> private bool StartCore(ProcessStartInfo startInfo) { EnsureSigChildHandler(); string filename; string[] argv; if (startInfo.UseShellExecute) { if (startInfo.RedirectStandardInput || startInfo.RedirectStandardOutput || startInfo.RedirectStandardError) { throw new InvalidOperationException(SR.CantRedirectStreams); } } int stdinFd = -1, stdoutFd = -1, stderrFd = -1; string[] envp = CreateEnvp(startInfo); string cwd = !string.IsNullOrWhiteSpace(startInfo.WorkingDirectory) ? startInfo.WorkingDirectory : null; bool setCredentials = !string.IsNullOrEmpty(startInfo.UserName); uint userId = 0; uint groupId = 0; uint[] groups = null; if (setCredentials) { (userId, groupId, groups) = GetUserAndGroupIds(startInfo); } if (startInfo.UseShellExecute) { string verb = startInfo.Verb; if (verb != string.Empty && !string.Equals(verb, "open", StringComparison.OrdinalIgnoreCase)) { throw new Win32Exception(Interop.Errors.ERROR_NO_ASSOCIATION); } // On Windows, UseShellExecute of executables and scripts causes those files to be executed. // To achieve this on Unix, we check if the file is executable (x-bit). // Some files may have the x-bit set even when they are not executable. This happens for example // when a Windows filesystem is mounted on Linux. To handle that, treat it as a regular file // when exec returns ENOEXEC (file format cannot be executed). bool isExecuting = false; filename = ResolveExecutableForShellExecute(startInfo.FileName, cwd); if (filename != null) { argv = ParseArgv(startInfo); isExecuting = ForkAndExecProcess(filename, argv, envp, cwd, startInfo.RedirectStandardInput, startInfo.RedirectStandardOutput, startInfo.RedirectStandardError, setCredentials, userId, groupId, groups, out stdinFd, out stdoutFd, out stderrFd, throwOnNoExec: false); // return false instead of throwing on ENOEXEC } // use default program to open file/url if (!isExecuting) { filename = GetPathToOpenFile(); argv = ParseArgv(startInfo, filename, ignoreArguments: true); ForkAndExecProcess(filename, argv, envp, cwd, startInfo.RedirectStandardInput, startInfo.RedirectStandardOutput, startInfo.RedirectStandardError, setCredentials, userId, groupId, groups, out stdinFd, out stdoutFd, out stderrFd); } } else { filename = ResolvePath(startInfo.FileName); argv = ParseArgv(startInfo); if (Directory.Exists(filename)) { throw new Win32Exception(SR.DirectoryNotValidAsInput); } ForkAndExecProcess(filename, argv, envp, cwd, startInfo.RedirectStandardInput, startInfo.RedirectStandardOutput, startInfo.RedirectStandardError, setCredentials, userId, groupId, groups, out stdinFd, out stdoutFd, out stderrFd); } // Configure the parent's ends of the redirection streams. // We use UTF8 encoding without BOM by-default(instead of Console encoding as on Windows) // as there is no good way to get this information from the native layer // and we do not want to take dependency on Console contract. if (startInfo.RedirectStandardInput) { Debug.Assert(stdinFd >= 0); _standardInput = new StreamWriter(OpenStream(stdinFd, FileAccess.Write), startInfo.StandardInputEncoding ?? s_utf8NoBom, StreamBufferSize) { AutoFlush = true }; } if (startInfo.RedirectStandardOutput) { Debug.Assert(stdoutFd >= 0); _standardOutput = new StreamReader(OpenStream(stdoutFd, FileAccess.Read), startInfo.StandardOutputEncoding ?? s_utf8NoBom, true, StreamBufferSize); } if (startInfo.RedirectStandardError) { Debug.Assert(stderrFd >= 0); _standardError = new StreamReader(OpenStream(stderrFd, FileAccess.Read), startInfo.StandardErrorEncoding ?? s_utf8NoBom, true, StreamBufferSize); } return true; } private bool ForkAndExecProcess( string filename, string[] argv, string[] envp, string cwd, bool redirectStdin, bool redirectStdout, bool redirectStderr, bool setCredentials, uint userId, uint groupId, uint[] groups, out int stdinFd, out int stdoutFd, out int stderrFd, bool throwOnNoExec = true) { if (string.IsNullOrEmpty(filename)) { throw new Win32Exception(Interop.Error.ENOENT.Info().RawErrno); } // Lock to avoid races with OnSigChild // By using a ReaderWriterLock we allow multiple processes to start concurrently. s_processStartLock.EnterReadLock(); try { int childPid; // Invoke the shim fork/execve routine. It will create pipes for all requested // redirects, fork a child process, map the pipe ends onto the appropriate stdin/stdout/stderr // descriptors, and execve to execute the requested process. The shim implementation // is used to fork/execve as executing managed code in a forked process is not safe (only // the calling thread will transfer, thread IDs aren't stable across the fork, etc.) int errno = Interop.Sys.ForkAndExecProcess( filename, argv, envp, cwd, redirectStdin, redirectStdout, redirectStderr, setCredentials, userId, groupId, groups, out childPid, out stdinFd, out stdoutFd, out stderrFd); if (errno == 0) { // Ensure we'll reap this process. // note: SetProcessId will set this if we don't set it first. _waitStateHolder = new ProcessWaitState.Holder(childPid, isNewChild: true); // Store the child's information into this Process object. Debug.Assert(childPid >= 0); SetProcessId(childPid); SetProcessHandle(new SafeProcessHandle(childPid)); return true; } else { if (!throwOnNoExec && new Interop.ErrorInfo(errno).Error == Interop.Error.ENOEXEC) { return false; } throw new Win32Exception(errno); } } finally { s_processStartLock.ExitReadLock(); } } // ----------------------------- // ---- PAL layer ends here ---- // ----------------------------- /// <summary>Finalizable holder for the underlying shared wait state object.</summary> private ProcessWaitState.Holder _waitStateHolder; /// <summary>Size to use for redirect streams and stream readers/writers.</summary> private const int StreamBufferSize = 4096; /// <summary>Converts the filename and arguments information from a ProcessStartInfo into an argv array.</summary> /// <param name="psi">The ProcessStartInfo.</param> /// <param name="resolvedExe">Resolved executable to open ProcessStartInfo.FileName</param> /// <param name="ignoreArguments">Don't pass ProcessStartInfo.Arguments</param> /// <returns>The argv array.</returns> private static string[] ParseArgv(ProcessStartInfo psi, string resolvedExe = null, bool ignoreArguments = false) { if (string.IsNullOrEmpty(resolvedExe) && (ignoreArguments || (string.IsNullOrEmpty(psi.Arguments) && psi.ArgumentList.Count == 0))) { return new string[] { psi.FileName }; } var argvList = new List<string>(); if (!string.IsNullOrEmpty(resolvedExe)) { argvList.Add(resolvedExe); if (resolvedExe.Contains("kfmclient")) { argvList.Add("openURL"); // kfmclient needs OpenURL } } argvList.Add(psi.FileName); if (!ignoreArguments) { if (!string.IsNullOrEmpty(psi.Arguments)) { ParseArgumentsIntoList(psi.Arguments, argvList); } else { argvList.AddRange(psi.ArgumentList); } } return argvList.ToArray(); } /// <summary>Converts the environment variables information from a ProcessStartInfo into an envp array.</summary> /// <param name="psi">The ProcessStartInfo.</param> /// <returns>The envp array.</returns> private static string[] CreateEnvp(ProcessStartInfo psi) { var envp = new string[psi.Environment.Count]; int index = 0; foreach (var pair in psi.Environment) { envp[index++] = pair.Key + "=" + pair.Value; } return envp; } private static string ResolveExecutableForShellExecute(string filename, string workingDirectory) { // Determine if filename points to an executable file. // filename may be an absolute path, a relative path or a uri. string resolvedFilename = null; // filename is an absolute path if (Path.IsPathRooted(filename)) { if (File.Exists(filename)) { resolvedFilename = filename; } } // filename is a uri else if (Uri.TryCreate(filename, UriKind.Absolute, out Uri uri)) { if (uri.IsFile && uri.Host == "" && File.Exists(uri.LocalPath)) { resolvedFilename = uri.LocalPath; } } // filename is relative else { // The WorkingDirectory property specifies the location of the executable. // If WorkingDirectory is an empty string, the current directory is understood to contain the executable. workingDirectory = workingDirectory != null ? Path.GetFullPath(workingDirectory) : Directory.GetCurrentDirectory(); string filenameInWorkingDirectory = Path.Combine(workingDirectory, filename); // filename is a relative path in the working directory if (File.Exists(filenameInWorkingDirectory)) { resolvedFilename = filenameInWorkingDirectory; } // find filename on PATH else { resolvedFilename = FindProgramInPath(filename); } } if (resolvedFilename == null) { return null; } if (Interop.Sys.Access(resolvedFilename, Interop.Sys.AccessMode.X_OK) == 0) { return resolvedFilename; } else { return null; } } /// <summary>Resolves a path to the filename passed to ProcessStartInfo. </summary> /// <param name="filename">The filename.</param> /// <returns>The resolved path. It can return null in case of URLs.</returns> private static string ResolvePath(string filename) { // Follow the same resolution that Windows uses with CreateProcess: // 1. First try the exact path provided // 2. Then try the file relative to the executable directory // 3. Then try the file relative to the current directory // 4. then try the file in each of the directories specified in PATH // Windows does additional Windows-specific steps between 3 and 4, // and we ignore those here. // If the filename is a complete path, use it, regardless of whether it exists. if (Path.IsPathRooted(filename)) { // In this case, it doesn't matter whether the file exists or not; // it's what the caller asked for, so it's what they'll get return filename; } // Then check the executable's directory string path = GetExePath(); if (path != null) { try { path = Path.Combine(Path.GetDirectoryName(path), filename); if (File.Exists(path)) { return path; } } catch (ArgumentException) { } // ignore any errors in data that may come from the exe path } // Then check the current directory path = Path.Combine(Directory.GetCurrentDirectory(), filename); if (File.Exists(path)) { return path; } // Then check each directory listed in the PATH environment variables return FindProgramInPath(filename); } /// <summary> /// Gets the path to the program /// </summary> /// <param name="program"></param> /// <returns></returns> private static string FindProgramInPath(string program) { string path; string pathEnvVar = Environment.GetEnvironmentVariable("PATH"); if (pathEnvVar != null) { var pathParser = new StringParser(pathEnvVar, ':', skipEmpty: true); while (pathParser.MoveNext()) { string subPath = pathParser.ExtractCurrent(); path = Path.Combine(subPath, program); if (File.Exists(path)) { return path; } } } return null; } /// <summary>Convert a number of "jiffies", or ticks, to a TimeSpan.</summary> /// <param name="ticks">The number of ticks.</param> /// <returns>The equivalent TimeSpan.</returns> internal static TimeSpan TicksToTimeSpan(double ticks) { // Look up the number of ticks per second in the system's configuration, // then use that to convert to a TimeSpan long ticksPerSecond = Interop.Sys.SysConf(Interop.Sys.SysConfName._SC_CLK_TCK); if (ticksPerSecond <= 0) { throw new Win32Exception(); } return TimeSpan.FromSeconds(ticks / (double)ticksPerSecond); } /// <summary>Opens a stream around the specified file descriptor and with the specified access.</summary> /// <param name="fd">The file descriptor.</param> /// <param name="access">The access mode.</param> /// <returns>The opened stream.</returns> private static FileStream OpenStream(int fd, FileAccess access) { Debug.Assert(fd >= 0); return new FileStream( new SafeFileHandle((IntPtr)fd, ownsHandle: true), access, StreamBufferSize, isAsync: false); } /// <summary>Parses a command-line argument string into a list of arguments.</summary> /// <param name="arguments">The argument string.</param> /// <param name="results">The list into which the component arguments should be stored.</param> /// <remarks> /// This follows the rules outlined in "Parsing C++ Command-Line Arguments" at /// https://msdn.microsoft.com/en-us/library/17w5ykft.aspx. /// </remarks> private static void ParseArgumentsIntoList(string arguments, List<string> results) { // Iterate through all of the characters in the argument string. for (int i = 0; i < arguments.Length; i++) { while (i < arguments.Length && (arguments[i] == ' ' || arguments[i] == '\t')) i++; if (i == arguments.Length) break; results.Add(GetNextArgument(arguments, ref i)); } } private static string GetNextArgument(string arguments, ref int i) { var currentArgument = StringBuilderCache.Acquire(); bool inQuotes = false; while (i < arguments.Length) { // From the current position, iterate through contiguous backslashes. int backslashCount = 0; while (i < arguments.Length && arguments[i] == '\\') { i++; backslashCount++; } if (backslashCount > 0) { if (i >= arguments.Length || arguments[i] != '"') { // Backslashes not followed by a double quote: // they should all be treated as literal backslashes. currentArgument.Append('\\', backslashCount); } else { // Backslashes followed by a double quote: // - Output a literal slash for each complete pair of slashes // - If one remains, use it to make the subsequent quote a literal. currentArgument.Append('\\', backslashCount / 2); if (backslashCount % 2 != 0) { currentArgument.Append('"'); i++; } } continue; } char c = arguments[i]; // If this is a double quote, track whether we're inside of quotes or not. // Anything within quotes will be treated as a single argument, even if // it contains spaces. if (c == '"') { if (inQuotes && i < arguments.Length - 1 && arguments[i + 1] == '"') { // Two consecutive double quotes inside an inQuotes region should result in a literal double quote // (the parser is left in the inQuotes region). // This behavior is not part of the spec of code:ParseArgumentsIntoList, but is compatible with CRT // and .NET Framework. currentArgument.Append('"'); i++; } else { inQuotes = !inQuotes; } i++; continue; } // If this is a space/tab and we're not in quotes, we're done with the current // argument, it should be added to the results and then reset for the next one. if ((c == ' ' || c == '\t') && !inQuotes) { break; } // Nothing special; add the character to the current argument. currentArgument.Append(c); i++; } return StringBuilderCache.GetStringAndRelease(currentArgument); } /// <summary>Gets the wait state for this Process object.</summary> private ProcessWaitState GetWaitState() { if (_waitStateHolder == null) { EnsureState(State.HaveId); _waitStateHolder = new ProcessWaitState.Holder(_processId); } return _waitStateHolder._state; } private static (uint userId, uint groupId, uint[] groups) GetUserAndGroupIds(ProcessStartInfo startInfo) { Debug.Assert(!string.IsNullOrEmpty(startInfo.UserName)); (uint? userId, uint? groupId) = GetUserAndGroupIds(startInfo.UserName); Debug.Assert(userId.HasValue == groupId.HasValue, "userId and groupId both need to have values, or both need to be null."); if (!userId.HasValue) { throw new Win32Exception(SR.Format(SR.UserDoesNotExist, startInfo.UserName)); } uint[] groups = Interop.Sys.GetGroupList(startInfo.UserName, groupId.Value); if (groups == null) { throw new Win32Exception(SR.Format(SR.UserGroupsCannotBeDetermined, startInfo.UserName)); } return (userId.Value, groupId.Value, groups); } private unsafe static (uint? userId, uint? groupId) GetUserAndGroupIds(string userName) { Interop.Sys.Passwd? passwd; // First try with a buffer that should suffice for 99% of cases. // Note: on CentOS/RedHat 7.1 systems, getpwnam_r returns 'user not found' if the buffer is too small // see https://bugs.centos.org/view.php?id=7324 const int BufLen = Interop.Sys.Passwd.InitialBufferSize; byte* stackBuf = stackalloc byte[BufLen]; if (TryGetPasswd(userName, stackBuf, BufLen, out passwd)) { if (passwd == null) { return (null, null); } return (passwd.Value.UserId, passwd.Value.GroupId); } // Fallback to heap allocations if necessary, growing the buffer until // we succeed. TryGetPasswd will throw if there's an unexpected error. int lastBufLen = BufLen; while (true) { lastBufLen *= 2; byte[] heapBuf = new byte[lastBufLen]; fixed (byte* buf = &heapBuf[0]) { if (TryGetPasswd(userName, buf, heapBuf.Length, out passwd)) { if (passwd == null) { return (null, null); } return (passwd.Value.UserId, passwd.Value.GroupId); } } } } private static unsafe bool TryGetPasswd(string name, byte* buf, int bufLen, out Interop.Sys.Passwd? passwd) { // Call getpwnam_r to get the passwd struct Interop.Sys.Passwd tempPasswd; int error = Interop.Sys.GetPwNamR(name, out tempPasswd, buf, bufLen); // If the call succeeds, give back the passwd retrieved if (error == 0) { passwd = tempPasswd; return true; } // If the current user's entry could not be found, give back null, // but still return true as false indicates the buffer was too small. if (error == -1) { passwd = null; return true; } var errorInfo = new Interop.ErrorInfo(error); // If the call failed because the buffer was too small, return false to // indicate the caller should try again with a larger buffer. if (errorInfo.Error == Interop.Error.ERANGE) { passwd = null; return false; } // Otherwise, fail. throw new Win32Exception(errorInfo.RawErrno, errorInfo.GetErrorMessage()); } public IntPtr MainWindowHandle => IntPtr.Zero; private bool CloseMainWindowCore() => false; public string MainWindowTitle => string.Empty; public bool Responding => true; private bool WaitForInputIdleCore(int milliseconds) => throw new InvalidOperationException(SR.InputIdleUnkownError); private static void EnsureSigChildHandler() { if (s_sigchildHandlerRegistered) { return; } lock (s_sigchildGate) { if (!s_sigchildHandlerRegistered) { // Ensure signal handling is setup and register our callback. if (!Interop.Sys.RegisterForSigChld(s_sigChildHandler)) { throw new Win32Exception(); } s_sigchildHandlerRegistered = true; } } } private static void OnSigChild(bool reapAll) { // Lock to avoid races with Process.Start s_processStartLock.EnterWriteLock(); try { ProcessWaitState.CheckChildren(reapAll); } finally { s_processStartLock.ExitWriteLock(); } } } }
using System; using System.Collections.Generic; using System.IO; using System.Text; using Google.Analytics; using Google.GData.Analytics; using NUnit.Framework; namespace Google.GData.Client.UnitTests.Analytics { /// <summary> ///This is a test class for AccountFeedTest and is intended ///to contain all AccountFeedTest Unit Tests ///</summary> [TestFixture, Category("Analytics")] public class AccountFeedTest { private const string AccountFeedUrl = "https://www.google.com/analytics/feeds/accounts/default"; /// <summary> ///Gets or sets the test context which provides ///information about and functionality for the current test run. ///</summary> public TestContext TestContext { get; set; } private static AccountFeed Parse(string xml) { byte[] bytes = new UTF8Encoding().GetBytes(xml); AccountFeed feed = new AccountFeed(new Uri(AccountFeedUrl), new AnalyticsService("Test")); feed.Parse(new MemoryStream(bytes), AlternativeFormat.Atom); return feed; } /// <summary> ///A test for AccountFeed Constructor ///</summary> [Test] public void AccountFeedConstructorTest() { AccountFeed target = new AccountFeed(null, null); Assert.IsNotNull(target, "better have an object"); Assert.IsNull(target.Service, "better have no service yet"); } [Test] public void AccountParseTest() { string xml = @"<?xml version='1.0' encoding='UTF-8'?> <feed xmlns='http://www.w3.org/2005/Atom' xmlns:gd='http://schemas.google.com/g/2005' gd:etag='W/&quot;D0UFR347eCp8ImA4WxVQE04.&quot;' xmlns:openSearch='http://a9.com/-/spec/opensearch/1.1/' xmlns:dxp='http://schemas.google.com/analytics/2009' xmlns:ga='http://schemas.google.com/ga/2009'> <author> <name>Google Analytics</name> </author> <generator>Google Analytics</generator> <id>http://www.google.com/analytics/feeds/accounts/[email protected]</id> <link href='http://www.google.com/analytics/feeds/accounts/default' rel='self' type='application/atom+xml' /> <title type='text'>Profile list for [email protected]</title> <updated>2009-01-31T01:01:01+10:00</updated> <dxp:segment id='gaid::-1' name='All Visits'> <dxp:definition> </dxp:definition> </dxp:segment> <dxp:segment id='gaid::-2' name='New Visitors'> <dxp:definition>ga:visitorType==New Visitor</dxp:definition> </dxp:segment> <entry gd:etag='W/&quot;D0UAR248eCp4ImA9WxVQE04.&quot;'> <ga:customVariable index='1' name='My Custom Variable' scope='3'/> <ga:customVariable index='2' name='My Seconds Variable' scope='1'/> <dxp:tableId>ga:1234567</dxp:tableId> <dxp:property name='ga:accountId' value='123456' /> <dxp:property name='ga:accountName' value='Test Account' /> <dxp:property name='ga:profileId' value='1234567' /> <dxp:property name='ga:webPropertyId' value='UA-111111-1' /> <title type='text'>www.test.com</title> <id>http://www.google.com/analytics/feeds/accounts/ga:1234567</id> <link href='http://www.google.com/analytics' rel='alternate' type='text/html' /> <content type='text'/> <updated>2009-01-31T01:01:01+10:00</updated> <ga:goal active='true' name='Completing Order' number='1' value='10.0'> <ga:destination caseSensitive='false' expression='/purchaseComplete.html' matchType='regex' step1Required='false'> <ga:step name='View Product Categories' number='1' path='/Apps|Accessories'/> <ga:step name='View Product' number='2' path='/Apps|Accessories/(.*)\.axd'/> <ga:step name='View Shopping Cart' number='3' path='/shoppingcart.aspx'/> <ga:step name='Login' number='4' path='/login.html'/> <ga:step name='Place Order' number='5' path='/placeOrder.html'/> </ga:destination> </ga:goal> <ga:goal active='true' name='Browsed my site over 5 minutes' number='2' value='0.0'> <ga:engagement comparison='&gt;' thresholdValue='300' type='timeOnSite'/> </ga:goal> <ga:goal active='true' name='Visited &gt; 4 pages' number='3' value='0.25'> <ga:engagement comparison='&gt;' thresholdValue='4' type='pagesVisited'/> </ga:goal> </entry> </feed>"; AccountFeed feed = Parse(xml); AccountEntry entry = feed.Entries[0] as AccountEntry; Assert.IsNotNull(entry, "entry"); Assert.IsNotNull(entry.Properties); Assert.IsNotNull(entry.ProfileId); Assert.AreEqual("ga:accountId", entry.Properties[0].Name); Assert.AreEqual("123456", entry.Properties[0].Value); Assert.AreEqual("ga:accountName", entry.Properties[1].Name); Assert.AreEqual("Test Account", entry.Properties[1].Value); Assert.AreEqual("ga:profileId", entry.Properties[2].Name); Assert.AreEqual("1234567", entry.Properties[2].Value); Assert.AreEqual("ga:webPropertyId", entry.Properties[3].Name); Assert.AreEqual("UA-111111-1", entry.Properties[3].Value); Assert.AreEqual("www.test.com", entry.Title.Text); Account a = new Account(); a.AtomEntry = entry; Assert.AreEqual("123456", a.AccountId); Assert.AreEqual("Test Account", a.AccountName); Assert.AreEqual("1234567", a.ProfileId); Assert.AreEqual("UA-111111-1", a.WebPropertyId); Assert.AreEqual("www.test.com", a.Title); Assert.AreEqual("ga:1234567", a.TableId); Assert.IsNotEmpty(feed.Segments); foreach (Segment s in feed.Segments) { Assert.IsNotNull(s.Name); Assert.IsNotNull(s.Id); } Assert.AreEqual(feed.Segments[0].Name, "All Visits"); Assert.AreEqual(feed.Segments[0].Id, "gaid::-1"); Assert.AreEqual(feed.Segments[1].Name, "New Visitors"); Assert.AreEqual(feed.Segments[1].Id, "gaid::-2"); List<Goal> goals = entry.Goals; Assert.IsNotEmpty(goals); Assert.AreEqual(goals.Count, 3); //First goal: Test all the way down Goal firstGoal = goals[0]; Assert.AreEqual(firstGoal.Active, "true"); Assert.AreEqual(firstGoal.Name, "Completing Order"); Assert.AreEqual(firstGoal.Number, "1"); Assert.AreEqual(firstGoal.Value, "10.0"); //Destination Assert.IsNotNull(firstGoal.Destination); Destination destination = firstGoal.Destination; Assert.AreEqual(destination.CaseSensitive, "false"); Assert.AreEqual(destination.Expression, "/purchaseComplete.html"); Assert.AreEqual(destination.MatchType, "regex"); Assert.AreEqual(destination.Step1Required, "false"); //Test first step of destination //<ga:step name='View Product Categories' number='1' path='/Apps|Accessories'/> Assert.IsNotNull(destination.Steps); Assert.IsNotEmpty(destination.Steps); Step step = destination.Steps[0]; Assert.AreEqual(step.Name, "View Product Categories"); Assert.AreEqual(step.Number, "1"); Assert.AreEqual(step.Path, "/Apps|Accessories"); //Engagement //testing against node: <ga:engagement comparison='&gt;' thresholdValue='300' type='timeOnSite'/> Assert.IsNotNull(goals[1].Engagement); Engagement engagement = goals[1].Engagement; Assert.AreEqual(engagement.Comparison, ">"); Assert.AreEqual(engagement.Threshold, "300"); Assert.AreEqual(engagement.Type, "timeOnSite"); //Custom Variables Assert.IsNotNull(entry.CustomVariables); Assert.IsNotEmpty(entry.CustomVariables); CustomVariable cv = entry.CustomVariables[0]; Assert.AreEqual(cv.Name, "My Custom Variable"); Assert.AreEqual(cv.Index, "1"); Assert.AreEqual(cv.Scope, "3"); } /// <summary> ///A test for CreateAccountFeed ///</summary> [Test] public void CreateAccountFeedTest() { AccountFeed target = new AccountFeed(null, null); AccountEntry entry = target.CreateFeedEntry() as AccountEntry; Assert.IsNotNull(entry, "better have a AccountEntry here"); } } }
using System; using System.Collections.Generic; using System.Text; // Copyright (c) 2006 by Hugh Pyle, inguzaudio.com namespace DSPUtil { public interface ISweepGenerator : ISoundObj { ISoundObj Inverse { get; } } [Serializable] public class SweepGenerator : SoundObj, ISweepGenerator { double _lengthSecs; // length of just the sweep, not the whole file double _startFreq; double _endFreq; double _gap; bool _pulse; double _gain; bool _repeat; double _phi; public SweepGenerator(ushort numChannels, double lengthSecs, uint startFreq, uint endFreq, uint sampleRate, double gapSecs, bool pulse, double gain, bool repeat) { _lengthSecs = lengthSecs; _lengthSamples = (int)(sampleRate * ( lengthSecs + 2*gapSecs ) + (pulse ? (1.025f*sampleRate) : 0 )); _startFreq = startFreq; _endFreq = endFreq; NumChannels = numChannels; SampleRate = sampleRate; _gap = gapSecs; _pulse = pulse; _gain = gain; _repeat = repeat; _phi = 0; } public SweepGenerator(ushort numChannels, int lengthSamples, uint startFreq, uint endFreq, uint sampleRate, double gain, bool repeat) { _lengthSecs = lengthSamples / sampleRate; _lengthSamples = lengthSamples; _startFreq = startFreq; _endFreq = endFreq; NumChannels = numChannels; SampleRate = sampleRate; _gap = 0; _pulse = false; _gain = gain; _repeat = repeat; _phi = 0; } /// <summary> /// Get an iterator for samples /// </summary> public override IEnumerator<ISample> Samples { get { if (_pulse) { // First a half-second gap before the pulse int j = 0; for (; j < SampleRate / 2; j++) { yield return new Sample(NumChannels); } // A reversed sweep, sub-second, 10kHz down to 100Hz SoundObj sweep = new SweepGenerator(NumChannels, 0.025f, 100, 10000, SampleRate, 0.0f, false, _gain, false); SoundObj rever = new Reverser(); rever.Input = sweep; foreach (ISample sample in rever) { yield return sample; j++; } // Then half-second gap from the *start* of the pulse for (; j < SampleRate; j++) { yield return new Sample(NumChannels); } } if (_gap > 0) { // The gap before and after the sweep for (int j = 0; j < (_gap * SampleRate); j++) { yield return new Sample(NumChannels); } } // The sweep itself double logStart = Math.Log(_startFreq); double logEnd = Math.Log(_endFreq); bool more = true; while (more) { for (int j = 0; j < _lengthSecs * SampleRate; j++) { Sample sample = new Sample(NumChannels); double value = (Math.Sin(_phi)); // instantaneous frequency, radians/sec double f = Math.Exp(logStart + j * (logEnd - logStart) / (_lengthSecs * SampleRate)); double delta = 2 * Math.PI * f / SampleRate; _phi += delta; value *= _gain; for (int c = 0; c < NumChannels; c++) { sample[c] = value; } yield return sample; } more = _repeat; } } } /// <summary> Number of iterations expected to do the signal processing </summary> int _lengthSamples; public override int Iterations { get { return (_lengthSamples); } } /// <summary> /// Get an iterator for samples /// </summary> public ISoundObj Inverse { get { // Build an inverse filter, for deconvolution of the recorded sweep. // We only build inverse of the main sweep, and don't include pulse; // assume those will be removed by post-processing the recorded sweep. // // Per Farina swept sine distortion paper, // inverse of a log sweep is the same sweep, time-reversed, then // amplitude reduced by 6dB/oct from 0 to -6.log2(w2/w1) double dbEnd = -6 * Math.Log(_endFreq / _startFreq, 2); SoundObj revsw = new Reverser(); revsw.Input = this; SoundObj adjust = new LinearDbEnvelope(0, dbEnd, this.Iterations); adjust.Input = revsw; return adjust; } } } public unsafe class FFTSweepGenerator : SoundObj, ISweepGenerator { double _lengthSecs; // length of just the sweep, not the whole file double _startFreq; double _endFreq; double _gain; double _A; double _B; bool _repeat; Complex[] _data; bool _gotdata; public FFTSweepGenerator(ushort numChannels, int lengthSamples, uint startFreq, uint endFreq, uint sampleRate, double gain, bool repeat) { _lengthSecs = lengthSamples / sampleRate; _lengthSamples = lengthSamples; _startFreq = startFreq; _endFreq = endFreq; NumChannels = numChannels; SampleRate = sampleRate; _gain = gain; _repeat = repeat; } /// <summary> Number of iterations expected to do the signal processing </summary> int _lengthSamples; public override int Iterations { get { return (_lengthSamples); } } public override IEnumerator<ISample> Samples { get { ushort nc = NumChannels; ISoundObj sweep = CalculateSweep(); bool more = true; while (more) { foreach (Sample s in sweep) { if (nc == 1) { yield return s; } else if (nc == 2) { yield return new Sample2(s[0], s[0]); } } more = _repeat; } } } public ISoundObj Inverse { get { CalculateSweep(); int fftSize = _data.Length; int N = fftSize / 2; // Copy the data buffer (in case someone's reading from it) Complex[] data1 = new Complex[fftSize]; for (int j = 0; j < N; j++) { data1[j] = new Complex(_data[j].Re, 0); } // FFT the sweep data Fourier.FFT(fftSize, data1); Complex unity = new Complex(1, 0); Complex[] data2 = new Complex[fftSize]; data2[N-1] = unity; Fourier.FFT(fftSize, data2); for (int j = 0; j < fftSize; j++) { data1[j].idiv(data2[j]); } // IFFT Fourier.IFFT(fftSize, data1); //, 1/Math.Sqrt(n)); ComplexBufferReader cbr = new ComplexBufferReader(data1, 0, fftSize ); cbr.SampleRate = _sr; return cbr; } } double T(double f) { return _A + (_B * Math.Log(f)); } double phi(double f) { return (2 * Math.PI * f * (T(f) - _B)) % (2 * Math.PI); } double mag(double f) { double ff = f - _startFreq; if (ff <= 0) { return (Math.Cos(Math.PI*ff/_startFreq)+1)/2; } double dbNow = 1 - (10 * Math.Log10(f / _startFreq)); double gainNow = MathUtil.gain(dbNow); return gainNow; } ISoundObj CalculateSweep() { // Per http://www.anselmgoertz.de/Page10383/Monkey_Forest_dt/Manual_dt/aes-swp-english.pdf int fftSize = MathUtil.NextPowerOfTwo(_lengthSamples * 2); int N = fftSize / 2; // Center the sweep in time to reduce impact of its extremities double fNyq = _sr/2; double FStart = _startFreq; double FEnd = _endFreq; double SStart = (N - _lengthSamples)/2; double TStart = SStart / _sr; double TEnd = TStart + _lengthSecs; _B = (TEnd - TStart) / Math.Log(FEnd / FStart); _A = TStart - _B * Math.Log(FStart); // Make the complex spectrum //double ph = 0; double df = (double)_sr / N; double phiNyq = phi(fNyq); double phiAdj = phiNyq % (2 * Math.PI); if (!_gotdata) { _data = new Complex[fftSize]; fixed (Complex* cdata = _data) { for (int j = 0; j < N; j++) { int m = j + 1; double f = (double)m * _sr / fftSize; double ph = phi(f) - (f / fNyq) * phiAdj; double v = mag(f); double Re = Math.Cos(ph) * v; double Im = Math.Sin(ph) * v; _data[j] = new Complex(Re, Im); } Fourier.IFFT(fftSize, _data, Math.Sqrt(fftSize) * _gain * MathUtil.gain(20)); } // Look for values beyond the end // whose magnitude greater than our allowed threshold; // if present, window then ifft then start again. // Below doesn't seem to converge well // so just window and be done /* double threshold = MathUtil.gain(-90); bool iterate = true; while (iterate) { iterate = false; for (n = (int)(TEnd * sr + SStart * 2); n < fftSize; n++) { if (_data[n].Magnitude > threshold) { iterate = true; break; } } if (iterate) { Blackman bh = new Blackman((int)(_lengthSamples / 2 + SStart), _lengthSamples / 200, _lengthSamples / 2); bh.Input = cbr; n=0; foreach (ISample s in bh) { _data[n++] = new Complex(s[0],0); } Fourier.FFT(fftSize, _data); for (n = 0; n < N; n++) { int m = n + 1; double f = (double)m * sr / fftSize; double ph = _data[n].Phase; double v = mag(f); double Re = Math.Cos(ph) * v; double Im = Math.Sin(ph) * v; _data[n] = new Complex(Re, Im); } Fourier.IFFT(fftSize, _data); } } */ CosWindow bh = new Hamming((int)(_lengthSamples / 2 + SStart), (int)(SStart), _lengthSamples / 2); IEnumerator<double> gains = bh.Gains; for (int j = 0; j < N; j++) { gains.MoveNext(); double g = gains.Current; _data[j].mul(g); _data[fftSize - j - 1].mul(g); } _gotdata = true; } ComplexBufferReader cbr = new ComplexBufferReader(_data, 0, N); //bh.Input = cbr; return cbr; } } /* [Serializable] public class EQSweepGenerator : SoundObj { // Generates a log-sweep, with amplitude controlled by parameters // When this sweep is deconvolved with a log-sweep, you get the impulse response // of the parametric filter defined by those parameters (and linear phase). private double _lengthSecs; private uint _startFreq; private uint _endFreq; public EQSweepGenerator(double lengthSecs) { _lengthSecs = lengthSecs; _startFreq = 20; _endFreq = 20480; } private FilterProfile _coeffs; public FilterProfile Coefficients { get { return _coeffs; } set { _coeffs = value; } } #region Overrides /// <summary> Number of iterations expected to do the signal processing </summary> public override int Iterations { get { return (int)(SampleRate * _lengthSecs); } } #endregion public SoundObj RawSweep { get { SoundObj source; source = new NoiseGenerator(NoiseType.WHITE_FLAT, NumChannels, _lengthSecs, SampleRate, 1.0, false); // source = new SweepGenerator("S", _lengthSecs, _startFreq, _endFreq, _sampleRate, 0, false, 1.0); SoundBuffer buff = new SoundBuffer(source); return buff; } } public SoundObj InverseSweep { get { SoundObj sweep = RawSweep; SoundObj revsw = new Reverser(); revsw.Input = sweep; return revsw; } } /// <summary> /// Get an iterator for samples /// </summary> public override IEnumerator<ISample> Samples { get { double lengthSecs = 2; // Construct a sweep from 20Hz to 20kHz // (10 octaves; 20, 40, 80, 160, 320, 640, 1280, 2560, 5120, 10240, 20480) // over lengthSecs SoundObj sweep = RawSweep; double logStart = Math.Log(_startFreq); double logEnd = Math.Log(_endFreq); // Frequency (Hz) at sample j is // double omega = Math.Exp(logStart + j * (logEnd - logStart) / (lengthSecs * SampleRate)); // f = 2.pi.omega // // ln(f/2pi) = logStart + j*(...) // j*(...) = ln(f/2pi) - logStart // // Sample j for frequency f is // j = (ln(f/2pi) - logStart) / ( (logEnd - logStart) / (lengthSecs * SampleRate) ) // Construct shelf envelopes ShelfEnvelope rcsePrev = null; for(int n=1; n<_coeffs.Count; n++) { double freq1 = _coeffs[n-1].Freq; double freq2 = _coeffs[n].Freq; // gains in dB double gain1 = _coeffs[n - 1].Gain; double gain2 = _coeffs[n].Gain; // Since we're chaining these filters together, // we actually want to adjust for pre-sweep == 0dB, then end-sweep=(difference) double gainEnd = gain2 - gain1; double startSample = (Math.Log(freq1 * (2 * Math.PI)) - logStart) / ((logEnd - logStart) / (lengthSecs * SampleRate)); double endSample = (Math.Log(freq2 * (2 * Math.PI)) - logStart) / ((logEnd - logStart) / (lengthSecs * SampleRate)); ShelfEnvelope rcse = new ShelfEnvelope(0, gainEnd, (int)startSample, (int)endSample); // Input of this shelf is output of the previous shelf // (or, for the first shelf, the sweep) if (rcsePrev == null) { rcse.Input = sweep; } else { rcse.Input = rcsePrev; } rcsePrev = rcse; } // Ready foreach (ISample sample in rcsePrev) { yield return sample; } } } } */ }
#if MOBILE_LEGACY #define FEATURE_REMOTING #endif // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // // <OWNER>[....]</OWNER> /*============================================================ ** ** Class: ExecutionContext ** ** ** Purpose: Capture execution context for a thread ** ** ===========================================================*/ namespace System.Threading { using System; using System.Security; using System.Runtime.Remoting; using System.Security.Principal; using System.Collections; using System.Reflection; using System.Runtime.Serialization; using System.Security.Permissions; using System.Runtime.Remoting.Messaging; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; #if FEATURE_CORRUPTING_EXCEPTIONS using System.Runtime.ExceptionServices; #endif // FEATURE_CORRUPTING_EXCEPTIONS using System.Runtime.ConstrainedExecution; using System.Diagnostics.Contracts; using System.Diagnostics.CodeAnalysis; // helper delegate to statically bind to Wait method internal delegate int WaitDelegate(IntPtr[] waitHandles, bool waitAll, int millisecondsTimeout); internal struct ExecutionContextSwitcher { internal ExecutionContext.Reader outerEC; // previous EC we need to restore on Undo internal bool outerECBelongsToScope; #if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK internal SecurityContextSwitcher scsw; #endif // #if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK internal Object hecsw; #if !FEATURE_PAL && FEATURE_IMPERSONATION internal WindowsIdentity wi; internal bool cachedAlwaysFlowImpersonationPolicy; internal bool wiIsValid; #endif internal Thread thread; [System.Security.SecurityCritical] // auto-generated [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] #if FEATURE_CORRUPTING_EXCEPTIONS [HandleProcessCorruptedStateExceptions] // #endif // FEATURE_CORRUPTING_EXCEPTIONS internal bool UndoNoThrow() { try { Undo(Thread.CurrentThread); } catch { return false; } return true; } [System.Security.SecurityCritical] // auto-generated [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] internal void Undo(Thread currentThread) { // // Don't use an uninitialized switcher, or one that's already been used. // if (thread == null) return; // Don't do anything Contract.Assert(currentThread == this.thread); // // Restore the HostExecutionContext before restoring the ExecutionContext. // #if FEATURE_CAS_POLICY if (hecsw != null) HostExecutionContextSwitcher.Undo(hecsw); #endif // FEATURE_CAS_POLICY // // restore the saved Execution Context. Note that this will also restore the // SynchronizationContext, Logical/IllogicalCallContext, etc. // #if !FEATURE_PAL && FEATURE_IMPERSONATION ExecutionContext.Reader innerEC = currentThread.GetExecutionContextReader(); #endif currentThread.SetExecutionContext(outerEC, outerECBelongsToScope); #if !MONO && DEBUG try { currentThread.ForbidExecutionContextMutation = true; #endif // // Tell the SecurityContext to do the side-effects of restoration. // #if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK if (scsw.currSC != null) { // Any critical failure inside scsw will cause FailFast scsw.Undo(); } #endif // #if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK #if !FEATURE_PAL && FEATURE_IMPERSONATION if (wiIsValid) SecurityContext.RestoreCurrentWI(outerEC, innerEC, wi, cachedAlwaysFlowImpersonationPolicy); #endif thread = null; // this will prevent the switcher object being used again #if !MONO && DEBUG } finally { currentThread.ForbidExecutionContextMutation = false; } #endif } } public struct AsyncFlowControl: IDisposable { private bool useEC; private ExecutionContext _ec; #if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK private SecurityContext _sc; #endif // #if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK private Thread _thread; #if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK [SecurityCritical] internal void Setup(SecurityContextDisableFlow flags) { useEC = false; Thread currentThread = Thread.CurrentThread; _sc = currentThread.GetMutableExecutionContext().SecurityContext; _sc._disableFlow = flags; _thread = currentThread; } #endif // #if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK [SecurityCritical] internal void Setup() { useEC = true; Thread currentThread = Thread.CurrentThread; _ec = currentThread.GetMutableExecutionContext(); _ec.isFlowSuppressed = true; _thread = currentThread; } public void Dispose() { Undo(); } [SecuritySafeCritical] public void Undo() { if (_thread == null) { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CannotUseAFCMultiple")); } if (_thread != Thread.CurrentThread) { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CannotUseAFCOtherThread")); } if (useEC) { if (Thread.CurrentThread.GetMutableExecutionContext() != _ec) { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_AsyncFlowCtrlCtxMismatch")); } ExecutionContext.RestoreFlow(); } #if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK else { if (!Thread.CurrentThread.GetExecutionContextReader().SecurityContext.IsSame(_sc)) { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_AsyncFlowCtrlCtxMismatch")); } SecurityContext.RestoreFlow(); } #endif // #if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK _thread = null; } public override int GetHashCode() { // review - [....] return _thread == null ? ToString().GetHashCode() : _thread.GetHashCode(); } public override bool Equals(Object obj) { if (obj is AsyncFlowControl) return Equals((AsyncFlowControl)obj); else return false; } public bool Equals(AsyncFlowControl obj) { return obj.useEC == useEC && obj._ec == _ec && #if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK obj._sc == _sc && #endif // #if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK obj._thread == _thread; } public static bool operator ==(AsyncFlowControl a, AsyncFlowControl b) { return a.Equals(b); } public static bool operator !=(AsyncFlowControl a, AsyncFlowControl b) { return !(a == b); } } #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #endif [System.Runtime.InteropServices.ComVisible(true)] public delegate void ContextCallback(Object state); [Serializable] public sealed class ExecutionContext : IDisposable, ISerializable { /*========================================================================= ** Data accessed from managed code that needs to be defined in ** ExecutionContextObject to maintain alignment between the two classes. ** DON'T CHANGE THESE UNLESS YOU MODIFY ExecutionContextObject in vm\object.h =========================================================================*/ #if FEATURE_CAS_POLICY private HostExecutionContext _hostExecutionContext; #endif // FEATURE_CAS_POLICY #if FEATURE_SYNCHRONIZATIONCONTEXT private SynchronizationContext _syncContext; private SynchronizationContext _syncContextNoFlow; #endif // FEATURE_SYNCHRONIZATIONCONTEXT #if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK private SecurityContext _securityContext; #endif // #if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK [System.Security.SecurityCritical] // auto-generated private LogicalCallContext _logicalCallContext; private IllogicalCallContext _illogicalCallContext; // this call context follows the physical thread enum Flags { None = 0x0, IsNewCapture = 0x1, IsFlowSuppressed = 0x2, IsPreAllocatedDefault = 0x4 } private Flags _flags; internal bool isNewCapture { get { return (_flags & (Flags.IsNewCapture | Flags.IsPreAllocatedDefault)) != Flags.None; } set { Contract.Assert(!IsPreAllocatedDefault); if (value) _flags |= Flags.IsNewCapture; else _flags &= ~Flags.IsNewCapture; } } internal bool isFlowSuppressed { get { return (_flags & Flags.IsFlowSuppressed) != Flags.None; } set { Contract.Assert(!IsPreAllocatedDefault); if (value) _flags |= Flags.IsFlowSuppressed; else _flags &= ~Flags.IsFlowSuppressed; } } private static readonly ExecutionContext s_dummyDefaultEC = new ExecutionContext(isPreAllocatedDefault: true); static internal ExecutionContext PreAllocatedDefault { [SecuritySafeCritical] get { return s_dummyDefaultEC; } } internal bool IsPreAllocatedDefault { get { // we use _flags instead of a direct comparison w/ s_dummyDefaultEC to avoid the static access on // hot code paths. if ((_flags & Flags.IsPreAllocatedDefault) != Flags.None) { Contract.Assert(this == s_dummyDefaultEC); return true; } else { return false; } } } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] internal ExecutionContext() { } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] internal ExecutionContext(bool isPreAllocatedDefault) { if (isPreAllocatedDefault) _flags = Flags.IsPreAllocatedDefault; } // Read-only wrapper around ExecutionContext. This enables safe reading of an ExecutionContext without accidentally modifying it. internal struct Reader { ExecutionContext m_ec; public Reader(ExecutionContext ec) { m_ec = ec; } public ExecutionContext DangerousGetRawExecutionContext() { return m_ec; } public bool IsNull { get { return m_ec == null; } } [SecurityCritical] public bool IsDefaultFTContext(bool ignoreSyncCtx) { return m_ec.IsDefaultFTContext(ignoreSyncCtx); } public bool IsFlowSuppressed { #if !FEATURE_CORECLR [MethodImpl(MethodImplOptions.AggressiveInlining)] #endif get { return IsNull ? false : m_ec.isFlowSuppressed; } } //public Thread Thread { get { return m_ec._thread; } } public bool IsSame(ExecutionContext.Reader other) { return m_ec == other.m_ec; } #if FEATURE_SYNCHRONIZATIONCONTEXT public SynchronizationContext SynchronizationContext { get { return IsNull ? null : m_ec.SynchronizationContext; } } public SynchronizationContext SynchronizationContextNoFlow { get { return IsNull ? null : m_ec.SynchronizationContextNoFlow; } } #endif #if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK public SecurityContext.Reader SecurityContext { [SecurityCritical] [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new SecurityContext.Reader(IsNull ? null : m_ec.SecurityContext); } } #endif public LogicalCallContext.Reader LogicalCallContext { [SecurityCritical] get { return new LogicalCallContext.Reader(IsNull ? null : m_ec.LogicalCallContext); } } public IllogicalCallContext.Reader IllogicalCallContext { [SecurityCritical] get { return new IllogicalCallContext.Reader(IsNull ? null : m_ec.IllogicalCallContext); } } } internal LogicalCallContext LogicalCallContext { [System.Security.SecurityCritical] // auto-generated get { if (_logicalCallContext == null) { _logicalCallContext = new LogicalCallContext(); } return _logicalCallContext; } [System.Security.SecurityCritical] // auto-generated set { Contract.Assert(this != s_dummyDefaultEC); _logicalCallContext = value; } } internal IllogicalCallContext IllogicalCallContext { get { if (_illogicalCallContext == null) { _illogicalCallContext = new IllogicalCallContext(); } return _illogicalCallContext; } set { Contract.Assert(this != s_dummyDefaultEC); _illogicalCallContext = value; } } #if FEATURE_SYNCHRONIZATIONCONTEXT internal SynchronizationContext SynchronizationContext { [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] get { return _syncContext; } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] set { Contract.Assert(this != s_dummyDefaultEC); _syncContext = value; } } internal SynchronizationContext SynchronizationContextNoFlow { [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] get { return _syncContextNoFlow; } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] set { Contract.Assert(this != s_dummyDefaultEC); _syncContextNoFlow = value; } } #endif // #if FEATURE_SYNCHRONIZATIONCONTEXT #if FEATURE_CAS_POLICY internal HostExecutionContext HostExecutionContext { get { return _hostExecutionContext; } set { Contract.Assert(this != s_dummyDefaultEC); _hostExecutionContext = value; } } #endif // FEATURE_CAS_POLICY #if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK internal SecurityContext SecurityContext { [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] get { return _securityContext; } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] set { Contract.Assert(this != s_dummyDefaultEC); // store the new security context _securityContext = value; // perform the reverse link too if (value != null) _securityContext.ExecutionContext = this; } } #endif // #if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK public void Dispose() { if(this.IsPreAllocatedDefault) return; //Do nothing if this is the default context #if FEATURE_CAS_POLICY if (_hostExecutionContext != null) _hostExecutionContext.Dispose(); #endif // FEATURE_CAS_POLICY #if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK if (_securityContext != null) _securityContext.Dispose(); #endif //FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK } [DynamicSecurityMethod] [System.Security.SecurityCritical] // auto-generated_required public static void Run(ExecutionContext executionContext, ContextCallback callback, Object state) { if (executionContext == null) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NullContext")); if (!executionContext.isNewCapture) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotNewCaptureContext")); Run(executionContext, callback, state, false); } // This method is special from a security perspective - the VM will not allow a stack walk to // continue past the call to ExecutionContext.Run. If you change the signature to this method, make // sure to update SecurityStackWalk::IsSpecialRunFrame in the VM to search for the new signature. [DynamicSecurityMethod] [SecurityCritical] [FriendAccessAllowed] internal static void Run(ExecutionContext executionContext, ContextCallback callback, Object state, bool preserveSyncCtx) { RunInternal(executionContext, callback, state, preserveSyncCtx); } // Actual implementation of Run is here, in a non-DynamicSecurityMethod, because the JIT seems to refuse to inline callees into // a DynamicSecurityMethod. [SecurityCritical] [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "Reviewed for thread safety")] [HandleProcessCorruptedStateExceptions] internal static void RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, bool preserveSyncCtx) { Contract.Assert(executionContext != null); if (executionContext.IsPreAllocatedDefault) { Contract.Assert(executionContext.IsDefaultFTContext(preserveSyncCtx)); } else { Contract.Assert(executionContext.isNewCapture); executionContext.isNewCapture = false; } Thread currentThread = Thread.CurrentThread; ExecutionContextSwitcher ecsw = default(ExecutionContextSwitcher); RuntimeHelpers.PrepareConstrainedRegions(); try { ExecutionContext.Reader ec = currentThread.GetExecutionContextReader(); if ( (ec.IsNull || ec.IsDefaultFTContext(preserveSyncCtx)) && #if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK SecurityContext.CurrentlyInDefaultFTSecurityContext(ec) && #endif // #if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK executionContext.IsDefaultFTContext(preserveSyncCtx)) { // Neither context is interesting, so we don't need to set the context. // We do need to reset any changes made by the user's callback, // so here we establish a "copy-on-write scope". Any changes will // result in a copy of the context being made, preserving the original // context. EstablishCopyOnWriteScope(currentThread, true, ref ecsw); } else { if (executionContext.IsPreAllocatedDefault) executionContext = executionContext.CreateCopy(); ecsw = SetExecutionContext(executionContext, preserveSyncCtx); } // // Call the user's callback // callback(state); } finally { ecsw.Undo(currentThread); } } [SecurityCritical] static internal void EstablishCopyOnWriteScope(Thread currentThread, bool knownNullWindowsIdentity, ref ExecutionContextSwitcher ecsw) { Contract.Assert(currentThread == Thread.CurrentThread); ecsw.outerEC = currentThread.GetExecutionContextReader(); ecsw.outerECBelongsToScope = currentThread.ExecutionContextBelongsToCurrentScope; #if !FEATURE_PAL && FEATURE_IMPERSONATION ecsw.cachedAlwaysFlowImpersonationPolicy = SecurityContext.AlwaysFlowImpersonationPolicy; if (knownNullWindowsIdentity) Contract.Assert(SecurityContext.GetCurrentWI(ecsw.outerEC, ecsw.cachedAlwaysFlowImpersonationPolicy) == null); else ecsw.wi = SecurityContext.GetCurrentWI(ecsw.outerEC, ecsw.cachedAlwaysFlowImpersonationPolicy); ecsw.wiIsValid = true; #endif currentThread.ExecutionContextBelongsToCurrentScope = false; ecsw.thread = currentThread; } // Sets the given execution context object on the thread. // Returns the previous one. [System.Security.SecurityCritical] // auto-generated [DynamicSecurityMethodAttribute()] [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable #if FEATURE_CORRUPTING_EXCEPTIONS [HandleProcessCorruptedStateExceptions] // #endif // FEATURE_CORRUPTING_EXCEPTIONS internal static ExecutionContextSwitcher SetExecutionContext(ExecutionContext executionContext, bool preserveSyncCtx) { #if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; #endif // #if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK Contract.Assert(executionContext != null); Contract.Assert(executionContext != s_dummyDefaultEC); // Set up the switcher object to return; ExecutionContextSwitcher ecsw = new ExecutionContextSwitcher(); Thread currentThread = Thread.CurrentThread; ExecutionContext.Reader outerEC = currentThread.GetExecutionContextReader(); ecsw.thread = currentThread; ecsw.outerEC = outerEC; ecsw.outerECBelongsToScope = currentThread.ExecutionContextBelongsToCurrentScope; if (preserveSyncCtx) executionContext.SynchronizationContext = outerEC.SynchronizationContext; executionContext.SynchronizationContextNoFlow = outerEC.SynchronizationContextNoFlow; currentThread.SetExecutionContext(executionContext, belongsToCurrentScope: true); RuntimeHelpers.PrepareConstrainedRegions(); try { #if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK //set the security context SecurityContext sc = executionContext.SecurityContext; if (sc != null) { // non-null SC: needs to be set SecurityContext.Reader prevSeC = outerEC.SecurityContext; ecsw.scsw = SecurityContext.SetSecurityContext(sc, prevSeC, false, ref stackMark); } else if (!SecurityContext.CurrentlyInDefaultFTSecurityContext(ecsw.outerEC)) { // null incoming SC, but we're currently not in FT: use static FTSC to set SecurityContext.Reader prevSeC = outerEC.SecurityContext; ecsw.scsw = SecurityContext.SetSecurityContext(SecurityContext.FullTrustSecurityContext, prevSeC, false, ref stackMark); } #endif // #if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK #if FEATURE_CAS_POLICY // set the Host Context HostExecutionContext hostContext = executionContext.HostExecutionContext; if (hostContext != null) { ecsw.hecsw = HostExecutionContextManager.SetHostExecutionContextInternal(hostContext); } #endif // FEATURE_CAS_POLICY } catch { ecsw.UndoNoThrow(); throw; } return ecsw; } // // Public CreateCopy. Used to copy captured ExecutionContexts so they can be reused multiple times. // This should only copy the portion of the context that we actually capture. // [SecuritySafeCritical] public ExecutionContext CreateCopy() { if (!isNewCapture) { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CannotCopyUsedContext")); } ExecutionContext ec = new ExecutionContext(); ec.isNewCapture = true; #if FEATURE_SYNCHRONIZATIONCONTEXT ec._syncContext = _syncContext == null ? null : _syncContext.CreateCopy(); #endif // #if FEATURE_SYNCHRONIZATIONCONTEXT #if FEATURE_CAS_POLICY // capture the host execution context ec._hostExecutionContext = _hostExecutionContext == null ? null : _hostExecutionContext.CreateCopy(); #endif // FEATURE_CAS_POLICY #if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK if (_securityContext != null) { ec._securityContext = _securityContext.CreateCopy(); ec._securityContext.ExecutionContext = ec; } #endif // #if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK if (this._logicalCallContext != null) ec.LogicalCallContext = (LogicalCallContext)this.LogicalCallContext.Clone(); Contract.Assert(this._illogicalCallContext == null); return ec; } // // Creates a complete copy, used for copy-on-write. // [SecuritySafeCritical] internal ExecutionContext CreateMutableCopy() { Contract.Assert(!this.isNewCapture); ExecutionContext ec = new ExecutionContext(); // We don't deep-copy the SyncCtx, since we're still in the same context after copy-on-write. #if FEATURE_SYNCHRONIZATIONCONTEXT ec._syncContext = this._syncContext; ec._syncContextNoFlow = this._syncContextNoFlow; #endif // #if FEATURE_SYNCHRONIZATIONCONTEXT #if FEATURE_CAS_POLICY // capture the host execution context ec._hostExecutionContext = this._hostExecutionContext == null ? null : _hostExecutionContext.CreateCopy(); #endif // FEATURE_CAS_POLICY #if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK if (_securityContext != null) { ec._securityContext = this._securityContext.CreateMutableCopy(); ec._securityContext.ExecutionContext = ec; } #endif // #if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK if (this._logicalCallContext != null) ec.LogicalCallContext = (LogicalCallContext)this.LogicalCallContext.Clone(); if (this._illogicalCallContext != null) ec.IllogicalCallContext = (IllogicalCallContext)this.IllogicalCallContext.CreateCopy(); ec.isFlowSuppressed = this.isFlowSuppressed; return ec; } [System.Security.SecurityCritical] // auto-generated_required public static AsyncFlowControl SuppressFlow() { if (IsFlowSuppressed()) { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CannotSupressFlowMultipleTimes")); } Contract.EndContractBlock(); AsyncFlowControl afc = new AsyncFlowControl(); afc.Setup(); return afc; } [SecuritySafeCritical] public static void RestoreFlow() { ExecutionContext ec = Thread.CurrentThread.GetMutableExecutionContext(); if (!ec.isFlowSuppressed) { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CannotRestoreUnsupressedFlow")); } ec.isFlowSuppressed = false; } [Pure] public static bool IsFlowSuppressed() { return Thread.CurrentThread.GetExecutionContextReader().IsFlowSuppressed; } [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable public static ExecutionContext Capture() { // set up a stack mark for finding the caller StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; return ExecutionContext.Capture(ref stackMark, CaptureOptions.None); } // // Captures an ExecutionContext with optimization for the "default" case, and captures a "null" synchronization context. // When calling ExecutionContext.Run on the returned context, specify ignoreSyncCtx = true // [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable [FriendAccessAllowed] internal static ExecutionContext FastCapture() { // set up a stack mark for finding the caller StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; return ExecutionContext.Capture(ref stackMark, CaptureOptions.IgnoreSyncCtx | CaptureOptions.OptimizeDefaultCase); } [Flags] internal enum CaptureOptions { None = 0x00, IgnoreSyncCtx = 0x01, //Don't flow SynchronizationContext OptimizeDefaultCase = 0x02, //Faster in the typical case, but can't show the result to users // because they could modify the shared default EC. // Use this only if you won't be exposing the captured EC to users. } // internal helper to capture the current execution context using a passed in stack mark [System.Security.SecurityCritical] // auto-generated static internal ExecutionContext Capture(ref StackCrawlMark stackMark, CaptureOptions options) { ExecutionContext.Reader ecCurrent = Thread.CurrentThread.GetExecutionContextReader(); // check to see if Flow is suppressed if (ecCurrent.IsFlowSuppressed) return null; // // Attempt to capture context. There may be nothing to capture... // #if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK // capture the security context SecurityContext secCtxNew = SecurityContext.Capture(ecCurrent, ref stackMark); #endif // #if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK #if FEATURE_CAS_POLICY // capture the host execution context HostExecutionContext hostCtxNew = HostExecutionContextManager.CaptureHostExecutionContext(); #endif // FEATURE_CAS_POLICY #if FEATURE_SYNCHRONIZATIONCONTEXT SynchronizationContext syncCtxNew = null; #endif LogicalCallContext logCtxNew = null; if (!ecCurrent.IsNull) { // capture the [....] context if (0 == (options & CaptureOptions.IgnoreSyncCtx)) syncCtxNew = (ecCurrent.SynchronizationContext == null) ? null : ecCurrent.SynchronizationContext.CreateCopy(); #endif // #if FEATURE_SYNCHRONIZATIONCONTEXT // copy over the Logical Call Context if (ecCurrent.LogicalCallContext.HasInfo) logCtxNew = ecCurrent.LogicalCallContext.Clone(); } // // If we didn't get anything but defaults, and we're allowed to return the // dummy default EC, don't bother allocating a new context. // if (0 != (options & CaptureOptions.OptimizeDefaultCase) && #if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK secCtxNew == null && #endif #if FEATURE_CAS_POLICY hostCtxNew == null && #endif // FEATURE_CAS_POLICY #if FEATURE_SYNCHRONIZATIONCONTEXT syncCtxNew == null && #endif // #if FEATURE_SYNCHRONIZATIONCONTEXT (logCtxNew == null || !logCtxNew.HasInfo)) { return s_dummyDefaultEC; } // // Allocate the new context, and fill it in. // ExecutionContext ecNew = new ExecutionContext(); #if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK ecNew.SecurityContext = secCtxNew; if (ecNew.SecurityContext != null) ecNew.SecurityContext.ExecutionContext = ecNew; #endif #if FEATURE_CAS_POLICY ecNew._hostExecutionContext = hostCtxNew; #endif // FEATURE_CAS_POLICY #if FEATURE_SYNCHRONIZATIONCONTEXT ecNew._syncContext = syncCtxNew; #endif // #if FEATURE_SYNCHRONIZATIONCONTEXT ecNew.LogicalCallContext = logCtxNew; ecNew.isNewCapture = true; return ecNew; } // // Implementation of ISerializable // [System.Security.SecurityCritical] // auto-generated_required public void GetObjectData(SerializationInfo info, StreamingContext context) { if (info==null) throw new ArgumentNullException("info"); Contract.EndContractBlock(); if (_logicalCallContext != null) { info.AddValue("LogicalCallContext", _logicalCallContext, typeof(LogicalCallContext)); } } [System.Security.SecurityCritical] // auto-generated private ExecutionContext(SerializationInfo info, StreamingContext context) { SerializationInfoEnumerator e = info.GetEnumerator(); while (e.MoveNext()) { if (e.Name.Equals("LogicalCallContext")) { _logicalCallContext = (LogicalCallContext) e.Value; } } } // ObjRef .ctor [System.Security.SecurityCritical] // auto-generated internal bool IsDefaultFTContext(bool ignoreSyncCtx) { #if FEATURE_CAS_POLICY if (_hostExecutionContext != null) return false; #endif // FEATURE_CAS_POLICY #if FEATURE_SYNCHRONIZATIONCONTEXT if (!ignoreSyncCtx && _syncContext != null) return false; #endif // #if FEATURE_SYNCHRONIZATIONCONTEXT #if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK if (_securityContext != null && !_securityContext.IsDefaultFTSecurityContext()) return false; #endif //#if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK if (_logicalCallContext != null && _logicalCallContext.HasInfo) return false; if (_illogicalCallContext != null && _illogicalCallContext.HasUserData) return false; return true; } } // class ExecutionContext }
//*********************************************************// // Copyright (c) Microsoft. All rights reserved. // // Apache 2.0 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.Globalization; using Microsoft.VisualStudio; using Microsoft.VisualStudio.Debugger.Interop; namespace Microsoft.NodejsTools.Debugger.DebugEngine { // And implementation of IDebugCodeContext2 and IDebugMemoryContext2. // IDebugMemoryContext2 represents a position in the address space of the machine running the program being debugged. // IDebugCodeContext2 represents the starting position of a code instruction. // For most run-time architectures today, a code context can be thought of as an address in a program's execution stream. sealed class AD7MemoryAddress : IDebugCodeContext2, IDebugCodeContext100 { private readonly int _column; private readonly AD7Engine _engine; private readonly string _fileName; private readonly NodeStackFrame _frame; private readonly int _line; private IDebugDocumentContext2 _documentContext; private AD7MemoryAddress(AD7Engine engine, NodeStackFrame frame, string fileName, int line, int column) { _engine = engine; _frame = frame; _fileName = fileName; _line = line; _column = column; } public AD7MemoryAddress(AD7Engine engine, string fileName, int line, int column) : this(engine, null, fileName, line, column) { } public AD7MemoryAddress(AD7Engine engine, NodeStackFrame frame) : this(engine, frame, null, frame.Line, frame.Column) { } public AD7Engine Engine { get { return _engine; } } public NodeModule Module { get { return _frame != null ? _frame.Module : null; } } public string FileName { get { return _frame != null ? _frame.FileName : _fileName; } } public int Line { get { return _line; } } public int Column { get { return _column; } } public void SetDocumentContext(IDebugDocumentContext2 docContext) { _documentContext = docContext; } #region IDebugMemoryContext2 Members // Adds a specified value to the current context's address to create a new context. public int Add(ulong dwCount, out IDebugMemoryContext2 newAddress) { newAddress = new AD7MemoryAddress(_engine, _frame, _fileName, _line + (int)dwCount, _column); return VSConstants.S_OK; } // Compares the memory context to each context in the given array in the manner indicated by compare flags, // returning an index of the first context that matches. public int Compare(enum_CONTEXT_COMPARE uContextCompare, IDebugMemoryContext2[] compareToItems, uint compareToLength, out uint foundIndex) { foundIndex = uint.MaxValue; enum_CONTEXT_COMPARE contextCompare = uContextCompare; for (uint c = 0; c < compareToLength; c++) { var compareTo = compareToItems[c] as AD7MemoryAddress; if (compareTo == null) { continue; } if (!ReferenceEquals(_engine, compareTo._engine)) { continue; } bool result; switch (contextCompare) { case enum_CONTEXT_COMPARE.CONTEXT_EQUAL: result = _line == compareTo._line; break; case enum_CONTEXT_COMPARE.CONTEXT_LESS_THAN: result = _line < compareTo._line; break; case enum_CONTEXT_COMPARE.CONTEXT_GREATER_THAN: result = _line > compareTo._line; break; case enum_CONTEXT_COMPARE.CONTEXT_LESS_THAN_OR_EQUAL: result = _line <= compareTo._line; break; case enum_CONTEXT_COMPARE.CONTEXT_GREATER_THAN_OR_EQUAL: result = _line >= compareTo._line; break; case enum_CONTEXT_COMPARE.CONTEXT_SAME_SCOPE: case enum_CONTEXT_COMPARE.CONTEXT_SAME_FUNCTION: if (_frame != null) { result = compareTo.FileName == FileName && compareTo._line >= _frame.StartLine && compareTo._line <= _frame.EndLine; } else if (compareTo._frame != null) { result = compareTo.FileName == FileName && _line >= compareTo._frame.StartLine && compareTo._line <= compareTo._frame.EndLine; } else { result = _line == compareTo._line && FileName == compareTo.FileName; } break; case enum_CONTEXT_COMPARE.CONTEXT_SAME_MODULE: result = FileName == compareTo.FileName; break; case enum_CONTEXT_COMPARE.CONTEXT_SAME_PROCESS: result = true; break; default: // A new comparison was invented that we don't support return VSConstants.E_NOTIMPL; } if (result) { foundIndex = c; return VSConstants.S_OK; } } return VSConstants.S_FALSE; } // Gets information that describes this context. public int GetInfo(enum_CONTEXT_INFO_FIELDS dwFields, CONTEXT_INFO[] pinfo) { pinfo[0].dwFields = 0; if ((dwFields & enum_CONTEXT_INFO_FIELDS.CIF_ADDRESS) != 0) { pinfo[0].bstrAddress = _line.ToString(CultureInfo.InvariantCulture); pinfo[0].dwFields |= enum_CONTEXT_INFO_FIELDS.CIF_ADDRESS; } if ((dwFields & enum_CONTEXT_INFO_FIELDS.CIF_FUNCTION) != 0 && _frame != null) { pinfo[0].bstrFunction = _frame.FunctionName; pinfo[0].dwFields |= enum_CONTEXT_INFO_FIELDS.CIF_FUNCTION; } // Fields not supported by the sample if ((dwFields & enum_CONTEXT_INFO_FIELDS.CIF_ADDRESSOFFSET) != 0) { } if ((dwFields & enum_CONTEXT_INFO_FIELDS.CIF_ADDRESSABSOLUTE) != 0) { } if ((dwFields & enum_CONTEXT_INFO_FIELDS.CIF_MODULEURL) != 0) { } if ((dwFields & enum_CONTEXT_INFO_FIELDS.CIF_FUNCTIONOFFSET) != 0) { } return VSConstants.S_OK; } // Gets the user-displayable name for this context // This is not supported by the sample engine. public int GetName(out string pbstrName) { throw new Exception("The method or operation is not implemented."); } // Subtracts a specified value from the current context's address to create a new context. public int Subtract(ulong dwCount, out IDebugMemoryContext2 ppMemCxt) { ppMemCxt = new AD7MemoryAddress(_engine, _frame, _fileName, _line - (int)dwCount, _column); return VSConstants.S_OK; } #endregion #region IDebugCodeContext2 Members // Gets the document context for this code-context public int GetDocumentContext(out IDebugDocumentContext2 ppSrcCxt) { ppSrcCxt = _documentContext; return VSConstants.S_OK; } // Gets the language information for this code context. public int GetLanguageInfo(ref string pbstrLanguage, ref Guid pguidLanguage) { if (_documentContext != null) { return _documentContext.GetLanguageInfo(ref pbstrLanguage, ref pguidLanguage); } AD7Engine.MapLanguageInfo(FileName, out pbstrLanguage, out pguidLanguage); return VSConstants.S_OK; } #endregion #region IDebugCodeContext100 Members // Returns the program being debugged. In the case of this sample // debug engine, AD7Engine implements IDebugProgram2 which represents // the program being debugged. int IDebugCodeContext100.GetProgram(out IDebugProgram2 pProgram) { pProgram = _engine; return VSConstants.S_OK; } #endregion } }
using UnityEngine; using System.Collections; using System.Collections.Generic; [System.Serializable] public class tk2dSpriteColliderIsland { public bool connected = true; public Vector2[] points; public bool IsValid() { if (connected) { return points.Length >= 3; } else { return points.Length >= 2; } } public void CopyFrom(tk2dSpriteColliderIsland src) { connected = src.connected; points = new Vector2[src.points.Length]; for (int i = 0; i < points.Length; ++i) points[i] = src.points[i]; } public bool CompareTo(tk2dSpriteColliderIsland src) { if (connected != src.connected) return false; if (points.Length != src.points.Length) return false; for (int i = 0; i < points.Length; ++i) if (points[i] != src.points[i]) return false; return true; } } [System.Serializable] public class tk2dSpriteCollectionDefinition { public enum Anchor { UpperLeft, UpperCenter, UpperRight, MiddleLeft, MiddleCenter, MiddleRight, LowerLeft, LowerCenter, LowerRight, Custom } public enum Pad { Default, BlackZeroAlpha, Extend, TileXY, } public enum ColliderType { UserDefined, // don't try to create or destroy anything ForceNone, // nothing will be created, if something exists, it will be destroyed BoxTrimmed, // box, trimmed to cover visible region BoxCustom, // box, with custom values provided by user Polygon, // polygon, can be concave } public enum PolygonColliderCap { None, FrontAndBack, Front, Back, } public enum ColliderColor { Default, // default unity color scheme Red, White, Black } public enum Source { Sprite, SpriteSheet, Font } public string name = ""; public bool disableTrimming = false; public bool additive = false; public Vector3 scale = new Vector3(1,1,1); public Texture2D texture = null; [System.NonSerialized] public Texture2D thumbnailTexture; public int materialId = 0; public Anchor anchor = Anchor.MiddleCenter; public float anchorX, anchorY; public Object overrideMesh; public bool doubleSidedSprite = false; public bool customSpriteGeometry = false; public tk2dSpriteColliderIsland[] geometryIslands = new tk2dSpriteColliderIsland[0]; public bool dice = false; public int diceUnitX = 64; public int diceUnitY = 0; public Pad pad = Pad.Default; public int extraPadding = 0; // default public Source source = Source.Sprite; public bool fromSpriteSheet = false; public bool hasSpriteSheetId = false; public int spriteSheetId = 0; public int spriteSheetX = 0, spriteSheetY = 0; public bool extractRegion = false; public int regionX, regionY, regionW, regionH; public int regionId; public ColliderType colliderType = ColliderType.UserDefined; public Vector2 boxColliderMin, boxColliderMax; public tk2dSpriteColliderIsland[] polyColliderIslands; public PolygonColliderCap polyColliderCap = PolygonColliderCap.FrontAndBack; public bool colliderConvex = false; public bool colliderSmoothSphereCollisions = false; public ColliderColor colliderColor = ColliderColor.Default; public void CopyFrom(tk2dSpriteCollectionDefinition src) { name = src.name; disableTrimming = src.disableTrimming; additive = src.additive; scale = src.scale; texture = src.texture; materialId = src.materialId; anchor = src.anchor; anchorX = src.anchorX; anchorY = src.anchorY; overrideMesh = src.overrideMesh; doubleSidedSprite = src.doubleSidedSprite; customSpriteGeometry = src.customSpriteGeometry; geometryIslands = src.geometryIslands; dice = src.dice; diceUnitX = src.diceUnitX; diceUnitY = src.diceUnitY; pad = src.pad; source = src.source; fromSpriteSheet = src.fromSpriteSheet; hasSpriteSheetId = src.hasSpriteSheetId; spriteSheetX = src.spriteSheetX; spriteSheetY = src.spriteSheetY; spriteSheetId = src.spriteSheetId; extractRegion = src.extractRegion; regionX = src.regionX; regionY = src.regionY; regionW = src.regionW; regionH = src.regionH; regionId = src.regionId; colliderType = src.colliderType; boxColliderMin = src.boxColliderMin; boxColliderMax = src.boxColliderMax; polyColliderCap = src.polyColliderCap; colliderColor = src.colliderColor; colliderConvex = src.colliderConvex; colliderSmoothSphereCollisions = src.colliderSmoothSphereCollisions; extraPadding = src.extraPadding; if (src.polyColliderIslands != null) { polyColliderIslands = new tk2dSpriteColliderIsland[src.polyColliderIslands.Length]; for (int i = 0; i < polyColliderIslands.Length; ++i) { polyColliderIslands[i] = new tk2dSpriteColliderIsland(); polyColliderIslands[i].CopyFrom(src.polyColliderIslands[i]); } } else { polyColliderIslands = new tk2dSpriteColliderIsland[0]; } if (src.geometryIslands != null) { geometryIslands = new tk2dSpriteColliderIsland[src.geometryIslands.Length]; for (int i = 0; i < geometryIslands.Length; ++i) { geometryIslands[i] = new tk2dSpriteColliderIsland(); geometryIslands[i].CopyFrom(src.geometryIslands[i]); } } else { geometryIslands = new tk2dSpriteColliderIsland[0]; } } public void Clear() { // Reinitialize var tmpVar = new tk2dSpriteCollectionDefinition(); CopyFrom(tmpVar); } public bool CompareTo(tk2dSpriteCollectionDefinition src) { if (name != src.name) return false; if (additive != src.additive) return false; if (scale != src.scale) return false; if (texture != src.texture) return false; if (materialId != src.materialId) return false; if (anchor != src.anchor) return false; if (anchorX != src.anchorX) return false; if (anchorY != src.anchorY) return false; if (overrideMesh != src.overrideMesh) return false; if (dice != src.dice) return false; if (diceUnitX != src.diceUnitX) return false; if (diceUnitY != src.diceUnitY) return false; if (pad != src.pad) return false; if (extraPadding != src.extraPadding) return false; if (doubleSidedSprite != src.doubleSidedSprite) return false; if (customSpriteGeometry != src.customSpriteGeometry) return false; if (geometryIslands != src.geometryIslands) return false; if (geometryIslands != null && src.geometryIslands != null) { if (geometryIslands.Length != src.geometryIslands.Length) return false; for (int i = 0; i < geometryIslands.Length; ++i) if (!geometryIslands[i].CompareTo(src.geometryIslands[i])) return false; } if (source != src.source) return false; if (fromSpriteSheet != src.fromSpriteSheet) return false; if (hasSpriteSheetId != src.hasSpriteSheetId) return false; if (spriteSheetId != src.spriteSheetId) return false; if (spriteSheetX != src.spriteSheetX) return false; if (spriteSheetY != src.spriteSheetY) return false; if (extractRegion != src.extractRegion) return false; if (regionX != src.regionX) return false; if (regionY != src.regionY) return false; if (regionW != src.regionW) return false; if (regionH != src.regionH) return false; if (regionId != src.regionId) return false; if (colliderType != src.colliderType) return false; if (boxColliderMin != src.boxColliderMin) return false; if (boxColliderMax != src.boxColliderMax) return false; if (polyColliderIslands != src.polyColliderIslands) return false; if (polyColliderIslands != null && src.polyColliderIslands != null) { if (polyColliderIslands.Length != src.polyColliderIslands.Length) return false; for (int i = 0; i < polyColliderIslands.Length; ++i) if (!polyColliderIslands[i].CompareTo(src.polyColliderIslands[i])) return false; } if (polyColliderCap != src.polyColliderCap) return false; if (colliderColor != src.colliderColor) return false; if (colliderSmoothSphereCollisions != src.colliderSmoothSphereCollisions) return false; if (colliderConvex != src.colliderConvex) return false; return true; } } [System.Serializable] public class tk2dSpriteCollectionDefault { public bool additive = false; public Vector3 scale = new Vector3(1,1,1); public tk2dSpriteCollectionDefinition.Anchor anchor = tk2dSpriteCollectionDefinition.Anchor.MiddleCenter; public tk2dSpriteCollectionDefinition.Pad pad = tk2dSpriteCollectionDefinition.Pad.Default; public tk2dSpriteCollectionDefinition.ColliderType colliderType = tk2dSpriteCollectionDefinition.ColliderType.UserDefined; } [System.Serializable] public class tk2dSpriteSheetSource { public enum Anchor { UpperLeft, UpperCenter, UpperRight, MiddleLeft, MiddleCenter, MiddleRight, LowerLeft, LowerCenter, LowerRight, } public enum SplitMethod { UniformDivision, } public Texture2D texture; public int tilesX, tilesY; public int numTiles = 0; public Anchor anchor = Anchor.MiddleCenter; public tk2dSpriteCollectionDefinition.Pad pad = tk2dSpriteCollectionDefinition.Pad.Default; public Vector3 scale = new Vector3(1,1,1); public bool additive = false; // version 1 public bool active = false; public int tileWidth, tileHeight; public int tileMarginX, tileMarginY; public int tileSpacingX, tileSpacingY; public SplitMethod splitMethod = SplitMethod.UniformDivision; public int version = 0; public const int CURRENT_VERSION = 1; public tk2dSpriteCollectionDefinition.ColliderType colliderType = tk2dSpriteCollectionDefinition.ColliderType.UserDefined; public void CopyFrom(tk2dSpriteSheetSource src) { texture = src.texture; tilesX = src.tilesX; tilesY = src.tilesY; numTiles = src.numTiles; anchor = src.anchor; pad = src.pad; scale = src.scale; colliderType = src.colliderType; version = src.version; active = src.active; tileWidth = src.tileWidth; tileHeight = src.tileHeight; tileSpacingX = src.tileSpacingX; tileSpacingY = src.tileSpacingY; tileMarginX = src.tileMarginX; tileMarginY = src.tileMarginY; splitMethod = src.splitMethod; } public bool CompareTo(tk2dSpriteSheetSource src) { if (texture != src.texture) return false; if (tilesX != src.tilesX) return false; if (tilesY != src.tilesY) return false; if (numTiles != src.numTiles) return false; if (anchor != src.anchor) return false; if (pad != src.pad) return false; if (scale != src.scale) return false; if (colliderType != src.colliderType) return false; if (version != src.version) return false; if (active != src.active) return false; if (tileWidth != src.tileWidth) return false; if (tileHeight != src.tileHeight) return false; if (tileSpacingX != src.tileSpacingX) return false; if (tileSpacingY != src.tileSpacingY) return false; if (tileMarginX != src.tileMarginX) return false; if (tileMarginY != src.tileMarginY) return false; if (splitMethod != src.splitMethod) return false; return true; } public string Name { get { return texture != null?texture.name:"New Sprite Sheet"; } } } [System.Serializable] public class tk2dSpriteCollectionFont { public bool active = false; public Object bmFont; public Texture2D texture; public bool dupeCaps = false; // duplicate lowercase into uc, or vice-versa, depending on which exists public bool flipTextureY = false; public int charPadX = 0; public tk2dFontData data; public tk2dFont editorData; public int materialId; public bool useGradient = false; public Texture2D gradientTexture = null; public int gradientCount = 1; public void CopyFrom(tk2dSpriteCollectionFont src) { active = src.active; bmFont = src.bmFont; texture = src.texture; dupeCaps = src.dupeCaps; flipTextureY = src.flipTextureY; charPadX = src.charPadX; data = src.data; editorData = src.editorData; materialId = src.materialId; gradientCount = src.gradientCount; gradientTexture = src.gradientTexture; useGradient = src.useGradient; } public string Name { get { if (bmFont == null || texture == null) return "Empty"; else { if (data == null) return bmFont.name + " (Inactive)"; else return bmFont.name; } } } public bool InUse { get { return active && bmFont != null && texture != null && data != null && editorData != null; } } } [System.Serializable] public class tk2dSpriteCollectionPlatform { public string name = ""; public tk2dSpriteCollection spriteCollection = null; public bool Valid { get { return name.Length > 0 && spriteCollection != null; } } public void CopyFrom(tk2dSpriteCollectionPlatform source) { name = source.name; spriteCollection = source.spriteCollection; } } [AddComponentMenu("2D Toolkit/Backend/tk2dSpriteCollection")] public class tk2dSpriteCollection : MonoBehaviour { public const int CURRENT_VERSION = 3; public enum NormalGenerationMode { None, NormalsOnly, NormalsAndTangents, }; // Deprecated fields [SerializeField] private tk2dSpriteCollectionDefinition[] textures; [SerializeField] private Texture2D[] textureRefs; public Texture2D[] DoNotUse__TextureRefs { get { return textureRefs; } set { textureRefs = value; } } // Don't use this for anything. Except maybe in tk2dSpriteCollectionBuilderDeprecated... // new method public tk2dSpriteSheetSource[] spriteSheets; public tk2dSpriteCollectionFont[] fonts; public tk2dSpriteCollectionDefault defaults; // platforms public List<tk2dSpriteCollectionPlatform> platforms = new List<tk2dSpriteCollectionPlatform>(); public bool managedSpriteCollection = false; // true when generated and managed by system, eg. platform specific data public bool HasPlatformData { get { return platforms.Count > 1; } } public bool loadable = false; public int maxTextureSize = 1024; public bool forceTextureSize = false; public int forcedTextureWidth = 1024; public int forcedTextureHeight = 1024; public enum TextureCompression { Uncompressed, Reduced16Bit, Compressed, Dithered16Bit_Alpha, Dithered16Bit_NoAlpha, } public TextureCompression textureCompression = TextureCompression.Uncompressed; public int atlasWidth, atlasHeight; public bool forceSquareAtlas = false; public float atlasWastage; public bool allowMultipleAtlases = false; public tk2dSpriteCollectionDefinition[] textureParams; public tk2dSpriteCollectionData spriteCollection; public bool premultipliedAlpha = false; public Material[] altMaterials; public Material[] atlasMaterials; public Texture2D[] atlasTextures; public bool useTk2dCamera = false; public int targetHeight = 640; public float targetOrthoSize = 10.0f; public float globalScale = 1.0f; // Texture settings [SerializeField] private bool pixelPerfectPointSampled = false; // obsolete public FilterMode filterMode = FilterMode.Bilinear; public TextureWrapMode wrapMode = TextureWrapMode.Clamp; public bool userDefinedTextureSettings = false; public bool mipmapEnabled = false; public int anisoLevel = 1; public float physicsDepth = 0.1f; public bool disableTrimming = false; public NormalGenerationMode normalGenerationMode = NormalGenerationMode.None; public int padAmount = -1; // default public bool autoUpdate = true; public float editorDisplayScale = 1.0f; public int version = 0; public string assetName = ""; // Fix up upgraded data structures public void Upgrade() { if (version == CURRENT_VERSION) return; Debug.Log("SpriteCollection '" + this.name + "' - Upgraded from version " + version.ToString()); if (version == 0) { if (pixelPerfectPointSampled) filterMode = FilterMode.Point; else filterMode = FilterMode.Bilinear; // don't bother messing about with user settings // on old atlases userDefinedTextureSettings = true; } if (version < 3) { if (textureRefs != null && textureParams != null && textureRefs.Length == textureParams.Length) { for (int i = 0; i < textureRefs.Length; ++i) textureParams[i].texture = textureRefs[i]; textureRefs = null; } } version = CURRENT_VERSION; #if UNITY_EDITOR UnityEditor.EditorUtility.SetDirty(this); #endif } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; namespace System.Globalization { /*=================================ThaiBuddhistCalendar========================== ** ** ThaiBuddhistCalendar is based on Gregorian calendar. Its year value has ** an offset to the Gregorain calendar. ** ** Calendar support range: ** Calendar Minimum Maximum ** ========== ========== ========== ** Gregorian 0001/01/01 9999/12/31 ** Thai 0544/01/01 10542/12/31 ============================================================================*/ [Serializable] [System.Runtime.InteropServices.ComVisible(true)] public class ThaiBuddhistCalendar : Calendar { // Initialize our era info. internal static EraInfo[] thaiBuddhistEraInfo = new EraInfo[] { new EraInfo( 1, 1, 1, 1, -543, 544, GregorianCalendar.MaxYear + 543) // era #, start year/month/day, yearOffset, minEraYear }; // // The era value for the current era. // public const int ThaiBuddhistEra = 1; internal GregorianCalendarHelper helper; [System.Runtime.InteropServices.ComVisible(false)] public override DateTime MinSupportedDateTime { get { return (DateTime.MinValue); } } [System.Runtime.InteropServices.ComVisible(false)] public override DateTime MaxSupportedDateTime { get { return (DateTime.MaxValue); } } [System.Runtime.InteropServices.ComVisible(false)] public override CalendarAlgorithmType AlgorithmType { get { return CalendarAlgorithmType.SolarCalendar; } } public ThaiBuddhistCalendar() { helper = new GregorianCalendarHelper(this, thaiBuddhistEraInfo); } internal override CalendarId ID { get { return (CalendarId.THAI); } } public override DateTime AddMonths(DateTime time, int months) { return (helper.AddMonths(time, months)); } public override DateTime AddYears(DateTime time, int years) { return (helper.AddYears(time, years)); } public override int GetDaysInMonth(int year, int month, int era) { return (helper.GetDaysInMonth(year, month, era)); } public override int GetDaysInYear(int year, int era) { return (helper.GetDaysInYear(year, era)); } public override int GetDayOfMonth(DateTime time) { return (helper.GetDayOfMonth(time)); } public override DayOfWeek GetDayOfWeek(DateTime time) { return (helper.GetDayOfWeek(time)); } public override int GetDayOfYear(DateTime time) { return (helper.GetDayOfYear(time)); } public override int GetMonthsInYear(int year, int era) { return (helper.GetMonthsInYear(year, era)); } [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems. [System.Runtime.InteropServices.ComVisible(false)] public override int GetWeekOfYear(DateTime time, CalendarWeekRule rule, DayOfWeek firstDayOfWeek) { return (helper.GetWeekOfYear(time, rule, firstDayOfWeek)); } public override int GetEra(DateTime time) { return (helper.GetEra(time)); } public override int GetMonth(DateTime time) { return (helper.GetMonth(time)); } public override int GetYear(DateTime time) { return (helper.GetYear(time)); } public override bool IsLeapDay(int year, int month, int day, int era) { return (helper.IsLeapDay(year, month, day, era)); } public override bool IsLeapYear(int year, int era) { return (helper.IsLeapYear(year, era)); } // Returns the leap month in a calendar year of the specified era. This method returns 0 // if this calendar does not have leap month, or this year is not a leap year. // [System.Runtime.InteropServices.ComVisible(false)] public override int GetLeapMonth(int year, int era) { return (helper.GetLeapMonth(year, era)); } public override bool IsLeapMonth(int year, int month, int era) { return (helper.IsLeapMonth(year, month, era)); } public override DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era) { return (helper.ToDateTime(year, month, day, hour, minute, second, millisecond, era)); } public override int[] Eras { get { return (helper.Eras); } } private const int DEFAULT_TWO_DIGIT_YEAR_MAX = 2572; public override int TwoDigitYearMax { get { if (twoDigitYearMax == -1) { twoDigitYearMax = GetSystemTwoDigitYearSetting(ID, DEFAULT_TWO_DIGIT_YEAR_MAX); } return (twoDigitYearMax); } set { VerifyWritable(); if (value < 99 || value > helper.MaxYear) { throw new ArgumentOutOfRangeException( "year", String.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 99, helper.MaxYear)); } twoDigitYearMax = value; } } public override int ToFourDigitYear(int year) { if (year < 0) { throw new ArgumentOutOfRangeException("year", SR.ArgumentOutOfRange_NeedNonNegNum); } Contract.EndContractBlock(); return (helper.ToFourDigitYear(year, this.TwoDigitYearMax)); } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace AzureVmFarmer.Service.Areas.HelpPage.SampleGeneration { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try get sample provided for a specific mediaType, controllerName, actionName and parameterNames. // If not found, try get the sample provided for a specific mediaType, controllerName and actionName regardless of the parameterNames // If still not found, try get the sample provided for a specific type and mediaType if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create one using <see cref="ObjectGenerator"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // Try create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); sampleObject = objectGenerator.GenerateObject(type); } return sampleObject; } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, e.Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
using System; using System.Linq; using NUnit.Framework; using ProtoCore.DSASM; using ProtoCore.DSASM.Mirror; using ProtoCore.Utils; using ProtoFFI; namespace ProtoTest.UtilsTests { [TestFixture] public class ArrayUtilsTest { public ProtoCore.Core core; private ProtoLanguage.CompileStateTracker compileState = null; [SetUp] public void Setup() { Console.WriteLine("Setup"); core = new ProtoCore.Core(new ProtoCore.Options()); core.Executives.Add(ProtoCore.Language.kAssociative, new ProtoAssociative.Executive(core)); core.Executives.Add(ProtoCore.Language.kImperative, new ProtoImperative.Executive(core)); //DLLFFIHandler.Env = ProtoFFI.CPPModuleHelper.GetEnv(); //DLLFFIHandler.Register(FFILanguage.CPlusPlus, new ProtoFFI.PInvokeModuleHelper()); } [Test] public void StackValueDiffTestDefect() { String code = @"[Imperative] { a = 1; b = 1.0; } "; ProtoScript.Runners.ProtoScriptTestRunner fsr = new ProtoScript.Runners.ProtoScriptTestRunner(); ExecutionMirror mirror = fsr.Execute(code, core, out compileState); ProtoCore.DSASM.StackValue svA = mirror.GetRawFirstValue("a"); ProtoCore.DSASM.StackValue svB = mirror.GetRawFirstValue("b"); Assert.IsTrue(svA.metaData.type != svB.metaData.type); } [Test] public void StackValueDiffTestUserDefined() { String code = @" class A { x : var; constructor A() { x = 20; } } [Imperative] { a = A.A(); b = 1.0; } "; ProtoScript.Runners.ProtoScriptTestRunner fsr = new ProtoScript.Runners.ProtoScriptTestRunner(); ExecutionMirror mirror = fsr.Execute(code, core, out compileState); ProtoCore.DSASM.StackValue svA = mirror.GetRawFirstValue("a"); ProtoCore.DSASM.StackValue svB = mirror.GetRawFirstValue("b"); Assert.IsTrue(svA.metaData.type != svB.metaData.type); } [Test] public void StackValueDiffTestProperty01() { String code = @" class A { x : var; constructor A() { x = 20; } } [Imperative] { a = A.A(); b = 1.0; } "; ProtoScript.Runners.ProtoScriptTestRunner fsr = new ProtoScript.Runners.ProtoScriptTestRunner(); ExecutionMirror mirror = fsr.Execute(code, core, out compileState); ProtoCore.DSASM.StackValue svA = mirror.GetRawFirstValue("a"); ProtoCore.DSASM.StackValue svB = mirror.GetRawFirstValue("b"); Assert.IsTrue(svA.metaData.type != svB.metaData.type); } [Test] public void StackValueDiffTestProperty02() { String code = @" class A { x : var; constructor A() { x = 20; } } [Imperative] { a = A.A(); b = a.x; c = 1.0; } "; ProtoScript.Runners.ProtoScriptTestRunner fsr = new ProtoScript.Runners.ProtoScriptTestRunner(); ExecutionMirror mirror = fsr.Execute(code, core, out compileState); ProtoCore.DSASM.StackValue svA = mirror.GetRawFirstValue("b"); ProtoCore.DSASM.StackValue svB = mirror.GetRawFirstValue("c"); Assert.IsTrue(svA.metaData.type != svB.metaData.type); } [Test] public void TestArrayLayerStatsSimple() { String code = @" a;b;c; [Imperative] { a = {1,2,3}; b = {1.0, 2.0, 3.0, 3.0}; c = {1.0, 2.0, 9}; } "; ProtoScript.Runners.ProtoScriptTestRunner fsr = new ProtoScript.Runners.ProtoScriptTestRunner(); ExecutionMirror mirror = fsr.Execute(code, core, out compileState); ProtoCore.DSASM.StackValue svA = mirror.GetRawFirstValue("a"); var dict = ProtoCore.Utils.ArrayUtils.GetTypeStatisticsForLayer(svA, core); Assert.IsTrue(dict[dict.Keys.First()] == 3); ProtoCore.DSASM.StackValue svB = mirror.GetRawFirstValue("b"); var dict2 = ProtoCore.Utils.ArrayUtils.GetTypeStatisticsForLayer(svB, core); Assert.IsTrue(dict2[dict2.Keys.First()] == 4); ProtoCore.DSASM.StackValue svC = mirror.GetRawFirstValue("c"); var dict3 = ProtoCore.Utils.ArrayUtils.GetTypeStatisticsForLayer(svC, core); Assert.IsTrue(dict3[dict3.Keys.First()] == 2); Assert.IsTrue(dict3[dict3.Keys.Last()] == 1); // Assert.IsTrue((Int64)o.Payload == 5); } [Test] public void TestArrayRankSimple() { String code = @"a;b;c;d;e; [Imperative] { a = {1,2,3}; b = {1.0, 2.0, 3.0, 3.0}; c = {1.0, 2.0, 9}; d = {{1}, {1}, {1}}; e = {{1, 2, 3}, {1, 2, 3}, {1, 2, 3}}; } "; ProtoScript.Runners.ProtoScriptTestRunner fsr = new ProtoScript.Runners.ProtoScriptTestRunner(); ExecutionMirror mirror = fsr.Execute(code, core, out compileState); ProtoCore.DSASM.StackValue svA = mirror.GetRawFirstValue("a"); ProtoCore.DSASM.StackValue svB = mirror.GetRawFirstValue("b"); ProtoCore.DSASM.StackValue svC = mirror.GetRawFirstValue("c"); ProtoCore.DSASM.StackValue svD = mirror.GetRawFirstValue("d"); ProtoCore.DSASM.StackValue svE = mirror.GetRawFirstValue("e"); var a = ProtoCore.Utils.ArrayUtils.GetMaxRankForArray(svA, core); Assert.IsTrue(a == 1); var b = ProtoCore.Utils.ArrayUtils.GetMaxRankForArray(svB, core); Assert.IsTrue(b == 1); var c = ProtoCore.Utils.ArrayUtils.GetMaxRankForArray(svC, core); Assert.IsTrue(c == 1); var d = ProtoCore.Utils.ArrayUtils.GetMaxRankForArray(svD, core); Assert.IsTrue(d == 2); var e = ProtoCore.Utils.ArrayUtils.GetMaxRankForArray(svE, core); Assert.IsTrue(e == 2); // Assert.IsTrue((Int64)o.Payload == 5); } [Test] public void TestArrayRankJagged() { String code = @" a;b;c;d;e; [Imperative] { a = {1,{2},3}; b = {1.0, {2.0, 3.0, 3.0}}; c = {1.0, {2.0, {9}}}; d = {{1}, {}, {1}}; e = {{1, 2, 3}, {1, {2}, 3}, {{{1}}, 2, 3}}; } "; ProtoScript.Runners.ProtoScriptTestRunner fsr = new ProtoScript.Runners.ProtoScriptTestRunner(); ExecutionMirror mirror = fsr.Execute(code, core, out compileState); ProtoCore.DSASM.StackValue svA = mirror.GetRawFirstValue("a"); ProtoCore.DSASM.StackValue svB = mirror.GetRawFirstValue("b"); ProtoCore.DSASM.StackValue svC = mirror.GetRawFirstValue("c"); ProtoCore.DSASM.StackValue svD = mirror.GetRawFirstValue("d"); ProtoCore.DSASM.StackValue svE = mirror.GetRawFirstValue("e"); var a = ProtoCore.Utils.ArrayUtils.GetMaxRankForArray(svA, core); Assert.IsTrue(a == 2); var b = ProtoCore.Utils.ArrayUtils.GetMaxRankForArray(svB, core); Assert.IsTrue(b == 2); var c = ProtoCore.Utils.ArrayUtils.GetMaxRankForArray(svC, core); Assert.IsTrue(c == 3); var d = ProtoCore.Utils.ArrayUtils.GetMaxRankForArray(svD, core); Assert.IsTrue(d == 2); var e = ProtoCore.Utils.ArrayUtils.GetMaxRankForArray(svE, core); Assert.IsTrue(e == 4); // Assert.IsTrue((Int64)o.Payload == 5); } [Test] public void TestArrayGetCommonSuperType() { String code = @" class A {} class B extends A {} class C extends B {} tAAA = {A.A(), A.A(), A.A()}; tAAB = {A.A(), A.A(), B.B()}; tAAC = {A.A(), A.A(), C.C()}; tABA = {A.A(), B.B(), A.A()}; tABB = {A.A(), B.B(), B.B()}; tABC = {A.A(), B.B(), C.C()}; tACA = {A.A(), C.C(), A.A()}; tACB = {A.A(), C.C(), B.B()}; tACC = {A.A(), C.C(), C.C()}; //--- tBAA = {B.B(), A.A(), A.A()}; tBAB = {B.B(), A.A(), B.B()}; tBAC = {B.B(), A.A(), C.C()}; tBBA = {B.B(), B.B(), A.A()}; tBBB = {B.B(), B.B(), B.B()}; tBBC = {B.B(), B.B(), C.C()}; tBCA = {B.B(), C.C(), A.A()}; tBCB = {B.B(), C.C(), B.B()}; tBCC = {B.B(), C.C(), C.C()}; //--- tCAA = {C.C(), A.A(), A.A()}; tCAB = {C.C(), A.A(), B.B()}; tCAC = {C.C(), A.A(), C.C()}; tCBA = {C.C(), B.B(), A.A()}; tCBB = {C.C(), B.B(), B.B()}; tCBC = {C.C(), B.B(), C.C()}; tCCA = {C.C(), C.C(), A.A()}; tCCB = {C.C(), C.C(), B.B()}; tCCC = {C.C(), C.C(), C.C()}; "; ProtoScript.Runners.ProtoScriptTestRunner fsr = new ProtoScript.Runners.ProtoScriptTestRunner(); ExecutionMirror mirror = fsr.Execute(code, core, out compileState); StackValue svAAA = mirror.GetRawFirstValue("tAAA"); ClassNode superAAA = ArrayUtils.GetGreatestCommonSubclassForArray(svAAA, core); Assert.IsTrue(superAAA.name == "A"); StackValue svAAB = mirror.GetRawFirstValue("tAAB"); ClassNode superAAB = ArrayUtils.GetGreatestCommonSubclassForArray(svAAB, core); Assert.IsTrue(superAAB.name == "A"); StackValue svAAC = mirror.GetRawFirstValue("tAAC"); ClassNode superAAC = ArrayUtils.GetGreatestCommonSubclassForArray(svAAC, core); Assert.IsTrue(superAAC.name == "A"); StackValue svABA = mirror.GetRawFirstValue("tABA"); ClassNode superABA = ArrayUtils.GetGreatestCommonSubclassForArray(svABA, core); Assert.IsTrue(superABA.name == "A"); StackValue svABB = mirror.GetRawFirstValue("tABB"); ClassNode superABB = ArrayUtils.GetGreatestCommonSubclassForArray(svABB, core); Assert.IsTrue(superABB.name == "A"); StackValue svABC = mirror.GetRawFirstValue("tABC"); ClassNode superABC = ArrayUtils.GetGreatestCommonSubclassForArray(svABC, core); Assert.IsTrue(superABC.name == "A"); StackValue svACA = mirror.GetRawFirstValue("tACA"); ClassNode superACA = ArrayUtils.GetGreatestCommonSubclassForArray(svACA, core); Assert.IsTrue(superACA.name == "A"); StackValue svACB = mirror.GetRawFirstValue("tACB"); ClassNode superACB = ArrayUtils.GetGreatestCommonSubclassForArray(svACB, core); Assert.IsTrue(superACB.name == "A"); StackValue svACC = mirror.GetRawFirstValue("tACC"); ClassNode superACC = ArrayUtils.GetGreatestCommonSubclassForArray(svACC, core); Assert.IsTrue(superACC.name == "A"); //---- StackValue svBAA = mirror.GetRawFirstValue("tBAA"); ClassNode superBAA = ArrayUtils.GetGreatestCommonSubclassForArray(svBAA, core); Assert.IsTrue(superBAA.name == "A"); StackValue svBAB = mirror.GetRawFirstValue("tBAB"); ClassNode superBAB = ArrayUtils.GetGreatestCommonSubclassForArray(svBAB, core); Assert.IsTrue(superBAB.name == "A"); StackValue svBAC = mirror.GetRawFirstValue("tBAC"); ClassNode superBAC = ArrayUtils.GetGreatestCommonSubclassForArray(svBAC, core); Assert.IsTrue(superBAC.name == "A"); StackValue svBBA = mirror.GetRawFirstValue("tBBA"); ClassNode superBBA = ArrayUtils.GetGreatestCommonSubclassForArray(svBBA, core); Assert.IsTrue(superBBA.name == "A"); StackValue svBBB = mirror.GetRawFirstValue("tBBB"); ClassNode superBBB = ArrayUtils.GetGreatestCommonSubclassForArray(svBBB, core); Assert.IsTrue(superBBB.name == "B"); StackValue svBBC = mirror.GetRawFirstValue("tBBC"); ClassNode superBBC = ArrayUtils.GetGreatestCommonSubclassForArray(svBBC, core); Assert.IsTrue(superBBC.name == "B"); StackValue svBCA = mirror.GetRawFirstValue("tBCA"); ClassNode superBCA = ArrayUtils.GetGreatestCommonSubclassForArray(svBCA, core); Assert.IsTrue(superBCA.name == "A"); StackValue svBCB = mirror.GetRawFirstValue("tBCB"); ClassNode superBCB = ArrayUtils.GetGreatestCommonSubclassForArray(svBCB, core); Assert.IsTrue(superBCB.name == "B"); StackValue svBCC = mirror.GetRawFirstValue("tBCC"); ClassNode superBCC = ArrayUtils.GetGreatestCommonSubclassForArray(svBCC, core); Assert.IsTrue(superBCC.name == "B"); //---- StackValue svCAA = mirror.GetRawFirstValue("tCAA"); ClassNode superCAA = ArrayUtils.GetGreatestCommonSubclassForArray(svCAA, core); Assert.IsTrue(superCAA.name == "A"); StackValue svCAB = mirror.GetRawFirstValue("tCAB"); ClassNode superCAB = ArrayUtils.GetGreatestCommonSubclassForArray(svCAB, core); Assert.IsTrue(superCAB.name == "A"); StackValue svCAC = mirror.GetRawFirstValue("tCAC"); ClassNode superCAC = ArrayUtils.GetGreatestCommonSubclassForArray(svCAC, core); Assert.IsTrue(superCAC.name == "A"); StackValue svCBA = mirror.GetRawFirstValue("tCBA"); ClassNode superCBA = ArrayUtils.GetGreatestCommonSubclassForArray(svCBA, core); Assert.IsTrue(superCBA.name == "A"); StackValue svCBB = mirror.GetRawFirstValue("tCBB"); ClassNode superCBB = ArrayUtils.GetGreatestCommonSubclassForArray(svCBB, core); Assert.IsTrue(superCBB.name == "B"); StackValue svCBC = mirror.GetRawFirstValue("tCBC"); ClassNode superCBC = ArrayUtils.GetGreatestCommonSubclassForArray(svCBC, core); Assert.IsTrue(superCBC.name == "B"); StackValue svCCA = mirror.GetRawFirstValue("tCCA"); ClassNode superCCA = ArrayUtils.GetGreatestCommonSubclassForArray(svCCA, core); Assert.IsTrue(superCCA.name == "A"); StackValue svCCB = mirror.GetRawFirstValue("tCCB"); ClassNode superCCB = ArrayUtils.GetGreatestCommonSubclassForArray(svCCB, core); Assert.IsTrue(superCCB.name == "B"); StackValue svCCC = mirror.GetRawFirstValue("tCCC"); ClassNode superCCC = ArrayUtils.GetGreatestCommonSubclassForArray(svCCC, core); Assert.IsTrue(superCCC.name == "C"); } [Test] public void Defect_TestArrayGetCommonSuperType() { String code = @" class A{}; class B extends A{}; class C extends A{}; class D extends C{}; a = A.A(); b = B.B(); c = C.C(); d = D.D(); //ba:A = B.B(); //ca:A = C.C(); //dc:C = D.D(); tABC = { a, b, c }; tABD = { a, b, d }; tACD = { a, c, d }; tBCD = { b, c, d }; tAB = { a, b }; tAD = { a, d }; tBC = { b, c }; tBD = { b, d }; tCD = { c, d }; "; ProtoScript.Runners.ProtoScriptTestRunner fsr = new ProtoScript.Runners.ProtoScriptTestRunner(); ExecutionMirror mirror = fsr.Execute(code, core, out compileState); StackValue svABC = mirror.GetRawFirstValue("tABC"); ClassNode superABC = ArrayUtils.GetGreatestCommonSubclassForArray(svABC, core); Assert.IsTrue(superABC.name == "A"); StackValue svABD = mirror.GetRawFirstValue("tABD"); ClassNode superABD = ArrayUtils.GetGreatestCommonSubclassForArray(svABD, core); Assert.IsTrue(superABD.name == "A"); StackValue svACD = mirror.GetRawFirstValue("tACD"); ClassNode superACD = ArrayUtils.GetGreatestCommonSubclassForArray(svACD, core); Assert.IsTrue(superABD.name == "A"); StackValue svBCD = mirror.GetRawFirstValue("tBCD"); ClassNode superBCD = ArrayUtils.GetGreatestCommonSubclassForArray(svBCD, core); Assert.IsTrue(superBCD.name == "A"); StackValue svAB = mirror.GetRawFirstValue("tAB"); ClassNode superAB = ArrayUtils.GetGreatestCommonSubclassForArray(svAB, core); Assert.IsTrue(superAB.name == "A"); StackValue svAD = mirror.GetRawFirstValue("tAD"); ClassNode superAD = ArrayUtils.GetGreatestCommonSubclassForArray(svAD, core); Assert.IsTrue(superAD.name == "A"); StackValue svBC = mirror.GetRawFirstValue("tBC"); ClassNode superBC = ArrayUtils.GetGreatestCommonSubclassForArray(svBC, core); Assert.IsTrue(superBC.name == "A"); StackValue svBD = mirror.GetRawFirstValue("tBD"); ClassNode superBD = ArrayUtils.GetGreatestCommonSubclassForArray(svBD, core); Assert.IsTrue(superBD.name == "A"); StackValue svCD = mirror.GetRawFirstValue("tCD"); ClassNode superCD = ArrayUtils.GetGreatestCommonSubclassForArray(svCD, core); Assert.IsTrue(superCD.name == "C"); } [Test] [Category("Method Resolution")] public void Defect_TestArrayGetCommonSuperType_2_EmptyArray() { String code = @" class A{}; class B extends A{}; class C extends A{}; class D extends C{}; a = A.A(); ba:A = B.B(); ca:A = C.C(); dc:C = D.D(); tABC = { a, ba, ca }; tABD = { a, ba, dc }; tACD = { a, ca, dc }; tBCD = { ba, ca, dc }; tDD = {dc, D.D()}; tE = {};//empty array "; ProtoScript.Runners.ProtoScriptTestRunner fsr = new ProtoScript.Runners.ProtoScriptTestRunner(); ExecutionMirror mirror = fsr.Execute(code, core, out compileState); StackValue svABC = mirror.GetRawFirstValue("tABC"); ClassNode superABC = ArrayUtils.GetGreatestCommonSubclassForArray(svABC, core); Assert.IsTrue(superABC.name == "A"); StackValue svABD = mirror.GetRawFirstValue("tABD"); ClassNode superABD = ArrayUtils.GetGreatestCommonSubclassForArray(svABD, core); Assert.IsTrue(superABD.name == "A"); StackValue svACD = mirror.GetRawFirstValue("tACD"); ClassNode superACD = ArrayUtils.GetGreatestCommonSubclassForArray(svACD, core); Assert.IsTrue(superABD.name == "A"); StackValue svBCD = mirror.GetRawFirstValue("tBCD"); ClassNode superBCD = ArrayUtils.GetGreatestCommonSubclassForArray(svBCD, core); Assert.IsTrue(superBCD.name == "A"); StackValue svDD = mirror.GetRawFirstValue("tDD"); ClassNode superDD = ArrayUtils.GetGreatestCommonSubclassForArray(svDD, core); Assert.IsTrue(superDD.name == "D"); StackValue svE = mirror.GetRawFirstValue("tE"); ClassNode superE = ArrayUtils.GetGreatestCommonSubclassForArray(svE, core); Assert.IsTrue(superE == null); //Assert.IsTrue(superE.name.Equals("")); } [Test] [Category("Method Resolution")] public void Defect_TestArrayGetCommonSuperType_3() { String code = @" class A{}; class B extends A{}; class C extends B{}; class D extends C{}; class E extends D{}; class F extends A{}; class G{}; class H extends G{}; a = A.A(); b = B.B(); c = C.C(); d = D.D(); e = E.E(); f = F.F(); g = G.G(); h = H.H(); rABCDEF = {a,b,c,d,e,f}; rBCDEF = {b,c,d,e,f}; rBH = {b,h}; "; ProtoScript.Runners.ProtoScriptTestRunner fsr = new ProtoScript.Runners.ProtoScriptTestRunner(); ExecutionMirror mirror = fsr.Execute(code, core, out compileState); StackValue svABCDEF = mirror.GetRawFirstValue("rABCDEF"); ClassNode superABCDEF = ArrayUtils.GetGreatestCommonSubclassForArray(svABCDEF, core); Assert.IsTrue(superABCDEF.name == "A"); StackValue svBCDEF = mirror.GetRawFirstValue("rBCDEF"); ClassNode superBCDEF = ArrayUtils.GetGreatestCommonSubclassForArray(svBCDEF, core); Assert.IsTrue(superBCDEF.name == "A"); StackValue svBH = mirror.GetRawFirstValue("rBH"); ClassNode superBH = ArrayUtils.GetGreatestCommonSubclassForArray(svBH, core); Assert.IsTrue(superBH.name == "var"); } [Test] public void IsArrayTest() { String code = @"a;b;c; [Imperative] { a = {1,2,3}; b = 1; c = a; } "; ProtoScript.Runners.ProtoScriptTestRunner fsr = new ProtoScript.Runners.ProtoScriptTestRunner(); ExecutionMirror mirror = fsr.Execute(code, core, out compileState); ProtoCore.DSASM.StackValue svA = mirror.GetRawFirstValue("a"); ProtoCore.DSASM.StackValue svB = mirror.GetRawFirstValue("b"); ProtoCore.DSASM.StackValue svC = mirror.GetRawFirstValue("c"); Assert.IsTrue(StackUtils.IsArray(svA)); Assert.IsTrue(!StackUtils.IsArray(svB)); Assert.IsTrue(StackUtils.IsArray(svC)); } [Test] public void TestDepthCountOnJaggedArray() { String code = @" a = {1,{{1},{3.1415}},null,1.0,12.3}; b = {1,2,{3}}; x = {{1},{3.1415}}; "; ProtoScript.Runners.ProtoScriptTestRunner fsr = new ProtoScript.Runners.ProtoScriptTestRunner(); ExecutionMirror mirror = fsr.Execute(code, core, out compileState); StackValue a = mirror.GetRawFirstValue("a"); StackValue b = mirror.GetRawFirstValue("b"); StackValue x = mirror.GetRawFirstValue("x"); int rankA = ArrayUtils.GetMaxRankForArray(a, core); Assert.IsTrue(rankA == 3); int rankB = ArrayUtils.GetMaxRankForArray(b, core); Assert.IsTrue(rankB == 2); int rankX = ArrayUtils.GetMaxRankForArray(x, core); Assert.IsTrue(rankX == 2); /* * */ } [Test] public void Defect_OnDepthCount() { String code = @" a = {{3.1415}}; r1 = Contains(a, 3.0); r2 = Contains(a, 3.0); //t = Contains(a, null); "; ProtoScript.Runners.ProtoScriptTestRunner fsr = new ProtoScript.Runners.ProtoScriptTestRunner(); ExecutionMirror mirror = fsr.Execute(code, core, out compileState); StackValue a = mirror.GetRawFirstValue("a"); int rankA = ArrayUtils.GetMaxRankForArray(a, core); Assert.IsTrue(rankA == 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.Diagnostics; namespace System.Runtime.Versioning { [Serializable] public sealed class FrameworkName : IEquatable<FrameworkName> { private readonly string _identifier; private readonly Version _version; private readonly string _profile; private string _fullName; private const char ComponentSeparator = ','; private const char KeyValueSeparator = '='; private const char VersionValuePrefix = 'v'; private const string VersionKey = "Version"; private const string ProfileKey = "Profile"; private static readonly char[] s_componentSplitSeparator = { ComponentSeparator }; public string Identifier { get { Debug.Assert(_identifier != null); return _identifier; } } public Version Version { get { Debug.Assert(_version != null); return _version; } } public string Profile { get { Debug.Assert(_profile != null); return _profile; } } public string FullName { get { if (_fullName == null) { if (string.IsNullOrEmpty(Profile)) { _fullName = Identifier + ComponentSeparator + VersionKey + KeyValueSeparator + VersionValuePrefix + Version.ToString(); } else { _fullName = Identifier + ComponentSeparator + VersionKey + KeyValueSeparator + VersionValuePrefix + Version.ToString() + ComponentSeparator + ProfileKey + KeyValueSeparator + Profile; } } Debug.Assert(_fullName != null); return _fullName; } } public override bool Equals(object obj) { return Equals(obj as FrameworkName); } public bool Equals(FrameworkName other) { if (object.ReferenceEquals(other, null)) { return false; } return Identifier == other.Identifier && Version == other.Version && Profile == other.Profile; } public override int GetHashCode() { return Identifier.GetHashCode() ^ Version.GetHashCode() ^ Profile.GetHashCode(); } public override string ToString() { return FullName; } public FrameworkName(string identifier, Version version) : this(identifier, version, null) { } public FrameworkName(string identifier, Version version, string profile) { if (identifier == null) { throw new ArgumentNullException(nameof(identifier)); } identifier = identifier.Trim(); if (identifier.Length == 0) { throw new ArgumentException(SR.Format(SR.net_emptystringcall, nameof(identifier)), nameof(identifier)); } if (version == null) { throw new ArgumentNullException(nameof(version)); } _identifier = identifier; _version = version; _profile = (profile == null) ? string.Empty : profile.Trim(); } // Parses strings in the following format: "<identifier>, Version=[v|V]<version>, Profile=<profile>" // - The identifier and version is required, profile is optional // - Only three components are allowed. // - The version string must be in the System.Version format; an optional "v" or "V" prefix is allowed public FrameworkName(string frameworkName) { if (frameworkName == null) { throw new ArgumentNullException(nameof(frameworkName)); } if (frameworkName.Length == 0) { throw new ArgumentException(SR.Format(SR.net_emptystringcall, nameof(frameworkName)), nameof(frameworkName)); } string[] components = frameworkName.Split(s_componentSplitSeparator); // Identifier and Version are required, Profile is optional. if (components.Length < 2 || components.Length > 3) { throw new ArgumentException(SR.Argument_FrameworkNameTooShort, nameof(frameworkName)); } // // 1) Parse the "Identifier", which must come first. Trim any whitespace // _identifier = components[0].Trim(); if (_identifier.Length == 0) { throw new ArgumentException(SR.Argument_FrameworkNameInvalid, nameof(frameworkName)); } bool versionFound = false; _profile = string.Empty; // // The required "Version" and optional "Profile" component can be in any order // for (int i = 1; i < components.Length; i++) { // Get the key/value pair separated by '=' string component = components[i]; int separatorIndex = component.IndexOf(KeyValueSeparator); if (separatorIndex == -1 || separatorIndex != component.LastIndexOf(KeyValueSeparator)) { throw new ArgumentException(SR.Argument_FrameworkNameInvalid, nameof(frameworkName)); } // Get the key and value, trimming any whitespace string key = component.Substring(0, separatorIndex).Trim(); string value = component.Substring(separatorIndex + 1).Trim(); // // 2) Parse the required "Version" key value // if (key.Equals(VersionKey, StringComparison.OrdinalIgnoreCase)) { versionFound = true; // Allow the version to include a 'v' or 'V' prefix... if (value.Length > 0 && (value[0] == VersionValuePrefix || value[0] == 'V')) { value = value.Substring(1); } try { _version = new Version(value); } catch (Exception e) { throw new ArgumentException(SR.Argument_FrameworkNameInvalidVersion, nameof(frameworkName), e); } } // // 3) Parse the optional "Profile" key value // else if (key.Equals(ProfileKey, StringComparison.OrdinalIgnoreCase)) { if (!string.IsNullOrEmpty(value)) { _profile = value; } } else { throw new ArgumentException(SR.Argument_FrameworkNameInvalid, nameof(frameworkName)); } } if (!versionFound) { throw new ArgumentException(SR.Argument_FrameworkNameMissingVersion, nameof(frameworkName)); } } public static bool operator ==(FrameworkName left, FrameworkName right) { if (object.ReferenceEquals(left, null)) { return object.ReferenceEquals(right, null); } return left.Equals(right); } public static bool operator !=(FrameworkName left, FrameworkName right) { return !(left == right); } } }
using System; using System.Text; using Org.BouncyCastle.Crypto.Parameters; namespace Org.BouncyCastle.Crypto.Engines { /** * Implementation of Daniel J. Bernstein's Salsa20 stream cipher, Snuffle 2005 */ public class Salsa20Engine : IStreamCipher { /** Constants */ private const int stateSize = 16; // 16, 32 bit ints = 64 bytes private readonly static byte[] sigma = Encoding.ASCII.GetBytes("expand 32-byte k"), tau = Encoding.ASCII.GetBytes("expand 16-byte k"); /* * variables to hold the state of the engine * during encryption and decryption */ private int index = 0; private int[] engineState = new int[stateSize]; // state private int[] x = new int[stateSize] ; // internal buffer private byte[] keyStream = new byte[stateSize * 4], // expanded state, 64 bytes workingKey = null, workingIV = null; private bool initialised = false; /* * internal counter */ private int cW0, cW1, cW2; /** * initialise a Salsa20 cipher. * * @param forEncryption whether or not we are for encryption. * @param params the parameters required to set up the cipher. * @exception ArgumentException if the params argument is * inappropriate. */ public void Init( bool forEncryption, ICipherParameters parameters) { /* * Salsa20 encryption and decryption is completely * symmetrical, so the 'forEncryption' is * irrelevant. (Like 90% of stream ciphers) */ ParametersWithIV ivParams = parameters as ParametersWithIV; if (ivParams == null) throw new ArgumentException("Salsa20 Init requires an IV", "parameters"); byte[] iv = ivParams.GetIV(); if (iv == null || iv.Length != 8) throw new ArgumentException("Salsa20 requires exactly 8 bytes of IV"); KeyParameter key = ivParams.Parameters as KeyParameter; if (key == null) throw new ArgumentException("Salsa20 Init requires a key", "parameters"); workingKey = key.GetKey(); workingIV = iv; setKey(workingKey, workingIV); } public string AlgorithmName { get { return "Salsa20"; } } public byte ReturnByte( byte input) { if (limitExceeded()) { throw new MaxBytesExceededException("2^70 byte limit per IV; Change IV"); } if (index == 0) { salsa20WordToByte(engineState, keyStream); engineState[8]++; if (engineState[8] == 0) { engineState[9]++; } } byte output = (byte)(keyStream[index]^input); index = (index + 1) & 63; return output; } public void ProcessBytes( byte[] inBytes, int inOff, int len, byte[] outBytes, int outOff) { if (!initialised) { throw new InvalidOperationException(AlgorithmName + " not initialised"); } if ((inOff + len) > inBytes.Length) { throw new DataLengthException("input buffer too short"); } if ((outOff + len) > outBytes.Length) { throw new DataLengthException("output buffer too short"); } if (limitExceeded(len)) { throw new MaxBytesExceededException("2^70 byte limit per IV would be exceeded; Change IV"); } for (int i = 0; i < len; i++) { if (index == 0) { salsa20WordToByte(engineState, keyStream); engineState[8]++; if (engineState[8] == 0) { engineState[9]++; } } outBytes[i+outOff] = (byte)(keyStream[index]^inBytes[i+inOff]); index = (index + 1) & 63; } } public void Reset() { setKey(workingKey, workingIV); } // Private implementation private void setKey(byte[] keyBytes, byte[] ivBytes) { workingKey = keyBytes; workingIV = ivBytes; index = 0; resetCounter(); int offset = 0; byte[] constants; // Key engineState[1] = byteToIntLittle(workingKey, 0); engineState[2] = byteToIntLittle(workingKey, 4); engineState[3] = byteToIntLittle(workingKey, 8); engineState[4] = byteToIntLittle(workingKey, 12); if (workingKey.Length == 32) { constants = sigma; offset = 16; } else { constants = tau; } engineState[11] = byteToIntLittle(workingKey, offset); engineState[12] = byteToIntLittle(workingKey, offset+4); engineState[13] = byteToIntLittle(workingKey, offset+8); engineState[14] = byteToIntLittle(workingKey, offset+12); engineState[0 ] = byteToIntLittle(constants, 0); engineState[5 ] = byteToIntLittle(constants, 4); engineState[10] = byteToIntLittle(constants, 8); engineState[15] = byteToIntLittle(constants, 12); // IV engineState[6] = byteToIntLittle(workingIV, 0); engineState[7] = byteToIntLittle(workingIV, 4); engineState[8] = engineState[9] = 0; initialised = true; } /** * Salsa20 function * * @param input input data * * @return keystream */ private void salsa20WordToByte( int[] input, byte[] output) { Array.Copy(input, 0, x, 0, input.Length); for (int i = 0; i < 10; i++) { x[ 4] ^= rotl((x[ 0]+x[12]), 7); x[ 8] ^= rotl((x[ 4]+x[ 0]), 9); x[12] ^= rotl((x[ 8]+x[ 4]),13); x[ 0] ^= rotl((x[12]+x[ 8]),18); x[ 9] ^= rotl((x[ 5]+x[ 1]), 7); x[13] ^= rotl((x[ 9]+x[ 5]), 9); x[ 1] ^= rotl((x[13]+x[ 9]),13); x[ 5] ^= rotl((x[ 1]+x[13]),18); x[14] ^= rotl((x[10]+x[ 6]), 7); x[ 2] ^= rotl((x[14]+x[10]), 9); x[ 6] ^= rotl((x[ 2]+x[14]),13); x[10] ^= rotl((x[ 6]+x[ 2]),18); x[ 3] ^= rotl((x[15]+x[11]), 7); x[ 7] ^= rotl((x[ 3]+x[15]), 9); x[11] ^= rotl((x[ 7]+x[ 3]),13); x[15] ^= rotl((x[11]+x[ 7]),18); x[ 1] ^= rotl((x[ 0]+x[ 3]), 7); x[ 2] ^= rotl((x[ 1]+x[ 0]), 9); x[ 3] ^= rotl((x[ 2]+x[ 1]),13); x[ 0] ^= rotl((x[ 3]+x[ 2]),18); x[ 6] ^= rotl((x[ 5]+x[ 4]), 7); x[ 7] ^= rotl((x[ 6]+x[ 5]), 9); x[ 4] ^= rotl((x[ 7]+x[ 6]),13); x[ 5] ^= rotl((x[ 4]+x[ 7]),18); x[11] ^= rotl((x[10]+x[ 9]), 7); x[ 8] ^= rotl((x[11]+x[10]), 9); x[ 9] ^= rotl((x[ 8]+x[11]),13); x[10] ^= rotl((x[ 9]+x[ 8]),18); x[12] ^= rotl((x[15]+x[14]), 7); x[13] ^= rotl((x[12]+x[15]), 9); x[14] ^= rotl((x[13]+x[12]),13); x[15] ^= rotl((x[14]+x[13]),18); } int offset = 0; for (int i = 0; i < stateSize; i++) { intToByteLittle(x[i] + input[i], output, offset); offset += 4; } for (int i = stateSize; i < x.Length; i++) { intToByteLittle(x[i], output, offset); offset += 4; } } /** * 32 bit word to 4 byte array in little endian order * * @param x value to 'unpack' * * @return value of x expressed as a byte[] array in little endian order */ private byte[] intToByteLittle( int x, byte[] bs, int off) { bs[off] = (byte)x; bs[off + 1] = (byte)(x >> 8); bs[off + 2] = (byte)(x >> 16); bs[off + 3] = (byte)(x >> 24); return bs; } /** * Rotate left * * @param x value to rotate * @param y amount to rotate x * * @return rotated x */ private int rotl( int x, int y) { return (x << y) | ((int)((uint) x >> -y)); } /** * Pack byte[] array into an int in little endian order * * @param x byte array to 'pack' * @param offset only x[offset]..x[offset+3] will be packed * * @return x[offset]..x[offset+3] 'packed' into an int in little-endian order */ private int byteToIntLittle( byte[] x, int offset) { return ((x[offset] & 255)) | ((x[offset + 1] & 255) << 8) | ((x[offset + 2] & 255) << 16) | (x[offset + 3] << 24); } private void resetCounter() { cW0 = 0; cW1 = 0; cW2 = 0; } private bool limitExceeded() { cW0++; if (cW0 == 0) { cW1++; if (cW1 == 0) { cW2++; return (cW2 & 0x20) != 0; // 2^(32 + 32 + 6) } } return false; } /* * this relies on the fact len will always be positive. */ private bool limitExceeded( int len) { if (cW0 >= 0) { cW0 += len; } else { cW0 += len; if (cW0 >= 0) { cW1++; if (cW1 == 0) { cW2++; return (cW2 & 0x20) != 0; // 2^(32 + 32 + 6) } } } return false; } } }
using System; using System.ComponentModel; using System.Drawing; using System.Drawing.Drawing2D; using System.Windows.Forms; namespace WeifenLuo.WinFormsUI.Docking { /// <summary> /// Visual Studio 2012 Light theme. /// </summary> public class VS2012LightTheme : ThemeBase { /// <summary> /// Applies the specified theme to the dock panel. /// </summary> /// <param name="dockPanel">The dock panel.</param> public override void Apply(DockPanel dockPanel) { if (dockPanel == null) { throw new NullReferenceException("dockPanel"); } Measures.SplitterSize = 6; dockPanel.Extender.DockPaneCaptionFactory = new VS2012LightDockPaneCaptionFactory(); dockPanel.Extender.AutoHideStripFactory = new VS2012LightAutoHideStripFactory(); dockPanel.Extender.AutoHideWindowFactory = new VS2012LightAutoHideWindowFactory(); dockPanel.Extender.DockPaneStripFactory = new VS2012LightDockPaneStripFactory(); dockPanel.Extender.DockPaneSplitterControlFactory = new VS2012LightDockPaneSplitterControlFactory(); dockPanel.Extender.DockWindowSplitterControlFactory = new VS2012LightDockWindowSplitterControlFactory(); dockPanel.Extender.DockWindowFactory = new VS2012LightDockWindowFactory(); dockPanel.Extender.PaneIndicatorFactory = new VS2012LightPaneIndicatorFactory(); dockPanel.Extender.PanelIndicatorFactory = new VS2012LightPanelIndicatorFactory(); dockPanel.Extender.DockOutlineFactory = new VS2012LightDockOutlineFactory(); dockPanel.Skin = CreateVisualStudio2012Light(); } private class VS2012LightDockOutlineFactory : DockPanelExtender.IDockOutlineFactory { public DockOutlineBase CreateDockOutline() { return new VS2012LightDockOutline(); } private class VS2012LightDockOutline : DockOutlineBase { public VS2012LightDockOutline() { m_dragForm = new DragForm(); SetDragForm(Rectangle.Empty); DragForm.BackColor = Color.FromArgb(0xff, 91, 173, 255); DragForm.Opacity = 0.5; DragForm.Show(false); } DragForm m_dragForm; private DragForm DragForm { get { return m_dragForm; } } protected override void OnShow() { CalculateRegion(); } protected override void OnClose() { DragForm.Close(); } private void CalculateRegion() { if (SameAsOldValue) return; if (!FloatWindowBounds.IsEmpty) SetOutline(FloatWindowBounds); else if (DockTo is DockPanel) SetOutline(DockTo as DockPanel, Dock, (ContentIndex != 0)); else if (DockTo is DockPane) SetOutline(DockTo as DockPane, Dock, ContentIndex); else SetOutline(); } private void SetOutline() { SetDragForm(Rectangle.Empty); } private void SetOutline(Rectangle floatWindowBounds) { SetDragForm(floatWindowBounds); } private void SetOutline(DockPanel dockPanel, DockStyle dock, bool fullPanelEdge) { Rectangle rect = fullPanelEdge ? dockPanel.DockArea : dockPanel.DocumentWindowBounds; rect.Location = dockPanel.PointToScreen(rect.Location); if (dock == DockStyle.Top) { int height = dockPanel.GetDockWindowSize(DockState.DockTop); rect = new Rectangle(rect.X, rect.Y, rect.Width, height); } else if (dock == DockStyle.Bottom) { int height = dockPanel.GetDockWindowSize(DockState.DockBottom); rect = new Rectangle(rect.X, rect.Bottom - height, rect.Width, height); } else if (dock == DockStyle.Left) { int width = dockPanel.GetDockWindowSize(DockState.DockLeft); rect = new Rectangle(rect.X, rect.Y, width, rect.Height); } else if (dock == DockStyle.Right) { int width = dockPanel.GetDockWindowSize(DockState.DockRight); rect = new Rectangle(rect.Right - width, rect.Y, width, rect.Height); } else if (dock == DockStyle.Fill) { rect = dockPanel.DocumentWindowBounds; rect.Location = dockPanel.PointToScreen(rect.Location); } SetDragForm(rect); } private void SetOutline(DockPane pane, DockStyle dock, int contentIndex) { if (dock != DockStyle.Fill) { Rectangle rect = pane.DisplayingRectangle; if (dock == DockStyle.Right) rect.X += rect.Width / 2; if (dock == DockStyle.Bottom) rect.Y += rect.Height / 2; if (dock == DockStyle.Left || dock == DockStyle.Right) rect.Width -= rect.Width / 2; if (dock == DockStyle.Top || dock == DockStyle.Bottom) rect.Height -= rect.Height / 2; rect.Location = pane.PointToScreen(rect.Location); SetDragForm(rect); } else if (contentIndex == -1) { Rectangle rect = pane.DisplayingRectangle; rect.Location = pane.PointToScreen(rect.Location); SetDragForm(rect); } else { using (GraphicsPath path = pane.TabStripControl.GetOutline(contentIndex)) { RectangleF rectF = path.GetBounds(); Rectangle rect = new Rectangle((int)rectF.X, (int)rectF.Y, (int)rectF.Width, (int)rectF.Height); using (Matrix matrix = new Matrix(rect, new Point[] { new Point(0, 0), new Point(rect.Width, 0), new Point(0, rect.Height) })) { path.Transform(matrix); } Region region = new Region(path); SetDragForm(rect, region); } } } private void SetDragForm(Rectangle rect) { DragForm.Bounds = rect; if (rect == Rectangle.Empty) { if (DragForm.Region != null) { DragForm.Region.Dispose(); } DragForm.Region = new Region(Rectangle.Empty); } else if (DragForm.Region != null) { DragForm.Region.Dispose(); DragForm.Region = null; } } private void SetDragForm(Rectangle rect, Region region) { DragForm.Bounds = rect; if (DragForm.Region != null) { DragForm.Region.Dispose(); } DragForm.Region = region; } } } private class VS2012LightPanelIndicatorFactory : DockPanelExtender.IPanelIndicatorFactory { public DockPanel.IPanelIndicator CreatePanelIndicator(DockStyle style) { return new VS2012LightPanelIndicator(style); } private class VS2012LightPanelIndicator : PictureBox, DockPanel.IPanelIndicator { private static Image _imagePanelLeft = Resources.DockIndicator_PanelLeft_VS2012; private static Image _imagePanelRight = Resources.DockIndicator_PanelRight_VS2012; private static Image _imagePanelTop = Resources.DockIndicator_PanelTop_VS2012; private static Image _imagePanelBottom = Resources.DockIndicator_PanelBottom_VS2012; private static Image _imagePanelFill = Resources.DockIndicator_PanelFill_VS2012; private static Image _imagePanelLeftActive = Resources.DockIndicator_PanelLeft_VS2012; private static Image _imagePanelRightActive = Resources.DockIndicator_PanelRight_VS2012; private static Image _imagePanelTopActive = Resources.DockIndicator_PanelTop_VS2012; private static Image _imagePanelBottomActive = Resources.DockIndicator_PanelBottom_VS2012; private static Image _imagePanelFillActive = Resources.DockIndicator_PanelFill_VS2012; public VS2012LightPanelIndicator(DockStyle dockStyle) { m_dockStyle = dockStyle; SizeMode = PictureBoxSizeMode.AutoSize; Image = ImageInactive; } private DockStyle m_dockStyle; private DockStyle DockStyle { get { return m_dockStyle; } } private DockStyle m_status; public DockStyle Status { get { return m_status; } set { if (value != DockStyle && value != DockStyle.None) throw new InvalidEnumArgumentException(); if (m_status == value) return; m_status = value; IsActivated = (m_status != DockStyle.None); } } private Image ImageInactive { get { if (DockStyle == DockStyle.Left) return _imagePanelLeft; else if (DockStyle == DockStyle.Right) return _imagePanelRight; else if (DockStyle == DockStyle.Top) return _imagePanelTop; else if (DockStyle == DockStyle.Bottom) return _imagePanelBottom; else if (DockStyle == DockStyle.Fill) return _imagePanelFill; else return null; } } private Image ImageActive { get { if (DockStyle == DockStyle.Left) return _imagePanelLeftActive; else if (DockStyle == DockStyle.Right) return _imagePanelRightActive; else if (DockStyle == DockStyle.Top) return _imagePanelTopActive; else if (DockStyle == DockStyle.Bottom) return _imagePanelBottomActive; else if (DockStyle == DockStyle.Fill) return _imagePanelFillActive; else return null; } } private bool m_isActivated = false; private bool IsActivated { get { return m_isActivated; } set { m_isActivated = value; Image = IsActivated ? ImageActive : ImageInactive; } } public DockStyle HitTest(Point pt) { return this.Visible && ClientRectangle.Contains(PointToClient(pt)) ? DockStyle : DockStyle.None; } } } private class VS2012LightPaneIndicatorFactory : DockPanelExtender.IPaneIndicatorFactory { public DockPanel.IPaneIndicator CreatePaneIndicator() { return new VS2012LightPaneIndicator(); } private class VS2012LightPaneIndicator : PictureBox, DockPanel.IPaneIndicator { private static Bitmap _bitmapPaneDiamond = Resources.Dockindicator_PaneDiamond_VS2012; private static Bitmap _bitmapPaneDiamondLeft = Resources.Dockindicator_PaneDiamond_Fill_VS2012; private static Bitmap _bitmapPaneDiamondRight = Resources.Dockindicator_PaneDiamond_Fill_VS2012; private static Bitmap _bitmapPaneDiamondTop = Resources.Dockindicator_PaneDiamond_Fill_VS2012; private static Bitmap _bitmapPaneDiamondBottom = Resources.Dockindicator_PaneDiamond_Fill_VS2012; private static Bitmap _bitmapPaneDiamondFill = Resources.Dockindicator_PaneDiamond_Fill_VS2012; private static Bitmap _bitmapPaneDiamondHotSpot = Resources.Dockindicator_PaneDiamond_Hotspot_VS2012; private static Bitmap _bitmapPaneDiamondHotSpotIndex = Resources.DockIndicator_PaneDiamond_HotspotIndex_VS2012; private static DockPanel.HotSpotIndex[] _hotSpots = new[] { new DockPanel.HotSpotIndex(1, 0, DockStyle.Top), new DockPanel.HotSpotIndex(0, 1, DockStyle.Left), new DockPanel.HotSpotIndex(1, 1, DockStyle.Fill), new DockPanel.HotSpotIndex(2, 1, DockStyle.Right), new DockPanel.HotSpotIndex(1, 2, DockStyle.Bottom) }; private GraphicsPath _displayingGraphicsPath = DrawHelper.CalculateGraphicsPathFromBitmap(_bitmapPaneDiamond); public VS2012LightPaneIndicator() { SizeMode = PictureBoxSizeMode.AutoSize; Image = _bitmapPaneDiamond; Region = new Region(DisplayingGraphicsPath); } public GraphicsPath DisplayingGraphicsPath { get { return _displayingGraphicsPath; } } public DockStyle HitTest(Point pt) { if (!Visible) return DockStyle.None; pt = PointToClient(pt); if (!ClientRectangle.Contains(pt)) return DockStyle.None; for (int i = _hotSpots.GetLowerBound(0); i <= _hotSpots.GetUpperBound(0); i++) { if (_bitmapPaneDiamondHotSpot.GetPixel(pt.X, pt.Y) == _bitmapPaneDiamondHotSpotIndex.GetPixel(_hotSpots[i].X, _hotSpots[i].Y)) return _hotSpots[i].DockStyle; } return DockStyle.None; } private DockStyle m_status = DockStyle.None; public DockStyle Status { get { return m_status; } set { m_status = value; if (m_status == DockStyle.None) Image = _bitmapPaneDiamond; else if (m_status == DockStyle.Left) Image = _bitmapPaneDiamondLeft; else if (m_status == DockStyle.Right) Image = _bitmapPaneDiamondRight; else if (m_status == DockStyle.Top) Image = _bitmapPaneDiamondTop; else if (m_status == DockStyle.Bottom) Image = _bitmapPaneDiamondBottom; else if (m_status == DockStyle.Fill) Image = _bitmapPaneDiamondFill; } } } } private class VS2012LightAutoHideWindowFactory : DockPanelExtender.IAutoHideWindowFactory { public DockPanel.AutoHideWindowControl CreateAutoHideWindow(DockPanel panel) { return new VS2012LightAutoHideWindowControl(panel); } } private class VS2012LightDockPaneSplitterControlFactory : DockPanelExtender.IDockPaneSplitterControlFactory { public DockPane.SplitterControlBase CreateSplitterControl(DockPane pane) { return new VS2012LightSplitterControl(pane); } } private class VS2012LightDockWindowSplitterControlFactory : DockPanelExtender.IDockWindowSplitterControlFactory { public SplitterBase CreateSplitterControl() { return new VS2012LightDockWindow.VS2012LightDockWindowSplitterControl(); } } private class VS2012LightDockPaneStripFactory : DockPanelExtender.IDockPaneStripFactory { public DockPaneStripBase CreateDockPaneStrip(DockPane pane) { return new VS2012LightDockPaneStrip(pane); } } private class VS2012LightAutoHideStripFactory : DockPanelExtender.IAutoHideStripFactory { public AutoHideStripBase CreateAutoHideStrip(DockPanel panel) { return new VS2012LightAutoHideStrip(panel); } } private class VS2012LightDockPaneCaptionFactory : DockPanelExtender.IDockPaneCaptionFactory { public DockPaneCaptionBase CreateDockPaneCaption(DockPane pane) { return new VS2012LightDockPaneCaption(pane); } } private class VS2012LightDockWindowFactory : DockPanelExtender.IDockWindowFactory { public DockWindow CreateDockWindow(DockPanel dockPanel, DockState dockState) { return new VS2012LightDockWindow(dockPanel, dockState); } } public static DockPanelSkin CreateVisualStudio2012Light() { var specialBlue = Color.FromArgb(0xFF, 0x00, 0x7A, 0xCC); var dot = Color.FromArgb(80, 170, 220); var activeTab = specialBlue; var mouseHoverTab = Color.FromArgb(0xFF, 28, 151, 234); var inactiveTab = SystemColors.Control; var lostFocusTab = Color.FromArgb(0xFF, 204, 206, 219); var skin = new DockPanelSkin(); skin.AutoHideStripSkin.DockStripGradient.StartColor = specialBlue; skin.AutoHideStripSkin.DockStripGradient.EndColor = SystemColors.ControlLight; skin.AutoHideStripSkin.TabGradient.TextColor = SystemColors.ControlDarkDark; skin.DockPaneStripSkin.DocumentGradient.DockStripGradient.StartColor = SystemColors.Control; skin.DockPaneStripSkin.DocumentGradient.DockStripGradient.EndColor = SystemColors.Control; skin.DockPaneStripSkin.DocumentGradient.ActiveTabGradient.StartColor = activeTab; skin.DockPaneStripSkin.DocumentGradient.ActiveTabGradient.EndColor = lostFocusTab; skin.DockPaneStripSkin.DocumentGradient.ActiveTabGradient.TextColor = Color.White; skin.DockPaneStripSkin.DocumentGradient.InactiveTabGradient.StartColor = inactiveTab; skin.DockPaneStripSkin.DocumentGradient.InactiveTabGradient.EndColor = mouseHoverTab; skin.DockPaneStripSkin.DocumentGradient.InactiveTabGradient.TextColor = Color.Black; skin.DockPaneStripSkin.ToolWindowGradient.DockStripGradient.StartColor = SystemColors.Control; skin.DockPaneStripSkin.ToolWindowGradient.DockStripGradient.EndColor = SystemColors.Control; skin.DockPaneStripSkin.ToolWindowGradient.ActiveTabGradient.StartColor = SystemColors.ControlLightLight; skin.DockPaneStripSkin.ToolWindowGradient.ActiveTabGradient.EndColor = SystemColors.ControlLightLight; skin.DockPaneStripSkin.ToolWindowGradient.ActiveTabGradient.TextColor = specialBlue; skin.DockPaneStripSkin.ToolWindowGradient.InactiveTabGradient.StartColor = SystemColors.Control; skin.DockPaneStripSkin.ToolWindowGradient.InactiveTabGradient.EndColor = SystemColors.Control; skin.DockPaneStripSkin.ToolWindowGradient.InactiveTabGradient.TextColor = SystemColors.GrayText; skin.DockPaneStripSkin.ToolWindowGradient.ActiveCaptionGradient.StartColor = specialBlue; skin.DockPaneStripSkin.ToolWindowGradient.ActiveCaptionGradient.EndColor = dot; skin.DockPaneStripSkin.ToolWindowGradient.ActiveCaptionGradient.LinearGradientMode = LinearGradientMode.Vertical; skin.DockPaneStripSkin.ToolWindowGradient.ActiveCaptionGradient.TextColor = Color.White; skin.DockPaneStripSkin.ToolWindowGradient.InactiveCaptionGradient.StartColor = SystemColors.Control; skin.DockPaneStripSkin.ToolWindowGradient.InactiveCaptionGradient.EndColor = SystemColors.ControlDark; skin.DockPaneStripSkin.ToolWindowGradient.InactiveCaptionGradient.LinearGradientMode = LinearGradientMode.Vertical; skin.DockPaneStripSkin.ToolWindowGradient.InactiveCaptionGradient.TextColor = SystemColors.GrayText; return skin; } } }
namespace InControl { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.InteropServices; using System.Text; using UnityEngine; using DeviceHandle = System.UInt32; public class NativeInputDeviceManager : InputDeviceManager { public static Func<NativeDeviceInfo, ReadOnlyCollection<NativeInputDevice>, NativeInputDevice> CustomFindDetachedDevice; List<NativeInputDevice> attachedDevices; List<NativeInputDevice> detachedDevices; List<NativeInputDeviceProfile> systemDeviceProfiles; List<NativeInputDeviceProfile> customDeviceProfiles; DeviceHandle[] deviceEvents; public NativeInputDeviceManager() { attachedDevices = new List<NativeInputDevice>(); detachedDevices = new List<NativeInputDevice>(); systemDeviceProfiles = new List<NativeInputDeviceProfile>( NativeInputDeviceProfileList.Profiles.Length ); customDeviceProfiles = new List<NativeInputDeviceProfile>(); deviceEvents = new DeviceHandle[32]; AddSystemDeviceProfiles(); var options = new NativeInputOptions(); options.enableXInput = InputManager.NativeInputEnableXInput; options.preventSleep = InputManager.NativeInputPreventSleep; if (InputManager.NativeInputUpdateRate > 0) { options.updateRate = (UInt16) InputManager.NativeInputUpdateRate; } else { options.updateRate = (UInt16) Mathf.FloorToInt( 1.0f / Time.fixedDeltaTime ); } Native.Init( options ); } public override void Destroy() { Native.Stop(); } UInt32 NextPowerOfTwo( UInt32 x ) { if (x < 0) { return 0; } --x; x |= x >> 1; x |= x >> 2; x |= x >> 4; x |= x >> 8; x |= x >> 16; return x + 1; } public override void Update( ulong updateTick, float deltaTime ) { IntPtr data; var size = Native.GetDeviceEvents( out data ); if (size > 0) { Utility.ArrayExpand( ref deviceEvents, size ); MarshalUtility.Copy( data, deviceEvents, size ); var index = 0; var attachedEventCount = deviceEvents[index++]; for (var i = 0; i < attachedEventCount; i++) { var deviceHandle = deviceEvents[index++]; var stringBuilder = new StringBuilder( 256 ); stringBuilder.Append( "Attached native device with handle " + deviceHandle + ":\n" ); NativeDeviceInfo deviceInfo; if (Native.GetDeviceInfo( deviceHandle, out deviceInfo )) { stringBuilder.AppendFormat( "Name: {0}\n", deviceInfo.name ); stringBuilder.AppendFormat( "Driver Type: {0}\n", deviceInfo.driverType ); stringBuilder.AppendFormat( "Location ID: {0}\n", deviceInfo.location ); stringBuilder.AppendFormat( "Serial Number: {0}\n", deviceInfo.serialNumber ); stringBuilder.AppendFormat( "Vendor ID: 0x{0:x}\n", deviceInfo.vendorID ); stringBuilder.AppendFormat( "Product ID: 0x{0:x}\n", deviceInfo.productID ); stringBuilder.AppendFormat( "Version Number: 0x{0:x}\n", deviceInfo.versionNumber ); stringBuilder.AppendFormat( "Buttons: {0}\n", deviceInfo.numButtons ); stringBuilder.AppendFormat( "Analogs: {0}\n", deviceInfo.numAnalogs ); DetectDevice( deviceHandle, deviceInfo ); } Logger.LogInfo( stringBuilder.ToString() ); } var detachedEventCount = deviceEvents[index++]; for (var i = 0; i < detachedEventCount; i++) { var deviceHandle = deviceEvents[index++]; Logger.LogInfo( "Detached native device with handle " + deviceHandle + ":" ); var device = FindAttachedDevice( deviceHandle ); if (device != null) { DetachDevice( device ); } else { Logger.LogWarning( "Couldn't find device to detach with handle: " + deviceHandle ); } } } /* while (Native.AttachedDeviceQueue.Dequeue( out deviceHandle )) { var stringBuilder = new StringBuilder( 256 ); stringBuilder.Append( "Attached native device with handle " + deviceHandle + ":\n" ); NativeDeviceInfo deviceInfo; if (Native.GetDeviceInfo( deviceHandle, out deviceInfo )) { stringBuilder.AppendFormat( "Name: {0}\n", deviceInfo.name ); stringBuilder.AppendFormat( "Driver Type: {0}\n", deviceInfo.driverType ); stringBuilder.AppendFormat( "Location ID: {0}\n", deviceInfo.location ); stringBuilder.AppendFormat( "Serial Number: {0}\n", deviceInfo.serialNumber ); stringBuilder.AppendFormat( "Vendor ID: 0x{0:x}\n", deviceInfo.vendorID ); stringBuilder.AppendFormat( "Product ID: 0x{0:x}\n", deviceInfo.productID ); stringBuilder.AppendFormat( "Version Number: 0x{0:x}\n", deviceInfo.versionNumber ); stringBuilder.AppendFormat( "Buttons: {0}\n", deviceInfo.numButtons ); stringBuilder.AppendFormat( "Analogs: {0}\n", deviceInfo.numAnalogs ); DetectDevice( deviceHandle, deviceInfo ); } Logger.LogInfo( stringBuilder.ToString() ); } while (Native.DetachedDeviceQueue.Dequeue( out deviceHandle )) { Logger.LogInfo( "Detached native device with handle " + deviceHandle + ":" ); var device = FindAttachedDevice( deviceHandle ); if (device != null) { DetachDevice( device ); } else { Logger.LogWarning( "Couldn't find device to detach with handle: " + deviceHandle ); } } */ } void DetectDevice( DeviceHandle deviceHandle, NativeDeviceInfo deviceInfo ) { // Try to find a matching profile for this device. NativeInputDeviceProfile deviceProfile = null; deviceProfile = deviceProfile ?? customDeviceProfiles.Find( profile => profile.Matches( deviceInfo ) ); deviceProfile = deviceProfile ?? systemDeviceProfiles.Find( profile => profile.Matches( deviceInfo ) ); deviceProfile = deviceProfile ?? customDeviceProfiles.Find( profile => profile.LastResortMatches( deviceInfo ) ); deviceProfile = deviceProfile ?? systemDeviceProfiles.Find( profile => profile.LastResortMatches( deviceInfo ) ); // Find a matching previously attached device or create a new one. var device = FindDetachedDevice( deviceInfo ) ?? new NativeInputDevice(); device.Initialize( deviceHandle, deviceInfo, deviceProfile ); AttachDevice( device ); } void AttachDevice( NativeInputDevice device ) { detachedDevices.Remove( device ); attachedDevices.Add( device ); InputManager.AttachDevice( device ); } void DetachDevice( NativeInputDevice device ) { attachedDevices.Remove( device ); detachedDevices.Add( device ); InputManager.DetachDevice( device ); } NativeInputDevice FindAttachedDevice( DeviceHandle deviceHandle ) { var attachedDevicesCount = attachedDevices.Count; for (var i = 0; i < attachedDevicesCount; i++) { var device = attachedDevices[i]; if (device.Handle == deviceHandle) { return device; } } return null; } NativeInputDevice FindDetachedDevice( NativeDeviceInfo deviceInfo ) { var devices = new ReadOnlyCollection<NativeInputDevice>( detachedDevices ); if (CustomFindDetachedDevice != null) { return CustomFindDetachedDevice( deviceInfo, devices ); } return SystemFindDetachedDevice( deviceInfo, devices ); } static NativeInputDevice SystemFindDetachedDevice( NativeDeviceInfo deviceInfo, ReadOnlyCollection<NativeInputDevice> detachedDevices ) { var detachedDevicesCount = detachedDevices.Count; for (var i = 0; i < detachedDevicesCount; i++) { var device = detachedDevices[i]; if (device.Info.HasSameVendorID( deviceInfo ) && device.Info.HasSameProductID( deviceInfo ) && device.Info.HasSameSerialNumber( deviceInfo )) { return device; } } for (var i = 0; i < detachedDevicesCount; i++) { var device = detachedDevices[i]; if (device.Info.HasSameVendorID( deviceInfo ) && device.Info.HasSameProductID( deviceInfo ) && device.Info.HasSameLocation( deviceInfo )) { return device; } } for (var i = 0; i < detachedDevicesCount; i++) { var device = detachedDevices[i]; if (device.Info.HasSameVendorID( deviceInfo ) && device.Info.HasSameProductID( deviceInfo ) && device.Info.HasSameVersionNumber( deviceInfo )) { return device; } } for (var i = 0; i < detachedDevicesCount; i++) { var device = detachedDevices[i]; if (device.Info.HasSameLocation( deviceInfo )) { return device; } } return null; } void AddSystemDeviceProfile( NativeInputDeviceProfile deviceProfile ) { if (deviceProfile.IsSupportedOnThisPlatform) { systemDeviceProfiles.Add( deviceProfile ); } } void AddSystemDeviceProfiles() { foreach (var typeName in NativeInputDeviceProfileList.Profiles) { var deviceProfile = (NativeInputDeviceProfile) Activator.CreateInstance( Type.GetType( typeName ) ); AddSystemDeviceProfile( deviceProfile ); } } public static bool CheckPlatformSupport( ICollection<string> errors ) { if (Application.platform != RuntimePlatform.OSXPlayer && Application.platform != RuntimePlatform.OSXEditor && Application.platform != RuntimePlatform.WindowsPlayer && Application.platform != RuntimePlatform.WindowsEditor) { errors.Add( "Native input is currently only supported on Windows and Mac." ); return false; } #if UNITY_4_3 || UNITY_4_4 || UNITY_4_5 || UNITY_4_6 || UNITY_4_7 if (!Application.HasProLicense()) { if (errors != null) { errors.Add( "Unity 4 Professional or Unity 5 is required for native input support." ); } return false; } #endif try { NativeVersionInfo versionInfo; Native.GetVersionInfo( out versionInfo ); Logger.LogInfo( "InControl Native (version " + versionInfo.major + "." + versionInfo.minor + "." + versionInfo.patch + ")" ); } catch (DllNotFoundException e) { if (errors != null) { errors.Add( e.Message + Utility.PluginFileExtension() + " could not be found or is missing a dependency." ); } return false; } return true; } internal static bool Enable() { var errors = new List<string>(); if (CheckPlatformSupport( errors )) { InputManager.AddDeviceManager<NativeInputDeviceManager>(); return true; } foreach (var error in errors) { Debug.LogError( "Error enabling NativeInputDeviceManager: " + error ); } return false; } } }
// Copyright 2007-2018 Chris Patterson, Dru Sellers, Travis Smith, et. al. // // 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 MassTransit.RabbitMqTransport.Pipeline { using System; using System.Collections.Concurrent; using System.Linq; using System.Threading.Tasks; using Contexts; using GreenPipes; using GreenPipes.Agents; using GreenPipes.Internals.Extensions; using Logging; using RabbitMQ.Client; using RabbitMQ.Client.Events; using Topology; using Transports; using Transports.Metrics; using Util; /// <summary> /// Receives messages from RabbitMQ, pushing them to the InboundPipe of the service endpoint. /// </summary> public class RabbitMqBasicConsumer : Supervisor, IBasicConsumer, RabbitMqDeliveryMetrics { readonly IDeadLetterTransport _deadLetterTransport; readonly TaskCompletionSource<bool> _deliveryComplete; readonly IErrorTransport _errorTransport; readonly Uri _inputAddress; readonly ILog _log = Logger.Get<RabbitMqBasicConsumer>(); readonly ModelContext _model; readonly ConcurrentDictionary<ulong, RabbitMqReceiveContext> _pending; readonly IReceiveObserver _receiveObserver; readonly IPipe<ReceiveContext> _receivePipe; readonly ReceiveSettings _receiveSettings; readonly RabbitMqReceiveEndpointContext _receiveEndpointContext; readonly IDeliveryTracker _tracker; string _consumerTag; /// <summary> /// The basic consumer receives messages pushed from the broker. /// </summary> /// <param name="model">The model context for the consumer</param> /// <param name="inputAddress">The input address for messages received by the consumer</param> /// <param name="receivePipe">The receive pipe to dispatch messages</param> /// <param name="receiveObserver">The observer for receive events</param> /// <param name="receiveEndpointContext">The topology</param> /// <param name="deadLetterTransport"></param> /// <param name="errorTransport"></param> public RabbitMqBasicConsumer(ModelContext model, Uri inputAddress, IPipe<ReceiveContext> receivePipe, IReceiveObserver receiveObserver, RabbitMqReceiveEndpointContext receiveEndpointContext, IDeadLetterTransport deadLetterTransport, IErrorTransport errorTransport) { _model = model; _inputAddress = inputAddress; _receivePipe = receivePipe; _receiveObserver = receiveObserver; _receiveEndpointContext = receiveEndpointContext; _deadLetterTransport = deadLetterTransport; _errorTransport = errorTransport; _tracker = new DeliveryTracker(HandleDeliveryComplete); _receiveSettings = model.GetPayload<ReceiveSettings>(); _pending = new ConcurrentDictionary<ulong, RabbitMqReceiveContext>(); _deliveryComplete = new TaskCompletionSource<bool>(); } /// <summary> /// Called when the consumer is ready to be delivered messages by the broker /// </summary> /// <param name="consumerTag"></param> void IBasicConsumer.HandleBasicConsumeOk(string consumerTag) { if (_log.IsDebugEnabled) _log.DebugFormat("ConsumerOk: {0} - {1}", _receiveEndpointContext.InputAddress, consumerTag); _consumerTag = consumerTag; SetReady(); } /// <summary> /// Called when the broker has received and acknowledged the BasicCancel, indicating /// that the consumer is requesting to be shut down gracefully. /// </summary> /// <param name="consumerTag">The consumerTag that was shut down.</param> void IBasicConsumer.HandleBasicCancelOk(string consumerTag) { if (_log.IsDebugEnabled) _log.DebugFormat("Consumer Cancel Ok: {0} - {1}", _receiveEndpointContext.InputAddress, consumerTag); _deliveryComplete.TrySetResult(true); SetCompleted(TaskUtil.Completed); } /// <summary> /// Called when the broker cancels the consumer due to an unexpected event, such as a /// queue removal, or other change, that would disconnect the consumer. /// </summary> /// <param name="consumerTag">The consumerTag that is being cancelled.</param> void IBasicConsumer.HandleBasicCancel(string consumerTag) { if (_log.IsDebugEnabled) _log.DebugFormat("Consumer Canceled: {0}", consumerTag); foreach (var context in _pending.Values) context.Cancel(); ConsumerCancelled?.Invoke(this, new ConsumerEventArgs(consumerTag)); _deliveryComplete.TrySetResult(true); SetCompleted(TaskUtil.Completed); } void IBasicConsumer.HandleModelShutdown(object model, ShutdownEventArgs reason) { if (_log.IsDebugEnabled) _log.DebugFormat("Consumer Model Shutdown ({0}), Concurrent Peak: {1}, {2}-{3}", _consumerTag, _tracker.MaxConcurrentDeliveryCount, reason.ReplyCode, reason.ReplyText); _deliveryComplete.TrySetResult(false); SetCompleted(TaskUtil.Completed); } async void IBasicConsumer.HandleBasicDeliver(string consumerTag, ulong deliveryTag, bool redelivered, string exchange, string routingKey, IBasicProperties properties, byte[] body) { if (IsStopping) { await WaitAndAbandonMessage(deliveryTag).ConfigureAwait(false); return; } using (var delivery = _tracker.BeginDelivery()) { var context = new RabbitMqReceiveContext(_inputAddress, exchange, routingKey, _consumerTag, deliveryTag, body, redelivered, properties, _receiveObserver, _receiveEndpointContext); context.GetOrAddPayload(() => _errorTransport); context.GetOrAddPayload(() => _deadLetterTransport); context.GetOrAddPayload(() => _receiveSettings); context.GetOrAddPayload(() => _model); context.GetOrAddPayload(() => _model.ConnectionContext); try { if (!_pending.TryAdd(deliveryTag, context)) if (_log.IsErrorEnabled) _log.ErrorFormat("Duplicate BasicDeliver: {0}", deliveryTag); await _receiveObserver.PreReceive(context).ConfigureAwait(false); await _receivePipe.Send(context).ConfigureAwait(false); await context.CompleteTask.ConfigureAwait(false); _model.BasicAck(deliveryTag, false); await _receiveObserver.PostReceive(context).ConfigureAwait(false); } catch (Exception ex) { await _receiveObserver.ReceiveFault(context, ex).ConfigureAwait(false); try { _model.BasicNack(deliveryTag, false, true); } catch (Exception ackEx) { if (_log.IsErrorEnabled) _log.ErrorFormat("An error occurred trying to NACK a message with delivery tag {0}: {1}", deliveryTag, ackEx.ToString()); } } finally { _pending.TryRemove(deliveryTag, out _); context.Dispose(); } } } IModel IBasicConsumer.Model => _model.Model; public event EventHandler<ConsumerEventArgs> ConsumerCancelled; string RabbitMqDeliveryMetrics.ConsumerTag => _consumerTag; long DeliveryMetrics.DeliveryCount => _tracker.DeliveryCount; int DeliveryMetrics.ConcurrentDeliveryCount => _tracker.MaxConcurrentDeliveryCount; void HandleDeliveryComplete() { if (IsStopping) { if (_log.IsDebugEnabled) _log.DebugFormat("Consumer shutdown completed: {0}", _receiveEndpointContext.InputAddress); _deliveryComplete.TrySetResult(true); } } async Task WaitAndAbandonMessage(ulong deliveryTag) { try { await _deliveryComplete.Task.ConfigureAwait(false); _model.BasicNack(deliveryTag, false, true); } catch (Exception exception) { if (_log.IsErrorEnabled) _log.Debug("Shutting down, nack message faulted: {_topology.InputAddress}", exception); } } protected override async Task StopSupervisor(StopSupervisorContext context) { if (_log.IsDebugEnabled) _log.DebugFormat("Stopping consumer: {0}", _receiveEndpointContext.InputAddress); SetCompleted(ActiveAndActualAgentsCompleted(context)); await Completed.ConfigureAwait(false); } async Task ActiveAndActualAgentsCompleted(StopSupervisorContext context) { await Task.WhenAll(context.Agents.Select(x => Completed)).UntilCompletedOrCanceled(context.CancellationToken).ConfigureAwait(false); if (_tracker.ActiveDeliveryCount > 0) { try { await _deliveryComplete.Task.UntilCompletedOrCanceled(context.CancellationToken).ConfigureAwait(false); } catch (OperationCanceledException) { if (_log.IsWarnEnabled) _log.WarnFormat("Stop canceled waiting for message consumers to complete: {0}", _receiveEndpointContext.InputAddress); } } try { await _model.BasicCancel(_consumerTag).ConfigureAwait(false); } catch (OperationCanceledException) { if (_log.IsWarnEnabled) _log.WarnFormat("Exception canceling the consumer: {0}", _receiveEndpointContext.InputAddress); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; namespace System.Collections.Immutable { /// <content> /// Contains the inner <see cref="ImmutableSortedDictionary{TKey, TValue}.Builder"/> class. /// </content> [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Ignored")] public sealed partial class ImmutableSortedDictionary<TKey, TValue> { /// <summary> /// A sorted dictionary that mutates with little or no memory allocations, /// can produce and/or build on immutable sorted dictionary instances very efficiently. /// </summary> /// <remarks> /// <para> /// This class allows multiple combinations of changes to be made to a set with equal efficiency. /// </para> /// <para> /// Instance members of this class are <em>not</em> thread-safe. /// </para> /// </remarks> [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Ignored")] [SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible", Justification = "Ignored")] [DebuggerDisplay("Count = {Count}")] [DebuggerTypeProxy(typeof(ImmutableSortedDictionaryBuilderDebuggerProxy<,>))] public sealed class Builder : IDictionary<TKey, TValue>, IReadOnlyDictionary<TKey, TValue>, IDictionary { /// <summary> /// The binary tree used to store the contents of the map. Contents are typically not entirely frozen. /// </summary> private Node _root = Node.EmptyNode; /// <summary> /// The key comparer. /// </summary> private IComparer<TKey> _keyComparer = Comparer<TKey>.Default; /// <summary> /// The value comparer. /// </summary> private IEqualityComparer<TValue> _valueComparer = EqualityComparer<TValue>.Default; /// <summary> /// The number of entries in the map. /// </summary> private int _count; /// <summary> /// Caches an immutable instance that represents the current state of the collection. /// </summary> /// <value>Null if no immutable view has been created for the current version.</value> private ImmutableSortedDictionary<TKey, TValue> _immutable; /// <summary> /// A number that increments every time the builder changes its contents. /// </summary> private int _version; /// <summary> /// The object callers may use to synchronize access to this collection. /// </summary> private object _syncRoot; /// <summary> /// Initializes a new instance of the <see cref="Builder"/> class. /// </summary> /// <param name="map">A map to act as the basis for a new map.</param> internal Builder(ImmutableSortedDictionary<TKey, TValue> map) { Requires.NotNull(map, nameof(map)); _root = map._root; _keyComparer = map.KeyComparer; _valueComparer = map.ValueComparer; _count = map.Count; _immutable = map; } #region IDictionary<TKey, TValue> Properties and Indexer /// <summary> /// See <see cref="IDictionary{TKey, TValue}"/> /// </summary> ICollection<TKey> IDictionary<TKey, TValue>.Keys { get { return this.Root.Keys.ToArray(this.Count); } } /// <summary> /// See <see cref="IReadOnlyDictionary{TKey, TValue}"/> /// </summary> public IEnumerable<TKey> Keys { get { return this.Root.Keys; } } /// <summary> /// See <see cref="IDictionary{TKey, TValue}"/> /// </summary> ICollection<TValue> IDictionary<TKey, TValue>.Values { get { return this.Root.Values.ToArray(this.Count); } } /// <summary> /// See <see cref="IReadOnlyDictionary{TKey, TValue}"/> /// </summary> public IEnumerable<TValue> Values { get { return this.Root.Values; } } /// <summary> /// Gets the number of elements in this map. /// </summary> public int Count { get { return _count; } } /// <summary> /// Gets a value indicating whether this instance is read-only. /// </summary> /// <value>Always <c>false</c>.</value> bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly { get { return false; } } #endregion /// <summary> /// Gets the current version of the contents of this builder. /// </summary> internal int Version { get { return _version; } } /// <summary> /// Gets or sets the root node that represents the data in this collection. /// </summary> private Node Root { get { return _root; } set { // We *always* increment the version number because some mutations // may not create a new value of root, although the existing root // instance may have mutated. _version++; if (_root != value) { _root = value; // Clear any cached value for the immutable view since it is now invalidated. _immutable = null; } } } #region IDictionary<TKey, TValue> Indexer /// <summary> /// Gets or sets the value for a given key. /// </summary> /// <param name="key">The key.</param> /// <returns>The value associated with the given key.</returns> public TValue this[TKey key] { get { TValue value; if (this.TryGetValue(key, out value)) { return value; } throw new KeyNotFoundException(SR.Format(SR.Arg_KeyNotFoundWithKey, key.ToString())); } set { bool replacedExistingValue, mutated; this.Root = _root.SetItem(key, value, _keyComparer, _valueComparer, out replacedExistingValue, out mutated); if (mutated && !replacedExistingValue) { _count++; } } } #if FEATURE_ITEMREFAPI /// <summary> /// Returns a read-only reference to the value associated with the provided key. /// </summary> /// <exception cref="KeyNotFoundException">If the key is not present.</exception> public ref readonly TValue ValueRef(TKey key) { Requires.NotNullAllowStructs(key, nameof(key)); return ref _root.ValueRef(key, _keyComparer); } #endif #endregion #region IDictionary Properties /// <summary> /// Gets a value indicating whether the <see cref="IDictionary"/> object has a fixed size. /// </summary> /// <returns>true if the <see cref="IDictionary"/> object has a fixed size; otherwise, false.</returns> bool IDictionary.IsFixedSize { get { return false; } } /// <summary> /// Gets a value indicating whether the <see cref="ICollection{T}"/> is read-only. /// </summary> /// <returns>true if the <see cref="ICollection{T}"/> is read-only; otherwise, false. /// </returns> bool IDictionary.IsReadOnly { get { return false; } } /// <summary> /// Gets an <see cref="ICollection{T}"/> containing the keys of the <see cref="IDictionary{TKey, TValue}"/>. /// </summary> /// <returns> /// An <see cref="ICollection{T}"/> containing the keys of the object that implements <see cref="IDictionary{TKey, TValue}"/>. /// </returns> ICollection IDictionary.Keys { get { return this.Keys.ToArray(this.Count); } } /// <summary> /// Gets an <see cref="ICollection{T}"/> containing the values in the <see cref="IDictionary{TKey, TValue}"/>. /// </summary> /// <returns> /// An <see cref="ICollection{T}"/> containing the values in the object that implements <see cref="IDictionary{TKey, TValue}"/>. /// </returns> ICollection IDictionary.Values { get { return this.Values.ToArray(this.Count); } } #endregion #region ICollection Properties /// <summary> /// Gets an object that can be used to synchronize access to the <see cref="ICollection"/>. /// </summary> /// <returns>An object that can be used to synchronize access to the <see cref="ICollection"/>.</returns> [DebuggerBrowsable(DebuggerBrowsableState.Never)] object ICollection.SyncRoot { get { if (_syncRoot == null) { Threading.Interlocked.CompareExchange<Object>(ref _syncRoot, new Object(), null); } return _syncRoot; } } /// <summary> /// Gets a value indicating whether access to the <see cref="ICollection"/> is synchronized (thread safe). /// </summary> /// <returns>true if access to the <see cref="ICollection"/> is synchronized (thread safe); otherwise, false.</returns> [DebuggerBrowsable(DebuggerBrowsableState.Never)] bool ICollection.IsSynchronized { get { return false; } } /// <summary> /// Gets or sets the key comparer. /// </summary> /// <value> /// The key comparer. /// </value> public IComparer<TKey> KeyComparer { get { return _keyComparer; } set { Requires.NotNull(value, nameof(value)); if (value != _keyComparer) { var newRoot = Node.EmptyNode; int count = 0; foreach (var item in this) { bool mutated; newRoot = newRoot.Add(item.Key, item.Value, value, _valueComparer, out mutated); if (mutated) { count++; } } _keyComparer = value; this.Root = newRoot; _count = count; } } } /// <summary> /// Gets or sets the value comparer. /// </summary> /// <value> /// The value comparer. /// </value> public IEqualityComparer<TValue> ValueComparer { get { return _valueComparer; } set { Requires.NotNull(value, nameof(value)); if (value != _valueComparer) { // When the key comparer is the same but the value comparer is different, we don't need a whole new tree // because the structure of the tree does not depend on the value comparer. // We just need a new root node to store the new value comparer. _valueComparer = value; _immutable = null; // invalidate cached immutable } } } #endregion #region IDictionary Methods /// <summary> /// Adds an element with the provided key and value to the <see cref="IDictionary"/> object. /// </summary> /// <param name="key">The <see cref="object"/> to use as the key of the element to add.</param> /// <param name="value">The <see cref="object"/> to use as the value of the element to add.</param> void IDictionary.Add(object key, object value) { this.Add((TKey)key, (TValue)value); } /// <summary> /// Determines whether the <see cref="IDictionary"/> object contains an element with the specified key. /// </summary> /// <param name="key">The key to locate in the <see cref="IDictionary"/> object.</param> /// <returns> /// true if the <see cref="IDictionary"/> contains an element with the key; otherwise, false. /// </returns> bool IDictionary.Contains(object key) { return this.ContainsKey((TKey)key); } /// <summary> /// Returns an <see cref="IDictionaryEnumerator"/> object for the <see cref="IDictionary"/> object. /// </summary> /// <returns> /// An <see cref="IDictionaryEnumerator"/> object for the <see cref="IDictionary"/> object. /// </returns> IDictionaryEnumerator IDictionary.GetEnumerator() { return new DictionaryEnumerator<TKey, TValue>(this.GetEnumerator()); } /// <summary> /// Removes the element with the specified key from the <see cref="IDictionary"/> object. /// </summary> /// <param name="key">The key of the element to remove.</param> void IDictionary.Remove(object key) { this.Remove((TKey)key); } /// <summary> /// Gets or sets the element with the specified key. /// </summary> /// <param name="key">The key.</param> /// <returns></returns> object IDictionary.this[object key] { get { return this[(TKey)key]; } set { this[(TKey)key] = (TValue)value; } } #endregion #region ICollection methods /// <summary> /// Copies the elements of the <see cref="ICollection"/> to an <see cref="Array"/>, starting at a particular <see cref="Array"/> index. /// </summary> /// <param name="array">The one-dimensional <see cref="Array"/> that is the destination of the elements copied from <see cref="ICollection"/>. The <see cref="Array"/> must have zero-based indexing.</param> /// <param name="index">The zero-based index in <paramref name="array"/> at which copying begins.</param> void ICollection.CopyTo(Array array, int index) { this.Root.CopyTo(array, index, this.Count); } #endregion #region IDictionary<TKey, TValue> Methods /// <summary> /// See <see cref="IDictionary{TKey, TValue}"/> /// </summary> public void Add(TKey key, TValue value) { bool mutated; this.Root = this.Root.Add(key, value, _keyComparer, _valueComparer, out mutated); if (mutated) { _count++; } } /// <summary> /// See <see cref="IDictionary{TKey, TValue}"/> /// </summary> public bool ContainsKey(TKey key) { return this.Root.ContainsKey(key, _keyComparer); } /// <summary> /// See <see cref="IDictionary{TKey, TValue}"/> /// </summary> public bool Remove(TKey key) { bool mutated; this.Root = this.Root.Remove(key, _keyComparer, out mutated); if (mutated) { _count--; } return mutated; } /// <summary> /// See <see cref="IDictionary{TKey, TValue}"/> /// </summary> public bool TryGetValue(TKey key, out TValue value) { return this.Root.TryGetValue(key, _keyComparer, out value); } /// <summary> /// See the <see cref="IImmutableDictionary{TKey, TValue}"/> interface. /// </summary> public bool TryGetKey(TKey equalKey, out TKey actualKey) { Requires.NotNullAllowStructs(equalKey, nameof(equalKey)); return this.Root.TryGetKey(equalKey, _keyComparer, out actualKey); } /// <summary> /// See <see cref="IDictionary{TKey, TValue}"/> /// </summary> public void Add(KeyValuePair<TKey, TValue> item) { this.Add(item.Key, item.Value); } /// <summary> /// See <see cref="IDictionary{TKey, TValue}"/> /// </summary> public void Clear() { this.Root = ImmutableSortedDictionary<TKey, TValue>.Node.EmptyNode; _count = 0; } /// <summary> /// See <see cref="IDictionary{TKey, TValue}"/> /// </summary> public bool Contains(KeyValuePair<TKey, TValue> item) { return this.Root.Contains(item, _keyComparer, _valueComparer); } /// <summary> /// See <see cref="IDictionary{TKey, TValue}"/> /// </summary> void ICollection<KeyValuePair<TKey, TValue>>.CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex) { this.Root.CopyTo(array, arrayIndex, this.Count); } /// <summary> /// See <see cref="IDictionary{TKey, TValue}"/> /// </summary> public bool Remove(KeyValuePair<TKey, TValue> item) { if (this.Contains(item)) { return this.Remove(item.Key); } return false; } /// <summary> /// See <see cref="IDictionary{TKey, TValue}"/> /// </summary> public ImmutableSortedDictionary<TKey, TValue>.Enumerator GetEnumerator() { return this.Root.GetEnumerator(this); } /// <summary> /// See <see cref="IDictionary{TKey, TValue}"/> /// </summary> IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator() { return this.GetEnumerator(); } /// <summary> /// See <see cref="IDictionary{TKey, TValue}"/> /// </summary> IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); } #endregion #region Public methods /// <summary> /// Determines whether the <see cref="ImmutableSortedDictionary{TKey, TValue}"/> /// contains an element with the specified value. /// </summary> /// <param name="value"> /// The value to locate in the <see cref="ImmutableSortedDictionary{TKey, TValue}"/>. /// The value can be null for reference types. /// </param> /// <returns> /// true if the <see cref="ImmutableSortedDictionary{TKey, TValue}"/> contains /// an element with the specified value; otherwise, false. /// </returns> [Pure] public bool ContainsValue(TValue value) { return _root.ContainsValue(value, _valueComparer); } /// <summary> /// Removes any entries from the dictionaries with keys that match those found in the specified sequence. /// </summary> /// <param name="items">The keys for entries to remove from the dictionary.</param> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")] public void AddRange(IEnumerable<KeyValuePair<TKey, TValue>> items) { Requires.NotNull(items, nameof(items)); foreach (var pair in items) { this.Add(pair); } } /// <summary> /// Removes any entries from the dictionaries with keys that match those found in the specified sequence. /// </summary> /// <param name="keys">The keys for entries to remove from the dictionary.</param> public void RemoveRange(IEnumerable<TKey> keys) { Requires.NotNull(keys, nameof(keys)); foreach (var key in keys) { this.Remove(key); } } /// <summary> /// Gets the value for a given key if a matching key exists in the dictionary. /// </summary> /// <param name="key">The key to search for.</param> /// <returns>The value for the key, or the default value for type <typeparamref name="TValue"/> if no matching key was found.</returns> [Pure] public TValue GetValueOrDefault(TKey key) { return this.GetValueOrDefault(key, default(TValue)); } /// <summary> /// Gets the value for a given key if a matching key exists in the dictionary. /// </summary> /// <param name="key">The key to search for.</param> /// <param name="defaultValue">The default value to return if no matching key is found in the dictionary.</param> /// <returns> /// The value for the key, or <paramref name="defaultValue"/> if no matching key was found. /// </returns> [Pure] public TValue GetValueOrDefault(TKey key, TValue defaultValue) { Requires.NotNullAllowStructs(key, nameof(key)); TValue value; if (this.TryGetValue(key, out value)) { return value; } return defaultValue; } /// <summary> /// Creates an immutable sorted dictionary based on the contents of this instance. /// </summary> /// <returns>An immutable map.</returns> /// <remarks> /// This method is an O(n) operation, and approaches O(1) time as the number of /// actual mutations to the set since the last call to this method approaches 0. /// </remarks> public ImmutableSortedDictionary<TKey, TValue> ToImmutable() { // Creating an instance of ImmutableSortedMap<T> with our root node automatically freezes our tree, // ensuring that the returned instance is immutable. Any further mutations made to this builder // will clone (and unfreeze) the spine of modified nodes until the next time this method is invoked. if (_immutable == null) { _immutable = Wrap(this.Root, _count, _keyComparer, _valueComparer); } return _immutable; } #endregion } } /// <summary> /// A simple view of the immutable collection that the debugger can show to the developer. /// </summary> internal class ImmutableSortedDictionaryBuilderDebuggerProxy<TKey, TValue> { /// <summary> /// The collection to be enumerated. /// </summary> private readonly ImmutableSortedDictionary<TKey, TValue>.Builder _map; /// <summary> /// The simple view of the collection. /// </summary> private KeyValuePair<TKey, TValue>[] _contents; /// <summary> /// Initializes a new instance of the <see cref="ImmutableSortedDictionaryBuilderDebuggerProxy{TKey, TValue}"/> class. /// </summary> /// <param name="map">The collection to display in the debugger</param> public ImmutableSortedDictionaryBuilderDebuggerProxy(ImmutableSortedDictionary<TKey, TValue>.Builder map) { Requires.NotNull(map, nameof(map)); _map = map; } /// <summary> /// Gets a simple debugger-viewable collection. /// </summary> [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public KeyValuePair<TKey, TValue>[] Contents { get { if (_contents == null) { _contents = _map.ToArray(_map.Count); } return _contents; } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Diagnostics; using System.Net.Sockets; using System.Runtime.InteropServices; using System.Text; namespace System.Net { internal static partial class NameResolutionPal { private static SocketError GetSocketErrorForErrno(int errno) { switch (errno) { case 0: return SocketError.Success; case (int)Interop.Sys.GetHostErrorCodes.HOST_NOT_FOUND: return SocketError.HostNotFound; case (int)Interop.Sys.GetHostErrorCodes.NO_DATA: return SocketError.NoData; case (int)Interop.Sys.GetHostErrorCodes.NO_RECOVERY: return SocketError.NoRecovery; case (int)Interop.Sys.GetHostErrorCodes.TRY_AGAIN: return SocketError.TryAgain; default: Debug.Fail("Unexpected errno: " + errno.ToString()); return SocketError.SocketError; } } private static SocketError GetSocketErrorForNativeError(int error) { switch (error) { case 0: return SocketError.Success; case (int)Interop.Sys.GetAddrInfoErrorFlags.EAI_AGAIN: return SocketError.TryAgain; case (int)Interop.Sys.GetAddrInfoErrorFlags.EAI_BADFLAGS: return SocketError.InvalidArgument; case (int)Interop.Sys.GetAddrInfoErrorFlags.EAI_FAIL: return SocketError.NoRecovery; case (int)Interop.Sys.GetAddrInfoErrorFlags.EAI_FAMILY: return SocketError.AddressFamilyNotSupported; case (int)Interop.Sys.GetAddrInfoErrorFlags.EAI_NONAME: return SocketError.HostNotFound; default: Debug.Fail("Unexpected error: " + error.ToString()); return SocketError.SocketError; } } private static unsafe IPHostEntry CreateHostEntry(Interop.libc.hostent* hostent) { string hostName = null; if (hostent->h_name != null) { hostName = Marshal.PtrToStringAnsi((IntPtr)hostent->h_name); } int numAddresses; for (numAddresses = 0; hostent->h_addr_list[numAddresses] != null; numAddresses++) { } IPAddress[] ipAddresses; if (numAddresses == 0) { ipAddresses = Array.Empty<IPAddress>(); } else { ipAddresses = new IPAddress[numAddresses]; for (int i = 0; i < numAddresses; i++) { Debug.Assert(hostent->h_addr_list[i] != null); ipAddresses[i] = new IPAddress(*(int*)hostent->h_addr_list[i]); } } int numAliases; for (numAliases = 0; hostent->h_aliases[numAliases] != null; numAliases++) { } string[] aliases; if (numAliases == 0) { aliases = Array.Empty<string>(); } else { aliases = new string[numAliases]; for (int i = 0; i < numAliases; i++) { Debug.Assert(hostent->h_aliases[i] != null); aliases[i] = Marshal.PtrToStringAnsi((IntPtr)hostent->h_aliases[i]); } } return new IPHostEntry { HostName = hostName, AddressList = ipAddresses, Aliases = aliases }; } public static unsafe SocketError TryGetAddrInfo(string name, out IPHostEntry hostinfo, out int nativeErrorCode) { Interop.Sys.HostEntry* entry = null; int result = Interop.Sys.GetHostEntriesForName(name, &entry); if (result != 0) { hostinfo = NameResolutionUtilities.GetUnresolvedAnswer(name); nativeErrorCode = result; return GetSocketErrorForNativeError(result); } try { string canonicalName = Marshal.PtrToStringAnsi((IntPtr)entry->CanonicalName); hostinfo = new IPHostEntry { HostName = string.IsNullOrEmpty(canonicalName) ? name : canonicalName, Aliases = Array.Empty<string>(), AddressList = new IPAddress[entry->Count] }; // Clean this up when fixing #3570 var buffer = new byte[SocketAddressPal.IPv6AddressSize]; for (int i = 0; i < entry->Count; i++) { SocketAddress sockaddr; IPEndPoint factory; int bufferLength; if (entry->Addresses[i].IsIpv6) { sockaddr = new SocketAddress(AddressFamily.InterNetworkV6); factory = IPEndPointStatics.IPv6Any; bufferLength = SocketAddressPal.IPv6AddressSize; SocketAddressPal.SetAddressFamily(buffer, AddressFamily.InterNetworkV6); SocketAddressPal.SetIPv6Address(buffer, entry->Addresses[i].Address, entry->Addresses[i].Count, 0); SocketAddressPal.SetPort(buffer, 0); } else { sockaddr = new SocketAddress(AddressFamily.InterNetwork); factory = IPEndPointStatics.Any; bufferLength = SocketAddressPal.IPv4AddressSize; SocketAddressPal.SetAddressFamily(buffer, AddressFamily.InterNetwork); SocketAddressPal.SetIPv4Address(buffer, entry->Addresses[i].Address); SocketAddressPal.SetPort(buffer, 0); } for (int d = 0; d < bufferLength; d++) { sockaddr[d] = buffer[d]; } hostinfo.AddressList[i] = ((IPEndPoint)factory.Create(sockaddr)).Address; } } finally { Interop.Sys.FreeHostEntriesForName(entry); } nativeErrorCode = 0; return SocketError.Success; } public static unsafe string TryGetNameInfo(IPAddress addr, out SocketError socketError, out int nativeErrorCode) { byte* buffer = stackalloc byte[Interop.Sys.NI_MAXHOST + 1 /*for null*/]; // TODO #2891: Remove the copying step to improve performance. This requires a change in the contracts. byte[] addressBuffer = addr.GetAddressBytes(); int error; fixed (byte* rawAddress = addressBuffer) { error = Interop.Sys.GetNameInfo( rawAddress, unchecked((uint)addressBuffer.Length), addr.AddressFamily == AddressFamily.InterNetworkV6, buffer, Interop.Sys.NI_MAXHOST, null, 0, Interop.Sys.GetNameInfoFlags.NI_NAMEREQD); } socketError = GetSocketErrorForNativeError(error); nativeErrorCode = error; return socketError != SocketError.Success ? null : Marshal.PtrToStringAnsi((IntPtr)buffer); } public static string GetHostName() { return Interop.Sys.GetHostName(); } public static void EnsureSocketsAreInitialized() { // No-op for Unix. } } }
// 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.Net.Security; using System.Runtime.CompilerServices; using System.Security.Authentication; using System.Security.Cryptography.X509Certificates; using System.Threading; using System.Threading.Tasks; using CURLAUTH = Interop.Http.CURLAUTH; using CURLcode = Interop.Http.CURLcode; using CURLMcode = Interop.Http.CURLMcode; using CURLoption = Interop.Http.CURLoption; namespace System.Net.Http { // Object model: // ------------- // CurlHandler provides an HttpMessageHandler implementation that wraps libcurl. The core processing for CurlHandler // is handled via a CurlHandler.MultiAgent instance, where currently a CurlHandler instance stores and uses a single // MultiAgent for the lifetime of the handler (with the MultiAgent lazily initialized on first use, so that it can // be initialized with all of the configured options on the handler). The MultiAgent is named as such because it wraps // a libcurl multi handle that's responsible for handling all requests on the instance. When a request arrives, it's // queued to the MultiAgent, which ensures that a thread is running to continually loop and process all work associated // with the multi handle until no more work is required; at that point, the thread is retired until more work arrives, // at which point another thread will be spun up. Any number of requests will have their handling multiplexed onto // this one event loop thread. Each request is represented by a CurlHandler.EasyRequest, so named because it wraps // a libcurl easy handle, libcurl's representation of a request. The EasyRequest stores all state associated with // the request, including the CurlHandler.CurlResponseMessage and CurlHandler.CurlResponseStream that are handed // back to the caller to provide access to the HTTP response information. // // Lifetime: // --------- // The MultiAgent is initialized on first use and is kept referenced by the CurlHandler for the remainder of the // handler's lifetime. Both are disposable, and disposing of the CurlHandler will dispose of the MultiAgent. // However, libcurl is not thread safe in that two threads can't be using the same multi or easy handles concurrently, // so any interaction with the multi handle must happen on the MultiAgent's thread. For this reason, the // SafeHandle storing the underlying multi handle has its ref count incremented when the MultiAgent worker is running // and decremented when it stops running, enabling any disposal requests to be delayed until the worker has quiesced. // To enable that to happen quickly when a dispose operation occurs, an "incoming request" (how all other threads // communicate with the MultiAgent worker) is queued to the worker to request a shutdown; upon receiving that request, // the worker will exit and allow the multi handle to be disposed of. // // An EasyRequest itself doesn't govern its own lifetime. Since an easy handle is added to a multi handle for // the multi handle to process, the easy handle must not be destroyed until after it's been removed from the multi handle. // As such, once the SafeHandle for an easy handle is created, although its stored in the EasyRequest instance, // it's also stored into a dictionary on the MultiAgent and has its ref count incremented to prevent it from being // disposed of while it's in use by the multi handle. // // When a request is made to the CurlHandler, callbacks are registered with libcurl, including state that will // be passed back into managed code and used to identify the associated EasyRequest. This means that the native // code needs to be able both to keep the EasyRequest alive and to refer to it using an IntPtr. For this, we // use a GCHandle to the EasyRequest. However, the native code needs to be able to refer to the EasyRequest for the // lifetime of the request, but we also need to avoid keeping the EasyRequest (and all state it references) alive artificially. // For the beginning phase of the request, the native code may be the only thing referencing the managed objects, since // when a caller invokes "Task<HttpResponseMessage> SendAsync(...)", there's nothing handed back to the caller that represents // the request until at least the HTTP response headers are received and the returned Task is completed with the response // message object. However, after that point, if the caller drops the HttpResponseMessage, we also want to cancel and // dispose of the associated state, which means something needs to be finalizable and not kept rooted while at the same // time still allowing the native code to continue using its GCHandle and lookup the associated state as long as it's alive. // Yet then when an async read is made on the response message, we want to postpone such finalization and ensure that the async // read can be appropriately completed with control and reference ownership given back to the reader. As such, we do two things: // we make the response stream finalizable, and we make the GCHandle be to a wrapper object for the EasyRequest rather than to // the EasyRequest itself. That wrapper object maintains a weak reference to the EasyRequest as well as sometimes maintaining // a strong reference. When the request starts out, the GCHandle is created to the wrapper, which has a strong reference to // the EasyRequest (which also back references to the wrapper so that the wrapper can be accessed via it). The GCHandle is // thus keeping the EasyRequest and all of the state it references alive, e.g. the CurlResponseStream, which itself has a reference // back to the EasyRequest. Once the request progresses to the point of receiving HTTP response headers and the HttpResponseMessage // is handed back to the caller, the wrapper object drops its strong reference and maintains only a weak reference. At this // point, if the caller were to drop its HttpResponseMessage object, that would also drop the only strong reference to the // CurlResponseStream; the CurlResponseStream would be available for collection and finalization, and its finalization would // request cancellation of the easy request to the multi agent. The multi agent would then in response remove the easy handle // from the multi handle and decrement the ref count on the SafeHandle for the easy handle, allowing it to be finalized and // the underlying easy handle released. If instead of dropping the HttpResponseMessage the caller makes a read request on the // response stream, the wrapper object is transitioned back to having a strong reference, so that even if the caller then drops // the HttpResponseMessage, the read Task returned from the read operation will still be completed eventually, at which point // the wrapper will transition back to being a weak reference. // // Even with that, of course, Dispose is still the recommended way of cleaning things up. Disposing the CurlResponseMessage // will Dispose the CurlResponseStream, which will Dispose of the SafeHandle for the easy handle and request that the MultiAgent // cancel the operation. Once canceled and removed, the SafeHandle will have its ref count decremented and the previous disposal // will proceed to release the underlying handle. internal partial class CurlHandler : HttpMessageHandler { #region Constants private const char SpaceChar = ' '; private const int StatusCodeLength = 3; private const string UriSchemeHttp = "http"; private const string UriSchemeHttps = "https"; private const string EncodingNameGzip = "gzip"; private const string EncodingNameDeflate = "deflate"; private const int MaxRequestBufferSize = 16384; // Default used by libcurl private const string NoTransferEncoding = HttpKnownHeaderNames.TransferEncoding + ":"; private const string NoContentType = HttpKnownHeaderNames.ContentType + ":"; private const string NoExpect = HttpKnownHeaderNames.Expect + ":"; private const int CurlAge = 5; private const int MinCurlAge = 3; #endregion #region Fields private static readonly KeyValuePair<string,CURLAUTH>[] s_orderedAuthTypes = new KeyValuePair<string, CURLAUTH>[] { new KeyValuePair<string,CURLAUTH>("Negotiate", CURLAUTH.Negotiate), new KeyValuePair<string,CURLAUTH>("NTLM", CURLAUTH.NTLM), new KeyValuePair<string,CURLAUTH>("Digest", CURLAUTH.Digest), new KeyValuePair<string,CURLAUTH>("Basic", CURLAUTH.Basic), }; // Max timeout value used by WinHttp handler, so mapping to that here. private static readonly TimeSpan s_maxTimeout = TimeSpan.FromMilliseconds(int.MaxValue); private static readonly char[] s_newLineCharArray = new char[] { HttpRuleParser.CR, HttpRuleParser.LF }; private static readonly bool s_supportsAutomaticDecompression; private static readonly bool s_supportsSSL; private static readonly bool s_supportsHttp2Multiplexing; private static string s_curlVersionDescription; private static string s_curlSslVersionDescription; private readonly MultiAgent _agent; private volatile bool _anyOperationStarted; private volatile bool _disposed; private IWebProxy _proxy = null; private ICredentials _serverCredentials = null; private bool _useProxy = HttpHandlerDefaults.DefaultUseProxy; private ICredentials _defaultProxyCredentials = null; private DecompressionMethods _automaticDecompression = HttpHandlerDefaults.DefaultAutomaticDecompression; private bool _preAuthenticate = HttpHandlerDefaults.DefaultPreAuthenticate; private CredentialCache _credentialCache = null; // protected by LockObject private bool _useDefaultCredentials = HttpHandlerDefaults.DefaultUseDefaultCredentials; private CookieContainer _cookieContainer = new CookieContainer(); private bool _useCookies = HttpHandlerDefaults.DefaultUseCookies; private TimeSpan _connectTimeout = Timeout.InfiniteTimeSpan; private bool _automaticRedirection = HttpHandlerDefaults.DefaultAutomaticRedirection; private int _maxAutomaticRedirections = HttpHandlerDefaults.DefaultMaxAutomaticRedirections; private int _maxConnectionsPerServer = HttpHandlerDefaults.DefaultMaxConnectionsPerServer; private int _maxResponseHeadersLength = HttpHandlerDefaults.DefaultMaxResponseHeadersLength; private ClientCertificateOption _clientCertificateOption = HttpHandlerDefaults.DefaultClientCertificateOption; private X509Certificate2Collection _clientCertificates; private Func<HttpRequestMessage, X509Certificate2, X509Chain, SslPolicyErrors, bool> _serverCertificateValidationCallback; private bool _checkCertificateRevocationList = HttpHandlerDefaults.DefaultCheckCertificateRevocationList; private SslProtocols _sslProtocols = SslProtocols.None; // use default private IDictionary<String, Object> _properties; // Only create dictionary when required. private object LockObject { get { return _agent; } } #endregion static CurlHandler() { // curl_global_init call handled by Interop.LibCurl's cctor Interop.Http.CurlFeatures features = Interop.Http.GetSupportedFeatures(); s_supportsSSL = (features & Interop.Http.CurlFeatures.CURL_VERSION_SSL) != 0; s_supportsAutomaticDecompression = (features & Interop.Http.CurlFeatures.CURL_VERSION_LIBZ) != 0; s_supportsHttp2Multiplexing = (features & Interop.Http.CurlFeatures.CURL_VERSION_HTTP2) != 0 && Interop.Http.GetSupportsHttp2Multiplexing(); if (NetEventSource.IsEnabled) { EventSourceTrace($"libcurl: {CurlVersionDescription} {CurlSslVersionDescription} {features}"); } } public CurlHandler() { _agent = new MultiAgent(this); } #region Properties private static string CurlVersionDescription => s_curlVersionDescription ?? (s_curlVersionDescription = Interop.Http.GetVersionDescription() ?? string.Empty); private static string CurlSslVersionDescription => s_curlSslVersionDescription ?? (s_curlSslVersionDescription = Interop.Http.GetSslVersionDescription() ?? string.Empty); internal bool AllowAutoRedirect { get { return _automaticRedirection; } set { CheckDisposedOrStarted(); _automaticRedirection = value; } } internal bool SupportsProxy => true; internal bool SupportsRedirectConfiguration => true; internal bool UseProxy { get { return _useProxy; } set { CheckDisposedOrStarted(); _useProxy = value; } } internal IWebProxy Proxy { get { return _proxy; } set { CheckDisposedOrStarted(); _proxy = value; } } internal ICredentials DefaultProxyCredentials { get { return _defaultProxyCredentials; } set { CheckDisposedOrStarted(); _defaultProxyCredentials = value; } } internal ICredentials Credentials { get { return _serverCredentials; } set { _serverCredentials = value; } } internal ClientCertificateOption ClientCertificateOptions { get { return _clientCertificateOption; } set { if (value != ClientCertificateOption.Manual && value != ClientCertificateOption.Automatic) { throw new ArgumentOutOfRangeException(nameof(value)); } CheckDisposedOrStarted(); _clientCertificateOption = value; } } internal X509Certificate2Collection ClientCertificates { get { if (_clientCertificateOption != ClientCertificateOption.Manual) { throw new InvalidOperationException(SR.Format(SR.net_http_invalid_enable_first, nameof(ClientCertificateOptions), nameof(ClientCertificateOption.Manual))); } return _clientCertificates ?? (_clientCertificates = new X509Certificate2Collection()); } } internal Func<HttpRequestMessage, X509Certificate2, X509Chain, SslPolicyErrors, bool> ServerCertificateCustomValidationCallback { get { return _serverCertificateValidationCallback; } set { CheckDisposedOrStarted(); _serverCertificateValidationCallback = value; } } internal bool CheckCertificateRevocationList { get { return _checkCertificateRevocationList; } set { CheckDisposedOrStarted(); _checkCertificateRevocationList = value; } } internal SslProtocols SslProtocols { get { return _sslProtocols; } set { SecurityProtocol.ThrowOnNotAllowed(value, allowNone: true); CheckDisposedOrStarted(); _sslProtocols = value; } } internal bool SupportsAutomaticDecompression => s_supportsAutomaticDecompression; internal DecompressionMethods AutomaticDecompression { get { return _automaticDecompression; } set { CheckDisposedOrStarted(); _automaticDecompression = value; } } internal bool PreAuthenticate { get { return _preAuthenticate; } set { CheckDisposedOrStarted(); _preAuthenticate = value; if (value && _credentialCache == null) { _credentialCache = new CredentialCache(); } } } internal bool UseCookies { get { return _useCookies; } set { CheckDisposedOrStarted(); _useCookies = value; } } internal CookieContainer CookieContainer { get { return _cookieContainer; } set { CheckDisposedOrStarted(); _cookieContainer = value; } } internal int MaxAutomaticRedirections { get { return _maxAutomaticRedirections; } set { if (value <= 0) { throw new ArgumentOutOfRangeException(nameof(value), value, SR.Format(SR.net_http_value_must_be_greater_than, 0)); } CheckDisposedOrStarted(); _maxAutomaticRedirections = value; } } internal int MaxConnectionsPerServer { get { return _maxConnectionsPerServer; } set { if (value < 1) { throw new ArgumentOutOfRangeException(nameof(value), value, SR.Format(SR.net_http_value_must_be_greater_than, 0)); } CheckDisposedOrStarted(); _maxConnectionsPerServer = value; } } internal int MaxResponseHeadersLength { get { return _maxResponseHeadersLength; } set { if (value <= 0) { throw new ArgumentOutOfRangeException(nameof(value), value, SR.Format(SR.net_http_value_must_be_greater_than, 0)); } CheckDisposedOrStarted(); _maxResponseHeadersLength = value; } } internal bool UseDefaultCredentials { get { return _useDefaultCredentials; } set { CheckDisposedOrStarted(); _useDefaultCredentials = value; } } public IDictionary<string, object> Properties { get { if (_properties == null) { _properties = new Dictionary<String, object>(); } return _properties; } } #endregion protected override void Dispose(bool disposing) { _disposed = true; if (disposing) { _agent.Dispose(); } base.Dispose(disposing); } protected internal override Task<HttpResponseMessage> SendAsync( HttpRequestMessage request, CancellationToken cancellationToken) { if (request == null) { throw new ArgumentNullException(nameof(request), SR.net_http_handler_norequest); } if (request.RequestUri.Scheme == UriSchemeHttps) { if (!s_supportsSSL) { throw new PlatformNotSupportedException(SR.Format(SR.net_http_unix_https_support_unavailable_libcurl, CurlVersionDescription)); } } else { Debug.Assert(request.RequestUri.Scheme == UriSchemeHttp, "HttpClient expected to validate scheme as http or https."); } if (request.Headers.TransferEncodingChunked.GetValueOrDefault() && (request.Content == null)) { throw new InvalidOperationException(SR.net_http_chunked_not_allowed_with_empty_content); } if (_useCookies && _cookieContainer == null) { throw new InvalidOperationException(SR.net_http_invalid_cookiecontainer); } CheckDisposed(); SetOperationStarted(); // Do an initial cancellation check to avoid initiating the async operation if // cancellation has already been requested. After this, we'll rely on CancellationToken.Register // to notify us of cancellation requests and shut down the operation if possible. if (cancellationToken.IsCancellationRequested) { return Task.FromCanceled<HttpResponseMessage>(cancellationToken); } // Create the easy request. This associates the easy request with this handler and configures // it based on the settings configured for the handler. var easy = new EasyRequest(this, _agent, request, cancellationToken); try { EventSourceTrace("{0}", request, easy: easy); _agent.Queue(new MultiAgent.IncomingRequest { Easy = easy, Type = MultiAgent.IncomingRequestType.New }); } catch (Exception exc) { easy.CleanupAndFailRequest(exc); } return easy.Task; } #region Private methods private void SetOperationStarted() { if (!_anyOperationStarted) { _anyOperationStarted = true; } } private KeyValuePair<NetworkCredential, CURLAUTH> GetCredentials(Uri requestUri) { // If preauthentication is enabled, we may have populated our internal credential cache, // so first check there to see if we have any credentials for this uri. if (_preAuthenticate) { KeyValuePair<NetworkCredential, CURLAUTH> ncAndScheme; lock (LockObject) { Debug.Assert(_credentialCache != null, "Expected non-null credential cache"); ncAndScheme = GetCredentials(requestUri, _credentialCache, s_orderedAuthTypes); } if (ncAndScheme.Key != null) { return ncAndScheme; } } // We either weren't preauthenticating or we didn't have any cached credentials // available, so check the credentials on the handler. return GetCredentials(requestUri, _serverCredentials, s_orderedAuthTypes); } private void TransferCredentialsToCache(Uri serverUri, CURLAUTH serverAuthAvail) { if (_serverCredentials == null) { // No credentials, nothing to put into the cache. return; } lock (LockObject) { // For each auth type we allow, check whether it's one supported by the server. KeyValuePair<string, CURLAUTH>[] validAuthTypes = s_orderedAuthTypes; for (int i = 0; i < validAuthTypes.Length; i++) { // Is it supported by the server? if ((serverAuthAvail & validAuthTypes[i].Value) != 0) { // And do we have a credential for it? NetworkCredential nc = _serverCredentials.GetCredential(serverUri, validAuthTypes[i].Key); if (nc != null) { // We have a credential for it, so add it, and we're done. Debug.Assert(_credentialCache != null, "Expected non-null credential cache"); try { _credentialCache.Add(serverUri, validAuthTypes[i].Key, nc); } catch (ArgumentException) { // Ignore the case of key already present } break; } } } } } private void AddResponseCookies(EasyRequest state, string cookieHeader) { if (!_useCookies) { return; } try { _cookieContainer.SetCookies(state._requestMessage.RequestUri, cookieHeader); state.SetCookieOption(state._requestMessage.RequestUri); } catch (CookieException e) { EventSourceTrace( "Malformed cookie parsing failed: {0}, server: {1}, cookie: {2}", e.Message, state._requestMessage.RequestUri, cookieHeader, easy: state); } } private static KeyValuePair<NetworkCredential, CURLAUTH> GetCredentials(Uri requestUri, ICredentials credentials, KeyValuePair<string, CURLAUTH>[] validAuthTypes) { NetworkCredential nc = null; CURLAUTH curlAuthScheme = CURLAUTH.None; if (credentials != null) { // For each auth type we consider valid, try to get a credential for it. // Union together the auth types for which we could get credentials, but validate // that the found credentials are all the same, as libcurl doesn't support differentiating // by auth type. for (int i = 0; i < validAuthTypes.Length; i++) { NetworkCredential networkCredential = credentials.GetCredential(requestUri, validAuthTypes[i].Key); if (networkCredential != null) { curlAuthScheme |= validAuthTypes[i].Value; if (nc == null) { nc = networkCredential; } else if(!AreEqualNetworkCredentials(nc, networkCredential)) { throw new PlatformNotSupportedException(SR.Format(SR.net_http_unix_invalid_credential, CurlVersionDescription)); } } } } EventSourceTrace("Authentication scheme: {0}", curlAuthScheme); return new KeyValuePair<NetworkCredential, CURLAUTH>(nc, curlAuthScheme); ; } private void CheckDisposed() { if (_disposed) { throw new ObjectDisposedException(GetType().FullName); } } private void CheckDisposedOrStarted() { CheckDisposed(); if (_anyOperationStarted) { throw new InvalidOperationException(SR.net_http_operation_started); } } private static void ThrowIfCURLEError(CURLcode error) { if (error != CURLcode.CURLE_OK) // success { string msg = CurlException.GetCurlErrorString((int)error, isMulti: false); EventSourceTrace(msg); switch (error) { case CURLcode.CURLE_OPERATION_TIMEDOUT: throw new OperationCanceledException(msg); case CURLcode.CURLE_OUT_OF_MEMORY: throw new OutOfMemoryException(msg); case CURLcode.CURLE_SEND_FAIL_REWIND: throw new InvalidOperationException(msg); default: throw new CurlException((int)error, msg); } } } private static void ThrowIfCURLMError(CURLMcode error) { if (error != CURLMcode.CURLM_OK && // success error != CURLMcode.CURLM_CALL_MULTI_PERFORM) // success + a hint to try curl_multi_perform again { string msg = CurlException.GetCurlErrorString((int)error, isMulti: true); EventSourceTrace(msg); switch (error) { case CURLMcode.CURLM_ADDED_ALREADY: case CURLMcode.CURLM_BAD_EASY_HANDLE: case CURLMcode.CURLM_BAD_HANDLE: case CURLMcode.CURLM_BAD_SOCKET: throw new ArgumentException(msg); case CURLMcode.CURLM_UNKNOWN_OPTION: throw new ArgumentOutOfRangeException(msg); case CURLMcode.CURLM_OUT_OF_MEMORY: throw new OutOfMemoryException(msg); case CURLMcode.CURLM_INTERNAL_ERROR: default: throw new CurlException((int)error, msg); } } } private static bool AreEqualNetworkCredentials(NetworkCredential credential1, NetworkCredential credential2) { Debug.Assert(credential1 != null && credential2 != null, "arguments are non-null in network equality check"); return credential1.UserName == credential2.UserName && credential1.Domain == credential2.Domain && string.Equals(credential1.Password, credential2.Password, StringComparison.Ordinal); } // PERF NOTE: // These generic overloads of EventSourceTrace (and similar wrapper methods in some of the other CurlHandler // nested types) exist to allow call sites to call EventSourceTrace without boxing and without checking // NetEventSource.IsEnabled. Do not remove these without fixing the call sites accordingly. private static void EventSourceTrace<TArg0>( string formatMessage, TArg0 arg0, MultiAgent agent = null, EasyRequest easy = null, [CallerMemberName] string memberName = null) { if (NetEventSource.IsEnabled) { EventSourceTraceCore(string.Format(formatMessage, arg0), agent, easy, memberName); } } private static void EventSourceTrace<TArg0, TArg1, TArg2> (string formatMessage, TArg0 arg0, TArg1 arg1, TArg2 arg2, MultiAgent agent = null, EasyRequest easy = null, [CallerMemberName] string memberName = null) { if (NetEventSource.IsEnabled) { EventSourceTraceCore(string.Format(formatMessage, arg0, arg1, arg2), agent, easy, memberName); } } private static void EventSourceTrace( string message, MultiAgent agent = null, EasyRequest easy = null, [CallerMemberName] string memberName = null) { if (NetEventSource.IsEnabled) { EventSourceTraceCore(message, agent, easy, memberName); } } private static void EventSourceTraceCore(string message, MultiAgent agent, EasyRequest easy, string memberName) { // If we weren't handed a multi agent, see if we can get one from the EasyRequest if (agent == null && easy != null) { agent = easy._associatedMultiAgent; } NetEventSource.Log.HandlerMessage( agent?.GetHashCode() ?? 0, (agent?.RunningWorkerId).GetValueOrDefault(), easy?.Task.Id ?? 0, memberName, message); } private static HttpRequestException CreateHttpRequestException(Exception inner) { return new HttpRequestException(SR.net_http_client_execution_error, inner); } private static IOException MapToReadWriteIOException(Exception error, bool isRead) { return new IOException( isRead ? SR.net_http_io_read : SR.net_http_io_write, error is HttpRequestException && error.InnerException != null ? error.InnerException : error); } private static void SetChunkedModeForSend(HttpRequestMessage request) { bool chunkedMode = request.Headers.TransferEncodingChunked.GetValueOrDefault(); HttpContent requestContent = request.Content; Debug.Assert(requestContent != null, "request is null"); // Deal with conflict between 'Content-Length' vs. 'Transfer-Encoding: chunked' semantics. // libcurl adds a Transfer-Encoding header by default and the request fails if both are set. if (requestContent.Headers.ContentLength.HasValue) { if (chunkedMode) { // Same behaviour as WinHttpHandler requestContent.Headers.ContentLength = null; } else { // Prevent libcurl from adding Transfer-Encoding header request.Headers.TransferEncodingChunked = false; } } else if (!chunkedMode) { // Make sure Transfer-Encoding: chunked header is set, // as we have content to send but no known length for it. request.Headers.TransferEncodingChunked = true; } } #endregion } }
using J2N; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; namespace YAF.Lucene.Net.Search { /* * 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 ArrayUtil = YAF.Lucene.Net.Util.ArrayUtil; /// <summary> /// A <see cref="Scorer"/> for OR like queries, counterpart of <see cref="ConjunctionScorer"/>. /// This <see cref="Scorer"/> implements <see cref="DocIdSetIterator.Advance(int)"/> and uses Advance() on the given <see cref="Scorer"/>s. /// <para/> /// This implementation uses the minimumMatch constraint actively to efficiently /// prune the number of candidates, it is hence a mixture between a pure <see cref="DisjunctionScorer"/> /// and a <see cref="ConjunctionScorer"/>. /// </summary> internal class MinShouldMatchSumScorer : Scorer { /// <summary> /// The overall number of non-finalized scorers </summary> private int numScorers; /// <summary> /// The minimum number of scorers that should match </summary> private readonly int mm; /// <summary> /// A static array of all subscorers sorted by decreasing cost </summary> private readonly Scorer[] sortedSubScorers; /// <summary> /// A monotonically increasing index into the array pointing to the next subscorer that is to be excluded </summary> private int sortedSubScorersIdx = 0; private readonly Scorer[] subScorers; // the first numScorers-(mm-1) entries are valid private int nrInHeap; // 0..(numScorers-(mm-1)-1) /// <summary> /// mmStack is supposed to contain the most costly subScorers that still did /// not run out of docs, sorted by increasing sparsity of docs returned by that subScorer. /// For now, the cost of subscorers is assumed to be inversely correlated with sparsity. /// </summary> private readonly Scorer[] mmStack; // of size mm-1: 0..mm-2, always full /// <summary> /// The document number of the current match. </summary> private int doc = -1; /// <summary> /// The number of subscorers that provide the current match. </summary> protected int m_nrMatchers = -1; private double score = float.NaN; /// <summary> /// Construct a <see cref="MinShouldMatchSumScorer"/>. /// </summary> /// <param name="weight"> The weight to be used. </param> /// <param name="subScorers"> A collection of at least two subscorers. </param> /// <param name="minimumNrMatchers"> The positive minimum number of subscorers that should /// match to match this query. /// <para/>When <paramref name="minimumNrMatchers"/> is bigger than /// the number of <paramref name="subScorers"/>, no matches will be produced. /// <para/>When <paramref name="minimumNrMatchers"/> equals the number of <paramref name="subScorers"/>, /// it is more efficient to use <see cref="ConjunctionScorer"/>. </param> public MinShouldMatchSumScorer(Weight weight, IList<Scorer> subScorers, int minimumNrMatchers) : base(weight) { this.nrInHeap = this.numScorers = subScorers.Count; if (minimumNrMatchers <= 0) { throw new System.ArgumentException("Minimum nr of matchers must be positive"); } if (numScorers <= 1) { throw new System.ArgumentException("There must be at least 2 subScorers"); } this.mm = minimumNrMatchers; this.sortedSubScorers = subScorers.ToArray(); // sorting by decreasing subscorer cost should be inversely correlated with // next docid (assuming costs are due to generating many postings) ArrayUtil.TimSort(sortedSubScorers, new ComparerAnonymousInnerClassHelper(this)); // take mm-1 most costly subscorers aside this.mmStack = new Scorer[mm - 1]; for (int i = 0; i < mm - 1; i++) { mmStack[i] = sortedSubScorers[i]; } nrInHeap -= mm - 1; this.sortedSubScorersIdx = mm - 1; // take remaining into heap, if any, and heapify this.subScorers = new Scorer[nrInHeap]; for (int i = 0; i < nrInHeap; i++) { this.subScorers[i] = this.sortedSubScorers[mm - 1 + i]; } MinheapHeapify(); Debug.Assert(MinheapCheck()); } private class ComparerAnonymousInnerClassHelper : IComparer<Scorer> { private readonly MinShouldMatchSumScorer outerInstance; public ComparerAnonymousInnerClassHelper(MinShouldMatchSumScorer outerInstance) { this.outerInstance = outerInstance; } public virtual int Compare(Scorer o1, Scorer o2) { return (o2.GetCost() - o1.GetCost()).Signum(); } } /// <summary> /// Construct a <see cref="DisjunctionScorer"/>, using one as the minimum number /// of matching <paramref name="subScorers"/>. /// </summary> public MinShouldMatchSumScorer(Weight weight, IList<Scorer> subScorers) : this(weight, subScorers, 1) { } public override sealed ICollection<ChildScorer> GetChildren() { List<ChildScorer> children = new List<ChildScorer>(numScorers); for (int i = 0; i < numScorers; i++) { children.Add(new ChildScorer(subScorers[i], "SHOULD")); } return children; } public override int NextDoc() { Debug.Assert(doc != NO_MORE_DOCS); while (true) { // to remove current doc, call next() on all subScorers on current doc within heap while (subScorers[0].DocID == doc) { if (subScorers[0].NextDoc() != NO_MORE_DOCS) { MinheapSiftDown(0); } else { MinheapRemoveRoot(); numScorers--; if (numScorers < mm) { return doc = NO_MORE_DOCS; } } //assert minheapCheck(); } EvaluateSmallestDocInHeap(); if (m_nrMatchers >= mm) // doc satisfies mm constraint { break; } } return doc; } private void EvaluateSmallestDocInHeap() { // within heap, subScorer[0] now contains the next candidate doc doc = subScorers[0].DocID; if (doc == NO_MORE_DOCS) { m_nrMatchers = int.MaxValue; // stop looping return; } // 1. score and count number of matching subScorers within heap score = subScorers[0].GetScore(); m_nrMatchers = 1; CountMatches(1); CountMatches(2); // 2. score and count number of matching subScorers within stack, // short-circuit: stop when mm can't be reached for current doc, then perform on heap next() // TODO instead advance() might be possible, but complicates things for (int i = mm - 2; i >= 0; i--) // first advance sparsest subScorer { if (mmStack[i].DocID >= doc || mmStack[i].Advance(doc) != NO_MORE_DOCS) { if (mmStack[i].DocID == doc) // either it was already on doc, or got there via advance() { m_nrMatchers++; score += mmStack[i].GetScore(); } // scorer advanced to next after doc, check if enough scorers left for current doc else { if (m_nrMatchers + i < mm) // too few subScorers left, abort advancing { return; // continue looping TODO consider advance() here } } } // subScorer exhausted else { numScorers--; if (numScorers < mm) // too few subScorers left { doc = NO_MORE_DOCS; m_nrMatchers = int.MaxValue; // stop looping return; } if (mm - 2 - i > 0) { // shift RHS of array left Array.Copy(mmStack, i + 1, mmStack, i, mm - 2 - i); } // find next most costly subScorer within heap TODO can this be done better? while (!MinheapRemove(sortedSubScorers[sortedSubScorersIdx++])) { //assert minheapCheck(); } // add the subScorer removed from heap to stack mmStack[mm - 2] = sortedSubScorers[sortedSubScorersIdx - 1]; if (m_nrMatchers + i < mm) // too few subScorers left, abort advancing { return; // continue looping TODO consider advance() here } } } } // TODO: this currently scores, but so did the previous impl // TODO: remove recursion. // TODO: consider separating scoring out of here, then modify this // and afterNext() to terminate when nrMatchers == minimumNrMatchers // then also change freq() to just always compute it from scratch private void CountMatches(int root) { if (root < nrInHeap && subScorers[root].DocID == doc) { m_nrMatchers++; score += subScorers[root].GetScore(); CountMatches((root << 1) + 1); CountMatches((root << 1) + 2); } } /// <summary> /// Returns the score of the current document matching the query. Initially /// invalid, until <see cref="NextDoc()"/> is called the first time. /// </summary> public override float GetScore() { return (float)score; } public override int DocID { get { return doc; } } public override int Freq { get { return m_nrMatchers; } } /// <summary> /// Advances to the first match beyond the current whose document number is /// greater than or equal to a given target. /// <para/> /// The implementation uses the Advance() method on the subscorers. /// </summary> /// <param name="target"> The target document number. </param> /// <returns> The document whose number is greater than or equal to the given /// target, or -1 if none exist. </returns> public override int Advance(int target) { if (numScorers < mm) { return doc = NO_MORE_DOCS; } // advance all Scorers in heap at smaller docs to at least target while (subScorers[0].DocID < target) { if (subScorers[0].Advance(target) != NO_MORE_DOCS) { MinheapSiftDown(0); } else { MinheapRemoveRoot(); numScorers--; if (numScorers < mm) { return doc = NO_MORE_DOCS; } } //assert minheapCheck(); } EvaluateSmallestDocInHeap(); if (m_nrMatchers >= mm) { return doc; } else { return NextDoc(); } } public override long GetCost() { // cost for merging of lists analog to DisjunctionSumScorer long costCandidateGeneration = 0; for (int i = 0; i < nrInHeap; i++) { costCandidateGeneration += subScorers[i].GetCost(); } // TODO is cost for advance() different to cost for iteration + heap merge // and how do they compare overall to pure disjunctions? const float c1 = 1.0f, c2 = 1.0f; // maybe a constant, maybe a proportion between costCandidateGeneration and sum(subScorer_to_be_advanced.cost())? return (long)(c1 * costCandidateGeneration + c2 * costCandidateGeneration * (mm - 1)); // advance() cost - heap-merge cost } /// <summary> /// Organize <see cref="subScorers"/> into a min heap with scorers generating the earliest document on top. /// </summary> protected void MinheapHeapify() { for (int i = (nrInHeap >> 1) - 1; i >= 0; i--) { MinheapSiftDown(i); } } /// <summary> /// The subtree of <see cref="subScorers"/> at root is a min heap except possibly for its root element. /// Bubble the root down as required to make the subtree a heap. /// </summary> protected void MinheapSiftDown(int root) { // TODO could this implementation also move rather than swapping neighbours? Scorer scorer = subScorers[root]; int doc = scorer.DocID; int i = root; while (i <= (nrInHeap >> 1) - 1) { int lchild = (i << 1) + 1; Scorer lscorer = subScorers[lchild]; int ldoc = lscorer.DocID; int rdoc = int.MaxValue, rchild = (i << 1) + 2; Scorer rscorer = null; if (rchild < nrInHeap) { rscorer = subScorers[rchild]; rdoc = rscorer.DocID; } if (ldoc < doc) { if (rdoc < ldoc) { subScorers[i] = rscorer; subScorers[rchild] = scorer; i = rchild; } else { subScorers[i] = lscorer; subScorers[lchild] = scorer; i = lchild; } } else if (rdoc < doc) { subScorers[i] = rscorer; subScorers[rchild] = scorer; i = rchild; } else { return; } } } protected void MinheapSiftUp(int i) { Scorer scorer = subScorers[i]; int doc = scorer.DocID; // find right place for scorer while (i > 0) { int parent = (i - 1) >> 1; Scorer pscorer = subScorers[parent]; int pdoc = pscorer.DocID; if (pdoc > doc) // move root down, make space { subScorers[i] = subScorers[parent]; i = parent; } // done, found right place else { break; } } subScorers[i] = scorer; } /// <summary> /// Remove the root <see cref="Scorer"/> from <see cref="subScorers"/> and re-establish it as a heap /// </summary> protected void MinheapRemoveRoot() { if (nrInHeap == 1) { //subScorers[0] = null; // not necessary nrInHeap = 0; } else { nrInHeap--; subScorers[0] = subScorers[nrInHeap]; //subScorers[nrInHeap] = null; // not necessary MinheapSiftDown(0); } } /// <summary> /// Removes a given <see cref="Scorer"/> from the heap by placing end of heap at that /// position and bubbling it either up or down /// </summary> protected bool MinheapRemove(Scorer scorer) { // find scorer: O(nrInHeap) for (int i = 0; i < nrInHeap; i++) { if (subScorers[i] == scorer) // remove scorer { subScorers[i] = subScorers[--nrInHeap]; //if (i != nrInHeap) subScorers[nrInHeap] = null; // not necessary MinheapSiftUp(i); MinheapSiftDown(i); return true; } } return false; // scorer already exhausted } internal virtual bool MinheapCheck() { return MinheapCheck(0); } private bool MinheapCheck(int root) { if (root >= nrInHeap) { return true; } int lchild = (root << 1) + 1; int rchild = (root << 1) + 2; if (lchild < nrInHeap && subScorers[root].DocID > subScorers[lchild].DocID) { return false; } if (rchild < nrInHeap && subScorers[root].DocID > subScorers[rchild].DocID) { return false; } return MinheapCheck(lchild) && MinheapCheck(rchild); } } }
using System; using System.Data; using System.Linq; using System.Linq.Expressions; using System.Threading.Tasks; namespace MicroOrm.Dapper.Repositories { /// <summary> /// Base Repository /// </summary> public partial class ReadOnlyDapperRepository<TEntity> where TEntity : class { /// <inheritdoc /> public virtual TEntity Find<TChild1>(Expression<Func<TEntity, bool>> predicate, Expression<Func<TEntity, object>> tChild1) { return Find<TChild1>(predicate, tChild1, null); } /// <inheritdoc /> public virtual TEntity Find<TChild1>(Expression<Func<TEntity, bool>> predicate, Expression<Func<TEntity, object>> tChild1, IDbTransaction transaction) { var queryResult = SqlGenerator.GetSelectFirst(predicate, FilterData, tChild1); return ExecuteJoinQuery<TChild1, DontMap, DontMap, DontMap, DontMap, DontMap>(queryResult, transaction, tChild1).FirstOrDefault(); } /// <inheritdoc /> public virtual TEntity Find<TChild1, TChild2>(Expression<Func<TEntity, bool>> predicate, Expression<Func<TEntity, object>> tChild1, Expression<Func<TEntity, object>> tChild2) { return Find<TChild1, TChild2>(predicate, tChild1, tChild2, null); } /// <inheritdoc /> public virtual TEntity Find<TChild1, TChild2>(Expression<Func<TEntity, bool>> predicate, Expression<Func<TEntity, object>> tChild1, Expression<Func<TEntity, object>> tChild2, IDbTransaction transaction) { var queryResult = SqlGenerator.GetSelectFirst(predicate, FilterData, tChild1, tChild2); return ExecuteJoinQuery<TChild1, TChild2, DontMap, DontMap, DontMap, DontMap>(queryResult, transaction, tChild1, tChild2).FirstOrDefault(); } /// <inheritdoc /> public virtual TEntity Find<TChild1, TChild2, TChild3>(Expression<Func<TEntity, bool>> predicate, Expression<Func<TEntity, object>> tChild1, Expression<Func<TEntity, object>> tChild2, Expression<Func<TEntity, object>> tChild3) { return Find<TChild1, TChild2, TChild3>(predicate, tChild1, tChild2, tChild3, null); } /// <inheritdoc /> public virtual TEntity Find<TChild1, TChild2, TChild3>(Expression<Func<TEntity, bool>> predicate, Expression<Func<TEntity, object>> tChild1, Expression<Func<TEntity, object>> tChild2, Expression<Func<TEntity, object>> tChild3, IDbTransaction transaction) { var queryResult = SqlGenerator.GetSelectFirst(predicate, FilterData, tChild1, tChild2, tChild3); return ExecuteJoinQuery<TChild1, TChild2, TChild3, DontMap, DontMap, DontMap>(queryResult, transaction, tChild1, tChild2, tChild3).FirstOrDefault(); } /// <inheritdoc /> public virtual TEntity Find<TChild1, TChild2, TChild3, TChild4>(Expression<Func<TEntity, bool>> predicate, Expression<Func<TEntity, object>> tChild1, Expression<Func<TEntity, object>> tChild2, Expression<Func<TEntity, object>> tChild3, Expression<Func<TEntity, object>> tChild4) { return Find<TChild1, TChild2, TChild3, TChild4>(predicate, tChild1, tChild2, tChild3, tChild4, null); } /// <inheritdoc /> public virtual TEntity Find<TChild1, TChild2, TChild3, TChild4>(Expression<Func<TEntity, bool>> predicate, Expression<Func<TEntity, object>> tChild1, Expression<Func<TEntity, object>> tChild2, Expression<Func<TEntity, object>> tChild3, Expression<Func<TEntity, object>> tChild4, IDbTransaction transaction) { var queryResult = SqlGenerator.GetSelectFirst(predicate, FilterData, tChild1, tChild2, tChild3, tChild4); return ExecuteJoinQuery<TChild1, TChild2, TChild3, TChild4, DontMap, DontMap>(queryResult, transaction, tChild1, tChild2, tChild3, tChild4).FirstOrDefault(); } /// <inheritdoc /> public virtual TEntity Find<TChild1, TChild2, TChild3, TChild4, TChild5>(Expression<Func<TEntity, bool>> predicate, Expression<Func<TEntity, object>> tChild1, Expression<Func<TEntity, object>> tChild2, Expression<Func<TEntity, object>> tChild3, Expression<Func<TEntity, object>> tChild4, Expression<Func<TEntity, object>> tChild5) { return Find<TChild1, TChild2, TChild3, TChild4, TChild5>(predicate, tChild1, tChild2, tChild3, tChild4, tChild5, null); } /// <inheritdoc /> public virtual TEntity Find<TChild1, TChild2, TChild3, TChild4, TChild5>(Expression<Func<TEntity, bool>> predicate, Expression<Func<TEntity, object>> tChild1, Expression<Func<TEntity, object>> tChild2, Expression<Func<TEntity, object>> tChild3, Expression<Func<TEntity, object>> tChild4, Expression<Func<TEntity, object>> tChild5, IDbTransaction transaction) { var queryResult = SqlGenerator.GetSelectFirst(predicate, FilterData, tChild1, tChild2, tChild3, tChild4, tChild5); return ExecuteJoinQuery<TChild1, TChild2, TChild3, TChild4, TChild5, DontMap>(queryResult, transaction, tChild1, tChild2, tChild3, tChild4, tChild5).FirstOrDefault(); } /// <inheritdoc /> public virtual TEntity Find<TChild1, TChild2, TChild3, TChild4, TChild5, TChild6>(Expression<Func<TEntity, bool>> predicate, Expression<Func<TEntity, object>> tChild1, Expression<Func<TEntity, object>> tChild2, Expression<Func<TEntity, object>> tChild3, Expression<Func<TEntity, object>> tChild4, Expression<Func<TEntity, object>> tChild5, Expression<Func<TEntity, object>> tChild6) { return Find<TChild1, TChild2, TChild3, TChild4, TChild5, TChild6>(predicate, tChild1, tChild2, tChild3, tChild4, tChild5, tChild6, null); } /// <inheritdoc /> public virtual TEntity Find<TChild1, TChild2, TChild3, TChild4, TChild5, TChild6>(Expression<Func<TEntity, bool>> predicate, Expression<Func<TEntity, object>> tChild1, Expression<Func<TEntity, object>> tChild2, Expression<Func<TEntity, object>> tChild3, Expression<Func<TEntity, object>> tChild4, Expression<Func<TEntity, object>> tChild5, Expression<Func<TEntity, object>> tChild6, IDbTransaction transaction) { var queryResult = SqlGenerator.GetSelectFirst(predicate, FilterData, tChild1, tChild2, tChild3, tChild4, tChild5, tChild6); return ExecuteJoinQuery<TChild1, TChild2, TChild3, TChild4, TChild5, TChild6>(queryResult, transaction, tChild1, tChild2, tChild3, tChild4, tChild5, tChild6) .FirstOrDefault(); } /// <inheritdoc /> public virtual Task<TEntity> FindAsync<TChild1>(Expression<Func<TEntity, bool>> predicate, Expression<Func<TEntity, object>> tChild1) { return FindAsync<TChild1>(predicate, tChild1, null); } /// <inheritdoc /> public virtual async Task<TEntity> FindAsync<TChild1>(Expression<Func<TEntity, bool>> predicate, Expression<Func<TEntity, object>> tChild1, IDbTransaction transaction) { var queryResult = SqlGenerator.GetSelectFirst(predicate, FilterData, tChild1); return (await ExecuteJoinQueryAsync<TChild1, DontMap, DontMap, DontMap, DontMap, DontMap>(queryResult, transaction, tChild1)).FirstOrDefault(); } /// <inheritdoc /> public virtual Task<TEntity> FindAsync<TChild1, TChild2>(Expression<Func<TEntity, bool>> predicate, Expression<Func<TEntity, object>> tChild1, Expression<Func<TEntity, object>> tChild2) { return FindAsync<TChild1, TChild2>(predicate, tChild1, tChild2, null); } /// <inheritdoc /> public virtual async Task<TEntity> FindAsync<TChild1, TChild2>(Expression<Func<TEntity, bool>> predicate, Expression<Func<TEntity, object>> tChild1, Expression<Func<TEntity, object>> tChild2, IDbTransaction transaction) { var queryResult = SqlGenerator.GetSelectFirst(predicate, FilterData, tChild1, tChild2); return (await ExecuteJoinQueryAsync<TChild1, TChild2, DontMap, DontMap, DontMap, DontMap>(queryResult, transaction, tChild1, tChild2)).FirstOrDefault(); } /// <inheritdoc /> public virtual Task<TEntity> FindAsync<TChild1, TChild2, TChild3>(Expression<Func<TEntity, bool>> predicate, Expression<Func<TEntity, object>> tChild1, Expression<Func<TEntity, object>> tChild2, Expression<Func<TEntity, object>> tChild3) { return FindAsync<TChild1, TChild2, TChild3>(predicate, tChild1, tChild2, tChild3, null); } /// <inheritdoc /> public virtual async Task<TEntity> FindAsync<TChild1, TChild2, TChild3>(Expression<Func<TEntity, bool>> predicate, Expression<Func<TEntity, object>> tChild1, Expression<Func<TEntity, object>> tChild2, Expression<Func<TEntity, object>> tChild3, IDbTransaction transaction) { var queryResult = SqlGenerator.GetSelectFirst(predicate, FilterData, tChild1, tChild2, tChild3); return (await ExecuteJoinQueryAsync<TChild1, TChild2, TChild3, DontMap, DontMap, DontMap>(queryResult, transaction, tChild1, tChild2, tChild3)).FirstOrDefault(); } /// <inheritdoc /> public virtual Task<TEntity> FindAsync<TChild1, TChild2, TChild3, TChild4>(Expression<Func<TEntity, bool>> predicate, Expression<Func<TEntity, object>> tChild1, Expression<Func<TEntity, object>> tChild2, Expression<Func<TEntity, object>> tChild3, Expression<Func<TEntity, object>> tChild4) { return FindAsync<TChild1, TChild2, TChild3, TChild4>(predicate, tChild1, tChild2, tChild3, tChild4, null); } /// <inheritdoc /> public virtual async Task<TEntity> FindAsync<TChild1, TChild2, TChild3, TChild4>(Expression<Func<TEntity, bool>> predicate, Expression<Func<TEntity, object>> tChild1, Expression<Func<TEntity, object>> tChild2, Expression<Func<TEntity, object>> tChild3, Expression<Func<TEntity, object>> tChild4, IDbTransaction transaction) { var queryResult = SqlGenerator.GetSelectFirst(predicate, FilterData, tChild1, tChild2, tChild3, tChild4); return (await ExecuteJoinQueryAsync<TChild1, TChild2, TChild3, TChild4, DontMap, DontMap>(queryResult, transaction, tChild1, tChild2, tChild3, tChild4)) .FirstOrDefault(); } /// <inheritdoc /> public virtual Task<TEntity> FindAsync<TChild1, TChild2, TChild3, TChild4, TChild5>(Expression<Func<TEntity, bool>> predicate, Expression<Func<TEntity, object>> tChild1, Expression<Func<TEntity, object>> tChild2, Expression<Func<TEntity, object>> tChild3, Expression<Func<TEntity, object>> tChild4, Expression<Func<TEntity, object>> tChild5) { return FindAsync<TChild1, TChild2, TChild3, TChild4, TChild5, DontMap>(predicate, tChild1, tChild2, tChild3, tChild4, tChild5, null); } /// <inheritdoc /> public virtual async Task<TEntity> FindAsync<TChild1, TChild2, TChild3, TChild4, TChild5>(Expression<Func<TEntity, bool>> predicate, Expression<Func<TEntity, object>> tChild1, Expression<Func<TEntity, object>> tChild2, Expression<Func<TEntity, object>> tChild3, Expression<Func<TEntity, object>> tChild4, Expression<Func<TEntity, object>> tChild5, IDbTransaction transaction) { var queryResult = SqlGenerator.GetSelectFirst(predicate, FilterData, tChild1, tChild2, tChild3, tChild4, tChild5); return (await ExecuteJoinQueryAsync<TChild1, TChild2, TChild3, TChild4, TChild5, DontMap>(queryResult, transaction, tChild1, tChild2, tChild3, tChild4, tChild5)) .FirstOrDefault(); } /// <inheritdoc /> public virtual Task<TEntity> FindAsync<TChild1, TChild2, TChild3, TChild4, TChild5, TChild6>(Expression<Func<TEntity, bool>> predicate, Expression<Func<TEntity, object>> tChild1, Expression<Func<TEntity, object>> tChild2, Expression<Func<TEntity, object>> tChild3, Expression<Func<TEntity, object>> tChild4, Expression<Func<TEntity, object>> tChild5, Expression<Func<TEntity, object>> tChild6) { return FindAsync<TChild1, TChild2, TChild3, TChild4, TChild5, TChild6>(predicate, tChild1, tChild2, tChild3, tChild4, tChild5, tChild6, null); } /// <inheritdoc /> public virtual async Task<TEntity> FindAsync<TChild1, TChild2, TChild3, TChild4, TChild5, TChild6>(Expression<Func<TEntity, bool>> predicate, Expression<Func<TEntity, object>> tChild1, Expression<Func<TEntity, object>> tChild2, Expression<Func<TEntity, object>> tChild3, Expression<Func<TEntity, object>> tChild4, Expression<Func<TEntity, object>> tChild5, Expression<Func<TEntity, object>> tChild6, IDbTransaction transaction) { var queryResult = SqlGenerator.GetSelectFirst(predicate, FilterData, tChild1, tChild2, tChild3, tChild4, tChild5, tChild6); return (await ExecuteJoinQueryAsync<TChild1, TChild2, TChild3, TChild4, TChild5, TChild6>(queryResult, transaction, tChild1, tChild2, tChild3, tChild4, tChild5, tChild6)).FirstOrDefault(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using FluentAssertions.Common; using FluentAssertions.Execution; namespace FluentAssertions.Equivalency { /// <remarks> /// I think (but did not try) this would have been easier using 'dynamic' but that is /// precluded by some of the PCL targets. /// </remarks> public class GenericDictionaryEquivalencyStep : IEquivalencyStep { public bool CanHandle(IEquivalencyValidationContext context, IEquivalencyAssertionOptions config) { Type subjectType = config.GetSubjectType(context); return ((context.Subject != null) && GetIDictionaryInterfaces(subjectType).Any()); } private static Type[] GetIDictionaryInterfaces(Type type) { return Common.TypeExtensions.GetClosedGenericInterfaces( type, typeof(IDictionary<,>)); } public bool Handle(IEquivalencyValidationContext context, IEquivalencyValidator parent, IEquivalencyAssertionOptions config) { if (PreconditionsAreMet(context, config)) { AssertDictionaryEquivalence(context, parent, config); } return true; } private static bool PreconditionsAreMet(IEquivalencyValidationContext context, IEquivalencyAssertionOptions config) { Type subjectType = config.GetSubjectType(context); return (AssertImplementsOnlyOneDictionaryInterface(context.Subject) && AssertIsCompatiblyTypedDictionary(subjectType, context.Expectation) && AssertSameLength(context.Subject, subjectType, context.Expectation)); } private static bool AssertImplementsOnlyOneDictionaryInterface(object subject) { Type[] interfaces = GetIDictionaryInterfaces(subject.GetType()); bool multipleInterfaces = (interfaces.Count() > 1); if (multipleInterfaces) { AssertionScope.Current.FailWith( string.Format( "{{context:Subject}} implements multiple dictionary types. " + "It is not known which type should be use for equivalence.{0}" + "The following IDictionary interfaces are implemented: {1}", Environment.NewLine, String.Join(", ", interfaces.Select(i => i.ToString()).ToArray()))); return false; } return true; } private static bool AssertIsCompatiblyTypedDictionary(Type subjectType, object expectation) { Type subjectDictionaryType = GetIDictionaryInterface(subjectType); Type subjectKeyType = GetDictionaryKeyType(subjectDictionaryType); Type[] expectationDictionaryInterfaces = GetIDictionaryInterfaces(expectation.GetType()); if (!expectationDictionaryInterfaces.Any()) { AssertionScope.Current.FailWith( "{context:subject} is a dictionary and cannot be compared with a non-dictionary type."); return false; } Type[] suitableDictionaryInterfaces = expectationDictionaryInterfaces.Where( @interface => GetDictionaryKeyType(@interface).IsAssignableFrom(subjectKeyType)).ToArray(); if (suitableDictionaryInterfaces.Count() > 1) { // Code could be written to handle this better, but is it really worth the effort? AssertionScope.Current.FailWith( "The expected object implements multiple IDictionary interfaces. " + "If you need to use ShouldBeEquivalentTo in this case please file " + "a bug with the FluentAssertions devlopment team"); return false; } if (!suitableDictionaryInterfaces.Any()) { AssertionScope.Current.FailWith( string.Format( "The {{context:subject}} dictionary has keys of type {0}; " + "however, the expected dictionary is not keyed with any compatible types.{1}" + "The expected dictionary implements: {2}", subjectKeyType, Environment.NewLine, string.Join(",", expectationDictionaryInterfaces.Select(i => i.ToString()).ToArray()))); return false; } return true; } private static Type GetDictionaryKeyType(Type subjectType) { return subjectType.GetGenericArguments()[0]; } private static bool AssertSameLength(object subject, Type subjectType, object expectation) { string methodName = ExpressionExtensions.GetMethodName(() => AssertSameLength<object, object, object, object>(null, null)); MethodCallExpression assertSameLength = Expression.Call( typeof(GenericDictionaryEquivalencyStep), methodName, GetDictionaryTypeArguments(subjectType) .Concat(GetDictionaryTypeArguments(expectation.GetType())) .ToArray(), Expression.Constant(subject, GetIDictionaryInterface(subjectType)), Expression.Constant(expectation, GetIDictionaryInterface(expectation.GetType()))); return (bool)Expression.Lambda(assertSameLength).Compile().DynamicInvoke(); } private static IEnumerable<Type> GetDictionaryTypeArguments(Type subjectType) { var dictionaryType = GetIDictionaryInterface(subjectType); return dictionaryType.GetGenericArguments(); } private static Type GetIDictionaryInterface(Type subjectType) { return GetIDictionaryInterfaces(subjectType).Single(); } private static bool AssertSameLength<TSubjectKey, TSubjectValue, TExpectKey, TExpectedValue>( IDictionary<TSubjectKey, TSubjectValue> subject, IDictionary<TExpectKey, TExpectedValue> expectation) { return AssertionScope.Current.ForCondition(subject.Count == expectation.Count) .FailWith( "Expected {context:subject} to be a dictionary with {0} item(s), but found {1} item(s).", expectation.Count, subject.Count); } private static void AssertDictionaryEquivalence( IEquivalencyValidationContext context, IEquivalencyValidator parent, IEquivalencyAssertionOptions config) { Type subjectType = config.GetSubjectType(context); string methodName = ExpressionExtensions.GetMethodName( () => AssertDictionaryEquivalence<object, object, object, object>(null, null, null, null, null)); var assertDictionaryEquivalence = Expression.Call( typeof(GenericDictionaryEquivalencyStep), methodName, GetDictionaryTypeArguments(subjectType) .Concat(GetDictionaryTypeArguments(context.Expectation.GetType())) .ToArray(), Expression.Constant(context), Expression.Constant(parent), Expression.Constant(config), Expression.Constant(context.Subject, GetIDictionaryInterface(subjectType)), Expression.Constant(context.Expectation, GetIDictionaryInterface(context.Expectation.GetType()))); Expression.Lambda(assertDictionaryEquivalence).Compile().DynamicInvoke(); } private static void AssertDictionaryEquivalence<TSubjectKey, TSubjectValue, TExpectKey, TExpectedValue>( EquivalencyValidationContext context, IEquivalencyValidator parent, IEquivalencyAssertionOptions config, IDictionary<TSubjectKey, TSubjectValue> subject, IDictionary<TExpectKey, TExpectedValue> expectation) where TSubjectKey : TExpectKey { foreach (TSubjectKey key in subject.Keys) { TExpectedValue expectedValue; if (expectation.TryGetValue(key, out expectedValue)) { if (config.IsRecursive) { parent.AssertEqualityUsing(context.CreateForDictionaryItem(key, subject[key], expectation[key])); } else { subject[key].Should().Be(expectation[key], context.Reason, context.ReasonArgs); } } else { AssertionScope.Current.FailWith("{context:subject} contains unexpected key {0}", key); } } } } }
#region license // Copyright (c) 2004, Rodrigo B. de Oliveira ([email protected]) // 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 Rodrigo B. de Oliveira nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF // THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion using System.Collections.Generic; using Boo.Lang.Compiler.TypeSystem.Services; using Boo.Lang.Environments; namespace Boo.Lang.Compiler.TypeSystem.Core { public class ArrayType : IArrayType { readonly IType _elementType; readonly int _rank; public ArrayType(IType elementType, int rank) { _elementType = elementType; _rank = rank; } public IEntity DeclaringEntity { get { return null; } } public string Name { get { return _rank > 1 ? "(" + _elementType + ", " + _rank + ")" : "(" + _elementType + ")"; } } public EntityType EntityType { get { return EntityType.Array; } } public string FullName { get { return Name; } } public IType Type { get { return this; } } public bool IsFinal { get { return true; } } public bool IsByRef { get { return false; } } public bool IsClass { get { return false; } } public bool IsInterface { get { return false; } } public bool IsAbstract { get { return false; } } public bool IsEnum { get { return false; } } public bool IsValueType { get { return false; } } public bool IsArray { get { return true; } } public bool IsPointer { get { return false; } } public int GetTypeDepth() { return 2; } public int Rank { get { return _rank; } } public IType ElementType { get { return _elementType; } } public IType BaseType { get { return My<TypeSystemServices>.Instance.ArrayType; } } public IEntity GetDefaultMember() { return null; } public virtual bool IsSubclassOf(IType other) { TypeSystemServices services = My<TypeSystemServices>.Instance; if (other == services.ArrayType || services.ArrayType.IsSubclassOf(other)) return true; // Arrays also implement several generic collection interfaces of their element type if (other.ConstructedInfo != null && other.IsInterface && IsSupportedInterfaceType(services, other.ConstructedInfo.GenericDefinition) && IsSubclassOfGenericEnumerable(other)) return true; return false; } protected bool IsSupportedInterfaceType(TypeSystemServices services, IType definition) { return definition == services.IEnumerableGenericType || definition == services.IListGenericType || definition == services.ICollectionGenericType || definition == services.IReadOnlyListGenericType || definition == services.IReadOnlyCollectionGenericType; } protected virtual bool IsSubclassOfGenericEnumerable(IType enumerableType) { return IsAssignableFrom(enumerableType.ConstructedInfo.GenericArguments[0], _elementType); } public virtual bool IsAssignableFrom(IType other) { if (other == this || other.IsNull()) return true; if (!other.IsArray) return false; var otherArray = (IArrayType)other; if (otherArray.Rank != _rank) return false; if (otherArray == EmptyArrayType.Default) return true; IType otherElementType = otherArray.ElementType; return IsAssignableFrom(_elementType, otherElementType); } private bool IsAssignableFrom(IType expectedType, IType actualType) { return TypeCompatibilityRules.IsAssignableFrom(expectedType, actualType); } public IType[] GetInterfaces() { TypeSystemServices services = My<TypeSystemServices>.Instance; return new[] { services.IEnumerableType, services.ICollectionType, services.IListType, services.IEnumerableGenericType.GenericInfo.ConstructType(_elementType), services.ICollectionGenericType.GenericInfo.ConstructType(_elementType), services.IListGenericType.GenericInfo.ConstructType(_elementType), }; } public IEnumerable<IEntity> GetMembers() { return BaseType.GetMembers(); } public INamespace ParentNamespace { get { return ElementType.ParentNamespace; } } public bool Resolve(ICollection<IEntity> resultingSet, string name, EntityType typesToConsider) { return BaseType.Resolve(resultingSet, name, typesToConsider); } override public string ToString() { return this.DisplayName(); } IGenericTypeInfo IType.GenericInfo { get { return null; } } IConstructedTypeInfo IType.ConstructedInfo { get { return null; } } #region IEntityWithAttributes Members public bool IsDefined(IType attributeType) { return false; } #endregion private ArrayTypeCache _arrayTypes; public IArrayType MakeArrayType(int rank) { if (null == _arrayTypes) _arrayTypes = new ArrayTypeCache(this); return _arrayTypes.MakeArrayType(rank); } public IType MakePointerType() { return null; } } }
using System; using System.Collections.Generic; using xsc = DotNetXmlSwfChart; namespace testWeb.tests { public class StackedColumn3dTwo : ChartTestBase { #region ChartInclude public override xsc.ChartHTML ChartInclude { get { DotNetXmlSwfChart.ChartHTML chartHtml = new DotNetXmlSwfChart.ChartHTML(); chartHtml.height = 300; chartHtml.bgColor = "777788"; chartHtml.flashFile = "charts/charts.swf"; chartHtml.libraryPath = "charts/charts_library"; chartHtml.xmlSource = "xmlData.aspx"; return chartHtml; } } #endregion #region Chart public override xsc.Chart Chart { get { xsc.Chart c = new xsc.Chart(); c.AddChartType(xsc.XmlSwfChartType.ColumnStacked3d); c.AxisCategory = SetAxisCategory(c.ChartType[0]); c.AxisTicks = SetAxisTicks(); c.AxisValue = SetAxisValue(); c.ChartBorder = SetChartBorder(); c.Data = SetChartData(); c.ChartGridH = SetChartGrid(xsc.ChartGridType.Horizontal); c.ChartGridV = SetChartGrid(xsc.ChartGridType.Vertical); c.ChartRectangle = SetChartRectangle(); c.ChartPreferences = SetChartPreferences(c.ChartType[0]); c.ChartValue = SetChartValue(); c.LegendLabel = SetLegendLabel(); c.LegendRectangle = SetLegendRectangle(); c.AddSeriesColor("ff6600"); c.AddSeriesColor("88ff00"); c.AddSeriesColor("8866ff"); c.SeriesGap = SetSeriesGap(); return c; } } #endregion #region Helpers #region SetAxisCategory(xsc.XmlSwfChartType type) private xsc.AxisCategory SetAxisCategory(xsc.XmlSwfChartType type) { xsc.AxisCategory ac = new xsc.AxisCategory(type); ac.Size = 10; ac.Color = "ffffff"; ac.Alpha = 75; return ac; } #endregion #region SetAxisTicks() private xsc.AxisTicks SetAxisTicks() { xsc.AxisTicks at = new xsc.AxisTicks(); at.CategoryTicks = true; at.ValueTicks = true; at.MinorCount = 1; return at; } #endregion #region SetAxisValue() private xsc.AxisValue SetAxisValue() { xsc.AxisValue av = new xsc.AxisValue(); av.Size = 10; av.Color = "ffffff"; av.Alpha = 75; return av; } #endregion #region SetChartBorder() private xsc.ChartBorder SetChartBorder() { xsc.ChartBorder cb = new xsc.ChartBorder(); cb.TopThickness = 0; cb.BottomThickness = 2; cb.LeftThickness = 2; cb.RightThickness = 0; return cb; } #endregion #region SetChartData() private xsc.ChartData SetChartData() { xsc.ChartData cd = new xsc.ChartData(); cd.AddDataPoint("Region 1", "Su", 22); cd.AddDataPoint("Region 1", "M", 15); cd.AddDataPoint("Region 1", "Tu", 11); cd.AddDataPoint("Region 1", "W", 15); cd.AddDataPoint("Region 1", "Th", 20); cd.AddDataPoint("Region 1", "F", 22); cd.AddDataPoint("Region 1", "Sa", 21); cd.AddDataPoint("Region 2", "Su", 15); cd.AddDataPoint("Region 2", "M", 20); cd.AddDataPoint("Region 2", "Tu", 15); cd.AddDataPoint("Region 2", "W", 17); cd.AddDataPoint("Region 2", "Th", 25); cd.AddDataPoint("Region 2", "F", 12); cd.AddDataPoint("Region 2", "Sa", 11); cd.AddDataPoint("Region 3", "Su", 30); cd.AddDataPoint("Region 3", "M", 32); cd.AddDataPoint("Region 3", "Tu", 35); cd.AddDataPoint("Region 3", "W", 20); cd.AddDataPoint("Region 3", "Th", 30); cd.AddDataPoint("Region 3", "F", 30); cd.AddDataPoint("Region 3", "Sa", 36); return cd; } #endregion #region SetChartGrid(xsc.ChartGridType type) private xsc.ChartGrid SetChartGrid(xsc.ChartGridType type) { xsc.ChartGrid cg = new xsc.ChartGrid(type); cg.Thickness = 1; cg.GridLineType = xsc.ChartGridLineType.solid; return cg; } #endregion #region SetChartRectangle() private xsc.ChartRectangle SetChartRectangle() { xsc.ChartRectangle cr = new xsc.ChartRectangle(); cr.X = 60; cr.Y = 60; cr.Width = 300; cr.Height = 150; cr.PositiveColor = "888888"; cr.PositiveAlpha = 50; return cr; } #endregion #region SetChartPreferences(xsc.XmlSwfChartType type) private xsc.ChartPreferences SetChartPreferences(xsc.XmlSwfChartType type) { xsc.ChartPreferences cp = new xsc.ChartPreferences(type); cp.RotationX = 15; cp.RotationY = 0; return cp; } #endregion #region SetChartValue() private xsc.ChartValue SetChartValue() { xsc.ChartValue cv = new xsc.ChartValue(); cv.Color = "ffffcc"; cv.BackgroundColor = "444488"; cv.Alpha = 100; cv.Size = 12; cv.Position = "cursor"; return cv; } #endregion #region SetLegendLabel() private xsc.LegendLabel SetLegendLabel() { xsc.LegendLabel ll = new xsc.LegendLabel(); ll.Layout = xsc.LegendLabelLayout.horizontal; ll.Size = 12; ll.Color = "000000"; ll.Alpha = 50; return ll; } #endregion #region SetLegendRectangle() private xsc.LegendRectangle SetLegendRectangle() { xsc.LegendRectangle lr = new xsc.LegendRectangle(); lr.X = 25; lr.Y = 250; lr.Width = 350; lr.Height = 50; lr.Margin = 20; lr.FillColor = "000000"; lr.FillAlpha = 7; lr.LineColor = "000000"; lr.LineAlpha = 0; lr.LineThickness = 0; return lr; } #endregion #region SetSeriesGap() private xsc.SeriesGap SetSeriesGap() { xsc.SeriesGap sg = new xsc.SeriesGap(); sg.BarGap = 0; sg.SetGap = 20; return sg; } #endregion #endregion } }
using GuiLabs.Canvas; using GuiLabs.Canvas.Controls; using GuiLabs.Canvas.Events; using GuiLabs.Editor.Actions; using GuiLabs.Editor.UI; using GuiLabs.Utils.Delegates; using GuiLabs.Canvas.Renderer; using System.Drawing; using GuiLabs.Editor.Clipboard; using GuiLabs.Utils; using GuiLabs.Undo; using System; namespace GuiLabs.Editor.Blocks { /// <summary> /// HOWTO: inherit from RootBlock: /// 1. Constructor should call base() /// 2. Constructor should set FocusBlock /// </summary> public partial class RootBlock : LinearContainerBlock //, IRootBlock, IDragDrop { #region ctor public RootBlock() : base() { InitActionManager(); Root = this; } #endregion #region Events public event Action UndoBufferChanged; protected void RaiseUndoBufferChanged(object sender, EventArgs e) { if (UndoBufferChanged != null) { UndoBufferChanged(); } if (ActiveBlock != null) { RaiseShouldDisplayContextHelp(ActiveBlock); } } public event ActiveBlockChangedHandler ActiveBlockChanged; private void RaiseActiveBlockChanged(Block oldActiveBlock) { if (ActiveBlockChanged != null) { ActiveBlockChanged(oldActiveBlock, mActiveBlock); } } public event ChangeHandler<Block> ShouldDisplayContextHelp; public void RaiseShouldDisplayContextHelp(Block helpForBlock) { if (ShouldDisplayContextHelp != null) { ShouldDisplayContextHelp(helpForBlock); } } public event ChangeHandler<string> ShouldShowStatus; public void ShowStatus(string statusText) { if (ShouldShowStatus != null) { ShouldShowStatus(statusText); } } #endregion #region OnEvents protected override void OnKeyDown(object sender, System.Windows.Forms.KeyEventArgs e) { if (e.KeyCode == System.Windows.Forms.Keys.Z && e.Control) { this.ActionManager.Undo(); } if (e.KeyCode == System.Windows.Forms.Keys.Y && e.Control) { this.ActionManager.Redo(); } OnCtrlPressed(e); // Do nothing. This is important. // Because otherwise this handler will be fired twice for the RootBlock. // // See ShapeWithEvents.cs: // public override void OnKeyDown(KeyEventArgs e) // { // base.OnKeyDown(e); // fire keydown once // RaiseKeyDown(e); // fire keydown for the second time // } } protected override void OnKeyUp(object sender, System.Windows.Forms.KeyEventArgs e) { base.OnKeyUp(sender, e); OnCtrlPressed(e); } #endregion #region ActionManager private void InitActionManager() { mActionManager = new ActionManager(); mActionManager.CollectionChanged += RaiseUndoBufferChanged; } private ActionManager mActionManager; public override ActionManager ActionManager { get { return mActionManager; } } #endregion #region Control protected override void InitControl(OrientationType orientation) { MyRootControl = new RootControl(this.Children.Controls); MyRootControl.LinearLayoutStrategy.Orientation = orientation; } private RootControl mMyRootControl; public virtual RootControl MyRootControl { get { return mMyRootControl; } protected set { if (mMyRootControl != null) { UnSubscribeControl(); mMyRootControl.AfterDraw -= Draw; } mMyRootControl = value; if (mMyRootControl != null) { SubscribeControl(); mMyRootControl.AfterDraw += Draw; } } } public override LinearContainerControl MyListControl { get { return MyRootControl; } protected set { // Should never be called } } public sealed override Control MyControl { get { return MyRootControl; } } #endregion #region Draw private static Rect dragRect = new Rect(0, 0, 64, 32); private static Rect dropRect = new Rect(); private void Draw(IRenderer renderer) { //if (this.CurrentSelection != null) //{ // Renderer.DrawOperations.DrawRectangle( // CurrentSelection.Bounds, // Color.Blue, // 3); //} if (DragState != null) { DragQuery query = DragState.Query; if (DragState.DragStarted) { dragRect.Location.Set( DragState.Query.DropPoint + 24); renderer.DrawOperations.DrawDotRectangle( dragRect, Color.DarkGray); } if (DragState.Result != null) { DragQueryResult result = DragState.Result; dropRect.Set(result.DropTarget.MyControl.Bounds.AddMargins( result.DropTarget.MyControl.Box.MouseSensitivityArea)); if (result.HowToDrop == DropTargetInfo.DropBeforeTarget) { dropRect.Size.Y = 3; } else if (result.HowToDrop == DropTargetInfo.DropAfterTarget) { dropRect.Location.Y += dropRect.Size.Y; dropRect.Size.Y = 3; } renderer.DrawOperations.DrawRectangle( dropRect, Color.DeepSkyBlue, 2); } } } public void Redraw() { if (MyRootControl != null) { MyRootControl.Redraw(); } } #endregion #region Styles public void ReloadAllStyles() { foreach (Block b in EnumAllBlocks()) { b.InitStyle(); } } #endregion #region ActiveBlock private Block mActiveBlock; /// <summary> /// Use Block.SetFocus to set the ActiveBlock property. /// </summary> public Block ActiveBlock { get { return mActiveBlock; } internal set { Block oldActiveBlock = mActiveBlock; mActiveBlock = value; //this.MyRootControl.ActiveControl = value.MyControl; RaiseActiveBlockChanged(oldActiveBlock); } } #endregion #region Visibility private VisibilityFilter mVisibilityManager; public VisibilityFilter VisibilityManager { get { return mVisibilityManager; } set { mVisibilityManager = value; CheckVisibility(); this.MyRootControl.Redraw(); } } #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. #if XMLSERIALIZERGENERATOR namespace Microsoft.XmlSerializer.Generator #else namespace System.Xml.Serialization #endif { using System.IO; using System; using System.Collections; using System.ComponentModel; using System.Xml; /// <include file='doc\_Events.uex' path='docs/doc[@for="XmlAttributeEventHandler"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> #if XMLSERIALIZERGENERATOR internal delegate void XmlAttributeEventHandler(object sender, XmlAttributeEventArgs e); #else public delegate void XmlAttributeEventHandler(object sender, XmlAttributeEventArgs e); #endif /// <include file='doc\_Events.uex' path='docs/doc[@for="XmlAttributeEventArgs"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> #if XMLSERIALIZERGENERATOR internal class XmlAttributeEventArgs : EventArgs #else public class XmlAttributeEventArgs : EventArgs #endif { private object _o; private XmlAttribute _attr; private string _qnames; private int _lineNumber; private int _linePosition; internal XmlAttributeEventArgs(XmlAttribute attr, int lineNumber, int linePosition, object o, string qnames) { _attr = attr; _o = o; _qnames = qnames; _lineNumber = lineNumber; _linePosition = linePosition; } /// <include file='doc\_Events.uex' path='docs/doc[@for="XmlAttributeEventArgs.ObjectBeingDeserialized"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public object ObjectBeingDeserialized { get { return _o; } } /// <include file='doc\_Events.uex' path='docs/doc[@for="XmlAttributeEventArgs.Attr"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public XmlAttribute Attr { get { return _attr; } } /// <include file='doc\_Events.uex' path='docs/doc[@for="XmlAttributeEventArgs.LineNumber"]/*' /> /// <devdoc> /// <para> /// Gets the current line number. /// </para> /// </devdoc> public int LineNumber { get { return _lineNumber; } } /// <include file='doc\_Events.uex' path='docs/doc[@for="XmlAttributeEventArgs.LinePosition"]/*' /> /// <devdoc> /// <para> /// Gets the current line position. /// </para> /// </devdoc> public int LinePosition { get { return _linePosition; } } /// <include file='doc\_Events.uex' path='docs/doc[@for="XmlAttributeEventArgs.Attributes"]/*' /> /// <devdoc> /// <para> /// List the qnames of attributes expected in the current context. /// </para> /// </devdoc> public string ExpectedAttributes { get { return _qnames == null ? string.Empty : _qnames; } } } /// <include file='doc\_Events.uex' path='docs/doc[@for="XmlElementEventHandler"]/*' /> #if XMLSERIALIZERGENERATOR internal delegate void XmlElementEventHandler(object sender, XmlElementEventArgs e); #else public delegate void XmlElementEventHandler(object sender, XmlElementEventArgs e); #endif /// <include file='doc\_Events.uex' path='docs/doc[@for="XmlElementEventArgs"]/*' /> #if XMLSERIALIZERGENERATOR internal class XmlElementEventArgs : EventArgs #else public class XmlElementEventArgs : EventArgs #endif { private object _o; private XmlElement _elem; private string _qnames; private int _lineNumber; private int _linePosition; internal XmlElementEventArgs(XmlElement elem, int lineNumber, int linePosition, object o, string qnames) { _elem = elem; _o = o; _qnames = qnames; _lineNumber = lineNumber; _linePosition = linePosition; } /// <include file='doc\_Events.uex' path='docs/doc[@for="XmlElementEventArgs.ObjectBeingDeserialized"]/*' /> public object ObjectBeingDeserialized { get { return _o; } } /// <include file='doc\_Events.uex' path='docs/doc[@for="XmlElementEventArgs.Attr"]/*' /> public XmlElement Element { get { return _elem; } } /// <include file='doc\_Events.uex' path='docs/doc[@for="XmlElementEventArgs.LineNumber"]/*' /> public int LineNumber { get { return _lineNumber; } } /// <include file='doc\_Events.uex' path='docs/doc[@for="XmlElementEventArgs.LinePosition"]/*' /> public int LinePosition { get { return _linePosition; } } /// <include file='doc\_Events.uex' path='docs/doc[@for="XmlAttributeEventArgs.ExpectedElements"]/*' /> /// <devdoc> /// <para> /// List of qnames of elements expected in the current context. /// </para> /// </devdoc> public string ExpectedElements { get { return _qnames == null ? string.Empty : _qnames; } } } /// <include file='doc\_Events.uex' path='docs/doc[@for="XmlNodeEventHandler"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> #if XMLSERIALIZERGENERATOR internal delegate void XmlNodeEventHandler(object sender, XmlNodeEventArgs e); #else public delegate void XmlNodeEventHandler(object sender, XmlNodeEventArgs e); #endif /// <include file='doc\_Events.uex' path='docs/doc[@for="XmlNodeEventArgs"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> #if XMLSERIALIZERGENERATOR internal class XmlNodeEventArgs : EventArgs #else public class XmlNodeEventArgs : EventArgs #endif { private object _o; private XmlNode _xmlNode; private int _lineNumber; private int _linePosition; internal XmlNodeEventArgs(XmlNode xmlNode, int lineNumber, int linePosition, object o) { _o = o; _xmlNode = xmlNode; _lineNumber = lineNumber; _linePosition = linePosition; } /// <include file='doc\_Events.uex' path='docs/doc[@for="XmlNodeEventArgs.ObjectBeingDeserialized"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public object ObjectBeingDeserialized { get { return _o; } } /// <include file='doc\_Events.uex' path='docs/doc[@for="XmlNodeEventArgs.NodeType"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public XmlNodeType NodeType { get { return _xmlNode.NodeType; } } /// <include file='doc\_Events.uex' path='docs/doc[@for="XmlNodeEventArgs.Name"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public string Name { get { return _xmlNode.Name; } } /// <include file='doc\_Events.uex' path='docs/doc[@for="XmlNodeEventArgs.LocalName"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public string LocalName { get { return _xmlNode.LocalName; } } /// <include file='doc\_Events.uex' path='docs/doc[@for="XmlNodeEventArgs.NamespaceURI"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public string NamespaceURI { get { return _xmlNode.NamespaceURI; } } /// <include file='doc\_Events.uex' path='docs/doc[@for="XmlNodeEventArgs.Text"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public string Text { get { return _xmlNode.Value; } } /// <include file='doc\_Events.uex' path='docs/doc[@for="XmlNodeEventArgs.LineNumber"]/*' /> /// <devdoc> /// <para> /// Gets the current line number. /// </para> /// </devdoc> public int LineNumber { get { return _lineNumber; } } /// <include file='doc\_Events.uex' path='docs/doc[@for="XmlNodeEventArgs.LinePosition"]/*' /> /// <devdoc> /// <para> /// Gets the current line position. /// </para> /// </devdoc> public int LinePosition { get { return _linePosition; } } } /// <include file='doc\_Events.uex' path='docs/doc[@for="UnreferencedObjectEventHandler"]/*' /> #if XMLSERIALIZERGENERATOR internal delegate void UnreferencedObjectEventHandler(object sender, UnreferencedObjectEventArgs e); #else public delegate void UnreferencedObjectEventHandler(object sender, UnreferencedObjectEventArgs e); #endif /// <include file='doc\_Events.uex' path='docs/doc[@for="UnreferencedObjectEventArgs"]/*' /> #if XMLSERIALIZERGENERATOR internal class UnreferencedObjectEventArgs : EventArgs #else public class UnreferencedObjectEventArgs : EventArgs #endif { private object _o; private string _id; /// <include file='doc\_Events.uex' path='docs/doc[@for="UnreferencedObjectEventArgs.UnreferencedObjectEventArgs"]/*' /> public UnreferencedObjectEventArgs(object o, string id) { _o = o; _id = id; } /// <include file='doc\_Events.uex' path='docs/doc[@for="UnreferencedObjectEventArgs.UnreferencedObject"]/*' /> public object UnreferencedObject { get { return _o; } } /// <include file='doc\_Events.uex' path='docs/doc[@for="UnreferencedObjectEventArgs.UnreferencedId"]/*' /> public string UnreferencedId { get { return _id; } } } }
using System; using System.Collections.Generic; using System.Xml.Linq; using Umbraco.Core.Models; using Umbraco.Core.Models.EntityBase; namespace Umbraco.Core.Services { /// <summary> /// Defines the ContentTypeService, which is an easy access to operations involving <see cref="IContentType"/> /// </summary> public interface IContentTypeService : IService { /// <summary> /// Given the path of a content item, this will return true if the content item exists underneath a list view content item /// </summary> /// <param name="contentPath"></param> /// <returns></returns> bool HasContainerInPath(string contentPath); int CountContentTypes(); int CountMediaTypes(); /// <summary> /// Validates the composition, if its invalid a list of property type aliases that were duplicated is returned /// </summary> /// <param name="compo"></param> /// <returns></returns> Attempt<string[]> ValidateComposition(IContentTypeComposition compo); Attempt<OperationStatus<EntityContainer, OperationStatusType>> CreateContentTypeContainer(int parentId, string name, int userId = 0); Attempt<OperationStatus<EntityContainer, OperationStatusType>> RenameContentTypeContainer(int id, string name, int userId = 0); Attempt<OperationStatus<EntityContainer, OperationStatusType>> RenameDataTypeContainer(int id, string name, int userId = 0); Attempt<OperationStatus<EntityContainer, OperationStatusType>> CreateMediaTypeContainer(int parentId, string name, int userId = 0); Attempt<OperationStatus> SaveContentTypeContainer(EntityContainer container, int userId = 0); Attempt<OperationStatus> SaveMediaTypeContainer(EntityContainer container, int userId = 0); EntityContainer GetContentTypeContainer(int containerId); EntityContainer GetContentTypeContainer(Guid containerId); IEnumerable<EntityContainer> GetContentTypeContainers(int[] containerIds); IEnumerable<EntityContainer> GetContentTypeContainers(IContentType contentType); IEnumerable<EntityContainer> GetContentTypeContainers(string folderName, int level); EntityContainer GetMediaTypeContainer(int containerId); EntityContainer GetMediaTypeContainer(Guid containerId); IEnumerable<EntityContainer> GetMediaTypeContainers(int[] containerIds); IEnumerable<EntityContainer> GetMediaTypeContainers(string folderName, int level); IEnumerable<EntityContainer> GetMediaTypeContainers(IMediaType mediaType); Attempt<OperationStatus> DeleteMediaTypeContainer(int folderId, int userId = 0); Attempt<OperationStatus> DeleteContentTypeContainer(int containerId, int userId = 0); /// <summary> /// Gets all property type aliases. /// </summary> /// <returns></returns> IEnumerable<string> GetAllPropertyTypeAliases(); /// <summary> /// Gets all content type aliases /// </summary> /// <param name="objectTypes"> /// If this list is empty, it will return all content type aliases for media, members and content, otherwise /// it will only return content type aliases for the object types specified /// </param> /// <returns></returns> IEnumerable<string> GetAllContentTypeAliases(params Guid[] objectTypes); /// <summary> /// Returns all content type Ids for the aliases given /// </summary> /// <param name="aliases"></param> /// <returns></returns> IEnumerable<int> GetAllContentTypeIds(string[] aliases); /// <summary> /// Copies a content type as a child under the specified parent if specified (otherwise to the root) /// </summary> /// <param name="original"> /// The content type to copy /// </param> /// <param name="alias"> /// The new alias of the content type /// </param> /// <param name="name"> /// The new name of the content type /// </param> /// <param name="parentId"> /// The parent to copy the content type to, default is -1 (root) /// </param> /// <returns></returns> IContentType Copy(IContentType original, string alias, string name, int parentId = -1); /// <summary> /// Copies a content type as a child under the specified parent if specified (otherwise to the root) /// </summary> /// <param name="original"> /// The content type to copy /// </param> /// <param name="alias"> /// The new alias of the content type /// </param> /// <param name="name"> /// The new name of the content type /// </param> /// <param name="parent"> /// The parent to copy the content type to /// </param> /// <returns></returns> IContentType Copy(IContentType original, string alias, string name, IContentType parent); /// <summary> /// Gets an <see cref="IContentType"/> object by its Id /// </summary> /// <param name="id">Id of the <see cref="IContentType"/> to retrieve</param> /// <returns><see cref="IContentType"/></returns> IContentType GetContentType(int id); /// <summary> /// Gets an <see cref="IContentType"/> object by its Alias /// </summary> /// <param name="alias">Alias of the <see cref="IContentType"/> to retrieve</param> /// <returns><see cref="IContentType"/></returns> IContentType GetContentType(string alias); /// <summary> /// Gets an <see cref="IContentType"/> object by its Key /// </summary> /// <param name="id">Alias of the <see cref="IContentType"/> to retrieve</param> /// <returns><see cref="IContentType"/></returns> IContentType GetContentType(Guid id); /// <summary> /// Gets a list of all available <see cref="IContentType"/> objects /// </summary> /// <param name="ids">Optional list of ids</param> /// <returns>An Enumerable list of <see cref="IContentType"/> objects</returns> IEnumerable<IContentType> GetAllContentTypes(params int[] ids); /// <summary> /// Gets a list of all available <see cref="IContentType"/> objects /// </summary> /// <param name="ids">Optional list of ids</param> /// <returns>An Enumerable list of <see cref="IContentType"/> objects</returns> IEnumerable<IContentType> GetAllContentTypes(IEnumerable<Guid> ids); /// <summary> /// Gets a list of children for a <see cref="IContentType"/> object /// </summary> /// <param name="id">Id of the Parent</param> /// <returns>An Enumerable list of <see cref="IContentType"/> objects</returns> IEnumerable<IContentType> GetContentTypeChildren(int id); /// <summary> /// Gets a list of children for a <see cref="IContentType"/> object /// </summary> /// <param name="id">Id of the Parent</param> /// <returns>An Enumerable list of <see cref="IContentType"/> objects</returns> IEnumerable<IContentType> GetContentTypeChildren(Guid id); /// <summary> /// Saves a single <see cref="IContentType"/> object /// </summary> /// <param name="contentType"><see cref="IContentType"/> to save</param> /// <param name="userId">Optional Id of the User saving the ContentType</param> void Save(IContentType contentType, int userId = 0); /// <summary> /// Saves a collection of <see cref="IContentType"/> objects /// </summary> /// <param name="contentTypes">Collection of <see cref="IContentType"/> to save</param> /// <param name="userId">Optional Id of the User saving the ContentTypes</param> void Save(IEnumerable<IContentType> contentTypes, int userId = 0); /// <summary> /// Deletes a single <see cref="IContentType"/> object /// </summary> /// <param name="contentType"><see cref="IContentType"/> to delete</param> /// <remarks>Deleting a <see cref="IContentType"/> will delete all the <see cref="IContent"/> objects based on this <see cref="IContentType"/></remarks> /// <param name="userId">Optional Id of the User deleting the ContentType</param> void Delete(IContentType contentType, int userId = 0); /// <summary> /// Deletes a collection of <see cref="IContentType"/> objects /// </summary> /// <param name="contentTypes">Collection of <see cref="IContentType"/> to delete</param> /// <remarks>Deleting a <see cref="IContentType"/> will delete all the <see cref="IContent"/> objects based on this <see cref="IContentType"/></remarks> /// <param name="userId">Optional Id of the User deleting the ContentTypes</param> void Delete(IEnumerable<IContentType> contentTypes, int userId = 0); /// <summary> /// Gets an <see cref="IMediaType"/> object by its Id /// </summary> /// <param name="id">Id of the <see cref="IMediaType"/> to retrieve</param> /// <returns><see cref="IMediaType"/></returns> IMediaType GetMediaType(int id); /// <summary> /// Gets an <see cref="IMediaType"/> object by its Alias /// </summary> /// <param name="alias">Alias of the <see cref="IMediaType"/> to retrieve</param> /// <returns><see cref="IMediaType"/></returns> IMediaType GetMediaType(string alias); /// <summary> /// Gets an <see cref="IMediaType"/> object by its Id /// </summary> /// <param name="id">Id of the <see cref="IMediaType"/> to retrieve</param> /// <returns><see cref="IMediaType"/></returns> IMediaType GetMediaType(Guid id); /// <summary> /// Gets a list of all available <see cref="IMediaType"/> objects /// </summary> /// <param name="ids">Optional list of ids</param> /// <returns>An Enumerable list of <see cref="IMediaType"/> objects</returns> IEnumerable<IMediaType> GetAllMediaTypes(params int[] ids); /// <summary> /// Gets a list of all available <see cref="IMediaType"/> objects /// </summary> /// <param name="ids">Optional list of ids</param> /// <returns>An Enumerable list of <see cref="IMediaType"/> objects</returns> IEnumerable<IMediaType> GetAllMediaTypes(IEnumerable<Guid> ids); /// <summary> /// Gets a list of children for a <see cref="IMediaType"/> object /// </summary> /// <param name="id">Id of the Parent</param> /// <returns>An Enumerable list of <see cref="IMediaType"/> objects</returns> IEnumerable<IMediaType> GetMediaTypeChildren(int id); /// <summary> /// Gets a list of children for a <see cref="IMediaType"/> object /// </summary> /// <param name="id">Id of the Parent</param> /// <returns>An Enumerable list of <see cref="IMediaType"/> objects</returns> IEnumerable<IMediaType> GetMediaTypeChildren(Guid id); /// <summary> /// Saves a single <see cref="IMediaType"/> object /// </summary> /// <param name="mediaType"><see cref="IMediaType"/> to save</param> /// <param name="userId">Optional Id of the User saving the MediaType</param> void Save(IMediaType mediaType, int userId = 0); /// <summary> /// Saves a collection of <see cref="IMediaType"/> objects /// </summary> /// <param name="mediaTypes">Collection of <see cref="IMediaType"/> to save</param> /// <param name="userId">Optional Id of the User saving the MediaTypes</param> void Save(IEnumerable<IMediaType> mediaTypes, int userId = 0); /// <summary> /// Deletes a single <see cref="IMediaType"/> object /// </summary> /// <param name="mediaType"><see cref="IMediaType"/> to delete</param> /// <remarks>Deleting a <see cref="IMediaType"/> will delete all the <see cref="IMedia"/> objects based on this <see cref="IMediaType"/></remarks> /// <param name="userId">Optional Id of the User deleting the MediaType</param> void Delete(IMediaType mediaType, int userId = 0); /// <summary> /// Deletes a collection of <see cref="IMediaType"/> objects /// </summary> /// <param name="mediaTypes">Collection of <see cref="IMediaType"/> to delete</param> /// <remarks>Deleting a <see cref="IMediaType"/> will delete all the <see cref="IMedia"/> objects based on this <see cref="IMediaType"/></remarks> /// <param name="userId">Optional Id of the User deleting the MediaTypes</param> void Delete(IEnumerable<IMediaType> mediaTypes, int userId = 0); /// <summary> /// Generates the complete (simplified) XML DTD. /// </summary> /// <returns>The DTD as a string</returns> string GetDtd(); /// <summary> /// Generates the complete XML DTD without the root. /// </summary> /// <returns>The DTD as a string</returns> string GetContentTypesDtd(); /// <summary> /// Checks whether an <see cref="IContentType"/> item has any children /// </summary> /// <param name="id">Id of the <see cref="IContentType"/></param> /// <returns>True if the content type has any children otherwise False</returns> bool HasChildren(int id); /// <summary> /// Checks whether an <see cref="IContentType"/> item has any children /// </summary> /// <param name="id">Id of the <see cref="IContentType"/></param> /// <returns>True if the content type has any children otherwise False</returns> bool HasChildren(Guid id); /// <summary> /// Checks whether an <see cref="IMediaType"/> item has any children /// </summary> /// <param name="id">Id of the <see cref="IMediaType"/></param> /// <returns>True if the media type has any children otherwise False</returns> bool MediaTypeHasChildren(int id); /// <summary> /// Checks whether an <see cref="IMediaType"/> item has any children /// </summary> /// <param name="id">Id of the <see cref="IMediaType"/></param> /// <returns>True if the media type has any children otherwise False</returns> bool MediaTypeHasChildren(Guid id); Attempt<OperationStatus<MoveOperationStatusType>> MoveMediaType(IMediaType toMove, int containerId); Attempt<OperationStatus<MoveOperationStatusType>> MoveContentType(IContentType toMove, int containerId); Attempt<OperationStatus<IMediaType, MoveOperationStatusType>> CopyMediaType(IMediaType toCopy, int containerId); Attempt<OperationStatus<IContentType, MoveOperationStatusType>> CopyContentType(IContentType toCopy, int containerId); Attempt<OperationStatus<EntityContainer, OperationStatusType>> RenameMediaTypeContainer(int id, string name, int userId = 0); } }
using System; using System.IO; using System.Net; using System.Net.Sockets; using System.Text; using System.Collections; namespace LumiSoft.Net { /// <summary> /// /// </summary> public delegate void SocketCallBack(SocketCallBackResult result,long count,Exception x,object tag); // /// <summary> // /// // /// </summary> // public delegate void SocketActivityCallback(object tag); /// <summary> /// Asynchronous command execute result. /// </summary> public enum SocketCallBackResult { /// <summary> /// Operation was successfull. /// </summary> Ok, /// <summary> /// Exceeded maximum allowed size. /// </summary> LengthExceeded, /// <summary> /// Connected client closed connection. /// </summary> SocketClosed, /// <summary> /// Exception happened. /// </summary> Exception, } /// <summary> /// Sokcet + buffer. Socket data reads are buffered. At first Recieve returns data from /// internal buffer and if no data available, gets more from socket. Socket buffer is also /// user settable, you can add data to socket buffer directly with AppendBuffer(). /// </summary> public class BufferedSocket { private Socket m_pSocket = null; private byte[] m_Buffer = null; private long m_BufPos = 0; private bool m_Closed = false; private Encoding m_pEncoding = null; private SocketLogger m_pLogger = null; /// <summary> /// Is called when there is some activity on socket (Read or Send). /// </summary> public event EventHandler Activity = null; /// <summary> /// Default constructor. /// </summary> /// <param name="socket">Source socket which to buffer.</param> public BufferedSocket(Socket socket) { m_pSocket = socket; m_Buffer = new byte[0]; m_pEncoding = Encoding.Default; } #region method Connect /// <summary> /// /// </summary> /// <param name="remoteEP"></param> public void Connect(EndPoint remoteEP) { m_pSocket.Connect(remoteEP); } #endregion #region method BeginConnect /// <summary> /// /// </summary> /// <param name="remoteEP"></param> /// <param name="callback"></param> /// <param name="state"></param> /// <returns></returns> public IAsyncResult BeginConnect(EndPoint remoteEP,AsyncCallback callback,object state) { return m_pSocket.BeginConnect(remoteEP,callback,state); } #endregion #region method EndConnect /// <summary> /// /// </summary> /// <param name="asyncResult"></param> /// <returns></returns> public void EndConnect(IAsyncResult asyncResult) { m_pSocket.EndConnect(asyncResult); } #endregion #region method Receive /// <summary> /// Receives data from buffer. If there isn't data in buffer, then receives more data from socket. /// </summary> /// <param name="buffer"></param> /// <returns></returns> public int Receive(byte[] buffer) { // There isn't data in buffer, get more if(this.AvailableInBuffer == 0){ byte[] buf = new byte[10000]; int countReaded = m_pSocket.Receive(buf); if(countReaded != buf.Length){ m_Buffer = new byte[countReaded]; Array.Copy(buf,0,m_Buffer,0,countReaded); } else{ m_Buffer = buf; } m_BufPos = 0; } return ReceiveFromFuffer(buffer); } #endregion #region method BeginReceive /// <summary> /// /// </summary> /// <param name="buffer"></param> /// <param name="offset"></param> /// <param name="size"></param> /// <param name="socketFlags"></param> /// <param name="callback"></param> /// <param name="state"></param> public void BeginReceive(byte[] buffer,int offset,int size,SocketFlags socketFlags,AsyncCallback callback,object state) { m_pSocket.BeginReceive(buffer,offset,size,socketFlags,callback,state); } #endregion #region method EndReceive /// <summary> /// /// </summary> /// <param name="asyncResult"></param> /// <returns></returns> public int EndReceive(IAsyncResult asyncResult) { return m_pSocket.EndReceive(asyncResult); } #endregion #region method Send /// <summary> /// /// </summary> /// <param name="buffer"></param> /// <returns></returns> public int Send(byte[] buffer) { return m_pSocket.Send(buffer); } #endregion #region method Send /// <summary> /// /// </summary> /// <param name="buffer"></param> /// <param name="offset"></param> /// <param name="size"></param> /// <param name="socketFlags"></param> public int Send(byte[] buffer,int offset,int size,SocketFlags socketFlags) { return m_pSocket.Send(buffer,offset,size,socketFlags); } #endregion #region method SetSocketOption /// <summary> /// /// </summary> /// <param name="otpionLevel"></param> /// <param name="optionName"></param> /// <param name="optionValue"></param> public void SetSocketOption(SocketOptionLevel otpionLevel,SocketOptionName optionName,int optionValue) { m_pSocket.SetSocketOption(otpionLevel,optionName,optionValue); } #endregion #region method Bind /// <summary> /// Binds socket to local endpoint. /// </summary> /// <param name="localEP"></param> public void Bind(EndPoint localEP) { m_pSocket.Bind(localEP); } #endregion #region method Shutdown /// <summary> /// /// </summary> /// <param name="how"></param> public void Shutdown(SocketShutdown how) { m_Closed = true; m_pSocket.Shutdown(how); } #endregion #region method Close /// <summary> /// /// </summary> public void Close() { m_Closed = true; m_pSocket.Close(); // m_pSocket = null; m_Buffer = new byte[0]; } #endregion #region method ReceiveFromFuffer /// <summary> /// Receives data from buffer. /// </summary> /// <param name="buffer"></param> /// <returns></returns> public int ReceiveFromFuffer(byte[] buffer) { int countInBuff = this.AvailableInBuffer; // There is more data in buffer as requested if(countInBuff > buffer.Length){ Array.Copy(m_Buffer,m_BufPos,buffer,0,buffer.Length); m_BufPos += buffer.Length; return buffer.Length; } else{ Array.Copy(m_Buffer,m_BufPos,buffer,0,countInBuff); // Reset buffer and pos, because we used all data from buffer m_Buffer = new byte[0]; m_BufPos = 0; return countInBuff; } } #endregion #region method AppendBuffer internal void AppendBuffer(byte[] data,int length) { if(m_Buffer.Length == 0){ m_Buffer = new byte[length]; Array.Copy(data,0,m_Buffer,0,length); } else{ byte[] newBuff = new byte[m_Buffer.Length + length]; Array.Copy(m_Buffer,0,newBuff,0,m_Buffer.Length); Array.Copy(data,0,newBuff,m_Buffer.Length,length); m_Buffer = newBuff; } } #endregion #region method ReadLine() /// <summary> /// Reads line from socket. /// </summary> /// <returns></returns> public string ReadLine() { return ReadLine(1024); } #endregion #region method ReadLine(maxLength) /// <summary> /// Reads line from socket. /// </summary> /// <param name="maxLength">Maximum length to read.</param> /// <returns></returns> public string ReadLine(long maxLength) { using(MemoryStream storeStream = new MemoryStream()){ ReadReplyCode code = ReadData(storeStream,maxLength,"\r\n","\r\n"); if(code != ReadReplyCode.Ok){ throw new ReadException(code,code.ToString()); } return m_pEncoding.GetString(storeStream.ToArray()).Trim(); } } #endregion #region method BeginReadLine /// <summary> /// Starts reading line from socket asynchronously. /// </summary> /// <param name="strm">Stream where to store line.</param> /// <param name="maxLength">Maximum line length.</param> /// <param name="tag">User data.</param> /// <param name="callBack">Method to call, if receive completes.</param> public void BeginReadLine(Stream strm,long maxLength,object tag,SocketCallBack callBack) { BeginReadData(strm,maxLength,"\r\n","\r\n",tag,callBack); } #endregion #region method SendLine /// <summary> /// Sends line to socket. /// </summary> /// <param name="line"></param> public void SendLine(string line) { if(!line.EndsWith("\r\n")){ line += "\r\n"; } byte[] data = m_pEncoding.GetBytes(line); int countSended = m_pSocket.Send(data); if(countSended != data.Length){ throw new Exception("Send error, didn't send all bytes !"); // ToDo: if this happens just try to resend unsent bytes } // Logging stuff if(m_pLogger != null){ m_pLogger.AddSendEntry(line,data.Length); } OnActivity(); } #endregion #region method BeginSendLine /// <summary> /// Starts sending line to socket asynchronously. /// </summary> /// <param name="line">Data line.</param> /// <param name="callBack">Callback to be called if sending ends.</param> public void BeginSendLine(string line,SocketCallBack callBack) { BeginSendLine(line,null,callBack); } /// <summary> /// Starts sending line to socket asynchronously. /// </summary> /// <param name="line">Data line.</param> /// <param name="tag">User data.</param> /// <param name="callBack">Callback to be called if sending ends.</param> public void BeginSendLine(string line,object tag,SocketCallBack callBack) { if(!line.EndsWith("\r\n")){ line += "\r\n"; } BeginSendData(new MemoryStream(m_pEncoding.GetBytes(line)),tag,callBack); } #endregion // 3 types of read // 1) To some terminator // 2) Specified length // 3) While socket is closed with ShutDown #region method ReadData (terminator) /// <summary> /// Reads data from socket while specified terminator is reached. /// If maximum length is exceeded, reading continues but data won't be stored to stream. /// </summary> /// <param name="storeStream">Stream where to store readed data.</param> /// <param name="maxLength">Maximum length to read.</param> /// <param name="terminator">Terminator which trminates reading.</param> /// <param name="removeFromEnd">Part of trminator what to remove from end. Can be empty or max part is terminator.</param> /// <returns></returns> public ReadReplyCode ReadData(Stream storeStream,long maxLength,string terminator,string removeFromEnd) { if(storeStream == null){ throw new Exception("Parameter storeStream can't be null !"); } ReadReplyCode replyCode = ReadReplyCode.Ok; try{ _FixedStack stack = new _FixedStack(terminator); long readedCount = 0; int nextReadWriteLen = 1; while(nextReadWriteLen > 0){ //Read byte(s) byte[] b = new byte[nextReadWriteLen]; int countRecieved = this.Receive(b); if(countRecieved > 0){ readedCount += countRecieved; // Write byte(s) to buffer, if length isn't exceeded. if(readedCount <= maxLength){ storeStream.Write(b,0,countRecieved); } // Write to stack(terminator checker) nextReadWriteLen = stack.Push(b,countRecieved); } // Client disconnected else{ return ReadReplyCode.SocketClosed; } OnActivity(); } // Check if length is exceeded if(readedCount > maxLength){ return ReadReplyCode.LengthExceeded; } // If reply is ok then remove chars if any specified by 'removeFromEnd'. if(replyCode == ReadReplyCode.Ok && removeFromEnd.Length > 0){ storeStream.SetLength(storeStream.Length - removeFromEnd.Length); } // Logging stuff if(m_pLogger != null){ if(storeStream is MemoryStream && storeStream.Length < 200){ MemoryStream ms = (MemoryStream)storeStream; m_pLogger.AddReadEntry(m_pEncoding.GetString(ms.ToArray()),readedCount); } else{ m_pLogger.AddReadEntry("Big binary, readed " + readedCount.ToString() + " bytes.",readedCount); } } } catch(Exception x){ replyCode = ReadReplyCode.UnKnownError; if(x is SocketException){ SocketException xS = (SocketException)x; if(xS.ErrorCode == 10060){ return ReadReplyCode.TimeOut; } } } return replyCode; } #endregion #region method ReadData (length) /// <summary> /// Reads specified amount of data from socket. /// </summary> /// <param name="storeStream">Stream where to store readed data.</param> /// <param name="countToRead">Amount of data to read.</param> /// <param name="storeToStream">Specifes if to store readed data to stream or junk it.</param> /// <returns></returns> public ReadReplyCode ReadData(Stream storeStream,long countToRead,bool storeToStream) { ReadReplyCode replyCode = ReadReplyCode.Ok; try{ long readedCount = 0; while(readedCount < countToRead){ byte[] b = new byte[4000]; // Ensure that we don't get more data than needed if((countToRead - readedCount) < 4000){ b = new byte[countToRead - readedCount]; } int countRecieved = this.Receive(b); if(countRecieved > 0){ readedCount += countRecieved; if(storeToStream){ storeStream.Write(b,0,countRecieved); } } // Client disconnected else{ return ReadReplyCode.SocketClosed; } OnActivity(); } // Logging stuff if(m_pLogger != null){ m_pLogger.AddReadEntry("Big binary, readed " + readedCount.ToString() + " bytes.",readedCount); } } catch(Exception x){ replyCode = ReadReplyCode.UnKnownError; if(x is SocketException){ SocketException xS = (SocketException)x; if(xS.ErrorCode == 10060){ return ReadReplyCode.TimeOut; } } } return replyCode; } #endregion #region method ReadData (shutdown) /// <summary> /// Reads data while socket is closed with shutdown. /// If maximum length is exceeded, reading continues but data won't be stored to stream. /// </summary> /// <param name="storeStream">Stream where to store readed data.</param> /// <param name="maxLength">Maximum length to read.</param> public ReadReplyCode ReadData(Stream storeStream,long maxLength) { try{ byte[] data = new byte[4000]; long readedCount = 0; int recievedCount = this.Receive(data); while(recievedCount > 0){ readedCount += recievedCount; if(readedCount <= maxLength){ storeStream.Write(data,0,recievedCount); } data = new byte[4000]; recievedCount = this.Receive(data); OnActivity(); } // Check if length is exceeded if(readedCount > maxLength){ return ReadReplyCode.LengthExceeded; } // Logging stuff if(m_pLogger != null){ m_pLogger.AddReadEntry("Big binary, readed " + readedCount.ToString() + " bytes.",readedCount); } } catch(Exception x){ if(x is SocketException){ SocketException xS = (SocketException)x; if(xS.ErrorCode == 10060){ return ReadReplyCode.TimeOut; } } return ReadReplyCode.UnKnownError; } return ReadReplyCode.Ok; } #endregion #region method SendData (string) /// <summary> /// Sends data to socket. /// </summary> /// <param name="data"></param> public void SendData(string data) { SendData(new MemoryStream(m_pEncoding.GetBytes(data))); } #endregion #region method SendData (byte[]) /// <summary> /// Sends data to socket. /// </summary> /// <param name="data"></param> public void SendData(byte[] data) { SendData(new MemoryStream(data)); } #endregion #region method SendData (Stream) /// <summary> /// Sends data to socket. /// </summary> /// <param name="dataStream"></param> public void SendData(Stream dataStream) { byte[] data = new byte[4000]; long sendedCount = 0; int readedCount = dataStream.Read(data,0,data.Length); while(readedCount > 0){ int count = m_pSocket.Send(data,readedCount,0); if(count != readedCount){ throw new Exception("Send error, didn't send all bytes !"); } sendedCount += readedCount; readedCount = dataStream.Read(data,0,data.Length); OnActivity(); } // Logging stuff if(m_pLogger != null){ if(dataStream is MemoryStream && dataStream.Length < 200){ MemoryStream ms = (MemoryStream)dataStream; m_pLogger.AddSendEntry(m_pEncoding.GetString(ms.ToArray()),sendedCount); } else{ m_pLogger.AddSendEntry("Big binary, sended " + sendedCount.ToString() + " bytes.",sendedCount); } } } #endregion #region method BeginReadData (terminator) /// <summary> /// Begins asynchronous data reading. /// </summary> /// <param name="strm">Stream where to store data.</param> /// <param name="maxLength">Maximum length of data which may read.</param> /// <param name="terminator">Terminator string which terminates reading. eg '\r\n'.</param> /// <param name="removeFromEnd">Removes following string at end of data.</param> /// <param name="tag">User data.</param> /// <param name="callBack">Method to call, if receive completes.</param> public void BeginReadData(Stream strm,long maxLength,string terminator,string removeFromEnd,object tag,SocketCallBack callBack) { _SocketState state = new _SocketState(strm,maxLength,terminator,removeFromEnd,tag,callBack); ProccessData_Term(state); } #endregion #region method BeginReadData (length) /// <summary> /// Begins asynchronous data reading. /// </summary> /// <param name="strm">Stream where to store data.</param> /// <param name="lengthToRead">Length of data to read.</param> /// <param name="maxLength">Maximum length of data which may read.</param> /// <param name="tag">User data.</param> /// <param name="callBack">Method to call, if receive completes.</param> public void BeginReadData(Stream strm,long lengthToRead,long maxLength,object tag,SocketCallBack callBack) { _SocketState state = new _SocketState(strm,lengthToRead,maxLength,tag,callBack); ProccessData_Len(state); } #endregion #region method OnRecievedData /// <summary> /// Is called from asynchronous socket if data is recieved. /// </summary> /// <param name="a"></param> private void OnRecievedData(IAsyncResult a) { _SocketState state = (_SocketState)a.AsyncState; try{ // Socket is closed by session, we don't need to get data or call callback method. // This mainlty happens when session timesout and session is ended. if(!this.IsClosed){ int countReaded = this.EndReceive(a); if(countReaded > 0){ this.AppendBuffer(state.RecvBuffer,countReaded); if(state.ReadType == ReadType.Terminator){ ProccessData_Term(state); } else{ ProccessData_Len(state); } } // Client disconnected else if(state.Callback != null){ state.Callback(SocketCallBackResult.SocketClosed,state.ReadCount,null,state.Tag); } } OnActivity(); } catch(Exception x){ if(state.Callback != null){ state.Callback(SocketCallBackResult.Exception,state.ReadCount,x,state.Tag); } } } #endregion #region method ProccessData_Term private void ProccessData_Term(_SocketState state) { while(state.NextRead > 0){ // We used buffer, request more data if(this.AvailableInBuffer < state.NextRead){ // Store nextReadWriteLen for next call of this command // state.NextRead = state.NextRead; // Recieve next bytes byte[] buff = new byte[4000]; state.RecvBuffer = buff; this.BeginReceive(buff,0,buff.Length,0,new AsyncCallback(OnRecievedData),state); // End this method, if data arrives, this method is called again return; } //Read byte(s) byte[] b = new byte[state.NextRead]; int countRecieved = this.ReceiveFromFuffer(b); // Increase readed count state.ReadCount += countRecieved; // Write byte(s) to buffer, if length isn't exceeded. if(state.ReadCount < state.MaxLength){ state.Stream.Write(b,0,countRecieved); } // Write to stack(terminator checker) state.NextRead = state.Stack.Push(b,countRecieved); } // If we reach so far, then we have successfully readed data if(state.ReadCount < state.MaxLength){ // Remove "removeFromEnd" from end if(state.RemFromEnd.Length > 0 && state.Stream.Length > state.RemFromEnd.Length){ state.Stream.SetLength(state.Stream.Length - state.RemFromEnd.Length); } state.Stream.Position = 0; // Logging stuff if(m_pLogger != null){ if(state.Stream.Length < 200 && state.Stream is MemoryStream){ MemoryStream ms = (MemoryStream)state.Stream; m_pLogger.AddReadEntry(m_pEncoding.GetString(ms.ToArray()),state.ReadCount); } else{ m_pLogger.AddReadEntry("Big binary, readed " + state.ReadCount.ToString() + " bytes.",state.ReadCount); } } // We got all data successfully, call EndRecieve call back if(state.Callback != null){ state.Callback(SocketCallBackResult.Ok,state.ReadCount,null,state.Tag); } } else if(state.Callback != null){ state.Callback(SocketCallBackResult.LengthExceeded,state.ReadCount,null,state.Tag); } } #endregion #region method ProccessData_Len private void ProccessData_Len(_SocketState state) { long dataAvailable = this.AvailableInBuffer; if(dataAvailable > 0){ byte[] data = new byte[dataAvailable]; // Ensure that we don't get more data than needed !!! if(dataAvailable > (state.LenthToRead - state.ReadCount)){ data = new byte[state.LenthToRead - state.ReadCount]; } int countRecieved = this.ReceiveFromFuffer(data); // Increase readed count state.ReadCount += data.Length; // Message size exceeded, just don't store it if(state.ReadCount < state.MaxLength){ state.Stream.Write(data,0,data.Length); } } // We got all data successfully, call EndRecieve call back if(state.ReadCount == state.LenthToRead){ // Message size exceeded if(state.ReadCount > state.MaxLength){ if(state.Callback != null){ state.Callback(SocketCallBackResult.LengthExceeded,state.ReadCount,null,state.Tag); } } else{ // Logging stuff if(m_pLogger != null){ m_pLogger.AddReadEntry("Big binary, readed " + state.ReadCount.ToString() + " bytes.",state.ReadCount); } if(state.Callback != null){ state.Callback(SocketCallBackResult.Ok,state.ReadCount,null,state.Tag); } } } else{ // Recieve next bytes byte[] buff = new byte[1024]; state.RecvBuffer = buff; this.BeginReceive(buff,0,buff.Length,0,new AsyncCallback(OnRecievedData),state); } } #endregion #region method BeginSendData (string) /// <summary> /// Begins asynchronous sending. /// </summary> /// <param name="data">Data to send.</param> /// <param name="tag">User data.</param> /// <param name="callBack">Method to call, if send completes.</param> public void BeginSendData(string data,object tag,SocketCallBack callBack) { BeginSendData(new MemoryStream(m_pEncoding.GetBytes(data)),tag,callBack); } #endregion #region method BeginSendData (Stream) /// <summary> /// Begins asynchronous sending. /// </summary> /// <param name="strm">Data to send.</param> /// <param name="tag">User data.</param> /// <param name="callBack">Method to call, if send completes.</param> public void BeginSendData(Stream strm,object tag,SocketCallBack callBack) { SendDataBlock(strm,tag,callBack); } #endregion #region method OnSendedData /// <summary> /// Is called from asynchronous socket if data is sended. /// </summary> /// <param name="a"></param> private void OnSendedData(IAsyncResult a) { object[] param = (object[])a.AsyncState; Stream strm = (Stream)param[0]; object tag = param[1]; SocketCallBack callBack = (SocketCallBack)param[2]; // ToDo: move to actual sendedCount. Currently strm.Position. try{ int countSended = m_pSocket.EndSend(a); // Send next data block if(strm.Position < strm.Length){ SendDataBlock(strm,tag,callBack); } // We sended all data else{ // Logging stuff if(m_pLogger != null){ if(strm is MemoryStream && strm.Length < 200){ MemoryStream ms = (MemoryStream)strm; m_pLogger.AddSendEntry(m_pEncoding.GetString(ms.ToArray()),strm.Length); } else{ m_pLogger.AddSendEntry("Big binary, readed " + strm.Position.ToString() + " bytes.",strm.Length); } } if(callBack != null){ callBack(SocketCallBackResult.Ok,strm.Position,null,tag); } } OnActivity(); } catch(Exception x){ if(callBack != null){ callBack(SocketCallBackResult.Exception,strm.Position,x,tag); } } } #endregion #region method SendDataBlock /// <summary> /// Starts sending block of data. /// </summary> /// <param name="strm">Data to send.</param> /// <param name="tag">User data.</param> /// <param name="callBack">Method to call, if send completes.</param> private void SendDataBlock(Stream strm,object tag,SocketCallBack callBack) { byte[] data = new byte[4000]; int countReaded = strm.Read(data,0,data.Length); m_pSocket.BeginSend(data,0,countReaded,0,new AsyncCallback(OnSendedData),new object[]{strm,tag,callBack}); } #endregion private void OnActivity() { if(this.Activity != null){ this.Activity(this,new EventArgs()); } } /// <summary> /// Gets or sets socket encoding for string(ReadLine,SendLine,....) operations. /// </summary> public Encoding SocketEncoding { get{ return m_pEncoding; } set{ m_pEncoding = value; } } /// <summary> /// Gets or sets logging source. If this is setted, reads/writes are logged to it. /// </summary> public SocketLogger Logger { get{ return m_pLogger; } set{ m_pLogger = value; } } #region Properties Implementation internal Socket Socket { get{ return m_pSocket; } } internal byte[] Buffer { get{ return m_Buffer; } } /// <summary> /// /// </summary> public int Available { get{ return (m_Buffer.Length - (int)m_BufPos) + m_pSocket.Available; } } /// <summary> /// /// </summary> public bool Connected { get{ return m_pSocket.Connected; } } /// <summary> /// /// </summary> public bool IsClosed { get{ return m_Closed; } } /// <summary> /// /// </summary> public EndPoint LocalEndPoint { get{ return m_pSocket.LocalEndPoint; } } /// <summary> /// /// </summary> public EndPoint RemoteEndPoint { get{ return m_pSocket.RemoteEndPoint; } } /// <summary> /// Gets the amount of data in buffer. /// </summary> public int AvailableInBuffer { get{ return m_Buffer.Length - (int)m_BufPos; } } #endregion } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Security; using System.Net.Sockets; using System.Security.Authentication; using System.Security.Cryptography.X509Certificates; using System.Threading; using System.Threading.Tasks; using Lime.Protocol; using Lime.Protocol.Network; using Lime.Protocol.Security; using Lime.Protocol.Serialization; using Lime.Protocol.Serialization.Newtonsoft; using System.Buffers; using System.Text; using System.Threading.Tasks.Dataflow; namespace Lime.Transport.Tcp { /// <summary> /// Provides the messaging protocol transport for TCP connections. /// </summary> public class PipeTcpTransport : TransportBase, ITransport, IAuthenticatableTransport, IDisposable { public static readonly string UriSchemeNetTcp = "net.tcp"; public static readonly TimeSpan CloseTimeout = TimeSpan.FromSeconds(30); private readonly SemaphoreSlim _optionsSemaphore; private readonly ITcpClient _tcpClient; private readonly RemoteCertificateValidationCallback _serverCertificateValidationCallback; private readonly RemoteCertificateValidationCallback _clientCertificateValidationCallback; private readonly X509Certificate2 _serverCertificate; private readonly X509Certificate2 _clientCertificate; private readonly EnvelopePipe _envelopePipe; private readonly BufferBlock<object> _readSynchronizationQueue; private Stream _stream; private string _hostName; private bool _disposed; private bool _sessionNegotiated; private bool _readTaskWaiting; /// <summary> /// Initializes a new instance of the <see cref="TcpTransport"/> class. /// </summary> /// <param name="clientCertificate"></param> /// <param name="pauseWriterThreshold">Number of buffered bytes in the pipe which can lead the write task to pause.</param> /// <param name="traceWriter">The trace writer.</param> /// <param name="serverCertificateValidationCallback">A callback to validate the server certificate in the TLS authentication process.</param> public PipeTcpTransport( X509Certificate2 clientCertificate = null, int pauseWriterThreshold = EnvelopePipe.DEFAULT_PAUSE_WRITER_THRESHOLD, ITraceWriter traceWriter = null, RemoteCertificateValidationCallback serverCertificateValidationCallback = null) : this(new EnvelopeSerializer(new DocumentTypeResolver()), clientCertificate, pauseWriterThreshold, traceWriter, serverCertificateValidationCallback) { } /// <summary> /// Initializes a new instance of the <see cref="TcpTransport" /> class. /// </summary> /// <param name="envelopeSerializer">The envelope serializer.</param> /// <param name="clientCertificate">The client certificate.</param> /// <param name="pauseWriterThreshold">Number of buffered bytes in the pipe which can lead the write task to pause.</param> /// <param name="traceWriter">The trace writer.</param> /// <param name="serverCertificateValidationCallback">A callback to validate the server certificate in the TLS authentication process.</param> public PipeTcpTransport( IEnvelopeSerializer envelopeSerializer, X509Certificate2 clientCertificate = null, int pauseWriterThreshold = EnvelopePipe.DEFAULT_PAUSE_WRITER_THRESHOLD, ITraceWriter traceWriter = null, RemoteCertificateValidationCallback serverCertificateValidationCallback = null) : this(new TcpClientAdapter(new TcpClient()), envelopeSerializer, null, clientCertificate, null, pauseWriterThreshold, null, traceWriter, serverCertificateValidationCallback, null) { } /// <summary> /// Initializes a new instance of the <see cref="TcpTransport"/> class. /// </summary> /// <param name="tcpClient">The TCP client.</param> /// <param name="envelopeSerializer">The envelope serializer.</param> /// <param name="hostName">Name of the host.</param> /// <param name="clientCertificate">The client certificate.</param> /// <param name="pauseWriterThreshold">Number of buffered bytes in the pipe which can lead the write task to pause.</param> /// <param name="traceWriter">The trace writer.</param> /// <param name="serverCertificateValidationCallback">A callback to validate the server certificate in the TLS authentication process.</param> public PipeTcpTransport( ITcpClient tcpClient, IEnvelopeSerializer envelopeSerializer, string hostName, X509Certificate2 clientCertificate = null, int pauseWriterThreshold = EnvelopePipe.DEFAULT_PAUSE_WRITER_THRESHOLD, ITraceWriter traceWriter = null, RemoteCertificateValidationCallback serverCertificateValidationCallback = null) : this(tcpClient, envelopeSerializer, null, clientCertificate, hostName, pauseWriterThreshold, null, traceWriter, serverCertificateValidationCallback, null) { } /// <summary> /// Initializes a new instance of the <see cref="TcpTransport"/> class. /// This constructor is used by the <see cref="TcpTransportListener"/> class. /// </summary> /// <param name="tcpClient">The TCP client.</param> /// <param name="envelopeSerializer">The envelope serializer.</param> /// <param name="serverCertificate">The server certificate.</param> /// <param name="pauseWriterThreshold">Number of buffered bytes in the pipe which can lead the write task to pause.</param> /// <param name="memoryPool">The memory pool instance which allow the pipe to reuse buffers.</param> /// <param name="traceWriter">The trace writer.</param> /// <param name="clientCertificateValidationCallback">A callback to validate the client certificate in the TLS authentication process.</param> internal PipeTcpTransport( ITcpClient tcpClient, IEnvelopeSerializer envelopeSerializer, X509Certificate2 serverCertificate, int pauseWriterThreshold = EnvelopePipe.DEFAULT_PAUSE_WRITER_THRESHOLD, MemoryPool<byte> memoryPool = null, ITraceWriter traceWriter = null, RemoteCertificateValidationCallback clientCertificateValidationCallback = null) : this(tcpClient, envelopeSerializer, serverCertificate, null, null, pauseWriterThreshold, memoryPool, traceWriter, null, clientCertificateValidationCallback) { } /// <summary> /// Initializes a new instance of the <see cref="TcpTransport"/> class. /// </summary> /// <param name="tcpClient">The TCP client.</param> /// <param name="envelopeSerializer">The envelope serializer.</param> /// <param name="serverCertificate">The server certificate.</param> /// <param name="clientCertificate">The client certificate.</param> /// <param name="hostName">Name of the host.</param> /// <param name="pauseWriterThreshold">Number of buffered bytes in the pipe which can lead the write task to pause.</param> /// <param name="memoryPool">The memory pool instance which allow the pipe to reuse buffers.</param> /// <param name="traceWriter">The trace writer.</param> /// <param name="serverCertificateValidationCallback">The server certificate validation callback.</param> /// <param name="clientCertificateValidationCallback">The client certificate validation callback.</param> /// <exception cref="System.ArgumentNullException"> /// tcpClient /// or /// envelopeSerializer /// </exception> private PipeTcpTransport( ITcpClient tcpClient, IEnvelopeSerializer envelopeSerializer, X509Certificate2 serverCertificate, X509Certificate2 clientCertificate, string hostName, int pauseWriterThreshold, MemoryPool<byte> memoryPool, ITraceWriter traceWriter, RemoteCertificateValidationCallback serverCertificateValidationCallback, RemoteCertificateValidationCallback clientCertificateValidationCallback) { _tcpClient = tcpClient ?? throw new ArgumentNullException(nameof(tcpClient)); _serverCertificate = serverCertificate; _clientCertificate = clientCertificate; _hostName = hostName; _serverCertificateValidationCallback = serverCertificateValidationCallback ?? ValidateServerCertificate; _clientCertificateValidationCallback = clientCertificateValidationCallback ?? ValidateClientCertificate; _envelopePipe = new EnvelopePipe(ReceiveFromPipeAsync, SendToPipeAsync, envelopeSerializer, traceWriter, pauseWriterThreshold, memoryPool); _readSynchronizationQueue = new BufferBlock<object>(); _optionsSemaphore = new SemaphoreSlim(1); } /// <summary> /// Sends an envelope to the connected node. /// </summary> /// <param name="envelope">Envelope to be transported</param> /// <param name="cancellationToken"></param> /// <returns></returns> /// <exception cref="System.NotImplementedException"></exception> public override async Task SendAsync(Envelope envelope, CancellationToken cancellationToken) { UpdateSessionNegotiated(envelope); try { await _envelopePipe.SendAsync(envelope, cancellationToken); } catch (InvalidOperationException) { await CloseWithTimeoutAsync(); throw; } } /// <summary> /// Reads one envelope from the pipe. /// </summary> /// <param name="cancellationToken"></param> /// <returns></returns> public override async Task<Envelope> ReceiveAsync(CancellationToken cancellationToken) { if (_readTaskWaiting) { // Signals the pipe stream read task to proceed await _readSynchronizationQueue.SendAsync(null, cancellationToken).ConfigureAwait(false); } try { var envelope = await _envelopePipe.ReceiveAsync(cancellationToken).ConfigureAwait(false); UpdateSessionNegotiated(envelope); return envelope; } catch (InvalidOperationException) { await CloseWithTimeoutAsync(); throw; } } /// <summary> /// Enumerates the supported encryption options for the transport. /// </summary> /// <returns></returns> public override SessionEncryption[] GetSupportedEncryption() { // Server or client mode if (IsTlsSupported) { return new[] { SessionEncryption.None, SessionEncryption.TLS }; } return new[] { SessionEncryption.None }; } /// <summary> /// Defines the encryption mode for the transport. /// </summary> /// <param name="encryption"></param> /// <param name="cancellationToken"></param> /// <returns></returns> /// <exception cref="System.NotSupportedException"></exception> public override async Task SetEncryptionAsync(SessionEncryption encryption, CancellationToken cancellationToken) { await _optionsSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false); try { switch (encryption) { case SessionEncryption.None: _stream = _tcpClient.GetStream(); break; case SessionEncryption.TLS: SslStream sslStream; if (_serverCertificate != null) { if (_stream == null) throw new InvalidOperationException("The stream was not initialized. Call OpenAsync first."); // Server sslStream = new SslStream( _stream, false, _clientCertificateValidationCallback, null, EncryptionPolicy.RequireEncryption); await sslStream .AuthenticateAsServerAsync( _serverCertificate, true, SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12, false) .WithCancellation(cancellationToken) .ConfigureAwait(false); } else { // Client if (string.IsNullOrWhiteSpace(_hostName)) { throw new InvalidOperationException("The hostname is mandatory for TLS client encryption support"); } sslStream = new SslStream( _stream, false, _serverCertificateValidationCallback); X509CertificateCollection clientCertificates = null; if (_clientCertificate != null) { clientCertificates = new X509CertificateCollection(new X509Certificate[] { _clientCertificate }); } await sslStream .AuthenticateAsClientAsync( _hostName, clientCertificates, SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12, false) .WithCancellation(cancellationToken) .ConfigureAwait(false); } _stream = sslStream; break; default: throw new NotSupportedException(); } Encryption = encryption; } finally { _optionsSemaphore.Release(); } } /// <summary> /// Indicates if the transport is connected. /// </summary> public override bool IsConnected => _tcpClient.Connected; /// <summary> /// Gets the local endpoint address. /// </summary> public override string LocalEndPoint => _tcpClient.Client?.LocalEndPoint.ToString(); /// <summary> /// Gets the remote endpoint address. /// </summary> public override string RemoteEndPoint => _tcpClient.Client?.RemoteEndPoint.ToString(); /// <summary> /// Gets specific transport metadata information. /// </summary> public override IReadOnlyDictionary<string, object> Options { get { if (_tcpClient.Client == null) return null; return new Dictionary<string, object>() { {nameof(Socket.AddressFamily), _tcpClient.Client.AddressFamily}, {nameof(Socket.Blocking), _tcpClient.Client.Blocking}, {nameof(Socket.DontFragment), _tcpClient.Client.DontFragment}, {nameof(Socket.ExclusiveAddressUse), _tcpClient.Client.ExclusiveAddressUse}, {$"{nameof(Socket.LingerState)}.{nameof(LingerOption.Enabled)}", _tcpClient.Client.LingerState?.Enabled}, {$"{nameof(Socket.LingerState)}.{nameof(LingerOption.LingerTime)}", _tcpClient.Client.LingerState?.LingerTime}, {nameof(Socket.NoDelay), _tcpClient.Client.NoDelay}, {nameof(Socket.ProtocolType), _tcpClient.Client.ProtocolType}, {nameof(Socket.ReceiveBufferSize), _tcpClient.Client.ReceiveBufferSize}, {nameof(Socket.ReceiveTimeout), _tcpClient.Client.ReceiveTimeout}, {nameof(Socket.SendBufferSize), _tcpClient.Client.SendBufferSize}, {nameof(Socket.SendTimeout), _tcpClient.Client.SendTimeout}, {nameof(Socket.SocketType), _tcpClient.Client.SocketType}, {nameof(Socket.Ttl), _tcpClient.Client.Ttl} }; } } /// <summary> /// Sets a transport option value. /// </summary> /// <param name="name">Name of the option.</param> /// <param name="value">The value.</param> /// <returns></returns> public override Task SetOptionAsync(string name, object value) { if (name == null) throw new ArgumentNullException(nameof(name)); if (_tcpClient.Client == null) throw new InvalidOperationException("The client state is invalid"); var names = name.Split('.'); object obj; if (names.Length == 1) { obj = _tcpClient.Client; } else if (names.Equals(nameof(Socket.LingerState)) && names.Length == 2) { obj = _tcpClient.Client.LingerState; name = names[1]; } else { throw new ArgumentException("Invalid option name", nameof(name)); } var propertyInfo = obj.GetType().GetProperty(name); propertyInfo.SetValue(obj, value); return Task.CompletedTask; } /// <summary> /// Authenticate the identity in the transport layer. /// </summary> /// <param name="identity">The identity to be authenticated</param> /// <returns> /// Indicates if the identity is authenticated /// </returns> public Task<DomainRole> AuthenticateAsync(Identity identity) { if (identity == null) throw new ArgumentNullException(nameof(identity)); if (!(_stream is SslStream sslStream) || !sslStream.IsAuthenticated || sslStream.RemoteCertificate == null) { return Task.FromResult(DomainRole.Unknown); } var certificate = sslStream.RemoteCertificate as X509Certificate2 ?? new X509Certificate2(sslStream.RemoteCertificate); return Task.FromResult(certificate.GetDomainRole(identity)); } /// <summary> /// Opens the transport connection with the specified Uri and begins to read from the stream. /// </summary> /// <param name="uri"></param> /// <param name="cancellationToken"></param> /// <returns></returns> /// <exception cref="System.NotImplementedException"></exception> protected override async Task PerformOpenAsync(Uri uri, CancellationToken cancellationToken) { // TODO: It is required to call OpenAsync in a server transport, which doesn't make much sense. The server transport is passive and it will be always be open after its creation. // We should refactor the transports to remove this need on the server side. if (!_tcpClient.Connected) { if (uri == null) throw new ArgumentNullException(nameof(uri), "The uri is mandatory for a not connected TCP client"); if (uri.Scheme != UriSchemeNetTcp) { throw new ArgumentException($"Invalid URI scheme. Expected is '{UriSchemeNetTcp}'.", nameof(uri)); } if (string.IsNullOrWhiteSpace(_hostName)) { _hostName = uri.Host; } await _tcpClient.ConnectAsync(uri.Host, uri.Port).ConfigureAwait(false); } _stream = _tcpClient.GetStream(); await _envelopePipe.StartAsync(cancellationToken); } /// <summary> /// Closes the transport. /// </summary> /// <param name="cancellationToken"></param> /// <returns></returns> /// <exception cref="System.NotImplementedException"></exception> protected override Task PerformCloseAsync(CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); _stream?.Close(); _tcpClient.Close(); return _envelopePipe.StopAsync(cancellationToken); } /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public void Dispose() { Dispose(true); } protected virtual void Dispose(bool disposing) { if (!_disposed) { if (disposing) { _optionsSemaphore.Dispose(); _stream?.Dispose(); _envelopePipe.Dispose(); } _disposed = true; } } private ValueTask SendToPipeAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken) => _stream.WriteAsync(buffer, cancellationToken); private async ValueTask<int> ReceiveFromPipeAsync(Memory<byte> buffer, CancellationToken cancellationToken) { if (CanBeUpgraded) { _readTaskWaiting = true; try { // If the connection can be upgraded to TLS/Gzip, we should wait for ITransport.ReceiveAsync method to be called // to proceed the with the read because the value of "_stream" field can be changed. await _readSynchronizationQueue.ReceiveAsync(cancellationToken).ConfigureAwait(false); } finally { _readTaskWaiting = false; } } var length = await _stream.ReadAsync(buffer, cancellationToken).ConfigureAwait(false); // Tries to determine if this is a partial read (there's no complete session envelope in the buffer) if (CanBeUpgraded && length > 0 && buffer.Span[length - 1] != '}') { // Adds a item to the synchronization queue to allow read the stream again without a new call to ReceiveAsync. // This is required for the cases when is required more than 1 stream ReadAsync call for producing 1 envelope. await _readSynchronizationQueue.SendAsync(null, cancellationToken).ConfigureAwait(false); } return length; } /// <summary> /// Indicates if the current transport instance supports TLS. /// </summary> private bool IsTlsSupported => _serverCertificate != null || !string.IsNullOrWhiteSpace(_hostName); /// <summary> /// Indicates if the transport options can be upgraded, which will change the value of the <see cref="_stream"/> field instance. /// </summary> private bool CanBeUpgraded => !_sessionNegotiated && Encryption == SessionEncryption.None && IsTlsSupported; /// <summary> /// Sets the value of the <see cref="_sessionNegotiated"/> field based on the envelopes that are exchanged. /// </summary> /// <param name="envelope"></param> private void UpdateSessionNegotiated(Envelope envelope) { if (!_sessionNegotiated && (!(envelope is Session) || ((Session)envelope).State > SessionState.Negotiating)) { _sessionNegotiated = true; } } private bool ValidateServerCertificate( object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return sslPolicyErrors == SslPolicyErrors.None; } private bool ValidateClientCertificate( object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { // TODO: Check key usage // The client certificate can be null but if present, must be valid if (certificate == null) { return true; } return sslPolicyErrors == SslPolicyErrors.None; } private Task CloseWithTimeoutAsync() { using (var cts = new CancellationTokenSource(CloseTimeout)) { return CloseAsync(cts.Token); } } } }
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; // <auto-generated /> namespace SAEON.Observations.Data{ /// <summary> /// Strongly-typed collection for the VInstrumentOrganisation class. /// </summary> [Serializable] public partial class VInstrumentOrganisationCollection : ReadOnlyList<VInstrumentOrganisation, VInstrumentOrganisationCollection> { public VInstrumentOrganisationCollection() {} } /// <summary> /// This is Read-only wrapper class for the vInstrumentOrganisation view. /// </summary> [Serializable] public partial class VInstrumentOrganisation : ReadOnlyRecord<VInstrumentOrganisation>, IReadOnlyRecord { #region Default Settings protected static void SetSQLProps() { GetTableSchema(); } #endregion #region Schema Accessor 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("vInstrumentOrganisation", TableType.View, DataService.GetInstance("ObservationsDB")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarId = new TableSchema.TableColumn(schema); colvarId.ColumnName = "ID"; colvarId.DataType = DbType.Guid; colvarId.MaxLength = 0; colvarId.AutoIncrement = false; colvarId.IsNullable = false; colvarId.IsPrimaryKey = false; colvarId.IsForeignKey = false; colvarId.IsReadOnly = false; schema.Columns.Add(colvarId); TableSchema.TableColumn colvarOrganisationID = new TableSchema.TableColumn(schema); colvarOrganisationID.ColumnName = "OrganisationID"; colvarOrganisationID.DataType = DbType.Guid; colvarOrganisationID.MaxLength = 0; colvarOrganisationID.AutoIncrement = false; colvarOrganisationID.IsNullable = false; colvarOrganisationID.IsPrimaryKey = false; colvarOrganisationID.IsForeignKey = false; colvarOrganisationID.IsReadOnly = false; schema.Columns.Add(colvarOrganisationID); TableSchema.TableColumn colvarOrganisationCode = new TableSchema.TableColumn(schema); colvarOrganisationCode.ColumnName = "OrganisationCode"; colvarOrganisationCode.DataType = DbType.AnsiString; colvarOrganisationCode.MaxLength = 50; colvarOrganisationCode.AutoIncrement = false; colvarOrganisationCode.IsNullable = false; colvarOrganisationCode.IsPrimaryKey = false; colvarOrganisationCode.IsForeignKey = false; colvarOrganisationCode.IsReadOnly = false; schema.Columns.Add(colvarOrganisationCode); TableSchema.TableColumn colvarOrganisationName = new TableSchema.TableColumn(schema); colvarOrganisationName.ColumnName = "OrganisationName"; colvarOrganisationName.DataType = DbType.AnsiString; colvarOrganisationName.MaxLength = 150; colvarOrganisationName.AutoIncrement = false; colvarOrganisationName.IsNullable = false; colvarOrganisationName.IsPrimaryKey = false; colvarOrganisationName.IsForeignKey = false; colvarOrganisationName.IsReadOnly = false; schema.Columns.Add(colvarOrganisationName); TableSchema.TableColumn colvarInstrumentID = new TableSchema.TableColumn(schema); colvarInstrumentID.ColumnName = "InstrumentID"; colvarInstrumentID.DataType = DbType.Guid; colvarInstrumentID.MaxLength = 0; colvarInstrumentID.AutoIncrement = false; colvarInstrumentID.IsNullable = false; colvarInstrumentID.IsPrimaryKey = false; colvarInstrumentID.IsForeignKey = false; colvarInstrumentID.IsReadOnly = false; schema.Columns.Add(colvarInstrumentID); TableSchema.TableColumn colvarInstrumentCode = new TableSchema.TableColumn(schema); colvarInstrumentCode.ColumnName = "InstrumentCode"; colvarInstrumentCode.DataType = DbType.AnsiString; colvarInstrumentCode.MaxLength = 50; colvarInstrumentCode.AutoIncrement = false; colvarInstrumentCode.IsNullable = false; colvarInstrumentCode.IsPrimaryKey = false; colvarInstrumentCode.IsForeignKey = false; colvarInstrumentCode.IsReadOnly = false; schema.Columns.Add(colvarInstrumentCode); TableSchema.TableColumn colvarInstrumentName = new TableSchema.TableColumn(schema); colvarInstrumentName.ColumnName = "InstrumentName"; colvarInstrumentName.DataType = DbType.AnsiString; colvarInstrumentName.MaxLength = 150; colvarInstrumentName.AutoIncrement = false; colvarInstrumentName.IsNullable = false; colvarInstrumentName.IsPrimaryKey = false; colvarInstrumentName.IsForeignKey = false; colvarInstrumentName.IsReadOnly = false; schema.Columns.Add(colvarInstrumentName); TableSchema.TableColumn colvarOrganisationRoleID = new TableSchema.TableColumn(schema); colvarOrganisationRoleID.ColumnName = "OrganisationRoleID"; colvarOrganisationRoleID.DataType = DbType.Guid; colvarOrganisationRoleID.MaxLength = 0; colvarOrganisationRoleID.AutoIncrement = false; colvarOrganisationRoleID.IsNullable = false; colvarOrganisationRoleID.IsPrimaryKey = false; colvarOrganisationRoleID.IsForeignKey = false; colvarOrganisationRoleID.IsReadOnly = false; schema.Columns.Add(colvarOrganisationRoleID); TableSchema.TableColumn colvarOrganisationRoleCode = new TableSchema.TableColumn(schema); colvarOrganisationRoleCode.ColumnName = "OrganisationRoleCode"; colvarOrganisationRoleCode.DataType = DbType.AnsiString; colvarOrganisationRoleCode.MaxLength = 50; colvarOrganisationRoleCode.AutoIncrement = false; colvarOrganisationRoleCode.IsNullable = false; colvarOrganisationRoleCode.IsPrimaryKey = false; colvarOrganisationRoleCode.IsForeignKey = false; colvarOrganisationRoleCode.IsReadOnly = false; schema.Columns.Add(colvarOrganisationRoleCode); TableSchema.TableColumn colvarOrganisationRoleName = new TableSchema.TableColumn(schema); colvarOrganisationRoleName.ColumnName = "OrganisationRoleName"; colvarOrganisationRoleName.DataType = DbType.AnsiString; colvarOrganisationRoleName.MaxLength = 150; colvarOrganisationRoleName.AutoIncrement = false; colvarOrganisationRoleName.IsNullable = false; colvarOrganisationRoleName.IsPrimaryKey = false; colvarOrganisationRoleName.IsForeignKey = false; colvarOrganisationRoleName.IsReadOnly = false; schema.Columns.Add(colvarOrganisationRoleName); TableSchema.TableColumn colvarStartDate = new TableSchema.TableColumn(schema); colvarStartDate.ColumnName = "StartDate"; colvarStartDate.DataType = DbType.Date; colvarStartDate.MaxLength = 0; colvarStartDate.AutoIncrement = false; colvarStartDate.IsNullable = true; colvarStartDate.IsPrimaryKey = false; colvarStartDate.IsForeignKey = false; colvarStartDate.IsReadOnly = false; schema.Columns.Add(colvarStartDate); TableSchema.TableColumn colvarEndDate = new TableSchema.TableColumn(schema); colvarEndDate.ColumnName = "EndDate"; colvarEndDate.DataType = DbType.Date; colvarEndDate.MaxLength = 0; colvarEndDate.AutoIncrement = false; colvarEndDate.IsNullable = true; colvarEndDate.IsPrimaryKey = false; colvarEndDate.IsForeignKey = false; colvarEndDate.IsReadOnly = false; schema.Columns.Add(colvarEndDate); TableSchema.TableColumn colvarLevel = new TableSchema.TableColumn(schema); colvarLevel.ColumnName = "Level"; colvarLevel.DataType = DbType.AnsiString; colvarLevel.MaxLength = 10; colvarLevel.AutoIncrement = false; colvarLevel.IsNullable = false; colvarLevel.IsPrimaryKey = false; colvarLevel.IsForeignKey = false; colvarLevel.IsReadOnly = false; schema.Columns.Add(colvarLevel); TableSchema.TableColumn colvarLevelCode = new TableSchema.TableColumn(schema); colvarLevelCode.ColumnName = "LevelCode"; colvarLevelCode.DataType = DbType.AnsiString; colvarLevelCode.MaxLength = 50; colvarLevelCode.AutoIncrement = false; colvarLevelCode.IsNullable = false; colvarLevelCode.IsPrimaryKey = false; colvarLevelCode.IsForeignKey = false; colvarLevelCode.IsReadOnly = false; schema.Columns.Add(colvarLevelCode); TableSchema.TableColumn colvarLevelName = new TableSchema.TableColumn(schema); colvarLevelName.ColumnName = "LevelName"; colvarLevelName.DataType = DbType.AnsiString; colvarLevelName.MaxLength = 150; colvarLevelName.AutoIncrement = false; colvarLevelName.IsNullable = false; colvarLevelName.IsPrimaryKey = false; colvarLevelName.IsForeignKey = false; colvarLevelName.IsReadOnly = false; schema.Columns.Add(colvarLevelName); TableSchema.TableColumn colvarWeight = new TableSchema.TableColumn(schema); colvarWeight.ColumnName = "Weight"; colvarWeight.DataType = DbType.Int32; colvarWeight.MaxLength = 0; colvarWeight.AutoIncrement = false; colvarWeight.IsNullable = false; colvarWeight.IsPrimaryKey = false; colvarWeight.IsForeignKey = false; colvarWeight.IsReadOnly = false; schema.Columns.Add(colvarWeight); TableSchema.TableColumn colvarIsReadOnly = new TableSchema.TableColumn(schema); colvarIsReadOnly.ColumnName = "IsReadOnly"; colvarIsReadOnly.DataType = DbType.Boolean; colvarIsReadOnly.MaxLength = 0; colvarIsReadOnly.AutoIncrement = false; colvarIsReadOnly.IsNullable = true; colvarIsReadOnly.IsPrimaryKey = false; colvarIsReadOnly.IsForeignKey = false; colvarIsReadOnly.IsReadOnly = false; schema.Columns.Add(colvarIsReadOnly); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["ObservationsDB"].AddSchema("vInstrumentOrganisation",schema); } } #endregion #region Query Accessor public static Query CreateQuery() { return new Query(Schema); } #endregion #region .ctors public VInstrumentOrganisation() { SetSQLProps(); SetDefaults(); MarkNew(); } public VInstrumentOrganisation(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) { ForceDefaults(); } MarkNew(); } public VInstrumentOrganisation(object keyID) { SetSQLProps(); LoadByKey(keyID); } public VInstrumentOrganisation(string columnName, object columnValue) { SetSQLProps(); LoadByParam(columnName,columnValue); } #endregion #region Props [XmlAttribute("Id")] [Bindable(true)] public Guid Id { get { return GetColumnValue<Guid>("ID"); } set { SetColumnValue("ID", value); } } [XmlAttribute("OrganisationID")] [Bindable(true)] public Guid OrganisationID { get { return GetColumnValue<Guid>("OrganisationID"); } set { SetColumnValue("OrganisationID", value); } } [XmlAttribute("OrganisationCode")] [Bindable(true)] public string OrganisationCode { get { return GetColumnValue<string>("OrganisationCode"); } set { SetColumnValue("OrganisationCode", value); } } [XmlAttribute("OrganisationName")] [Bindable(true)] public string OrganisationName { get { return GetColumnValue<string>("OrganisationName"); } set { SetColumnValue("OrganisationName", value); } } [XmlAttribute("InstrumentID")] [Bindable(true)] public Guid InstrumentID { get { return GetColumnValue<Guid>("InstrumentID"); } set { SetColumnValue("InstrumentID", value); } } [XmlAttribute("InstrumentCode")] [Bindable(true)] public string InstrumentCode { get { return GetColumnValue<string>("InstrumentCode"); } set { SetColumnValue("InstrumentCode", value); } } [XmlAttribute("InstrumentName")] [Bindable(true)] public string InstrumentName { get { return GetColumnValue<string>("InstrumentName"); } set { SetColumnValue("InstrumentName", value); } } [XmlAttribute("OrganisationRoleID")] [Bindable(true)] public Guid OrganisationRoleID { get { return GetColumnValue<Guid>("OrganisationRoleID"); } set { SetColumnValue("OrganisationRoleID", value); } } [XmlAttribute("OrganisationRoleCode")] [Bindable(true)] public string OrganisationRoleCode { get { return GetColumnValue<string>("OrganisationRoleCode"); } set { SetColumnValue("OrganisationRoleCode", value); } } [XmlAttribute("OrganisationRoleName")] [Bindable(true)] public string OrganisationRoleName { get { return GetColumnValue<string>("OrganisationRoleName"); } set { SetColumnValue("OrganisationRoleName", value); } } [XmlAttribute("StartDate")] [Bindable(true)] public DateTime? StartDate { get { return GetColumnValue<DateTime?>("StartDate"); } set { SetColumnValue("StartDate", value); } } [XmlAttribute("EndDate")] [Bindable(true)] public DateTime? EndDate { get { return GetColumnValue<DateTime?>("EndDate"); } set { SetColumnValue("EndDate", value); } } [XmlAttribute("Level")] [Bindable(true)] public string Level { get { return GetColumnValue<string>("Level"); } set { SetColumnValue("Level", value); } } [XmlAttribute("LevelCode")] [Bindable(true)] public string LevelCode { get { return GetColumnValue<string>("LevelCode"); } set { SetColumnValue("LevelCode", value); } } [XmlAttribute("LevelName")] [Bindable(true)] public string LevelName { get { return GetColumnValue<string>("LevelName"); } set { SetColumnValue("LevelName", value); } } [XmlAttribute("Weight")] [Bindable(true)] public int Weight { get { return GetColumnValue<int>("Weight"); } set { SetColumnValue("Weight", value); } } [XmlAttribute("IsReadOnly")] [Bindable(true)] public bool? IsReadOnly { get { return GetColumnValue<bool?>("IsReadOnly"); } set { SetColumnValue("IsReadOnly", value); } } #endregion #region Columns Struct public struct Columns { public static string Id = @"ID"; public static string OrganisationID = @"OrganisationID"; public static string OrganisationCode = @"OrganisationCode"; public static string OrganisationName = @"OrganisationName"; public static string InstrumentID = @"InstrumentID"; public static string InstrumentCode = @"InstrumentCode"; public static string InstrumentName = @"InstrumentName"; public static string OrganisationRoleID = @"OrganisationRoleID"; public static string OrganisationRoleCode = @"OrganisationRoleCode"; public static string OrganisationRoleName = @"OrganisationRoleName"; public static string StartDate = @"StartDate"; public static string EndDate = @"EndDate"; public static string Level = @"Level"; public static string LevelCode = @"LevelCode"; public static string LevelName = @"LevelName"; public static string Weight = @"Weight"; public static string IsReadOnly = @"IsReadOnly"; } #endregion #region IAbstractRecord Members public new CT GetColumnValue<CT>(string columnName) { return base.GetColumnValue<CT>(columnName); } public object GetColumnValue(string columnName) { return base.GetColumnValue<object>(columnName); } #endregion } }
using System; using System.Collections; using System.Collections.Generic; using System.Threading; using System.IO; using System.Net.Sockets; ////////////////////////////////////////////////////////////////////////////////// // Portions of this code were copied from // // http://www.codeproject.com/Articles/137979/Simple-HTTP-Server-in-Collections // // by author David Jeske. // ////////////////////////////////////////////////////////////////////////////////// namespace orange_core { class WebModule : HttpServer, IModule { public WebModule() : base(80) { // DON'T PUT ANYTHING HERE } public void Initialize() { Thread thread = new Thread(new ThreadStart(this.listen)); ModuleWatchdog.Register("Web Interface"); thread.Start(); } public void Shutdown() { // This can survive a SIGKILL, so do nothing } public void Update() { // No updating needed } public override void handleGETRequest(HttpProcessor p) { p.writeSuccess(); p.outputStream.WriteLine("<html><body><h1>Orange Web Portal</h1>"); p.outputStream.WriteLine("WARNING: This is Alpha stage software.<br>"); p.outputStream.WriteLine("url : {0}<br>", p.http_url); p.outputStream.WriteLine(getModuleStatus()); p.outputStream.WriteLine(getUserStatus()); p.outputStream.WriteLine("</body></html>"); } public override void handlePOSTRequest(HttpProcessor p, StreamReader inputData) { string data = inputData.ReadToEnd(); p.outputStream.WriteLine("<html><body><h1>test server</h1>"); p.outputStream.WriteLine("<a href=/test>return</a><p>"); p.outputStream.WriteLine("postbody: <pre>{0}</pre>", data); } private string getModuleStatus() { string result = "<h3>Modules</h3><ul>"; foreach (KeyValuePair<string, string> i in ModuleWatchdog.GetAllModulesWithStatus()) { result += String.Format("<li>{0}: {1}</li>", i.Key, i.Value); } result += "</ul>"; return result; } private string getUserStatus() { string result = "<h3>User Status</h3><ul>"; result += String.Format("<li>Distance Traveled: {0} ft</li>", (int)UserStatusModule.UserDistanceTraveled); result += String.Format("<li>GPS Coordinates: ({0},{1})</li>", UserStatusModule.UserPosition.x, UserStatusModule.UserPosition.y); result += String.Format("<li>Heart Rate: {0} BPM</li>", UserStatusModule.UserHeartRate); result += String.Format("<li>Connected time: {0}:{1}:{2}</li>", UserStatusModule.UserConnectedTime.Hour, UserStatusModule.UserConnectedTime.Minute, UserStatusModule.UserConnectedTime.Second); result += String.Format("<li>Primary Battery ('{0}'): {1}%", UserStatusModule.UserBatteryName, UserStatusModule.UserBatteryLevel); result += "</ul>"; return result; } } public abstract class HttpServer { protected int port; TcpListener listener; bool is_active = true; public HttpServer(int port) { this.port = port; } public void listen() { listener = new TcpListener(port); listener.Start(); while (is_active) { ModuleWatchdog.HeartBeat("Web Interface"); TcpClient s = listener.AcceptTcpClient(); HttpProcessor processor = new HttpProcessor(s, this); Thread thread = new Thread(new ThreadStart(processor.process)); thread.Start(); Thread.Sleep(1); } } public abstract void handleGETRequest(HttpProcessor p); public abstract void handlePOSTRequest(HttpProcessor p, StreamReader inputData); } public class HttpProcessor { public TcpClient socket; public HttpServer srv; private Stream inputStream; public StreamWriter outputStream; public String http_method; public String http_url; public String http_protocol_versionstring; public Hashtable httpHeaders = new Hashtable(); private static int MAX_POST_SIZE = 10 * 1024 * 1024; // 10MB public HttpProcessor(TcpClient s, HttpServer srv) { this.socket = s; this.srv = srv; } private string streamReadLine(Stream inputStream) { int next_char; string data = ""; while (true) { next_char = inputStream.ReadByte(); if (next_char == '\n') { break; } if (next_char == '\r') { continue; } if (next_char == -1) { Thread.Sleep(1); continue; }; data += Convert.ToChar(next_char); } return data; } public void process() { // we can't use a StreamReader for input, because it buffers up extra data on us inside it's // "processed" view of the world, and we want the data raw after the headers inputStream = new BufferedStream(socket.GetStream()); // we probably shouldn't be using a streamwriter for all output from handlers either outputStream = new StreamWriter(new BufferedStream(socket.GetStream())); try { parseRequest(); readHeaders(); if (http_method.Equals("GET")) { handleGETRequest(); } else if (http_method.Equals("POST")) { handlePOSTRequest(); } } catch (Exception e) { writeFailure(); } outputStream.Flush(); // bs.Flush(); // flush any remaining output inputStream = null; outputStream = null; // bs = null; socket.Close(); } public void parseRequest() { String request = streamReadLine(inputStream); string[] tokens = request.Split(' '); if (tokens.Length != 3) { throw new Exception("invalid http request line"); } http_method = tokens[0].ToUpper(); http_url = tokens[1]; http_protocol_versionstring = tokens[2]; } public void readHeaders() { String line; while ((line = streamReadLine(inputStream)) != null) { if (line.Equals("")) { return; } int separator = line.IndexOf(':'); if (separator == -1) { throw new Exception("invalid http header line: " + line); } String name = line.Substring(0, separator); int pos = separator + 1; while ((pos < line.Length) && (line[pos] == ' ')) { pos++; // strip any spaces } string value = line.Substring(pos, line.Length - pos); httpHeaders[name] = value; } } public void handleGETRequest() { srv.handleGETRequest(this); } private const int BUF_SIZE = 4096; public void handlePOSTRequest() { // this post data processing just reads everything into a memory stream. // this is fine for smallish things, but for large stuff we should really // hand an input stream to the request processor. However, the input stream // we hand him needs to let him see the "end of the stream" at this content // length, because otherwise he won't know when he's seen it all! int content_len = 0; MemoryStream ms = new MemoryStream(); if (this.httpHeaders.ContainsKey("Content-Length")) { content_len = Convert.ToInt32(this.httpHeaders["Content-Length"]); if (content_len > MAX_POST_SIZE) { throw new Exception( String.Format("POST Content-Length({0}) too big for this simple server", content_len)); } byte[] buf = new byte[BUF_SIZE]; int to_read = content_len; while (to_read > 0) { int numread = this.inputStream.Read(buf, 0, Math.Min(BUF_SIZE, to_read)); if (numread == 0) { if (to_read == 0) { break; } else { throw new Exception("client disconnected during post"); } } to_read -= numread; ms.Write(buf, 0, numread); } ms.Seek(0, SeekOrigin.Begin); } srv.handlePOSTRequest(this, new StreamReader(ms)); } public void writeSuccess(string content_type="text/html") { // this is the successful HTTP response line outputStream.WriteLine("HTTP/1.0 200 OK"); // these are the HTTP headers... outputStream.WriteLine("Content-Type: " + content_type); outputStream.WriteLine("Connection: close"); // ..add your own headers here if you like outputStream.WriteLine(""); // this terminates the HTTP headers.. everything after this is HTTP body.. } public void writeFailure() { // this is an http 404 failure response outputStream.WriteLine("HTTP/1.0 404 File not found"); // these are the HTTP headers outputStream.WriteLine("Connection: close"); // ..add your own headers here outputStream.WriteLine(""); // this terminates the HTTP headers. } } }
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. namespace System.Data.Entity.Interception { using System.Data.Common; using System.Data.Entity.Core; using System.Data.Entity.Core.Common; using System.Data.Entity.Core.EntityClient; using System.Data.Entity.Core.Objects; using System.Data.Entity.Infrastructure; using System.Data.Entity.Infrastructure.DependencyResolution; using System.Data.Entity.Infrastructure.Interception; using System.Data.Entity.SqlServer; using System.Data.Entity.TestHelpers; using System.Data.SqlClient; using System.Linq; using System.Threading; using System.Threading.Tasks; using Moq; using Xunit; public class CommitFailureTests : FunctionalTestBase { private void Execute_commit_failure_test( Action<Action> verifyInitialization, Action<Action> verifySaveChanges, int expectedBlogs, bool useTransactionHandler, bool useExecutionStrategy, bool rollbackOnFail) { var failingTransactionInterceptorMock = new Mock<FailingTransactionInterceptor> { CallBase = true }; var failingTransactionInterceptor = failingTransactionInterceptorMock.Object; DbInterception.Add(failingTransactionInterceptor); if (useTransactionHandler) { MutableResolver.AddResolver<Func<TransactionHandler>>( new TransactionHandlerResolver(() => new CommitFailureHandler(), null, null)); } var isSqlAzure = DatabaseTestHelpers.IsSqlAzure(ModelHelpers.BaseConnectionString); if (useExecutionStrategy) { MutableResolver.AddResolver<Func<IDbExecutionStrategy>>( key => (Func<IDbExecutionStrategy>) (() => isSqlAzure ? new TestSqlAzureExecutionStrategy() : (IDbExecutionStrategy) new SqlAzureExecutionStrategy(maxRetryCount: 2, maxDelay: TimeSpan.FromMilliseconds(1)))); } try { using (var context = new BlogContextCommit()) { context.Database.Delete(); failingTransactionInterceptor.ShouldFailTimes = 1; failingTransactionInterceptor.ShouldRollBack = rollbackOnFail; verifyInitialization(() => context.Blogs.Count()); failingTransactionInterceptor.ShouldFailTimes = 0; ExtendedSqlAzureExecutionStrategy.ExecuteNew( () => { Assert.Equal(1, context.Blogs.Count()); }); failingTransactionInterceptor.ShouldFailTimes = 1; context.Blogs.Add(new BlogContext.Blog()); verifySaveChanges(() => context.SaveChanges()); var expectedCommitCount = useTransactionHandler ? useExecutionStrategy ? 6 : rollbackOnFail ? 4 : 3 : 4; failingTransactionInterceptorMock.Verify( m => m.Committing(It.IsAny<DbTransaction>(), It.IsAny<DbTransactionInterceptionContext>()), isSqlAzure ? Times.AtLeast(expectedCommitCount) : Times.Exactly(expectedCommitCount)); } using (var context = new BlogContextCommit()) { ExtendedSqlAzureExecutionStrategy.ExecuteNew( () => { Assert.Equal(expectedBlogs, context.Blogs.Count()); }); using (var transactionContext = new TransactionContext(context.Database.Connection)) { using (var infoContext = GetInfoContext(transactionContext)) { Assert.True( !infoContext.TableExists("__Transactions") || !transactionContext.Transactions.Any()); } } } } finally { DbInterception.Remove(failingTransactionInterceptor); MutableResolver.ClearResolvers(); } DbDispatchersHelpers.AssertNoInterceptors(); } [Fact] public void No_TransactionHandler_and_no_ExecutionStrategy_throws_CommitFailedException_on_commit_fail() { Execute_commit_failure_test( c => Assert.Throws<DataException>(() => c()).InnerException.ValidateMessage("CommitFailed"), c => Assert.Throws<CommitFailedException>(() => c()).ValidateMessage("CommitFailed"), expectedBlogs: 1, useTransactionHandler: false, useExecutionStrategy: false, rollbackOnFail: true); } [Fact] public void No_TransactionHandler_and_no_ExecutionStrategy_throws_CommitFailedException_on_false_commit_fail() { Execute_commit_failure_test( c => Assert.Throws<DataException>(() => c()).InnerException.ValidateMessage("CommitFailed"), c => Assert.Throws<CommitFailedException>(() => c()).ValidateMessage("CommitFailed"), expectedBlogs: 2, useTransactionHandler: false, useExecutionStrategy: false, rollbackOnFail: false); } [Fact] [UseDefaultExecutionStrategy] public void TransactionHandler_and_no_ExecutionStrategy_rethrows_original_exception_on_commit_fail() { Execute_commit_failure_test( c => Assert.Throws<TimeoutException>(() => c()), c => { var exception = Assert.Throws<EntityException>(() => c()); Assert.IsType<TimeoutException>(exception.InnerException); }, expectedBlogs: 1, useTransactionHandler: true, useExecutionStrategy: false, rollbackOnFail: true); } [Fact] public void TransactionHandler_and_no_ExecutionStrategy_does_not_throw_on_false_commit_fail() { Execute_commit_failure_test( c => c(), c => c(), expectedBlogs: 2, useTransactionHandler: true, useExecutionStrategy: false, rollbackOnFail: false); } [Fact] public void No_TransactionHandler_and_ExecutionStrategy_throws_CommitFailedException_on_commit_fail() { Execute_commit_failure_test( c => Assert.Throws<DataException>(() => c()).InnerException.ValidateMessage("CommitFailed"), c => Assert.Throws<CommitFailedException>(() => c()).ValidateMessage("CommitFailed"), expectedBlogs: 1, useTransactionHandler: false, useExecutionStrategy: true, rollbackOnFail: true); } [Fact] public void No_TransactionHandler_and_ExecutionStrategy_throws_CommitFailedException_on_false_commit_fail() { Execute_commit_failure_test( c => Assert.Throws<DataException>(() => c()).InnerException.ValidateMessage("CommitFailed"), c => Assert.Throws<CommitFailedException>(() => c()).ValidateMessage("CommitFailed"), expectedBlogs: 2, useTransactionHandler: false, useExecutionStrategy: true, rollbackOnFail: false); } [Fact] public void TransactionHandler_and_ExecutionStrategy_retries_on_commit_fail() { Execute_commit_failure_test( c => c(), c => c(), expectedBlogs: 2, useTransactionHandler: true, useExecutionStrategy: true, rollbackOnFail: true); } [Fact] public void TransactionHandler_and_ExecutionStrategy_does_not_retry_on_false_commit_fail() { MutableResolver.AddResolver<Func<TransactionHandler>>( new TransactionHandlerResolver(() => new CommitFailureHandler(), null, null)); TransactionHandler_and_ExecutionStrategy_does_not_retry_on_false_commit_fail_implementation( context => context.SaveChanges()); } #if !NET40 [Fact] public void TransactionHandler_and_ExecutionStrategy_does_not_retry_on_false_commit_fail_async() { MutableResolver.AddResolver<Func<TransactionHandler>>( new TransactionHandlerResolver(() => new CommitFailureHandler(), null, null)); TransactionHandler_and_ExecutionStrategy_does_not_retry_on_false_commit_fail_implementation( context => context.SaveChangesAsync().Wait()); } #endif [Fact] public void TransactionHandler_and_ExecutionStrategy_does_not_retry_on_false_commit_fail_with_custom_TransactionContext() { MutableResolver.AddResolver<Func<TransactionHandler>>( new TransactionHandlerResolver(() => new CommitFailureHandler(c => new MyTransactionContext(c)), null, null)); TransactionHandler_and_ExecutionStrategy_does_not_retry_on_false_commit_fail_implementation( context => { context.SaveChanges(); using (var infoContext = GetInfoContext(context)) { Assert.True(infoContext.TableExists("MyTransactions")); var column = infoContext.Columns.Single(c => c.Name == "Time"); Assert.Equal("datetime2", column.Type); } }); } public class MyTransactionContext : TransactionContext { public MyTransactionContext(DbConnection connection) : base(connection) { } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<TransactionRow>() .ToTable("MyTransactions") .HasKey(e => e.Id) .Property(e => e.CreationTime).HasColumnName("Time").HasColumnType("datetime2"); } } private void TransactionHandler_and_ExecutionStrategy_does_not_retry_on_false_commit_fail_implementation( Action<BlogContextCommit> runAndVerify) { var failingTransactionInterceptorMock = new Mock<FailingTransactionInterceptor> { CallBase = true }; var failingTransactionInterceptor = failingTransactionInterceptorMock.Object; DbInterception.Add(failingTransactionInterceptor); var isSqlAzure = DatabaseTestHelpers.IsSqlAzure(ModelHelpers.BaseConnectionString); MutableResolver.AddResolver<Func<IDbExecutionStrategy>>( key => (Func<IDbExecutionStrategy>) (() => isSqlAzure ? new TestSqlAzureExecutionStrategy() : (IDbExecutionStrategy)new SqlAzureExecutionStrategy(maxRetryCount: 2, maxDelay: TimeSpan.FromMilliseconds(1)))); try { using (var context = new BlogContextCommit()) { failingTransactionInterceptor.ShouldFailTimes = 0; context.Database.Delete(); Assert.Equal(1, context.Blogs.Count()); failingTransactionInterceptor.ShouldFailTimes = 2; failingTransactionInterceptor.ShouldRollBack = false; context.Blogs.Add(new BlogContext.Blog()); runAndVerify(context); failingTransactionInterceptorMock.Verify( m => m.Committing(It.IsAny<DbTransaction>(), It.IsAny<DbTransactionInterceptionContext>()), isSqlAzure ? Times.AtLeast(3) : Times.Exactly(3)); } using (var context = new BlogContextCommit()) { Assert.Equal(2, context.Blogs.Count()); using (var transactionContext = new TransactionContext(context.Database.Connection)) { using (var infoContext = GetInfoContext(transactionContext)) { Assert.True( !infoContext.TableExists("__Transactions") || !transactionContext.Transactions.Any()); } } } } finally { DbInterception.Remove(failingTransactionInterceptorMock.Object); MutableResolver.ClearResolvers(); } DbDispatchersHelpers.AssertNoInterceptors(); } [Fact] public void CommitFailureHandler_Dispose_does_not_use_ExecutionStrategy() { CommitFailureHandler_with_ExecutionStrategy_test( (c, executionStrategyMock) => { c.TransactionHandler.Dispose(); executionStrategyMock.Verify(e => e.Execute(It.IsAny<Func<int>>()), Times.Exactly(3)); }); } [Fact] public void CommitFailureHandler_Dispose_catches_exceptions() { CommitFailureHandler_with_ExecutionStrategy_test( (c, executionStrategyMock) => { using (var transactionContext = new TransactionContext(((EntityConnection)c.Connection).StoreConnection)) { foreach (var tran in transactionContext.Set<TransactionRow>().ToList()) { transactionContext.Transactions.Remove(tran); } transactionContext.SaveChanges(); } c.TransactionHandler.Dispose(); }); } [Fact] public void CommitFailureHandler_prunes_transactions_after_set_amount() { CommitFailureHandler_prunes_transactions_after_set_amount_implementation(false); } [Fact] public void CommitFailureHandler_prunes_transactions_after_set_amount_and_handles_false_failure() { CommitFailureHandler_prunes_transactions_after_set_amount_implementation(true); } private void CommitFailureHandler_prunes_transactions_after_set_amount_implementation(bool shouldThrow) { var failingTransactionInterceptor = new FailingTransactionInterceptor(); DbInterception.Add(failingTransactionInterceptor); MutableResolver.AddResolver<Func<TransactionHandler>>( new TransactionHandlerResolver(() => new MyCommitFailureHandler(c => new TransactionContext(c)), null, null)); try { using (var context = new BlogContextCommit()) { context.Database.Delete(); Assert.Equal(1, context.Blogs.Count()); var objectContext = ((IObjectContextAdapter)context).ObjectContext; var transactionHandler = (MyCommitFailureHandler)objectContext.TransactionHandler; for (var i = 0; i < transactionHandler.PruningLimit; i++) { context.Blogs.Add(new BlogContext.Blog()); context.SaveChanges(); } AssertTransactionHistoryCount(context, transactionHandler.PruningLimit); if (shouldThrow) { failingTransactionInterceptor.ShouldFailTimes = 1; failingTransactionInterceptor.ShouldRollBack = false; } context.Blogs.Add(new BlogContext.Blog()); context.SaveChanges(); context.Blogs.Add(new BlogContext.Blog()); context.SaveChanges(); AssertTransactionHistoryCount(context, 1); Assert.Equal(1, transactionHandler.TransactionContext.ChangeTracker.Entries<TransactionRow>().Count()); } } finally { DbInterception.Remove(failingTransactionInterceptor); MutableResolver.ClearResolvers(); } DbDispatchersHelpers.AssertNoInterceptors(); } [Fact] public void CommitFailureHandler_ClearTransactionHistory_uses_ExecutionStrategy() { CommitFailureHandler_with_ExecutionStrategy_test( (c, executionStrategyMock) => { ((MyCommitFailureHandler)c.TransactionHandler).ClearTransactionHistory(); executionStrategyMock.Verify(e => e.Execute(It.IsAny<Func<int>>()), Times.Exactly(4)); Assert.Empty(((MyCommitFailureHandler)c.TransactionHandler).TransactionContext.ChangeTracker.Entries<TransactionRow>()); }); } [Fact] public void CommitFailureHandler_ClearTransactionHistory_does_not_catch_exceptions() { var failingTransactionInterceptor = new FailingTransactionInterceptor(); DbInterception.Add(failingTransactionInterceptor); try { CommitFailureHandler_with_ExecutionStrategy_test( (c, executionStrategyMock) => { MutableResolver.AddResolver<Func<IDbExecutionStrategy>>( key => (Func<IDbExecutionStrategy>)(() => new SimpleExecutionStrategy())); failingTransactionInterceptor.ShouldFailTimes = 1; failingTransactionInterceptor.ShouldRollBack = true; Assert.Throws<EntityException>( () => ((MyCommitFailureHandler)c.TransactionHandler).ClearTransactionHistory()); MutableResolver.ClearResolvers(); AssertTransactionHistoryCount(c, 1); ((MyCommitFailureHandler)c.TransactionHandler).ClearTransactionHistory(); AssertTransactionHistoryCount(c, 0); }); } finally { DbInterception.Remove(failingTransactionInterceptor); } } [Fact] public void CommitFailureHandler_PruneTransactionHistory_uses_ExecutionStrategy() { CommitFailureHandler_with_ExecutionStrategy_test( (c, executionStrategyMock) => { ((MyCommitFailureHandler)c.TransactionHandler).PruneTransactionHistory(); executionStrategyMock.Verify(e => e.Execute(It.IsAny<Func<int>>()), Times.Exactly(4)); Assert.Empty(((MyCommitFailureHandler)c.TransactionHandler).TransactionContext.ChangeTracker.Entries<TransactionRow>()); }); } [Fact] public void CommitFailureHandler_PruneTransactionHistory_does_not_catch_exceptions() { var failingTransactionInterceptor = new FailingTransactionInterceptor(); DbInterception.Add(failingTransactionInterceptor); try { CommitFailureHandler_with_ExecutionStrategy_test( (c, executionStrategyMock) => { MutableResolver.AddResolver<Func<IDbExecutionStrategy>>( key => (Func<IDbExecutionStrategy>)(() => new SimpleExecutionStrategy())); failingTransactionInterceptor.ShouldFailTimes = 1; failingTransactionInterceptor.ShouldRollBack = true; Assert.Throws<EntityException>( () => ((MyCommitFailureHandler)c.TransactionHandler).PruneTransactionHistory()); MutableResolver.ClearResolvers(); AssertTransactionHistoryCount(c, 1); ((MyCommitFailureHandler)c.TransactionHandler).PruneTransactionHistory(); AssertTransactionHistoryCount(c, 0); }); } finally { DbInterception.Remove(failingTransactionInterceptor); } } #if !NET40 [Fact] public void CommitFailureHandler_ClearTransactionHistoryAsync_uses_ExecutionStrategy() { CommitFailureHandler_with_ExecutionStrategy_test( (c, executionStrategyMock) => { ((MyCommitFailureHandler)c.TransactionHandler).ClearTransactionHistoryAsync().Wait(); executionStrategyMock.Verify( e => e.ExecuteAsync(It.IsAny<Func<Task<int>>>(), It.IsAny<CancellationToken>()), Times.Once()); Assert.Empty(((MyCommitFailureHandler)c.TransactionHandler).TransactionContext.ChangeTracker.Entries<TransactionRow>()); }); } [Fact] public void CommitFailureHandler_ClearTransactionHistoryAsync_does_not_catch_exceptions() { var failingTransactionInterceptor = new FailingTransactionInterceptor(); DbInterception.Add(failingTransactionInterceptor); try { CommitFailureHandler_with_ExecutionStrategy_test( (c, executionStrategyMock) => { MutableResolver.AddResolver<Func<IDbExecutionStrategy>>( key => (Func<IDbExecutionStrategy>)(() => new SimpleExecutionStrategy())); failingTransactionInterceptor.ShouldFailTimes = 1; failingTransactionInterceptor.ShouldRollBack = true; Assert.Throws<EntityException>( () => ExceptionHelpers.UnwrapAggregateExceptions( () => ((MyCommitFailureHandler)c.TransactionHandler).ClearTransactionHistoryAsync().Wait())); MutableResolver.ClearResolvers(); AssertTransactionHistoryCount(c, 1); ((MyCommitFailureHandler)c.TransactionHandler).ClearTransactionHistoryAsync().Wait(); AssertTransactionHistoryCount(c, 0); }); } finally { DbInterception.Remove(failingTransactionInterceptor); } } [Fact] public void CommitFailureHandler_PruneTransactionHistoryAsync_uses_ExecutionStrategy() { CommitFailureHandler_with_ExecutionStrategy_test( (c, executionStrategyMock) => { ((MyCommitFailureHandler)c.TransactionHandler).PruneTransactionHistoryAsync().Wait(); executionStrategyMock.Verify( e => e.ExecuteAsync(It.IsAny<Func<Task<int>>>(), It.IsAny<CancellationToken>()), Times.Once()); Assert.Empty(((MyCommitFailureHandler)c.TransactionHandler).TransactionContext.ChangeTracker.Entries<TransactionRow>()); }); } [Fact] public void CommitFailureHandler_PruneTransactionHistoryAsync_does_not_catch_exceptions() { var failingTransactionInterceptor = new FailingTransactionInterceptor(); DbInterception.Add(failingTransactionInterceptor); try { CommitFailureHandler_with_ExecutionStrategy_test( (c, executionStrategyMock) => { MutableResolver.AddResolver<Func<IDbExecutionStrategy>>( key => (Func<IDbExecutionStrategy>)(() => new SimpleExecutionStrategy())); failingTransactionInterceptor.ShouldFailTimes = 1; failingTransactionInterceptor.ShouldRollBack = true; Assert.Throws<EntityException>( () => ExceptionHelpers.UnwrapAggregateExceptions( () => ((MyCommitFailureHandler)c.TransactionHandler).PruneTransactionHistoryAsync().Wait())); MutableResolver.ClearResolvers(); AssertTransactionHistoryCount(c, 1); ((MyCommitFailureHandler)c.TransactionHandler).PruneTransactionHistoryAsync().Wait(); AssertTransactionHistoryCount(c, 0); }); } finally { DbInterception.Remove(failingTransactionInterceptor); } } #endif private void CommitFailureHandler_with_ExecutionStrategy_test( Action<ObjectContext, Mock<TestSqlAzureExecutionStrategy>> pruneAndVerify) { MutableResolver.AddResolver<Func<TransactionHandler>>( new TransactionHandlerResolver(() => new MyCommitFailureHandler(c => new TransactionContext(c)), null, null)); var executionStrategyMock = new Mock<TestSqlAzureExecutionStrategy> { CallBase = true }; MutableResolver.AddResolver<Func<IDbExecutionStrategy>>( key => (Func<IDbExecutionStrategy>)(() => executionStrategyMock.Object)); try { using (var context = new BlogContextCommit()) { context.Database.Delete(); Assert.Equal(1, context.Blogs.Count()); context.Blogs.Add(new BlogContext.Blog()); context.SaveChanges(); AssertTransactionHistoryCount(context, 1); executionStrategyMock.Verify(e => e.Execute(It.IsAny<Func<int>>()), Times.Exactly(3)); #if !NET40 executionStrategyMock.Verify( e => e.ExecuteAsync(It.IsAny<Func<Task<int>>>(), It.IsAny<CancellationToken>()), Times.Never()); #endif var objectContext = ((IObjectContextAdapter)context).ObjectContext; pruneAndVerify(objectContext, executionStrategyMock); using (var transactionContext = new TransactionContext(context.Database.Connection)) { Assert.Equal(0, transactionContext.Transactions.Count()); } } } finally { MutableResolver.ClearResolvers(); } } private void AssertTransactionHistoryCount(DbContext context, int count) { AssertTransactionHistoryCount(((IObjectContextAdapter)context).ObjectContext, count); } private void AssertTransactionHistoryCount(ObjectContext context, int count) { using (var transactionContext = new TransactionContext(((EntityConnection)context.Connection).StoreConnection)) { Assert.Equal(count, transactionContext.Transactions.Count()); } } public class SimpleExecutionStrategy : IDbExecutionStrategy { public bool RetriesOnFailure { get { return false; } } public virtual void Execute(Action operation) { operation(); } public virtual TResult Execute<TResult>(Func<TResult> operation) { return operation(); } #if !NET40 public virtual Task ExecuteAsync(Func<Task> operation, CancellationToken cancellationToken) { return operation(); } public virtual Task<TResult> ExecuteAsync<TResult>(Func<Task<TResult>> operation, CancellationToken cancellationToken) { return operation(); } #endif } public class MyCommitFailureHandler : CommitFailureHandler { public MyCommitFailureHandler(Func<DbConnection, TransactionContext> transactionContextFactory) : base(transactionContextFactory) { } public new void MarkTransactionForPruning(TransactionRow transaction) { base.MarkTransactionForPruning(transaction); } public new TransactionContext TransactionContext { get { return base.TransactionContext; } } public new virtual int PruningLimit { get { return base.PruningLimit; } } } [Fact] [UseDefaultExecutionStrategy] public void CommitFailureHandler_supports_nested_transactions() { MutableResolver.AddResolver<Func<TransactionHandler>>( new TransactionHandlerResolver(() => new CommitFailureHandler(), null, null)); try { using (var context = new BlogContextCommit()) { context.Database.Delete(); Assert.Equal(1, context.Blogs.Count()); context.Blogs.Add(new BlogContext.Blog()); using (var transaction = context.Database.BeginTransaction()) { using (var innerContext = new BlogContextCommit()) { using (var innerTransaction = innerContext.Database.BeginTransaction()) { Assert.Equal(1, innerContext.Blogs.Count()); innerContext.Blogs.Add(new BlogContext.Blog()); innerContext.SaveChanges(); innerTransaction.Commit(); } } context.SaveChanges(); transaction.Commit(); } } using (var context = new BlogContextCommit()) { Assert.Equal(3, context.Blogs.Count()); } } finally { MutableResolver.ClearResolvers(); } DbDispatchersHelpers.AssertNoInterceptors(); } [Fact] public void BuildDatabaseInitializationScript_can_be_used_to_initialize_the_database() { MutableResolver.AddResolver<Func<TransactionHandler>>( new TransactionHandlerResolver(() => new CommitFailureHandler(), null, null)); MutableResolver.AddResolver<Func<IDbExecutionStrategy>>( key => (Func<IDbExecutionStrategy>)(() => new TestSqlAzureExecutionStrategy())); try { using (var context = new BlogContextCommit()) { context.Database.Delete(); Assert.Equal(1, context.Blogs.Count()); } MutableResolver.AddResolver<Func<TransactionHandler>>( new TransactionHandlerResolver(() => new CommitFailureHandler(c => new TransactionContextNoInit(c)), null, null)); using (var context = new BlogContextCommit()) { context.Blogs.Add(new BlogContext.Blog()); Assert.Throws<EntityException>(() => context.SaveChanges()); context.Database.ExecuteSqlCommand( TransactionalBehavior.DoNotEnsureTransaction, ((IObjectContextAdapter)context).ObjectContext.TransactionHandler.BuildDatabaseInitializationScript()); context.SaveChanges(); } using (var context = new BlogContextCommit()) { Assert.Equal(2, context.Blogs.Count()); } } finally { MutableResolver.ClearResolvers(); } DbDispatchersHelpers.AssertNoInterceptors(); } [Fact] public void BuildDatabaseInitializationScript_can_be_used_to_initialize_the_database_if_no_migration_generator() { var mockDbProviderServiceResolver = new Mock<IDbDependencyResolver>(); mockDbProviderServiceResolver .Setup(r => r.GetService(It.IsAny<Type>(), It.IsAny<string>())) .Returns(SqlProviderServices.Instance); MutableResolver.AddResolver<DbProviderServices>(mockDbProviderServiceResolver.Object); var mockDbProviderFactoryResolver = new Mock<IDbDependencyResolver>(); mockDbProviderFactoryResolver .Setup(r => r.GetService(It.IsAny<Type>(), It.IsAny<string>())) .Returns(SqlClientFactory.Instance); MutableResolver.AddResolver<DbProviderFactory>(mockDbProviderFactoryResolver.Object); BuildDatabaseInitializationScript_can_be_used_to_initialize_the_database(); } [Fact] public void FromContext_returns_the_current_handler() { MutableResolver.AddResolver<Func<TransactionHandler>>( new TransactionHandlerResolver(() => new CommitFailureHandler(), null, null)); try { using (var context = new BlogContextCommit()) { context.Database.Delete(); var commitFailureHandler = CommitFailureHandler.FromContext(((IObjectContextAdapter)context).ObjectContext); Assert.IsType<CommitFailureHandler>(commitFailureHandler); Assert.Same(commitFailureHandler, CommitFailureHandler.FromContext(context)); } } finally { MutableResolver.ClearResolvers(); } } [Fact] public void TransactionHandler_is_disposed_even_if_the_context_is_not() { var context = new BlogContextCommit(); context.Database.Delete(); Assert.Equal(1, context.Blogs.Count()); var weakDbContext = new WeakReference(context); var weakObjectContext = new WeakReference(((IObjectContextAdapter)context).ObjectContext); var weakTransactionHandler = new WeakReference(((IObjectContextAdapter)context).ObjectContext.TransactionHandler); context = null; GC.Collect(); GC.WaitForPendingFinalizers(); Assert.False(weakDbContext.IsAlive); Assert.False(weakObjectContext.IsAlive); DbDispatchersHelpers.AssertNoInterceptors(); // Need a second pass as the TransactionHandler is removed from the interceptors in the ObjectContext finalizer GC.Collect(); Assert.False(weakTransactionHandler.IsAlive); } public class TransactionContextNoInit : TransactionContext { static TransactionContextNoInit() { Database.SetInitializer<TransactionContextNoInit>(null); } public TransactionContextNoInit(DbConnection connection) : base(connection) { } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<TransactionRow>() .ToTable("TransactionContextNoInit"); } } public class FailingTransactionInterceptor : IDbTransactionInterceptor { private int _timesToFail; private int _shouldFailTimes; public int ShouldFailTimes { get { return _shouldFailTimes; } set { _shouldFailTimes = value; _timesToFail = value; } } public bool ShouldRollBack; public FailingTransactionInterceptor() { _timesToFail = ShouldFailTimes; } public void ConnectionGetting(DbTransaction transaction, DbTransactionInterceptionContext<DbConnection> interceptionContext) { } public void ConnectionGot(DbTransaction transaction, DbTransactionInterceptionContext<DbConnection> interceptionContext) { } public void IsolationLevelGetting( DbTransaction transaction, DbTransactionInterceptionContext<IsolationLevel> interceptionContext) { } public void IsolationLevelGot(DbTransaction transaction, DbTransactionInterceptionContext<IsolationLevel> interceptionContext) { } public virtual void Committing(DbTransaction transaction, DbTransactionInterceptionContext interceptionContext) { if (_timesToFail-- > 0) { if (ShouldRollBack) { transaction.Rollback(); } else { transaction.Commit(); } interceptionContext.Exception = new TimeoutException(); } else { _timesToFail = ShouldFailTimes; } } public void Committed(DbTransaction transaction, DbTransactionInterceptionContext interceptionContext) { if (interceptionContext.Exception != null) { _timesToFail--; } } public void Disposing(DbTransaction transaction, DbTransactionInterceptionContext interceptionContext) { } public void Disposed(DbTransaction transaction, DbTransactionInterceptionContext interceptionContext) { } public void RollingBack(DbTransaction transaction, DbTransactionInterceptionContext interceptionContext) { } public void RolledBack(DbTransaction transaction, DbTransactionInterceptionContext interceptionContext) { } } public class BlogContextCommit : BlogContext { static BlogContextCommit() { Database.SetInitializer<BlogContextCommit>(new BlogInitializer()); } } } }
/* * 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. */ // ReSharper disable UnusedAutoPropertyAccessor.Global // ReSharper disable MemberCanBePrivate.Global namespace Apache.Ignite.Core.Cache.Configuration { using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using Apache.Ignite.Core.Binary; using Apache.Ignite.Core.Impl.Binary; using Apache.Ignite.Core.Impl.Cache; using Apache.Ignite.Core.Impl.Client; using Apache.Ignite.Core.Log; /// <summary> /// Query entity is a description of cache entry (composed of key and value) /// in a way of how it must be indexed and can be queried. /// </summary> public sealed class QueryEntity : IQueryEntityInternal, IBinaryRawWriteAwareEx { /** */ private Type _keyType; /** */ private Type _valueType; /** */ private string _valueTypeName; /** */ private string _keyTypeName; /** */ private Dictionary<string, string> _aliasMap; /** */ private ICollection<QueryAlias> _aliases; /// <summary> /// Initializes a new instance of the <see cref="QueryEntity"/> class. /// </summary> public QueryEntity() { // No-op. } /// <summary> /// Initializes a new instance of the <see cref="QueryEntity"/> class. /// </summary> /// <param name="valueType">Type of the cache entry value.</param> public QueryEntity(Type valueType) { ValueType = valueType; } /// <summary> /// Initializes a new instance of the <see cref="QueryEntity"/> class. /// </summary> /// <param name="keyType">Type of the key.</param> /// <param name="valueType">Type of the value.</param> public QueryEntity(Type keyType, Type valueType) { KeyType = keyType; ValueType = valueType; } /// <summary> /// Gets or sets key Java type name. /// </summary> public string KeyTypeName { get { return _keyTypeName; } set { _keyTypeName = value; _keyType = null; } } /// <summary> /// Gets or sets the type of the key. /// <para /> /// This is a shortcut for <see cref="KeyTypeName"/>. Getter will return null for non-primitive types. /// <para /> /// Setting this property will overwrite <see cref="Fields"/> and <see cref="Indexes"/> according to /// <see cref="QuerySqlFieldAttribute"/>, if any. /// </summary> public Type KeyType { get { return _keyType ?? JavaTypes.GetDotNetType(KeyTypeName); } set { RescanAttributes(value, _valueType); // Do this first because it can throw KeyTypeName = value == null ? null : (JavaTypes.GetJavaTypeName(value) ?? BinaryUtils.GetSqlTypeName(value)); _keyType = value; } } /// <summary> /// Gets or sets value Java type name. /// </summary> public string ValueTypeName { get { return _valueTypeName; } set { _valueTypeName = value; _valueType = null; } } /// <summary> /// Gets or sets the type of the value. /// <para /> /// This is a shortcut for <see cref="ValueTypeName"/>. Getter will return null for non-primitive types. /// <para /> /// Setting this property will overwrite <see cref="Fields"/> and <see cref="Indexes"/> according to /// <see cref="QuerySqlFieldAttribute"/>, if any. /// </summary> public Type ValueType { get { return _valueType ?? JavaTypes.GetDotNetType(ValueTypeName); } set { RescanAttributes(_keyType, value); // Do this first because it can throw ValueTypeName = value == null ? null : (JavaTypes.GetJavaTypeName(value) ?? BinaryUtils.GetSqlTypeName(value)); _valueType = value; } } /// <summary> /// Gets or sets the name of the field that is used to denote the entire key. /// <para /> /// By default, entite key can be accessed with a special "_key" field name. /// </summary> public string KeyFieldName { get; set; } /// <summary> /// Gets or sets the name of the field that is used to denote the entire value. /// <para /> /// By default, entite value can be accessed with a special "_val" field name. /// </summary> public string ValueFieldName { get; set; } /// <summary> /// Gets or sets the name of the SQL table. /// When not set, value type name is used. /// </summary> public string TableName { get; set; } /// <summary> /// Gets or sets query fields, a map from field name to Java type name. /// The order of fields defines the order of columns returned by the 'select *' queries. /// </summary> [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public ICollection<QueryField> Fields { get; set; } /// <summary> /// Gets or sets field name aliases: mapping from full name in dot notation to an alias /// that will be used as SQL column name. /// Example: {"parent.name" -> "parentName"}. /// </summary> [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public ICollection<QueryAlias> Aliases { get { return _aliases; } set { _aliases = value; _aliasMap = null; } } /// <summary> /// Gets or sets the query indexes. /// </summary> [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public ICollection<QueryIndex> Indexes { get; set; } /// <summary> /// Gets the alias by field name, or null when no match found. /// This method constructs a dictionary lazily to perform lookups. /// </summary> string IQueryEntityInternal.GetAlias(string fieldName) { if (Aliases == null || Aliases.Count == 0) { return null; } // PERF: No ToDictionary. if (_aliasMap == null) { _aliasMap = new Dictionary<string, string>(Aliases.Count, StringComparer.Ordinal); foreach (var alias in Aliases) { _aliasMap[alias.FullName] = alias.Alias; } } string res; return _aliasMap.TryGetValue(fieldName, out res) ? res : null; } /// <summary> /// Initializes a new instance of the <see cref="QueryEntity"/> class. /// </summary> /// <param name="reader">The reader.</param> /// <param name="srvVer">Server version.</param> internal QueryEntity(IBinaryRawReader reader, ClientProtocolVersion srvVer) { KeyTypeName = reader.ReadString(); ValueTypeName = reader.ReadString(); TableName = reader.ReadString(); KeyFieldName = reader.ReadString(); ValueFieldName = reader.ReadString(); var count = reader.ReadInt(); Fields = count == 0 ? null : Enumerable.Range(0, count).Select(x => new QueryField(reader, srvVer)).ToList(); count = reader.ReadInt(); Aliases = count == 0 ? null : Enumerable.Range(0, count) .Select(x=> new QueryAlias(reader.ReadString(), reader.ReadString())).ToList(); count = reader.ReadInt(); Indexes = count == 0 ? null : Enumerable.Range(0, count).Select(x => new QueryIndex(reader)).ToList(); } /// <summary> /// Writes this instance. /// </summary> void IBinaryRawWriteAwareEx<IBinaryRawWriter>.Write(IBinaryRawWriter writer, ClientProtocolVersion srvVer) { writer.WriteString(KeyTypeName); writer.WriteString(ValueTypeName); writer.WriteString(TableName); writer.WriteString(KeyFieldName); writer.WriteString(ValueFieldName); if (Fields != null) { writer.WriteInt(Fields.Count); foreach (var field in Fields) { field.Write(writer, srvVer); } } else writer.WriteInt(0); if (Aliases != null) { writer.WriteInt(Aliases.Count); foreach (var queryAlias in Aliases) { writer.WriteString(queryAlias.FullName); writer.WriteString(queryAlias.Alias); } } else writer.WriteInt(0); if (Indexes != null) { writer.WriteInt(Indexes.Count); foreach (var index in Indexes) { if (index == null) throw new InvalidOperationException("Invalid cache configuration: QueryIndex can't be null."); index.Write(writer); } } else writer.WriteInt(0); } /// <summary> /// Validates this instance and outputs information to the log, if necessary. /// </summary> internal void Validate(ILogger log, string logInfo) { Debug.Assert(log != null); Debug.Assert(logInfo != null); logInfo += string.Format(", QueryEntity '{0}:{1}'", _keyTypeName ?? "", _valueTypeName ?? ""); JavaTypes.LogIndirectMappingWarning(_keyType, log, logInfo); JavaTypes.LogIndirectMappingWarning(_valueType, log, logInfo); var fields = Fields; if (fields != null) { foreach (var field in fields) field.Validate(log, logInfo); } } /// <summary> /// Copies the local properties (properties that are not written in Write method). /// </summary> internal void CopyLocalProperties(QueryEntity entity) { Debug.Assert(entity != null); if (entity._keyType != null) { _keyType = entity._keyType; } if (entity._valueType != null) { _valueType = entity._valueType; } if (Fields != null && entity.Fields != null) { var fields = entity.Fields.Where(x => x != null).ToDictionary(x => "_" + x.Name, x => x); foreach (var field in Fields) { QueryField src; if (fields.TryGetValue("_" + field.Name, out src)) { field.CopyLocalProperties(src); } } } } /// <summary> /// Rescans the attributes in <see cref="KeyType"/> and <see cref="ValueType"/>. /// </summary> private void RescanAttributes(Type keyType, Type valType) { if (keyType == null && valType == null) return; var fields = new List<QueryField>(); var indexes = new List<QueryIndexEx>(); if (keyType != null) ScanAttributes(keyType, fields, indexes, null, new HashSet<Type>(), true); if (valType != null) ScanAttributes(valType, fields, indexes, null, new HashSet<Type>(), false); if (fields.Any()) Fields = fields.OrderBy(x => x.Name).ToList(); if (indexes.Any()) Indexes = GetGroupIndexes(indexes).ToArray(); } /// <summary> /// Gets the group indexes. /// </summary> /// <param name="indexes">Ungrouped indexes with their group names.</param> /// <returns></returns> private static IEnumerable<QueryIndex> GetGroupIndexes(List<QueryIndexEx> indexes) { return indexes.Where(idx => idx.IndexGroups != null) .SelectMany(idx => idx.IndexGroups.Select(g => new {Index = idx, GroupName = g})) .GroupBy(x => x.GroupName) .Select(g => { var idxs = g.Select(pair => pair.Index).ToArray(); var first = idxs.First(); return new QueryIndex(idxs.SelectMany(i => i.Fields).ToArray()) { IndexType = first.IndexType, Name = first.Name }; }) .Concat(indexes.Where(idx => idx.IndexGroups == null)); } /// <summary> /// Scans specified type for occurences of <see cref="QuerySqlFieldAttribute" />. /// </summary> /// <param name="type">The type.</param> /// <param name="fields">The fields.</param> /// <param name="indexes">The indexes.</param> /// <param name="parentPropName">Name of the parent property.</param> /// <param name="visitedTypes">The visited types.</param> /// <param name="isKey">Whether this is a key type.</param> /// <exception cref="System.InvalidOperationException">Recursive Query Field definition detected: + type</exception> private static void ScanAttributes(Type type, List<QueryField> fields, List<QueryIndexEx> indexes, string parentPropName, ISet<Type> visitedTypes, bool isKey) { Debug.Assert(type != null); Debug.Assert(fields != null); Debug.Assert(indexes != null); if (visitedTypes.Contains(type)) throw new InvalidOperationException("Recursive Query Field definition detected: " + type); visitedTypes.Add(type); foreach (var memberInfo in ReflectionUtils.GetFieldsAndProperties(type)) { var customAttributes = memberInfo.Key.GetCustomAttributes(true); foreach (var attr in customAttributes.OfType<QuerySqlFieldAttribute>()) { var columnName = attr.Name ?? memberInfo.Key.Name; // Dot notation is required for nested SQL fields. if (parentPropName != null) { columnName = parentPropName + "." + columnName; } if (attr.IsIndexed) { indexes.Add(new QueryIndexEx(columnName, attr.IsDescending, QueryIndexType.Sorted, attr.IndexGroups) { InlineSize = attr.IndexInlineSize, }); } fields.Add(new QueryField(columnName, memberInfo.Value) { IsKeyField = isKey, NotNull = attr.NotNull, DefaultValue = attr.DefaultValue, Precision = attr.Precision, Scale = attr.Scale }); ScanAttributes(memberInfo.Value, fields, indexes, columnName, visitedTypes, isKey); } foreach (var attr in customAttributes.OfType<QueryTextFieldAttribute>()) { var columnName = attr.Name ?? memberInfo.Key.Name; if (parentPropName != null) { columnName = parentPropName + "." + columnName; } indexes.Add(new QueryIndexEx(columnName, false, QueryIndexType.FullText, null)); fields.Add(new QueryField(columnName, memberInfo.Value) {IsKeyField = isKey}); ScanAttributes(memberInfo.Value, fields, indexes, columnName, visitedTypes, isKey); } } visitedTypes.Remove(type); } /// <summary> /// Extended index with group names. /// </summary> private class QueryIndexEx : QueryIndex { /// <summary> /// Initializes a new instance of the <see cref="QueryIndexEx"/> class. /// </summary> /// <param name="fieldName">Name of the field.</param> /// <param name="isDescending">if set to <c>true</c> [is descending].</param> /// <param name="indexType">Type of the index.</param> /// <param name="groups">The groups.</param> public QueryIndexEx(string fieldName, bool isDescending, QueryIndexType indexType, ICollection<string> groups) : base(isDescending, indexType, fieldName) { IndexGroups = groups; } /// <summary> /// Gets or sets the index groups. /// </summary> public ICollection<string> IndexGroups { get; set; } } } }
#region Copyright //////////////////////////////////////////////////////////////////////////////// // The following FIT Protocol software provided may be used with FIT protocol // devices only and remains the copyrighted property of Dynastream Innovations Inc. // The software is being provided on an "as-is" basis and as an accommodation, // and therefore all warranties, representations, or guarantees of any kind // (whether express, implied or statutory) including, without limitation, // warranties of merchantability, non-infringement, or fitness for a particular // purpose, are specifically disclaimed. // // Copyright 2015 Dynastream Innovations Inc. //////////////////////////////////////////////////////////////////////////////// // ****WARNING**** This file is auto-generated! Do NOT edit this file. // Profile Version = 16.10Release // Tag = development-akw-16.10.00-0 //////////////////////////////////////////////////////////////////////////////// #endregion using System; using System.Collections.Generic; using System.Diagnostics; using System.Text; using System.IO; namespace Dynastream.Fit { /// <summary> /// Implements the Record profile message. /// </summary> public class RecordMesg : Mesg { #region Fields #endregion #region Constructors public RecordMesg() : base(Profile.mesgs[Profile.RecordIndex]) { } public RecordMesg(Mesg mesg) : base(mesg) { } #endregion // Constructors #region Methods ///<summary> /// Retrieves the Timestamp field /// Units: s</summary> /// <returns>Returns DateTime representing the Timestamp field</returns> public DateTime GetTimestamp() { return TimestampToDateTime((uint?)GetFieldValue(253, 0, Fit.SubfieldIndexMainField)); } /// <summary> /// Set Timestamp field /// Units: s</summary> /// <param name="timestamp_">Nullable field value to be set</param> public void SetTimestamp(DateTime timestamp_) { SetFieldValue(253, 0, timestamp_.GetTimeStamp(), Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the PositionLat field /// Units: semicircles</summary> /// <returns>Returns nullable int representing the PositionLat field</returns> public int? GetPositionLat() { return (int?)GetFieldValue(0, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set PositionLat field /// Units: semicircles</summary> /// <param name="positionLat_">Nullable field value to be set</param> public void SetPositionLat(int? positionLat_) { SetFieldValue(0, 0, positionLat_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the PositionLong field /// Units: semicircles</summary> /// <returns>Returns nullable int representing the PositionLong field</returns> public int? GetPositionLong() { return (int?)GetFieldValue(1, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set PositionLong field /// Units: semicircles</summary> /// <param name="positionLong_">Nullable field value to be set</param> public void SetPositionLong(int? positionLong_) { SetFieldValue(1, 0, positionLong_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the Altitude field /// Units: m</summary> /// <returns>Returns nullable float representing the Altitude field</returns> public float? GetAltitude() { return (float?)GetFieldValue(2, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set Altitude field /// Units: m</summary> /// <param name="altitude_">Nullable field value to be set</param> public void SetAltitude(float? altitude_) { SetFieldValue(2, 0, altitude_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the HeartRate field /// Units: bpm</summary> /// <returns>Returns nullable byte representing the HeartRate field</returns> public byte? GetHeartRate() { return (byte?)GetFieldValue(3, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set HeartRate field /// Units: bpm</summary> /// <param name="heartRate_">Nullable field value to be set</param> public void SetHeartRate(byte? heartRate_) { SetFieldValue(3, 0, heartRate_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the Cadence field /// Units: rpm</summary> /// <returns>Returns nullable byte representing the Cadence field</returns> public byte? GetCadence() { return (byte?)GetFieldValue(4, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set Cadence field /// Units: rpm</summary> /// <param name="cadence_">Nullable field value to be set</param> public void SetCadence(byte? cadence_) { SetFieldValue(4, 0, cadence_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the Distance field /// Units: m</summary> /// <returns>Returns nullable float representing the Distance field</returns> public float? GetDistance() { return (float?)GetFieldValue(5, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set Distance field /// Units: m</summary> /// <param name="distance_">Nullable field value to be set</param> public void SetDistance(float? distance_) { SetFieldValue(5, 0, distance_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the Speed field /// Units: m/s</summary> /// <returns>Returns nullable float representing the Speed field</returns> public float? GetSpeed() { return (float?)GetFieldValue(6, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set Speed field /// Units: m/s</summary> /// <param name="speed_">Nullable field value to be set</param> public void SetSpeed(float? speed_) { SetFieldValue(6, 0, speed_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the Power field /// Units: watts</summary> /// <returns>Returns nullable ushort representing the Power field</returns> public ushort? GetPower() { return (ushort?)GetFieldValue(7, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set Power field /// Units: watts</summary> /// <param name="power_">Nullable field value to be set</param> public void SetPower(ushort? power_) { SetFieldValue(7, 0, power_, Fit.SubfieldIndexMainField); } /// <summary> /// /// </summary> /// <returns>returns number of elements in field CompressedSpeedDistance</returns> public int GetNumCompressedSpeedDistance() { return GetNumFieldValues(8, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the CompressedSpeedDistance field</summary> /// <param name="index">0 based index of CompressedSpeedDistance element to retrieve</param> /// <returns>Returns nullable byte representing the CompressedSpeedDistance field</returns> public byte? GetCompressedSpeedDistance(int index) { return (byte?)GetFieldValue(8, index, Fit.SubfieldIndexMainField); } /// <summary> /// Set CompressedSpeedDistance field</summary> /// <param name="index">0 based index of compressed_speed_distance</param> /// <param name="compressedSpeedDistance_">Nullable field value to be set</param> public void SetCompressedSpeedDistance(int index, byte? compressedSpeedDistance_) { SetFieldValue(8, index, compressedSpeedDistance_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the Grade field /// Units: %</summary> /// <returns>Returns nullable float representing the Grade field</returns> public float? GetGrade() { return (float?)GetFieldValue(9, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set Grade field /// Units: %</summary> /// <param name="grade_">Nullable field value to be set</param> public void SetGrade(float? grade_) { SetFieldValue(9, 0, grade_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the Resistance field /// Comment: Relative. 0 is none 254 is Max.</summary> /// <returns>Returns nullable byte representing the Resistance field</returns> public byte? GetResistance() { return (byte?)GetFieldValue(10, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set Resistance field /// Comment: Relative. 0 is none 254 is Max.</summary> /// <param name="resistance_">Nullable field value to be set</param> public void SetResistance(byte? resistance_) { SetFieldValue(10, 0, resistance_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the TimeFromCourse field /// Units: s</summary> /// <returns>Returns nullable float representing the TimeFromCourse field</returns> public float? GetTimeFromCourse() { return (float?)GetFieldValue(11, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set TimeFromCourse field /// Units: s</summary> /// <param name="timeFromCourse_">Nullable field value to be set</param> public void SetTimeFromCourse(float? timeFromCourse_) { SetFieldValue(11, 0, timeFromCourse_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the CycleLength field /// Units: m</summary> /// <returns>Returns nullable float representing the CycleLength field</returns> public float? GetCycleLength() { return (float?)GetFieldValue(12, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set CycleLength field /// Units: m</summary> /// <param name="cycleLength_">Nullable field value to be set</param> public void SetCycleLength(float? cycleLength_) { SetFieldValue(12, 0, cycleLength_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the Temperature field /// Units: C</summary> /// <returns>Returns nullable sbyte representing the Temperature field</returns> public sbyte? GetTemperature() { return (sbyte?)GetFieldValue(13, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set Temperature field /// Units: C</summary> /// <param name="temperature_">Nullable field value to be set</param> public void SetTemperature(sbyte? temperature_) { SetFieldValue(13, 0, temperature_, Fit.SubfieldIndexMainField); } /// <summary> /// /// </summary> /// <returns>returns number of elements in field Speed1s</returns> public int GetNumSpeed1s() { return GetNumFieldValues(17, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the Speed1s field /// Units: m/s /// Comment: Speed at 1s intervals. Timestamp field indicates time of last array element.</summary> /// <param name="index">0 based index of Speed1s element to retrieve</param> /// <returns>Returns nullable float representing the Speed1s field</returns> public float? GetSpeed1s(int index) { return (float?)GetFieldValue(17, index, Fit.SubfieldIndexMainField); } /// <summary> /// Set Speed1s field /// Units: m/s /// Comment: Speed at 1s intervals. Timestamp field indicates time of last array element.</summary> /// <param name="index">0 based index of speed_1s</param> /// <param name="speed1s_">Nullable field value to be set</param> public void SetSpeed1s(int index, float? speed1s_) { SetFieldValue(17, index, speed1s_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the Cycles field /// Units: cycles</summary> /// <returns>Returns nullable byte representing the Cycles field</returns> public byte? GetCycles() { return (byte?)GetFieldValue(18, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set Cycles field /// Units: cycles</summary> /// <param name="cycles_">Nullable field value to be set</param> public void SetCycles(byte? cycles_) { SetFieldValue(18, 0, cycles_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the TotalCycles field /// Units: cycles</summary> /// <returns>Returns nullable uint representing the TotalCycles field</returns> public uint? GetTotalCycles() { return (uint?)GetFieldValue(19, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set TotalCycles field /// Units: cycles</summary> /// <param name="totalCycles_">Nullable field value to be set</param> public void SetTotalCycles(uint? totalCycles_) { SetFieldValue(19, 0, totalCycles_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the CompressedAccumulatedPower field /// Units: watts</summary> /// <returns>Returns nullable ushort representing the CompressedAccumulatedPower field</returns> public ushort? GetCompressedAccumulatedPower() { return (ushort?)GetFieldValue(28, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set CompressedAccumulatedPower field /// Units: watts</summary> /// <param name="compressedAccumulatedPower_">Nullable field value to be set</param> public void SetCompressedAccumulatedPower(ushort? compressedAccumulatedPower_) { SetFieldValue(28, 0, compressedAccumulatedPower_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the AccumulatedPower field /// Units: watts</summary> /// <returns>Returns nullable uint representing the AccumulatedPower field</returns> public uint? GetAccumulatedPower() { return (uint?)GetFieldValue(29, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set AccumulatedPower field /// Units: watts</summary> /// <param name="accumulatedPower_">Nullable field value to be set</param> public void SetAccumulatedPower(uint? accumulatedPower_) { SetFieldValue(29, 0, accumulatedPower_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the LeftRightBalance field</summary> /// <returns>Returns nullable byte representing the LeftRightBalance field</returns> public byte? GetLeftRightBalance() { return (byte?)GetFieldValue(30, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set LeftRightBalance field</summary> /// <param name="leftRightBalance_">Nullable field value to be set</param> public void SetLeftRightBalance(byte? leftRightBalance_) { SetFieldValue(30, 0, leftRightBalance_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the GpsAccuracy field /// Units: m</summary> /// <returns>Returns nullable byte representing the GpsAccuracy field</returns> public byte? GetGpsAccuracy() { return (byte?)GetFieldValue(31, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set GpsAccuracy field /// Units: m</summary> /// <param name="gpsAccuracy_">Nullable field value to be set</param> public void SetGpsAccuracy(byte? gpsAccuracy_) { SetFieldValue(31, 0, gpsAccuracy_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the VerticalSpeed field /// Units: m/s</summary> /// <returns>Returns nullable float representing the VerticalSpeed field</returns> public float? GetVerticalSpeed() { return (float?)GetFieldValue(32, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set VerticalSpeed field /// Units: m/s</summary> /// <param name="verticalSpeed_">Nullable field value to be set</param> public void SetVerticalSpeed(float? verticalSpeed_) { SetFieldValue(32, 0, verticalSpeed_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the Calories field /// Units: kcal</summary> /// <returns>Returns nullable ushort representing the Calories field</returns> public ushort? GetCalories() { return (ushort?)GetFieldValue(33, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set Calories field /// Units: kcal</summary> /// <param name="calories_">Nullable field value to be set</param> public void SetCalories(ushort? calories_) { SetFieldValue(33, 0, calories_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the VerticalOscillation field /// Units: mm</summary> /// <returns>Returns nullable float representing the VerticalOscillation field</returns> public float? GetVerticalOscillation() { return (float?)GetFieldValue(39, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set VerticalOscillation field /// Units: mm</summary> /// <param name="verticalOscillation_">Nullable field value to be set</param> public void SetVerticalOscillation(float? verticalOscillation_) { SetFieldValue(39, 0, verticalOscillation_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the StanceTimePercent field /// Units: percent</summary> /// <returns>Returns nullable float representing the StanceTimePercent field</returns> public float? GetStanceTimePercent() { return (float?)GetFieldValue(40, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set StanceTimePercent field /// Units: percent</summary> /// <param name="stanceTimePercent_">Nullable field value to be set</param> public void SetStanceTimePercent(float? stanceTimePercent_) { SetFieldValue(40, 0, stanceTimePercent_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the StanceTime field /// Units: ms</summary> /// <returns>Returns nullable float representing the StanceTime field</returns> public float? GetStanceTime() { return (float?)GetFieldValue(41, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set StanceTime field /// Units: ms</summary> /// <param name="stanceTime_">Nullable field value to be set</param> public void SetStanceTime(float? stanceTime_) { SetFieldValue(41, 0, stanceTime_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the ActivityType field</summary> /// <returns>Returns nullable ActivityType enum representing the ActivityType field</returns> public ActivityType? GetActivityType() { object obj = GetFieldValue(42, 0, Fit.SubfieldIndexMainField); ActivityType? value = obj == null ? (ActivityType?)null : (ActivityType)obj; return value; } /// <summary> /// Set ActivityType field</summary> /// <param name="activityType_">Nullable field value to be set</param> public void SetActivityType(ActivityType? activityType_) { SetFieldValue(42, 0, activityType_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the LeftTorqueEffectiveness field /// Units: percent</summary> /// <returns>Returns nullable float representing the LeftTorqueEffectiveness field</returns> public float? GetLeftTorqueEffectiveness() { return (float?)GetFieldValue(43, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set LeftTorqueEffectiveness field /// Units: percent</summary> /// <param name="leftTorqueEffectiveness_">Nullable field value to be set</param> public void SetLeftTorqueEffectiveness(float? leftTorqueEffectiveness_) { SetFieldValue(43, 0, leftTorqueEffectiveness_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the RightTorqueEffectiveness field /// Units: percent</summary> /// <returns>Returns nullable float representing the RightTorqueEffectiveness field</returns> public float? GetRightTorqueEffectiveness() { return (float?)GetFieldValue(44, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set RightTorqueEffectiveness field /// Units: percent</summary> /// <param name="rightTorqueEffectiveness_">Nullable field value to be set</param> public void SetRightTorqueEffectiveness(float? rightTorqueEffectiveness_) { SetFieldValue(44, 0, rightTorqueEffectiveness_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the LeftPedalSmoothness field /// Units: percent</summary> /// <returns>Returns nullable float representing the LeftPedalSmoothness field</returns> public float? GetLeftPedalSmoothness() { return (float?)GetFieldValue(45, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set LeftPedalSmoothness field /// Units: percent</summary> /// <param name="leftPedalSmoothness_">Nullable field value to be set</param> public void SetLeftPedalSmoothness(float? leftPedalSmoothness_) { SetFieldValue(45, 0, leftPedalSmoothness_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the RightPedalSmoothness field /// Units: percent</summary> /// <returns>Returns nullable float representing the RightPedalSmoothness field</returns> public float? GetRightPedalSmoothness() { return (float?)GetFieldValue(46, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set RightPedalSmoothness field /// Units: percent</summary> /// <param name="rightPedalSmoothness_">Nullable field value to be set</param> public void SetRightPedalSmoothness(float? rightPedalSmoothness_) { SetFieldValue(46, 0, rightPedalSmoothness_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the CombinedPedalSmoothness field /// Units: percent</summary> /// <returns>Returns nullable float representing the CombinedPedalSmoothness field</returns> public float? GetCombinedPedalSmoothness() { return (float?)GetFieldValue(47, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set CombinedPedalSmoothness field /// Units: percent</summary> /// <param name="combinedPedalSmoothness_">Nullable field value to be set</param> public void SetCombinedPedalSmoothness(float? combinedPedalSmoothness_) { SetFieldValue(47, 0, combinedPedalSmoothness_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the Time128 field /// Units: s</summary> /// <returns>Returns nullable float representing the Time128 field</returns> public float? GetTime128() { return (float?)GetFieldValue(48, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set Time128 field /// Units: s</summary> /// <param name="time128_">Nullable field value to be set</param> public void SetTime128(float? time128_) { SetFieldValue(48, 0, time128_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the StrokeType field</summary> /// <returns>Returns nullable StrokeType enum representing the StrokeType field</returns> public StrokeType? GetStrokeType() { object obj = GetFieldValue(49, 0, Fit.SubfieldIndexMainField); StrokeType? value = obj == null ? (StrokeType?)null : (StrokeType)obj; return value; } /// <summary> /// Set StrokeType field</summary> /// <param name="strokeType_">Nullable field value to be set</param> public void SetStrokeType(StrokeType? strokeType_) { SetFieldValue(49, 0, strokeType_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the Zone field</summary> /// <returns>Returns nullable byte representing the Zone field</returns> public byte? GetZone() { return (byte?)GetFieldValue(50, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set Zone field</summary> /// <param name="zone_">Nullable field value to be set</param> public void SetZone(byte? zone_) { SetFieldValue(50, 0, zone_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the BallSpeed field /// Units: m/s</summary> /// <returns>Returns nullable float representing the BallSpeed field</returns> public float? GetBallSpeed() { return (float?)GetFieldValue(51, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set BallSpeed field /// Units: m/s</summary> /// <param name="ballSpeed_">Nullable field value to be set</param> public void SetBallSpeed(float? ballSpeed_) { SetFieldValue(51, 0, ballSpeed_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the Cadence256 field /// Units: rpm /// Comment: Log cadence and fractional cadence for backwards compatability</summary> /// <returns>Returns nullable float representing the Cadence256 field</returns> public float? GetCadence256() { return (float?)GetFieldValue(52, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set Cadence256 field /// Units: rpm /// Comment: Log cadence and fractional cadence for backwards compatability</summary> /// <param name="cadence256_">Nullable field value to be set</param> public void SetCadence256(float? cadence256_) { SetFieldValue(52, 0, cadence256_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the FractionalCadence field /// Units: rpm</summary> /// <returns>Returns nullable float representing the FractionalCadence field</returns> public float? GetFractionalCadence() { return (float?)GetFieldValue(53, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set FractionalCadence field /// Units: rpm</summary> /// <param name="fractionalCadence_">Nullable field value to be set</param> public void SetFractionalCadence(float? fractionalCadence_) { SetFieldValue(53, 0, fractionalCadence_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the TotalHemoglobinConc field /// Units: g/dL /// Comment: Total saturated and unsaturated hemoglobin</summary> /// <returns>Returns nullable float representing the TotalHemoglobinConc field</returns> public float? GetTotalHemoglobinConc() { return (float?)GetFieldValue(54, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set TotalHemoglobinConc field /// Units: g/dL /// Comment: Total saturated and unsaturated hemoglobin</summary> /// <param name="totalHemoglobinConc_">Nullable field value to be set</param> public void SetTotalHemoglobinConc(float? totalHemoglobinConc_) { SetFieldValue(54, 0, totalHemoglobinConc_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the TotalHemoglobinConcMin field /// Units: g/dL /// Comment: Min saturated and unsaturated hemoglobin</summary> /// <returns>Returns nullable float representing the TotalHemoglobinConcMin field</returns> public float? GetTotalHemoglobinConcMin() { return (float?)GetFieldValue(55, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set TotalHemoglobinConcMin field /// Units: g/dL /// Comment: Min saturated and unsaturated hemoglobin</summary> /// <param name="totalHemoglobinConcMin_">Nullable field value to be set</param> public void SetTotalHemoglobinConcMin(float? totalHemoglobinConcMin_) { SetFieldValue(55, 0, totalHemoglobinConcMin_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the TotalHemoglobinConcMax field /// Units: g/dL /// Comment: Max saturated and unsaturated hemoglobin</summary> /// <returns>Returns nullable float representing the TotalHemoglobinConcMax field</returns> public float? GetTotalHemoglobinConcMax() { return (float?)GetFieldValue(56, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set TotalHemoglobinConcMax field /// Units: g/dL /// Comment: Max saturated and unsaturated hemoglobin</summary> /// <param name="totalHemoglobinConcMax_">Nullable field value to be set</param> public void SetTotalHemoglobinConcMax(float? totalHemoglobinConcMax_) { SetFieldValue(56, 0, totalHemoglobinConcMax_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the SaturatedHemoglobinPercent field /// Units: % /// Comment: Percentage of hemoglobin saturated with oxygen</summary> /// <returns>Returns nullable float representing the SaturatedHemoglobinPercent field</returns> public float? GetSaturatedHemoglobinPercent() { return (float?)GetFieldValue(57, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set SaturatedHemoglobinPercent field /// Units: % /// Comment: Percentage of hemoglobin saturated with oxygen</summary> /// <param name="saturatedHemoglobinPercent_">Nullable field value to be set</param> public void SetSaturatedHemoglobinPercent(float? saturatedHemoglobinPercent_) { SetFieldValue(57, 0, saturatedHemoglobinPercent_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the SaturatedHemoglobinPercentMin field /// Units: % /// Comment: Min percentage of hemoglobin saturated with oxygen</summary> /// <returns>Returns nullable float representing the SaturatedHemoglobinPercentMin field</returns> public float? GetSaturatedHemoglobinPercentMin() { return (float?)GetFieldValue(58, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set SaturatedHemoglobinPercentMin field /// Units: % /// Comment: Min percentage of hemoglobin saturated with oxygen</summary> /// <param name="saturatedHemoglobinPercentMin_">Nullable field value to be set</param> public void SetSaturatedHemoglobinPercentMin(float? saturatedHemoglobinPercentMin_) { SetFieldValue(58, 0, saturatedHemoglobinPercentMin_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the SaturatedHemoglobinPercentMax field /// Units: % /// Comment: Max percentage of hemoglobin saturated with oxygen</summary> /// <returns>Returns nullable float representing the SaturatedHemoglobinPercentMax field</returns> public float? GetSaturatedHemoglobinPercentMax() { return (float?)GetFieldValue(59, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set SaturatedHemoglobinPercentMax field /// Units: % /// Comment: Max percentage of hemoglobin saturated with oxygen</summary> /// <param name="saturatedHemoglobinPercentMax_">Nullable field value to be set</param> public void SetSaturatedHemoglobinPercentMax(float? saturatedHemoglobinPercentMax_) { SetFieldValue(59, 0, saturatedHemoglobinPercentMax_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the DeviceIndex field</summary> /// <returns>Returns nullable byte representing the DeviceIndex field</returns> public byte? GetDeviceIndex() { return (byte?)GetFieldValue(62, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set DeviceIndex field</summary> /// <param name="deviceIndex_">Nullable field value to be set</param> public void SetDeviceIndex(byte? deviceIndex_) { SetFieldValue(62, 0, deviceIndex_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the LeftPco field /// Units: mm /// Comment: Left platform center offset</summary> /// <returns>Returns nullable sbyte representing the LeftPco field</returns> public sbyte? GetLeftPco() { return (sbyte?)GetFieldValue(67, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set LeftPco field /// Units: mm /// Comment: Left platform center offset</summary> /// <param name="leftPco_">Nullable field value to be set</param> public void SetLeftPco(sbyte? leftPco_) { SetFieldValue(67, 0, leftPco_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the RightPco field /// Units: mm /// Comment: Right platform center offset</summary> /// <returns>Returns nullable sbyte representing the RightPco field</returns> public sbyte? GetRightPco() { return (sbyte?)GetFieldValue(68, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set RightPco field /// Units: mm /// Comment: Right platform center offset</summary> /// <param name="rightPco_">Nullable field value to be set</param> public void SetRightPco(sbyte? rightPco_) { SetFieldValue(68, 0, rightPco_, Fit.SubfieldIndexMainField); } /// <summary> /// /// </summary> /// <returns>returns number of elements in field LeftPowerPhase</returns> public int GetNumLeftPowerPhase() { return GetNumFieldValues(69, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the LeftPowerPhase field /// Units: degrees /// Comment: Left power phase angles. Data value indexes defined by power_phase_type.</summary> /// <param name="index">0 based index of LeftPowerPhase element to retrieve</param> /// <returns>Returns nullable float representing the LeftPowerPhase field</returns> public float? GetLeftPowerPhase(int index) { return (float?)GetFieldValue(69, index, Fit.SubfieldIndexMainField); } /// <summary> /// Set LeftPowerPhase field /// Units: degrees /// Comment: Left power phase angles. Data value indexes defined by power_phase_type.</summary> /// <param name="index">0 based index of left_power_phase</param> /// <param name="leftPowerPhase_">Nullable field value to be set</param> public void SetLeftPowerPhase(int index, float? leftPowerPhase_) { SetFieldValue(69, index, leftPowerPhase_, Fit.SubfieldIndexMainField); } /// <summary> /// /// </summary> /// <returns>returns number of elements in field LeftPowerPhasePeak</returns> public int GetNumLeftPowerPhasePeak() { return GetNumFieldValues(70, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the LeftPowerPhasePeak field /// Units: degrees /// Comment: Left power phase peak angles. Data value indexes defined by power_phase_type.</summary> /// <param name="index">0 based index of LeftPowerPhasePeak element to retrieve</param> /// <returns>Returns nullable float representing the LeftPowerPhasePeak field</returns> public float? GetLeftPowerPhasePeak(int index) { return (float?)GetFieldValue(70, index, Fit.SubfieldIndexMainField); } /// <summary> /// Set LeftPowerPhasePeak field /// Units: degrees /// Comment: Left power phase peak angles. Data value indexes defined by power_phase_type.</summary> /// <param name="index">0 based index of left_power_phase_peak</param> /// <param name="leftPowerPhasePeak_">Nullable field value to be set</param> public void SetLeftPowerPhasePeak(int index, float? leftPowerPhasePeak_) { SetFieldValue(70, index, leftPowerPhasePeak_, Fit.SubfieldIndexMainField); } /// <summary> /// /// </summary> /// <returns>returns number of elements in field RightPowerPhase</returns> public int GetNumRightPowerPhase() { return GetNumFieldValues(71, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the RightPowerPhase field /// Units: degrees /// Comment: Right power phase angles. Data value indexes defined by power_phase_type.</summary> /// <param name="index">0 based index of RightPowerPhase element to retrieve</param> /// <returns>Returns nullable float representing the RightPowerPhase field</returns> public float? GetRightPowerPhase(int index) { return (float?)GetFieldValue(71, index, Fit.SubfieldIndexMainField); } /// <summary> /// Set RightPowerPhase field /// Units: degrees /// Comment: Right power phase angles. Data value indexes defined by power_phase_type.</summary> /// <param name="index">0 based index of right_power_phase</param> /// <param name="rightPowerPhase_">Nullable field value to be set</param> public void SetRightPowerPhase(int index, float? rightPowerPhase_) { SetFieldValue(71, index, rightPowerPhase_, Fit.SubfieldIndexMainField); } /// <summary> /// /// </summary> /// <returns>returns number of elements in field RightPowerPhasePeak</returns> public int GetNumRightPowerPhasePeak() { return GetNumFieldValues(72, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the RightPowerPhasePeak field /// Units: degrees /// Comment: Right power phase peak angles. Data value indexes defined by power_phase_type.</summary> /// <param name="index">0 based index of RightPowerPhasePeak element to retrieve</param> /// <returns>Returns nullable float representing the RightPowerPhasePeak field</returns> public float? GetRightPowerPhasePeak(int index) { return (float?)GetFieldValue(72, index, Fit.SubfieldIndexMainField); } /// <summary> /// Set RightPowerPhasePeak field /// Units: degrees /// Comment: Right power phase peak angles. Data value indexes defined by power_phase_type.</summary> /// <param name="index">0 based index of right_power_phase_peak</param> /// <param name="rightPowerPhasePeak_">Nullable field value to be set</param> public void SetRightPowerPhasePeak(int index, float? rightPowerPhasePeak_) { SetFieldValue(72, index, rightPowerPhasePeak_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the EnhancedSpeed field /// Units: m/s</summary> /// <returns>Returns nullable float representing the EnhancedSpeed field</returns> public float? GetEnhancedSpeed() { return (float?)GetFieldValue(73, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set EnhancedSpeed field /// Units: m/s</summary> /// <param name="enhancedSpeed_">Nullable field value to be set</param> public void SetEnhancedSpeed(float? enhancedSpeed_) { SetFieldValue(73, 0, enhancedSpeed_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the EnhancedAltitude field /// Units: m</summary> /// <returns>Returns nullable float representing the EnhancedAltitude field</returns> public float? GetEnhancedAltitude() { return (float?)GetFieldValue(78, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set EnhancedAltitude field /// Units: m</summary> /// <param name="enhancedAltitude_">Nullable field value to be set</param> public void SetEnhancedAltitude(float? enhancedAltitude_) { SetFieldValue(78, 0, enhancedAltitude_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the BatterySoc field /// Units: percent /// Comment: lev battery state of charge</summary> /// <returns>Returns nullable float representing the BatterySoc field</returns> public float? GetBatterySoc() { return (float?)GetFieldValue(81, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set BatterySoc field /// Units: percent /// Comment: lev battery state of charge</summary> /// <param name="batterySoc_">Nullable field value to be set</param> public void SetBatterySoc(float? batterySoc_) { SetFieldValue(81, 0, batterySoc_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the MotorPower field /// Units: watts /// Comment: lev motor power</summary> /// <returns>Returns nullable ushort representing the MotorPower field</returns> public ushort? GetMotorPower() { return (ushort?)GetFieldValue(82, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set MotorPower field /// Units: watts /// Comment: lev motor power</summary> /// <param name="motorPower_">Nullable field value to be set</param> public void SetMotorPower(ushort? motorPower_) { SetFieldValue(82, 0, motorPower_, Fit.SubfieldIndexMainField); } #endregion // Methods } // Class } // namespace
// 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.Xml.Schema { using System.Collections; using System.Diagnostics; internal sealed class SchemaNames { private XmlNameTable _nameTable; public XmlNameTable NameTable { get { return _nameTable; } } public string NsDataType; public string NsDataTypeAlias; public string NsDataTypeOld; public string NsXml; public string NsXmlNs; public string NsXdr; public string NsXdrAlias; public string NsXs; public string NsXsi; public string XsiType; public string XsiNil; public string XsiSchemaLocation; public string XsiNoNamespaceSchemaLocation; public string XsdSchema; public string XdrSchema; public XmlQualifiedName QnPCData; public XmlQualifiedName QnXml; public XmlQualifiedName QnXmlNs; public XmlQualifiedName QnDtDt; public XmlQualifiedName QnXmlLang; public XmlQualifiedName QnName; public XmlQualifiedName QnType; public XmlQualifiedName QnMaxOccurs; public XmlQualifiedName QnMinOccurs; public XmlQualifiedName QnInfinite; public XmlQualifiedName QnModel; public XmlQualifiedName QnOpen; public XmlQualifiedName QnClosed; public XmlQualifiedName QnContent; public XmlQualifiedName QnMixed; public XmlQualifiedName QnEmpty; public XmlQualifiedName QnEltOnly; public XmlQualifiedName QnTextOnly; public XmlQualifiedName QnOrder; public XmlQualifiedName QnSeq; public XmlQualifiedName QnOne; public XmlQualifiedName QnMany; public XmlQualifiedName QnRequired; public XmlQualifiedName QnYes; public XmlQualifiedName QnNo; public XmlQualifiedName QnString; public XmlQualifiedName QnID; public XmlQualifiedName QnIDRef; public XmlQualifiedName QnIDRefs; public XmlQualifiedName QnEntity; public XmlQualifiedName QnEntities; public XmlQualifiedName QnNmToken; public XmlQualifiedName QnNmTokens; public XmlQualifiedName QnEnumeration; public XmlQualifiedName QnDefault; public XmlQualifiedName QnXdrSchema; public XmlQualifiedName QnXdrElementType; public XmlQualifiedName QnXdrElement; public XmlQualifiedName QnXdrGroup; public XmlQualifiedName QnXdrAttributeType; public XmlQualifiedName QnXdrAttribute; public XmlQualifiedName QnXdrDataType; public XmlQualifiedName QnXdrDescription; public XmlQualifiedName QnXdrExtends; public XmlQualifiedName QnXdrAliasSchema; public XmlQualifiedName QnDtType; public XmlQualifiedName QnDtValues; public XmlQualifiedName QnDtMaxLength; public XmlQualifiedName QnDtMinLength; public XmlQualifiedName QnDtMax; public XmlQualifiedName QnDtMin; public XmlQualifiedName QnDtMinExclusive; public XmlQualifiedName QnDtMaxExclusive; // For XSD Schema public XmlQualifiedName QnTargetNamespace; public XmlQualifiedName QnVersion; public XmlQualifiedName QnFinalDefault; public XmlQualifiedName QnBlockDefault; public XmlQualifiedName QnFixed; public XmlQualifiedName QnAbstract; public XmlQualifiedName QnBlock; public XmlQualifiedName QnSubstitutionGroup; public XmlQualifiedName QnFinal; public XmlQualifiedName QnNillable; public XmlQualifiedName QnRef; public XmlQualifiedName QnBase; public XmlQualifiedName QnDerivedBy; public XmlQualifiedName QnNamespace; public XmlQualifiedName QnProcessContents; public XmlQualifiedName QnRefer; public XmlQualifiedName QnPublic; public XmlQualifiedName QnSystem; public XmlQualifiedName QnSchemaLocation; public XmlQualifiedName QnValue; public XmlQualifiedName QnUse; public XmlQualifiedName QnForm; public XmlQualifiedName QnElementFormDefault; public XmlQualifiedName QnAttributeFormDefault; public XmlQualifiedName QnItemType; public XmlQualifiedName QnMemberTypes; public XmlQualifiedName QnXPath; public XmlQualifiedName QnXsdSchema; public XmlQualifiedName QnXsdAnnotation; public XmlQualifiedName QnXsdInclude; public XmlQualifiedName QnXsdImport; public XmlQualifiedName QnXsdElement; public XmlQualifiedName QnXsdAttribute; public XmlQualifiedName QnXsdAttributeGroup; public XmlQualifiedName QnXsdAnyAttribute; public XmlQualifiedName QnXsdGroup; public XmlQualifiedName QnXsdAll; public XmlQualifiedName QnXsdChoice; public XmlQualifiedName QnXsdSequence; public XmlQualifiedName QnXsdAny; public XmlQualifiedName QnXsdNotation; public XmlQualifiedName QnXsdSimpleType; public XmlQualifiedName QnXsdComplexType; public XmlQualifiedName QnXsdUnique; public XmlQualifiedName QnXsdKey; public XmlQualifiedName QnXsdKeyRef; public XmlQualifiedName QnXsdSelector; public XmlQualifiedName QnXsdField; public XmlQualifiedName QnXsdMinExclusive; public XmlQualifiedName QnXsdMinInclusive; public XmlQualifiedName QnXsdMaxInclusive; public XmlQualifiedName QnXsdMaxExclusive; public XmlQualifiedName QnXsdTotalDigits; public XmlQualifiedName QnXsdFractionDigits; public XmlQualifiedName QnXsdLength; public XmlQualifiedName QnXsdMinLength; public XmlQualifiedName QnXsdMaxLength; public XmlQualifiedName QnXsdEnumeration; public XmlQualifiedName QnXsdPattern; public XmlQualifiedName QnXsdDocumentation; public XmlQualifiedName QnXsdAppinfo; public XmlQualifiedName QnSource; public XmlQualifiedName QnXsdComplexContent; public XmlQualifiedName QnXsdSimpleContent; public XmlQualifiedName QnXsdRestriction; public XmlQualifiedName QnXsdExtension; public XmlQualifiedName QnXsdUnion; public XmlQualifiedName QnXsdList; public XmlQualifiedName QnXsdWhiteSpace; public XmlQualifiedName QnXsdRedefine; public XmlQualifiedName QnXsdAnyType; internal XmlQualifiedName[] TokenToQName = new XmlQualifiedName[(int)Token.XmlLang + 1]; public SchemaNames(XmlNameTable nameTable) { _nameTable = nameTable; NsDataType = nameTable.Add(XmlReservedNs.NsDataType); NsDataTypeAlias = nameTable.Add(XmlReservedNs.NsDataTypeAlias); NsDataTypeOld = nameTable.Add(XmlReservedNs.NsDataTypeOld); NsXml = nameTable.Add(XmlReservedNs.NsXml); NsXmlNs = nameTable.Add(XmlReservedNs.NsXmlNs); NsXdr = nameTable.Add(XmlReservedNs.NsXdr); NsXdrAlias = nameTable.Add(XmlReservedNs.NsXdrAlias); NsXs = nameTable.Add(XmlReservedNs.NsXs); NsXsi = nameTable.Add(XmlReservedNs.NsXsi); XsiType = nameTable.Add("type"); XsiNil = nameTable.Add("nil"); XsiSchemaLocation = nameTable.Add("schemaLocation"); XsiNoNamespaceSchemaLocation = nameTable.Add("noNamespaceSchemaLocation"); XsdSchema = nameTable.Add("schema"); XdrSchema = nameTable.Add("Schema"); QnPCData = new XmlQualifiedName(nameTable.Add("#PCDATA")); QnXml = new XmlQualifiedName(nameTable.Add("xml")); QnXmlNs = new XmlQualifiedName(nameTable.Add("xmlns"), NsXmlNs); QnDtDt = new XmlQualifiedName(nameTable.Add("dt"), NsDataType); QnXmlLang = new XmlQualifiedName(nameTable.Add("lang"), NsXml); // Empty namespace QnName = new XmlQualifiedName(nameTable.Add("name")); QnType = new XmlQualifiedName(nameTable.Add("type")); QnMaxOccurs = new XmlQualifiedName(nameTable.Add("maxOccurs")); QnMinOccurs = new XmlQualifiedName(nameTable.Add("minOccurs")); QnInfinite = new XmlQualifiedName(nameTable.Add("*")); QnModel = new XmlQualifiedName(nameTable.Add("model")); QnOpen = new XmlQualifiedName(nameTable.Add("open")); QnClosed = new XmlQualifiedName(nameTable.Add("closed")); QnContent = new XmlQualifiedName(nameTable.Add("content")); QnMixed = new XmlQualifiedName(nameTable.Add("mixed")); QnEmpty = new XmlQualifiedName(nameTable.Add("empty")); QnEltOnly = new XmlQualifiedName(nameTable.Add("eltOnly")); QnTextOnly = new XmlQualifiedName(nameTable.Add("textOnly")); QnOrder = new XmlQualifiedName(nameTable.Add("order")); QnSeq = new XmlQualifiedName(nameTable.Add("seq")); QnOne = new XmlQualifiedName(nameTable.Add("one")); QnMany = new XmlQualifiedName(nameTable.Add("many")); QnRequired = new XmlQualifiedName(nameTable.Add("required")); QnYes = new XmlQualifiedName(nameTable.Add("yes")); QnNo = new XmlQualifiedName(nameTable.Add("no")); QnString = new XmlQualifiedName(nameTable.Add("string")); QnID = new XmlQualifiedName(nameTable.Add("id")); QnIDRef = new XmlQualifiedName(nameTable.Add("idref")); QnIDRefs = new XmlQualifiedName(nameTable.Add("idrefs")); QnEntity = new XmlQualifiedName(nameTable.Add("entity")); QnEntities = new XmlQualifiedName(nameTable.Add("entities")); QnNmToken = new XmlQualifiedName(nameTable.Add("nmtoken")); QnNmTokens = new XmlQualifiedName(nameTable.Add("nmtokens")); QnEnumeration = new XmlQualifiedName(nameTable.Add("enumeration")); QnDefault = new XmlQualifiedName(nameTable.Add("default")); //For XSD Schema QnTargetNamespace = new XmlQualifiedName(nameTable.Add("targetNamespace")); QnVersion = new XmlQualifiedName(nameTable.Add("version")); QnFinalDefault = new XmlQualifiedName(nameTable.Add("finalDefault")); QnBlockDefault = new XmlQualifiedName(nameTable.Add("blockDefault")); QnFixed = new XmlQualifiedName(nameTable.Add("fixed")); QnAbstract = new XmlQualifiedName(nameTable.Add("abstract")); QnBlock = new XmlQualifiedName(nameTable.Add("block")); QnSubstitutionGroup = new XmlQualifiedName(nameTable.Add("substitutionGroup")); QnFinal = new XmlQualifiedName(nameTable.Add("final")); QnNillable = new XmlQualifiedName(nameTable.Add("nillable")); QnRef = new XmlQualifiedName(nameTable.Add("ref")); QnBase = new XmlQualifiedName(nameTable.Add("base")); QnDerivedBy = new XmlQualifiedName(nameTable.Add("derivedBy")); QnNamespace = new XmlQualifiedName(nameTable.Add("namespace")); QnProcessContents = new XmlQualifiedName(nameTable.Add("processContents")); QnRefer = new XmlQualifiedName(nameTable.Add("refer")); QnPublic = new XmlQualifiedName(nameTable.Add("public")); QnSystem = new XmlQualifiedName(nameTable.Add("system")); QnSchemaLocation = new XmlQualifiedName(nameTable.Add("schemaLocation")); QnValue = new XmlQualifiedName(nameTable.Add("value")); QnUse = new XmlQualifiedName(nameTable.Add("use")); QnForm = new XmlQualifiedName(nameTable.Add("form")); QnAttributeFormDefault = new XmlQualifiedName(nameTable.Add("attributeFormDefault")); QnElementFormDefault = new XmlQualifiedName(nameTable.Add("elementFormDefault")); QnSource = new XmlQualifiedName(nameTable.Add("source")); QnMemberTypes = new XmlQualifiedName(nameTable.Add("memberTypes")); QnItemType = new XmlQualifiedName(nameTable.Add("itemType")); QnXPath = new XmlQualifiedName(nameTable.Add("xpath")); // XDR namespace QnXdrSchema = new XmlQualifiedName(XdrSchema, NsXdr); QnXdrElementType = new XmlQualifiedName(nameTable.Add("ElementType"), NsXdr); QnXdrElement = new XmlQualifiedName(nameTable.Add("element"), NsXdr); QnXdrGroup = new XmlQualifiedName(nameTable.Add("group"), NsXdr); QnXdrAttributeType = new XmlQualifiedName(nameTable.Add("AttributeType"), NsXdr); QnXdrAttribute = new XmlQualifiedName(nameTable.Add("attribute"), NsXdr); QnXdrDataType = new XmlQualifiedName(nameTable.Add("datatype"), NsXdr); QnXdrDescription = new XmlQualifiedName(nameTable.Add("description"), NsXdr); QnXdrExtends = new XmlQualifiedName(nameTable.Add("extends"), NsXdr); // XDR alias namespace QnXdrAliasSchema = new XmlQualifiedName(nameTable.Add("Schema"), NsDataTypeAlias); // DataType namespace QnDtType = new XmlQualifiedName(nameTable.Add("type"), NsDataType); QnDtValues = new XmlQualifiedName(nameTable.Add("values"), NsDataType); QnDtMaxLength = new XmlQualifiedName(nameTable.Add("maxLength"), NsDataType); QnDtMinLength = new XmlQualifiedName(nameTable.Add("minLength"), NsDataType); QnDtMax = new XmlQualifiedName(nameTable.Add("max"), NsDataType); QnDtMin = new XmlQualifiedName(nameTable.Add("min"), NsDataType); QnDtMinExclusive = new XmlQualifiedName(nameTable.Add("minExclusive"), NsDataType); QnDtMaxExclusive = new XmlQualifiedName(nameTable.Add("maxExclusive"), NsDataType); // XSD namespace QnXsdSchema = new XmlQualifiedName(XsdSchema, NsXs); QnXsdAnnotation = new XmlQualifiedName(nameTable.Add("annotation"), NsXs); QnXsdInclude = new XmlQualifiedName(nameTable.Add("include"), NsXs); QnXsdImport = new XmlQualifiedName(nameTable.Add("import"), NsXs); QnXsdElement = new XmlQualifiedName(nameTable.Add("element"), NsXs); QnXsdAttribute = new XmlQualifiedName(nameTable.Add("attribute"), NsXs); QnXsdAttributeGroup = new XmlQualifiedName(nameTable.Add("attributeGroup"), NsXs); QnXsdAnyAttribute = new XmlQualifiedName(nameTable.Add("anyAttribute"), NsXs); QnXsdGroup = new XmlQualifiedName(nameTable.Add("group"), NsXs); QnXsdAll = new XmlQualifiedName(nameTable.Add("all"), NsXs); QnXsdChoice = new XmlQualifiedName(nameTable.Add("choice"), NsXs); QnXsdSequence = new XmlQualifiedName(nameTable.Add("sequence"), NsXs); QnXsdAny = new XmlQualifiedName(nameTable.Add("any"), NsXs); QnXsdNotation = new XmlQualifiedName(nameTable.Add("notation"), NsXs); QnXsdSimpleType = new XmlQualifiedName(nameTable.Add("simpleType"), NsXs); QnXsdComplexType = new XmlQualifiedName(nameTable.Add("complexType"), NsXs); QnXsdUnique = new XmlQualifiedName(nameTable.Add("unique"), NsXs); QnXsdKey = new XmlQualifiedName(nameTable.Add("key"), NsXs); QnXsdKeyRef = new XmlQualifiedName(nameTable.Add("keyref"), NsXs); QnXsdSelector = new XmlQualifiedName(nameTable.Add("selector"), NsXs); QnXsdField = new XmlQualifiedName(nameTable.Add("field"), NsXs); QnXsdMinExclusive = new XmlQualifiedName(nameTable.Add("minExclusive"), NsXs); QnXsdMinInclusive = new XmlQualifiedName(nameTable.Add("minInclusive"), NsXs); QnXsdMaxInclusive = new XmlQualifiedName(nameTable.Add("maxInclusive"), NsXs); QnXsdMaxExclusive = new XmlQualifiedName(nameTable.Add("maxExclusive"), NsXs); QnXsdTotalDigits = new XmlQualifiedName(nameTable.Add("totalDigits"), NsXs); QnXsdFractionDigits = new XmlQualifiedName(nameTable.Add("fractionDigits"), NsXs); QnXsdLength = new XmlQualifiedName(nameTable.Add("length"), NsXs); QnXsdMinLength = new XmlQualifiedName(nameTable.Add("minLength"), NsXs); QnXsdMaxLength = new XmlQualifiedName(nameTable.Add("maxLength"), NsXs); QnXsdEnumeration = new XmlQualifiedName(nameTable.Add("enumeration"), NsXs); QnXsdPattern = new XmlQualifiedName(nameTable.Add("pattern"), NsXs); QnXsdDocumentation = new XmlQualifiedName(nameTable.Add("documentation"), NsXs); QnXsdAppinfo = new XmlQualifiedName(nameTable.Add("appinfo"), NsXs); QnXsdComplexContent = new XmlQualifiedName(nameTable.Add("complexContent"), NsXs); QnXsdSimpleContent = new XmlQualifiedName(nameTable.Add("simpleContent"), NsXs); QnXsdRestriction = new XmlQualifiedName(nameTable.Add("restriction"), NsXs); QnXsdExtension = new XmlQualifiedName(nameTable.Add("extension"), NsXs); QnXsdUnion = new XmlQualifiedName(nameTable.Add("union"), NsXs); QnXsdList = new XmlQualifiedName(nameTable.Add("list"), NsXs); QnXsdWhiteSpace = new XmlQualifiedName(nameTable.Add("whiteSpace"), NsXs); QnXsdRedefine = new XmlQualifiedName(nameTable.Add("redefine"), NsXs); QnXsdAnyType = new XmlQualifiedName(nameTable.Add("anyType"), NsXs); //Create token to Qname table CreateTokenToQNameTable(); } public void CreateTokenToQNameTable() { TokenToQName[(int)Token.SchemaName] = QnName; TokenToQName[(int)Token.SchemaType] = QnType; TokenToQName[(int)Token.SchemaMaxOccurs] = QnMaxOccurs; TokenToQName[(int)Token.SchemaMinOccurs] = QnMinOccurs; TokenToQName[(int)Token.SchemaInfinite] = QnInfinite; TokenToQName[(int)Token.SchemaModel] = QnModel; TokenToQName[(int)Token.SchemaOpen] = QnOpen; TokenToQName[(int)Token.SchemaClosed] = QnClosed; TokenToQName[(int)Token.SchemaContent] = QnContent; TokenToQName[(int)Token.SchemaMixed] = QnMixed; TokenToQName[(int)Token.SchemaEmpty] = QnEmpty; TokenToQName[(int)Token.SchemaElementOnly] = QnEltOnly; TokenToQName[(int)Token.SchemaTextOnly] = QnTextOnly; TokenToQName[(int)Token.SchemaOrder] = QnOrder; TokenToQName[(int)Token.SchemaSeq] = QnSeq; TokenToQName[(int)Token.SchemaOne] = QnOne; TokenToQName[(int)Token.SchemaMany] = QnMany; TokenToQName[(int)Token.SchemaRequired] = QnRequired; TokenToQName[(int)Token.SchemaYes] = QnYes; TokenToQName[(int)Token.SchemaNo] = QnNo; TokenToQName[(int)Token.SchemaString] = QnString; TokenToQName[(int)Token.SchemaId] = QnID; TokenToQName[(int)Token.SchemaIdref] = QnIDRef; TokenToQName[(int)Token.SchemaIdrefs] = QnIDRefs; TokenToQName[(int)Token.SchemaEntity] = QnEntity; TokenToQName[(int)Token.SchemaEntities] = QnEntities; TokenToQName[(int)Token.SchemaNmtoken] = QnNmToken; TokenToQName[(int)Token.SchemaNmtokens] = QnNmTokens; TokenToQName[(int)Token.SchemaEnumeration] = QnEnumeration; TokenToQName[(int)Token.SchemaDefault] = QnDefault; TokenToQName[(int)Token.XdrRoot] = QnXdrSchema; TokenToQName[(int)Token.XdrElementType] = QnXdrElementType; TokenToQName[(int)Token.XdrElement] = QnXdrElement; TokenToQName[(int)Token.XdrGroup] = QnXdrGroup; TokenToQName[(int)Token.XdrAttributeType] = QnXdrAttributeType; TokenToQName[(int)Token.XdrAttribute] = QnXdrAttribute; TokenToQName[(int)Token.XdrDatatype] = QnXdrDataType; TokenToQName[(int)Token.XdrDescription] = QnXdrDescription; TokenToQName[(int)Token.XdrExtends] = QnXdrExtends; TokenToQName[(int)Token.SchemaXdrRootAlias] = QnXdrAliasSchema; TokenToQName[(int)Token.SchemaDtType] = QnDtType; TokenToQName[(int)Token.SchemaDtValues] = QnDtValues; TokenToQName[(int)Token.SchemaDtMaxLength] = QnDtMaxLength; TokenToQName[(int)Token.SchemaDtMinLength] = QnDtMinLength; TokenToQName[(int)Token.SchemaDtMax] = QnDtMax; TokenToQName[(int)Token.SchemaDtMin] = QnDtMin; TokenToQName[(int)Token.SchemaDtMinExclusive] = QnDtMinExclusive; TokenToQName[(int)Token.SchemaDtMaxExclusive] = QnDtMaxExclusive; TokenToQName[(int)Token.SchemaTargetNamespace] = QnTargetNamespace; TokenToQName[(int)Token.SchemaVersion] = QnVersion; TokenToQName[(int)Token.SchemaFinalDefault] = QnFinalDefault; TokenToQName[(int)Token.SchemaBlockDefault] = QnBlockDefault; TokenToQName[(int)Token.SchemaFixed] = QnFixed; TokenToQName[(int)Token.SchemaAbstract] = QnAbstract; TokenToQName[(int)Token.SchemaBlock] = QnBlock; TokenToQName[(int)Token.SchemaSubstitutionGroup] = QnSubstitutionGroup; TokenToQName[(int)Token.SchemaFinal] = QnFinal; TokenToQName[(int)Token.SchemaNillable] = QnNillable; TokenToQName[(int)Token.SchemaRef] = QnRef; TokenToQName[(int)Token.SchemaBase] = QnBase; TokenToQName[(int)Token.SchemaDerivedBy] = QnDerivedBy; TokenToQName[(int)Token.SchemaNamespace] = QnNamespace; TokenToQName[(int)Token.SchemaProcessContents] = QnProcessContents; TokenToQName[(int)Token.SchemaRefer] = QnRefer; TokenToQName[(int)Token.SchemaPublic] = QnPublic; TokenToQName[(int)Token.SchemaSystem] = QnSystem; TokenToQName[(int)Token.SchemaSchemaLocation] = QnSchemaLocation; TokenToQName[(int)Token.SchemaValue] = QnValue; TokenToQName[(int)Token.SchemaItemType] = QnItemType; TokenToQName[(int)Token.SchemaMemberTypes] = QnMemberTypes; TokenToQName[(int)Token.SchemaXPath] = QnXPath; TokenToQName[(int)Token.XsdSchema] = QnXsdSchema; TokenToQName[(int)Token.XsdAnnotation] = QnXsdAnnotation; TokenToQName[(int)Token.XsdInclude] = QnXsdInclude; TokenToQName[(int)Token.XsdImport] = QnXsdImport; TokenToQName[(int)Token.XsdElement] = QnXsdElement; TokenToQName[(int)Token.XsdAttribute] = QnXsdAttribute; TokenToQName[(int)Token.xsdAttributeGroup] = QnXsdAttributeGroup; TokenToQName[(int)Token.XsdAnyAttribute] = QnXsdAnyAttribute; TokenToQName[(int)Token.XsdGroup] = QnXsdGroup; TokenToQName[(int)Token.XsdAll] = QnXsdAll; TokenToQName[(int)Token.XsdChoice] = QnXsdChoice; TokenToQName[(int)Token.XsdSequence] = QnXsdSequence; TokenToQName[(int)Token.XsdAny] = QnXsdAny; TokenToQName[(int)Token.XsdNotation] = QnXsdNotation; TokenToQName[(int)Token.XsdSimpleType] = QnXsdSimpleType; TokenToQName[(int)Token.XsdComplexType] = QnXsdComplexType; TokenToQName[(int)Token.XsdUnique] = QnXsdUnique; TokenToQName[(int)Token.XsdKey] = QnXsdKey; TokenToQName[(int)Token.XsdKeyref] = QnXsdKeyRef; TokenToQName[(int)Token.XsdSelector] = QnXsdSelector; TokenToQName[(int)Token.XsdField] = QnXsdField; TokenToQName[(int)Token.XsdMinExclusive] = QnXsdMinExclusive; TokenToQName[(int)Token.XsdMinInclusive] = QnXsdMinInclusive; TokenToQName[(int)Token.XsdMaxExclusive] = QnXsdMaxExclusive; TokenToQName[(int)Token.XsdMaxInclusive] = QnXsdMaxInclusive; TokenToQName[(int)Token.XsdTotalDigits] = QnXsdTotalDigits; TokenToQName[(int)Token.XsdFractionDigits] = QnXsdFractionDigits; TokenToQName[(int)Token.XsdLength] = QnXsdLength; TokenToQName[(int)Token.XsdMinLength] = QnXsdMinLength; TokenToQName[(int)Token.XsdMaxLength] = QnXsdMaxLength; TokenToQName[(int)Token.XsdEnumeration] = QnXsdEnumeration; TokenToQName[(int)Token.XsdPattern] = QnXsdPattern; TokenToQName[(int)Token.XsdWhitespace] = QnXsdWhiteSpace; TokenToQName[(int)Token.XsdDocumentation] = QnXsdDocumentation; TokenToQName[(int)Token.XsdAppInfo] = QnXsdAppinfo; TokenToQName[(int)Token.XsdComplexContent] = QnXsdComplexContent; TokenToQName[(int)Token.XsdComplexContentRestriction] = QnXsdRestriction; TokenToQName[(int)Token.XsdSimpleContentRestriction] = QnXsdRestriction; TokenToQName[(int)Token.XsdSimpleTypeRestriction] = QnXsdRestriction; TokenToQName[(int)Token.XsdComplexContentExtension] = QnXsdExtension; TokenToQName[(int)Token.XsdSimpleContentExtension] = QnXsdExtension; TokenToQName[(int)Token.XsdSimpleContent] = QnXsdSimpleContent; TokenToQName[(int)Token.XsdSimpleTypeUnion] = QnXsdUnion; TokenToQName[(int)Token.XsdSimpleTypeList] = QnXsdList; TokenToQName[(int)Token.XsdRedefine] = QnXsdRedefine; TokenToQName[(int)Token.SchemaSource] = QnSource; TokenToQName[(int)Token.SchemaUse] = QnUse; TokenToQName[(int)Token.SchemaForm] = QnForm; TokenToQName[(int)Token.SchemaElementFormDefault] = QnElementFormDefault; TokenToQName[(int)Token.SchemaAttributeFormDefault] = QnAttributeFormDefault; TokenToQName[(int)Token.XmlLang] = QnXmlLang; TokenToQName[(int)Token.Empty] = XmlQualifiedName.Empty; } public SchemaType SchemaTypeFromRoot(string localName, string ns) { if (IsXSDRoot(localName, ns)) { return SchemaType.XSD; } else if (IsXDRRoot(localName, XmlSchemaDatatype.XdrCanonizeUri(ns, _nameTable, this))) { return SchemaType.XDR; } else { return SchemaType.None; } } public bool IsXSDRoot(string localName, string ns) { return Ref.Equal(ns, NsXs) && Ref.Equal(localName, XsdSchema); } public bool IsXDRRoot(string localName, string ns) { return Ref.Equal(ns, NsXdr) && Ref.Equal(localName, XdrSchema); } public XmlQualifiedName GetName(SchemaNames.Token token) { return TokenToQName[(int)token]; } public enum Token { Empty, SchemaName, SchemaType, SchemaMaxOccurs, SchemaMinOccurs, SchemaInfinite, SchemaModel, SchemaOpen, SchemaClosed, SchemaContent, SchemaMixed, SchemaEmpty, SchemaElementOnly, SchemaTextOnly, SchemaOrder, SchemaSeq, SchemaOne, SchemaMany, SchemaRequired, SchemaYes, SchemaNo, SchemaString, SchemaId, SchemaIdref, SchemaIdrefs, SchemaEntity, SchemaEntities, SchemaNmtoken, SchemaNmtokens, SchemaEnumeration, SchemaDefault, XdrRoot, XdrElementType, XdrElement, XdrGroup, XdrAttributeType, XdrAttribute, XdrDatatype, XdrDescription, XdrExtends, SchemaXdrRootAlias, SchemaDtType, SchemaDtValues, SchemaDtMaxLength, SchemaDtMinLength, SchemaDtMax, SchemaDtMin, SchemaDtMinExclusive, SchemaDtMaxExclusive, SchemaTargetNamespace, SchemaVersion, SchemaFinalDefault, SchemaBlockDefault, SchemaFixed, SchemaAbstract, SchemaBlock, SchemaSubstitutionGroup, SchemaFinal, SchemaNillable, SchemaRef, SchemaBase, SchemaDerivedBy, SchemaNamespace, SchemaProcessContents, SchemaRefer, SchemaPublic, SchemaSystem, SchemaSchemaLocation, SchemaValue, SchemaSource, SchemaAttributeFormDefault, SchemaElementFormDefault, SchemaUse, SchemaForm, XsdSchema, XsdAnnotation, XsdInclude, XsdImport, XsdElement, XsdAttribute, xsdAttributeGroup, XsdAnyAttribute, XsdGroup, XsdAll, XsdChoice, XsdSequence, XsdAny, XsdNotation, XsdSimpleType, XsdComplexType, XsdUnique, XsdKey, XsdKeyref, XsdSelector, XsdField, XsdMinExclusive, XsdMinInclusive, XsdMaxExclusive, XsdMaxInclusive, XsdTotalDigits, XsdFractionDigits, XsdLength, XsdMinLength, XsdMaxLength, XsdEnumeration, XsdPattern, XsdDocumentation, XsdAppInfo, XsdComplexContent, XsdComplexContentExtension, XsdComplexContentRestriction, XsdSimpleContent, XsdSimpleContentExtension, XsdSimpleContentRestriction, XsdSimpleTypeList, XsdSimpleTypeRestriction, XsdSimpleTypeUnion, XsdWhitespace, XsdRedefine, SchemaItemType, SchemaMemberTypes, SchemaXPath, XmlLang }; }; }
// 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.Globalization; using System.IO; using Avalonia.Platform; namespace Avalonia.Media { /// <summary> /// Parses a path markup string. /// </summary> public class PathMarkupParser : IDisposable { private static readonly Dictionary<char, Command> s_commands = new Dictionary<char, Command> { { 'F', Command.FillRule }, { 'M', Command.Move }, { 'L', Command.Line }, { 'H', Command.HorizontalLine }, { 'V', Command.VerticalLine }, { 'Q', Command.QuadraticBezierCurve }, { 'T', Command.SmoothQuadraticBezierCurve }, { 'C', Command.CubicBezierCurve }, { 'S', Command.SmoothCubicBezierCurve }, { 'A', Command.Arc }, { 'Z', Command.Close }, }; private IGeometryContext _geometryContext; private Point _currentPoint; private Point? _previousControlPoint; private bool _isOpen; private bool _isDisposed; /// <summary> /// Initializes a new instance of the <see cref="PathMarkupParser"/> class. /// </summary> /// <param name="geometryContext">The geometry context.</param> /// <exception cref="ArgumentNullException">geometryContext</exception> public PathMarkupParser(IGeometryContext geometryContext) { if (geometryContext == null) { throw new ArgumentNullException(nameof(geometryContext)); } _geometryContext = geometryContext; } private enum Command { None, FillRule, Move, Line, HorizontalLine, VerticalLine, CubicBezierCurve, QuadraticBezierCurve, SmoothCubicBezierCurve, SmoothQuadraticBezierCurve, Arc, Close } void IDisposable.Dispose() { Dispose(true); } protected virtual void Dispose(bool disposing) { if (_isDisposed) { return; } if (disposing) { _geometryContext = null; } _isDisposed = true; } private static Point MirrorControlPoint(Point controlPoint, Point center) { var dir = controlPoint - center; return center + -dir; } /// <summary> /// Parses the specified path data and writes the result to the geometryContext of this instance. /// </summary> /// <param name="pathData">The path data.</param> public void Parse(string pathData) { var span = pathData.AsSpan(); _currentPoint = new Point(); while(!span.IsEmpty) { if(!ReadCommand(ref span, out var command, out var relative)) { break; } bool initialCommand = true; do { if (!initialCommand) { span = ReadSeparator(span); } switch (command) { case Command.None: break; case Command.FillRule: SetFillRule(ref span); break; case Command.Move: AddMove(ref span, relative); break; case Command.Line: AddLine(ref span, relative); break; case Command.HorizontalLine: AddHorizontalLine(ref span, relative); break; case Command.VerticalLine: AddVerticalLine(ref span, relative); break; case Command.CubicBezierCurve: AddCubicBezierCurve(ref span, relative); break; case Command.QuadraticBezierCurve: AddQuadraticBezierCurve(ref span, relative); break; case Command.SmoothCubicBezierCurve: AddSmoothCubicBezierCurve(ref span, relative); break; case Command.SmoothQuadraticBezierCurve: AddSmoothQuadraticBezierCurve(ref span, relative); break; case Command.Arc: AddArc(ref span, relative); break; case Command.Close: CloseFigure(); break; default: throw new NotSupportedException("Unsupported command"); } initialCommand = false; } while (PeekArgument(span)); } if (_isOpen) { _geometryContext.EndFigure(false); } } private void CreateFigure() { if (_isOpen) { _geometryContext.EndFigure(false); } _geometryContext.BeginFigure(_currentPoint); _isOpen = true; } private void SetFillRule(ref ReadOnlySpan<char> span) { if (!ReadArgument(ref span, out var fillRule) || fillRule.Length != 1) { throw new InvalidDataException("Invalid fill rule."); } FillRule rule; switch (fillRule[0]) { case '0': rule = FillRule.EvenOdd; break; case '1': rule = FillRule.NonZero; break; default: throw new InvalidDataException("Invalid fill rule"); } _geometryContext.SetFillRule(rule); } private void CloseFigure() { if (_isOpen) { _geometryContext.EndFigure(true); } _previousControlPoint = null; _isOpen = false; } private void AddMove(ref ReadOnlySpan<char> span, bool relative) { var currentPoint = relative ? ReadRelativePoint(ref span, _currentPoint) : ReadPoint(ref span); _currentPoint = currentPoint; CreateFigure(); while (PeekArgument(span)) { span = ReadSeparator(span); AddLine(ref span, relative); if (!relative) { _currentPoint = currentPoint; CreateFigure(); } } } private void AddLine(ref ReadOnlySpan<char> span, bool relative) { _currentPoint = relative ? ReadRelativePoint(ref span, _currentPoint) : ReadPoint(ref span); if (!_isOpen) { CreateFigure(); } _geometryContext.LineTo(_currentPoint); } private void AddHorizontalLine(ref ReadOnlySpan<char> span, bool relative) { _currentPoint = relative ? new Point(_currentPoint.X + ReadDouble(ref span), _currentPoint.Y) : _currentPoint.WithX(ReadDouble(ref span)); if (!_isOpen) { CreateFigure(); } _geometryContext.LineTo(_currentPoint); } private void AddVerticalLine(ref ReadOnlySpan<char> span, bool relative) { _currentPoint = relative ? new Point(_currentPoint.X, _currentPoint.Y + ReadDouble(ref span)) : _currentPoint.WithY(ReadDouble(ref span)); if (!_isOpen) { CreateFigure(); } _geometryContext.LineTo(_currentPoint); } private void AddCubicBezierCurve(ref ReadOnlySpan<char> span, bool relative) { var point1 = relative ? ReadRelativePoint(ref span, _currentPoint) : ReadPoint(ref span); span = ReadSeparator(span); var point2 = relative ? ReadRelativePoint(ref span, _currentPoint) : ReadPoint(ref span); _previousControlPoint = point2; span = ReadSeparator(span); var point3 = relative ? ReadRelativePoint(ref span, _currentPoint) : ReadPoint(ref span); if (!_isOpen) { CreateFigure(); } _geometryContext.CubicBezierTo(point1, point2, point3); _currentPoint = point3; } private void AddQuadraticBezierCurve(ref ReadOnlySpan<char> span, bool relative) { var start = relative ? ReadRelativePoint(ref span, _currentPoint) : ReadPoint(ref span); _previousControlPoint = start; span = ReadSeparator(span); var end = relative ? ReadRelativePoint(ref span, _currentPoint) : ReadPoint(ref span); if (!_isOpen) { CreateFigure(); } _geometryContext.QuadraticBezierTo(start, end); _currentPoint = end; } private void AddSmoothCubicBezierCurve(ref ReadOnlySpan<char> span, bool relative) { var point2 = relative ? ReadRelativePoint(ref span, _currentPoint) : ReadPoint(ref span); span = ReadSeparator(span); var end = relative ? ReadRelativePoint(ref span, _currentPoint) : ReadPoint(ref span); if (_previousControlPoint != null) { _previousControlPoint = MirrorControlPoint((Point)_previousControlPoint, _currentPoint); } if (!_isOpen) { CreateFigure(); } _geometryContext.CubicBezierTo(_previousControlPoint ?? _currentPoint, point2, end); _previousControlPoint = point2; _currentPoint = end; } private void AddSmoothQuadraticBezierCurve(ref ReadOnlySpan<char> span, bool relative) { var end = relative ? ReadRelativePoint(ref span, _currentPoint) : ReadPoint(ref span); if (_previousControlPoint != null) { _previousControlPoint = MirrorControlPoint((Point)_previousControlPoint, _currentPoint); } if (!_isOpen) { CreateFigure(); } _geometryContext.QuadraticBezierTo(_previousControlPoint ?? _currentPoint, end); _currentPoint = end; } private void AddArc(ref ReadOnlySpan<char> span, bool relative) { var size = ReadSize(ref span); span = ReadSeparator(span); var rotationAngle = ReadDouble(ref span); span = ReadSeparator(span); var isLargeArc = ReadBool(ref span); span = ReadSeparator(span); var sweepDirection = ReadBool(ref span) ? SweepDirection.Clockwise : SweepDirection.CounterClockwise; span = ReadSeparator(span); var end = relative ? ReadRelativePoint(ref span, _currentPoint) : ReadPoint(ref span); if (!_isOpen) { CreateFigure(); } _geometryContext.ArcTo(end, size, rotationAngle, isLargeArc, sweepDirection); _currentPoint = end; _previousControlPoint = null; } private static bool PeekArgument(ReadOnlySpan<char> span) { span = SkipWhitespace(span); return !span.IsEmpty && (span[0] == ',' || span[0] == '-' || span[0] == '.' || char.IsDigit(span[0])); } private static bool ReadArgument(ref ReadOnlySpan<char> remaining, out ReadOnlySpan<char> argument) { remaining = SkipWhitespace(remaining); if (remaining.IsEmpty) { argument = ReadOnlySpan<char>.Empty; return false; } var valid = false; int i = 0; if (remaining[i] == '-') { i++; } for (; i < remaining.Length && char.IsNumber(remaining[i]); i++) valid = true; if (i < remaining.Length && remaining[i] == '.') { valid = false; i++; } for (; i < remaining.Length && char.IsNumber(remaining[i]); i++) valid = true; if (i < remaining.Length) { // scientific notation if (remaining[i] == 'E' || remaining[i] == 'e') { valid = false; i++; if (remaining[i] == '-' || remaining[i] == '+') { i++; for (; i < remaining.Length && char.IsNumber(remaining[i]); i++) valid = true; } } } if (!valid) { argument = ReadOnlySpan<char>.Empty; return false; } argument = remaining.Slice(0, i); remaining = remaining.Slice(i); return true; } private static ReadOnlySpan<char> ReadSeparator(ReadOnlySpan<char> span) { span = SkipWhitespace(span); if (!span.IsEmpty && span[0] == ',') { span = span.Slice(1); } return span; } private static ReadOnlySpan<char> SkipWhitespace(ReadOnlySpan<char> span) { int i = 0; for (; i < span.Length && char.IsWhiteSpace(span[i]); i++) ; return span.Slice(i); } private bool ReadBool(ref ReadOnlySpan<char> span) { if (!ReadArgument(ref span, out var boolValue) || boolValue.Length != 1) { throw new InvalidDataException("Invalid bool rule."); } switch (boolValue[0]) { case '0': return false; case '1': return true; default: throw new InvalidDataException("Invalid bool rule"); } } private double ReadDouble(ref ReadOnlySpan<char> span) { if (!ReadArgument(ref span, out var doubleValue)) { throw new InvalidDataException("Invalid double value"); } return double.Parse(doubleValue.ToString(), CultureInfo.InvariantCulture); } private Size ReadSize(ref ReadOnlySpan<char> span) { var width = ReadDouble(ref span); span = ReadSeparator(span); var height = ReadDouble(ref span); return new Size(width, height); } private Point ReadPoint(ref ReadOnlySpan<char> span) { var x = ReadDouble(ref span); span = ReadSeparator(span); var y = ReadDouble(ref span); return new Point(x, y); } private Point ReadRelativePoint(ref ReadOnlySpan<char> span, Point origin) { var x = ReadDouble(ref span); span = ReadSeparator(span); var y = ReadDouble(ref span); return new Point(origin.X + x, origin.Y + y); } private bool ReadCommand(ref ReadOnlySpan<char> span, out Command command, out bool relative) { span = SkipWhitespace(span); if (span.IsEmpty) { command = default; relative = false; return false; } var c = span[0]; if (!s_commands.TryGetValue(char.ToUpperInvariant(c), out command)) { throw new InvalidDataException("Unexpected path command '" + c + "'."); } relative = char.IsLower(c); span = span.Slice(1); return true; } } }
#pragma warning disable 1587 #region Header /// /// JsonMapper.cs /// JSON to .Net object and object to JSON conversions. /// /// The authors disclaim copyright to this source code. For more details, see /// the COPYING file included with this distribution. /// #endregion using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Reflection; namespace ThirdParty.Json.LitJson { internal struct PropertyMetadata { public MemberInfo Info; public bool IsField; public Type Type; } internal struct ArrayMetadata { private Type element_type; private bool is_array; private bool is_list; public Type ElementType { get { if (element_type == null) return typeof (JsonData); return element_type; } set { element_type = value; } } public bool IsArray { get { return is_array; } set { is_array = value; } } public bool IsList { get { return is_list; } set { is_list = value; } } } internal struct ObjectMetadata { private Type element_type; private bool is_dictionary; private IDictionary<string, PropertyMetadata> properties; public Type ElementType { get { if (element_type == null) return typeof (JsonData); return element_type; } set { element_type = value; } } public bool IsDictionary { get { return is_dictionary; } set { is_dictionary = value; } } public IDictionary<string, PropertyMetadata> Properties { get { return properties; } set { properties = value; } } } internal delegate void ExporterFunc (object obj, JsonWriter writer); public delegate void ExporterFunc<T> (T obj, JsonWriter writer); internal delegate object ImporterFunc (object input); public delegate TValue ImporterFunc<TJson, TValue> (TJson input); public delegate IJsonWrapper WrapperFactory (); public class JsonMapper { #region Fields private static int max_nesting_depth; private static IFormatProvider datetime_format; private static IDictionary<Type, ExporterFunc> base_exporters_table; private static IDictionary<Type, ExporterFunc> custom_exporters_table; private static IDictionary<Type, IDictionary<Type, ImporterFunc>> base_importers_table; private static IDictionary<Type, IDictionary<Type, ImporterFunc>> custom_importers_table; private static IDictionary<Type, ArrayMetadata> array_metadata; private static readonly object array_metadata_lock = new Object (); private static IDictionary<Type, IDictionary<Type, MethodInfo>> conv_ops; private static readonly object conv_ops_lock = new Object (); private static IDictionary<Type, ObjectMetadata> object_metadata; private static readonly object object_metadata_lock = new Object (); private static IDictionary<Type, IList<PropertyMetadata>> type_properties; private static readonly object type_properties_lock = new Object (); private static JsonWriter static_writer; private static readonly object static_writer_lock = new Object (); #endregion #region Constructors static JsonMapper () { max_nesting_depth = 100; array_metadata = new Dictionary<Type, ArrayMetadata> (); conv_ops = new Dictionary<Type, IDictionary<Type, MethodInfo>> (); object_metadata = new Dictionary<Type, ObjectMetadata> (); type_properties = new Dictionary<Type, IList<PropertyMetadata>> (); static_writer = new JsonWriter (); datetime_format = DateTimeFormatInfo.InvariantInfo; base_exporters_table = new Dictionary<Type, ExporterFunc> (); custom_exporters_table = new Dictionary<Type, ExporterFunc> (); base_importers_table = new Dictionary<Type, IDictionary<Type, ImporterFunc>> (); custom_importers_table = new Dictionary<Type, IDictionary<Type, ImporterFunc>> (); RegisterBaseExporters (); RegisterBaseImporters (); } #endregion #region Private Methods private static void AddArrayMetadata (Type type) { if (array_metadata.ContainsKey (type)) return; ArrayMetadata data = new ArrayMetadata (); data.IsArray = type.IsArray; if (type.GetInterface ("System.Collections.IList") != null) data.IsList = true; foreach (PropertyInfo p_info in type.GetProperties ()) { if (p_info.Name != "Item") continue; ParameterInfo[] parameters = p_info.GetIndexParameters (); if (parameters.Length != 1) continue; if (parameters[0].ParameterType == typeof (int)) data.ElementType = p_info.PropertyType; } lock (array_metadata_lock) { try { array_metadata.Add (type, data); } catch (ArgumentException) { return; } } } private static void AddObjectMetadata (Type type) { if (object_metadata.ContainsKey (type)) return; ObjectMetadata data = new ObjectMetadata (); if (type.GetInterface ("System.Collections.IDictionary") != null) data.IsDictionary = true; data.Properties = new Dictionary<string, PropertyMetadata> (); foreach (PropertyInfo p_info in type.GetProperties ()) { if (p_info.Name == "Item") { ParameterInfo[] parameters = p_info.GetIndexParameters (); if (parameters.Length != 1) continue; if (parameters[0].ParameterType == typeof (string)) data.ElementType = p_info.PropertyType; continue; } PropertyMetadata p_data = new PropertyMetadata (); p_data.Info = p_info; p_data.Type = p_info.PropertyType; data.Properties.Add (p_info.Name, p_data); } foreach (FieldInfo f_info in type.GetFields ()) { PropertyMetadata p_data = new PropertyMetadata (); p_data.Info = f_info; p_data.IsField = true; p_data.Type = f_info.FieldType; data.Properties.Add (f_info.Name, p_data); } lock (object_metadata_lock) { try { object_metadata.Add (type, data); } catch (ArgumentException) { return; } } } private static void AddTypeProperties (Type type) { if (type_properties.ContainsKey (type)) return; IList<PropertyMetadata> props = new List<PropertyMetadata> (); foreach (PropertyInfo p_info in type.GetProperties ()) { if (p_info.Name == "Item") continue; PropertyMetadata p_data = new PropertyMetadata (); p_data.Info = p_info; p_data.IsField = false; props.Add (p_data); } foreach (FieldInfo f_info in type.GetFields ()) { PropertyMetadata p_data = new PropertyMetadata (); p_data.Info = f_info; p_data.IsField = true; props.Add (p_data); } lock (type_properties_lock) { try { type_properties.Add (type, props); } catch (ArgumentException) { return; } } } private static MethodInfo GetConvOp (Type t1, Type t2) { lock (conv_ops_lock) { if (! conv_ops.ContainsKey (t1)) conv_ops.Add (t1, new Dictionary<Type, MethodInfo> ()); } if (conv_ops[t1].ContainsKey (t2)) return conv_ops[t1][t2]; MethodInfo op = t1.GetMethod ( "op_Implicit", new Type[] { t2 }); lock (conv_ops_lock) { try { conv_ops[t1].Add (t2, op); } catch (ArgumentException) { return conv_ops[t1][t2]; } } return op; } private static object ReadValue (Type inst_type, JsonReader reader) { reader.Read (); if (reader.Token == JsonToken.ArrayEnd) return null; if (reader.Token == JsonToken.Null) { if (! inst_type.IsClass) throw new JsonException (String.Format ( "Can't assign null to an instance of type {0}", inst_type)); return null; } if (reader.Token == JsonToken.Double || reader.Token == JsonToken.Int || reader.Token == JsonToken.Long || reader.Token == JsonToken.String || reader.Token == JsonToken.Boolean) { Type json_type = reader.Value.GetType (); if (inst_type.IsAssignableFrom (json_type)) return reader.Value; // If there's a custom importer that fits, use it if (custom_importers_table.ContainsKey (json_type) && custom_importers_table[json_type].ContainsKey ( inst_type)) { ImporterFunc importer = custom_importers_table[json_type][inst_type]; return importer (reader.Value); } // Maybe there's a base importer that works if (base_importers_table.ContainsKey (json_type) && base_importers_table[json_type].ContainsKey ( inst_type)) { ImporterFunc importer = base_importers_table[json_type][inst_type]; return importer (reader.Value); } // Maybe it's an enum if (inst_type.IsEnum) return Enum.ToObject (inst_type, reader.Value); // Try using an implicit conversion operator MethodInfo conv_op = GetConvOp (inst_type, json_type); if (conv_op != null) return conv_op.Invoke (null, new object[] { reader.Value }); // No luck throw new JsonException (String.Format ( "Can't assign value '{0}' (type {1}) to type {2}", reader.Value, json_type, inst_type)); } object instance = null; if (reader.Token == JsonToken.ArrayStart) { AddArrayMetadata (inst_type); ArrayMetadata t_data = array_metadata[inst_type]; if (! t_data.IsArray && ! t_data.IsList) throw new JsonException (String.Format ( "Type {0} can't act as an array", inst_type)); IList list; Type elem_type; if (! t_data.IsArray) { list = (IList) Activator.CreateInstance (inst_type); elem_type = t_data.ElementType; } else { list = new ArrayList (); elem_type = inst_type.GetElementType (); } while (true) { object item = ReadValue (elem_type, reader); if (reader.Token == JsonToken.ArrayEnd) break; list.Add (item); } if (t_data.IsArray) { int n = list.Count; instance = Array.CreateInstance (elem_type, n); for (int i = 0; i < n; i++) ((Array) instance).SetValue (list[i], i); } else instance = list; } else if (reader.Token == JsonToken.ObjectStart) { AddObjectMetadata (inst_type); ObjectMetadata t_data = object_metadata[inst_type]; instance = Activator.CreateInstance (inst_type); while (true) { reader.Read (); if (reader.Token == JsonToken.ObjectEnd) break; string property = (string) reader.Value; if (t_data.Properties.ContainsKey (property)) { PropertyMetadata prop_data = t_data.Properties[property]; if (prop_data.IsField) { ((FieldInfo) prop_data.Info).SetValue ( instance, ReadValue (prop_data.Type, reader)); } else { PropertyInfo p_info = (PropertyInfo) prop_data.Info; if (p_info.CanWrite) p_info.SetValue ( instance, ReadValue (prop_data.Type, reader), null); else ReadValue (prop_data.Type, reader); } } else { if (! t_data.IsDictionary) throw new JsonException (String.Format ( "The type {0} doesn't have the " + "property '{1}'", inst_type, property)); ((IDictionary) instance).Add ( property, ReadValue ( t_data.ElementType, reader)); } } } return instance; } private static IJsonWrapper ReadValue (WrapperFactory factory, JsonReader reader) { reader.Read (); if (reader.Token == JsonToken.ArrayEnd || reader.Token == JsonToken.Null) return null; IJsonWrapper instance = factory (); if (reader.Token == JsonToken.String) { instance.SetString ((string) reader.Value); return instance; } if (reader.Token == JsonToken.Double) { instance.SetDouble ((double) reader.Value); return instance; } if (reader.Token == JsonToken.Int) { instance.SetInt ((int) reader.Value); return instance; } if (reader.Token == JsonToken.Long) { instance.SetLong ((long) reader.Value); return instance; } if (reader.Token == JsonToken.Boolean) { instance.SetBoolean ((bool) reader.Value); return instance; } if (reader.Token == JsonToken.ArrayStart) { instance.SetJsonType (JsonType.Array); while (true) { IJsonWrapper item = ReadValue (factory, reader); // nij - added check to see if the item is not null. This is to handle arrays within arrays. // In those cases when the outer array read the inner array an item was returned back the current // reader.Token is at the ArrayEnd for the inner array. if (item == null && reader.Token == JsonToken.ArrayEnd) break; ((IList) instance).Add (item); } } else if (reader.Token == JsonToken.ObjectStart) { instance.SetJsonType (JsonType.Object); while (true) { reader.Read (); if (reader.Token == JsonToken.ObjectEnd) break; string property = (string) reader.Value; ((IDictionary) instance)[property] = ReadValue ( factory, reader); } } return instance; } private static void RegisterBaseExporters () { base_exporters_table[typeof (byte)] = delegate (object obj, JsonWriter writer) { writer.Write (Convert.ToInt32 ((byte) obj)); }; base_exporters_table[typeof (char)] = delegate (object obj, JsonWriter writer) { writer.Write (Convert.ToString ((char) obj)); }; base_exporters_table[typeof (DateTime)] = delegate (object obj, JsonWriter writer) { writer.Write (Convert.ToString ((DateTime) obj, datetime_format)); }; base_exporters_table[typeof (decimal)] = delegate (object obj, JsonWriter writer) { writer.Write ((decimal) obj); }; base_exporters_table[typeof (sbyte)] = delegate (object obj, JsonWriter writer) { writer.Write (Convert.ToInt32 ((sbyte) obj)); }; base_exporters_table[typeof (short)] = delegate (object obj, JsonWriter writer) { writer.Write (Convert.ToInt32 ((short) obj)); }; base_exporters_table[typeof (ushort)] = delegate (object obj, JsonWriter writer) { writer.Write (Convert.ToInt32 ((ushort) obj)); }; base_exporters_table[typeof (uint)] = delegate (object obj, JsonWriter writer) { writer.Write (Convert.ToUInt64 ((uint) obj)); }; base_exporters_table[typeof (ulong)] = delegate (object obj, JsonWriter writer) { writer.Write ((ulong) obj); }; } private static void RegisterBaseImporters () { ImporterFunc importer; importer = delegate (object input) { return Convert.ToByte ((int) input); }; RegisterImporter (base_importers_table, typeof (int), typeof (byte), importer); importer = delegate (object input) { return Convert.ToUInt64 ((int) input); }; RegisterImporter (base_importers_table, typeof (int), typeof (ulong), importer); importer = delegate (object input) { return Convert.ToSByte ((int) input); }; RegisterImporter (base_importers_table, typeof (int), typeof (sbyte), importer); importer = delegate (object input) { return Convert.ToInt16 ((int) input); }; RegisterImporter (base_importers_table, typeof (int), typeof (short), importer); importer = delegate (object input) { return Convert.ToUInt16 ((int) input); }; RegisterImporter (base_importers_table, typeof (int), typeof (ushort), importer); importer = delegate (object input) { return Convert.ToUInt32 ((int) input); }; RegisterImporter (base_importers_table, typeof (int), typeof (uint), importer); importer = delegate (object input) { return Convert.ToSingle ((int) input); }; RegisterImporter (base_importers_table, typeof (int), typeof (float), importer); importer = delegate (object input) { return Convert.ToDouble ((int) input); }; RegisterImporter (base_importers_table, typeof (int), typeof (double), importer); importer = delegate (object input) { return Convert.ToDecimal ((double) input); }; RegisterImporter (base_importers_table, typeof (double), typeof (decimal), importer); importer = delegate (object input) { return Convert.ToUInt32 ((long) input); }; RegisterImporter (base_importers_table, typeof (long), typeof (uint), importer); importer = delegate (object input) { return Convert.ToChar ((string) input); }; RegisterImporter (base_importers_table, typeof (string), typeof (char), importer); importer = delegate (object input) { return Convert.ToDateTime ((string) input, datetime_format); }; RegisterImporter (base_importers_table, typeof (string), typeof (DateTime), importer); } private static void RegisterImporter ( IDictionary<Type, IDictionary<Type, ImporterFunc>> table, Type json_type, Type value_type, ImporterFunc importer) { if (! table.ContainsKey (json_type)) table.Add (json_type, new Dictionary<Type, ImporterFunc> ()); table[json_type][value_type] = importer; } private static void WriteValue (object obj, JsonWriter writer, bool writer_is_private, int depth) { if (depth > max_nesting_depth) throw new JsonException ( String.Format ("Max allowed object depth reached while " + "trying to export from type {0}", obj.GetType ())); if (obj == null) { writer.Write (null); return; } if (obj is IJsonWrapper) { if (writer_is_private) writer.TextWriter.Write (((IJsonWrapper) obj).ToJson ()); else ((IJsonWrapper) obj).ToJson (writer); return; } if (obj is String) { writer.Write ((string) obj); return; } if (obj is Double) { writer.Write ((double) obj); return; } if (obj is Int32) { writer.Write ((int) obj); return; } if (obj is Boolean) { writer.Write ((bool) obj); return; } if (obj is Int64) { writer.Write ((long) obj); return; } if (obj is Array) { writer.WriteArrayStart (); foreach (object elem in (Array) obj) WriteValue (elem, writer, writer_is_private, depth + 1); writer.WriteArrayEnd (); return; } if (obj is IList) { writer.WriteArrayStart (); foreach (object elem in (IList) obj) WriteValue (elem, writer, writer_is_private, depth + 1); writer.WriteArrayEnd (); return; } if (obj is IDictionary) { writer.WriteObjectStart (); foreach (DictionaryEntry entry in (IDictionary) obj) { writer.WritePropertyName ((string) entry.Key); WriteValue (entry.Value, writer, writer_is_private, depth + 1); } writer.WriteObjectEnd (); return; } Type obj_type = obj.GetType (); // See if there's a custom exporter for the object if (custom_exporters_table.ContainsKey (obj_type)) { ExporterFunc exporter = custom_exporters_table[obj_type]; exporter (obj, writer); return; } // If not, maybe there's a base exporter if (base_exporters_table.ContainsKey (obj_type)) { ExporterFunc exporter = base_exporters_table[obj_type]; exporter (obj, writer); return; } // Last option, let's see if it's an enum if (obj is Enum) { Type e_type = Enum.GetUnderlyingType (obj_type); if (e_type == typeof (long) || e_type == typeof (uint) || e_type == typeof (ulong)) writer.Write ((ulong) obj); else writer.Write ((int) obj); return; } // Okay, so it looks like the input should be exported as an // object AddTypeProperties (obj_type); IList<PropertyMetadata> props = type_properties[obj_type]; writer.WriteObjectStart (); foreach (PropertyMetadata p_data in props) { if (p_data.IsField) { writer.WritePropertyName (p_data.Info.Name); WriteValue (((FieldInfo) p_data.Info).GetValue (obj), writer, writer_is_private, depth + 1); } else { PropertyInfo p_info = (PropertyInfo) p_data.Info; if (p_info.CanRead) { writer.WritePropertyName (p_data.Info.Name); WriteValue (p_info.GetValue (obj, null), writer, writer_is_private, depth + 1); } } } writer.WriteObjectEnd (); } #endregion public static string ToJson (object obj) { lock (static_writer_lock) { static_writer.Reset (); WriteValue (obj, static_writer, true, 0); return static_writer.ToString (); } } public static void ToJson (object obj, JsonWriter writer) { WriteValue (obj, writer, false, 0); } public static JsonData ToObject (JsonReader reader) { return (JsonData) ToWrapper ( delegate { return new JsonData (); }, reader); } public static JsonData ToObject (TextReader reader) { JsonReader json_reader = new JsonReader (reader); return (JsonData) ToWrapper ( delegate { return new JsonData (); }, json_reader); } public static JsonData ToObject (string json) { return (JsonData) ToWrapper ( delegate { return new JsonData (); }, json); } public static T ToObject<T> (JsonReader reader) { return (T) ReadValue (typeof (T), reader); } public static T ToObject<T> (TextReader reader) { JsonReader json_reader = new JsonReader (reader); return (T) ReadValue (typeof (T), json_reader); } public static T ToObject<T> (string json) { JsonReader reader = new JsonReader (json); return (T) ReadValue (typeof (T), reader); } public static IJsonWrapper ToWrapper (WrapperFactory factory, JsonReader reader) { return ReadValue (factory, reader); } public static IJsonWrapper ToWrapper (WrapperFactory factory, string json) { JsonReader reader = new JsonReader (json); return ReadValue (factory, reader); } public static void RegisterExporter<T> (ExporterFunc<T> exporter) { ExporterFunc exporter_wrapper = delegate (object obj, JsonWriter writer) { exporter ((T) obj, writer); }; custom_exporters_table[typeof (T)] = exporter_wrapper; } public static void RegisterImporter<TJson, TValue> ( ImporterFunc<TJson, TValue> importer) { ImporterFunc importer_wrapper = delegate (object input) { return importer ((TJson) input); }; RegisterImporter (custom_importers_table, typeof (TJson), typeof (TValue), importer_wrapper); } public static void UnregisterExporters () { custom_exporters_table.Clear (); } public static void UnregisterImporters () { custom_importers_table.Clear (); } } }
using System; using System.Management.Automation; using EnvDTE; using NuGet.VisualStudio; namespace NuGet.PowerShell.Commands { /// <summary> /// This project updates the specified package to the specified project. /// </summary> [Cmdlet(VerbsData.Update, "Package", DefaultParameterSetName = "All")] public class UpdatePackageCommand : ProcessPackageBaseCommand, IPackageOperationEventListener { private readonly IVsPackageSourceProvider _packageSourceProvider; private readonly IPackageRepositoryFactory _repositoryFactory; private readonly IProductUpdateService _productUpdateService; private bool _hasConnectedToHttpSource; public UpdatePackageCommand() : this(ServiceLocator.GetInstance<ISolutionManager>(), ServiceLocator.GetInstance<IVsPackageManagerFactory>(), ServiceLocator.GetInstance<IPackageRepositoryFactory>(), ServiceLocator.GetInstance<IVsPackageSourceProvider>(), ServiceLocator.GetInstance<IHttpClientEvents>(), ServiceLocator.GetInstance<IProductUpdateService>(), ServiceLocator.GetInstance<IVsCommonOperations>()) { } public UpdatePackageCommand(ISolutionManager solutionManager, IVsPackageManagerFactory packageManagerFactory, IPackageRepositoryFactory repositoryFactory, IVsPackageSourceProvider packageSourceProvider, IHttpClientEvents httpClientEvents, IProductUpdateService productUpdateService, IVsCommonOperations vsCommonOperations) : base(solutionManager, packageManagerFactory, httpClientEvents, vsCommonOperations) { _repositoryFactory = repositoryFactory; _packageSourceProvider = packageSourceProvider; _productUpdateService = productUpdateService; } // We need to override id since it's mandatory in the base class. We don't // want it to be mandatory here. [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, Position = 0, ParameterSetName = "Project")] [Parameter(ValueFromPipelineByPropertyName = true, Position = 0, ParameterSetName = "All")] public override string Id { get { return base.Id; } set { base.Id = value; } } [Parameter(Position = 1, ValueFromPipelineByPropertyName = true, ParameterSetName = "All")] [Parameter(Position = 1, ValueFromPipelineByPropertyName = true, ParameterSetName = "Project")] public override string ProjectName { get { return base.ProjectName; } set { base.ProjectName = value; } } [Parameter(Position = 2, ParameterSetName = "Project")] [ValidateNotNull] public SemanticVersion Version { get; set; } [Parameter(Position = 3)] [ValidateNotNullOrEmpty] public string Source { get; set; } [Parameter] public SwitchParameter IgnoreDependencies { get; set; } [Parameter] public SwitchParameter Safe { get; set; } [Parameter, Alias("Prerelease")] public SwitchParameter IncludePrerelease { get; set; } protected override IVsPackageManager CreatePackageManager() { if (!String.IsNullOrEmpty(Source)) { IPackageRepository repository = CreateRepositoryFromSource(_repositoryFactory, _packageSourceProvider, Source); return repository == null ? null : PackageManagerFactory.CreatePackageManager(repository, useFallbackForDependencies: true); } return base.CreatePackageManager(); } protected override void ProcessRecordCore() { if (!SolutionManager.IsSolutionOpen) { // terminating ErrorHandler.ThrowSolutionNotOpenTerminatingError(); } try { SubscribeToProgressEvents(); if (PackageManager != null) { IProjectManager projectManager = ProjectManager; if (!String.IsNullOrEmpty(Id)) { // If a package id was specified, but no project was specified, then update this package in all projects if (String.IsNullOrEmpty(ProjectName)) { if (Safe.IsPresent) { PackageManager.SafeUpdatePackage(Id, !IgnoreDependencies.IsPresent, IncludePrerelease, this, this); } else { PackageManager.UpdatePackage(Id, Version, !IgnoreDependencies.IsPresent, IncludePrerelease, this, this); } } else if (projectManager != null) { // If there was a project specified, then update the package in that project if (Safe.IsPresent) { PackageManager.SafeUpdatePackage(projectManager, Id, !IgnoreDependencies, IncludePrerelease, this); } else { PackageManager.UpdatePackage(projectManager, Id, Version, !IgnoreDependencies, IncludePrerelease, this); } } } else { // if no id was specified then update all packages in the solution if (Safe.IsPresent) { if (String.IsNullOrEmpty(ProjectName)) { PackageManager.SafeUpdatePackages(!IgnoreDependencies.IsPresent, IncludePrerelease, this, this); } else if (projectManager != null) { PackageManager.SafeUpdatePackages(projectManager, !IgnoreDependencies.IsPresent, IncludePrerelease, this); } } else { if (String.IsNullOrEmpty(ProjectName)) { PackageManager.UpdatePackages(!IgnoreDependencies.IsPresent, IncludePrerelease, this, this); } else if (projectManager != null) { PackageManager.UpdatePackages(projectManager, !IgnoreDependencies.IsPresent, IncludePrerelease, this); } } } _hasConnectedToHttpSource |= UriHelper.IsHttpSource(Source, _packageSourceProvider); } } finally { UnsubscribeFromProgressEvents(); } } protected override void EndProcessing() { base.EndProcessing(); CheckForNuGetUpdate(); } private void CheckForNuGetUpdate() { if (_productUpdateService != null && _hasConnectedToHttpSource) { _productUpdateService.CheckForAvailableUpdateAsync(); } } public void OnBeforeAddPackageReference(Project project) { RegisterProjectEvents(project); } public void OnAfterAddPackageReference(Project project) { // No-op } public void OnAddPackageReferenceError(Project project, Exception exception) { // No-op } } }
// // Copyright (c) 2004-2021 Jaroslaw Kowalski <[email protected]>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.LayoutRenderers { using System; using System.Collections.Generic; using System.Globalization; using System.Reflection; using System.Text; using System.Xml; using NLog.Common; using NLog.Config; using NLog.Internal; using NLog.Internal.Fakeables; using NLog.Layouts; using NLog.Targets; /// <summary> /// XML event description compatible with log4j, Chainsaw and NLogViewer. /// </summary> [LayoutRenderer("log4jxmlevent")] [MutableUnsafe] public class Log4JXmlEventLayoutRenderer : LayoutRenderer, IUsesStackTrace, IIncludeContext { private static readonly DateTime log4jDateBase = new DateTime(1970, 1, 1); private static readonly string dummyNamespace = "http://nlog-project.org/dummynamespace/" + Guid.NewGuid(); private static readonly string dummyNamespaceRemover = " xmlns:log4j=\"" + dummyNamespace + "\""; private static readonly string dummyNLogNamespace = "http://nlog-project.org/dummynamespace/" + Guid.NewGuid(); private static readonly string dummyNLogNamespaceRemover = " xmlns:nlog=\"" + dummyNLogNamespace + "\""; private readonly ScopeContextNestedStatesLayoutRenderer _scopeNestedLayoutRenderer = new ScopeContextNestedStatesLayoutRenderer(); /// <summary> /// Initializes a new instance of the <see cref="Log4JXmlEventLayoutRenderer" /> class. /// </summary> public Log4JXmlEventLayoutRenderer() : this(LogFactory.DefaultAppEnvironment) { } /// <summary> /// Initializes a new instance of the <see cref="Log4JXmlEventLayoutRenderer" /> class. /// </summary> internal Log4JXmlEventLayoutRenderer(IAppEnvironment appEnvironment) { #if NETSTANDARD1_3 AppInfo = "NetCore Application"; #else AppInfo = string.Format( CultureInfo.InvariantCulture, "{0}({1})", appEnvironment.AppDomainFriendlyName, appEnvironment.CurrentProcessId); #endif Parameters = new List<NLogViewerParameterInfo>(); try { _machineName = EnvironmentHelper.GetMachineName(); if (string.IsNullOrEmpty(_machineName)) { InternalLogger.Info("MachineName is not available."); } } catch (Exception exception) { InternalLogger.Error(exception, "Error getting machine name."); if (exception.MustBeRethrown()) { throw; } _machineName = string.Empty; } } /// <inheritdoc/> protected override void InitializeLayoutRenderer() { base.InitializeLayoutRenderer(); _xmlWriterSettings = new XmlWriterSettings { Indent = IndentXml, ConformanceLevel = ConformanceLevel.Fragment, #if !NET35 NamespaceHandling = NamespaceHandling.OmitDuplicates, #endif IndentChars = " ", }; } /// <summary> /// Gets or sets a value indicating whether to include NLog-specific extensions to log4j schema. /// </summary> /// <docgen category='Payload Options' order='10' /> public bool IncludeNLogData { get; set; } /// <summary> /// Gets or sets a value indicating whether the XML should use spaces for indentation. /// </summary> /// <docgen category='Payload Options' order='10' /> public bool IndentXml { get; set; } /// <summary> /// Gets or sets the AppInfo field. By default it's the friendly name of the current AppDomain. /// </summary> /// <docgen category='Payload Options' order='10' /> public Layout AppInfo { get; set; } /// <summary> /// Gets or sets a value indicating whether to include call site (class and method name) in the information sent over the network. /// </summary> /// <docgen category='Payload Options' order='10' /> public bool IncludeCallSite { get; set; } /// <summary> /// Gets or sets a value indicating whether to include source info (file name and line number) in the information sent over the network. /// </summary> /// <docgen category='Payload Options' order='10' /> public bool IncludeSourceInfo { get; set; } /// <summary> /// Gets or sets a value indicating whether to include contents of the <see cref="MappedDiagnosticsContext"/> dictionary. /// </summary> /// <docgen category='Payload Options' order='10' /> [Obsolete("Replaced by IncludeScopeProperties. Marked obsolete on NLog 5.0")] public bool IncludeMdc { get => _includeMdc ?? false; set => _includeMdc = value; } private bool? _includeMdc; /// <summary> /// Gets or sets a value indicating whether to include contents of the <see cref="MappedDiagnosticsLogicalContext"/> dictionary. /// </summary> /// <docgen category='Payload Options' order='10' /> [Obsolete("Replaced by IncludeScopeProperties. Marked obsolete on NLog 5.0")] public bool IncludeMdlc { get => _includeMdlc ?? false; set => _includeMdlc = value; } private bool? _includeMdlc; /// <summary> /// Gets or sets a value indicating whether to include contents of the <see cref="NestedDiagnosticsLogicalContext"/> stack. /// </summary> /// <docgen category='Payload Options' order='10' /> [Obsolete("Replaced by IncludeNdc. Marked obsolete on NLog 5.0")] public bool IncludeNdlc { get => _includeNdlc ?? false; set => _includeNdlc = value; } private bool? _includeNdlc; /// <summary> /// Gets or sets whether to include log4j:NDC in output from <see cref="ScopeContext"/> nested context. /// </summary> /// <docgen category='Payload Options' order='10' /> public bool IncludeNdc { get => _includeNdc ?? false; set => _includeNdc = value; } private bool? _includeNdc; /// <summary> /// Gets or sets whether to include the contents of the <see cref="ScopeContext"/> properties-dictionary. /// </summary> /// <docgen category='Payload Options' order='10' /> public bool IncludeScopeProperties { get => _includeScopeProperties ?? (_includeMdlc == true || _includeMdc == true); set => _includeScopeProperties = value; } private bool? _includeScopeProperties; /// <summary> /// Gets or sets whether to include log4j:NDC in output from <see cref="ScopeContext"/> nested context. /// </summary> /// <docgen category='Payload Options' order='10' /> public bool IncludeScopeNested { get => _includeScopeNested ?? (_includeNdlc == true || _includeNdc == true); set => _includeScopeNested = value; } private bool? _includeScopeNested; /// <summary> /// Gets or sets the stack separator for log4j:NDC in output from <see cref="ScopeContext"/> nested context. /// </summary> /// <docgen category='Payload Options' order='10' /> public string ScopeNestedSeparator { get => _scopeNestedLayoutRenderer.Separator; set => _scopeNestedLayoutRenderer.Separator = value; } /// <summary> /// Gets or sets the stack separator for log4j:NDC in output from <see cref="ScopeContext"/> nested context. /// </summary> /// <docgen category='Payload Options' order='10' /> [Obsolete("Replaced by NdcItemSeparator. Marked obsolete on NLog 5.0")] public string NdlcItemSeparator { get => ScopeNestedSeparator; set => ScopeNestedSeparator = value; } /// <summary> /// Gets or sets the option to include all properties from the log events /// </summary> /// <docgen category='Payload Options' order='10' /> [Obsolete("Replaced by IncludeEventProperties. Marked obsolete on NLog 5.0")] public bool IncludeAllProperties { get => IncludeEventProperties; set => IncludeEventProperties = value; } /// <summary> /// Gets or sets the option to include all properties from the log events /// </summary> /// <docgen category='Payload Options' order='10' /> public bool IncludeEventProperties { get; set; } /// <summary> /// Gets or sets the stack separator for log4j:NDC in output from <see cref="ScopeContext"/> nested context. /// </summary> /// <docgen category='Payload Options' order='10' /> public string NdcItemSeparator { get => ScopeNestedSeparator; set => ScopeNestedSeparator = value; } /// <summary> /// Gets or sets the log4j:event logger-xml-attribute (Default ${logger}) /// </summary> /// <docgen category='Payload Options' order='10' /> public Layout LoggerName { get; set; } /// <summary> /// Gets or sets whether the log4j:throwable xml-element should be written as CDATA /// </summary> public bool WriteThrowableCData { get; set; } private readonly string _machineName; private XmlWriterSettings _xmlWriterSettings; /// <inheritdoc/> StackTraceUsage IUsesStackTrace.StackTraceUsage => (IncludeCallSite || IncludeSourceInfo) ? (StackTraceUsageUtils.GetStackTraceUsage(IncludeSourceInfo, 0, true) | StackTraceUsage.WithCallSiteClassName) : StackTraceUsage.None; internal IList<NLogViewerParameterInfo> Parameters { get; set; } /// <inheritdoc/> protected override void Append(StringBuilder builder, LogEventInfo logEvent) { StringBuilder sb = new StringBuilder(); using (XmlWriter xtw = XmlWriter.Create(sb, _xmlWriterSettings)) { xtw.WriteStartElement("log4j", "event", dummyNamespace); bool includeNLogCallsite = (IncludeCallSite || IncludeSourceInfo) && logEvent.CallSiteInformation != null; if (includeNLogCallsite && IncludeNLogData) { xtw.WriteAttributeString("xmlns", "nlog", null, dummyNLogNamespace); } xtw.WriteAttributeSafeString("logger", LoggerName != null ? LoggerName.Render(logEvent) : logEvent.LoggerName); xtw.WriteAttributeString("level", logEvent.Level.Name.ToUpperInvariant()); xtw.WriteAttributeString("timestamp", Convert.ToString((long)(logEvent.TimeStamp.ToUniversalTime() - log4jDateBase).TotalMilliseconds, CultureInfo.InvariantCulture)); xtw.WriteAttributeString("thread", AsyncHelpers.GetManagedThreadId().ToString(CultureInfo.InvariantCulture)); xtw.WriteElementSafeString("log4j", "message", dummyNamespace, logEvent.FormattedMessage); if (logEvent.Exception != null) { if (WriteThrowableCData) { // CDATA correctly preserves newlines and indention, but not all viewers support this xtw.WriteStartElement("log4j", "throwable", dummyNamespace); xtw.WriteSafeCData(logEvent.Exception.ToString()); xtw.WriteEndElement(); } else { xtw.WriteElementSafeString("log4j", "throwable", dummyNamespace, logEvent.Exception.ToString()); } } AppendScopeContextNestedStates(xtw, logEvent); if (includeNLogCallsite) { AppendCallSite(logEvent, xtw); } xtw.WriteStartElement("log4j", "properties", dummyNamespace); AppendScopeContextProperties("log4j", dummyNamespaceRemover, xtw); if (IncludeEventProperties) { AppendProperties("log4j", dummyNamespaceRemover, xtw, logEvent); } AppendParameters(logEvent, xtw); xtw.WriteStartElement("log4j", "data", dummyNamespace); xtw.WriteAttributeString("name", "log4japp"); xtw.WriteAttributeSafeString("value", AppInfo?.Render(logEvent) ?? string.Empty); xtw.WriteEndElement(); xtw.WriteStartElement("log4j", "data", dummyNamespace); xtw.WriteAttributeString("name", "log4jmachinename"); xtw.WriteAttributeSafeString("value", _machineName); xtw.WriteEndElement(); xtw.WriteEndElement(); // properties xtw.WriteEndElement(); // event xtw.Flush(); // get rid of 'nlog' and 'log4j' namespace declarations sb.Replace(dummyNamespaceRemover, string.Empty); if (includeNLogCallsite && IncludeNLogData) { sb.Replace(dummyNLogNamespaceRemover, string.Empty); } sb.CopyTo(builder); // StringBuilder.Replace is not good when reusing the StringBuilder } } private void AppendScopeContextProperties(string prefix, string propertiesNamespace, XmlWriter xtw) { if (IncludeScopeProperties) { using (var scopeEnumerator = ScopeContext.GetAllPropertiesEnumerator()) { while (scopeEnumerator.MoveNext()) { var scopeProperty = scopeEnumerator.Current; if (string.IsNullOrEmpty(scopeProperty.Key)) continue; string propertyValue = XmlHelper.XmlConvertToStringSafe(scopeProperty.Value); if (propertyValue is null) continue; xtw.WriteStartElement(prefix, "data", propertiesNamespace); xtw.WriteAttributeSafeString("name", scopeProperty.Key); xtw.WriteAttributeString("value", propertyValue); xtw.WriteEndElement(); } } } } private void AppendScopeContextNestedStates(XmlWriter xtw, LogEventInfo logEvent) { if (IncludeScopeNested) { var nestedStates = _scopeNestedLayoutRenderer.Render(logEvent); //NDLC and NDC should be in the same element xtw.WriteElementSafeString("log4j", "NDC", dummyNamespace, nestedStates); } } private void AppendParameters(LogEventInfo logEvent, XmlWriter xtw) { for (int i = 0; i < Parameters?.Count; ++i) { var parameter = Parameters[i]; if (string.IsNullOrEmpty(parameter?.Name)) continue; var parameterValue = parameter.Layout?.Render(logEvent) ?? string.Empty; if (!parameter.IncludeEmptyValue && string.IsNullOrEmpty(parameterValue)) continue; xtw.WriteStartElement("log4j", "data", dummyNamespace); xtw.WriteAttributeSafeString("name", parameter.Name); xtw.WriteAttributeSafeString("value", parameterValue); xtw.WriteEndElement(); } } private void AppendCallSite(LogEventInfo logEvent, XmlWriter xtw) { MethodBase methodBase = logEvent.CallSiteInformation.GetCallerStackFrameMethod(0); string callerClassName = logEvent.CallSiteInformation.GetCallerClassName(methodBase, true, true, true); string callerMethodName = logEvent.CallSiteInformation.GetCallerMethodName(methodBase, true, true, true); xtw.WriteStartElement("log4j", "locationInfo", dummyNamespace); if (!string.IsNullOrEmpty(callerClassName)) { xtw.WriteAttributeSafeString("class", callerClassName); } xtw.WriteAttributeSafeString("method", callerMethodName); if (IncludeSourceInfo) { xtw.WriteAttributeSafeString("file", logEvent.CallSiteInformation.GetCallerFilePath(0)); xtw.WriteAttributeString("line", logEvent.CallSiteInformation.GetCallerLineNumber(0).ToString(CultureInfo.InvariantCulture)); } xtw.WriteEndElement(); if (IncludeNLogData) { xtw.WriteElementSafeString("nlog", "eventSequenceNumber", dummyNLogNamespace, logEvent.SequenceID.ToString(CultureInfo.InvariantCulture)); xtw.WriteStartElement("nlog", "locationInfo", dummyNLogNamespace); var type = methodBase?.DeclaringType; if (type != null) { xtw.WriteAttributeSafeString("assembly", type.GetAssembly().FullName); } xtw.WriteEndElement(); xtw.WriteStartElement("nlog", "properties", dummyNLogNamespace); AppendProperties("nlog", dummyNLogNamespace, xtw, logEvent); xtw.WriteEndElement(); } } private void AppendProperties(string prefix, string propertiesNamespace, XmlWriter xtw, LogEventInfo logEvent) { if (logEvent.HasProperties) { foreach (var contextProperty in logEvent.Properties) { string propertyKey = XmlHelper.XmlConvertToStringSafe(contextProperty.Key); if (string.IsNullOrEmpty(propertyKey)) continue; string propertyValue = XmlHelper.XmlConvertToStringSafe(contextProperty.Value); if (propertyValue is null) continue; xtw.WriteStartElement(prefix, "data", propertiesNamespace); xtw.WriteAttributeString("name", propertyKey); xtw.WriteAttributeString("value", propertyValue); xtw.WriteEndElement(); } } } } }
using UnityEngine; using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Xml; using System.Xml.Serialization; using System.Runtime.Serialization.Formatters.Binary; using System.Runtime.Serialization; public static class VHFile { public delegate void OnExceptionThrown(Exception e); public static void CopyDirectory(string sourceDirectory, string destinationDirectory, bool copySubdirectories, bool overwrite, string directoryExcludeString = "") { // usage: CopyDirectory("Assets/Scripts, "Assets/ScriptsNew", true, true, ".svn"); // taken from "How to: Copy Directories" http://msdn.microsoft.com/en-us/library/bb762914.aspx // modified to include overwrite flag DirectoryInfo dir = new DirectoryInfo(sourceDirectory); DirectoryInfo[] dirs3 = VHFile.DirectoryInfoWrapper.GetDirectories(dir); // If the source directory does not exist, throw an exception. if (!dir.Exists) { throw new DirectoryNotFoundException("Source directory does not exist or could not be found: " + sourceDirectory); } if (!string.IsNullOrEmpty(directoryExcludeString)) { if (dir.FullName.Contains(directoryExcludeString)) { return; } } // If the destination directory does not exist, create it. if (!Directory.Exists(destinationDirectory)) { Directory.CreateDirectory(destinationDirectory); } // Get the file contents of the directory to copy. FileInfo[] files = VHFile.DirectoryInfoWrapper.GetFiles(dir); foreach (FileInfo file in files) { // Create the path to the new copy of the file. string temppath = Path.Combine(destinationDirectory, file.Name); // Copy the file. If destination exists, clear any read-only flag that might be present if (File.Exists(temppath)) File.SetAttributes(temppath, FileAttributes.Normal); VHFile.FileInfoWrapper.CopyTo(file, temppath, overwrite); } // If copySubDirs is true, copy the subdirectories. if (copySubdirectories) { foreach (DirectoryInfo subdir in dirs3) { // Create the subdirectory. string temppath = Path.Combine(destinationDirectory, subdir.Name); // Copy the subdirectories. CopyDirectory(subdir.FullName, temppath, copySubdirectories, overwrite, directoryExcludeString); } } } public static void CopyFiles(string[] sourceFiles, string destinationDirectory) { for (int i = 0; i < sourceFiles.Length; i++) { if (File.Exists(sourceFiles[i])) { File.Copy(sourceFiles[i], destinationDirectory + Path.GetFileName(sourceFiles[i]), true); } } } public static void CopyFiles(string sourceDirectory, string destinationDirectory, string searchPattern, SearchOption searchOption) { // usage: CopyFiles("Assets/Scripts", "Assets/NewScripts", "*.cs", SearchOption.AllDirectories); string[] files = Directory.GetFiles(sourceDirectory, searchPattern, searchOption); CopyFiles(files, destinationDirectory); } public static void MoveFiles(string sourceDirectory, string destinationDirectory, string searchPattern, SearchOption searchOption) { string[] files = Directory.GetFiles(sourceDirectory, searchPattern, searchOption); for (int i = 0; i < files.Length; i++) { string destinationPath = destinationDirectory + Path.GetFileName(files[i]); if (File.Exists(destinationPath)) { File.Delete(destinationPath); } File.Move(files[i], destinationPath); } } public static string [] GetStreamingAssetsFiles(string path, string extension) { // this function works on all platforms, special cased for Android. See StreamingAssetsExtract class. // path is relative to StreamingAssets (see LoadStreamingAssets()) // extension includes the dot, eg ".wav" // wildcards not accepted in this function if (Application.platform == RuntimePlatform.Android) { return StreamingAssetsExtract.GetFiles(path, extension); } else { string [] files = VHFile.DirectoryWrapper.GetFiles(VHFile.GetStreamingAssetsPath() + path, "*" + extension, SearchOption.AllDirectories); List<string> fileList = new List<string>(files); for (int i = 0; i < fileList.Count; i++) { fileList[i] = fileList[i].Replace(VHFile.GetStreamingAssetsPath(), ""); } return fileList.ToArray(); } } public static string GetStreamingAssetsPath() { string path; if (Application.platform == RuntimePlatform.IPhonePlayer || Application.platform == RuntimePlatform.WindowsEditor || Application.platform == RuntimePlatform.OSXEditor || Application.platform == RuntimePlatform.WindowsPlayer || Application.platform == RuntimePlatform.OSXPlayer) { path = Application.streamingAssetsPath + "/"; } else if (Application.platform == RuntimePlatform.Android) { path = ""; Debug.Log("GetStreamingAssetsPath() - This function is invalid on Android. Cannot access streaming assets path directly. Need to use WWW url format (see GetStreamingAssetsURL())"); } else { path = ""; Debug.Log("GetStreamingAssetsPath() error - Platform not supported"); } return path; } public static string GetStreamingAssetsURL() { string path; if (Application.platform == RuntimePlatform.WindowsEditor || Application.platform == RuntimePlatform.OSXEditor || Application.platform == RuntimePlatform.WindowsPlayer || Application.platform == RuntimePlatform.OSXPlayer) { path = "file://" + Application.streamingAssetsPath + "/"; } else if (Application.platform == RuntimePlatform.IPhonePlayer) { path = "file://" + Application.streamingAssetsPath + "/"; } else if (Application.platform == RuntimePlatform.Android) { path = "jar:file://" + Application.dataPath + "!/assets/"; } else { path = ""; Debug.Log("GetStreamingAssetsURL() error - Platform not supported"); } return path; } public static string GetExternalAssetsPath() { // this is the same for all platforms except for Android, where persistantDataPath is used string path; if (Application.platform == RuntimePlatform.IPhonePlayer || Application.platform == RuntimePlatform.WindowsEditor || Application.platform == RuntimePlatform.OSXEditor || Application.platform == RuntimePlatform.WindowsPlayer || Application.platform == RuntimePlatform.OSXPlayer) { path = Application.streamingAssetsPath + "/"; } else if (Application.platform == RuntimePlatform.Android) { path = Application.persistentDataPath + "/"; } else { path = ""; Debug.Log("GetExternalAssetsPath() error - Platform not supported"); } return path; } public static WWW LoadStreamingAssets(string filename) { // This function will load data from the StreamingAssets folder in a cross-platform manner. // filename is relative to the StreamingAssets folder. // ie: \Assets\StreamingAssets\data\file.dat // filename should be: data\file.dat // data can be accessed through the WWW accessors: .bytes, .texture, .audioClip, etc. // this function doesn't return until the data has been completely loaded. // see LoadStreamingAssetsAsync() for an asynchronous version. if (Application.platform == RuntimePlatform.IPhonePlayer) { Debug.LogWarning("LoadStreamingAssets() - doesn't work on iOS since it needs to wait a frame before it will start loading, and will get stuck in an endless loop. Use LoadStreamingAssetsBytes() instead. (See unity support #3167)"); return null; } string fullPath = GetStreamingAssetsURL() + filename; //Debug.Log("LoadStreamingAssets() - fullPath = " + fullPath); var www = new WWW(fullPath); while (!www.isDone) { } if (www.error != null) { Debug.Log("LoadStreamingAssets() error - " + www.error); return null; } //Debug.Log("length: " + www.bytes.Length); return www; } public static WWW LoadStreamingAssetsAsync(string filename) { // This function will load data from the StreamingAssets folder in a cross-platform manner. // filename is relative to the StreamingAssets folder. // ie: \Assets\StreamingAssets\data\file.dat // filename should be: data\file.dat // data can be accessed through the WWW accessors: .bytes, .texture, .audioClip, etc. // returned WWW needs to wait until it is finished loading, via isDone or yield // do not while loop on isDone, because on certain platforms, this will cause an endless loop, see unity support #3167 string fullPath = GetStreamingAssetsURL() + filename; Debug.Log("fullPath: " + fullPath); //Debug.Log("LoadStreamingAssetsAsync() - fullPath = " + fullPath); var www = new WWW(fullPath); return www; } public static byte [] LoadStreamingAssetsBytes(string filename) { // This function will load data from the StreamingAssets folder in a cross-platform manner. // filename is relative to the StreamingAssets folder. // ie: \Assets\StreamingAssets\data\file.dat // filename should be: data\file.dat // this function doesn't return until the data has been completely loaded. //Debug.Log("LoadStreamingAssetsBytes() - " + filename); if (Application.platform == RuntimePlatform.Android) { // Android needs to use the WWW class return LoadStreamingAssets(filename).bytes; } else { string fullPath = GetStreamingAssetsPath() + filename; byte [] bytes = VHFile.FileWrapper.ReadAllBytes(fullPath); return bytes; } } public static string RemovePathUpTo(string upToHere, string path) { int index = path.LastIndexOf(upToHere); if (index > -1) { return path.Substring(index); } return path; } public static void ClearAttributesRecursive(string currentDir) { // recursively clear the attributes on all files under the given folder if (Directory.Exists(currentDir)) { string [] subDirs = Directory.GetDirectories(currentDir); foreach (string dir in subDirs) { ClearAttributesRecursive(dir); } string [] files = Directory.GetFiles(currentDir); foreach (string file in files) { if (File.Exists(file)) { File.SetAttributes(file, FileAttributes.Normal); } } } } static public void WriteXML<T>(string filename, T data) { WriteXML<T>(filename, data, null); } static public void WriteXML<T>(string filename, T data, OnExceptionThrown cb) { XmlSerializer serializer = null; TextWriter writer = null; try { serializer = new XmlSerializer(typeof(T)); writer = new StreamWriter(filename); serializer.Serialize(writer, data); writer.WriteLine(); } catch (Exception e) { Debug.LogError("Failed to write xml file " + filename + " Message: " + e.Message + ". Inner Exception: " + e.InnerException); if (cb != null) { cb(e); } } finally { if (writer != null) { writer.Close(); } } } static public T ReadXML<T>(string filename) { T retval = default(T); XmlSerializer serializer = null; FileStream fs = null; try { serializer = new XmlSerializer(typeof(T)); fs = new FileStream(filename, FileMode.Open, FileAccess.Read); retval = (T)serializer.Deserialize(fs); } catch (Exception e) { Debug.LogError("Failed to read xml file " + filename + " Message: " + e.Message + ". Inner Exception: " + e.InnerException); } finally { if (fs != null) { fs.Close(); } } return retval; } static public string FindPathToFolder(string folderName) { string folderLocation = string.Empty; string [] dirs = VHFile.DirectoryWrapper.GetDirectories(Application.dataPath, folderName, SearchOption.AllDirectories); for (int i = 0; i < dirs.Length; i++) { if (dirs[i].Contains(folderName)) { folderLocation = dirs[i]; folderLocation = folderLocation.Replace('\\', '/'); int index = folderLocation.IndexOf("/Assets"); if (index != -1) { folderLocation = folderLocation.Remove(0, index + 1); } folderLocation += '/'; break; } } return folderLocation; } public static class DirectoryWrapper { public static void Delete(string path, bool recursive) { #if UNITY_WEBGL Debug.LogError("Directory.Delete() isn't defined on this platform"); #else Directory.Delete(path, recursive); #endif } public static string[] GetDirectories(string path, string searchPattern, SearchOption searchOption) { #if UNITY_WEBGL Debug.LogError("Directory.GetDirectories() isn't defined on this platform"); return null; #else return Directory.GetDirectories(path, searchPattern, searchOption); #endif } public static string [] GetFiles(string path, string searchPattern, SearchOption searchOption) { #if UNITY_WEBGL Debug.LogError("Directory.GetFiles() isn't defined on this platform"); return null; #else return Directory.GetFiles(path, searchPattern, searchOption); #endif } } public static class DirectoryInfoWrapper { public static DirectoryInfo [] GetDirectories(DirectoryInfo source) { #if UNITY_WEBGL Debug.LogError("DirectoryInfo.GetDirectories() isn't defined on this platform"); return null; #else return source.GetDirectories(); #endif } public static FileInfo[] GetFiles(DirectoryInfo source) { #if UNITY_WEBGL Debug.LogError("DirectoryInfo.GetFiles() isn't defined on this platform"); return null; #else return source.GetFiles(); #endif } } public static class FileWrapper { public static void AppendAllText(string path, string contents) { #if UNITY_WEBGL Debug.LogError("File.AppendAllText() isn't defined on this platform"); #else File.AppendAllText(path, contents); #endif } public static void Move(string sourceFileName, string destFileName) { #if UNITY_WEBGL Debug.LogError("File.Move() isn't defined on this platform"); #else File.Move(sourceFileName, destFileName); #endif } public static FileStream Open(string path, FileMode mode, FileAccess access) { #if UNITY_WEBGL Debug.LogError("File.Open() isn't defined on this platform"); return null; #else return File.Open(path, mode, access); #endif } public static byte [] ReadAllBytes(string path) { #if UNITY_WEBGL Debug.LogError("File.FileReadAllBytes() isn't defined on this platform"); return null; #else return File.ReadAllBytes(path); #endif } public static string ReadAllText(string path) { #if UNITY_WEBGL Debug.LogError("File.ReadAllText() isn't defined on this platform"); return null; #else return File.ReadAllText(path); #endif } } public static class FileInfoWrapper { public static FileInfo CopyTo(FileInfo source, string destFileName, bool overwrite) { #if UNITY_WEBGL Debug.LogError("FileInfo.CopyTo() isn't defined on this platform"); return null; #else return source.CopyTo(destFileName, overwrite); #endif } } }
/* * 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.Drawing; using System.Drawing.Imaging; using System.Reflection; using System.Xml.Serialization; using log4net; using OpenMetaverse; namespace OpenSim.Framework { public enum ProfileShape : byte { Circle = 0, Square = 1, IsometricTriangle = 2, EquilateralTriangle = 3, RightTriangle = 4, HalfCircle = 5 } public enum HollowShape : byte { Same = 0, Circle = 16, Square = 32, Triangle = 48 } public enum PCodeEnum : byte { Primitive = 9, Avatar = 47, Grass = 95, NewTree = 111, ParticleSystem = 143, Tree = 255 } public enum Extrusion : byte { Straight = 16, Curve1 = 32, Curve2 = 48, Flexible = 128 } [Serializable] public class PrimitiveBaseShape { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private static readonly byte[] DEFAULT_TEXTURE = new Primitive.TextureEntry(new UUID("89556747-24cb-43ed-920b-47caed15465f")).GetBytes(); private byte[] m_textureEntry; private ushort _pathBegin; private byte _pathCurve; private ushort _pathEnd; private sbyte _pathRadiusOffset; private byte _pathRevolutions; private byte _pathScaleX; private byte _pathScaleY; private byte _pathShearX; private byte _pathShearY; private sbyte _pathSkew; private sbyte _pathTaperX; private sbyte _pathTaperY; private sbyte _pathTwist; private sbyte _pathTwistBegin; private byte _pCode; private ushort _profileBegin; private ushort _profileEnd; private ushort _profileHollow; private Vector3 _scale; private byte _state; private ProfileShape _profileShape; private HollowShape _hollowShape; // Sculpted [XmlIgnore] private UUID _sculptTexture; [XmlIgnore] private byte _sculptType; [XmlIgnore] private byte[] _sculptData = Utils.EmptyBytes; // Flexi [XmlIgnore] private int _flexiSoftness; [XmlIgnore] private float _flexiTension; [XmlIgnore] private float _flexiDrag; [XmlIgnore] private float _flexiGravity; [XmlIgnore] private float _flexiWind; [XmlIgnore] private float _flexiForceX; [XmlIgnore] private float _flexiForceY; [XmlIgnore] private float _flexiForceZ; //Bright n sparkly [XmlIgnore] private float _lightColorR; [XmlIgnore] private float _lightColorG; [XmlIgnore] private float _lightColorB; [XmlIgnore] private float _lightColorA = 1.0f; [XmlIgnore] private float _lightRadius; [XmlIgnore] private float _lightCutoff; [XmlIgnore] private float _lightFalloff; [XmlIgnore] private float _lightIntensity = 1.0f; [XmlIgnore] private bool _flexiEntry; [XmlIgnore] private bool _lightEntry; [XmlIgnore] private bool _sculptEntry; public byte ProfileCurve { get { return (byte)((byte)HollowShape | (byte)ProfileShape); } set { // Handle hollow shape component byte hollowShapeByte = (byte)(value & 0xf0); if (!Enum.IsDefined(typeof(HollowShape), hollowShapeByte)) { m_log.WarnFormat( "[SHAPE]: Attempt to set a ProfileCurve with a hollow shape value of {0}, which isn't a valid enum. Replacing with default shape.", hollowShapeByte); this._hollowShape = HollowShape.Same; } else { this._hollowShape = (HollowShape)hollowShapeByte; } // Handle profile shape component byte profileShapeByte = (byte)(value & 0xf); if (!Enum.IsDefined(typeof(ProfileShape), profileShapeByte)) { m_log.WarnFormat( "[SHAPE]: Attempt to set a ProfileCurve with a profile shape value of {0}, which isn't a valid enum. Replacing with square.", profileShapeByte); this._profileShape = ProfileShape.Square; } else { this._profileShape = (ProfileShape)profileShapeByte; } } } public PrimitiveBaseShape() { PCode = (byte) PCodeEnum.Primitive; ExtraParams = new byte[1]; m_textureEntry = DEFAULT_TEXTURE; } public PrimitiveBaseShape(bool noShape) { if (noShape) return; PCode = (byte)PCodeEnum.Primitive; ExtraParams = new byte[1]; m_textureEntry = DEFAULT_TEXTURE; } public PrimitiveBaseShape(Primitive prim) { PCode = (byte)prim.PrimData.PCode; ExtraParams = new byte[1]; State = prim.PrimData.State; PathBegin = Primitive.PackBeginCut(prim.PrimData.PathBegin); PathEnd = Primitive.PackEndCut(prim.PrimData.PathEnd); PathScaleX = Primitive.PackPathScale(prim.PrimData.PathScaleX); PathScaleY = Primitive.PackPathScale(prim.PrimData.PathScaleY); PathShearX = (byte)Primitive.PackPathShear(prim.PrimData.PathShearX); PathShearY = (byte)Primitive.PackPathShear(prim.PrimData.PathShearY); PathSkew = Primitive.PackPathTwist(prim.PrimData.PathSkew); ProfileBegin = Primitive.PackBeginCut(prim.PrimData.ProfileBegin); ProfileEnd = Primitive.PackEndCut(prim.PrimData.ProfileEnd); Scale = prim.Scale; PathCurve = (byte)prim.PrimData.PathCurve; ProfileCurve = (byte)prim.PrimData.ProfileCurve; ProfileHollow = Primitive.PackProfileHollow(prim.PrimData.ProfileHollow); PathRadiusOffset = Primitive.PackPathTwist(prim.PrimData.PathRadiusOffset); PathRevolutions = Primitive.PackPathRevolutions(prim.PrimData.PathRevolutions); PathTaperX = Primitive.PackPathTaper(prim.PrimData.PathTaperX); PathTaperY = Primitive.PackPathTaper(prim.PrimData.PathTaperY); PathTwist = Primitive.PackPathTwist(prim.PrimData.PathTwist); PathTwistBegin = Primitive.PackPathTwist(prim.PrimData.PathTwistBegin); m_textureEntry = prim.Textures.GetBytes(); SculptEntry = (prim.Sculpt.Type != OpenMetaverse.SculptType.None); SculptData = prim.Sculpt.GetBytes(); SculptTexture = prim.Sculpt.SculptTexture; SculptType = (byte)prim.Sculpt.Type; } [XmlIgnore] public Primitive.TextureEntry Textures { get { //m_log.DebugFormat("[PRIMITIVE BASE SHAPE]: get m_textureEntry length {0}", m_textureEntry.Length); return new Primitive.TextureEntry(m_textureEntry, 0, m_textureEntry.Length); } set { m_textureEntry = value.GetBytes(); } } public byte[] TextureEntry { get { return m_textureEntry; } set { if (value == null) m_textureEntry = new byte[1]; else m_textureEntry = value; } } public static PrimitiveBaseShape Default { get { PrimitiveBaseShape boxShape = CreateBox(); boxShape.SetScale(0.5f); return boxShape; } } public static PrimitiveBaseShape Create() { PrimitiveBaseShape shape = new PrimitiveBaseShape(); return shape; } public static PrimitiveBaseShape CreateBox() { PrimitiveBaseShape shape = Create(); shape._pathCurve = (byte) Extrusion.Straight; shape._profileShape = ProfileShape.Square; shape._pathScaleX = 100; shape._pathScaleY = 100; return shape; } public static PrimitiveBaseShape CreateSphere() { PrimitiveBaseShape shape = Create(); shape._pathCurve = (byte) Extrusion.Curve1; shape._profileShape = ProfileShape.HalfCircle; shape._pathScaleX = 100; shape._pathScaleY = 100; return shape; } public static PrimitiveBaseShape CreateCylinder() { PrimitiveBaseShape shape = Create(); shape._pathCurve = (byte) Extrusion.Curve1; shape._profileShape = ProfileShape.Square; shape._pathScaleX = 100; shape._pathScaleY = 100; return shape; } public void SetScale(float side) { _scale = new Vector3(side, side, side); } public void SetHeigth(float heigth) { _scale.Z = heigth; } public void SetRadius(float radius) { _scale.X = _scale.Y = radius * 2f; } // TODO: void returns need to change of course public virtual void GetMesh() { } public PrimitiveBaseShape Copy() { return (PrimitiveBaseShape) MemberwiseClone(); } public static PrimitiveBaseShape CreateCylinder(float radius, float heigth) { PrimitiveBaseShape shape = CreateCylinder(); shape.SetHeigth(heigth); shape.SetRadius(radius); return shape; } public void SetPathRange(Vector3 pathRange) { _pathBegin = Primitive.PackBeginCut(pathRange.X); _pathEnd = Primitive.PackEndCut(pathRange.Y); } public void SetPathRange(float begin, float end) { _pathBegin = Primitive.PackBeginCut(begin); _pathEnd = Primitive.PackEndCut(end); } public void SetSculptData(byte sculptType, UUID SculptTextureUUID) { _sculptType = sculptType; _sculptTexture = SculptTextureUUID; } public void SetProfileRange(Vector3 profileRange) { _profileBegin = Primitive.PackBeginCut(profileRange.X); _profileEnd = Primitive.PackEndCut(profileRange.Y); } public void SetProfileRange(float begin, float end) { _profileBegin = Primitive.PackBeginCut(begin); _profileEnd = Primitive.PackEndCut(end); } public byte[] ExtraParams { get { return ExtraParamsToBytes(); } set { ReadInExtraParamsBytes(value); } } public ushort PathBegin { get { return _pathBegin; } set { _pathBegin = value; } } public byte PathCurve { get { return _pathCurve; } set { _pathCurve = value; } } public ushort PathEnd { get { return _pathEnd; } set { _pathEnd = value; } } public sbyte PathRadiusOffset { get { return _pathRadiusOffset; } set { _pathRadiusOffset = value; } } public byte PathRevolutions { get { return _pathRevolutions; } set { _pathRevolutions = value; } } public byte PathScaleX { get { return _pathScaleX; } set { _pathScaleX = value; } } public byte PathScaleY { get { return _pathScaleY; } set { _pathScaleY = value; } } public byte PathShearX { get { return _pathShearX; } set { _pathShearX = value; } } public byte PathShearY { get { return _pathShearY; } set { _pathShearY = value; } } public sbyte PathSkew { get { return _pathSkew; } set { _pathSkew = value; } } public sbyte PathTaperX { get { return _pathTaperX; } set { _pathTaperX = value; } } public sbyte PathTaperY { get { return _pathTaperY; } set { _pathTaperY = value; } } public sbyte PathTwist { get { return _pathTwist; } set { _pathTwist = value; } } public sbyte PathTwistBegin { get { return _pathTwistBegin; } set { _pathTwistBegin = value; } } public byte PCode { get { return _pCode; } set { _pCode = value; } } public ushort ProfileBegin { get { return _profileBegin; } set { _profileBegin = value; } } public ushort ProfileEnd { get { return _profileEnd; } set { _profileEnd = value; } } public ushort ProfileHollow { get { return _profileHollow; } set { _profileHollow = value; } } public Vector3 Scale { get { return _scale; } set { _scale = value; } } public byte State { get { return _state; } set { _state = value; } } public ProfileShape ProfileShape { get { return _profileShape; } set { _profileShape = value; } } public HollowShape HollowShape { get { return _hollowShape; } set { _hollowShape = value; } } public UUID SculptTexture { get { return _sculptTexture; } set { _sculptTexture = value; } } public byte SculptType { get { return _sculptType; } set { _sculptType = value; } } public byte[] SculptData { get { return _sculptData; } set { _sculptData = value; } } public int FlexiSoftness { get { return _flexiSoftness; } set { _flexiSoftness = value; } } public float FlexiTension { get { return _flexiTension; } set { _flexiTension = value; } } public float FlexiDrag { get { return _flexiDrag; } set { _flexiDrag = value; } } public float FlexiGravity { get { return _flexiGravity; } set { _flexiGravity = value; } } public float FlexiWind { get { return _flexiWind; } set { _flexiWind = value; } } public float FlexiForceX { get { return _flexiForceX; } set { _flexiForceX = value; } } public float FlexiForceY { get { return _flexiForceY; } set { _flexiForceY = value; } } public float FlexiForceZ { get { return _flexiForceZ; } set { _flexiForceZ = value; } } public float LightColorR { get { return _lightColorR; } set { _lightColorR = value; } } public float LightColorG { get { return _lightColorG; } set { _lightColorG = value; } } public float LightColorB { get { return _lightColorB; } set { _lightColorB = value; } } public float LightColorA { get { return _lightColorA; } set { _lightColorA = value; } } public float LightRadius { get { return _lightRadius; } set { _lightRadius = value; } } public float LightCutoff { get { return _lightCutoff; } set { _lightCutoff = value; } } public float LightFalloff { get { return _lightFalloff; } set { _lightFalloff = value; } } public float LightIntensity { get { return _lightIntensity; } set { _lightIntensity = value; } } public bool FlexiEntry { get { return _flexiEntry; } set { _flexiEntry = value; } } public bool LightEntry { get { return _lightEntry; } set { _lightEntry = value; } } public bool SculptEntry { get { return _sculptEntry; } set { _sculptEntry = value; } } public byte[] ExtraParamsToBytes() { ushort FlexiEP = 0x10; ushort LightEP = 0x20; ushort SculptEP = 0x30; int i = 0; uint TotalBytesLength = 1; // ExtraParamsNum uint ExtraParamsNum = 0; if (_flexiEntry) { ExtraParamsNum++; TotalBytesLength += 16;// data TotalBytesLength += 2 + 4; // type } if (_lightEntry) { ExtraParamsNum++; TotalBytesLength += 16;// data TotalBytesLength += 2 + 4; // type } if (_sculptEntry) { ExtraParamsNum++; TotalBytesLength += 17;// data TotalBytesLength += 2 + 4; // type } byte[] returnbytes = new byte[TotalBytesLength]; // uint paramlength = ExtraParamsNum; // Stick in the number of parameters returnbytes[i++] = (byte)ExtraParamsNum; if (_flexiEntry) { byte[] FlexiData = GetFlexiBytes(); returnbytes[i++] = (byte)(FlexiEP % 256); returnbytes[i++] = (byte)((FlexiEP >> 8) % 256); returnbytes[i++] = (byte)(FlexiData.Length % 256); returnbytes[i++] = (byte)((FlexiData.Length >> 8) % 256); returnbytes[i++] = (byte)((FlexiData.Length >> 16) % 256); returnbytes[i++] = (byte)((FlexiData.Length >> 24) % 256); Array.Copy(FlexiData, 0, returnbytes, i, FlexiData.Length); i += FlexiData.Length; } if (_lightEntry) { byte[] LightData = GetLightBytes(); returnbytes[i++] = (byte)(LightEP % 256); returnbytes[i++] = (byte)((LightEP >> 8) % 256); returnbytes[i++] = (byte)(LightData.Length % 256); returnbytes[i++] = (byte)((LightData.Length >> 8) % 256); returnbytes[i++] = (byte)((LightData.Length >> 16) % 256); returnbytes[i++] = (byte)((LightData.Length >> 24) % 256); Array.Copy(LightData, 0, returnbytes, i, LightData.Length); i += LightData.Length; } if (_sculptEntry) { byte[] SculptData = GetSculptBytes(); returnbytes[i++] = (byte)(SculptEP % 256); returnbytes[i++] = (byte)((SculptEP >> 8) % 256); returnbytes[i++] = (byte)(SculptData.Length % 256); returnbytes[i++] = (byte)((SculptData.Length >> 8) % 256); returnbytes[i++] = (byte)((SculptData.Length >> 16) % 256); returnbytes[i++] = (byte)((SculptData.Length >> 24) % 256); Array.Copy(SculptData, 0, returnbytes, i, SculptData.Length); i += SculptData.Length; } if (!_flexiEntry && !_lightEntry && !_sculptEntry) { byte[] returnbyte = new byte[1]; returnbyte[0] = 0; return returnbyte; } return returnbytes; //m_log.Info("[EXTRAPARAMS]: Length = " + m_shape.ExtraParams.Length.ToString()); } public void ReadInUpdateExtraParam(ushort type, bool inUse, byte[] data) { const ushort FlexiEP = 0x10; const ushort LightEP = 0x20; const ushort SculptEP = 0x30; switch (type) { case FlexiEP: if (!inUse) { _flexiEntry = false; return; } ReadFlexiData(data, 0); break; case LightEP: if (!inUse) { _lightEntry = false; return; } ReadLightData(data, 0); break; case SculptEP: if (!inUse) { _sculptEntry = false; return; } ReadSculptData(data, 0); break; } } public void ReadInExtraParamsBytes(byte[] data) { if (data == null || data.Length == 1) return; const ushort FlexiEP = 0x10; const ushort LightEP = 0x20; const ushort SculptEP = 0x30; bool lGotFlexi = false; bool lGotLight = false; bool lGotSculpt = false; int i = 0; byte extraParamCount = 0; if (data.Length > 0) { extraParamCount = data[i++]; } for (int k = 0; k < extraParamCount; k++) { ushort epType = Utils.BytesToUInt16(data, i); i += 2; // uint paramLength = Helpers.BytesToUIntBig(data, i); i += 4; switch (epType) { case FlexiEP: ReadFlexiData(data, i); i += 16; lGotFlexi = true; break; case LightEP: ReadLightData(data, i); i += 16; lGotLight = true; break; case SculptEP: ReadSculptData(data, i); i += 17; lGotSculpt = true; break; } } if (!lGotFlexi) _flexiEntry = false; if (!lGotLight) _lightEntry = false; if (!lGotSculpt) _sculptEntry = false; } public void ReadSculptData(byte[] data, int pos) { byte[] SculptTextureUUID = new byte[16]; UUID SculptUUID = UUID.Zero; byte SculptTypel = data[16+pos]; if (data.Length+pos >= 17) { _sculptEntry = true; SculptTextureUUID = new byte[16]; SculptTypel = data[16 + pos]; Array.Copy(data, pos, SculptTextureUUID,0, 16); SculptUUID = new UUID(SculptTextureUUID, 0); } else { _sculptEntry = false; SculptUUID = UUID.Zero; SculptTypel = 0x00; } if (_sculptEntry) { if (_sculptType != (byte)1 && _sculptType != (byte)2 && _sculptType != (byte)3 && _sculptType != (byte)4) _sculptType = 4; } _sculptTexture = SculptUUID; _sculptType = SculptTypel; //m_log.Info("[SCULPT]:" + SculptUUID.ToString()); } public byte[] GetSculptBytes() { byte[] data = new byte[17]; _sculptTexture.GetBytes().CopyTo(data, 0); data[16] = (byte)_sculptType; return data; } public void ReadFlexiData(byte[] data, int pos) { if (data.Length-pos >= 16) { _flexiEntry = true; _flexiSoftness = ((data[pos] & 0x80) >> 6) | ((data[pos + 1] & 0x80) >> 7); _flexiTension = (float)(data[pos++] & 0x7F) / 10.0f; _flexiDrag = (float)(data[pos++] & 0x7F) / 10.0f; _flexiGravity = (float)(data[pos++] / 10.0f) - 10.0f; _flexiWind = (float)data[pos++] / 10.0f; Vector3 lForce = new Vector3(data, pos); _flexiForceX = lForce.X; _flexiForceY = lForce.Y; _flexiForceZ = lForce.Z; } else { _flexiEntry = false; _flexiSoftness = 0; _flexiTension = 0.0f; _flexiDrag = 0.0f; _flexiGravity = 0.0f; _flexiWind = 0.0f; _flexiForceX = 0f; _flexiForceY = 0f; _flexiForceZ = 0f; } } public byte[] GetFlexiBytes() { byte[] data = new byte[16]; int i = 0; // Softness is packed in the upper bits of tension and drag data[i] = (byte)((_flexiSoftness & 2) << 6); data[i + 1] = (byte)((_flexiSoftness & 1) << 7); data[i++] |= (byte)((byte)(_flexiTension * 10.01f) & 0x7F); data[i++] |= (byte)((byte)(_flexiDrag * 10.01f) & 0x7F); data[i++] = (byte)((_flexiGravity + 10.0f) * 10.01f); data[i++] = (byte)(_flexiWind * 10.01f); Vector3 lForce = new Vector3(_flexiForceX, _flexiForceY, _flexiForceZ); lForce.GetBytes().CopyTo(data, i); return data; } public void ReadLightData(byte[] data, int pos) { if (data.Length - pos >= 16) { _lightEntry = true; Color4 lColor = new Color4(data, pos, false); _lightIntensity = lColor.A; _lightColorA = 1f; _lightColorR = lColor.R; _lightColorG = lColor.G; _lightColorB = lColor.B; _lightRadius = Utils.BytesToFloat(data, pos + 4); _lightCutoff = Utils.BytesToFloat(data, pos + 8); _lightFalloff = Utils.BytesToFloat(data, pos + 12); } else { _lightEntry = false; _lightColorA = 1f; _lightColorR = 0f; _lightColorG = 0f; _lightColorB = 0f; _lightRadius = 0f; _lightCutoff = 0f; _lightFalloff = 0f; _lightIntensity = 0f; } } public byte[] GetLightBytes() { byte[] data = new byte[16]; // Alpha channel in color is intensity Color4 tmpColor = new Color4(_lightColorR,_lightColorG,_lightColorB,_lightIntensity); tmpColor.GetBytes().CopyTo(data, 0); Utils.FloatToBytes(_lightRadius).CopyTo(data, 4); Utils.FloatToBytes(_lightCutoff).CopyTo(data, 8); Utils.FloatToBytes(_lightFalloff).CopyTo(data, 12); return data; } /// <summary> /// Creates a OpenMetaverse.Primitive and populates it with converted PrimitiveBaseShape values /// </summary> /// <returns></returns> public Primitive ToOmvPrimitive() { // position and rotation defaults here since they are not available in PrimitiveBaseShape return ToOmvPrimitive(new Vector3(0.0f, 0.0f, 0.0f), new Quaternion(0.0f, 0.0f, 0.0f, 1.0f)); } /// <summary> /// Creates a OpenMetaverse.Primitive and populates it with converted PrimitiveBaseShape values /// </summary> /// <param name="position"></param> /// <param name="rotation"></param> /// <returns></returns> public Primitive ToOmvPrimitive(Vector3 position, Quaternion rotation) { OpenMetaverse.Primitive prim = new OpenMetaverse.Primitive(); prim.Scale = this.Scale; prim.Position = position; prim.Rotation = rotation; if (this.SculptEntry) { prim.Sculpt = new Primitive.SculptData(); prim.Sculpt.Type = (OpenMetaverse.SculptType)this.SculptType; prim.Sculpt.SculptTexture = this.SculptTexture; } prim.PrimData.PathShearX = this.PathShearX < 128 ? (float)this.PathShearX * 0.01f : (float)(this.PathShearX - 256) * 0.01f; prim.PrimData.PathShearY = this.PathShearY < 128 ? (float)this.PathShearY * 0.01f : (float)(this.PathShearY - 256) * 0.01f; prim.PrimData.PathBegin = (float)this.PathBegin * 2.0e-5f; prim.PrimData.PathEnd = 1.0f - (float)this.PathEnd * 2.0e-5f; prim.PrimData.PathScaleX = (200 - this.PathScaleX) * 0.01f; prim.PrimData.PathScaleY = (200 - this.PathScaleY) * 0.01f; prim.PrimData.PathTaperX = this.PathTaperX * 0.01f; prim.PrimData.PathTaperY = this.PathTaperY * 0.01f; prim.PrimData.PathTwistBegin = this.PathTwistBegin * 0.01f; prim.PrimData.PathTwist = this.PathTwist * 0.01f; prim.PrimData.ProfileBegin = (float)this.ProfileBegin * 2.0e-5f; prim.PrimData.ProfileEnd = 1.0f - (float)this.ProfileEnd * 2.0e-5f; prim.PrimData.ProfileHollow = (float)this.ProfileHollow * 2.0e-5f; prim.PrimData.profileCurve = this.ProfileCurve; prim.PrimData.ProfileHole = (HoleType)this.HollowShape; prim.PrimData.PathCurve = (PathCurve)this.PathCurve; prim.PrimData.PathRadiusOffset = 0.01f * this.PathRadiusOffset; prim.PrimData.PathRevolutions = 1.0f + 0.015f * this.PathRevolutions; prim.PrimData.PathSkew = 0.01f * this.PathSkew; prim.PrimData.PCode = OpenMetaverse.PCode.Prim; prim.PrimData.State = 0; if (this.FlexiEntry) { prim.Flexible = new Primitive.FlexibleData(); prim.Flexible.Drag = this.FlexiDrag; prim.Flexible.Force = new Vector3(this.FlexiForceX, this.FlexiForceY, this.FlexiForceZ); prim.Flexible.Gravity = this.FlexiGravity; prim.Flexible.Softness = this.FlexiSoftness; prim.Flexible.Tension = this.FlexiTension; prim.Flexible.Wind = this.FlexiWind; } if (this.LightEntry) { prim.Light = new Primitive.LightData(); prim.Light.Color = new Color4(this.LightColorR, this.LightColorG, this.LightColorB, this.LightColorA); prim.Light.Cutoff = this.LightCutoff; prim.Light.Falloff = this.LightFalloff; prim.Light.Intensity = this.LightIntensity; prim.Light.Radius = this.LightRadius; } prim.Textures = this.Textures; prim.Properties = new Primitive.ObjectProperties(); prim.Properties.Name = "Primitive"; prim.Properties.Description = ""; prim.Properties.CreatorID = UUID.Zero; prim.Properties.GroupID = UUID.Zero; prim.Properties.OwnerID = UUID.Zero; prim.Properties.Permissions = new Permissions(); prim.Properties.SalePrice = 10; prim.Properties.SaleType = new SaleType(); return prim; } } }
#pragma warning disable 0168 using System; using System.Linq; using nHydrate.Generator.Models; using System.Text; namespace nHydrate.Generator.EFCodeFirstNetCore.Generators.ContextExtensions { public class ContextExtensionsGeneratedTemplate : EFCodeFirstNetCoreBaseTemplate { private StringBuilder sb = new StringBuilder(); public ContextExtensionsGeneratedTemplate(ModelRoot model) : base(model) { } #region BaseClassTemplate overrides public override string FileName => _model.ProjectName + "EntitiesExtensions.Generated.cs"; public string ParentItemName => _model.ProjectName + "EntitiesExtensions.cs"; public override string FileContent { get { this.GenerateContent(); return sb.ToString(); } } #endregion #region GenerateContent private void GenerateContent() { try { nHydrate.Generator.GenerationHelper.AppendFileGeneatedMessageInCode(sb); this.AppendUsingStatements(); sb.AppendLine($"namespace {this.GetLocalNamespace()}"); sb.AppendLine("{"); this.AppendExtensions(); sb.AppendLine("}"); } catch (Exception ex) { throw; } } private void AppendUsingStatements() { sb.AppendLine("using System;"); sb.AppendLine("using System.Linq;"); sb.AppendLine("using System.Collections.Generic;"); sb.AppendLine("using System.Reflection;"); sb.AppendLine(); } private void AppendExtensions() { sb.AppendLine($" #region {_model.ProjectName}EntitiesExtensions"); sb.AppendLine(); sb.AppendLine(" /// <summary>"); sb.AppendLine(" /// Extension methods for this library"); sb.AppendLine(" /// </summary>"); sb.AppendLine($" [System.CodeDom.Compiler.GeneratedCode(\"nHydrate\", \"{_model.ModelToolVersion}\")]"); sb.AppendLine($" public static partial class {_model.ProjectName}EntitiesExtensions"); sb.AppendLine(" {"); #region GetFieldType sb.AppendLine(" #region GetFieldType Extension Method"); sb.AppendLine(); sb.AppendLine(" /// <summary>"); sb.AppendLine(" /// Get the system type of a field of one of the contained context objects"); sb.AppendLine(" /// </summary>"); sb.AppendLine($" public static System.Type GetFieldType(this {this.GetLocalNamespace()}.{_model.ProjectName}Entities context, Enum field)"); sb.AppendLine(" {"); foreach (var table in _model.Database.Tables.Where(x => !x.AssociativeTable && (x.TypedTable != TypedTableConstants.EnumOnly)).OrderBy(x => x.PascalName)) { sb.AppendLine($" if (field is {this.GetLocalNamespace()}.Entity.{table.PascalName}.FieldNameConstants)"); sb.AppendLine($" return {this.GetLocalNamespace()}.Entity.{table.PascalName}.GetFieldType(({this.GetLocalNamespace()}.Entity.{table.PascalName}.FieldNameConstants)field);"); } sb.AppendLine(" throw new Exception(\"Unknown field type!\");"); sb.AppendLine(" }"); sb.AppendLine(); sb.AppendLine(" #endregion"); sb.AppendLine(); #endregion #region GetEntityType sb.AppendLine(" #region GetEntityType"); sb.AppendLine(); sb.AppendLine(" /// <summary>"); sb.AppendLine(" /// Determines the entity from one of its fields"); sb.AppendLine(" /// </summary>"); sb.AppendLine(" public static System.Type GetEntityType(EntityMappingConstants entityType)"); sb.AppendLine(" {"); sb.AppendLine(" switch (entityType)"); sb.AppendLine(" {"); foreach (var table in _model.Database.Tables.Where(x => !x.AssociativeTable && (x.TypedTable != TypedTableConstants.EnumOnly)).OrderBy(x => x.PascalName)) sb.AppendLine(" case EntityMappingConstants." + table.PascalName + ": return typeof(" + this.GetLocalNamespace() + ".Entity." + table.PascalName + ");"); sb.AppendLine(" }"); sb.AppendLine(" throw new Exception(\"Unknown entity type!\");"); sb.AppendLine(" }"); sb.AppendLine(); sb.AppendLine(" #endregion"); sb.AppendLine(); #endregion #region GetValue Methods sb.AppendLine(" #region GetValue Methods"); sb.AppendLine(); //GetValue by lambda sb.AppendLine(" /// <summary>"); sb.AppendLine(" /// Gets the value of one of this object's properties."); sb.AppendLine(" /// </summary>"); sb.AppendLine(" /// <typeparam name=\"T\">The type of value to retrieve</typeparam>"); sb.AppendLine(" /// <typeparam name=\"R\">The type of object from which retrieve the field value</typeparam>"); sb.AppendLine(" /// <param name=\"item\">The item from which to pull the value.</param>"); sb.AppendLine(" /// <param name=\"selector\">The field to retrieve</param>"); sb.AppendLine(" /// <returns></returns>"); sb.AppendLine(" public static T GetValue<T, R>(this R item, System.Linq.Expressions.Expression<System.Func<R, T>> selector)"); sb.AppendLine(" where R : BaseEntity"); sb.AppendLine(" {"); sb.AppendLine(" var b = selector.Body.ToString();"); sb.AppendLine(" var arr = b.Split('.');"); sb.AppendLine(" if (arr.Length != 2) throw new System.Exception(\"Invalid selector\");"); sb.AppendLine(" var tn = arr.Last();"); sb.AppendLine(" var ft = ((IReadOnlyBusinessObject)item).GetFieldNameConstants();"); sb.AppendLine(" var te = (System.Enum)Enum.Parse(ft, tn, true);"); sb.AppendLine(" return item.GetValueInternal<T, R>(field: te, defaultValue: default(T));"); sb.AppendLine(" }"); sb.AppendLine(); //GetValue by lambda with default sb.AppendLine(" /// <summary>"); sb.AppendLine(" /// Gets the value of one of this object's properties."); sb.AppendLine(" /// </summary>"); sb.AppendLine(" /// <typeparam name=\"T\">The type of value to retrieve</typeparam>"); sb.AppendLine(" /// <typeparam name=\"R\">The type of object from which retrieve the field value</typeparam>"); sb.AppendLine(" /// <param name=\"item\">The item from which to pull the value.</param>"); sb.AppendLine(" /// <param name=\"selector\">The field to retrieve</param>"); sb.AppendLine(" /// <param name=\"defaultValue\">The default value to return if the specified value is NULL</param>"); sb.AppendLine(" /// <returns></returns>"); sb.AppendLine(" public static T GetValue<T, R>(this R item, System.Linq.Expressions.Expression<System.Func<R, T>> selector, T defaultValue)"); sb.AppendLine(" where R : BaseEntity"); sb.AppendLine(" {"); sb.AppendLine(" var b = selector.Body.ToString();"); sb.AppendLine(" var arr = b.Split('.');"); sb.AppendLine(" if (arr.Length != 2) throw new System.Exception(\"Invalid selector\");"); sb.AppendLine(" var tn = arr.Last();"); sb.AppendLine(" var ft = ((IReadOnlyBusinessObject)item).GetFieldNameConstants();"); sb.AppendLine(" var te = (System.Enum)Enum.Parse(ft, tn, true);"); sb.AppendLine(" return item.GetValueInternal<T, R>(field: te, defaultValue: defaultValue);"); sb.AppendLine(" }"); sb.AppendLine(); //GetValue by by Enum with default sb.AppendLine(" /// <summary>"); sb.AppendLine(" /// Gets the value of one of this object's properties."); sb.AppendLine(" /// </summary>"); sb.AppendLine(" /// <typeparam name=\"T\">The type of value to retrieve</typeparam>"); sb.AppendLine(" /// <typeparam name=\"R\">The type of object from which retrieve the field value</typeparam>"); sb.AppendLine(" /// <param name=\"item\">The item from which to pull the value.</param>"); sb.AppendLine(" /// <param name=\"field\">The field value to retrieve</param>"); sb.AppendLine(" /// <param name=\"defaultValue\">The default value to return if the specified value is NULL</param>"); sb.AppendLine(" /// <returns></returns>"); sb.AppendLine(" private static T GetValueInternal<T, R>(this R item, System.Enum field, T defaultValue)"); sb.AppendLine(" where R : BaseEntity"); sb.AppendLine(" {"); sb.AppendLine(" var valid = false;"); sb.AppendLine(" if (typeof(T) == typeof(bool)) valid = true;"); sb.AppendLine(" else if (typeof(T) == typeof(byte)) valid = true;"); sb.AppendLine(" else if (typeof(T) == typeof(char)) valid = true;"); sb.AppendLine(" else if (typeof(T) == typeof(DateTime)) valid = true;"); sb.AppendLine(" else if (typeof(T) == typeof(decimal)) valid = true;"); sb.AppendLine(" else if (typeof(T) == typeof(double)) valid = true;"); sb.AppendLine(" else if (typeof(T) == typeof(int)) valid = true;"); sb.AppendLine(" else if (typeof(T) == typeof(long)) valid = true;"); sb.AppendLine(" else if (typeof(T) == typeof(Single)) valid = true;"); sb.AppendLine(" else if (typeof(T) == typeof(string)) valid = true;"); sb.AppendLine(" if (!valid)"); sb.AppendLine(" throw new Exception(\"Cannot convert object to type '\" + typeof(T).ToString() + \"'!\");"); sb.AppendLine(); sb.AppendLine(" object o = ((IReadOnlyBusinessObject)item).GetValue(field, defaultValue);"); sb.AppendLine(" if (o == null) return defaultValue;"); sb.AppendLine(); sb.AppendLine(" if (o is T)"); sb.AppendLine(" {"); sb.AppendLine(" return (T)o;"); sb.AppendLine(" }"); sb.AppendLine(" else if (typeof(T) == typeof(bool))"); sb.AppendLine(" {"); sb.AppendLine(" return (T)(object)Convert.ToBoolean(o);"); sb.AppendLine(" }"); sb.AppendLine(" else if (typeof(T) == typeof(byte))"); sb.AppendLine(" {"); sb.AppendLine(" return (T)(object)Convert.ToByte(o);"); sb.AppendLine(" }"); sb.AppendLine(" else if (typeof(T) == typeof(char))"); sb.AppendLine(" {"); sb.AppendLine(" return (T)(object)Convert.ToChar(o);"); sb.AppendLine(" }"); sb.AppendLine(" else if (typeof(T) == typeof(DateTime))"); sb.AppendLine(" {"); sb.AppendLine(" return (T)(object)Convert.ToDateTime(o);"); sb.AppendLine(" }"); sb.AppendLine(" else if (typeof(T) == typeof(decimal))"); sb.AppendLine(" {"); sb.AppendLine(" return (T)(object)Convert.ToDecimal(o);"); sb.AppendLine(" }"); sb.AppendLine(" else if (typeof(T) == typeof(double))"); sb.AppendLine(" {"); sb.AppendLine(" return (T)(object)Convert.ToDouble(o);"); sb.AppendLine(" }"); sb.AppendLine(" else if (typeof(T) == typeof(int))"); sb.AppendLine(" {"); sb.AppendLine(" return (T)(object)Convert.ToInt32(o);"); sb.AppendLine(" }"); sb.AppendLine(" else if (typeof(T) == typeof(long))"); sb.AppendLine(" {"); sb.AppendLine(" return (T)(object)Convert.ToInt64(o);"); sb.AppendLine(" }"); sb.AppendLine(" else if (typeof(T) == typeof(Single))"); sb.AppendLine(" {"); sb.AppendLine(" return (T)(object)Convert.ToSingle(o);"); sb.AppendLine(" }"); sb.AppendLine(" else if (typeof(T) == typeof(string))"); sb.AppendLine(" {"); sb.AppendLine(" return (T)(object)Convert.ToString(o);"); sb.AppendLine(" }"); sb.AppendLine(" throw new Exception(\"Cannot convert object!\");"); sb.AppendLine(" }"); sb.AppendLine(); sb.AppendLine(" #endregion"); sb.AppendLine(); #endregion #region SetValue sb.AppendLine(" #region SetValue"); sb.AppendLine(" /// <summary>"); sb.AppendLine(" /// Assigns a value to a field on this object."); sb.AppendLine(" /// </summary>"); sb.AppendLine(" /// <param name=\"item\">The entity to set</param>"); sb.AppendLine(" /// <param name=\"selector\">The field on the entity to set</param>"); sb.AppendLine(" /// <param name=\"newValue\">The new value to assign to the field</param>"); sb.AppendLine(" public static void SetValue<TResult, R>(this R item, System.Linq.Expressions.Expression<System.Func<R, TResult>> selector, TResult newValue)"); sb.AppendLine(" where R : BaseEntity, IBusinessObject"); sb.AppendLine(" {"); sb.AppendLine(" SetValue(item: item, selector: selector, newValue: newValue, fixLength: false);"); sb.AppendLine(" }"); sb.AppendLine(); sb.AppendLine(" /// <summary>"); sb.AppendLine(" /// Assigns a value to a field on this object."); sb.AppendLine(" /// </summary>"); sb.AppendLine(" /// <param name=\"item\">The entity to set</param>"); sb.AppendLine(" /// <param name=\"selector\">The field on the entity to set</param>"); sb.AppendLine(" /// <param name=\"newValue\">The new value to assign to the field</param>"); sb.AppendLine(" /// <param name=\"fixLength\">Determines if the length should be truncated if too long. When false, an error will be raised if data is too large to be assigned to the field.</param>"); sb.AppendLine(" public static void SetValue<TResult, R>(this R item, System.Linq.Expressions.Expression<System.Func<R, TResult>> selector, TResult newValue, bool fixLength)"); sb.AppendLine(" where R : BaseEntity, IBusinessObject"); sb.AppendLine(" {"); sb.AppendLine(" var b = selector.Body.ToString();"); sb.AppendLine(" var arr = b.Split('.');"); sb.AppendLine(" if (arr.Length != 2) throw new System.Exception(\"Invalid selector\");"); sb.AppendLine(" var tn = arr.Last();"); sb.AppendLine(" var ft = ((IReadOnlyBusinessObject)item).GetFieldNameConstants();"); sb.AppendLine(" var te = (System.Enum)Enum.Parse(ft, tn, true);"); sb.AppendLine(" ((IBusinessObject)item).SetValue(field: te, newValue: newValue, fixLength: fixLength);"); sb.AppendLine(" }"); sb.AppendLine(); sb.AppendLine(" #endregion"); sb.AppendLine(); #endregion #region ObservableCollection sb.AppendLine(" #region ObservableCollection"); sb.AppendLine(" /// <summary>"); sb.AppendLine(" /// Returns an observable collection that can bound to UI controls"); sb.AppendLine(" /// </summary>"); sb.AppendLine(" public static System.Collections.ObjectModel.ObservableCollection<T> AsObservable<T>(this System.Collections.Generic.IEnumerable<T> list)"); sb.AppendLine(" where T : " + this.GetLocalNamespace() + ".IReadOnlyBusinessObject"); sb.AppendLine(" {"); sb.AppendLine(" var retval = new System.Collections.ObjectModel.ObservableCollection<T>();"); sb.AppendLine(" foreach (var o in list)"); sb.AppendLine(" retval.Add(o);"); sb.AppendLine(" return retval;"); sb.AppendLine(" }"); sb.AppendLine(" #endregion"); sb.AppendLine(); #endregion #region Many-to-Many Convenience extensions sb.AppendLine(" #region Many-to-Many Convenience Extensions"); foreach (var table in _model.Database.Tables.Where(x => x.AssociativeTable)) { var relations = table.GetRelationsWhereChild().ToList(); if (relations.Count == 2) { var relation1 = relations.First(); var relation2 = relations.Last(); sb.AppendLine(" /// <summary>"); sb.AppendLine($" /// Adds a {relation1.ParentTable.PascalName} child entity to a many-to-many relationship"); sb.AppendLine(" /// </summary>"); sb.AppendLine($" public static void Associate{relation1.ParentTable.PascalName}(this EFDAL.Entity.{relation2.ParentTable.PascalName} item, EFDAL.Entity.{relation1.ParentTable.PascalName} child)"); sb.AppendLine(" {"); sb.AppendLine($" if (item.{table.PascalName}List == null)"); sb.AppendLine($" item.{table.PascalName}List = new List<Entity.{table.PascalName}>();"); sb.AppendLine(" item." + table.PascalName + "List.Add(new EFDAL.Entity." + table.PascalName + " { " + relation2.ParentTable.PascalName + " = item, " + relation1.ParentTable.PascalName + " = child });"); sb.AppendLine(" }"); sb.AppendLine(); sb.AppendLine(" /// <summary>"); sb.AppendLine($" /// Removes a {relation1.ParentTable.PascalName} child entity from a many-to-many relationship"); sb.AppendLine(" /// </summary>"); sb.AppendLine($" public static void Unassociate{relation1.ParentTable.PascalName}(this EFDAL.Entity.{relation2.ParentTable.PascalName} item, EFDAL.Entity.{relation1.ParentTable.PascalName} child)"); sb.AppendLine(" {"); sb.AppendLine($" if (item.{table.PascalName}List == null)"); sb.AppendLine($" item.{table.PascalName}List = new List<Entity.{table.PascalName}>();"); sb.AppendLine(); sb.AppendLine($" var list = item.{table.PascalName}List.Where(x => x.{relation1.ParentTable.PascalName} == child).ToList();"); sb.AppendLine(" foreach (var cItem in list)"); sb.AppendLine($" item.{table.PascalName}List.Remove(cItem);"); sb.AppendLine(" }"); sb.AppendLine(); sb.AppendLine(" /// <summary>"); sb.AppendLine($" /// Adds a {relation2.ParentTable.PascalName} child entity to a many-to-many relationship"); sb.AppendLine(" /// </summary>"); sb.AppendLine($" public static void Associate{relation2.ParentTable.PascalName}(this EFDAL.Entity.{relation1.ParentTable.PascalName} item, EFDAL.Entity.{relation2.ParentTable.PascalName} child)"); sb.AppendLine(" {"); sb.AppendLine($" if (item.{table.PascalName}List == null)"); sb.AppendLine($" item.{table.PascalName}List = new List<Entity.{table.PascalName}>();"); sb.AppendLine(" item." + table.PascalName + "List.Add(new EFDAL.Entity." + table.PascalName + " { " + relation1.ParentTable.PascalName + " = item, " + relation2.ParentTable.PascalName + " = child });"); sb.AppendLine(" }"); sb.AppendLine(); sb.AppendLine(" /// <summary>"); sb.AppendLine($" /// Removes a {relation2.ParentTable.PascalName} child entity from a many-to-many relationship"); sb.AppendLine(" /// </summary>"); sb.AppendLine($" public static void Unassociate{relation2.ParentTable.PascalName}(this EFDAL.Entity.{relation1.ParentTable.PascalName} item, EFDAL.Entity.{relation2.ParentTable.PascalName} child)"); sb.AppendLine(" {"); sb.AppendLine($" if (item.{table.PascalName}List == null)"); sb.AppendLine($" item.{table.PascalName}List = new List<Entity.{table.PascalName}>();"); sb.AppendLine(); sb.AppendLine($" var list = item.{table.PascalName}List.Where(x => x.{relation2.ParentTable.PascalName} == child).ToList();"); sb.AppendLine(" foreach (var cItem in list)"); sb.AppendLine($" item.{table.PascalName}List.Remove(cItem);"); sb.AppendLine(" }"); sb.AppendLine(); } } sb.AppendLine(" #endregion"); #endregion sb.AppendLine(" }"); sb.AppendLine(); #region SequentialId sb.AppendLine(" #region SequentialIdGenerator"); sb.AppendLine(); sb.AppendLine(" /// <summary>"); sb.AppendLine(" /// Generates Sequential Guid values that can be used for Sql Server UniqueIdentifiers to improve performance."); sb.AppendLine(" /// </summary>"); sb.AppendLine(" internal class SequentialIdGenerator"); sb.AppendLine(" {"); sb.AppendLine(" private readonly object _lock;"); sb.AppendLine(" private Guid _lastGuid;"); sb.AppendLine(" // 3 - the least significant byte in Guid ByteArray [for SQL Server ORDER BY clause]"); sb.AppendLine(" // 10 - the most significant byte in Guid ByteArray [for SQL Server ORDERY BY clause]"); sb.AppendLine(" private static readonly int[] SqlOrderMap = new int[] { 3, 2, 1, 0, 5, 4, 7, 6, 9, 8, 15, 14, 13, 12, 11, 10 };"); sb.AppendLine(); sb.AppendLine(" /// <summary>"); sb.AppendLine(" /// Creates a new SequentialId class to generate sequential GUID values."); sb.AppendLine(" /// </summary>"); sb.AppendLine(" public SequentialIdGenerator() : this(Guid.NewGuid()) { }"); sb.AppendLine(); sb.AppendLine(" /// <summary>"); sb.AppendLine(" /// Creates a new SequentialId class to generate sequential GUID values."); sb.AppendLine(" /// </summary>"); sb.AppendLine(" /// <param name=\"seed\">Starting seed value.</param>"); sb.AppendLine(" /// <remarks>You can save the last generated value <see cref=\"LastValue\"/> and then "); sb.AppendLine(" /// use this as the new seed value to pick up where you left off.</remarks>"); sb.AppendLine(" public SequentialIdGenerator(Guid seed)"); sb.AppendLine(" {"); sb.AppendLine(" _lock = new object();"); sb.AppendLine(" _lastGuid = seed;"); sb.AppendLine(" }"); sb.AppendLine(); sb.AppendLine(" /// <summary>"); sb.AppendLine(" /// Last generated guid value. If no values have been generated, this will be the seed value."); sb.AppendLine(" /// </summary>"); sb.AppendLine(" public Guid LastValue"); sb.AppendLine(" {"); sb.AppendLine(" get {"); sb.AppendLine(" lock (_lock)"); sb.AppendLine(" {"); sb.AppendLine(" return _lastGuid;"); sb.AppendLine(" }"); sb.AppendLine(" }"); sb.AppendLine(" set"); sb.AppendLine(" {"); sb.AppendLine(" lock (_lock)"); sb.AppendLine(" {"); sb.AppendLine(" _lastGuid = value;"); sb.AppendLine(" }"); sb.AppendLine(" }"); sb.AppendLine(" }"); sb.AppendLine(); sb.AppendLine(" /// <summary>"); sb.AppendLine(" /// Generate a new sequential id."); sb.AppendLine(" /// </summary>"); sb.AppendLine(" /// <returns>New sequential id value.</returns>"); sb.AppendLine(" public Guid NewId()"); sb.AppendLine(" {"); sb.AppendLine(" Guid newId;"); sb.AppendLine(" lock (_lock)"); sb.AppendLine(" {"); sb.AppendLine(" var guidBytes = _lastGuid.ToByteArray();"); sb.AppendLine(" ReorderToSqlOrder(ref guidBytes);"); sb.AppendLine(" newId = new Guid(guidBytes);"); sb.AppendLine(" _lastGuid = newId;"); sb.AppendLine(" }"); sb.AppendLine(); sb.AppendLine(" return newId;"); sb.AppendLine(" }"); sb.AppendLine(); sb.AppendLine(" private static void ReorderToSqlOrder(ref byte[] bytes)"); sb.AppendLine(" {"); sb.AppendLine(" foreach (var bytesIndex in SqlOrderMap)"); sb.AppendLine(" {"); sb.AppendLine(" bytes[bytesIndex]++;"); sb.AppendLine(" if (bytes[bytesIndex] != 0)"); sb.AppendLine(" {"); sb.AppendLine(" break;"); sb.AppendLine(" }"); sb.AppendLine(" }"); sb.AppendLine(" }"); sb.AppendLine(); sb.AppendLine(" /// <summary>"); sb.AppendLine(" /// IComparer.Compare compatible method to order Guid values the same way as MS Sql Server."); sb.AppendLine(" /// </summary>"); sb.AppendLine(" /// <param name=\"x\">The first guid to compare</param>"); sb.AppendLine(" /// <param name=\"y\">The second guid to compare</param>"); sb.AppendLine(" /// <returns><see cref=\"System.Collections.IComparer.Compare\"/></returns>"); sb.AppendLine(" public static int SqlCompare(Guid x, Guid y)"); sb.AppendLine(" {"); sb.AppendLine(" var result = 0;"); sb.AppendLine(" var index = SqlOrderMap.Length - 1;"); sb.AppendLine(" var xBytes = x.ToByteArray();"); sb.AppendLine(" var yBytes = y.ToByteArray();"); sb.AppendLine(); sb.AppendLine(" while (result == 0 && index >= 0)"); sb.AppendLine(" {"); sb.AppendLine(" result = xBytes[SqlOrderMap[index]].CompareTo(yBytes[SqlOrderMap[index]]);"); sb.AppendLine(" index--;"); sb.AppendLine(" }"); sb.AppendLine(" return result;"); sb.AppendLine(" }"); sb.AppendLine(" }"); sb.AppendLine(); sb.AppendLine(" #endregion"); sb.AppendLine(); #endregion sb.AppendLine(" #endregion"); sb.AppendLine(); } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Media; namespace NinjaSaviour { /// <summary> /// This is the main type for your game /// </summary> public class Game1 : Microsoft.Xna.Framework.Game { GraphicsDeviceManager graphics; SpriteBatch spriteBatch; const int W_WIDTH = 800; const int W_HEIGHT = 600; // game objects Ninja ninja; Boss boss; // level fields Level level; Level levelOne; Level levelTwo; Level levelThree; Level bossLevel; int startingX; int startingY; // state and menu fields string state = "menu"; int selected = 1; Texture2D menuTexture; Texture2D menuStartTexture; Texture2D menuInstructionsTexture; Texture2D menuExitTexture; Texture2D instructionsTexture; Texture2D introTexture; Texture2D pauseResumeTexture; Texture2D pauseResetTexture; Texture2D pauseMenuTexture; Texture2D failAgainTexture; Texture2D failMenuTexture; Texture2D congratsTexture; Rectangle menuRectangle = new Rectangle(); bool isKeyDown = false; // audio object SoundEffect music; SoundEffectInstance instance; public Game1() { graphics = new GraphicsDeviceManager(this); Content.RootDirectory = "Content"; // set resolution graphics.PreferredBackBufferWidth = W_WIDTH; graphics.PreferredBackBufferHeight = W_HEIGHT; } /// <summary> /// Allows the game to perform any initialization it needs to before starting to run. /// This is where it can query for any required services and load any non-graphic /// related content. Calling base.Initialize will enumerate through any components /// and initialize them as well. /// </summary> protected override void Initialize() { // TODO: Add your initialization logic here base.Initialize(); } /// <summary> /// LoadContent will be called once per game and is the place to load /// all of your content. /// </summary> protected override void LoadContent() { // Create a new SpriteBatch, which can be used to draw textures. spriteBatch = new SpriteBatch(GraphicsDevice); // create an object for the ninja ninja = new Ninja(Content, "ninja2"); // create an object for the boss boss = new Boss(Content, "boss", 640, 270); // create objects for the levels levelOne = new Level(Content, W_WIDTH, W_HEIGHT, "level1", 1, null); levelTwo = new Level(Content, W_WIDTH, W_HEIGHT, "level2", 2, null); levelThree = new Level(Content, W_WIDTH, W_HEIGHT, "level3", 3, null); bossLevel = new Level(Content, W_WIDTH, W_HEIGHT, "bosslevel3", 4, boss); startingX = 40; startingY = 500; level = levelOne; // load menu images menuRectangle.X = 0; menuRectangle.Y = 0; menuRectangle.Width = W_WIDTH; menuRectangle.Height = W_HEIGHT; menuStartTexture = Content.Load<Texture2D>("menu_start"); menuInstructionsTexture = Content.Load<Texture2D>("menu_instructions"); menuExitTexture = Content.Load<Texture2D>("menu_exit"); instructionsTexture = Content.Load<Texture2D>("instructions"); introTexture = Content.Load<Texture2D>("intro"); pauseResumeTexture = Content.Load<Texture2D>("pause_resume"); pauseResetTexture = Content.Load<Texture2D>("pause_reset"); pauseMenuTexture = Content.Load<Texture2D>("pause_menu"); failAgainTexture = Content.Load<Texture2D>("fail_again"); failMenuTexture = Content.Load<Texture2D>("fail_menu"); congratsTexture = Content.Load<Texture2D>("congratulations"); menuTexture = menuStartTexture; // load music music = Content.Load<SoundEffect>("ninjasaviour"); instance = music.CreateInstance(); instance.IsLooped = true; } /// <summary> /// UnloadContent will be called once per game and is the place to unload /// all content. /// </summary> protected override void UnloadContent() { // TODO: Unload any non ContentManager content here } /// <summary> /// Allows the game to run logic such as updating the world, /// checking for collisions, gathering input, and playing audio. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Update(GameTime gameTime) { KeyboardState keyboard = Keyboard.GetState(); // if the game is in the menu state if (state == "menu") { // update selection if ((keyboard.IsKeyDown(Keys.Down) || keyboard.IsKeyDown(Keys.S)) && !isKeyDown) { isKeyDown = true; selected++; if (selected == 4) selected = 3; } else if ((keyboard.IsKeyDown(Keys.Up) || keyboard.IsKeyDown(Keys.W)) && !isKeyDown) { isKeyDown = true; selected--; if (selected == 0) selected = 1; } else if (keyboard.GetPressedKeys().Length == 0) isKeyDown = false; // update textures if (selected == 1) menuTexture = menuStartTexture; else if (selected == 2) menuTexture = menuInstructionsTexture; else if (selected == 3) menuTexture = menuExitTexture; if (selected == 1 && (keyboard.IsKeyDown(Keys.Space) || keyboard.IsKeyDown(Keys.Enter)) && !isKeyDown) { state = "intro"; menuTexture = introTexture; isKeyDown = true; } else if (selected == 2 && (keyboard.IsKeyDown(Keys.Space) || keyboard.IsKeyDown(Keys.Enter)) && !isKeyDown) { state = "instructions"; menuTexture = instructionsTexture; isKeyDown = true; } else if (selected == 3 && (keyboard.IsKeyDown(Keys.Space) || keyboard.IsKeyDown(Keys.Enter)) && !isKeyDown) this.Exit(); } // if the game is in the instructions state else if (state == "instructions") { if (keyboard.IsKeyDown(Keys.Space) || keyboard.IsKeyDown(Keys.Enter)) { if (!isKeyDown) { state = "menu"; menuTexture = menuStartTexture; selected = 1; isKeyDown = true; } } else isKeyDown = false; } // if the game is in the intro state else if (state == "intro") { if (keyboard.IsKeyDown(Keys.Space) || keyboard.IsKeyDown(Keys.Enter)) { if (!isKeyDown) { state = "play"; menuTexture = menuStartTexture; selected = 1; isKeyDown = true; } } else isKeyDown = false; } // if the game is in the play state else if (state == "play") { // update the ninja ninja.Update(gameTime, keyboard, level); // update the boss if needed if (boss.Active) boss.Update(gameTime, level); // update the level level.Update(gameTime, ninja); if (level == levelOne && ninja.Xpos == 700 && ninja.Ypos == 500) { level = levelTwo; ninja.Xpos = 40; ninja.Ypos = 200; startingX = 40; startingY = 200; } if (level == levelTwo && ninja.Xpos == 400 && ninja.Ypos == 500) { level = levelThree; ninja.Xpos = 40; ninja.Ypos = 100; startingX = 40; startingY = 100; } if (level == levelThree && ninja.Xpos == 700 && ninja.Ypos == 100) { level = bossLevel; ninja.Xpos = 40; ninja.Ypos = 300; startingX = 40; startingY = 300; boss.Active = true; } // check for a death if (level.checkDeath(ninja, boss)) { levelOne.resetLevel(Content); levelTwo.resetLevel(Content); levelThree.resetLevel(Content); bossLevel.resetLevel(Content); if (level != bossLevel) boss.Active = false; boss.Life = 3; ninja.Xpos = startingX; ninja.Ypos = startingY; ninja.Shuriken = null; ninja.Offset = 0; state = "fail"; menuTexture = failAgainTexture; isKeyDown = true; selected = 1; } // check for victory if (boss.Life == 0 && boss.Active == false) { state = "victory"; menuTexture = congratsTexture; selected = 1; isKeyDown = true; level = levelOne; levelOne.resetLevel(Content); levelTwo.resetLevel(Content); levelThree.resetLevel(Content); bossLevel.resetLevel(Content); if (level != bossLevel) boss.Active = false; boss.Life = 3; startingX = 40; startingY = 500; ninja.Xpos = startingX; ninja.Ypos = startingY; ninja.Shuriken = null; ninja.Offset = 0; } // check for a pause if (keyboard.IsKeyDown(Keys.Escape)) { state = "pause"; menuTexture = pauseResetTexture; selected = 1; } else isKeyDown = false; } // if the game is in the pause state if (state == "pause") { // update selection if ((keyboard.IsKeyDown(Keys.Down) || keyboard.IsKeyDown(Keys.S)) && !isKeyDown) { isKeyDown = true; selected++; if (selected == 4) selected = 3; } else if ((keyboard.IsKeyDown(Keys.Up) || keyboard.IsKeyDown(Keys.W)) && !isKeyDown) { isKeyDown = true; selected--; if (selected == 0) selected = 1; } else if (keyboard.GetPressedKeys().Length == 0) isKeyDown = false; // update textures if (selected == 1) menuTexture = pauseResumeTexture; else if (selected == 2) menuTexture = pauseResetTexture; else if (selected == 3) menuTexture = pauseMenuTexture; if (selected == 1 && (keyboard.IsKeyDown(Keys.Space) || keyboard.IsKeyDown(Keys.Enter)) && !isKeyDown) state = "play"; else if (selected == 2 && (keyboard.IsKeyDown(Keys.Space) || keyboard.IsKeyDown(Keys.Enter)) && !isKeyDown) { levelOne.resetLevel(Content); levelTwo.resetLevel(Content); levelThree.resetLevel(Content); bossLevel.resetLevel(Content); if (level != bossLevel) boss.Active = false; boss.Life = 3; ninja.Xpos = startingX; ninja.Ypos = startingY; ninja.Shuriken = null; ninja.Offset = 0; state = "play"; } else if (selected == 3 && (keyboard.IsKeyDown(Keys.Space) || keyboard.IsKeyDown(Keys.Enter)) && !isKeyDown) { menuTexture = menuStartTexture; selected = 1; isKeyDown = true; level = levelOne; levelOne.resetLevel(Content); levelTwo.resetLevel(Content); levelThree.resetLevel(Content); bossLevel.resetLevel(Content); if (level != bossLevel) boss.Active = false; boss.Life = 3; startingX = 40; startingY = 500; ninja.Xpos = startingX; ninja.Ypos = startingY; ninja.Shuriken = null; ninja.Offset = 0; state = "menu"; } } // if the game is in the fail state if (state == "fail") { // update selection if ((keyboard.IsKeyDown(Keys.Down) || keyboard.IsKeyDown(Keys.S)) && !isKeyDown) { isKeyDown = true; selected++; if (selected == 3) selected = 2; } else if ((keyboard.IsKeyDown(Keys.Up) || keyboard.IsKeyDown(Keys.W)) && !isKeyDown) { isKeyDown = true; selected--; if (selected == 0) selected = 1; } else if (keyboard.GetPressedKeys().Length == 0) isKeyDown = false; // update textures if (selected == 1) menuTexture = failAgainTexture; else if (selected == 2) menuTexture = failMenuTexture; if (selected == 1 && (keyboard.IsKeyDown(Keys.Space) || keyboard.IsKeyDown(Keys.Enter)) && !isKeyDown) { state = "play"; isKeyDown = true; } else if (selected == 2 && (keyboard.IsKeyDown(Keys.Space) || keyboard.IsKeyDown(Keys.Enter)) && !isKeyDown) { level = levelOne; state = "menu"; menuTexture = menuStartTexture; isKeyDown = true; selected = 1; startingX = 40; startingY = 500; ninja.Xpos = startingX; ninja.Ypos = startingY; } } // if the game is in the victory state else if (state == "victory") { if (keyboard.IsKeyDown(Keys.Space) || keyboard.IsKeyDown(Keys.Enter)) { if (!isKeyDown) { state = "menu"; menuTexture = menuStartTexture; selected = 1; isKeyDown = true; } } else isKeyDown = false; } // play music if (!(instance.State == SoundState.Playing)) instance.Play(); base.Update(gameTime); } /// <summary> /// This is called when the game should draw itself. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(Color.CornflowerBlue); spriteBatch.Begin(); if (state == "play") { level.Draw(spriteBatch); ninja.Draw(spriteBatch); boss.Draw(spriteBatch); } else spriteBatch.Draw(menuTexture, menuRectangle, Color.White); spriteBatch.End(); base.Draw(gameTime); } } }
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- namespace Microsoft.Azure.Commands.ResourceManager.Cmdlets.Implementation { using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Components; using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Entities.Resources; using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Extensions; using Newtonsoft.Json.Linq; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Management.Automation; using System.Threading.Tasks; /// <summary> /// Cmdlet to get existing resources from ARM cache. /// </summary> [Cmdlet(VerbsCommon.Find, "AzureRmResource", DefaultParameterSetName = FindAzureResourceCmdlet.ListResourcesParameterSet), OutputType(typeof(PSObject))] public sealed class FindAzureResourceCmdlet : ResourceManagerCmdletBase { /// <summary> /// Contains the errors that encountered while satifying the request. /// </summary> private readonly ConcurrentBag<ErrorRecord> errors = new ConcurrentBag<ErrorRecord>(); /// <summary> /// The list resources parameter set. /// </summary> internal const string ListResourcesParameterSet = "Lists the resources based on the specified scope."; /// <summary> /// The list tenant resources parameter set. /// </summary> internal const string ListTenantResourcesParameterSet = "Lists the resources based on the specified scope at the tenant level."; /// <summary> /// The get tenant resource parameter set. /// </summary> internal const string MultiSubscriptionListResourcesParameterSet = "Get a resources using a multi-subscription query."; /// <summary> /// Caches the current subscription ids to get all subscription ids in the pipeline. /// </summary> private readonly List<Guid> subscriptionIds = new List<Guid>(); /// <summary> /// Gets or sets the resource name parameter. /// </summary> [Alias("Name")] [Parameter(ParameterSetName = FindAzureResourceCmdlet.ListResourcesParameterSet, Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The resource name substring. e.g. if your resource name is testResource, you can specify test.")] [Parameter(ParameterSetName = FindAzureResourceCmdlet.ListTenantResourcesParameterSet, Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The resource name substring. e.g. if your resource name is testResource, you can specify test.")] [Parameter(ParameterSetName = FindAzureResourceCmdlet.MultiSubscriptionListResourcesParameterSet, Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The resource name substring. e.g. if your resource name is testResource, you can specify test.")] [ValidateNotNullOrEmpty] public string ResourceNameContains { get; set; } /// <summary> /// Gets or sets the resource type parameter. /// </summary> [Parameter(ParameterSetName = FindAzureResourceCmdlet.ListResourcesParameterSet, Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The resource type. e.g. Microsoft.Sql/Servers/Databases.")] [Parameter(ParameterSetName = FindAzureResourceCmdlet.ListTenantResourcesParameterSet, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The resource type. e.g. Microsoft.Sql/Servers/Databases.")] [Parameter(ParameterSetName = FindAzureResourceCmdlet.MultiSubscriptionListResourcesParameterSet, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The resource type. e.g. Microsoft.Sql/Servers/Databases.")] [ValidateNotNullOrEmpty] public string ResourceType { get; set; } /// <summary> /// Gets or sets the extension resource type. /// </summary> [Parameter(ParameterSetName = FindAzureResourceCmdlet.ListResourcesParameterSet, Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The extension resource type. e.g. Microsoft.Sql/Servers/{serverName}/Databases/myDatabase.")] [Parameter(ParameterSetName = FindAzureResourceCmdlet.ListTenantResourcesParameterSet, Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The extension resource type. e.g. Microsoft.Sql/Servers/{serverName}/Databases/myDatabase.")] [Parameter(ParameterSetName = FindAzureResourceCmdlet.MultiSubscriptionListResourcesParameterSet, Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The extension resource type. e.g. Microsoft.Sql/Servers/{serverName}/Databases/myDatabase.")] [ValidateNotNullOrEmpty] public string ExtensionResourceType { get; set; } /// <summary> /// Gets or sets the top parameter. /// </summary> [Parameter(ParameterSetName = FindAzureResourceCmdlet.ListResourcesParameterSet, Mandatory = false, HelpMessage = "The number of resources to retrieve.")] [Parameter(ParameterSetName = FindAzureResourceCmdlet.ListTenantResourcesParameterSet, Mandatory = false, HelpMessage = "The number of resources to retrieve.")] [Parameter(ParameterSetName = FindAzureResourceCmdlet.MultiSubscriptionListResourcesParameterSet, Mandatory = false, HelpMessage = "The number of resources to retrieve.")] [ValidateNotNullOrEmpty] public int? Top { get; set; } /// <summary> /// Gets or sets the OData query parameter. /// </summary> [Parameter(Mandatory = false, HelpMessage = "An OData style filter which will be appended to the request in addition to any other filters.")] [ValidateNotNullOrEmpty] public string ODataQuery { get; set; } /// <summary> /// Gets or sets the tag name. /// </summary> [Parameter(ParameterSetName = FindAzureResourceCmdlet.ListResourcesParameterSet, Mandatory = false, HelpMessage = "The name of the tag to query by.")] [Parameter(ParameterSetName = FindAzureResourceCmdlet.MultiSubscriptionListResourcesParameterSet, Mandatory = false, HelpMessage = "The name of the tag to query by.")] [ValidateNotNullOrEmpty] public string TagName { get; set; } /// <summary> /// Gets or sets the tag value. /// </summary> [Parameter(ParameterSetName = FindAzureResourceCmdlet.ListResourcesParameterSet, Mandatory = false, HelpMessage = "The value of the tag to query by.")] [Parameter(ParameterSetName = FindAzureResourceCmdlet.MultiSubscriptionListResourcesParameterSet, Mandatory = false, HelpMessage = "The value of the tag to query by.")] [ValidateNotNullOrEmpty] public string TagValue { get; set; } /// <summary> /// Gets or sets the resource group name. /// </summary> [Alias("ResourceGroupName")] [Parameter(Mandatory = false, ParameterSetName = FindAzureResourceCmdlet.ListResourcesParameterSet, ValueFromPipelineByPropertyName = true, HelpMessage = "The resource group name substring.")] [Parameter(Mandatory = false, ParameterSetName = FindAzureResourceCmdlet.MultiSubscriptionListResourcesParameterSet, ValueFromPipelineByPropertyName = true, HelpMessage = "The resource group name substring.")] [ValidateNotNullOrEmpty] public string ResourceGroupNameContains { get; set; } /// <summary> /// Gets or sets the expand properties property. /// </summary> [Parameter(Mandatory = false, HelpMessage = "When specified, expands the properties of the resource.")] public SwitchParameter ExpandProperties { get; set; } /// <summary> /// Gets or sets the tenant level parameter. /// </summary> [Parameter(ParameterSetName = FindAzureResourceCmdlet.ListTenantResourcesParameterSet, Mandatory = true, HelpMessage = "Indicates that this is a tenant level operation.")] public SwitchParameter TenantLevel { get; set; } /// <summary> /// Gets or sets the subscription id. /// </summary> public Guid? SubscriptionId { get; set; } /// <summary> /// Collects subscription ids from the pipeline. /// </summary> protected override void OnProcessRecord() { base.OnProcessRecord(); } /// <summary> /// Finishes the pipeline execution and runs the cmdlet. /// </summary> protected override void OnEndProcessing() { base.OnEndProcessing(); this.RunCmdlet(); } /// <summary> /// Contains the cmdlet's execution logic. /// </summary> private void RunCmdlet() { if (!this.TenantLevel) { this.SubscriptionId = DefaultContext.Subscription.Id; } PaginatedResponseHelper.ForEach( getFirstPage: () => this.GetResources(), getNextPage: nextLink => this.GetNextLink<JObject>(nextLink), cancellationToken: this.CancellationToken, action: resources => { Resource<JToken> resource; if (resources.CoalesceEnumerable().FirstOrDefault().TryConvertTo(out resource)) { var genericResources = resources.CoalesceEnumerable().Where(res => res != null).SelectArray(res => res.ToResource()); foreach (var batch in genericResources.Batch()) { var items = batch; if (this.ExpandProperties) { items = this.GetPopulatedResource(batch).Result; } var powerShellObjects = items.SelectArray(genericResource => genericResource.ToPsObject()); this.WriteObject(sendToPipeline: powerShellObjects, enumerateCollection: true); } } else { this.WriteObject(sendToPipeline: resources.CoalesceEnumerable().SelectArray(res => res.ToPsObject()), enumerateCollection: true); } }); if (this.errors.Count != 0) { foreach (var error in this.errors) { this.WriteError(error); } } } /// <summary> /// Queries the ARM cache and returns the cached resource that match the query specified. /// </summary> private async Task<ResponseWithContinuation<JObject[]>> GetResources() { if (this.IsResourceTypeCollectionGet()) { return await this.ListResourcesTypeCollection().ConfigureAwait(continueOnCapturedContext: false); } if (this.IsResourceGroupLevelQuery()) { return await this.ListResourcesInResourceGroup().ConfigureAwait(continueOnCapturedContext: false); } if (this.IsSubscriptionLevelQuery()) { return await this.ListResourcesInSubscription().ConfigureAwait(continueOnCapturedContext: false); } return await this.ListResourcesInTenant().ConfigureAwait(continueOnCapturedContext: false); } /// <summary> /// Lists resources in a type collection. /// </summary> private async Task<ResponseWithContinuation<JObject[]>> ListResourcesTypeCollection() { var resourceCollectionId = ResourceIdUtility.GetResourceId( subscriptionId: this.SubscriptionId.AsArray().CoalesceEnumerable().Cast<Guid?>().FirstOrDefault(), resourceGroupName: null, resourceType: this.ResourceType, resourceName: null, extensionResourceType: this.ExtensionResourceType, extensionResourceName: null); var apiVersion = await this .DetermineApiVersion(resourceId: resourceCollectionId) .ConfigureAwait(continueOnCapturedContext: false); var odataQuery = QueryFilterBuilder.CreateFilter( resourceType: null, resourceName: null, tagName: this.TagName, tagValue: this.TagValue, filter: this.ODataQuery, resourceGroupNameContains: this.ResourceGroupNameContains, nameContains: this.ResourceNameContains); return await this .GetResourcesClient() .ListObjectColleciton<JObject>( resourceCollectionId: resourceCollectionId, apiVersion: apiVersion, cancellationToken: this.CancellationToken.Value, odataQuery: odataQuery) .ConfigureAwait(continueOnCapturedContext: false); } /// <summary> /// Lists the resources in the tenant. /// </summary> private async Task<ResponseWithContinuation<JObject[]>> ListResourcesInTenant() { var filterQuery = QueryFilterBuilder .CreateFilter( subscriptionIds: new Guid[] { this.SubscriptionId.Value }, resourceGroup: null, resourceType: this.ResourceType, resourceName: null, tagName: this.TagName, tagValue: this.TagValue, filter: this.ODataQuery, resourceGroupNameContains: this.ResourceGroupNameContains, nameContains: this.ResourceNameContains); var apiVersion = await this .DetermineApiVersion(providerNamespace: Constants.MicrosoftResourceNamesapce, resourceType: Constants.ResourceGroups) .ConfigureAwait(continueOnCapturedContext: false); return await this .GetResourcesClient() .ListResources<JObject>( apiVersion: apiVersion, top: this.Top, filter: filterQuery, cancellationToken: this.CancellationToken.Value) .ConfigureAwait(continueOnCapturedContext: false); } /// <summary> /// Lists the resources in a resource group. /// </summary> private async Task<ResponseWithContinuation<JObject[]>> ListResourcesInResourceGroup() { var filterQuery = QueryFilterBuilder .CreateFilter( resourceType: this.ResourceType, resourceName: null, tagName: this.TagName, tagValue: this.TagValue, filter: this.ODataQuery, resourceGroupNameContains: this.ResourceGroupNameContains, nameContains: this.ResourceNameContains); var apiVersion = await this .DetermineApiVersion(providerNamespace: Constants.MicrosoftResourceNamesapce, resourceType: Constants.ResourceGroups) .ConfigureAwait(continueOnCapturedContext: false); return await this .GetResourcesClient() .ListResources<JObject>( subscriptionId: this.SubscriptionId.Value, resourceGroupName: null, apiVersion: apiVersion, top: this.Top, filter: filterQuery, cancellationToken: this.CancellationToken.Value) .ConfigureAwait(continueOnCapturedContext: false); } /// <summary> /// Gets the resources in a subscription. /// </summary> private async Task<ResponseWithContinuation<JObject[]>> ListResourcesInSubscription() { var filterQuery = QueryFilterBuilder .CreateFilter( resourceType: this.ResourceType, resourceName: null, tagName: this.TagName, tagValue: this.TagValue, filter: this.ODataQuery, nameContains: this.ResourceNameContains); var apiVersion = await this .DetermineApiVersion(providerNamespace: Constants.MicrosoftResourceNamesapce, resourceType: Constants.ResourceGroups) .ConfigureAwait(continueOnCapturedContext: false); return await this .GetResourcesClient() .ListResources<JObject>( subscriptionId: this.SubscriptionId.Value, apiVersion: apiVersion, top: this.Top, filter: filterQuery, cancellationToken: this.CancellationToken.Value) .ConfigureAwait(continueOnCapturedContext: false); } /// <summary> /// Gets the next set of resources using the <paramref name="nextLink"/> /// </summary> /// <param name="nextLink">The next link.</param> private Task<ResponseWithContinuation<TType[]>> GetNextLink<TType>(string nextLink) { return this .GetResourcesClient() .ListNextBatch<TType>(nextLink: nextLink, cancellationToken: this.CancellationToken.Value); } /// <summary> /// Populates the properties on an array of resources. /// </summary> /// <param name="resources">The resource.</param> private async Task<Resource<JToken>[]> GetPopulatedResource(IEnumerable<Resource<JToken>> resources) { return await resources .Select(resource => this.GetPopulatedResource(resource)) .WhenAllForAwait() .ConfigureAwait(continueOnCapturedContext: false); } /// <summary> /// Populates the properties of a single resource. /// </summary> /// <param name="resource">The resource.</param> private async Task<Resource<JToken>> GetPopulatedResource(Resource<JToken> resource) { try { var apiVersion = await this.DetermineApiVersion( resourceId: resource.Id, pre: this.Pre) .ConfigureAwait(continueOnCapturedContext: false); return await this .GetResourcesClient() .GetResource<Resource<JToken>>( resourceId: resource.Id, apiVersion: apiVersion, cancellationToken: this.CancellationToken.Value) .ConfigureAwait(continueOnCapturedContext: false); } catch (Exception ex) { if (ex.IsFatal()) { throw; } ex = (ex is AggregateException) ? (ex as AggregateException).Flatten() : ex; this.errors.Add(new ErrorRecord(ex, "ErrorExpandingProperties", ErrorCategory.CloseError, resource)); } return resource; } /// <summary> /// Returns true if this is get on a resource type collection, at any scope. /// </summary> private bool IsResourceTypeCollectionGet() { return (this.TenantLevel) && (this.IsResourceGroupLevelResourceTypeCollectionGet() || this.IsSubscriptionLevelResourceTypeCollectionGet() || this.IsTenantLevelResourceTypeCollectionGet()); } /// <summary> /// Returns true if this is a get on a type collection that is at the subscription level. /// </summary> private bool IsSubscriptionLevelResourceTypeCollectionGet() { return this.SubscriptionId.HasValue && this.ResourceGroupNameContains == null && (this.ResourceType != null || this.ExtensionResourceType != null); } /// <summary> /// Returns true if this is a get on a type collection that is at the resource group. /// </summary> private bool IsResourceGroupLevelResourceTypeCollectionGet() { return this.SubscriptionId.HasValue && this.ResourceGroupNameContains != null && (this.ResourceType != null || this.ExtensionResourceType != null); } /// <summary> /// Returns true if this is a tenant level resource type collection get (a get without a subscription or /// resource group or resource name but with a resource or extension type.) /// </summary> private bool IsTenantLevelResourceTypeCollectionGet() { return this.SubscriptionId == null && this.ResourceGroupNameContains == null && (this.ResourceType != null || this.ExtensionResourceType != null); } /// <summary> /// Returns true if this is a subscription level query. /// </summary> private bool IsSubscriptionLevelQuery() { return this.SubscriptionId.HasValue && this.ResourceGroupNameContains == null; } /// <summary> /// Returns true if this is a resource group level query. /// </summary> private bool IsResourceGroupLevelQuery() { return this.SubscriptionId.HasValue && this.ResourceGroupNameContains != null && (this.TagName != null || this.TagValue != null || this.ResourceType != null || this.ExtensionResourceType != null); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // FirstQueryOperator.cs // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System.Collections.Generic; using System.Diagnostics.Contracts; using System.Threading; namespace System.Linq.Parallel { /// <summary> /// First tries to discover the first element in the source, optionally matching a /// predicate. All partitions search in parallel, publish the lowest index for a /// candidate match, and reach a barrier. Only the partition that "wins" the race, /// i.e. who found the candidate with the smallest index, will yield an element. /// </summary> /// <typeparam name="TSource"></typeparam> internal sealed class FirstQueryOperator<TSource> : UnaryQueryOperator<TSource, TSource> { private readonly Func<TSource, bool> _predicate; // The optional predicate used during the search. private readonly bool _prematureMergeNeeded; // Whether to prematurely merge the input of this operator. //--------------------------------------------------------------------------------------- // Initializes a new first operator. // // Arguments: // child - the child whose data we will reverse // internal FirstQueryOperator(IEnumerable<TSource> child, Func<TSource, bool> predicate) : base(child) { Contract.Assert(child != null, "child data source cannot be null"); _predicate = predicate; _prematureMergeNeeded = Child.OrdinalIndexState.IsWorseThan(OrdinalIndexState.Increasing); } //--------------------------------------------------------------------------------------- // Just opens the current operator, including opening the child and wrapping it with // partitions as needed. // internal override QueryResults<TSource> Open(QuerySettings settings, bool preferStriping) { // We just open the child operator. QueryResults<TSource> childQueryResults = Child.Open(settings, false); return new UnaryQueryOperatorResults(childQueryResults, this, settings, preferStriping); } internal override void WrapPartitionedStream<TKey>( PartitionedStream<TSource, TKey> inputStream, IPartitionedStreamRecipient<TSource> recipient, bool preferStriping, QuerySettings settings) { // If the index is not at least increasing, we need to reindex. if (_prematureMergeNeeded) { ListQueryResults<TSource> listResults = ExecuteAndCollectResults(inputStream, inputStream.PartitionCount, Child.OutputOrdered, preferStriping, settings); WrapHelper<int>(listResults.GetPartitionedStream(), recipient, settings); } else { WrapHelper<TKey>(inputStream, recipient, settings); } } private void WrapHelper<TKey>( PartitionedStream<TSource, TKey> inputStream, IPartitionedStreamRecipient<TSource> recipient, QuerySettings settings) { int partitionCount = inputStream.PartitionCount; // Generate the shared data. FirstQueryOperatorState<TKey> operatorState = new FirstQueryOperatorState<TKey>(); CountdownEvent sharedBarrier = new CountdownEvent(partitionCount); PartitionedStream<TSource, int> outputStream = new PartitionedStream<TSource, int>( partitionCount, Util.GetDefaultComparer<int>(), OrdinalIndexState.Shuffled); for (int i = 0; i < partitionCount; i++) { outputStream[i] = new FirstQueryOperatorEnumerator<TKey>( inputStream[i], _predicate, operatorState, sharedBarrier, settings.CancellationState.MergedCancellationToken, inputStream.KeyComparer, i); } recipient.Receive(outputStream); } //--------------------------------------------------------------------------------------- // Returns an enumerable that represents the query executing sequentially. // internal override IEnumerable<TSource> AsSequentialQuery(CancellationToken token) { Contract.Assert(false, "This method should never be called as fallback to sequential is handled in ParallelEnumerable.First()."); throw new NotSupportedException(); } //--------------------------------------------------------------------------------------- // Whether this operator performs a premature merge that would not be performed in // a similar sequential operation (i.e., in LINQ to Objects). // internal override bool LimitsParallelism { get { return false; } } //--------------------------------------------------------------------------------------- // The enumerator type responsible for executing the first operation. // class FirstQueryOperatorEnumerator<TKey> : QueryOperatorEnumerator<TSource, int> { private QueryOperatorEnumerator<TSource, TKey> _source; // The data source to enumerate. private Func<TSource, bool> _predicate; // The optional predicate used during the search. private bool _alreadySearched; // Set once the enumerator has performed the search. private int _partitionId; // ID of this partition // Data shared among partitions. private FirstQueryOperatorState<TKey> _operatorState; // The current first candidate and its partition index. private CountdownEvent _sharedBarrier; // Shared barrier, signaled when partitions find their 1st element. private CancellationToken _cancellationToken; // Token used to cancel this operator. private IComparer<TKey> _keyComparer; // Comparer for the order keys //--------------------------------------------------------------------------------------- // Instantiates a new enumerator. // internal FirstQueryOperatorEnumerator( QueryOperatorEnumerator<TSource, TKey> source, Func<TSource, bool> predicate, FirstQueryOperatorState<TKey> operatorState, CountdownEvent sharedBarrier, CancellationToken cancellationToken, IComparer<TKey> keyComparer, int partitionId) { Contract.Assert(source != null); Contract.Assert(operatorState != null); Contract.Assert(sharedBarrier != null); Contract.Assert(keyComparer != null); _source = source; _predicate = predicate; _operatorState = operatorState; _sharedBarrier = sharedBarrier; _cancellationToken = cancellationToken; _keyComparer = keyComparer; _partitionId = partitionId; } //--------------------------------------------------------------------------------------- // Straightforward IEnumerator<T> methods. // internal override bool MoveNext(ref TSource currentElement, ref int currentKey) { Contract.Assert(_source != null); if (_alreadySearched) { return false; } // Look for the lowest element. TSource candidate = default(TSource); TKey candidateKey = default(TKey); try { TSource value = default(TSource); TKey key = default(TKey); int i = 0; while (_source.MoveNext(ref value, ref key)) { if ((i++ & CancellationState.POLL_INTERVAL) == 0) CancellationState.ThrowIfCanceled(_cancellationToken); // If the predicate is null or the current element satisfies it, we have found the // current partition's "candidate" for the first element. Note it. if (_predicate == null || _predicate(value)) { candidate = value; candidateKey = key; lock (_operatorState) { if (_operatorState._partitionId == -1 || _keyComparer.Compare(candidateKey, _operatorState._key) < 0) { _operatorState._key = candidateKey; _operatorState._partitionId = _partitionId; } } break; } } } finally { // No matter whether we exit due to an exception or normal completion, we must ensure // that we signal other partitions that we have completed. Otherwise, we can cause deadlocks. _sharedBarrier.Signal(); } _alreadySearched = true; // Wait only if we may have the result if (_partitionId == _operatorState._partitionId) { _sharedBarrier.Wait(_cancellationToken); // Now re-read the shared index. If it's the same as ours, we won and return true. if (_partitionId == _operatorState._partitionId) { currentElement = candidate; currentKey = 0; // 1st (and only) element, so we hardcode the output index to 0. return true; } } // If we got here, we didn't win. Return false. return false; } protected override void Dispose(bool disposing) { _source.Dispose(); } } class FirstQueryOperatorState<TKey> { internal TKey _key; internal int _partitionId = -1; } } }
using System; using System.Collections.ObjectModel; using System.ComponentModel; using System.Globalization; using System.Linq; using Bedrock.Properties; using Bedrock.Regions.Behaviors; using Bedrock.Views; using Microsoft.Practices.ServiceLocation; namespace Bedrock.Regions { /// <summary> /// Implementation of <see cref="IRegion"/> that allows multiple active views. /// </summary> public class RegionBase : IRegion { private ObservableCollection<IView> itemCollection; private ObservableCollection<IView> activatedItemCollection; private string name; private ViewsCollection views; private ViewsCollection activeViews; private object context; private IRegionManager regionManager; /// <summary> /// Initializes a new instance of <see cref="Region"/>. /// </summary> public RegionBase(object control) { this.Behaviors = new RegionBehaviorCollection(this); this.name = GetNamePropertyVal(control); this.Control = control; this.activatedItemCollection = new ObservableCollection<IView>(); } public RegionBase(string name, object control) { this.Behaviors = new RegionBehaviorCollection(this); this.name = name; this.Control = control; this.activatedItemCollection = new ObservableCollection<IView>(); } /// <summary> /// Occurs when a property value changes. /// </summary> public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// Gets the collection of <see cref="IRegionBehavior"/>s that can extend the behavior of regions. /// </summary> public IRegionBehaviorCollection Behaviors { get; private set; } /// <summary> /// Gets or sets a context for the region. This value can be used by the user to share context with the views. /// </summary> /// <value>The context value to be shared.</value> public object Context { get { return this.context; } set { if (this.context != value) { this.context = value; this.OnPropertyChanged("Context"); } } } /// <summary> /// Gets the name of the region that uniequely identifies the region within a <see cref="IRegionManager"/>. /// </summary> /// <value>The name of the region.</value> public string Name { get { return this.name; } set { if (this.name != null && this.name != value) { throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Resources.CannotChangeRegionNameException, this.name)); } if (string.IsNullOrEmpty(value)) { throw new ArgumentException(Resources.RegionNameCannotBeEmptyException); } this.name = value; this.OnPropertyChanged("Name"); } } public object Control { get; set; } /// <summary> /// Gets a readonly view of the collection of views in the region. /// </summary> /// <value>An <see cref="IViewsCollection"/> of all the added views.</value> public virtual IViewsCollection Views { get { if (this.views == null) { this.views = new ViewsCollection(ItemMetadataCollection); } return this.views; } } /// <summary> /// Gets a readonly view of the collection of all the active views in the region. /// </summary> /// <value>An <see cref="IViewsCollection"/> of all the active views.</value> public virtual IViewsCollection ActiveViews { get { if (this.activeViews == null) { this.activeViews = new ViewsCollection(activatedItemCollection); } return this.activeViews; } } /// <summary> /// Gets or sets the <see cref="IRegionManager"/> that will be passed to the views when adding them to the region, unless the view is added by specifying createRegionManagerScope as <see langword="true" />. /// </summary> /// <value>The <see cref="IRegionManager"/> where this <see cref="IRegion"/> is registered.</value> /// <remarks>This is usually used by implementations of <see cref="IRegionManager"/> and should not be /// used by the developer explicitely.</remarks> public IRegionManager RegionManager { get { return this.regionManager; } set { if (this.regionManager != value) { this.regionManager = value; this.OnPropertyChanged("RegionManager"); } } } /// <summary> /// Gets the collection with all the views along with their metadata. /// </summary> /// <value>An <see cref="ObservableCollection{T}"/> of <see cref="ItemMetadata"/> with all the added views.</value> protected virtual ObservableCollection<IView> ItemMetadataCollection { get { if (this.itemCollection == null) { this.itemCollection = new ObservableCollection<IView>(); } return this.itemCollection; } } /// <overloads>Adds a new view to the region.</overloads> /// <summary> /// Adds a new view to the region. /// </summary> /// <param name="view">The view to add.</param> /// <returns>The <see cref="IRegionManager"/> that is set on the view if it is a <see cref="DependencyObject"/>. It will be the current region manager when using this overload.</returns> public IRegionManager Add(IView view) { return this.Add(view, view.Name, false); } /// <summary> /// Adds a new view to the region. /// </summary> /// <param name="view">The view to add.</param> /// <param name="viewName">The name of the view. This can be used to retrieve it later by calling <see cref="IRegion.GetView"/>.</param> /// <returns>The <see cref="IRegionManager"/> that is set on the view if it is a <see cref="DependencyObject"/>. It will be the current region manager when using this overload.</returns> public IRegionManager Add(IView view, string viewName) { if (string.IsNullOrEmpty(viewName)) { throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Resources.StringCannotBeNullOrEmpty, "viewName")); } return this.Add(view, viewName, false); } /// <summary> /// Adds a new view to the region. /// </summary> /// <param name="view">The view to add.</param> /// <param name="viewName">The name of the view. This can be used to retrieve it later by calling <see cref="IRegion.GetView"/>.</param> /// <param name="createRegionManagerScope">When <see langword="true"/>, the added view will receive a new instance of <see cref="IRegionManager"/>, otherwise it will use the current region manager for this region.</param> /// <returns>The <see cref="IRegionManager"/> that is set on the view if it is a <see cref="DependencyObject"/>.</returns> public virtual IRegionManager Add(IView view, string viewName, bool createRegionManagerScope) { if (GetView(viewName) != null) { throw new InvalidOperationException(Resources.ViewAlreadyExistsInRegion); } view.Name = viewName; IRegionManager manager = createRegionManagerScope ? this.RegionManager.CreateRegionManager() : this.RegionManager; this.ItemMetadataCollection.Add(view); return manager; } public void RemoveAllViews() { foreach (IView view in Views) { Deactivate(view); ActiveViews.Remove(view); Views.Remove(view); } } /// <summary> /// Removes the specified view from the region. /// </summary> /// <param name="view">The view to remove.</param> public virtual void Remove(IView view) { this.ItemMetadataCollection.Remove(view); ActiveViews.Remove(view); Views.Remove(view); } /// <summary> /// Marks the specified view as active. /// </summary> /// <param name="view">The view to activate.</param> public virtual void Activate(IView view) { if (view == null) { throw new ArgumentNullException(Resources.ViewShouldNotBeNull); } if (GetView(view.Name) == null) { throw new ArgumentException(Resources.ViewNotInRegionException); } ActiveViews.Add(view); } public void Activate() { foreach (IView view in Views) { Activate(view); } } /// <summary> /// Marks the specified view as inactive. /// </summary> /// <param name="view">The view to deactivate.</param> public virtual void Deactivate(IView view) { if (view == null) { throw new ArgumentNullException(Resources.ViewShouldNotBeNull); } if (GetView(view.Name) == null) { throw new ArgumentException(Resources.ViewNotInRegionException); } ActiveViews.Remove(view); } public void Deactivate() { foreach (IView view in Views) { Deactivate(view); } } /// <summary> /// Returns the view instance that was added to the region using a specific name. /// </summary> /// <param name="viewName">The name used when adding the view to the region.</param> /// <returns>Returns the named view or <see langword="null"/> if the view with <paramref name="viewName"/> does not exist in the current region.</returns> public virtual IView GetView(string viewName) { if (string.IsNullOrEmpty(viewName)) { throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Resources.StringCannotBeNullOrEmpty, "viewName")); } return ItemMetadataCollection.FirstOrDefault(x => x.Name == viewName); } private void OnPropertyChanged(string propertyName) { PropertyChangedEventHandler eventHandler = this.PropertyChanged; if (eventHandler != null) { eventHandler(this, new PropertyChangedEventArgs(propertyName)); } } private string GetNamePropertyVal(object control) { var nameProperty = control.GetType().GetProperty("Name"); if (nameProperty == null) { throw new ArgumentNullException(Resources.CannotFindNameProperty); } var val = nameProperty.GetValue(control); if (val == null) { throw new ArgumentNullException(Resources.NameValueOfControlIsNull); } return val.ToString(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using PRoCon.Core; using PRoCon.Core.Plugin; using PRoCon.Core.Plugin.Commands; using PRoCon.Core.Players; namespace PRoConEvents { class SamplePlugin : PRoConPluginAPI, IPRoConPluginInterface { private bool pluginEnabled; private bool debug = false; public SamplePlugin() { } #region Console Methods public enum ConsoleMessageType { Warning, Error, Exception, Normal, Debug }; private string FormatMessage(string msg, ConsoleMessageType type) { string prefix = "[^b" + GetPluginName() + "^n] "; switch (type) { case ConsoleMessageType.Warning: prefix += "^1^bWARNING^0^n: "; break; case ConsoleMessageType.Error: prefix += "^1^bERROR^0^n: "; break; case ConsoleMessageType.Exception: prefix += "^1^bEXCEPTION^0^n: "; break; case ConsoleMessageType.Debug: prefix += "^1^bDEBUG^0^n: "; break; } return prefix + msg; } public void LogWrite(string msg) { this.ExecuteCommand("procon.protected.pluginconsole.write", msg); } public void ConsoleWrite(string msg, ConsoleMessageType type) { LogWrite(FormatMessage(msg, type)); } public void ConsoleWrite(string msg) { ConsoleWrite(msg, ConsoleMessageType.Normal); } public void ConsoleDebug(string msg) { if (debug) ConsoleWrite(msg, ConsoleMessageType.Debug); } public void ConsoleWarn(string msg) { ConsoleWrite(msg, ConsoleMessageType.Warning); } public void ConsoleError(string msg) { ConsoleWrite(msg, ConsoleMessageType.Error); } public void ConsoleException(string msg) { ConsoleWrite(msg, ConsoleMessageType.Exception); } public void AdminSayAll(string msg) { if (debug) ConsoleDebug("Saying to all: " + msg); foreach (string s in splitMessage(msg, 128)) this.ExecuteCommand("procon.protected.send", "admin.say", s, "all"); } public void AdminSayTeam(string msg, int teamID) { if (debug) ConsoleDebug("Saying to Team " + teamID + ": " + msg); foreach (string s in splitMessage(msg, 128)) this.ExecuteCommand("procon.protected.send", "admin.say", s, "team", string.Concat(teamID)); } public void AdminSaySquad(string msg, int teamID, int squadID) { if (debug) ConsoleDebug("Saying to Squad " + squadID + " in Team " + teamID + ": " + msg); foreach (string s in splitMessage(msg, 128)) this.ExecuteCommand("procon.protected.send", "admin.say", s, "squad", string.Concat(teamID), string.Concat(squadID)); } public void AdminSayPlayer(string msg, string player) { if (debug) ConsoleDebug("Saying to player '" + player + "': " + msg); foreach (string s in splitMessage(msg, 128)) this.ExecuteCommand("procon.protected.send", "admin.say", s, "player", player); } public void AdminYellAll(string msg) { AdminYellAll(msg, 10); } public void AdminYellAll(string msg, int duration) { if (msg.Length > 256) ConsoleError("AdminYell msg > 256. msg: " + msg); if (debug) ConsoleDebug("Yelling to all: " + msg); this.ExecuteCommand("procon.protected.send", "admin.yell", msg, string.Concat(duration), "all"); } public void AdminYellTeam(string msg, int teamID) { AdminYellTeam(msg, teamID, 10); } public void AdminYellTeam(string msg, int teamID, int duration) { if (msg.Length > 256) ConsoleError("AdminYell msg > 256. msg: " + msg); if (debug) ConsoleDebug("Yelling to Team " + teamID + ": " + msg); this.ExecuteCommand("procon.protected.send", "admin.yell", msg, string.Concat(duration), "team", string.Concat(teamID)); } public void AdminYellSquad(string msg, int teamID, int squadID) { AdminYellSquad(msg, teamID, squadID, 10); } public void AdminYellSquad(string msg, int teamID, int squadID, int duration) { if (msg.Length > 256) ConsoleError("AdminYell msg > 256. msg: " + msg); if (debug) ConsoleDebug("Yelling to Squad " + squadID + " in Team " + teamID + ": " + msg); this.ExecuteCommand("procon.protected.send", "admin.yell", msg, string.Concat(duration), "squad", string.Concat(teamID), string.Concat(squadID)); } public void AdminYellPlayer(string msg, string player) { AdminYellPlayer(msg, player, 10); } public void AdminYellPlayer(string msg, string player, int duration) { if (msg.Length > 256) ConsoleError("AdminYell msg > 256. msg: " + msg); if (debug) ConsoleDebug("Yelling to player '" + player + "': " + msg); this.ExecuteCommand("procon.protected.send", "admin.yell", msg, string.Concat(duration), "player", player); } // This method splits the given string if it exceeds the maxSize by, in order of precedence: newlines, end-of-sentence punctuation marks, commas, spaces, or arbitrarily.</p> private static List<string> splitMessage(string message, int maxSize) { List<string> messages = new List<string>(message.Replace("\r", "").Trim().Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries)); for (int a = 0; a < messages.Count; a++) { messages[a] = messages[a].Trim(); if (messages[a] == "") { messages.RemoveAt(a); a--; continue; } if (messages[a][0] == '/') messages[a] = ' ' + messages[a]; string msg = messages[a]; if (msg.Length > maxSize) { List<int> splitOptions = new List<int>(); int split = -1; do { split = msg.IndexOfAny(new char[] { '.', '!', '?', ';' }, split + 1); if (split != -1 && split != msg.Length - 1) splitOptions.Add(split); } while (split != -1); if (splitOptions.Count > 2) split = splitOptions[(int)Math.Round(splitOptions.Count / 2.0)] + 1; else if (splitOptions.Count > 0) split = splitOptions[0] + 1; else { split = msg.IndexOf(','); if (split == -1) { split = msg.IndexOf(' ', msg.Length / 2); if (split == -1) { split = msg.IndexOf(' '); if (split == -1) split = maxSize / 2; } } } messages[a] = msg.Substring(0, split).Trim(); messages.Insert(a + 1, msg.Substring(split).Trim()); a--; } } return messages; } #endregion #region Plugin Config public string GetPluginName() { return "Sample Plugin Template"; } public string GetPluginVersion() { return "0.0.0"; } public string GetPluginAuthor() { return "author"; } public string GetPluginWebsite() { return "purebattlefield.org"; } public string GetPluginDescription() { return @" <h1>Your Title Here</h1> <p>TBD</p> <h2>Description</h2> <p>TBD</p> <h2>Commands</h2> <p>TBD</p> <h2>Settings</h2> <p>TBD</p> <h2>Development</h2> <p>TBD</p> <h3>Changelog</h3> <blockquote><h4>1.0.0.0 (15-SEP-2012)</h4> - initial version<br/> </blockquote> "; } public void OnPluginLoaded(string strHostName, string strPort, string strPRoConVersion) { this.RegisterEvents(this.GetType().Name, /* list of event method names */); } public void OnPluginEnable() { this.pluginEnabled = true; ConsoleWrite("^2" + GetPluginName() + " Enabled"); } public void OnPluginDisable() { this.pluginEnabled = false; ConsoleWrite("^8" + GetPluginName() + " Disabled"); } #endregion public List<CPluginVariable> GetDisplayPluginVariables() { List<CPluginVariable> variables = new List<CPluginVariable>(); variables.Add(new CPluginVariable("Debug", typeof(bool), debug)); return variables; } public List<CPluginVariable> GetPluginVariables() { return GetDisplayPluginVariables(); } public void SetPluginVariable(string variable, string value) { if (variable.Equals("Debug")) debug = bool.Parse(value); } } }
// SigatureParser.cs // Script#/Core/ScriptSharp // Copyright (c) Nikhil Kothari. // Copyright (c) Microsoft Corporation. // This source code is subject to terms and conditions of the Microsoft // Public License. A copy of the license can be found in License.txt. // using System; using System.Diagnostics; using System.Runtime.InteropServices; using System.Text; using ScriptSharp; using ScriptSharp.ScriptModel; namespace ScriptSharp.Importer { internal sealed class SignatureParser { private SymbolSet _symbols; private ICompilerErrorHandler _errorHandler; private Interop.IMetadataImport _mdImport; private IntPtr _signatureBytes; private int _signatureLength; private int _signatureIndex; public SignatureParser(SymbolSet symbols, ICompilerErrorHandler errorHandler) { _symbols = symbols; _errorHandler = errorHandler; } private bool CanRead { get { return (_signatureIndex < _signatureLength); } } public TypeSymbol Parse(Interop.IMetadataImport mdImport, IntPtr signatureBytes, int signatureLength) { bool dummy; return Parse(mdImport, signatureBytes, signatureLength, out dummy); } public TypeSymbol Parse(Interop.IMetadataImport mdImport, IntPtr signatureBytes, int signatureLength, out bool isIndexer) { _mdImport = mdImport; _signatureBytes = signatureBytes; _signatureLength = signatureLength; _signatureIndex = 0; isIndexer = false; byte signatureMarker = Read(); byte typeMarker = (byte)(signatureMarker & 0xF); switch (typeMarker) { case Interop.SIG_FIELD: return ParseField(); case Interop.SIG_PROPERTY: return ParseProperty(out isIndexer); case Interop.SIG_METHOD_DEFAULT: case Interop.SIG_METHOD_C: case Interop.SIG_METHOD_THISCALL: case Interop.SIG_METHOD_VARARG: case Interop.SIG_METHOD_STDCALL: case Interop.SIG_METHOD_FASTCALL: bool isGeneric = ((signatureMarker & Interop.SIG_GENERIC) != 0); return ParseMethod(isGeneric); default: // TODO: Error Debug.Fail("Unexpected signature type"); return null; } } private TypeSymbol ParseField() { return ReadType(); } private TypeSymbol ParseMethod(bool isGeneric) { if (isGeneric) { int genericArguments = ReadNumber(); } // Skip parameter count ReadNumber(); byte typeMarker = Peek(); if (typeMarker == Interop.ELEMENT_TYPE_VOID) { Read(); TypeSymbol typeSymbol = (TypeSymbol)((ISymbolTable)_symbols.SystemNamespace).FindSymbol("Void", null, SymbolFilter.Types); Debug.Assert(typeSymbol != null); return typeSymbol; } return ReadType(); } private TypeSymbol ParseProperty(out bool isIndexer) { int parameterCount = ReadNumber(); isIndexer = (parameterCount != 0); return ReadType(); } private byte Peek() { return Marshal.ReadByte(_signatureBytes, _signatureIndex); } private byte Read() { Debug.Assert(CanRead); byte b = Marshal.ReadByte(_signatureBytes, _signatureIndex); _signatureIndex++; return b; } private TypeSymbol ReadArray() { TypeSymbol itemTypeSymbol = ReadType(); if (itemTypeSymbol != null) { return TypeSymbol.CreateArrayType(itemTypeSymbol, _symbols); } return null; } private TypeSymbol ReadClass() { int encodedToken = ReadNumber(); byte tokenType = (byte)(encodedToken & 0x3); int index = (encodedToken >> 2); StringBuilder nameBuilder = null; Debug.Assert((tokenType == Interop.SIG_INDEX_TYPE_TYPEDEF) || (tokenType == Interop.SIG_INDEX_TYPE_TYPEREF)); if (tokenType == Interop.SIG_INDEX_TYPE_TYPEDEF) { int typeNameLength; int typeFlags; int typeExtendsToken; int token = index | (int)Interop.CorTokenType.mdtTypeDef; _mdImport.GetTypeDefProps(token, null, 0, out typeNameLength, out typeFlags, out typeExtendsToken); nameBuilder = new StringBuilder(typeNameLength); _mdImport.GetTypeDefProps(token, nameBuilder, typeNameLength, out typeNameLength, out typeFlags, out typeExtendsToken); } else if (tokenType == Interop.SIG_INDEX_TYPE_TYPEREF) { int typeNameLength; int scopeToken; int token = index | (int)Interop.CorTokenType.mdtTypeRef; _mdImport.GetTypeRefProps(token, out scopeToken, null, 0, out typeNameLength); nameBuilder = new StringBuilder(typeNameLength); _mdImport.GetTypeRefProps(token, out scopeToken, nameBuilder, typeNameLength, out typeNameLength); } Debug.Assert(nameBuilder != null); string typeName = nameBuilder.ToString(); TypeSymbol typeSymbol = (TypeSymbol)((ISymbolTable)_symbols).FindSymbol(typeName, null, SymbolFilter.Types); Debug.Assert(typeSymbol != null); return typeSymbol; } private int ReadNumber() { byte b1 = Read(); if (b1 == 0xFF) { // Special encoding of NULL return 0; } if ((b1 & 0x80) == 0) { // 1-byte encoding return (int)b1; } byte b2 = Read(); if ((b1 & 0x40) == 0) { // 2-byte encoding return (((b1 & 0x3F) << 8) | b2); } // 4-byte encoding Debug.Assert((b1 & 0x20) == 0); byte b3 = Read(); byte b4 = Read(); return (((b1 & 0x1F) << 24) | (b2 << 16) | (b3 << 8) | b4); } private TypeSymbol ReadType() { byte typeMarker = Read(); string typeName = null; switch (typeMarker) { case Interop.ELEMENT_TYPE_BOOLEAN: typeName = "Boolean"; break; case Interop.ELEMENT_TYPE_CHAR: typeName = "Char"; break; case Interop.ELEMENT_TYPE_I1: typeName = "SByte"; break; case Interop.ELEMENT_TYPE_U1: typeName = "Byte"; break; case Interop.ELEMENT_TYPE_I2: typeName = "Int16"; break; case Interop.ELEMENT_TYPE_U2: typeName = "UInt16"; break; case Interop.ELEMENT_TYPE_I4: typeName = "Int32"; break; case Interop.ELEMENT_TYPE_U4: typeName = "UInt32"; break; case Interop.ELEMENT_TYPE_I8: typeName = "Int64"; break; case Interop.ELEMENT_TYPE_U8: typeName = "UInt64"; break; case Interop.ELEMENT_TYPE_I: typeName = "IntPtr"; break; case Interop.ELEMENT_TYPE_U: typeName = "UIntPtr"; break; case Interop.ELEMENT_TYPE_R4: typeName = "Single"; break; case Interop.ELEMENT_TYPE_R8: typeName = "Double"; break; case Interop.ELEMENT_TYPE_STRING: typeName = "String"; break; case Interop.ELEMENT_TYPE_OBJECT: typeName = "Object"; break; case Interop.ELEMENT_TYPE_CLASS: case Interop.ELEMENT_TYPE_VALUETYPE: return ReadClass(); case Interop.ELEMENT_TYPE_SZARRAY: return ReadArray(); case Interop.ELEMENT_TYPE_PTR: case Interop.ELEMENT_TYPE_FNPTR: case Interop.ELEMENT_TYPE_GENERICINST: case Interop.ELEMENT_TYPE_VAR: case Interop.ELEMENT_TYPE_ARRAY: // TODO: Error handler Debug.Fail("Unsupported types"); break; case Interop.ELEMENT_TYPE_MVAR: typeName = "Object"; break; default: Debug.Fail("Unexpected type"); break; } if (typeName != null) { TypeSymbol typeSymbol = (TypeSymbol)((ISymbolTable)_symbols.SystemNamespace).FindSymbol(typeName, null, SymbolFilter.Types); Debug.Assert(typeSymbol != null); if (typeMarker == Interop.ELEMENT_TYPE_MVAR) { int genericArgIndex = ReadNumber(); typeSymbol = new GenericTypeSymbol(genericArgIndex, (NamespaceSymbol)typeSymbol.Parent); } return typeSymbol; } // TODO: Error handler return null; } } }
// // 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.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Hyak.Common; using Microsoft.Azure; using Microsoft.Azure.Management.Automation; using Microsoft.Azure.Management.Automation.Models; using Newtonsoft.Json.Linq; namespace Microsoft.Azure.Management.Automation { /// <summary> /// Service operation for automation schedules. (see /// http://aka.ms/azureautomationsdk/scheduleoperations for more /// information) /// </summary> internal partial class ScheduleOperations : IServiceOperations<AutomationManagementClient>, IScheduleOperations { /// <summary> /// Initializes a new instance of the ScheduleOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal ScheduleOperations(AutomationManagementClient client) { this._client = client; } private AutomationManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.Azure.Management.Automation.AutomationManagementClient. /// </summary> public AutomationManagementClient Client { get { return this._client; } } /// <summary> /// Create a schedule. (see /// http://aka.ms/azureautomationsdk/scheduleoperations for more /// information) /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='parameters'> /// Required. The parameters supplied to the create or update schedule /// operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response model for the create or update schedule operation. /// </returns> public async Task<ScheduleCreateOrUpdateResponse> CreateOrUpdateAsync(string resourceGroupName, string automationAccount, ScheduleCreateOrUpdateParameters parameters, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (automationAccount == null) { throw new ArgumentNullException("automationAccount"); } if (parameters == null) { throw new ArgumentNullException("parameters"); } if (parameters.Name == null) { throw new ArgumentNullException("parameters.Name"); } if (parameters.Properties == null) { throw new ArgumentNullException("parameters.Properties"); } if (parameters.Properties.Frequency == null) { throw new ArgumentNullException("parameters.Properties.Frequency"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("automationAccount", automationAccount); 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 + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; if (this.Client.ResourceNamespace != null) { url = url + Uri.EscapeDataString(this.Client.ResourceNamespace); } url = url + "/automationAccounts/"; url = url + Uri.EscapeDataString(automationAccount); url = url + "/schedules/"; url = url + Uri.EscapeDataString(parameters.Name); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-10-31"); 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"); httpRequest.Headers.Add("x-ms-version", "2014-06-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; JToken requestDoc = null; JObject scheduleCreateOrUpdateParametersValue = new JObject(); requestDoc = scheduleCreateOrUpdateParametersValue; scheduleCreateOrUpdateParametersValue["name"] = parameters.Name; JObject propertiesValue = new JObject(); scheduleCreateOrUpdateParametersValue["properties"] = propertiesValue; if (parameters.Properties.Description != null) { propertiesValue["description"] = parameters.Properties.Description; } propertiesValue["startTime"] = parameters.Properties.StartTime; if (parameters.Properties.ExpiryTime != null) { propertiesValue["expiryTime"] = parameters.Properties.ExpiryTime.Value; } if (parameters.Properties.Interval != null) { propertiesValue["interval"] = parameters.Properties.Interval.Value; } propertiesValue["frequency"] = parameters.Properties.Frequency; requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Created) { 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 ScheduleCreateOrUpdateResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Created) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ScheduleCreateOrUpdateResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { Schedule scheduleInstance = new Schedule(); result.Schedule = scheduleInstance; JToken idValue = responseDoc["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); scheduleInstance.Id = idInstance; } JToken nameValue = responseDoc["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); scheduleInstance.Name = nameInstance; } JToken propertiesValue2 = responseDoc["properties"]; if (propertiesValue2 != null && propertiesValue2.Type != JTokenType.Null) { ScheduleProperties propertiesInstance = new ScheduleProperties(); scheduleInstance.Properties = propertiesInstance; JToken startTimeValue = propertiesValue2["startTime"]; if (startTimeValue != null && startTimeValue.Type != JTokenType.Null) { DateTimeOffset startTimeInstance = ((DateTimeOffset)startTimeValue); propertiesInstance.StartTime = startTimeInstance; } JToken expiryTimeValue = propertiesValue2["expiryTime"]; if (expiryTimeValue != null && expiryTimeValue.Type != JTokenType.Null) { DateTimeOffset expiryTimeInstance = ((DateTimeOffset)expiryTimeValue); propertiesInstance.ExpiryTime = expiryTimeInstance; } JToken isEnabledValue = propertiesValue2["isEnabled"]; if (isEnabledValue != null && isEnabledValue.Type != JTokenType.Null) { bool isEnabledInstance = ((bool)isEnabledValue); propertiesInstance.IsEnabled = isEnabledInstance; } JToken nextRunValue = propertiesValue2["nextRun"]; if (nextRunValue != null && nextRunValue.Type != JTokenType.Null) { DateTimeOffset nextRunInstance = ((DateTimeOffset)nextRunValue); propertiesInstance.NextRun = nextRunInstance; } JToken intervalValue = propertiesValue2["interval"]; if (intervalValue != null && intervalValue.Type != JTokenType.Null) { byte intervalInstance = ((byte)intervalValue); propertiesInstance.Interval = intervalInstance; } JToken frequencyValue = propertiesValue2["frequency"]; if (frequencyValue != null && frequencyValue.Type != JTokenType.Null) { string frequencyInstance = ((string)frequencyValue); propertiesInstance.Frequency = frequencyInstance; } JToken creationTimeValue = propertiesValue2["creationTime"]; if (creationTimeValue != null && creationTimeValue.Type != JTokenType.Null) { DateTimeOffset creationTimeInstance = ((DateTimeOffset)creationTimeValue); propertiesInstance.CreationTime = creationTimeInstance; } JToken lastModifiedTimeValue = propertiesValue2["lastModifiedTime"]; if (lastModifiedTimeValue != null && lastModifiedTimeValue.Type != JTokenType.Null) { DateTimeOffset lastModifiedTimeInstance = ((DateTimeOffset)lastModifiedTimeValue); propertiesInstance.LastModifiedTime = lastModifiedTimeInstance; } JToken descriptionValue = propertiesValue2["description"]; if (descriptionValue != null && descriptionValue.Type != JTokenType.Null) { string descriptionInstance = ((string)descriptionValue); propertiesInstance.Description = descriptionInstance; } } } } 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> /// Delete the schedule identified by schedule name. (see /// http://aka.ms/azureautomationsdk/scheduleoperations for more /// information) /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='scheduleName'> /// Required. The schedule name. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public async Task<AzureOperationResponse> DeleteAsync(string resourceGroupName, string automationAccount, string scheduleName, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (automationAccount == null) { throw new ArgumentNullException("automationAccount"); } if (scheduleName == null) { throw new ArgumentNullException("scheduleName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("automationAccount", automationAccount); tracingParameters.Add("scheduleName", scheduleName); TracingAdapter.Enter(invocationId, this, "DeleteAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; if (this.Client.ResourceNamespace != null) { url = url + Uri.EscapeDataString(this.Client.ResourceNamespace); } url = url + "/automationAccounts/"; url = url + Uri.EscapeDataString(automationAccount); url = url + "/schedules/"; url = url + Uri.EscapeDataString(scheduleName); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-10-31"); 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"); httpRequest.Headers.Add("x-ms-version", "2014-06-01"); // 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 AzureOperationResponse result = null; // Deserialize Response result = new AzureOperationResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Retrieve the schedule identified by schedule name. (see /// http://aka.ms/azureautomationsdk/scheduleoperations for more /// information) /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='scheduleName'> /// Required. The schedule name. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response model for the get schedule operation. /// </returns> public async Task<ScheduleGetResponse> GetAsync(string resourceGroupName, string automationAccount, string scheduleName, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (automationAccount == null) { throw new ArgumentNullException("automationAccount"); } if (scheduleName == null) { throw new ArgumentNullException("scheduleName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("automationAccount", automationAccount); tracingParameters.Add("scheduleName", scheduleName); TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; if (this.Client.ResourceNamespace != null) { url = url + Uri.EscapeDataString(this.Client.ResourceNamespace); } url = url + "/automationAccounts/"; url = url + Uri.EscapeDataString(automationAccount); url = url + "/schedules/"; url = url + Uri.EscapeDataString(scheduleName); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-10-31"); 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"); httpRequest.Headers.Add("x-ms-version", "2014-06-01"); // 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 ScheduleGetResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ScheduleGetResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { Schedule scheduleInstance = new Schedule(); result.Schedule = scheduleInstance; JToken idValue = responseDoc["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); scheduleInstance.Id = idInstance; } JToken nameValue = responseDoc["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); scheduleInstance.Name = nameInstance; } JToken propertiesValue = responseDoc["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { ScheduleProperties propertiesInstance = new ScheduleProperties(); scheduleInstance.Properties = propertiesInstance; JToken startTimeValue = propertiesValue["startTime"]; if (startTimeValue != null && startTimeValue.Type != JTokenType.Null) { DateTimeOffset startTimeInstance = ((DateTimeOffset)startTimeValue); propertiesInstance.StartTime = startTimeInstance; } JToken expiryTimeValue = propertiesValue["expiryTime"]; if (expiryTimeValue != null && expiryTimeValue.Type != JTokenType.Null) { DateTimeOffset expiryTimeInstance = ((DateTimeOffset)expiryTimeValue); propertiesInstance.ExpiryTime = expiryTimeInstance; } JToken isEnabledValue = propertiesValue["isEnabled"]; if (isEnabledValue != null && isEnabledValue.Type != JTokenType.Null) { bool isEnabledInstance = ((bool)isEnabledValue); propertiesInstance.IsEnabled = isEnabledInstance; } JToken nextRunValue = propertiesValue["nextRun"]; if (nextRunValue != null && nextRunValue.Type != JTokenType.Null) { DateTimeOffset nextRunInstance = ((DateTimeOffset)nextRunValue); propertiesInstance.NextRun = nextRunInstance; } JToken intervalValue = propertiesValue["interval"]; if (intervalValue != null && intervalValue.Type != JTokenType.Null) { byte intervalInstance = ((byte)intervalValue); propertiesInstance.Interval = intervalInstance; } JToken frequencyValue = propertiesValue["frequency"]; if (frequencyValue != null && frequencyValue.Type != JTokenType.Null) { string frequencyInstance = ((string)frequencyValue); propertiesInstance.Frequency = frequencyInstance; } JToken creationTimeValue = propertiesValue["creationTime"]; if (creationTimeValue != null && creationTimeValue.Type != JTokenType.Null) { DateTimeOffset creationTimeInstance = ((DateTimeOffset)creationTimeValue); propertiesInstance.CreationTime = creationTimeInstance; } JToken lastModifiedTimeValue = propertiesValue["lastModifiedTime"]; if (lastModifiedTimeValue != null && lastModifiedTimeValue.Type != JTokenType.Null) { DateTimeOffset lastModifiedTimeInstance = ((DateTimeOffset)lastModifiedTimeValue); propertiesInstance.LastModifiedTime = lastModifiedTimeInstance; } JToken descriptionValue = propertiesValue["description"]; if (descriptionValue != null && descriptionValue.Type != JTokenType.Null) { string descriptionInstance = ((string)descriptionValue); propertiesInstance.Description = descriptionInstance; } } } } 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> /// Retrieve a list of schedules. (see /// http://aka.ms/azureautomationsdk/scheduleoperations for more /// information) /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response model for the list schedule operation. /// </returns> public async Task<ScheduleListResponse> ListAsync(string resourceGroupName, string automationAccount, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (automationAccount == null) { throw new ArgumentNullException("automationAccount"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("automationAccount", automationAccount); TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; if (this.Client.ResourceNamespace != null) { url = url + Uri.EscapeDataString(this.Client.ResourceNamespace); } url = url + "/automationAccounts/"; url = url + Uri.EscapeDataString(automationAccount); url = url + "/schedules"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-10-31"); 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"); httpRequest.Headers.Add("ocp-referer", url); httpRequest.Headers.Add("x-ms-version", "2014-06-01"); // 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 ScheduleListResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ScheduleListResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { Schedule scheduleInstance = new Schedule(); result.Schedules.Add(scheduleInstance); JToken idValue = valueValue["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); scheduleInstance.Id = idInstance; } JToken nameValue = valueValue["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); scheduleInstance.Name = nameInstance; } JToken propertiesValue = valueValue["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { ScheduleProperties propertiesInstance = new ScheduleProperties(); scheduleInstance.Properties = propertiesInstance; JToken startTimeValue = propertiesValue["startTime"]; if (startTimeValue != null && startTimeValue.Type != JTokenType.Null) { DateTimeOffset startTimeInstance = ((DateTimeOffset)startTimeValue); propertiesInstance.StartTime = startTimeInstance; } JToken expiryTimeValue = propertiesValue["expiryTime"]; if (expiryTimeValue != null && expiryTimeValue.Type != JTokenType.Null) { DateTimeOffset expiryTimeInstance = ((DateTimeOffset)expiryTimeValue); propertiesInstance.ExpiryTime = expiryTimeInstance; } JToken isEnabledValue = propertiesValue["isEnabled"]; if (isEnabledValue != null && isEnabledValue.Type != JTokenType.Null) { bool isEnabledInstance = ((bool)isEnabledValue); propertiesInstance.IsEnabled = isEnabledInstance; } JToken nextRunValue = propertiesValue["nextRun"]; if (nextRunValue != null && nextRunValue.Type != JTokenType.Null) { DateTimeOffset nextRunInstance = ((DateTimeOffset)nextRunValue); propertiesInstance.NextRun = nextRunInstance; } JToken intervalValue = propertiesValue["interval"]; if (intervalValue != null && intervalValue.Type != JTokenType.Null) { byte intervalInstance = ((byte)intervalValue); propertiesInstance.Interval = intervalInstance; } JToken frequencyValue = propertiesValue["frequency"]; if (frequencyValue != null && frequencyValue.Type != JTokenType.Null) { string frequencyInstance = ((string)frequencyValue); propertiesInstance.Frequency = frequencyInstance; } JToken creationTimeValue = propertiesValue["creationTime"]; if (creationTimeValue != null && creationTimeValue.Type != JTokenType.Null) { DateTimeOffset creationTimeInstance = ((DateTimeOffset)creationTimeValue); propertiesInstance.CreationTime = creationTimeInstance; } JToken lastModifiedTimeValue = propertiesValue["lastModifiedTime"]; if (lastModifiedTimeValue != null && lastModifiedTimeValue.Type != JTokenType.Null) { DateTimeOffset lastModifiedTimeInstance = ((DateTimeOffset)lastModifiedTimeValue); propertiesInstance.LastModifiedTime = lastModifiedTimeInstance; } JToken descriptionValue = propertiesValue["description"]; if (descriptionValue != null && descriptionValue.Type != JTokenType.Null) { string descriptionInstance = ((string)descriptionValue); propertiesInstance.Description = descriptionInstance; } } } } JToken odatanextLinkValue = responseDoc["odata.nextLink"]; if (odatanextLinkValue != null && odatanextLinkValue.Type != JTokenType.Null) { string odatanextLinkInstance = Regex.Match(((string)odatanextLinkValue), "^.*[&\\?]\\$skiptoken=([^&]*)(&.*)?").Groups[1].Value; result.SkipToken = odatanextLinkInstance; } JToken nextLinkValue = responseDoc["nextLink"]; if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null) { string nextLinkInstance = ((string)nextLinkValue); result.NextLink = nextLinkInstance; } } } 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> /// Retrieve next list of schedules. (see /// http://aka.ms/azureautomationsdk/scheduleoperations for more /// information) /// </summary> /// <param name='nextLink'> /// Required. The link to retrieve next set of items. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response model for the list schedule operation. /// </returns> public async Task<ScheduleListResponse> ListNextAsync(string nextLink, CancellationToken cancellationToken) { // Validate if (nextLink == null) { throw new ArgumentNullException("nextLink"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextLink", nextLink); TracingAdapter.Enter(invocationId, this, "ListNextAsync", tracingParameters); } // Construct URL string url = ""; url = url + nextLink; 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"); httpRequest.Headers.Add("ocp-referer", url); httpRequest.Headers.Add("x-ms-version", "2014-06-01"); // 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 ScheduleListResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ScheduleListResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { Schedule scheduleInstance = new Schedule(); result.Schedules.Add(scheduleInstance); JToken idValue = valueValue["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); scheduleInstance.Id = idInstance; } JToken nameValue = valueValue["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); scheduleInstance.Name = nameInstance; } JToken propertiesValue = valueValue["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { ScheduleProperties propertiesInstance = new ScheduleProperties(); scheduleInstance.Properties = propertiesInstance; JToken startTimeValue = propertiesValue["startTime"]; if (startTimeValue != null && startTimeValue.Type != JTokenType.Null) { DateTimeOffset startTimeInstance = ((DateTimeOffset)startTimeValue); propertiesInstance.StartTime = startTimeInstance; } JToken expiryTimeValue = propertiesValue["expiryTime"]; if (expiryTimeValue != null && expiryTimeValue.Type != JTokenType.Null) { DateTimeOffset expiryTimeInstance = ((DateTimeOffset)expiryTimeValue); propertiesInstance.ExpiryTime = expiryTimeInstance; } JToken isEnabledValue = propertiesValue["isEnabled"]; if (isEnabledValue != null && isEnabledValue.Type != JTokenType.Null) { bool isEnabledInstance = ((bool)isEnabledValue); propertiesInstance.IsEnabled = isEnabledInstance; } JToken nextRunValue = propertiesValue["nextRun"]; if (nextRunValue != null && nextRunValue.Type != JTokenType.Null) { DateTimeOffset nextRunInstance = ((DateTimeOffset)nextRunValue); propertiesInstance.NextRun = nextRunInstance; } JToken intervalValue = propertiesValue["interval"]; if (intervalValue != null && intervalValue.Type != JTokenType.Null) { byte intervalInstance = ((byte)intervalValue); propertiesInstance.Interval = intervalInstance; } JToken frequencyValue = propertiesValue["frequency"]; if (frequencyValue != null && frequencyValue.Type != JTokenType.Null) { string frequencyInstance = ((string)frequencyValue); propertiesInstance.Frequency = frequencyInstance; } JToken creationTimeValue = propertiesValue["creationTime"]; if (creationTimeValue != null && creationTimeValue.Type != JTokenType.Null) { DateTimeOffset creationTimeInstance = ((DateTimeOffset)creationTimeValue); propertiesInstance.CreationTime = creationTimeInstance; } JToken lastModifiedTimeValue = propertiesValue["lastModifiedTime"]; if (lastModifiedTimeValue != null && lastModifiedTimeValue.Type != JTokenType.Null) { DateTimeOffset lastModifiedTimeInstance = ((DateTimeOffset)lastModifiedTimeValue); propertiesInstance.LastModifiedTime = lastModifiedTimeInstance; } JToken descriptionValue = propertiesValue["description"]; if (descriptionValue != null && descriptionValue.Type != JTokenType.Null) { string descriptionInstance = ((string)descriptionValue); propertiesInstance.Description = descriptionInstance; } } } } JToken odatanextLinkValue = responseDoc["odata.nextLink"]; if (odatanextLinkValue != null && odatanextLinkValue.Type != JTokenType.Null) { string odatanextLinkInstance = Regex.Match(((string)odatanextLinkValue), "^.*[&\\?]\\$skiptoken=([^&]*)(&.*)?").Groups[1].Value; result.SkipToken = odatanextLinkInstance; } JToken nextLinkValue = responseDoc["nextLink"]; if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null) { string nextLinkInstance = ((string)nextLinkValue); result.NextLink = nextLinkInstance; } } } 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> /// Update the schedule identified by schedule name. (see /// http://aka.ms/azureautomationsdk/scheduleoperations for more /// information) /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='parameters'> /// Required. The parameters supplied to the patch schedule operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public async Task<AzureOperationResponse> PatchAsync(string resourceGroupName, string automationAccount, SchedulePatchParameters parameters, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (automationAccount == null) { throw new ArgumentNullException("automationAccount"); } if (parameters == null) { throw new ArgumentNullException("parameters"); } if (parameters.Name == null) { throw new ArgumentNullException("parameters.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("resourceGroupName", resourceGroupName); tracingParameters.Add("automationAccount", automationAccount); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "PatchAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; if (this.Client.ResourceNamespace != null) { url = url + Uri.EscapeDataString(this.Client.ResourceNamespace); } url = url + "/automationAccounts/"; url = url + Uri.EscapeDataString(automationAccount); url = url + "/schedules/"; url = url + Uri.EscapeDataString(parameters.Name); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-10-31"); 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 = new HttpMethod("PATCH"); httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept", "application/json"); httpRequest.Headers.Add("x-ms-version", "2014-06-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; JToken requestDoc = null; JObject schedulePatchParametersValue = new JObject(); requestDoc = schedulePatchParametersValue; schedulePatchParametersValue["name"] = parameters.Name; if (parameters.Properties != null) { JObject propertiesValue = new JObject(); schedulePatchParametersValue["properties"] = propertiesValue; if (parameters.Properties.Description != null) { propertiesValue["description"] = parameters.Properties.Description; } if (parameters.Properties.IsEnabled != null) { propertiesValue["isEnabled"] = parameters.Properties.IsEnabled.Value; } } requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { 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 AzureOperationResponse result = null; // Deserialize Response result = new AzureOperationResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
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 AprEstadoNacimiento class. /// </summary> [Serializable] public partial class AprEstadoNacimientoCollection : ActiveList<AprEstadoNacimiento, AprEstadoNacimientoCollection> { public AprEstadoNacimientoCollection() {} /// <summary> /// Filters an existing collection based on the set criteria. This is an in-memory filter /// Thanks to developingchris for this! /// </summary> /// <returns>AprEstadoNacimientoCollection</returns> public AprEstadoNacimientoCollection Filter() { for (int i = this.Count - 1; i > -1; i--) { AprEstadoNacimiento o = this[i]; foreach (SubSonic.Where w in this.wheres) { bool remove = false; System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName); if (pi.CanRead) { object val = pi.GetValue(o, null); switch (w.Comparison) { case SubSonic.Comparison.Equals: if (!val.Equals(w.ParameterValue)) { remove = true; } break; } } if (remove) { this.Remove(o); break; } } } return this; } } /// <summary> /// This is an ActiveRecord class which wraps the APR_EstadoNacimiento table. /// </summary> [Serializable] public partial class AprEstadoNacimiento : ActiveRecord<AprEstadoNacimiento>, IActiveRecord { #region .ctors and Default Settings public AprEstadoNacimiento() { SetSQLProps(); InitSetDefaults(); MarkNew(); } private void InitSetDefaults() { SetDefaults(); } public AprEstadoNacimiento(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) ForceDefaults(); MarkNew(); } public AprEstadoNacimiento(object keyID) { SetSQLProps(); InitSetDefaults(); LoadByKey(keyID); } public AprEstadoNacimiento(string columnName, object columnValue) { SetSQLProps(); InitSetDefaults(); LoadByParam(columnName,columnValue); } protected static void SetSQLProps() { GetTableSchema(); } #endregion #region Schema and Query Accessor public static Query CreateQuery() { return new Query(Schema); } public static TableSchema.Table Schema { get { if (BaseSchema == null) SetSQLProps(); return BaseSchema; } } private static void GetTableSchema() { if(!IsSchemaInitialized) { //Schema declaration TableSchema.Table schema = new TableSchema.Table("APR_EstadoNacimiento", TableType.Table, DataService.GetInstance("sicProvider")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarIdEstadoNacimiento = new TableSchema.TableColumn(schema); colvarIdEstadoNacimiento.ColumnName = "idEstadoNacimiento"; colvarIdEstadoNacimiento.DataType = DbType.Int32; colvarIdEstadoNacimiento.MaxLength = 0; colvarIdEstadoNacimiento.AutoIncrement = true; colvarIdEstadoNacimiento.IsNullable = false; colvarIdEstadoNacimiento.IsPrimaryKey = true; colvarIdEstadoNacimiento.IsForeignKey = false; colvarIdEstadoNacimiento.IsReadOnly = false; colvarIdEstadoNacimiento.DefaultSetting = @""; colvarIdEstadoNacimiento.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdEstadoNacimiento); TableSchema.TableColumn colvarNombre = new TableSchema.TableColumn(schema); colvarNombre.ColumnName = "nombre"; colvarNombre.DataType = DbType.AnsiString; colvarNombre.MaxLength = 50; colvarNombre.AutoIncrement = false; colvarNombre.IsNullable = false; colvarNombre.IsPrimaryKey = false; colvarNombre.IsForeignKey = false; colvarNombre.IsReadOnly = false; colvarNombre.DefaultSetting = @""; colvarNombre.ForeignKeyTableName = ""; schema.Columns.Add(colvarNombre); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["sicProvider"].AddSchema("APR_EstadoNacimiento",schema); } } #endregion #region Props [XmlAttribute("IdEstadoNacimiento")] [Bindable(true)] public int IdEstadoNacimiento { get { return GetColumnValue<int>(Columns.IdEstadoNacimiento); } set { SetColumnValue(Columns.IdEstadoNacimiento, value); } } [XmlAttribute("Nombre")] [Bindable(true)] public string Nombre { get { return GetColumnValue<string>(Columns.Nombre); } set { SetColumnValue(Columns.Nombre, value); } } #endregion //no foreign key tables defined (0) //no ManyToMany tables defined (0) #region ObjectDataSource support /// <summary> /// Inserts a record, can be used with the Object Data Source /// </summary> public static void Insert(string varNombre) { AprEstadoNacimiento item = new AprEstadoNacimiento(); item.Nombre = varNombre; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } /// <summary> /// Updates a record, can be used with the Object Data Source /// </summary> public static void Update(int varIdEstadoNacimiento,string varNombre) { AprEstadoNacimiento item = new AprEstadoNacimiento(); item.IdEstadoNacimiento = varIdEstadoNacimiento; item.Nombre = varNombre; item.IsNew = false; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } #endregion #region Typed Columns public static TableSchema.TableColumn IdEstadoNacimientoColumn { get { return Schema.Columns[0]; } } public static TableSchema.TableColumn NombreColumn { get { return Schema.Columns[1]; } } #endregion #region Columns Struct public struct Columns { public static string IdEstadoNacimiento = @"idEstadoNacimiento"; public static string Nombre = @"nombre"; } #endregion #region Update PK Collections #endregion #region Deep Save #endregion } }
#region LGPL License /* Axiom Game Engine Library Copyright (C) 2003 Axiom Project Team The overall design, and a majority of the core engine and rendering code contained within this library is a derivative of the open source Object Oriented Graphics Engine OGRE, which can be found at http://ogre.sourceforge.net. Many thanks to the OGRE team for maintaining such a high quality project. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #endregion using System; using System.Diagnostics; using System.Collections.Generic; using System.Runtime.InteropServices; using Axiom.Core; using Axiom.Graphics; using Axiom.MathLib; namespace Axiom.Core { /// <summary> /// A surface which is defined by curves of some kind to form a patch, e.g. a Bezier patch. /// </summary> /// <remarks> /// This object will take a list of control points with various assorted data, and will /// subdivide it into a patch mesh. Currently only Bezier curves are supported for defining /// the surface, but other techniques such as NURBS would follow the same basic approach. /// </remarks> public class PatchSurface { #region Fields /// <summary> /// Vertex declaration describing the control point buffer. /// </summary> protected VertexDeclaration declaration; /// <summary> /// Buffer containing the system-memory control points. /// </summary> protected System.Array controlPointBuffer; /// <summary> /// Type of surface. /// </summary> protected PatchSurfaceType type; /// <summary> /// Width in control points. /// </summary> protected int controlWidth; /// <summary> /// Height in control points. /// </summary> protected int controlHeight; /// <summary> /// Total number of control level. /// </summary> protected int controlCount; /// <summary> /// U-direction subdivision level. /// </summary> protected int uLevel; /// <summary> /// V-direction subdivision level. /// </summary> protected int vLevel; /// <summary> /// Max U subdivision level. /// </summary> protected int maxULevel; /// <summary> /// Max V subdivision level. /// </summary> protected int maxVLevel; /// <summary> /// Width of the subdivided mesh (big enough for max level). /// </summary> protected int meshWidth; /// <summary> /// Height of the subdivided mesh (big enough for max level). /// </summary> protected int meshHeight; /// <summary> /// Which side is visible. /// </summary> protected VisibleSide side; /// <summary> /// Mesh subdivision factor. /// </summary> protected float subdivisionFactor; /// <summary> /// List of control points. /// </summary> protected List<Vector3> controlPoints = new List<Vector3>(); protected HardwareVertexBuffer vertexBuffer; protected HardwareIndexBuffer indexBuffer; protected int vertexOffset; protected int indexOffset; protected int requiredVertexCount; protected int requiredIndexCount; protected int currentIndexCount; protected AxisAlignedBox aabb = AxisAlignedBox.Null; protected float boundingSphereRadius; /// <summary> /// Constant for indicating automatic determination of subdivision level for patches. /// </summary> const int AUTO_LEVEL = -1; #endregion Fields #region Constructor /// <summary> /// Default contructor. /// </summary> public PatchSurface() { type = PatchSurfaceType.Bezier; } #endregion Constructor #region Methods /// <summary> /// Sets up the surface by defining it's control points, type and initial subdivision level. /// </summary> /// <remarks> /// This method initialises the surface by passing it a set of control points. The type of curves to be used /// are also defined here, although the only supported option currently is a bezier patch. You can also /// specify a global subdivision level here if you like, although it is recommended that the parameter /// is left as AUTO_LEVEL, which means the system decides how much subdivision is required (based on the /// curvature of the surface). /// </remarks> /// <param name="controlPoints"> /// A pointer to a buffer containing the vertex data which defines control points /// of the curves rather than actual vertices. Note that you are expected to provide not /// just position information, but potentially normals and texture coordinates too. The /// format of the buffer is defined in the VertexDeclaration parameter. /// </param> /// <param name="decl"> /// VertexDeclaration describing the contents of the buffer. /// Note this declaration must _only_ draw on buffer source 0! /// </param> /// <param name="width">Specifies the width of the patch in control points.</param> /// <param name="height">Specifies the height of the patch in control points.</param> /// <param name="type">The type of surface.</param> /// <param name="uMaxSubdivisionLevel"> /// If you want to manually set the top level of subdivision, /// do it here, otherwise let the system decide. /// </param> /// <param name="vMaxSubdivisionLevel"> /// If you want to manually set the top level of subdivision, /// do it here, otherwise let the system decide. /// </param> /// <param name="side">Determines which side of the patch (or both) triangles are generated for.</param> public unsafe void DefineSurface(System.Array controlPointBuffer, VertexDeclaration declaration, int width, int height, PatchSurfaceType type, int uMaxSubdivisionLevel, int vMaxSubdivisionLevel, VisibleSide visibleSide) { if (height == 0 || width == 0) { return; // Do nothing - garbage } this.type = type; this.controlWidth = width; this.controlHeight = height; this.controlCount = width * height; this.controlPointBuffer = controlPointBuffer; this.declaration = declaration; // Copy positions into Vector3 vector controlPoints.Clear(); VertexElement elem = declaration.FindElementBySemantic(VertexElementSemantic.Position); int vertSize = declaration.GetVertexSize(0); byte *pVert = (byte*)Marshal.UnsafeAddrOfPinnedArrayElement(controlPointBuffer, 0); float* pReal = null; for (int i = 0; i < controlCount; i++) { pReal = (float*)(pVert + elem.Offset); controlPoints.Add(new Vector3(pReal[0], pReal[1], pReal[2])); pVert += vertSize; } this.side = visibleSide; // Determine max level // Initialise to 100% detail subdivisionFactor = 1.0f; if (uMaxSubdivisionLevel == AUTO_LEVEL) { uLevel = maxULevel = GetAutoULevel(); } else { uLevel = maxULevel = uMaxSubdivisionLevel; } if (vMaxSubdivisionLevel == AUTO_LEVEL) { vLevel = maxVLevel = GetAutoVLevel(); } else { vLevel = maxVLevel = vMaxSubdivisionLevel; } // Derive mesh width / height meshWidth = (LevelWidth(maxULevel) - 1) * ((controlWidth-1) / 2) + 1; meshHeight = (LevelWidth(maxVLevel) - 1) * ((controlHeight-1) / 2) + 1; // Calculate number of required vertices / indexes at max resolution requiredVertexCount = meshWidth * meshHeight; int iterations = (side == VisibleSide.Both)? 2 : 1; requiredIndexCount = (meshWidth-1) * (meshHeight - 1) * 2 * iterations * 3; // Calculate bounds based on control points Vector3 min = Vector3.Zero; Vector3 max = Vector3.Zero; float maxSqRadius = 0.0f; bool first = true; for(int i = 0; i < controlPoints.Count; i++) { Vector3 vec = controlPoints[i]; if (first) { min = max = vec; maxSqRadius = vec.LengthSquared; first = false; } else { min.Floor(vec); max.Ceil(vec); maxSqRadius = MathUtil.Max(vec.LengthSquared, maxSqRadius); } } // set the bounds of the patch aabb.SetExtents(min, max); boundingSphereRadius = MathUtil.Sqrt(maxSqRadius); } /// <summary> /// Sets up the surface by defining it's control points, type and initial subdivision level. /// </summary> /// <remarks> /// This method initialises the surface by passing it a set of control points. The type of curves to be used /// are also defined here, although the only supported option currently is a bezier patch. You can also /// specify a global subdivision level here if you like, although it is recommended that the parameter /// is left as AUTO_LEVEL, which means the system decides how much subdivision is required (based on the /// curvature of the surface). /// </remarks> /// <param name="controlPoints"> /// A pointer to a buffer containing the vertex data which defines control points /// of the curves rather than actual vertices. Note that you are expected to provide not /// just position information, but potentially normals and texture coordinates too. The /// format of the buffer is defined in the VertexDeclaration parameter. /// </param> /// <param name="decl"> /// VertexDeclaration describing the contents of the buffer. /// Note this declaration must _only_ draw on buffer source 0! /// </param> /// <param name="width">Specifies the width of the patch in control points.</param> /// <param name="height">Specifies the height of the patch in control points.</param> /// <param name="type">The type of surface.</param> /// <param name="uMaxSubdivision"> /// If you want to manually set the top level of subdivision, /// do it here, otherwise let the system decide. /// </param> /// <param name="vMaxSubdivision"> /// If you want to manually set the top level of subdivision, /// do it here, otherwise let the system decide. /// </param> /// <param name="side">Determines which side of the patch (or both) triangles are generated for.</param> public void DefineSurface(System.Array controlPoints, VertexDeclaration decl, int width, int height) { DefineSurface(controlPoints, decl, width, height, PatchSurfaceType.Bezier, AUTO_LEVEL, AUTO_LEVEL, VisibleSide.Front); } /// <summary> /// Tells the system to build the mesh relating to the surface into externally created buffers. /// </summary> /// <remarks> /// The VertexDeclaration of the vertex buffer must be identical to the one passed into /// <see cref="DefineSurface"/>. In addition, there must be enough space in the buffer to /// accommodate the patch at full detail level; you should check <see cref="RequiredVertexCount"/> /// and <see cref="RequiredIndexCount"/> to determine this. This method does not create an internal /// mesh for this patch and so GetMesh will return null if you call it after building the /// patch this way. /// </remarks> /// <param name="destVertexBuffer">The destination vertex buffer in which to build the patch.</param> /// <param name="vertexStart">The offset at which to start writing vertices for this patch.</param> /// <param name="destIndexBuffer">The destination index buffer in which to build the patch.</param> /// <param name="indexStart">The offset at which to start writing indexes for this patch.</param> public void Build(HardwareVertexBuffer destVertexBuffer, int vertexStart, HardwareIndexBuffer destIndexBuffer, int indexStart) { if(controlPoints.Count == 0) { return; } vertexBuffer = destVertexBuffer; vertexOffset = vertexStart; indexBuffer = destIndexBuffer; indexOffset = indexStart; // lock just the region we are interested in IntPtr lockedBuffer = vertexBuffer.Lock( vertexOffset * declaration.GetVertexSize(0), requiredVertexCount * declaration.GetVertexSize(0), BufferLocking.NoOverwrite); DistributeControlPoints(lockedBuffer); // subdivide the curves to the max // Do u direction first, so need to step over v levels not done yet int vStep = 1 << maxVLevel; int uStep = 1 << maxULevel; // subdivide this row in u for(int v = 0; v < meshHeight; v += vStep) { SubdivideCurve(lockedBuffer, v * meshWidth, uStep, meshWidth / uStep, uLevel); } // Now subdivide in v direction, this time all the u direction points are there so no step for(int u = 0; u < meshWidth; u++) { SubdivideCurve(lockedBuffer, u, vStep * meshWidth, meshHeight / vStep, vLevel); } // don't forget to unlock! vertexBuffer.Unlock(); // Make triangles from mesh at this current level of detail MakeTriangles(); } /// <summary> /// Internal method for finding the subdivision level given 3 control points. /// </summary> /// <param name="a">First control point.</param> /// <param name="b">Second control point.</param> /// <param name="c">Third control point.</param> /// <returns></returns> protected int FindLevel(ref Vector3 a, ref Vector3 b, ref Vector3 c) { // Derived from work by Bart Sekura in rogl // Apart from I think I fixed a bug - see below // I also commented the code, the only thing wrong with rogl is almost no comments!! const int maxLevels = 5; const float subdiv = 10; int level; float test = subdiv * subdiv; Vector3 s = Vector3.Zero; Vector3 t = Vector3.Zero; Vector3 d = Vector3.Zero; for(level=0; level < maxLevels - 1; level++) { // Subdivide the 2 lines s = a.MidPoint(b); t = b.MidPoint(c); // Find the midpoint between the 2 midpoints c = s.MidPoint(t); // Get the vector between this subdivided midpoint and the middle point of the original line d = c - b; // Find the squared length, and break when small enough if(d.Dot(d) < test) { break; } b = a; } return level; } /// <summary> /// /// </summary> /// <param name="lockedBuffer"></param> protected unsafe void DistributeControlPoints(IntPtr lockedBuffer) { // Insert original control points into expanded mesh int uStep = 1 << uLevel; int vStep = 1 << vLevel; void* pSrc = Marshal.UnsafeAddrOfPinnedArrayElement(controlPointBuffer, 0).ToPointer(); void* pDest; int vertexSize = declaration.GetVertexSize(0); float* pSrcReal, pDestReal; int* pSrcRGBA, pDestRGBA; VertexElement elemPos = declaration.FindElementBySemantic(VertexElementSemantic.Position); VertexElement elemNorm = declaration.FindElementBySemantic(VertexElementSemantic.Normal); VertexElement elemTex0 = declaration.FindElementBySemantic(VertexElementSemantic.TexCoords, 0); VertexElement elemTex1 = declaration.FindElementBySemantic(VertexElementSemantic.TexCoords, 1); VertexElement elemDiffuse = declaration.FindElementBySemantic(VertexElementSemantic.Diffuse); for (int v = 0; v < meshHeight; v += vStep) { // set dest by v from base pDest = (void*)((byte*)(lockedBuffer.ToPointer()) + (vertexSize * meshWidth * v)); for (int u = 0; u < meshWidth; u += uStep) { // Copy Position pSrcReal = (float*)((byte*)pSrc + elemPos.Offset); pDestReal = (float*)((byte*)pDest + elemPos.Offset); *pDestReal++ = *pSrcReal++; *pDestReal++ = *pSrcReal++; *pDestReal++ = *pSrcReal++; // Copy Normals if (elemNorm != null) { pSrcReal = (float*)((byte*)pSrc + elemNorm.Offset); pDestReal = (float*)((byte*)pDest + elemNorm.Offset); *pDestReal++ = *pSrcReal++; *pDestReal++ = *pSrcReal++; *pDestReal++ = *pSrcReal++; } // Copy Diffuse if (elemDiffuse != null) { pSrcRGBA = (int*)((byte*)pSrc + elemDiffuse.Offset); pDestRGBA = (int*)((byte*)pDest + elemDiffuse.Offset); *pDestRGBA++ = *pSrcRGBA++; } // Copy texture coords if (elemTex0 != null) { pSrcReal = (float*)((byte*)pSrc + elemTex0.Offset); pDestReal = (float*)((byte*)pDest + elemTex0.Offset); for (int dim = 0; dim < VertexElement.GetTypeCount(elemTex0.Type); dim++) { *pDestReal++ = *pSrcReal++; } } if (elemTex1 != null) { pSrcReal = (float*)((byte*)pSrc + elemTex1.Offset); pDestReal = (float*)((byte*)pDest + elemTex1.Offset); for (int dim = 0; dim < VertexElement.GetTypeCount(elemTex1.Type); dim++) { *pDestReal++ = *pSrcReal++; } } // Increment source by one vertex pSrc = (void*)((byte*)(pSrc) + vertexSize); // Increment dest by 1 vertex * uStep pDest = (void*)((byte*)(pDest) + (vertexSize * uStep)); } // u } // v } /// <summary> /// /// </summary> /// <param name="lockedBuffer"></param> /// <param name="startIdx"></param> /// <param name="stepSize"></param> /// <param name="numSteps"></param> /// <param name="iterations"></param> protected void SubdivideCurve(IntPtr lockedBuffer, int startIdx, int stepSize, int numSteps, int iterations) { // Subdivides a curve within a sparsely populated buffer (gaps are already there to be interpolated into) int leftIdx, rightIdx, destIdx, halfStep, maxIdx; bool firstSegment; maxIdx = startIdx + (numSteps * stepSize); int step = stepSize; while(iterations-- > 0) { halfStep = step / 2; leftIdx = startIdx; destIdx = leftIdx + halfStep; rightIdx = leftIdx + step; firstSegment = true; while (leftIdx < maxIdx) { // Interpolate InterpolateVertexData(lockedBuffer, leftIdx, rightIdx, destIdx); // If 2nd or more segment, interpolate current left between current and last mid points if (!firstSegment) { InterpolateVertexData(lockedBuffer, leftIdx - halfStep, leftIdx + halfStep, leftIdx); } // Next segment leftIdx = rightIdx; destIdx = leftIdx + halfStep; rightIdx = leftIdx + step; firstSegment = false; } step = halfStep; } } /// <summary> /// /// </summary> /// <param name="lockedBuffer"></param> /// <param name="leftIndex"></param> /// <param name="rightIndex"></param> /// <param name="destIndex"></param> protected unsafe void InterpolateVertexData(IntPtr lockedBuffer, int leftIndex, int rightIndex, int destIndex) { int vertexSize = declaration.GetVertexSize(0); VertexElement elemPos = declaration.FindElementBySemantic(VertexElementSemantic.Position); VertexElement elemNorm = declaration.FindElementBySemantic(VertexElementSemantic.Normal); VertexElement elemDiffuse = declaration.FindElementBySemantic(VertexElementSemantic.Diffuse); VertexElement elemTex0 = declaration.FindElementBySemantic(VertexElementSemantic.TexCoords, 0); VertexElement elemTex1 = declaration.FindElementBySemantic(VertexElementSemantic.TexCoords, 1); float* pDestReal, pLeftReal, pRightReal; byte* pDestChar, pLeftChar, pRightChar; byte* pDest, pLeft, pRight; // Set up pointers & interpolate pDest = ((byte*)(lockedBuffer.ToPointer()) + (vertexSize * destIndex)); pLeft = ((byte*)(lockedBuffer.ToPointer()) + (vertexSize * leftIndex)); pRight = ((byte*)(lockedBuffer.ToPointer()) + (vertexSize * rightIndex)); // Position pDestReal = (float*)((byte*)pDest + elemPos.Offset); pLeftReal = (float*)((byte*)pLeft + elemPos.Offset); pRightReal = (float*)((byte*)pRight + elemPos.Offset); *pDestReal++ = (*pLeftReal++ + *pRightReal++) * 0.5f; *pDestReal++ = (*pLeftReal++ + *pRightReal++) * 0.5f; *pDestReal++ = (*pLeftReal++ + *pRightReal++) * 0.5f; if (elemNorm != null) { // Normals pDestReal = (float*)((byte*)pDest + elemNorm.Offset); pLeftReal = (float*)((byte*)pLeft + elemNorm.Offset); pRightReal = (float*)((byte*)pRight + elemNorm.Offset); Vector3 norm = Vector3.Zero; norm.x = (*pLeftReal++ + *pRightReal++) * 0.5f; norm.y = (*pLeftReal++ + *pRightReal++) * 0.5f; norm.z = (*pLeftReal++ + *pRightReal++) * 0.5f; norm.Normalize(); *pDestReal++ = norm.x; *pDestReal++ = norm.y; *pDestReal++ = norm.z; } if (elemDiffuse != null) { // Blend each byte individually pDestChar = (byte*)(pDest + elemDiffuse.Offset); pLeftChar = (byte*)(pLeft + elemDiffuse.Offset); pRightChar = (byte*)(pRight + elemDiffuse.Offset); // 4 bytes to RGBA *pDestChar++ = (byte)(((*pLeftChar++) + (*pRightChar++)) * 0.5f); *pDestChar++ = (byte)(((*pLeftChar++) + (*pRightChar++)) * 0.5f); *pDestChar++ = (byte)(((*pLeftChar++) + (*pRightChar++)) * 0.5f); *pDestChar++ = (byte)(((*pLeftChar++) + (*pRightChar++)) * 0.5f); } if (elemTex0 != null) { // Blend each byte individually pDestReal = (float*)((byte*)pDest + elemTex0.Offset); pLeftReal = (float*)((byte*)pLeft + elemTex0.Offset); pRightReal = (float*)((byte*)pRight + elemTex0.Offset); for (int dim = 0; dim < VertexElement.GetTypeCount(elemTex0.Type); dim++) { *pDestReal++ = ((*pLeftReal++) + (*pRightReal++)) * 0.5f; } } if (elemTex1 != null) { // Blend each byte individually pDestReal = (float*)((byte*)pDest + elemTex1.Offset); pLeftReal = (float*)((byte*)pLeft + elemTex1.Offset); pRightReal = (float*)((byte*)pRight + elemTex1.Offset); for (int dim = 0; dim < VertexElement.GetTypeCount(elemTex1.Type); dim++) { *pDestReal++ = ((*pLeftReal++) + (*pRightReal++)) * 0.5f; } } } /// <summary> /// /// </summary> protected unsafe void MakeTriangles() { // Our vertex buffer is subdivided to the highest level, we need to generate tris // which step over the vertices we don't need for this level of detail. // Calculate steps int vStep = 1 << (maxVLevel - vLevel); int uStep = 1 << (maxULevel - uLevel); int currentWidth = (LevelWidth(uLevel)-1) * ((controlWidth - 1) / 2) + 1; int currentHeight = (LevelWidth(vLevel)-1) * ((controlHeight - 1) / 2) + 1; bool use32bitindexes = (indexBuffer.Type == IndexType.Size32); // The mesh is built, just make a list of indexes to spit out the triangles int vInc, uInc; int vCount, uCount, v, u, iterations; if (side == VisibleSide.Both) { iterations = 2; vInc = vStep; v = 0; // Start with front } else { iterations = 1; if (side == VisibleSide.Front) { vInc = vStep; v = 0; } else { vInc = -vStep; v = meshHeight - 1; } } // Calc num indexes currentIndexCount = (currentWidth - 1) * (currentHeight - 1) * 6 * iterations; int v1, v2, v3; int count = 0; // Lock just the section of the buffer we need IntPtr shortBuffer = IntPtr.Zero; IntPtr intBuffer = IntPtr.Zero; short* p16 = null; int* p32 = null; if (use32bitindexes) { intBuffer = indexBuffer.Lock( indexOffset * sizeof(int), requiredIndexCount * sizeof(int), BufferLocking.NoOverwrite); p32 = (int*)intBuffer.ToPointer(); } else { shortBuffer = indexBuffer.Lock( indexOffset * sizeof(short), requiredIndexCount * sizeof(short), BufferLocking.NoOverwrite); p16 = (short*)shortBuffer.ToPointer(); } while (iterations-- > 0) { // Make tris in a zigzag pattern (compatible with strips) u = 0; uInc = uStep; // Start with moving +u vCount = currentHeight - 1; while (vCount-- > 0) { uCount = currentWidth - 1; while (uCount-- > 0) { // First Tri in cell // ----------------- v1 = ((v + vInc) * meshWidth) + u; v2 = (v * meshWidth) + u; v3 = ((v + vInc) * meshWidth) + (u + uInc); // Output indexes if (use32bitindexes) { p32[count++] = v1; p32[count++] = v2; p32[count++] = v3; } else { p16[count++] = (short)v1; p16[count++] = (short)v2; p16[count++] = (short)v3; } // Second Tri in cell // ------------------ v1 = ((v + vInc) * meshWidth) + (u + uInc); v2 = (v * meshWidth) + u; v3 = (v * meshWidth) + (u + uInc); // Output indexes if (use32bitindexes) { p32[count++] = v1; p32[count++] = v2; p32[count++] = v3; } else { p16[count++] = (short)v1; p16[count++] = (short)v2; p16[count++] = (short)v3; } // Next column u += uInc; } // Next row v += vInc; u = 0; } // Reverse vInc for double sided v = meshHeight - 1; vInc = -vInc; } // don't forget to unlock! indexBuffer.Unlock(); } /// <summary> /// /// </summary> /// <param name="forMax"></param> /// <returns></returns> protected int GetAutoULevel() { return GetAutoULevel(false); } /// <summary> /// /// </summary> /// <param name="forMax"></param> /// <returns></returns> protected int GetAutoULevel(bool forMax) { // determine levels // Derived from work by Bart Sekura in Rogl Vector3 a = Vector3.Zero; Vector3 b = Vector3.Zero; Vector3 c = Vector3.Zero; bool found = false; // Find u level for(int v = 0; v < controlHeight; v++) { for(int u = 0; u < controlWidth-1; u += 2) { a = controlPoints[v * controlWidth + u + 0]; b = controlPoints[v * controlWidth + u + 1]; c = controlPoints[v * controlWidth + u + 2]; if(a != c) { found = true; break; } } if(found) { break; } } if(!found) { throw new AxiomException("Can't find suitable control points for determining U subdivision level"); } return FindLevel(ref a, ref b, ref c); } /// <summary> /// /// </summary> /// <param name="forMax"></param> /// <returns></returns> protected int GetAutoVLevel() { return GetAutoVLevel(false); } /// <summary> /// /// </summary> /// <param name="forMax"></param> /// <returns></returns> protected int GetAutoVLevel(bool forMax) { Vector3 a = Vector3.Zero; Vector3 b = Vector3.Zero; Vector3 c = Vector3.Zero; bool found=false; for(int u = 0; u < controlWidth; u++) { for(int v = 0; v < controlHeight - 1; v += 2) { a = controlPoints[v * controlWidth + u]; b = controlPoints[(v + 1) * controlWidth + u]; c = controlPoints[(v + 2) * controlWidth + u]; if(a != c) { found=true; break; } } if(found) { break; } } if(!found) { throw new AxiomException("Can't find suitable control points for determining U subdivision level"); } return FindLevel(ref a, ref b, ref c); } protected int LevelWidth(int level) { return (1 << (level + 1)) + 1; } #endregion Methods #region Properties /// <summary> /// Based on a previous call to <see cref="DefineSurface"/>, establishes the number of vertices required /// to hold this patch at the maximum detail level. /// </summary> /// <remarks> /// This is useful when you wish to build the patch into external vertex / index buffers. /// </remarks> public int RequiredVertexCount { get { return requiredVertexCount; } } /// <summary> /// Based on a previous call to <see cref="DefineSurface"/>, establishes the number of indexes required /// to hold this patch at the maximum detail level. /// </summary> public int RequiredIndexCount { get { return requiredIndexCount; } } /// <summary> /// Gets the current index count based on the current subdivision level. /// </summary> public int CurrentIndexCount { get { return currentIndexCount; } } /// <summary> /// Returns the index offset used by this buffer to write data into the buffer. /// </summary> public int IndexOffset { get { return indexOffset; } } /// <summary> /// Returns the vertex offset used by this buffer to write data into the buffer. /// </summary> public int VertexOffset { get { return vertexOffset; } } /// <summary> /// Gets the bounds of this patch, only valid after calling <see cref="DefineSurface"/>. /// </summary> public AxisAlignedBox Bounds { get { return aabb; } } /// <summary> /// Gets the radius of the bounding sphere for this patch, only valid after <see cref="DefineSurface"/> /// has been called. /// </summary> public float BoundingSphereRadius { get { return boundingSphereRadius; } } /// <summary> /// Gets/Sets the level of subdivision for this surface. /// </summary> /// <remarks> /// This method changes the proportionate detail level of the patch; since /// the U and V directions can have different subdivision levels, this property /// takes a single float value where 0 is the minimum detail (the control points) /// and 1 is the maximum detail level as supplied to the original call to /// <see cref="DefineSurface"/>. /// </remarks> public float SubdivisionFactor { get { return subdivisionFactor; } set { Debug.Assert(value >= 0.0f && value <= 1.0f); subdivisionFactor = value; uLevel = (int)(subdivisionFactor * maxULevel); vLevel = (int)(subdivisionFactor * maxVLevel); MakeTriangles(); } } /// <summary> /// Gets the control point buffer being used for this patch surface. /// </summary> public System.Array ControlPointBuffer { get { return controlPointBuffer; } } #endregion Properties } /// <summary> /// /// </summary> public enum VisibleSide { /// <summary> /// The side from which u goes right and v goes up (as in texture coords). /// </summary> Front, /// <summary> /// The side from which u goes right and v goes down (reverse of texture coords). /// </summary> Back, /// <summary> /// Both sides are visible - warning this creates 2x the number of triangles and adds /// extra overhead for calculating normals. /// </summary> Both } /// <summary> /// A patch defined by a set of bezier curves. /// </summary> public enum PatchSurfaceType { Bezier } }
// // OciCalls.cs // // Part of the Mono class libraries at // mcs/class/System.Data.OracleClient/System.Data.OracleClient.Oci // // Assembly: System.Data.OracleClient.dll // Namespace: System.Data.OracleClient.Oci // // Authors: Joerg Rosenkranz <[email protected]> // // Copyright (C) Joerg Rosenkranz, 2004 // // Licensed under the MIT/X11 License. // using System; using System.Diagnostics; using System.Runtime.InteropServices; using System.Text; namespace System.Data.OracleClient.Oci { internal sealed class OciCalls { private static bool traceOci; #if TRACE static OciCalls() { string env = Environment.GetEnvironmentVariable("OCI_TRACE"); traceOci = (env != null && env.Length > 0); } #endif private OciCalls () {} #region OCI native calls private sealed class OciNativeCalls { private OciNativeCalls () {} [DllImport ("oci", EntryPoint = "OCIAttrSet")] internal static extern int OCIAttrSet (IntPtr trgthndlp, [MarshalAs (UnmanagedType.U4)] OciHandleType trghndltyp, IntPtr attributep, uint size, [MarshalAs (UnmanagedType.U4)] OciAttributeType attrtype, IntPtr errhp); [DllImport ("oci", EntryPoint = "OCIAttrSet")] internal static extern int OCIAttrSetString (IntPtr trgthndlp, [MarshalAs (UnmanagedType.U4)] OciHandleType trghndltyp, string attributep, uint size, [MarshalAs (UnmanagedType.U4)] OciAttributeType attrtype, IntPtr errhp); [DllImport ("oci")] internal static extern int OCIErrorGet (IntPtr hndlp, uint recordno, IntPtr sqlstate, out int errcodep, IntPtr bufp, uint bufsize, [MarshalAs (UnmanagedType.U4)] OciHandleType type); [DllImport ("oci", EntryPoint = "OCIBindByName")] internal static extern int OCIBindByName (IntPtr stmtp, out IntPtr bindpp, IntPtr errhp, string placeholder, int placeh_len, IntPtr valuep, int value_sz, [MarshalAs (UnmanagedType.U2)] OciDataType dty, int indp, IntPtr alenp, IntPtr rcodep, uint maxarr_len, IntPtr curelp, uint mode); [DllImport ("oci", EntryPoint = "OCIBindByName")] internal static extern int OCIBindByNameBytes (IntPtr stmtp, out IntPtr bindpp, IntPtr errhp, string placeholder, int placeh_len, byte[] valuep, int value_sz, [MarshalAs (UnmanagedType.U2)] OciDataType dty, int indp, IntPtr alenp, IntPtr rcodep, uint maxarr_len, IntPtr curelp, uint mode); [DllImport ("oci")] internal static extern int OCIDateTimeFromText (IntPtr hndl, IntPtr errhp, [In][Out] byte[] date_str, uint dstr_length, [In][Out] byte[] fmt, uint fmt_length, [In][Out] byte[] lang_name, uint lang_length, IntPtr datetime); [DllImport ("oci")] internal static extern int OCIDefineByPos (IntPtr stmtp, out IntPtr defnpp, IntPtr errhp, [MarshalAs (UnmanagedType.U4)] int position, IntPtr valuep, int value_sz, [MarshalAs (UnmanagedType.U4)] OciDataType dty, ref short indp, ref short rlenp, IntPtr rcodep, uint mode); [DllImport ("oci", EntryPoint="OCIDefineByPos")] internal static extern int OCIDefineByPosPtr (IntPtr stmtp, out IntPtr defnpp, IntPtr errhp, [MarshalAs (UnmanagedType.U4)] int position, ref IntPtr valuep, int value_sz, [MarshalAs (UnmanagedType.U4)] OciDataType dty, ref short indp, ref short rlenp, IntPtr rcodep, uint mode); [DllImport ("oci")] internal static extern int OCIDescriptorFree (IntPtr hndlp, [MarshalAs (UnmanagedType.U4)] OciHandleType type); [DllImport ("oci")] internal static extern int OCIEnvCreate (out IntPtr envhpp, [MarshalAs (UnmanagedType.U4)] OciEnvironmentMode mode, IntPtr ctxp, IntPtr malocfp, IntPtr ralocfp, IntPtr mfreep, int xtramem_sz, IntPtr usrmempp); [DllImport ("oci")] internal static extern int OCIAttrGet (IntPtr trgthndlp, [MarshalAs (UnmanagedType.U4)] OciHandleType trghndltyp, out IntPtr attributep, out int sizep, [MarshalAs (UnmanagedType.U4)] OciAttributeType attrtype, IntPtr errhp); [DllImport ("oci", EntryPoint = "OCIAttrGet")] internal static extern int OCIAttrGetSByte (IntPtr trgthndlp, [MarshalAs (UnmanagedType.U4)] OciHandleType trghndltyp, out sbyte attributep, IntPtr sizep, [MarshalAs (UnmanagedType.U4)] OciAttributeType attrtype, IntPtr errhp); [DllImport ("oci", EntryPoint = "OCIAttrGet")] internal static extern int OCIAttrGetByte (IntPtr trgthndlp, [MarshalAs (UnmanagedType.U4)] OciHandleType trghndltyp, out byte attributep, IntPtr sizep, [MarshalAs (UnmanagedType.U4)] OciAttributeType attrtype, IntPtr errhp); [DllImport ("oci", EntryPoint = "OCIAttrGet")] internal static extern int OCIAttrGetUInt16 (IntPtr trgthndlp, [MarshalAs (UnmanagedType.U4)] OciHandleType trghndltyp, out ushort attributep, IntPtr sizep, [MarshalAs (UnmanagedType.U4)] OciAttributeType attrtype, IntPtr errhp); [DllImport ("oci", EntryPoint = "OCIAttrGet")] internal static extern int OCIAttrGetInt32 (IntPtr trgthndlp, [MarshalAs (UnmanagedType.U4)] OciHandleType trghndltyp, out int attributep, IntPtr sizep, [MarshalAs (UnmanagedType.U4)] OciAttributeType attrtype, IntPtr errhp); [DllImport ("oci", EntryPoint = "OCIAttrGet")] internal static extern int OCIAttrGetIntPtr (IntPtr trgthndlp, [MarshalAs (UnmanagedType.U4)] OciHandleType trghndltyp, out IntPtr attributep, IntPtr sizep, [MarshalAs (UnmanagedType.U4)] OciAttributeType attrtype, IntPtr errhp); [DllImport ("oci")] internal static extern int OCIDescriptorAlloc (IntPtr parenth, out IntPtr hndlpp, [MarshalAs (UnmanagedType.U4)] OciHandleType type, int xtramem_sz, IntPtr usrmempp); [DllImport ("oci")] internal static extern int OCIHandleAlloc (IntPtr parenth, out IntPtr descpp, [MarshalAs (UnmanagedType.U4)] OciHandleType type, int xtramem_sz, IntPtr usrmempp); [DllImport ("oci")] internal static extern int OCIHandleFree (IntPtr hndlp, [MarshalAs (UnmanagedType.U4)] OciHandleType type); [DllImport ("oci")] internal static extern int OCILobClose (IntPtr svchp, IntPtr errhp, IntPtr locp); [DllImport ("oci")] internal static extern int OCILobCopy (IntPtr svchp, IntPtr errhp, IntPtr dst_locp, IntPtr src_locp, uint amount, uint dst_offset, uint src_offset); [DllImport ("oci")] internal static extern int OCILobErase (IntPtr svchp, IntPtr errhp, IntPtr locp, ref uint amount, uint offset); [DllImport ("oci")] internal static extern int OCILobGetChunkSize (IntPtr svchp, IntPtr errhp, IntPtr locp, out uint chunk_size); [DllImport ("oci")] internal static extern int OCILobGetLength (IntPtr svchp, IntPtr errhp, IntPtr locp, out uint lenp); [DllImport ("oci")] internal static extern int OCILobOpen (IntPtr svchp, IntPtr errhp, IntPtr locp, byte mode); [DllImport ("oci")] internal static extern int OCILobRead (IntPtr svchp, IntPtr errhp, IntPtr locp, ref uint amtp, uint offset, byte[] bufp, uint bufl, IntPtr ctxp, IntPtr cbfp, ushort csid, byte csfrm); [DllImport ("oci")] internal static extern int OCILobTrim (IntPtr svchp, IntPtr errhp, IntPtr locp, uint newlen); [DllImport ("oci")] internal static extern int OCILobWrite (IntPtr svchp, IntPtr errhp, IntPtr locp, ref uint amtp, uint offset, byte[] bufp, uint bufl, byte piece, IntPtr ctxp, IntPtr cbfp, ushort csid, byte csfrm); [DllImport ("oci")] internal static extern int OCINlsGetInfo (IntPtr hndl, IntPtr errhp, [In][Out] byte[] bufp, uint buflen, ushort item); [DllImport ("oci")] internal static extern int OCIServerAttach (IntPtr srvhp, IntPtr errhp, string dblink, [MarshalAs (UnmanagedType.U4)] int dblink_len, uint mode); [DllImport ("oci")] internal static extern int OCIServerDetach (IntPtr srvhp, IntPtr errhp, uint mode); [DllImport ("oci")] internal static extern int OCIServerVersion (IntPtr hndlp, IntPtr errhp, [In][Out] byte[] bufp, uint bufsz, [MarshalAs (UnmanagedType.U4)] OciHandleType type); [DllImport ("oci")] internal static extern int OCISessionBegin (IntPtr svchp, IntPtr errhp, IntPtr usrhp, [MarshalAs (UnmanagedType.U4)] OciCredentialType credt, [MarshalAs (UnmanagedType.U4)] OciSessionMode mode); [DllImport ("oci")] internal static extern int OCISessionEnd (IntPtr svchp, IntPtr errhp, IntPtr usrhp, uint mode); [DllImport ("oci")] internal static extern int OCIParamGet (IntPtr hndlp, [MarshalAs (UnmanagedType.U4)] OciHandleType htype, IntPtr errhp, out IntPtr parmdpp, [MarshalAs (UnmanagedType.U4)] int pos); [DllImport ("oci")] internal static extern int OCIStmtExecute (IntPtr svchp, IntPtr stmthp, IntPtr errhp, [MarshalAs (UnmanagedType.U4)] uint iters, uint rowoff, IntPtr snap_in, IntPtr snap_out, [MarshalAs (UnmanagedType.U4)] OciExecuteMode mode); [DllImport ("oci")] internal static extern int OCIStmtFetch (IntPtr stmtp, IntPtr errhp, uint nrows, ushort orientation, uint mode); [DllImport ("oci")] internal static extern int OCIStmtPrepare (IntPtr stmthp, IntPtr errhp, byte [] stmt, [MarshalAs (UnmanagedType.U4)] int stmt_length, [MarshalAs (UnmanagedType.U4)] OciStatementLanguage language, [MarshalAs (UnmanagedType.U4)] OciStatementMode mode); [DllImport ("oci")] internal static extern int OCITransCommit (IntPtr svchp, IntPtr errhp, uint flags); [DllImport ("oci")] internal static extern int OCITransRollback (IntPtr svchp, IntPtr errhp, uint flags); [DllImport ("oci")] internal static extern int OCITransStart (IntPtr svchp, IntPtr errhp, uint timeout, [MarshalAs (UnmanagedType.U4)] OciTransactionFlags flags); [DllImport ("oci")] internal static extern int OCICharSetToUnicode ( IntPtr svchp, [MarshalAs (UnmanagedType.LPWStr)] StringBuilder dst, [MarshalAs (UnmanagedType.U4)] int dstlen, byte [] src, [MarshalAs (UnmanagedType.U4)] int srclen, [MarshalAs (UnmanagedType.U4)] out int rsize); [DllImport ("oci")] internal static extern int OCIUnicodeToCharSet ( IntPtr svchp, byte [] dst, [MarshalAs (UnmanagedType.U4)] int dstlen, [MarshalAs (UnmanagedType.LPWStr)] string src, [MarshalAs (UnmanagedType.U4)] int srclen, [MarshalAs (UnmanagedType.U4)] out int rsize); } #endregion #region OCI call wrappers internal static int OCIAttrSet (IntPtr trgthndlp, OciHandleType trghndltyp, IntPtr attributep, uint size, OciAttributeType attrtype, IntPtr errhp) { Trace.WriteLineIf(traceOci, string.Format("OCIAttrSet ({0}, {1})", trghndltyp, attrtype), "OCI"); return OciNativeCalls.OCIAttrSet (trgthndlp, trghndltyp, attributep, size, attrtype, errhp); } internal static int OCIAttrSetString (IntPtr trgthndlp, OciHandleType trghndltyp, string attributep, uint size, OciAttributeType attrtype, IntPtr errhp) { Trace.WriteLineIf(traceOci, string.Format("OCIAttrSetString ({0}, {1})", trghndltyp, attrtype), "OCI"); return OciNativeCalls.OCIAttrSetString (trgthndlp, trghndltyp, attributep, size, attrtype, errhp); } internal static int OCIErrorGet (IntPtr hndlp, uint recordno, IntPtr sqlstate, out int errcodep, IntPtr bufp, uint bufsize, OciHandleType type) { Trace.WriteLineIf(traceOci, "OCIErrorGet", "OCI"); return OciNativeCalls.OCIErrorGet (hndlp, recordno, sqlstate, out errcodep, bufp, bufsize, type); } internal static int OCIBindByName (IntPtr stmtp, out IntPtr bindpp, IntPtr errhp, string placeholder, int placeh_len, IntPtr valuep, int value_sz, OciDataType dty, int indp, IntPtr alenp, IntPtr rcodep, uint maxarr_len, IntPtr curelp, uint mode) { Trace.WriteLineIf(traceOci, "OCIBindByName", "OCI"); return OciNativeCalls.OCIBindByName (stmtp, out bindpp, errhp, placeholder, placeh_len, valuep, value_sz, dty, indp, alenp, rcodep, maxarr_len, curelp, mode); } internal static int OCIBindByNameBytes (IntPtr stmtp, out IntPtr bindpp, IntPtr errhp, string placeholder, int placeh_len, byte[] valuep, int value_sz, [MarshalAs (UnmanagedType.U2)] OciDataType dty, int indp, IntPtr alenp, IntPtr rcodep, uint maxarr_len, IntPtr curelp, uint mode) { Trace.WriteLineIf(traceOci, "OCIBindByName", "OCI"); return OciNativeCalls.OCIBindByNameBytes (stmtp, out bindpp, errhp, placeholder, placeh_len, valuep, value_sz, dty, indp, alenp, rcodep, maxarr_len, curelp, mode); } internal static int OCIDefineByPos (IntPtr stmtp, out IntPtr defnpp, IntPtr errhp, int position, IntPtr valuep, int value_sz, OciDataType dty, ref short indp, ref short rlenp, IntPtr rcodep, uint mode) { Trace.WriteLineIf(traceOci, "OCIDefineByPos", "OCI"); return OciNativeCalls.OCIDefineByPos (stmtp, out defnpp, errhp, position, valuep, value_sz, dty, ref indp, ref rlenp, rcodep, mode); } internal static int OCIDefineByPosPtr (IntPtr stmtp, out IntPtr defnpp, IntPtr errhp, int position, ref IntPtr valuep, int value_sz, OciDataType dty, ref short indp, ref short rlenp, IntPtr rcodep, uint mode) { Trace.WriteLineIf(traceOci, "OCIDefineByPosPtr", "OCI"); return OciNativeCalls.OCIDefineByPosPtr (stmtp, out defnpp, errhp, position, ref valuep, value_sz, dty, ref indp, ref rlenp, rcodep, mode); } internal static int OCIDescriptorFree (IntPtr hndlp, OciHandleType type) { Trace.WriteLineIf(traceOci, string.Format("OCIDescriptorFree ({0})", type), "OCI"); return OciNativeCalls.OCIDescriptorFree (hndlp, type); } internal static int OCIEnvCreate (out IntPtr envhpp, OciEnvironmentMode mode, IntPtr ctxp, IntPtr malocfp, IntPtr ralocfp, IntPtr mfreep, int xtramem_sz, IntPtr usrmempp) { Trace.WriteLineIf(traceOci, "OCIEnvCreate", "OCI"); return OciNativeCalls.OCIEnvCreate (out envhpp, mode, ctxp, malocfp, ralocfp, mfreep, xtramem_sz, usrmempp); } internal static int OCIAttrGet (IntPtr trgthndlp, OciHandleType trghndltyp, out IntPtr attributep, out int sizep, OciAttributeType attrtype, IntPtr errhp) { Trace.WriteLineIf(traceOci, "OCIAttrGet", "OCI"); return OciNativeCalls.OCIAttrGet (trgthndlp, trghndltyp, out attributep, out sizep, attrtype, errhp); } internal static int OCIAttrGetSByte (IntPtr trgthndlp, OciHandleType trghndltyp, out sbyte attributep, IntPtr sizep, OciAttributeType attrtype, IntPtr errhp) { Trace.WriteLineIf(traceOci, "OCIAttrGetSByte", "OCI"); return OciNativeCalls.OCIAttrGetSByte (trgthndlp, trghndltyp, out attributep, sizep, attrtype, errhp); } internal static int OCIAttrGetByte (IntPtr trgthndlp, OciHandleType trghndltyp, out byte attributep, IntPtr sizep, OciAttributeType attrtype, IntPtr errhp) { Trace.WriteLineIf(traceOci, "OCIAttrGetByte", "OCI"); return OciNativeCalls.OCIAttrGetByte (trgthndlp, trghndltyp, out attributep, sizep, attrtype, errhp); } internal static int OCIAttrGetUInt16 (IntPtr trgthndlp, OciHandleType trghndltyp, out ushort attributep, IntPtr sizep, OciAttributeType attrtype, IntPtr errhp) { Trace.WriteLineIf(traceOci, "OCIAttrGetUInt16", "OCI"); return OciNativeCalls.OCIAttrGetUInt16 (trgthndlp, trghndltyp, out attributep, sizep, attrtype, errhp); } internal static int OCIAttrGetInt32 (IntPtr trgthndlp, OciHandleType trghndltyp, out int attributep, IntPtr sizep, OciAttributeType attrtype, IntPtr errhp) { Trace.WriteLineIf(traceOci, "OCIAttrGetInt32", "OCI"); return OciNativeCalls.OCIAttrGetInt32 (trgthndlp, trghndltyp, out attributep, sizep, attrtype, errhp); } internal static int OCIAttrGetIntPtr (IntPtr trgthndlp, OciHandleType trghndltyp, out IntPtr attributep, IntPtr sizep, OciAttributeType attrtype, IntPtr errhp) { Trace.WriteLineIf(traceOci, "OCIAttrGetIntPtr", "OCI"); return OciNativeCalls.OCIAttrGetIntPtr (trgthndlp, trghndltyp, out attributep, sizep, attrtype, errhp); } internal static int OCIDescriptorAlloc (IntPtr parenth, out IntPtr hndlpp, OciHandleType type, int xtramem_sz, IntPtr usrmempp) { Trace.WriteLineIf(traceOci, "OCIDescriptorAlloc", "OCI"); return OciNativeCalls.OCIDescriptorAlloc (parenth, out hndlpp, type, xtramem_sz, usrmempp); } internal static int OCIHandleAlloc (IntPtr parenth, out IntPtr descpp, OciHandleType type, int xtramem_sz, IntPtr usrmempp) { Trace.WriteLineIf(traceOci, string.Format("OCIHandleAlloc ({0})", type), "OCI"); return OciNativeCalls.OCIHandleAlloc (parenth, out descpp, type, xtramem_sz, usrmempp); } internal static int OCIHandleFree (IntPtr hndlp, OciHandleType type) { Trace.WriteLineIf(traceOci, string.Format("OCIHandleFree ({0})", type), "OCI"); return OciNativeCalls.OCIHandleFree (hndlp, type); } internal static int OCILobClose (IntPtr svchp, IntPtr errhp, IntPtr locp) { Trace.WriteLineIf(traceOci, "OCILobClose", "OCI"); return OciNativeCalls.OCILobClose (svchp, errhp, locp); } internal static int OCILobCopy (IntPtr svchp, IntPtr errhp, IntPtr dst_locp, IntPtr src_locp, uint amount, uint dst_offset, uint src_offset) { Trace.WriteLineIf(traceOci, "OCILobCopy", "OCI"); return OciNativeCalls.OCILobCopy (svchp, errhp, dst_locp, src_locp, amount, dst_offset, src_offset); } internal static int OCILobErase (IntPtr svchp, IntPtr errhp, IntPtr locp, ref uint amount, uint offset) { Trace.WriteLineIf(traceOci, "OCILobErase", "OCI"); return OciNativeCalls.OCILobErase (svchp, errhp, locp, ref amount, offset); } internal static int OCILobGetChunkSize (IntPtr svchp, IntPtr errhp, IntPtr locp, out uint chunk_size) { Trace.WriteLineIf(traceOci, "OCILobGetChunkSize", "OCI"); return OciNativeCalls.OCILobGetChunkSize (svchp, errhp, locp, out chunk_size); } internal static int OCILobGetLength (IntPtr svchp, IntPtr errhp, IntPtr locp, out uint lenp) { Trace.WriteLineIf(traceOci, "OCILobGetLength", "OCI"); return OciNativeCalls.OCILobGetLength (svchp, errhp, locp, out lenp); } internal static int OCILobOpen (IntPtr svchp, IntPtr errhp, IntPtr locp, byte mode) { Trace.WriteLineIf(traceOci, "OCILobOpen", "OCI"); return OciNativeCalls.OCILobOpen (svchp, errhp, locp, mode); } internal static int OCILobRead (IntPtr svchp, IntPtr errhp, IntPtr locp, ref uint amtp, uint offset, byte[] bufp, uint bufl, IntPtr ctxp, IntPtr cbfp, ushort csid, byte csfrm) { Trace.WriteLineIf(traceOci, "OCILobRead", "OCI"); return OciNativeCalls.OCILobRead (svchp, errhp, locp, ref amtp, offset, bufp, bufl, ctxp, cbfp, csid, csfrm); } internal static int OCILobTrim (IntPtr svchp, IntPtr errhp, IntPtr locp, uint newlen) { Trace.WriteLineIf(traceOci, "OCILobTrim", "OCI"); return OciNativeCalls.OCILobTrim (svchp, errhp, locp, newlen); } internal static int OCILobWrite (IntPtr svchp, IntPtr errhp, IntPtr locp, ref uint amtp, uint offset, byte[] bufp, uint bufl, byte piece, IntPtr ctxp, IntPtr cbfp, ushort csid, byte csfrm) { Trace.WriteLineIf(traceOci, "OCILobWrite", "OCI"); return OciNativeCalls.OCILobWrite (svchp, errhp, locp, ref amtp, offset, bufp, bufl, piece, ctxp, cbfp, csid, csfrm); } internal static int OCINlsGetInfo (IntPtr hndl, IntPtr errhp, ref byte[] bufp, uint buflen, ushort item) { Trace.WriteLineIf(traceOci, "OCINlsGetInfo", "OCI"); return OciNativeCalls.OCINlsGetInfo (hndl, errhp, bufp, buflen, item); } internal static int OCIServerAttach (IntPtr srvhp, IntPtr errhp, string dblink, int dblink_len, uint mode) { Trace.WriteLineIf(traceOci, "OCIServerAttach", "OCI"); return OciNativeCalls.OCIServerAttach (srvhp, errhp, dblink, dblink_len, mode); } internal static int OCIServerDetach (IntPtr srvhp, IntPtr errhp, uint mode) { Trace.WriteLineIf(traceOci, "OCIServerDetach", "OCI"); return OciNativeCalls.OCIServerDetach (srvhp, errhp, mode); } internal static int OCIServerVersion (IntPtr hndlp, IntPtr errhp, ref byte[] bufp, uint bufsz, OciHandleType hndltype) { Trace.WriteLineIf(traceOci, "OCIServerVersion", "OCI"); return OciNativeCalls.OCIServerVersion (hndlp, errhp, bufp, bufsz, hndltype); } internal static int OCISessionBegin (IntPtr svchp, IntPtr errhp, IntPtr usrhp, OciCredentialType credt, OciSessionMode mode) { Trace.WriteLineIf(traceOci, "OCISessionBegin", "OCI"); return OciNativeCalls.OCISessionBegin (svchp, errhp, usrhp, credt, mode); } internal static int OCISessionEnd (IntPtr svchp, IntPtr errhp, IntPtr usrhp, uint mode) { Trace.WriteLineIf(traceOci, "OCISessionEnd", "OCI"); return OciNativeCalls.OCISessionEnd (svchp, errhp, usrhp, mode); } internal static int OCIParamGet (IntPtr hndlp, OciHandleType htype, IntPtr errhp, out IntPtr parmdpp, int pos) { Trace.WriteLineIf(traceOci, "OCIParamGet", "OCI"); return OciNativeCalls.OCIParamGet (hndlp, htype, errhp, out parmdpp, pos); } internal static int OCIStmtExecute (IntPtr svchp, IntPtr stmthp, IntPtr errhp, bool iters, uint rowoff, IntPtr snap_in, IntPtr snap_out, OciExecuteMode mode) { Trace.WriteLineIf(traceOci, "OCIStmtExecute", "OCI"); uint it = 0; if (iters == true) it = 1; return OciNativeCalls.OCIStmtExecute (svchp, stmthp, errhp, it, rowoff, snap_in, snap_out, mode); } internal static int OCIStmtFetch (IntPtr stmtp, IntPtr errhp, uint nrows, ushort orientation, uint mode) { Trace.WriteLineIf(traceOci, "OCIStmtFetch", "OCI"); return OciNativeCalls.OCIStmtFetch (stmtp, errhp, nrows, orientation, mode); } internal static int OCIStmtPrepare (IntPtr stmthp, IntPtr errhp, byte [] stmt, int stmt_length, OciStatementLanguage language, OciStatementMode mode) { Trace.WriteLineIf(traceOci, string.Format("OCIStmtPrepare ({0})", System.Text.Encoding.UTF8.GetString(stmt)), "OCI"); return OciNativeCalls.OCIStmtPrepare (stmthp, errhp, stmt, stmt_length, language, mode); } internal static int OCITransCommit (IntPtr svchp, IntPtr errhp, uint flags) { Trace.WriteLineIf(traceOci, "OCITransCommit", "OCI"); return OciNativeCalls.OCITransCommit (svchp, errhp, flags); } internal static int OCITransRollback (IntPtr svchp, IntPtr errhp, uint flags) { Trace.WriteLineIf(traceOci, "OCITransRollback", "OCI"); return OciNativeCalls.OCITransRollback (svchp, errhp, flags); } internal static int OCITransStart (IntPtr svchp, IntPtr errhp, uint timeout, OciTransactionFlags flags) { Trace.WriteLineIf(traceOci, "OCITransStart", "OCI"); return OciNativeCalls.OCITransStart (svchp, errhp, timeout, flags); } internal static int OCICharSetToUnicode ( IntPtr svchp, StringBuilder dst, byte [] src, out int rsize) { Trace.WriteLineIf(traceOci, "OCICharSetToUnicode", "OCI"); return OciNativeCalls.OCICharSetToUnicode (svchp, dst, dst!=null ? dst.Capacity : 0, src, src.Length, out rsize); } internal static int OCIUnicodeToCharSet ( IntPtr svchp, byte [] dst, [MarshalAs (UnmanagedType.LPWStr)] string src, [MarshalAs (UnmanagedType.U4)] out int rsize) { Trace.WriteLineIf(traceOci, "OCICharSetToUnicode", "OCI"); return OciNativeCalls.OCIUnicodeToCharSet (svchp, dst, dst!=null ? dst.Length : 0, src, src.Length, out rsize); } #endregion } }
using Microsoft.IdentityModel; using Microsoft.IdentityModel.S2S.Protocols.OAuth2; using Microsoft.IdentityModel.S2S.Tokens; using Microsoft.SharePoint.Client; using Microsoft.SharePoint.Client.EventReceivers; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.IdentityModel.Selectors; using System.IdentityModel.Tokens; using System.IO; using System.Linq; using System.Net; using System.Security.Cryptography.X509Certificates; using System.Security.Principal; using System.ServiceModel; using System.Text; using System.Web; using System.Web.Configuration; using System.Web.Script.Serialization; using AudienceRestriction = Microsoft.IdentityModel.Tokens.AudienceRestriction; using AudienceUriValidationFailedException = Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException; using SecurityTokenHandlerConfiguration = Microsoft.IdentityModel.Tokens.SecurityTokenHandlerConfiguration; using X509SigningCredentials = Microsoft.IdentityModel.SecurityTokenService.X509SigningCredentials; namespace Core.UserProfiles.Sync { public static class TokenHelper { #region public fields /// <summary> /// SharePoint principal. /// </summary> public const string SharePointPrincipal = "00000003-0000-0ff1-ce00-000000000000"; /// <summary> /// Lifetime of HighTrust access token, 12 hours. /// </summary> public static readonly TimeSpan HighTrustAccessTokenLifetime = TimeSpan.FromHours(12.0); #endregion public fields #region public methods /// <summary> /// Retrieves the context token string from the specified request by looking for well-known parameter names in the /// POSTed form parameters and the querystring. Returns null if no context token is found. /// </summary> /// <param name="request">HttpRequest in which to look for a context token</param> /// <returns>The context token string</returns> public static string GetContextTokenFromRequest(HttpRequest request) { return GetContextTokenFromRequest(new HttpRequestWrapper(request)); } /// <summary> /// Retrieves the context token string from the specified request by looking for well-known parameter names in the /// POSTed form parameters and the querystring. Returns null if no context token is found. /// </summary> /// <param name="request">HttpRequest in which to look for a context token</param> /// <returns>The context token string</returns> public static string GetContextTokenFromRequest(HttpRequestBase request) { string[] paramNames = { "AppContext", "AppContextToken", "AccessToken", "SPAppToken" }; foreach (string paramName in paramNames) { if (!string.IsNullOrEmpty(request.Form[paramName])) { return request.Form[paramName]; } if (!string.IsNullOrEmpty(request.QueryString[paramName])) { return request.QueryString[paramName]; } } return null; } /// <summary> /// Validate that a specified context token string is intended for this application based on the parameters /// specified in web.config. Parameters used from web.config used for validation include ClientId, /// HostedAppHostNameOverride, HostedAppHostName, ClientSecret, and Realm (if it is specified). If HostedAppHostNameOverride is present, /// it will be used for validation. Otherwise, if the <paramref name="appHostName"/> is not /// null, it is used for validation instead of the web.config's HostedAppHostName. If the token is invalid, an /// exception is thrown. If the token is valid, TokenHelper's static STS metadata url is updated based on the token contents /// and a JsonWebSecurityToken based on the context token is returned. /// </summary> /// <param name="contextTokenString">The context token to validate</param> /// <param name="appHostName">The URL authority, consisting of Domain Name System (DNS) host name or IP address and the port number, to use for token audience validation. /// If null, HostedAppHostName web.config setting is used instead. HostedAppHostNameOverride web.config setting, if present, will be used /// for validation instead of <paramref name="appHostName"/> .</param> /// <returns>A JsonWebSecurityToken based on the context token.</returns> public static SharePointContextToken ReadAndValidateContextToken(string contextTokenString, string appHostName = null) { JsonWebSecurityTokenHandler tokenHandler = CreateJsonWebSecurityTokenHandler(); SecurityToken securityToken = tokenHandler.ReadToken(contextTokenString); JsonWebSecurityToken jsonToken = securityToken as JsonWebSecurityToken; SharePointContextToken token = SharePointContextToken.Create(jsonToken); string stsAuthority = (new Uri(token.SecurityTokenServiceUri)).Authority; int firstDot = stsAuthority.IndexOf('.'); GlobalEndPointPrefix = stsAuthority.Substring(0, firstDot); AcsHostUrl = stsAuthority.Substring(firstDot + 1); tokenHandler.ValidateToken(jsonToken); string[] acceptableAudiences; if (!String.IsNullOrEmpty(HostedAppHostNameOverride)) { acceptableAudiences = HostedAppHostNameOverride.Split(';'); } else if (appHostName == null) { acceptableAudiences = new[] { HostedAppHostName }; } else { acceptableAudiences = new[] { appHostName }; } bool validationSuccessful = false; string realm = Realm ?? token.Realm; foreach (var audience in acceptableAudiences) { string principal = GetFormattedPrincipal(ClientId, audience, realm); if (StringComparer.OrdinalIgnoreCase.Equals(token.Audience, principal)) { validationSuccessful = true; break; } } if (!validationSuccessful) { throw new AudienceUriValidationFailedException( String.Format(CultureInfo.CurrentCulture, "\"{0}\" is not the intended audience \"{1}\"", String.Join(";", acceptableAudiences), token.Audience)); } return token; } /// <summary> /// Retrieves an access token from ACS to call the source of the specified context token at the specified /// targetHost. The targetHost must be registered for the principal that sent the context token. /// </summary> /// <param name="contextToken">Context token issued by the intended access token audience</param> /// <param name="targetHost">Url authority of the target principal</param> /// <returns>An access token with an audience matching the context token's source</returns> public static OAuth2AccessTokenResponse GetAccessToken(SharePointContextToken contextToken, string targetHost) { string targetPrincipalName = contextToken.TargetPrincipalName; // Extract the refreshToken from the context token string refreshToken = contextToken.RefreshToken; if (String.IsNullOrEmpty(refreshToken)) { return null; } string targetRealm = Realm ?? contextToken.Realm; return GetAccessToken(refreshToken, targetPrincipalName, targetHost, targetRealm); } /// <summary> /// Uses the specified authorization code to retrieve an access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="authorizationCode">Authorization code to exchange for access token</param> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAccessToken( string authorizationCode, string targetPrincipalName, string targetHost, string targetRealm, Uri redirectUri) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, null, targetRealm); // Create request for token. The RedirectUri is null here. This will fail if redirect uri is registered OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithAuthorizationCode( clientId, ClientSecret, authorizationCode, redirectUri, resource); // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Uses the specified refresh token to retrieve an access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="refreshToken">Refresh token to exchange for access token</param> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAccessToken( string refreshToken, string targetPrincipalName, string targetHost, string targetRealm) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, null, targetRealm); OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithRefreshToken(clientId, ClientSecret, refreshToken, resource); // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Retrieves an app-only access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAppOnlyAccessToken( string targetPrincipalName, string targetHost, string targetRealm) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, HostedAppHostName, targetRealm); OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithClientCredentials(clientId, ClientSecret, resource); oauth2Request.Resource = resource; // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Creates a client context based on the properties of a remote event receiver /// </summary> /// <param name="properties">Properties of a remote event receiver</param> /// <returns>A ClientContext ready to call the web where the event originated</returns> public static ClientContext CreateRemoteEventReceiverClientContext(SPRemoteEventProperties properties) { Uri sharepointUrl; if (properties.ListEventProperties != null) { sharepointUrl = new Uri(properties.ListEventProperties.WebUrl); } else if (properties.ItemEventProperties != null) { sharepointUrl = new Uri(properties.ItemEventProperties.WebUrl); } else if (properties.WebEventProperties != null) { sharepointUrl = new Uri(properties.WebEventProperties.FullUrl); } else { return null; } if (IsHighTrustApp()) { return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null); } return CreateAcsClientContextForUrl(properties, sharepointUrl); } /// <summary> /// Creates a client context based on the properties of an app event /// </summary> /// <param name="properties">Properties of an app event</param> /// <param name="useAppWeb">True to target the app web, false to target the host web</param> /// <returns>A ClientContext ready to call the app web or the parent web</returns> public static ClientContext CreateAppEventClientContext(SPRemoteEventProperties properties, bool useAppWeb) { if (properties.AppEventProperties == null) { return null; } Uri sharepointUrl = useAppWeb ? properties.AppEventProperties.AppWebFullUrl : properties.AppEventProperties.HostWebFullUrl; if (IsHighTrustApp()) { return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null); } return CreateAcsClientContextForUrl(properties, sharepointUrl); } /// <summary> /// Retrieves an access token from ACS using the specified authorization code, and uses that access token to /// create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithAuthorizationCode( string targetUrl, string authorizationCode, Uri redirectUri) { return GetClientContextWithAuthorizationCode(targetUrl, SharePointPrincipal, authorizationCode, GetRealmFromTargetUrl(new Uri(targetUrl)), redirectUri); } /// <summary> /// Retrieves an access token from ACS using the specified authorization code, and uses that access token to /// create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="targetPrincipalName">Name of the target SharePoint principal</param> /// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithAuthorizationCode( string targetUrl, string targetPrincipalName, string authorizationCode, string targetRealm, Uri redirectUri) { Uri targetUri = new Uri(targetUrl); string accessToken = GetAccessToken(authorizationCode, targetPrincipalName, targetUri.Authority, targetRealm, redirectUri).AccessToken; return GetClientContextWithAccessToken(targetUrl, accessToken); } /// <summary> /// Uses the specified access token to create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="accessToken">Access token to be used when calling the specified targetUrl</param> /// <returns>A ClientContext ready to call targetUrl with the specified access token</returns> public static ClientContext GetClientContextWithAccessToken(string targetUrl, string accessToken) { ClientContext clientContext = new ClientContext(targetUrl); clientContext.AuthenticationMode = ClientAuthenticationMode.Anonymous; clientContext.FormDigestHandlingEnabled = false; clientContext.ExecutingWebRequest += delegate(object oSender, WebRequestEventArgs webRequestEventArgs) { webRequestEventArgs.WebRequestExecutor.RequestHeaders["Authorization"] = "Bearer " + accessToken; }; return clientContext; } /// <summary> /// Retrieves an access token from ACS using the specified context token, and uses that access token to create /// a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="contextTokenString">Context token received from the target SharePoint site</param> /// <param name="appHostUrl">Url authority of the hosted app. If this is null, the value in the HostedAppHostName /// of web.config will be used instead</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithContextToken( string targetUrl, string contextTokenString, string appHostUrl) { SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, appHostUrl); Uri targetUri = new Uri(targetUrl); string accessToken = GetAccessToken(contextToken, targetUri.Authority).AccessToken; return GetClientContextWithAccessToken(targetUrl, accessToken); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request consent and get back /// an authorization code. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format /// (e.g. "Web.Read Site.Write")</param> /// <returns>Url of the SharePoint site's OAuth authorization page</returns> public static string GetAuthorizationUrl(string contextUrl, string scope) { return string.Format( "{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code", EnsureTrailingSlash(contextUrl), AuthorizationPage, ClientId, scope); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request consent and get back /// an authorization code. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format /// (e.g. "Web.Read Site.Write")</param> /// <param name="redirectUri">Uri to which SharePoint should redirect the browser to after consent is /// granted</param> /// <returns>Url of the SharePoint site's OAuth authorization page</returns> public static string GetAuthorizationUrl(string contextUrl, string scope, string redirectUri) { return string.Format( "{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code&redirect_uri={4}", EnsureTrailingSlash(contextUrl), AuthorizationPage, ClientId, scope, redirectUri); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request a new context token. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="redirectUri">Uri to which SharePoint should redirect the browser to with a context token</param> /// <returns>Url of the SharePoint site's context token redirect page</returns> public static string GetAppContextTokenRequestUrl(string contextUrl, string redirectUri) { return string.Format( "{0}{1}?client_id={2}&redirect_uri={3}", EnsureTrailingSlash(contextUrl), RedirectPage, ClientId, redirectUri); } /// <summary> /// Retrieves an S2S access token signed by the application's private certificate on behalf of the specified /// WindowsIdentity and intended for the SharePoint at the targetApplicationUri. If no Realm is specified in /// web.config, an auth challenge will be issued to the targetApplicationUri to discover it. /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <param name="identity">Windows identity of the user on whose behalf to create the access token</param> /// <returns>An access token with an audience of the target principal</returns> public static string GetS2SAccessTokenWithWindowsIdentity( Uri targetApplicationUri, WindowsIdentity identity) { string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm; JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null; return GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims); } /// <summary> /// Retrieves an S2S client context with an access token signed by the application's private certificate on /// behalf of the specified WindowsIdentity and intended for application at the targetApplicationUri using the /// targetRealm. If no Realm is specified in web.config, an auth challenge will be issued to the /// targetApplicationUri to discover it. /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <param name="identity">Windows identity of the user on whose behalf to create the access token</param> /// <returns>A ClientContext using an access token with an audience of the target application</returns> public static ClientContext GetS2SClientContextWithWindowsIdentity( Uri targetApplicationUri, WindowsIdentity identity) { string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm; JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null; string accessToken = GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims); return GetClientContextWithAccessToken(targetApplicationUri.ToString(), accessToken); } /// <summary> /// Get authentication realm from SharePoint /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <returns>String representation of the realm GUID</returns> public static string GetRealmFromTargetUrl(Uri targetApplicationUri) { WebRequest request = WebRequest.Create(targetApplicationUri + "/_vti_bin/client.svc"); request.Headers.Add("Authorization: Bearer "); try { using (request.GetResponse()) { } } catch (WebException e) { if (e.Response == null) { return null; } string bearerResponseHeader = e.Response.Headers["WWW-Authenticate"]; if (string.IsNullOrEmpty(bearerResponseHeader)) { return null; } const string bearer = "Bearer realm=\""; int bearerIndex = bearerResponseHeader.IndexOf(bearer, StringComparison.Ordinal); if (bearerIndex < 0) { return null; } int realmIndex = bearerIndex + bearer.Length; if (bearerResponseHeader.Length >= realmIndex + 36) { string targetRealm = bearerResponseHeader.Substring(realmIndex, 36); Guid realmGuid; if (Guid.TryParse(targetRealm, out realmGuid)) { return targetRealm; } } } return null; } /// <summary> /// Determines if this is a high trust app. /// </summary> /// <returns>True if this is a high trust app.</returns> public static bool IsHighTrustApp() { return SigningCredentials != null; } /// <summary> /// Ensures that the specified URL ends with '/' if it is not null or empty. /// </summary> /// <param name="url">The url.</param> /// <returns>The url ending with '/' if it is not null or empty.</returns> public static string EnsureTrailingSlash(string url) { if (!string.IsNullOrEmpty(url) && url[url.Length - 1] != '/') { return url + "/"; } return url; } #endregion #region private fields // // Configuration Constants // private const string AuthorizationPage = "_layouts/15/OAuthAuthorize.aspx"; private const string RedirectPage = "_layouts/15/AppRedirect.aspx"; private const string AcsPrincipalName = "00000001-0000-0000-c000-000000000000"; private const string AcsMetadataEndPointRelativeUrl = "metadata/json/1"; private const string S2SProtocol = "OAuth2"; private const string DelegationIssuance = "DelegationIssuance1.0"; private const string NameIdentifierClaimType = JsonWebTokenConstants.ReservedClaims.NameIdentifier; private const string TrustedForImpersonationClaimType = "trustedfordelegation"; private const string ActorTokenClaimType = JsonWebTokenConstants.ReservedClaims.ActorToken; // // Environment Constants // private static string GlobalEndPointPrefix = "accounts"; private static string AcsHostUrl = "accesscontrol.windows.net"; // // Hosted app configuration // private static readonly string ClientId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientId")) ? WebConfigurationManager.AppSettings.Get("HostedAppName") : WebConfigurationManager.AppSettings.Get("ClientId"); private static readonly string IssuerId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("IssuerId")) ? ClientId : WebConfigurationManager.AppSettings.Get("IssuerId"); private static readonly string HostedAppHostNameOverride = WebConfigurationManager.AppSettings.Get("HostedAppHostNameOverride"); private static readonly string HostedAppHostName = WebConfigurationManager.AppSettings.Get("HostedAppHostName"); private static readonly string ClientSecret = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientSecret")) ? WebConfigurationManager.AppSettings.Get("HostedAppSigningKey") : WebConfigurationManager.AppSettings.Get("ClientSecret"); private static readonly string SecondaryClientSecret = WebConfigurationManager.AppSettings.Get("SecondaryClientSecret"); private static readonly string Realm = WebConfigurationManager.AppSettings.Get("Realm"); private static readonly string ServiceNamespace = WebConfigurationManager.AppSettings.Get("Realm"); private static readonly string ClientSigningCertificatePath = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePath"); private static readonly string ClientSigningCertificatePassword = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePassword"); private static readonly X509Certificate2 ClientCertificate = (string.IsNullOrEmpty(ClientSigningCertificatePath) || string.IsNullOrEmpty(ClientSigningCertificatePassword)) ? null : new X509Certificate2(ClientSigningCertificatePath, ClientSigningCertificatePassword); private static readonly X509SigningCredentials SigningCredentials = (ClientCertificate == null) ? null : new X509SigningCredentials(ClientCertificate, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest); #endregion #region private methods private static ClientContext CreateAcsClientContextForUrl(SPRemoteEventProperties properties, Uri sharepointUrl) { string contextTokenString = properties.ContextToken; if (String.IsNullOrEmpty(contextTokenString)) { return null; } SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, OperationContext.Current.IncomingMessageHeaders.To.Host); string accessToken = GetAccessToken(contextToken, sharepointUrl.Authority).AccessToken; return GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken); } private static string GetAcsMetadataEndpointUrl() { return Path.Combine(GetAcsGlobalEndpointUrl(), AcsMetadataEndPointRelativeUrl); } private static string GetFormattedPrincipal(string principalName, string hostName, string realm) { if (!String.IsNullOrEmpty(hostName)) { return String.Format(CultureInfo.InvariantCulture, "{0}/{1}@{2}", principalName, hostName, realm); } return String.Format(CultureInfo.InvariantCulture, "{0}@{1}", principalName, realm); } private static string GetAcsPrincipalName(string realm) { return GetFormattedPrincipal(AcsPrincipalName, new Uri(GetAcsGlobalEndpointUrl()).Host, realm); } private static string GetAcsGlobalEndpointUrl() { return String.Format(CultureInfo.InvariantCulture, "https://{0}.{1}/", GlobalEndPointPrefix, AcsHostUrl); } private static JsonWebSecurityTokenHandler CreateJsonWebSecurityTokenHandler() { JsonWebSecurityTokenHandler handler = new JsonWebSecurityTokenHandler(); handler.Configuration = new SecurityTokenHandlerConfiguration(); handler.Configuration.AudienceRestriction = new AudienceRestriction(AudienceUriMode.Never); handler.Configuration.CertificateValidator = X509CertificateValidator.None; List<byte[]> securityKeys = new List<byte[]>(); securityKeys.Add(Convert.FromBase64String(ClientSecret)); if (!string.IsNullOrEmpty(SecondaryClientSecret)) { securityKeys.Add(Convert.FromBase64String(SecondaryClientSecret)); } List<SecurityToken> securityTokens = new List<SecurityToken>(); securityTokens.Add(new MultipleSymmetricKeySecurityToken(securityKeys)); handler.Configuration.IssuerTokenResolver = SecurityTokenResolver.CreateDefaultSecurityTokenResolver( new ReadOnlyCollection<SecurityToken>(securityTokens), false); SymmetricKeyIssuerNameRegistry issuerNameRegistry = new SymmetricKeyIssuerNameRegistry(); foreach (byte[] securitykey in securityKeys) { issuerNameRegistry.AddTrustedIssuer(securitykey, GetAcsPrincipalName(ServiceNamespace)); } handler.Configuration.IssuerNameRegistry = issuerNameRegistry; return handler; } private static string GetS2SAccessTokenWithClaims( string targetApplicationHostName, string targetRealm, IEnumerable<JsonWebTokenClaim> claims) { return IssueToken( ClientId, IssuerId, targetRealm, SharePointPrincipal, targetRealm, targetApplicationHostName, true, claims, claims == null); } private static JsonWebTokenClaim[] GetClaimsWithWindowsIdentity(WindowsIdentity identity) { JsonWebTokenClaim[] claims = new JsonWebTokenClaim[] { new JsonWebTokenClaim(NameIdentifierClaimType, identity.User.Value.ToLower()), new JsonWebTokenClaim("nii", "urn:office:idp:activedirectory") }; return claims; } private static string IssueToken( string sourceApplication, string issuerApplication, string sourceRealm, string targetApplication, string targetRealm, string targetApplicationHostName, bool trustedForDelegation, IEnumerable<JsonWebTokenClaim> claims, bool appOnly = false) { if (null == SigningCredentials) { throw new InvalidOperationException("SigningCredentials was not initialized"); } #region Actor token string issuer = string.IsNullOrEmpty(sourceRealm) ? issuerApplication : string.Format("{0}@{1}", issuerApplication, sourceRealm); string nameid = string.IsNullOrEmpty(sourceRealm) ? sourceApplication : string.Format("{0}@{1}", sourceApplication, sourceRealm); string audience = string.Format("{0}/{1}@{2}", targetApplication, targetApplicationHostName, targetRealm); List<JsonWebTokenClaim> actorClaims = new List<JsonWebTokenClaim>(); actorClaims.Add(new JsonWebTokenClaim(JsonWebTokenConstants.ReservedClaims.NameIdentifier, nameid)); if (trustedForDelegation && !appOnly) { actorClaims.Add(new JsonWebTokenClaim(TrustedForImpersonationClaimType, "true")); } // Create token JsonWebSecurityToken actorToken = new JsonWebSecurityToken( issuer: issuer, audience: audience, validFrom: DateTime.UtcNow, validTo: DateTime.UtcNow.Add(HighTrustAccessTokenLifetime), signingCredentials: SigningCredentials, claims: actorClaims); string actorTokenString = new JsonWebSecurityTokenHandler().WriteTokenAsString(actorToken); if (appOnly) { // App-only token is the same as actor token for delegated case return actorTokenString; } #endregion Actor token #region Outer token List<JsonWebTokenClaim> outerClaims = null == claims ? new List<JsonWebTokenClaim>() : new List<JsonWebTokenClaim>(claims); outerClaims.Add(new JsonWebTokenClaim(ActorTokenClaimType, actorTokenString)); JsonWebSecurityToken jsonToken = new JsonWebSecurityToken( nameid, // outer token issuer should match actor token nameid audience, DateTime.UtcNow, DateTime.UtcNow.Add(HighTrustAccessTokenLifetime), outerClaims); string accessToken = new JsonWebSecurityTokenHandler().WriteTokenAsString(jsonToken); #endregion Outer token return accessToken; } #endregion #region AcsMetadataParser // This class is used to get MetaData document from the global STS endpoint. It contains // methods to parse the MetaData document and get endpoints and STS certificate. public static class AcsMetadataParser { public static X509Certificate2 GetAcsSigningCert(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); if (null != document.keys && document.keys.Count > 0) { JsonKey signingKey = document.keys[0]; if (null != signingKey && null != signingKey.keyValue) { return new X509Certificate2(Encoding.UTF8.GetBytes(signingKey.keyValue.value)); } } throw new Exception("Metadata document does not contain ACS signing certificate."); } public static string GetDelegationServiceUrl(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); JsonEndpoint delegationEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == DelegationIssuance); if (null != delegationEndpoint) { return delegationEndpoint.location; } throw new Exception("Metadata document does not contain Delegation Service endpoint Url"); } private static JsonMetadataDocument GetMetadataDocument(string realm) { string acsMetadataEndpointUrlWithRealm = String.Format(CultureInfo.InvariantCulture, "{0}?realm={1}", GetAcsMetadataEndpointUrl(), realm); byte[] acsMetadata; using (WebClient webClient = new WebClient()) { acsMetadata = webClient.DownloadData(acsMetadataEndpointUrlWithRealm); } string jsonResponseString = Encoding.UTF8.GetString(acsMetadata); JavaScriptSerializer serializer = new JavaScriptSerializer(); JsonMetadataDocument document = serializer.Deserialize<JsonMetadataDocument>(jsonResponseString); if (null == document) { throw new Exception("No metadata document found at the global endpoint " + acsMetadataEndpointUrlWithRealm); } return document; } public static string GetStsUrl(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); JsonEndpoint s2sEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == S2SProtocol); if (null != s2sEndpoint) { return s2sEndpoint.location; } throw new Exception("Metadata document does not contain STS endpoint url"); } private class JsonMetadataDocument { public string serviceName { get; set; } public List<JsonEndpoint> endpoints { get; set; } public List<JsonKey> keys { get; set; } } private class JsonEndpoint { public string location { get; set; } public string protocol { get; set; } public string usage { get; set; } } private class JsonKeyValue { public string type { get; set; } public string value { get; set; } } private class JsonKey { public string usage { get; set; } public JsonKeyValue keyValue { get; set; } } } #endregion } /// <summary> /// A JsonWebSecurityToken generated by SharePoint to authenticate to a 3rd party application and allow callbacks using a refresh token /// </summary> public class SharePointContextToken : JsonWebSecurityToken { public static SharePointContextToken Create(JsonWebSecurityToken contextToken) { return new SharePointContextToken(contextToken.Issuer, contextToken.Audience, contextToken.ValidFrom, contextToken.ValidTo, contextToken.Claims); } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims) : base(issuer, audience, validFrom, validTo, claims) { } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SecurityToken issuerToken, JsonWebSecurityToken actorToken) : base(issuer, audience, validFrom, validTo, claims, issuerToken, actorToken) { } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SigningCredentials signingCredentials) : base(issuer, audience, validFrom, validTo, claims, signingCredentials) { } public string NameId { get { return GetClaimValue(this, "nameid"); } } /// <summary> /// The principal name portion of the context token's "appctxsender" claim /// </summary> public string TargetPrincipalName { get { string appctxsender = GetClaimValue(this, "appctxsender"); if (appctxsender == null) { return null; } return appctxsender.Split('@')[0]; } } /// <summary> /// The context token's "refreshtoken" claim /// </summary> public string RefreshToken { get { return GetClaimValue(this, "refreshtoken"); } } /// <summary> /// The context token's "CacheKey" claim /// </summary> public string CacheKey { get { string appctx = GetClaimValue(this, "appctx"); if (appctx == null) { return null; } ClientContext ctx = new ClientContext("http://tempuri.org"); Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx); string cacheKey = (string)dict["CacheKey"]; return cacheKey; } } /// <summary> /// The context token's "SecurityTokenServiceUri" claim /// </summary> public string SecurityTokenServiceUri { get { string appctx = GetClaimValue(this, "appctx"); if (appctx == null) { return null; } ClientContext ctx = new ClientContext("http://tempuri.org"); Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx); string securityTokenServiceUri = (string)dict["SecurityTokenServiceUri"]; return securityTokenServiceUri; } } /// <summary> /// The realm portion of the context token's "audience" claim /// </summary> public string Realm { get { string aud = Audience; if (aud == null) { return null; } string tokenRealm = aud.Substring(aud.IndexOf('@') + 1); return tokenRealm; } } private static string GetClaimValue(JsonWebSecurityToken token, string claimType) { if (token == null) { throw new ArgumentNullException("token"); } foreach (JsonWebTokenClaim claim in token.Claims) { if (StringComparer.Ordinal.Equals(claim.ClaimType, claimType)) { return claim.Value; } } return null; } } /// <summary> /// Represents a security token which contains multiple security keys that are generated using symmetric algorithms. /// </summary> public class MultipleSymmetricKeySecurityToken : SecurityToken { /// <summary> /// Initializes a new instance of the MultipleSymmetricKeySecurityToken class. /// </summary> /// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param> public MultipleSymmetricKeySecurityToken(IEnumerable<byte[]> keys) : this(UniqueId.CreateUniqueId(), keys) { } /// <summary> /// Initializes a new instance of the MultipleSymmetricKeySecurityToken class. /// </summary> /// <param name="tokenId">The unique identifier of the security token.</param> /// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param> public MultipleSymmetricKeySecurityToken(string tokenId, IEnumerable<byte[]> keys) { if (keys == null) { throw new ArgumentNullException("keys"); } if (String.IsNullOrEmpty(tokenId)) { throw new ArgumentException("Value cannot be a null or empty string.", "tokenId"); } foreach (byte[] key in keys) { if (key.Length <= 0) { throw new ArgumentException("The key length must be greater then zero.", "keys"); } } id = tokenId; effectiveTime = DateTime.UtcNow; securityKeys = CreateSymmetricSecurityKeys(keys); } /// <summary> /// Gets the unique identifier of the security token. /// </summary> public override string Id { get { return id; } } /// <summary> /// Gets the cryptographic keys associated with the security token. /// </summary> public override ReadOnlyCollection<SecurityKey> SecurityKeys { get { return securityKeys.AsReadOnly(); } } /// <summary> /// Gets the first instant in time at which this security token is valid. /// </summary> public override DateTime ValidFrom { get { return effectiveTime; } } /// <summary> /// Gets the last instant in time at which this security token is valid. /// </summary> public override DateTime ValidTo { get { // Never expire return DateTime.MaxValue; } } /// <summary> /// Returns a value that indicates whether the key identifier for this instance can be resolved to the specified key identifier. /// </summary> /// <param name="keyIdentifierClause">A SecurityKeyIdentifierClause to compare to this instance</param> /// <returns>true if keyIdentifierClause is a SecurityKeyIdentifierClause and it has the same unique identifier as the Id property; otherwise, false.</returns> public override bool MatchesKeyIdentifierClause(SecurityKeyIdentifierClause keyIdentifierClause) { if (keyIdentifierClause == null) { throw new ArgumentNullException("keyIdentifierClause"); } // Since this is a symmetric token and we do not have IDs to distinguish tokens, we just check for the // presence of a SymmetricIssuerKeyIdentifier. The actual mapping to the issuer takes place later // when the key is matched to the issuer. if (keyIdentifierClause is SymmetricIssuerKeyIdentifierClause) { return true; } return base.MatchesKeyIdentifierClause(keyIdentifierClause); } #region private members private List<SecurityKey> CreateSymmetricSecurityKeys(IEnumerable<byte[]> keys) { List<SecurityKey> symmetricKeys = new List<SecurityKey>(); foreach (byte[] key in keys) { symmetricKeys.Add(new InMemorySymmetricSecurityKey(key)); } return symmetricKeys; } private string id; private DateTime effectiveTime; private List<SecurityKey> securityKeys; #endregion } }
// Copyright 2012 The Noda Time Authors. All rights reserved. // Use of this source code is governed by the Apache License 2.0, // as found in the LICENSE.txt file. using NodaTime.Annotations; using NodaTime.Extensions; using NodaTime.Utility; using System; using System.Collections.Generic; using System.Linq; namespace NodaTime.TimeZones { /// <summary> /// Representation of a time zone converted from a <see cref="TimeZoneInfo"/> from the Base Class Library. /// </summary> /// <remarks> /// <para> /// Two instances of this class are deemed equal if and only if they refer to the exact same /// <see cref="TimeZoneInfo"/> object. /// </para> /// <para> /// This implementation does not always give the same results as <c>TimeZoneInfo</c>, in that it doesn't replicate /// the bugs in the BCL interpretation of the data. These bugs are described in /// <a href="http://codeblog.jonskeet.uk/2014/09/30/the-mysteries-of-bcl-time-zone-data/">a blog post</a>, but we're /// not expecting them to be fixed any time soon. Being bug-for-bug compatible would not only be tricky, but would be painful /// if the BCL were ever to be fixed. As far as we are aware, there are only discrepancies around new year where the zone /// changes from observing one rule to observing another. /// </para> /// </remarks> /// <threadsafety>This type is immutable reference type. See the thread safety section of the user guide for more information.</threadsafety> [Immutable] public sealed class BclDateTimeZone : DateTimeZone { /// <summary> /// This is used to cache the last result of a call to <see cref="ForSystemDefault"/>, but it doesn't /// matter if it's out of date - we'll just create another wrapper if necessary. It's not *that* expensive to make /// a few more wrappers than we need. /// </summary> private static BclDateTimeZone systemDefault; private readonly IZoneIntervalMap map; /// <summary> /// Gets the original <see cref="TimeZoneInfo"/> from which this was created. /// </summary> /// <value>The original <see cref="TimeZoneInfo"/> from which this was created.</value> public TimeZoneInfo OriginalZone { get; } /// <summary> /// Gets the display name associated with the time zone, as provided by the Base Class Library. /// </summary> /// <value>The display name associated with the time zone, as provided by the Base Class Library.</value> public string DisplayName => OriginalZone.DisplayName; private BclDateTimeZone(TimeZoneInfo bclZone, Offset minOffset, Offset maxOffset, IZoneIntervalMap map) : base(bclZone.Id, bclZone.SupportsDaylightSavingTime, minOffset, maxOffset) { this.OriginalZone = bclZone; this.map = map; } /// <inheritdoc /> public override ZoneInterval GetZoneInterval(Instant instant) { return map.GetZoneInterval(instant); } /// <summary> /// Creates a new <see cref="BclDateTimeZone" /> from a <see cref="TimeZoneInfo"/> from the Base Class Library. /// </summary> /// <param name="bclZone">The original time zone to take information from.</param> /// <returns>A <see cref="BclDateTimeZone"/> wrapping the given <c>TimeZoneInfo</c>.</returns> public static BclDateTimeZone FromTimeZoneInfo(TimeZoneInfo bclZone) { Preconditions.CheckNotNull(bclZone, nameof(bclZone)); Offset standardOffset = bclZone.BaseUtcOffset.ToOffset(); var rules = bclZone.GetAdjustmentRules(); if (!bclZone.SupportsDaylightSavingTime || rules.Length == 0) { var fixedInterval = new ZoneInterval(bclZone.StandardName, Instant.BeforeMinValue, Instant.AfterMaxValue, standardOffset, Offset.Zero); return new BclDateTimeZone(bclZone, standardOffset, standardOffset, new SingleZoneIntervalMap(fixedInterval)); } int windowsRules = rules.Count(IsWindowsRule); var ruleConverter = AreWindowsStyleRules(rules) ? rule => BclAdjustmentRule.FromWindowsAdjustmentRule(bclZone, rule) : (Converter<TimeZoneInfo.AdjustmentRule, BclAdjustmentRule>) (rule => BclAdjustmentRule.FromUnixAdjustmentRule(bclZone, rule)); BclAdjustmentRule[] convertedRules = Array.ConvertAll(rules, ruleConverter); Offset minRuleOffset = convertedRules.Aggregate(Offset.MaxValue, (min, rule) => Offset.Min(min, rule.Savings + rule.StandardOffset)); Offset maxRuleOffset = convertedRules.Aggregate(Offset.MinValue, (min, rule) => Offset.Max(min, rule.Savings + rule.StandardOffset)); IZoneIntervalMap uncachedMap = BuildMap(convertedRules, standardOffset, bclZone.StandardName); IZoneIntervalMap cachedMap = CachingZoneIntervalMap.CacheMap(uncachedMap); return new BclDateTimeZone(bclZone, Offset.Min(standardOffset, minRuleOffset), Offset.Max(standardOffset, maxRuleOffset), cachedMap); } /// <summary> /// .NET Core on Unix adjustment rules can't currently be treated like regular Windows ones. /// Instead of dividing time into periods by year, the rules are read from TZIF files, so are like /// our PrecalculatedDateTimeZone. This is only visible for testing purposes. /// </summary> internal static bool AreWindowsStyleRules(TimeZoneInfo.AdjustmentRule[] rules) { int windowsRules = rules.Count(IsWindowsRule); return windowsRules == rules.Length; bool IsWindowsRule(TimeZoneInfo.AdjustmentRule rule) => rule.DateStart.Month == 1 && rule.DateStart.Day == 1 && rule.DateStart.TimeOfDay.Ticks == 0 && rule.DateEnd.Month == 12 && rule.DateEnd.Day == 31 && rule.DateEnd.TimeOfDay.Ticks == 0; } private static bool IsWindowsRule(TimeZoneInfo.AdjustmentRule rule) => rule.DateStart.Month == 1 && rule.DateStart.Day == 1 && rule.DateStart.TimeOfDay.Ticks == 0 && rule.DateEnd.Month == 12 && rule.DateEnd.Day == 31 && rule.DateEnd.TimeOfDay.Ticks == 0; private static IZoneIntervalMap BuildMap(BclAdjustmentRule[] rules, Offset standardOffset, string standardName) { Preconditions.CheckNotNull(standardName, nameof(standardName)); // First work out a naive list of partial maps. These will give the right offset at every instant, but not necessarily // correct intervals - we may we need to stitch intervals together. List<PartialZoneIntervalMap> maps = new List<PartialZoneIntervalMap>(); // Handle the start of time until the start of the first rule, if necessary. if (rules[0].Start.IsValid) { maps.Add(PartialZoneIntervalMap.ForZoneInterval(standardName, Instant.BeforeMinValue, rules[0].Start, standardOffset, Offset.Zero)); } for (int i = 0; i < rules.Length - 1; i++) { var beforeRule = rules[i]; var afterRule = rules[i + 1]; maps.Add(beforeRule.PartialMap); // If there's a gap between this rule and the next one, fill it with a fixed interval. if (beforeRule.End < afterRule.Start) { maps.Add(PartialZoneIntervalMap.ForZoneInterval(standardName, beforeRule.End, afterRule.Start, standardOffset, Offset.Zero)); } } var lastRule = rules[rules.Length - 1]; maps.Add(lastRule.PartialMap); // Handle the end of the last rule until the end of time, if necessary. if (lastRule.End.IsValid) { maps.Add(PartialZoneIntervalMap.ForZoneInterval(standardName, lastRule.End, Instant.AfterMaxValue, standardOffset, Offset.Zero)); } return PartialZoneIntervalMap.ConvertToFullMap(maps); } /// <summary> /// Just a mapping of a TimeZoneInfo.AdjustmentRule into Noda Time types. Very little cleverness here. /// </summary> private sealed class BclAdjustmentRule { private static readonly DateTime MaxDate = DateTime.MaxValue.Date; /// <summary> /// Instant on which this rule starts. /// </summary> internal Instant Start { get; } /// <summary> /// Instant on which this rule ends. /// </summary> internal Instant End { get; } /// <summary> /// Daylight savings, when applicable within this rule. /// </summary> internal Offset Savings { get; } /// <summary> /// The standard offset for the duration of this rule. /// </summary> internal Offset StandardOffset { get; } internal PartialZoneIntervalMap PartialMap { get; } private BclAdjustmentRule(Instant start, Instant end, Offset standardOffset, Offset savings, PartialZoneIntervalMap partialMap) { Start = start; End = end; StandardOffset = standardOffset; Savings = savings; PartialMap = partialMap; } internal static BclAdjustmentRule FromUnixAdjustmentRule(TimeZoneInfo zone, TimeZoneInfo.AdjustmentRule rule) { // On .NET Core on Unix, each "adjustment rule" is effectively just a zone interval. The transitions are only used // to give the time of day values to combine with rule.DateStart and rule.DateEnd. It's all a bit odd. // The *last* adjustment rule internally can work like a normal Windows standard/daylight rule, but currently that's // not exposed properly. var bclLocalStart = rule.DateStart + rule.DaylightTransitionStart.TimeOfDay.TimeOfDay; var bclLocalEnd = rule.DateEnd + rule.DaylightTransitionEnd.TimeOfDay.TimeOfDay; var bclUtcStart = DateTime.SpecifyKind(bclLocalStart == DateTime.MinValue ? DateTime.MinValue : bclLocalStart - zone.BaseUtcOffset, DateTimeKind.Utc); var bclWallOffset = zone.GetUtcOffset(bclUtcStart); var bclSavings = rule.DaylightDelta; var bclUtcEnd = DateTime.SpecifyKind(rule.DateEnd == MaxDate ? DateTime.MaxValue : bclLocalEnd - (zone.BaseUtcOffset + bclSavings), DateTimeKind.Utc); var isDst = zone.IsDaylightSavingTime(bclUtcStart); // The BCL rule can't express "It's DST with a changed standard time" so we sometimes end // up with DST but no savings. Assume this means a savings of 1 hour. That's not a valid // assumption in all cases, but it's probably better than alternatives, given limited information. if (isDst && bclSavings == TimeSpan.Zero) { bclSavings = TimeSpan.FromHours(1); } // Sometimes the rule says "This rule doesn't apply daylight savings" but still has a daylight // savings delta. Extremely bizarre: just override the savings to zero. if (!isDst && bclSavings != TimeSpan.Zero) { bclSavings = TimeSpan.Zero; } // Handle changes crossing the international date line, which are represented as savings of +/-23 // hours (but could conceivably be more). if (bclSavings.Hours < -14) { bclSavings += TimeSpan.FromDays(1); } else if (bclSavings.Hours > 14) { bclSavings -= TimeSpan.FromDays(1); } var bclStandard = bclWallOffset - bclSavings; // Now all the values are sensible - and in particular, now the daylight savings are in a range that can be represented by // Offset - we can converted everything to Noda Time types. var nodaStart = bclUtcStart == DateTime.MinValue ? Instant.BeforeMinValue : bclUtcStart.ToInstant(); // The representation returned to us (not the internal representation) has an end point one second before the transition. var nodaEnd = bclUtcEnd == DateTime.MaxValue ? Instant.AfterMaxValue : bclUtcEnd.ToInstant() + Duration.FromSeconds(1); var nodaWallOffset = bclWallOffset.ToOffset(); var nodaStandard = bclStandard.ToOffset(); var nodaSavings = bclSavings.ToOffset(); var partialMap = PartialZoneIntervalMap.ForZoneInterval(isDst ? zone.StandardName : zone.DaylightName, nodaStart, nodaEnd, nodaWallOffset, nodaSavings); return new BclAdjustmentRule(nodaStart, nodaEnd, nodaStandard, nodaSavings, partialMap); } internal static BclAdjustmentRule FromWindowsAdjustmentRule(TimeZoneInfo zone, TimeZoneInfo.AdjustmentRule rule) { // With .NET 4.6, adjustment rules can have their own standard offsets, allowing // a much more reasonable set of time zone data. Unfortunately, this isn't directly // exposed, but we can detect it by just finding the UTC offset for an arbitrary // time within the rule - the start, in this case - and then take account of the // possibility of that being in daylight saving time. Fortunately, we only need // to do this during the setup. var ruleStandardOffset = zone.GetUtcOffset(rule.DateStart); if (zone.IsDaylightSavingTime(rule.DateStart)) { ruleStandardOffset -= rule.DaylightDelta; } var standardOffset = ruleStandardOffset.ToOffset(); // Although the rule may have its own standard offset, the start/end is still determined // using the zone's standard offset. var zoneStandardOffset = zone.BaseUtcOffset.ToOffset(); // Note: this extends back from DateTime.MinValue to start of time, even though the BCL can represent // as far back as 1AD. This is in the *spirit* of a rule which goes back that far. var start = rule.DateStart == DateTime.MinValue ? Instant.BeforeMinValue : rule.DateStart.ToLocalDateTime().WithOffset(zoneStandardOffset).ToInstant(); // The end instant (exclusive) is the end of the given date, so we need to add a day. var end = rule.DateEnd == MaxDate ? Instant.AfterMaxValue : rule.DateEnd.ToLocalDateTime().PlusDays(1).WithOffset(zoneStandardOffset).ToInstant(); var savings = rule.DaylightDelta.ToOffset(); PartialZoneIntervalMap partialMap; // Some rules have DST start/end of "January 1st", to indicate that they're just in standard time. This is important // for rules which have a standard offset which is different to the standard offset of the zone itself. if (IsStandardOffsetOnlyRule(rule)) { partialMap = PartialZoneIntervalMap.ForZoneInterval(zone.StandardName, start, end, standardOffset, Offset.Zero); } else { var daylightRecurrence = new ZoneRecurrence(zone.DaylightName, savings, ConvertTransition(rule.DaylightTransitionStart), int.MinValue, int.MaxValue); var standardRecurrence = new ZoneRecurrence(zone.StandardName, Offset.Zero, ConvertTransition(rule.DaylightTransitionEnd), int.MinValue, int.MaxValue); IZoneIntervalMap recurringMap = new StandardDaylightAlternatingMap(standardOffset, standardRecurrence, daylightRecurrence); // Fake 1 hour savings if the adjustment rule claims to be 0 savings. See DaylightFakingZoneIntervalMap documentation below for more details. if (savings == Offset.Zero) { recurringMap = new DaylightFakingZoneIntervalMap(recurringMap, zone.DaylightName); } partialMap = new PartialZoneIntervalMap(start, end, recurringMap); } return new BclAdjustmentRule(start, end, standardOffset, savings, partialMap); } /// <summary> /// An implementation of IZoneIntervalMap that delegates to an original map, except for where the result of a /// ZoneInterval lookup has the given daylight name. In that case, a new ZoneInterval is built with the same /// wall offset (and start/end instants etc), but with a savings of 1 hour. This is only used to work around TimeZoneInfo /// adjustment rules with a daylight saving of 0 which are really trying to fake a more comprehensive solution. /// (This is currently only seen on Mono on Linux...) /// This addresses https://github.com/nodatime/nodatime/issues/746. /// If TimeZoneInfo had sufficient flexibility to use different names for different periods of time, we'd have /// another problem, as some "daylight names" don't always mean daylight - e.g. "BST" = British Summer Time and British Standard Time. /// In this case, the limited nature of TimeZoneInfo works in our favour. /// </summary> private sealed class DaylightFakingZoneIntervalMap : IZoneIntervalMap { private readonly IZoneIntervalMap originalMap; private readonly string daylightName; internal DaylightFakingZoneIntervalMap(IZoneIntervalMap originalMap, string daylightName) { this.originalMap = originalMap; this.daylightName = daylightName; } public ZoneInterval GetZoneInterval(Instant instant) { var interval = originalMap.GetZoneInterval(instant); return interval.Name == daylightName ? new ZoneInterval(daylightName, interval.RawStart, interval.RawEnd, interval.WallOffset, Offset.FromHours(1)) : interval; } } /// <summary> /// The BCL represents "standard-only" rules using two fixed date January 1st transitions. /// Currently the time-of-day used for the DST end transition is at one millisecond past midnight... we'll /// be slightly more lenient, accepting anything up to 12:01... /// </summary> private static bool IsStandardOffsetOnlyRule(TimeZoneInfo.AdjustmentRule rule) { var daylight = rule.DaylightTransitionStart; var standard = rule.DaylightTransitionEnd; return daylight.IsFixedDateRule && daylight.Day == 1 && daylight.Month == 1 && daylight.TimeOfDay.TimeOfDay < TimeSpan.FromMinutes(1) && standard.IsFixedDateRule && standard.Day == 1 && standard.Month == 1 && standard.TimeOfDay.TimeOfDay < TimeSpan.FromMinutes(1); } // Converts a TimeZoneInfo "TransitionTime" to a "ZoneYearOffset" - the two correspond pretty closely. private static ZoneYearOffset ConvertTransition(TimeZoneInfo.TransitionTime transitionTime) { // Used for both fixed and non-fixed transitions. LocalTime timeOfDay = LocalDateTime.FromDateTime(transitionTime.TimeOfDay).TimeOfDay; // Easy case - fixed day of the month. if (transitionTime.IsFixedDateRule) { return new ZoneYearOffset(TransitionMode.Wall, transitionTime.Month, transitionTime.Day, 0, false, timeOfDay); } // Floating: 1st Sunday in March etc. int dayOfWeek = (int) BclConversions.ToIsoDayOfWeek(transitionTime.DayOfWeek); int dayOfMonth; bool advance; // "Last" if (transitionTime.Week == 5) { advance = false; dayOfMonth = -1; } else { advance = true; // Week 1 corresponds to ">=1" // Week 2 corresponds to ">=8" etc dayOfMonth = (transitionTime.Week * 7) - 6; } return new ZoneYearOffset(TransitionMode.Wall, transitionTime.Month, dayOfMonth, dayOfWeek, advance, timeOfDay); } } /// <summary> /// Returns a time zone converted from the BCL representation of the system local time zone. /// </summary> /// <remarks> /// <para> /// This method is approximately equivalent to calling <see cref="IDateTimeZoneProvider.GetSystemDefault"/> with /// an implementation that wraps <see cref="BclDateTimeZoneSource"/> (e.g. /// <see cref="DateTimeZoneProviders.Bcl"/>), with the exception that it will succeed even if the current local /// time zone was not one of the set of system time zones captured when the source was created (which, while /// highly unlikely, might occur either because the local time zone is not a system time zone, or because the /// system time zones have themselves changed). /// </para> /// <para> /// This method will retain a reference to the returned <c>BclDateTimeZone</c>, and will attempt to return it if /// called repeatedly (assuming that the local time zone has not changed) rather than creating a new instance, /// though this behaviour is not guaranteed. /// </para> /// </remarks> /// <exception cref="InvalidOperationException">The system does not provide a time zone.</exception> /// <returns>A <see cref="BclDateTimeZone"/> wrapping the "local" (system) time zone as returned by /// <see cref="TimeZoneInfo.Local"/>.</returns> public static BclDateTimeZone ForSystemDefault() { TimeZoneInfo? local = TimeZoneInfoInterceptor.Local; if (local is null) { throw new InvalidOperationException("No system default time zone is available"); } BclDateTimeZone currentSystemDefault = systemDefault; // Cached copy is out of date - wrap a new one. // If currentSystemDefault is null, we always enter this block (as local isn't null). if (currentSystemDefault?.OriginalZone != local) { currentSystemDefault = FromTimeZoneInfo(local); systemDefault = currentSystemDefault; } // Always return our local variable; the field may have changed again. // The ! is because the compiler doesn't recognize the logic around // "always fetch if we currentSystemDefault is null". return currentSystemDefault!; } } }
// Licensed to the .NET Foundation under one or more agreements. // See the LICENSE file in the project root for more information. // (C) Punit Todi // // Copyright (C) 2004 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using Xunit; namespace System.Data.Tests { public class DataTableCollectionTest : IDisposable { // common variables here private DataSet[] _dataset; private DataTable[] _tables; public DataTableCollectionTest() { // setting up dataset && tables _dataset = new DataSet[2]; _tables = new DataTable[2]; _dataset[0] = new DataSet(); _dataset[1] = new DataSet(); _tables[0] = new DataTable("Books"); _tables[0].Columns.Add("id", typeof(int)); _tables[0].Columns.Add("name", typeof(string)); _tables[0].Columns.Add("author", typeof(string)); _tables[1] = new DataTable("Category"); _tables[1].Columns.Add("id", typeof(int)); _tables[1].Columns.Add("desc", typeof(string)); } // clean up code here public void Dispose() { _dataset[0].Tables.Clear(); _dataset[1].Tables.Clear(); } [Fact] public void Add() { DataTableCollection tbcol = _dataset[0].Tables; tbcol.Add(_tables[0]); int i, j; i = 0; foreach (DataTable table in tbcol) { Assert.Equal(_tables[i].TableName, table.TableName); j = 0; foreach (DataColumn column in table.Columns) { Assert.Equal(_tables[i].Columns[j].ColumnName, column.ColumnName); j++; } i++; } tbcol.Add(_tables[1]); i = 0; foreach (DataTable table in tbcol) { Assert.Equal(_tables[i].TableName, table.TableName); j = 0; foreach (DataColumn column in table.Columns) { Assert.Equal(_tables[i].Columns[j].ColumnName, column.ColumnName); j++; } i++; } } [Fact] public void AddException1() { Assert.Throws<ArgumentNullException>(() => { DataTableCollection tbcol = _dataset[0].Tables; DataTable tb = null; tbcol.Add(tb); }); } [Fact] public void AddException2() { Assert.Throws<ArgumentException>(() => { /* table already exist in the collection */ DataTableCollection tbcol = _dataset[0].Tables; tbcol.Add(_tables[0]); tbcol.Add(_tables[0]); }); } [Fact] public void AddException3() { Assert.Throws<DuplicateNameException>(() => { DataTableCollection tbcol = _dataset[0].Tables; tbcol.Add(new DataTable("SameTableName")); tbcol.Add(new DataTable("SameTableName")); }); } [Fact] public void AddException4() { Assert.Throws<DuplicateNameException>(() => { DataTableCollection tbcol = _dataset[0].Tables; tbcol.Add("SameTableName"); tbcol.Add("SameTableName"); }); } [Fact] public void Count() { DataTableCollection tbcol = _dataset[0].Tables; tbcol.Add(_tables[0]); Assert.Equal(1, tbcol.Count); tbcol.Add(_tables[1]); Assert.Equal(2, tbcol.Count); } [Fact] public void AddRange() { DataTableCollection tbcol = _dataset[0].Tables; tbcol.Clear(); /* _tables is array of type DataTable defined in Setup */ tbcol.AddRange(_tables); int i, j; i = 0; foreach (DataTable table in tbcol) { Assert.Equal(_tables[i].TableName, table.TableName); j = 0; foreach (DataColumn column in table.Columns) { Assert.Equal(_tables[i].Columns[j].ColumnName, column.ColumnName); j++; } i++; } } [Fact] public void CanRemove() { DataTableCollection tbcol = _dataset[0].Tables; tbcol.Clear(); /* _tables is array of DataTables defined in Setup */ tbcol.AddRange(_tables); DataTable tbl = null; /* checking for a recently input table, expecting true */ Assert.Equal(true, tbcol.CanRemove(_tables[0])); /* trying to check with a null reference, expecting false */ Assert.Equal(false, tbcol.CanRemove(tbl)); /* trying to check with a table that does not exist in collection, expecting false */ Assert.Equal(false, tbcol.CanRemove(new DataTable("newTable"))); } [Fact] public void Remove() { DataTableCollection tbcol = _dataset[0].Tables; tbcol.Clear(); /* _tables is array of DataTables defined in Setup */ tbcol.AddRange(_tables); /* removing a recently added table */ int count = tbcol.Count; tbcol.Remove(_tables[0]); Assert.Equal(count - 1, tbcol.Count); DataTable tbl = null; /* removing a null reference. must generate an Exception */ try { tbcol.Remove(tbl); Assert.False(true); } catch (Exception e) { Assert.Equal(typeof(ArgumentNullException), e.GetType()); } /* removing a table that is not there in collection */ try { tbcol.Remove(new DataTable("newTable")); Assert.False(true); } catch (Exception e) { Assert.Equal(typeof(ArgumentException), e.GetType()); } } [Fact] public void Clear() { DataTableCollection tbcol = _dataset[0].Tables; tbcol.Add(_tables[0]); tbcol.Clear(); Assert.Equal(0, tbcol.Count); tbcol.AddRange(new DataTable[] { _tables[0], _tables[1] }); tbcol.Clear(); Assert.Equal(0, tbcol.Count); } [Fact] public void Contains() { DataTableCollection tbcol = _dataset[0].Tables; tbcol.Clear(); /* _tables is array of DataTables defined in Setup */ tbcol.AddRange(_tables); string tblname = ""; /* checking for a recently input table, expecting true */ Assert.Equal(true, tbcol.Contains(_tables[0].TableName)); /* trying to check with a empty string, expecting false */ Assert.Equal(false, tbcol.Contains(tblname)); /* trying to check for a table that donot exist, expecting false */ Assert.Equal(false, tbcol.Contains("InvalidTableName")); } [Fact] public void CopyTo() { DataTableCollection tbcol = _dataset[0].Tables; tbcol.Add("Table1"); tbcol.Add("Table2"); tbcol.Add("Table3"); tbcol.Add("Table4"); DataTable[] array = new DataTable[4]; /* copying to the beginning of the array */ tbcol.CopyTo(array, 0); Assert.Equal(4, array.Length); Assert.Equal("Table1", array[0].TableName); Assert.Equal("Table2", array[1].TableName); Assert.Equal("Table3", array[2].TableName); Assert.Equal("Table4", array[3].TableName); /* copying with in a array */ DataTable[] array1 = new DataTable[6]; tbcol.CopyTo(array1, 2); Assert.Equal(null, array1[0]); Assert.Equal(null, array1[1]); Assert.Equal("Table1", array1[2].TableName); Assert.Equal("Table2", array1[3].TableName); Assert.Equal("Table3", array1[4].TableName); Assert.Equal("Table4", array1[5].TableName); } [Fact] public void Equals() { DataTableCollection tbcol1 = _dataset[0].Tables; DataTableCollection tbcol2 = _dataset[1].Tables; DataTableCollection tbcol3; tbcol1.Add(_tables[0]); tbcol2.Add(_tables[1]); tbcol3 = tbcol1; Assert.Equal(true, tbcol1.Equals(tbcol1)); Assert.Equal(true, tbcol1.Equals(tbcol3)); Assert.Equal(true, tbcol3.Equals(tbcol1)); Assert.Equal(false, tbcol1.Equals(tbcol2)); Assert.Equal(false, tbcol2.Equals(tbcol1)); Assert.Equal(true, object.Equals(tbcol1, tbcol3)); Assert.Equal(true, object.Equals(tbcol1, tbcol1)); Assert.Equal(false, object.Equals(tbcol1, tbcol2)); } [Fact] public void IndexOf() { DataTableCollection tbcol = _dataset[0].Tables; tbcol.Add(_tables[0]); tbcol.Add("table1"); tbcol.Add("table2"); Assert.Equal(0, tbcol.IndexOf(_tables[0])); Assert.Equal(-1, tbcol.IndexOf(_tables[1])); Assert.Equal(1, tbcol.IndexOf("table1")); Assert.Equal(2, tbcol.IndexOf("table2")); Assert.Equal(0, tbcol.IndexOf(tbcol[0])); Assert.Equal(1, tbcol.IndexOf(tbcol[1])); Assert.Equal(-1, tbcol.IndexOf("_noTable_")); DataTable tb = new DataTable("new_table"); Assert.Equal(-1, tbcol.IndexOf(tb)); } [Fact] public void RemoveAt() { DataTableCollection tbcol = _dataset[0].Tables; tbcol.Add(_tables[0]); tbcol.Add("table1"); try { tbcol.RemoveAt(-1); Assert.False(true); } catch (IndexOutOfRangeException e) { } try { tbcol.RemoveAt(101); Assert.False(true); } catch (IndexOutOfRangeException e) { } tbcol.RemoveAt(1); Assert.Equal(1, tbcol.Count); tbcol.RemoveAt(0); Assert.Equal(0, tbcol.Count); } [Fact] public void ToStringTest() { DataTableCollection tbcol = _dataset[0].Tables; tbcol.Add("Table1"); tbcol.Add("Table2"); tbcol.Add("Table3"); Assert.Equal("System.Data.DataTableCollection", tbcol.ToString()); } [Fact] public void TableDataSetNamespaces() { DataTable dt = new DataTable("dt1"); Assert.Equal(string.Empty, dt.Namespace); Assert.Null(dt.DataSet); DataSet ds1 = new DataSet("ds1"); ds1.Tables.Add(dt); Assert.Equal(string.Empty, dt.Namespace); Assert.Equal(ds1, dt.DataSet); ds1.Namespace = "ns1"; Assert.Equal("ns1", dt.Namespace); // back to null again ds1.Tables.Remove(dt); Assert.Equal(string.Empty, dt.Namespace); Assert.Null(dt.DataSet); // This table is being added to _already namespaced_ // dataset. dt = new DataTable("dt2"); ds1.Tables.Add(dt); Assert.Equal("ns1", dt.Namespace); Assert.Equal(ds1, dt.DataSet); ds1.Tables.Remove(dt); Assert.Equal(string.Empty, dt.Namespace); Assert.Null(dt.DataSet); DataSet ds2 = new DataSet("ds2"); ds2.Namespace = "ns2"; ds2.Tables.Add(dt); Assert.Equal("ns2", dt.Namespace); Assert.Equal(ds2, dt.DataSet); } } }
using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Net.Mime; using System.Text; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Options; using Umbraco.Cms.Core; using Umbraco.Cms.Core.Configuration.Models; using Umbraco.Cms.Core.Mapping; using Umbraco.Cms.Core.Models; using Umbraco.Cms.Core.Models.ContentEditing; using Umbraco.Cms.Core.PropertyEditors; using Umbraco.Cms.Core.Security; using Umbraco.Cms.Core.Serialization; using Umbraco.Cms.Core.Services; using Umbraco.Cms.Web.BackOffice.Filters; using Umbraco.Cms.Web.Common.Attributes; using Umbraco.Cms.Web.Common.Authorization; using Umbraco.Extensions; using Constants = Umbraco.Cms.Core.Constants; namespace Umbraco.Cms.Web.BackOffice.Controllers { /// <summary> /// The API controller used for editing data types /// </summary> /// <remarks> /// The security for this controller is defined to allow full CRUD access to data types if the user has access to either: /// Content Types, Member Types or Media Types ... and of course to Data Types /// </remarks> [PluginController(Constants.Web.Mvc.BackOfficeApiArea)] [Authorize(Policy = AuthorizationPolicies.TreeAccessDocumentsOrDocumentTypes)] [ParameterSwapControllerActionSelector(nameof(GetById), "id", typeof(int), typeof(Guid), typeof(Udi))] public class DataTypeController : BackOfficeNotificationsController { private readonly PropertyEditorCollection _propertyEditors; private readonly IDataTypeService _dataTypeService; private readonly ContentSettings _contentSettings; private readonly IUmbracoMapper _umbracoMapper; private readonly PropertyEditorCollection _propertyEditorCollection; private readonly IContentTypeService _contentTypeService; private readonly IMediaTypeService _mediaTypeService; private readonly IMemberTypeService _memberTypeService; private readonly ILocalizedTextService _localizedTextService; private readonly IBackOfficeSecurityAccessor _backOfficeSecurityAccessor; private readonly IConfigurationEditorJsonSerializer _serializer; public DataTypeController( PropertyEditorCollection propertyEditors, IDataTypeService dataTypeService, IOptions<ContentSettings> contentSettings, IUmbracoMapper umbracoMapper, PropertyEditorCollection propertyEditorCollection, IContentTypeService contentTypeService, IMediaTypeService mediaTypeService, IMemberTypeService memberTypeService, ILocalizedTextService localizedTextService, IBackOfficeSecurityAccessor backOfficeSecurityAccessor, IConfigurationEditorJsonSerializer serializer) { _propertyEditors = propertyEditors ?? throw new ArgumentNullException(nameof(propertyEditors)); _dataTypeService = dataTypeService ?? throw new ArgumentNullException(nameof(dataTypeService)); _contentSettings = contentSettings.Value ?? throw new ArgumentNullException(nameof(contentSettings)); _umbracoMapper = umbracoMapper ?? throw new ArgumentNullException(nameof(umbracoMapper)); _propertyEditorCollection = propertyEditorCollection ?? throw new ArgumentNullException(nameof(propertyEditorCollection)); _contentTypeService = contentTypeService ?? throw new ArgumentNullException(nameof(contentTypeService)); _mediaTypeService = mediaTypeService ?? throw new ArgumentNullException(nameof(mediaTypeService)); _memberTypeService = memberTypeService ?? throw new ArgumentNullException(nameof(memberTypeService)); _localizedTextService = localizedTextService ?? throw new ArgumentNullException(nameof(localizedTextService)); _backOfficeSecurityAccessor = backOfficeSecurityAccessor ?? throw new ArgumentNullException(nameof(backOfficeSecurityAccessor)); _serializer = serializer ?? throw new ArgumentNullException(nameof(serializer)); } /// <summary> /// Gets data type by name /// </summary> /// <param name="name"></param> /// <returns></returns> public DataTypeDisplay GetByName(string name) { var dataType = _dataTypeService.GetDataType(name); return dataType == null ? null : _umbracoMapper.Map<IDataType, DataTypeDisplay>(dataType); } /// <summary> /// Gets the datatype json for the datatype id /// </summary> /// <param name="id"></param> /// <returns></returns> public ActionResult<DataTypeDisplay> GetById(int id) { var dataType = _dataTypeService.GetDataType(id); if (dataType == null) { return NotFound(); } return _umbracoMapper.Map<IDataType, DataTypeDisplay>(dataType); } /// <summary> /// Gets the datatype json for the datatype guid /// </summary> /// <param name="id"></param> /// <returns></returns> public ActionResult<DataTypeDisplay> GetById(Guid id) { var dataType = _dataTypeService.GetDataType(id); if (dataType == null) { return NotFound(); } return _umbracoMapper.Map<IDataType, DataTypeDisplay>(dataType); } /// <summary> /// Gets the datatype json for the datatype udi /// </summary> /// <param name="id"></param> /// <returns></returns> public ActionResult<DataTypeDisplay> GetById(Udi id) { var guidUdi = id as GuidUdi; if (guidUdi == null) return NotFound(); var dataType = _dataTypeService.GetDataType(guidUdi.Guid); if (dataType == null) { return NotFound(); } return _umbracoMapper.Map<IDataType, DataTypeDisplay>(dataType); } /// <summary> /// Deletes a data type with a given ID /// </summary> /// <param name="id"></param> /// <returns></returns> [HttpDelete] [HttpPost] public IActionResult DeleteById(int id) { var foundType = _dataTypeService.GetDataType(id); if (foundType == null) { return NotFound(); } var currentUser = _backOfficeSecurityAccessor.BackOfficeSecurity.CurrentUser; _dataTypeService.Delete(foundType, currentUser.Id); return Ok(); } public DataTypeDisplay GetEmpty(int parentId) { // cannot create an "empty" data type, so use something by default. var editor = _propertyEditors[Constants.PropertyEditors.Aliases.Label]; var dt = new DataType(editor, _serializer, parentId); return _umbracoMapper.Map<IDataType, DataTypeDisplay>(dt); } /// <summary> /// Returns a custom listview, based on a content type alias, if found /// </summary> /// <param name="contentTypeAlias"></param> /// <returns>a DataTypeDisplay</returns> public ActionResult<DataTypeDisplay> GetCustomListView(string contentTypeAlias) { var dt = _dataTypeService.GetDataType(Constants.Conventions.DataTypes.ListViewPrefix + contentTypeAlias); if (dt == null) { return NotFound(); } return _umbracoMapper.Map<IDataType, DataTypeDisplay>(dt); } /// <summary> /// Creates a custom list view - give a document type alias /// </summary> /// <param name="contentTypeAlias"></param> /// <returns></returns> public DataTypeDisplay PostCreateCustomListView(string contentTypeAlias) { var dt = _dataTypeService.GetDataType(Constants.Conventions.DataTypes.ListViewPrefix + contentTypeAlias); //if it doesn't exist yet, we will create it. if (dt == null) { var editor = _propertyEditors[Constants.PropertyEditors.Aliases.ListView]; dt = new DataType(editor, _serializer) { Name = Constants.Conventions.DataTypes.ListViewPrefix + contentTypeAlias }; _dataTypeService.Save(dt); } return _umbracoMapper.Map<IDataType, DataTypeDisplay>(dt); } /// <summary> /// Returns the pre-values for the specified property editor /// </summary> /// <param name="editorAlias"></param> /// <param name="dataTypeId">The data type id for the pre-values, -1 if it is a new data type</param> /// <returns></returns> public ActionResult<IEnumerable<DataTypeConfigurationFieldDisplay>> GetPreValues(string editorAlias, int dataTypeId = -1) { var propEd = _propertyEditors[editorAlias]; if (propEd == null) { throw new InvalidOperationException("Could not find property editor with alias " + editorAlias); } if (dataTypeId == -1) { //this is a new data type, so just return the field editors with default values return new ActionResult<IEnumerable<DataTypeConfigurationFieldDisplay>>(_umbracoMapper.Map<IDataEditor, IEnumerable<DataTypeConfigurationFieldDisplay>>(propEd)); } //we have a data type associated var dataType = _dataTypeService.GetDataType(dataTypeId); if (dataType == null) { return NotFound(); } //now, lets check if the data type has the current editor selected, if that is true //we will need to wire up it's saved values. Otherwise it's an existing data type //that is changing it's underlying property editor, in which case there's no values. if (dataType.EditorAlias == editorAlias) { //this is the currently assigned pre-value editor, return with values. return new ActionResult<IEnumerable<DataTypeConfigurationFieldDisplay>>(_umbracoMapper.Map<IDataType, IEnumerable<DataTypeConfigurationFieldDisplay>>(dataType)); } //these are new pre-values, so just return the field editors with default values return new ActionResult<IEnumerable<DataTypeConfigurationFieldDisplay>>(_umbracoMapper.Map<IDataEditor, IEnumerable<DataTypeConfigurationFieldDisplay>>(propEd)); } /// <summary> /// Deletes a data type container with a given ID /// </summary> /// <param name="id"></param> /// <returns></returns> [HttpDelete] [HttpPost] public IActionResult DeleteContainer(int id) { var currentUser = _backOfficeSecurityAccessor.BackOfficeSecurity.CurrentUser; _dataTypeService.DeleteContainer(id, currentUser.Id); return Ok(); } public IActionResult PostCreateContainer(int parentId, string name) { var currentUser = _backOfficeSecurityAccessor.BackOfficeSecurity.CurrentUser; var result = _dataTypeService.CreateContainer(parentId, Guid.NewGuid(), name, currentUser.Id); if (result.Success) return Ok(result.Result); //return the id else return ValidationProblem(result.Exception.Message); } /// <summary> /// Saves the data type /// </summary> /// <param name="dataType"></param> /// <returns></returns> [DataTypeValidate] public ActionResult<DataTypeDisplay> PostSave(DataTypeSave dataType) { //If we've made it here, then everything has been wired up and validated by the attribute // TODO: Check if the property editor has changed, if it has ensure we don't pass the // existing values to the new property editor! // get the current configuration, // get the new configuration as a dictionary (this is how we get it from model) // and map to an actual configuration object var currentConfiguration = dataType.PersistedDataType.Configuration; var configurationDictionary = dataType.ConfigurationFields.ToDictionary(x => x.Key, x => x.Value); var configuration = dataType.PropertyEditor.GetConfigurationEditor().FromConfigurationEditor(configurationDictionary, currentConfiguration); dataType.PersistedDataType.Configuration = configuration; var currentUser = _backOfficeSecurityAccessor.BackOfficeSecurity.CurrentUser; // save the data type try { _dataTypeService.Save(dataType.PersistedDataType, currentUser.Id); } catch (DuplicateNameException ex) { ModelState.AddModelError("Name", ex.Message); return ValidationProblem(ModelState); } // map back to display model, and return var display = _umbracoMapper.Map<IDataType, DataTypeDisplay>(dataType.PersistedDataType); display.AddSuccessNotification(_localizedTextService.Localize("speechBubbles", "dataTypeSaved"), ""); return display; } /// <summary> /// Move the media type /// </summary> /// <param name="move"></param> /// <returns></returns> public IActionResult PostMove(MoveOrCopy move) { var toMove = _dataTypeService.GetDataType(move.Id); if (toMove == null) { return NotFound(); } var result = _dataTypeService.Move(toMove, move.ParentId); if (result.Success) { return Content(toMove.Path,MediaTypeNames.Text.Plain, Encoding.UTF8); } switch (result.Result.Result) { case MoveOperationStatusType.FailedParentNotFound: return NotFound(); case MoveOperationStatusType.FailedCancelledByEvent: return ValidationProblem(); case MoveOperationStatusType.FailedNotAllowedByPath: var notificationModel = new SimpleNotificationModel(); notificationModel.AddErrorNotification(_localizedTextService.Localize("moveOrCopy", "notAllowedByPath"), ""); return ValidationProblem(notificationModel); default: throw new ArgumentOutOfRangeException(); } } public IActionResult PostRenameContainer(int id, string name) { var currentUser = _backOfficeSecurityAccessor.BackOfficeSecurity.CurrentUser; var result = _dataTypeService.RenameContainer(id, name, currentUser.Id); if (result.Success) return Ok(result.Result); else return ValidationProblem(result.Exception.Message); } /// <summary> /// Returns the references (usages) for the data type /// </summary> /// <param name="id"></param> /// <returns></returns> public DataTypeReferences GetReferences(int id) { var result = new DataTypeReferences(); var usages = _dataTypeService.GetReferences(id); foreach(var groupOfEntityType in usages.GroupBy(x => x.Key.EntityType)) { //get all the GUIDs for the content types to find var guidsAndPropertyAliases = groupOfEntityType.ToDictionary(i => ((GuidUdi)i.Key).Guid, i => i.Value); if (groupOfEntityType.Key == ObjectTypes.GetUdiType(UmbracoObjectTypes.DocumentType)) result.DocumentTypes = GetContentTypeUsages(_contentTypeService.GetAll(guidsAndPropertyAliases.Keys), guidsAndPropertyAliases); else if (groupOfEntityType.Key == ObjectTypes.GetUdiType(UmbracoObjectTypes.MediaType)) result.MediaTypes = GetContentTypeUsages(_mediaTypeService.GetAll(guidsAndPropertyAliases.Keys), guidsAndPropertyAliases); else if (groupOfEntityType.Key == ObjectTypes.GetUdiType(UmbracoObjectTypes.MemberType)) result.MemberTypes = GetContentTypeUsages(_memberTypeService.GetAll(guidsAndPropertyAliases.Keys), guidsAndPropertyAliases); } return result; } /// <summary> /// Maps the found content types and usages to the resulting model /// </summary> /// <param name="cts"></param> /// <param name="usages"></param> /// <returns></returns> private IEnumerable<DataTypeReferences.ContentTypeReferences> GetContentTypeUsages( IEnumerable<IContentTypeBase> cts, IReadOnlyDictionary<Guid, IEnumerable<string>> usages) { return cts.Select(x => new DataTypeReferences.ContentTypeReferences { Id = x.Id, Key = x.Key, Alias = x.Alias, Icon = x.Icon, Name = x.Name, Udi = new GuidUdi(ObjectTypes.GetUdiType(UmbracoObjectTypes.DocumentType), x.Key), //only select matching properties Properties = x.PropertyTypes.Where(p => usages[x.Key].InvariantContains(p.Alias)) .Select(p => new DataTypeReferences.ContentTypeReferences.PropertyTypeReferences { Alias = p.Alias, Name = p.Name }) }); } #region ReadOnly actions to return basic data - allow access for: content ,media, members, settings, developer /// <summary> /// Gets the content json for all data types /// </summary> /// <returns></returns> /// <remarks> /// Permission is granted to this method if the user has access to any of these sections: Content, media, settings, developer, members /// </remarks> [Authorize(Policy = AuthorizationPolicies.SectionAccessForDataTypeReading)] public IEnumerable<DataTypeBasic> GetAll() { return _dataTypeService .GetAll() .Select(_umbracoMapper.Map<IDataType, DataTypeBasic>).Where(x => x.IsSystemDataType == false); } /// <summary> /// Returns all data types grouped by their property editor group /// </summary> /// <returns></returns> /// <remarks> /// Permission is granted to this method if the user has access to any of these sections: Content, media, settings, developer, members /// </remarks> [Authorize(Policy = AuthorizationPolicies.SectionAccessForDataTypeReading)] public IDictionary<string, IEnumerable<DataTypeBasic>> GetGroupedDataTypes() { var dataTypes = _dataTypeService .GetAll() .Select(_umbracoMapper.Map<IDataType, DataTypeBasic>) .ToArray(); var propertyEditors =_propertyEditorCollection.ToArray(); foreach (var dataType in dataTypes) { var propertyEditor = propertyEditors.SingleOrDefault(x => x.Alias == dataType.Alias); if (propertyEditor != null) dataType.HasPrevalues = propertyEditor.GetConfigurationEditor().Fields.Any(); } var grouped = dataTypes .GroupBy(x => x.Group.IsNullOrWhiteSpace() ? "" : x.Group.ToLower()) .ToDictionary(group => group.Key, group => group.OrderBy(d => d.Name).AsEnumerable()); return grouped; } /// <summary> /// Returns all property editors grouped /// </summary> /// <returns></returns> /// <remarks> /// Permission is granted to this method if the user has access to any of these sections: Content, media, settings, developer, members /// </remarks> [Authorize(Policy = AuthorizationPolicies.SectionAccessForDataTypeReading)] public IDictionary<string, IEnumerable<DataTypeBasic>> GetGroupedPropertyEditors() { var datatypes = new List<DataTypeBasic>(); var showDeprecatedPropertyEditors = _contentSettings.ShowDeprecatedPropertyEditors; var propertyEditors =_propertyEditorCollection .Where(x=>x.IsDeprecated == false || showDeprecatedPropertyEditors); foreach (var propertyEditor in propertyEditors) { var hasPrevalues = propertyEditor.GetConfigurationEditor().Fields.Any(); var basic = _umbracoMapper.Map<DataTypeBasic>(propertyEditor); basic.HasPrevalues = hasPrevalues; datatypes.Add(basic); } var grouped = Enumerable.ToDictionary(datatypes .GroupBy(x => x.Group.IsNullOrWhiteSpace() ? "" : x.Group.ToLower()), group => group.Key, group => group.OrderBy(d => d.Name).AsEnumerable()); return grouped; } /// <summary> /// Gets all property editors defined /// </summary> /// <returns></returns> /// <remarks> /// Permission is granted to this method if the user has access to any of these sections: Content, media, settings, developer, members /// </remarks> [Authorize(Policy = AuthorizationPolicies.SectionAccessForDataTypeReading)] public IEnumerable<PropertyEditorBasic> GetAllPropertyEditors() { return _propertyEditorCollection .OrderBy(x => x.Name) .Select(_umbracoMapper.Map<PropertyEditorBasic>); } #endregion } }
// Copyright (c) 2002-2003, Sony Computer Entertainment America // Copyright (c) 2002-2003, Craig Reynolds <[email protected]> // Copyright (C) 2007 Bjoern Graf <[email protected]> // Copyright (C) 2007 Michael Coles <[email protected]> // All rights reserved. // // This software is licensed as described in the file license.txt, which // you should have received as part of this distribution. The terms // are also available at http://www.codeplex.com/SharpSteer/Project/License.aspx. using System; using System.Numerics; using SharpSteer2; using SharpSteer2.Helpers; namespace Demo { public class Camera : LocalSpace { // camera mode selection public enum CameraMode { // marks beginning of list StartMode, // fixed global position and aimpoint Fixed, // camera position is directly above (in global Up/Y) target // camera up direction is target's forward direction StraightDown, // look at subject vehicle, adjusting camera position to be a // constant distance from the subject FixedDistanceOffset, // camera looks at subject vehicle from a fixed offset in the // local space of the vehicle (as if attached to the vehicle) FixedLocalOffset, // camera looks in the vehicle's forward direction, camera // position has a fixed local offset from the vehicle. OffsetPOV, // marks the end of the list for cycling (to cmStartMode+1) EndMode } // xxx since currently (10-21-02) the camera's Forward and Side basis // xxx vectors are not being set, construct a temporary local space for // xxx the camera view -- so as not to make the camera behave // xxx differently (which is to say, correctly) during mouse adjustment. LocalSpace _ls; public LocalSpace xxxls() { _ls.RegenerateOrthonormalBasis(Target - Position, Up); return _ls; } // "look at" point, center of view public Vector3 Target; // vehicle being tracked public IVehicle VehicleToTrack; // aim at predicted position of vehicleToTrack, this far into thefuture public float AimLeadTime; private bool _smoothNextMove; private float _smoothMoveSpeed; // current mode for this camera instance public CameraMode Mode; // "static" camera mode parameters public Vector3 FixedPosition; public Vector3 FixedTarget; public Vector3 FixedUp; // "constant distance from vehicle" camera mode parameters public float FixedDistanceDistance; // desired distance from it public float FixedDistanceVerticalOffset; // fixed vertical offset from it // "look straight down at vehicle" camera mode parameters public float LookDownDistance; // fixed vertical offset from it // "fixed local offset" camera mode parameters private Vector3 _fixedLocalOffset; // "offset POV" camera mode parameters public Vector3 PovOffset; // constructor public Camera() { Reset(); } // reset all camera state to default values public void Reset() { // reset camera's position and orientation ResetLocalSpace(); _ls = new LocalSpace(); // "look at" point, center of view Target = Vector3.Zero; // vehicle being tracked VehicleToTrack = null; // aim at predicted position of vehicleToTrack, this far into thefuture AimLeadTime = 1; // make first update abrupt _smoothNextMove = false; // relative rate at which camera transitions proceed _smoothMoveSpeed = 1.5f; // select camera aiming mode Mode = CameraMode.Fixed; // "constant distance from vehicle" camera mode parameters FixedDistanceDistance = 1; FixedDistanceVerticalOffset = 0; // "look straight down at vehicle" camera mode parameters LookDownDistance = 30; // "static" camera mode parameters FixedPosition = new Vector3(75, 75, 75); FixedTarget = Vector3.Zero; FixedUp = Vector3.UnitY; // "fixed local offset" camera mode parameters _fixedLocalOffset = new Vector3(5, 5, -5); // "offset POV" camera mode parameters PovOffset = new Vector3(0, 1, -3); } // per frame simulation update public void Update(float elapsedTime, bool simulationPaused = false) { // vehicle being tracked (just a reference with a more concise name) IVehicle v = VehicleToTrack; bool noVehicle = VehicleToTrack == null; // new position/target/up, set in switch below, defaults to current Vector3 newPosition = Position; Vector3 newTarget = Target; Vector3 newUp = Up; // prediction time to compensate for lag caused by smoothing moves float antiLagTime = simulationPaused ? 0 : 1 / _smoothMoveSpeed; // aim at a predicted future position of the target vehicle float predictionTime = AimLeadTime + antiLagTime; // set new position/target/up according to camera aim mode switch (Mode) { case CameraMode.Fixed: newPosition = FixedPosition; newTarget = FixedTarget; newUp = FixedUp; break; case CameraMode.FixedDistanceOffset: if (noVehicle) break; newUp = Vector3.UnitY; // xxx maybe this should be v.up ? newTarget = v.PredictFuturePosition(predictionTime); newPosition = ConstantDistanceHelper(); break; case CameraMode.StraightDown: if (noVehicle) break; newUp = v.Forward; newTarget = v.PredictFuturePosition(predictionTime); newPosition = newTarget; newPosition.Y += LookDownDistance; break; case CameraMode.FixedLocalOffset: if (noVehicle) break; newUp = v.Up; newTarget = v.PredictFuturePosition(predictionTime); newPosition = v.GlobalizePosition(_fixedLocalOffset); break; case CameraMode.OffsetPOV: { if (noVehicle) break; newUp = v.Up; Vector3 futurePosition = v.PredictFuturePosition(antiLagTime); Vector3 globalOffset = v.GlobalizeDirection(PovOffset); newPosition = futurePosition + globalOffset; // XXX hack to improve smoothing between modes (no effect on aim) const float L = 10; newTarget = newPosition + (v.Forward * L); break; } } // blend from current position/target/up towards new values SmoothCameraMove(newPosition, newTarget, newUp, elapsedTime); // set camera in draw module //FIXME: drawCameraLookAt(position(), target, up()); } // helper function for "drag behind" mode private Vector3 ConstantDistanceHelper() { // is the "global up"/"vertical" offset constraint enabled? (it forces // the camera's global-up (Y) cordinate to be a above/below the target // vehicle by a given offset.) // ReSharper disable CompareOfFloatsByEqualityOperator bool constrainUp = (FixedDistanceVerticalOffset != 0); // ReSharper restore CompareOfFloatsByEqualityOperator // vector offset from target to current camera position Vector3 adjustedPosition = new Vector3(Position.X, (constrainUp) ? Target.Y : Position.Y, Position.Z); Vector3 offset = adjustedPosition - Target; // current distance between them float distance = offset.Length(); // move camera only when geometry is well-defined (avoid degenerate case) // ReSharper disable CompareOfFloatsByEqualityOperator if (distance == 0) // ReSharper restore CompareOfFloatsByEqualityOperator { return Position; } // unit vector along original offset Vector3 unitOffset = offset / distance; // new offset of length XXX float xxxDistance = (float)Math.Sqrt(FixedDistanceDistance * FixedDistanceDistance - FixedDistanceVerticalOffset * FixedDistanceVerticalOffset); Vector3 newOffset = unitOffset * xxxDistance; // return new camera position: adjust distance to target return Target + newOffset + new Vector3(0, FixedDistanceVerticalOffset, 0); } // Smoothly move camera ... private void SmoothCameraMove(Vector3 newPosition, Vector3 newTarget, Vector3 newUp, float elapsedTime) { if (_smoothNextMove) { float smoothRate = elapsedTime * _smoothMoveSpeed; Vector3 tempPosition = Position; Vector3 tempUp = Up; Utilities.BlendIntoAccumulator(smoothRate, newPosition, ref tempPosition); Utilities.BlendIntoAccumulator(smoothRate, newTarget, ref Target); Utilities.BlendIntoAccumulator(smoothRate, newUp, ref tempUp); Position = (tempPosition); Up = tempUp; // xxx not sure if these are needed, seems like a good idea // xxx (also if either up or oldUP are zero, use the other?) // xxx (even better: force up to be perp to target-position axis)) Up = Up == Vector3.Zero ? Vector3.UnitY : Vector3.Normalize(Up); } else { _smoothNextMove = true; Position = newPosition; Target = newTarget; Up = newUp; } } public void DoNotSmoothNextMove() { _smoothNextMove = false; } // adjust the offset vector of the current camera mode based on a // "mouse adjustment vector" from OpenSteerDemo (xxx experiment 10-17-02) public void MouseAdjustOffset(Vector3 adjustment) { // vehicle being tracked (just a reference with a more concise name) IVehicle v = VehicleToTrack; switch (Mode) { case CameraMode.Fixed: { Vector3 offset = FixedPosition - FixedTarget; Vector3 adjusted = MouseAdjustPolar(adjustment, offset); FixedPosition = FixedTarget + adjusted; break; } case CameraMode.FixedDistanceOffset: { // XXX this is the oddball case, adjusting "position" instead // XXX of mode parameters, hence no smoothing during adjustment // XXX Plus the fixedDistVOffset feature complicates things Vector3 offset = Position - Target; Vector3 adjusted = MouseAdjustPolar(adjustment, offset); // XXX -------------------------------------------------- //position = target + adjusted; //fixedDistDistance = adjusted.length(); //fixedDistVOffset = position.y - target.y; // XXX -------------------------------------------------- //const float s = smoothMoveSpeed * (1.0f/40f); //const Vector3 newPosition = target + adjusted; //position = interpolate (s, position, newPosition); //fixedDistDistance = interpolate (s, fixedDistDistance, adjusted.length()); //fixedDistVOffset = interpolate (s, fixedDistVOffset, position.y - target.y); // XXX -------------------------------------------------- //position = target + adjusted; Position = (Target + adjusted); FixedDistanceDistance = adjusted.Length(); //fixedDistVOffset = position.y - target.y; FixedDistanceVerticalOffset = Position.Y - Target.Y; // XXX -------------------------------------------------- break; } case CameraMode.StraightDown: { Vector3 offset = new Vector3(0, 0, LookDownDistance); Vector3 adjusted = MouseAdjustPolar(adjustment, offset); LookDownDistance = adjusted.Z; break; } case CameraMode.FixedLocalOffset: { Vector3 offset = v.GlobalizeDirection(_fixedLocalOffset); Vector3 adjusted = MouseAdjustPolar(adjustment, offset); _fixedLocalOffset = v.LocalizeDirection(adjusted); break; } case CameraMode.OffsetPOV: { // XXX this might work better as a translation control, it is // XXX non-obvious using a polar adjustment when the view // XXX center is not at the camera aim target Vector3 offset = v.GlobalizeDirection(PovOffset); Vector3 adjusted = MouseAdjustOrtho(adjustment, offset); PovOffset = v.LocalizeDirection(adjusted); break; } } } private Vector3 MouseAdjust2(bool polar, Vector3 adjustment, Vector3 offsetToAdjust) { // value to be returned Vector3 result = offsetToAdjust; // using the camera's side/up axes (essentially: screen space) move the // offset vector sideways according to adjustment.x and vertically // according to adjustment.y, constrain the offset vector's length to // stay the same, hence the offset's "tip" stays on the surface of a // sphere. float oldLength = result.Length(); float rate = polar ? oldLength : 1; result += xxxls().Side * (adjustment.X * rate); result += xxxls().Up * (adjustment.Y * rate); if (polar) { float newLength = result.Length(); result *= oldLength / newLength; } // change the length of the offset vector according to adjustment.z if (polar) result *= (1 + adjustment.Z); else result += xxxls().Forward * adjustment.Z; return result; } private Vector3 MouseAdjustPolar(Vector3 adjustment, Vector3 offsetToAdjust) { return MouseAdjust2(true, adjustment, offsetToAdjust); } private Vector3 MouseAdjustOrtho(Vector3 adjustment, Vector3 offsetToAdjust) { return MouseAdjust2(false, adjustment, offsetToAdjust); } // string naming current camera mode, used by OpenSteerDemo public String ModeName { get { switch (Mode) { case CameraMode.Fixed: return "static"; case CameraMode.FixedDistanceOffset: return "fixed distance offset"; case CameraMode.FixedLocalOffset: return "fixed local offset"; case CameraMode.OffsetPOV: return "offset POV"; case CameraMode.StraightDown: return "straight down"; default: return "unknown"; } } } // select next camera mode, used by OpenSteerDemo public void SelectNextMode() { Mode = SuccessorMode(Mode); if (Mode >= CameraMode.EndMode) Mode = SuccessorMode(CameraMode.StartMode); } // the mode that comes after the given mode (used by selectNextMode) private static CameraMode SuccessorMode(CameraMode cm) { return (CameraMode)(((int)cm) + 1); } } }
using System; using System.IO; using System.Collections.Specialized; using System.Text; namespace Eminent.CodeGenerator { /// <summary> /// Summary description for Template. /// </summary> public class Template { public Template() { } public Template(FileInfo fi) { FileName = fi.Name; FileExtension = fi.Extension; DirectoryName = fi.DirectoryName; DateCreated = fi.CreationTime; DateModified = fi.LastWriteTime; FullFileName = fi.FullName; StreamReader fileSR = null; try { fileSR = File.OpenText(fi.FullName); EntireContents = fileSR.ReadToEnd(); } catch { } finally { if(fileSR != null) { fileSR.Close(); } } ParseTemplate(EntireContents); } public string FileName = ""; public string BaseClass = ""; public string FullFileName = ""; public string FileExtension = ""; public string Description = ""; public string DirectoryName = ""; private string _Language = ""; public string TargetLanguage = ""; public string OutputLocation = ""; public DateTime DateCreated ; public DateTime DateModified ; public string EntireContents = ""; public StringCollection Assemblies = new StringCollection(); public StringCollection Namespaces = new StringCollection(); public PropertyCollection Properties = new PropertyCollection(); public StringBuilder CodeSnippet = new StringBuilder(); private string CRLF = "\\r\\n"; private string STMTTERM = ";"; private void InitLanguageSettings() { switch(Language.ToLower().Trim()) { case "vb": CRLF = "vbCRLF"; STMTTERM = ""; break; case "c#": default: CRLF = "\\r\\n"; STMTTERM = ";"; break; } } public string ClassName { get; set; } public string Language { get { return _Language; } set { _Language = value; InitLanguageSettings(); } } #region ParseTemplate /// <summary> /// Parses a script into a compilable program /// </summary> /// <param name="code"></param public void ParseTemplate(string code) { if (String.IsNullOrEmpty(code)) return; //hack - don't like but sometimes receiving newline in weird formats //https://stackoverflow.com/questions/14059212/why-i-get-r-r-n-as-newline-instead-of-r-n-as-newline-char-in-windows code = code.Replace("\r\r\n", "\r\n"); int lnLast = 0; int lnAt2 = 0; int lnAt = code.IndexOf("<%",0); CodeSnippet.Append("\tresponseSB.Length = 0" + STMTTERM + "\r\n\r\n"); if (lnAt > -1) { while (lnAt > -1) { // *** Catch the plain text write out to the Response Stream as is - fix up for quotes if (lnAt > -1) { if (code.Substring(lnLast, lnAt - lnLast).Replace("\"", "\"\"").Trim() != String.Empty) { string snip = code.Substring(lnLast, lnAt - lnLast).Replace("\"", "\\\"").Replace("\r\n", CRLF); //string snip = code.Substring(lnLast,lnAt - lnLast).Replace("\"","\"\"").Replace("\r\n",CRLF); //hack: quick fix..better algo can be used here int maxCopy = 8000; int lengthToCopy = snip.Length > maxCopy ? maxCopy : snip.Length; CodeSnippet.Append("\tresponseSB.Append(\"" + snip.Substring(0, lengthToCopy) + "\" )" + STMTTERM + "\r\n\r\n"); snip = snip.Substring(lengthToCopy); while (snip.Length > maxCopy) { CodeSnippet.Append("\tresponseSB.Append(\"" + snip.Substring(0, maxCopy) + "\" )" + STMTTERM + "\r\n\r\n"); snip = snip.Substring(maxCopy); } //CodeSnippet.Append("\tresponseSB.Append(\"" + code.Substring(lnLast,lnAt - lnLast).Replace("\"","\"\"").Replace("\r\n",CRLF) + "\" );\r\n\r\n"); } } //*** Find end tag lnAt2 = code.IndexOf("%>", lnAt); if (lnAt2 < 0) break; string lcSnippet = code.Substring(lnAt, lnAt2 - lnAt + 2); // *** Write out an expression. 'Eval' inside of a Response.Write call if (lcSnippet.Substring(2, 1) == "=") { CodeSnippet.Append("\tresponseSB.Append(" + lcSnippet.Substring(3, lcSnippet.Length - 5).Trim() + ".ToString())" + STMTTERM + "\r\n"); } else if (lcSnippet.Substring(2, 1) == "@") { string lcAttribute = ""; // *** Handle Directives for Template/Assembly/Proprty/Import lcAttribute = StrExtract(lcSnippet, "Property", "="); if (lcAttribute.Length > 0) { Property p = new Property(); lcAttribute = StrExtract(lcSnippet, "Name=\"", "\""); if (lcAttribute.Length > 0) p.Name = lcAttribute; lcAttribute = StrExtract(lcSnippet, "Type=\"", "\""); if (lcAttribute.Length > 0) p.Type = lcAttribute; lcAttribute = StrExtract(lcSnippet, "Default=\"", "\""); if (lcAttribute.Length > 0) p.Default = lcAttribute; lcAttribute = StrExtract(lcSnippet, "Category=\"", "\""); if (lcAttribute.Length > 0) p.Category = lcAttribute; lcAttribute = StrExtract(lcSnippet, "Description=\"", "\""); if (lcAttribute.Length > 0) p.Description = lcAttribute; Properties.Add(p); } else { lcAttribute = StrExtract(lcSnippet, "Assembly", "="); if (lcAttribute.Length > 0) { lcAttribute = StrExtract(lcSnippet, "\"", "\""); if (lcAttribute.Length > 0) Assemblies.Add(lcAttribute); } else { lcAttribute = StrExtract(lcSnippet, "Import", "="); if (lcAttribute.Length > 0) { lcAttribute = StrExtract(lcSnippet, "\"", "\""); if (lcAttribute.Length > 0) Namespaces.Add(lcAttribute); } else { lcAttribute = StrExtract(lcSnippet, "Template", "="); if (lcAttribute.Length > 0) { lcAttribute = StrExtract(lcSnippet, "Language=\"", "\""); if (lcAttribute.Length > 0) Language = lcAttribute; lcAttribute = StrExtract(lcSnippet, "Inherits=\"", "\""); if (lcAttribute.Length > 0) BaseClass = lcAttribute; lcAttribute = StrExtract(lcSnippet, "TargetLanguage=\"", "\""); if (lcAttribute.Length > 0) TargetLanguage = lcAttribute; lcAttribute = StrExtract(lcSnippet, "Description=\"", "\""); if (lcAttribute.Length > 0) Description = lcAttribute; } } } } } else { // *** Write out a line of code as is. CodeSnippet.Append("\t" + lcSnippet.Substring(2, lcSnippet.Length - 4) + "\r\n"); } lnLast = lnAt2 + 2; lnAt = code.IndexOf("<%", lnLast); if (lnAt < 0) { // *** Write out the final block of non-code text if (code.Substring(lnLast, code.Length - lnLast).Replace("\"", "\"\"").Trim() != String.Empty) { //orig code - does not seem to handle html with apostrophes well (") tryinh @ for verbatim string literal //CodeSnippet.Append("\tresponseSB.Append(\"" + code.Substring(lnLast, code.Length - lnLast).Replace("\"", "\"\"").Replace("\r\n", CRLF) + "\" )" + STMTTERM + "\r\n"); CodeSnippet.Append("\tresponseSB.Append(@\"" + code.Substring(lnLast, code.Length - lnLast).Replace("\"", "\"\"") + "\" )" + STMTTERM + "\r\n"); } } } } else { //orig code - does not seem to handle html with apostrophes well (") tryinh @ for verbatim string literal //CodeSnippet.Append("\tresponseSB.Append(\"" + code.Replace("\"", "\"\"").Replace("\r\n", CRLF) + "\" )" + STMTTERM + "\r\n"); CodeSnippet.Append("\tresponseSB.Append(@\"" + code.Replace("\"", "\"\"") + "\" )" + STMTTERM + "\r\n"); } CodeSnippet.Append("\treturn responseSB.ToString()"); } #endregion #region StrExtract /// <summary> /// Receives a string along with starting and ending delimiters and returns the /// part of the string between the delimiters. Receives a beginning occurence /// to begin the extraction from and also receives a flag (0/1) where 1 indicates /// that the search should be case insensitive. /// <pre> /// Example: /// string cExpression = "JoeDoeJoeDoe"; /// VFPToolkit.strings.StrExtract(cExpression, "o", "eJ", 1, 0); //returns "eDo" /// </pre> /// </summary> private static string StrExtract(string cSearchExpression, string cBeginDelim, string cEndDelim, int nBeginOccurence, int nFlags) { string cstring = cSearchExpression; string cb = cBeginDelim; string ce = cEndDelim; if (nFlags == 1) { cb = cb.ToLower(); ce = ce.ToLower(); cstring = cstring.ToLower(); } int lnAt = cSearchExpression.IndexOf(cb,0); if (lnAt < 0) return ""; int lnAtCut = lnAt + cb.Length ; int lnAt2 = cSearchExpression.IndexOf(ce,lnAtCut); if (lnAt2 < 0) return ""; return cSearchExpression.Substring(lnAtCut,lnAt2 - lnAtCut); } /// <summary> /// Receives a string and a delimiter as parameters and returns a string starting /// from the position after the delimiter /// <pre> /// Example: /// string cExpression = "JoeDoeJoeDoe"; /// VFPToolkit.strings.StrExtract(cExpression, "o"); //returns "eDoeJoeDoe" /// </pre> /// </summary> /// <param name="cSearchExpression"> </param> /// <param name="cBeginDelim"> </param> private static string StrExtract(string cSearchExpression, string cBeginDelim) { int nbpos = At(cBeginDelim, cSearchExpression); return cSearchExpression.Substring(nbpos + cBeginDelim.Length - 1); } /// <summary> /// Receives a string along with starting and ending delimiters and returns the /// part of the string between the delimiters /// <pre> /// Example: /// string cExpression = "JoeDoeJoeDoe"; /// VFPToolkit.strings.StrExtract(cExpression, "o", "eJ"); //returns "eDo" /// </pre> /// </summary> /// <param name="cSearchExpression"> </param> /// <param name="cBeginDelim"> </param> /// <param name="cEndDelim"> </param> private static string StrExtract(string cSearchExpression, string cBeginDelim, string cEndDelim) { return StrExtract(cSearchExpression, cBeginDelim, cEndDelim, 1, 0); } /// <summary> /// Receives a string along with starting and ending delimiters and returns the /// part of the string between the delimiters. It also receives a beginning occurence /// to begin the extraction from. /// <pre> /// Example: /// string cExpression = "JoeDoeJoeDoe"; /// VFPToolkit.strings.StrExtract(cExpression, "o", "eJ", 2); //returns "" /// </pre> /// </summary> /// <param name="cSearchExpression"> </param> /// <param name="cBeginDelim"> </param> /// <param name="cEndDelim"> </param> /// <param name="nBeginOccurence"> </param> private static string StrExtract(string cSearchExpression, string cBeginDelim, string cEndDelim, int nBeginOccurence) { return StrExtract(cSearchExpression, cBeginDelim, cEndDelim, nBeginOccurence, 0); } #endregion /// Private Implementation: This is the actual implementation of the At() and RAt() functions. /// Receives two strings, the expression in which search is performed and the expression to search for. /// Also receives an occurence position and the mode (1 or 0) that specifies whether it is a search /// from Left to Right (for At() function) or from Right to Left (for RAt() function) private static int __at(string cSearchFor, string cSearchIn, int nOccurence, int nMode) { //In this case we actually have to locate the occurence int i = 0; int nOccured = 0; int nPos = 0; if (nMode == 1) {nPos = 0;} else {nPos = cSearchIn.Length;} //Loop through the string and get the position of the requiref occurence for (i=1;i<=nOccurence;i++) { if(nMode == 1) {nPos = cSearchIn.IndexOf(cSearchFor,nPos);} else {nPos = cSearchIn.LastIndexOf(cSearchFor,nPos);} if (nPos < 0) { //This means that we did not find the item break; } else { //Increment the occured counter based on the current mode we are in nOccured++; //Check if this is the occurence we are looking for if (nOccured == nOccurence) { return nPos + 1; } else { if(nMode == 1) {nPos++;} else {nPos--;} } } } //We never found our guy if we reached here return 0; } /// <summary> /// Receives two strings as parameters and searches for one string within another. /// If found, returns the beginning numeric position otherwise returns 0 /// <pre> /// Example: /// VFPToolkit.strings.At("D", "Joe Doe"); //returns 5 /// </pre> /// </summary> /// <param name="cSearchFor"> </param> /// <param name="cSearchIn"> </param> private static int At(string cSearchFor, string cSearchIn) { return cSearchIn.IndexOf(cSearchFor) + 1; } /// <summary> /// Receives two strings and an occurence position (1st, 2nd etc) as parameters and /// searches for one string within another for that position. /// If found, returns the beginning numeric position otherwise returns 0 /// <pre> /// Example: /// VFPToolkit.strings.At("o", "Joe Doe", 1); //returns 2 /// VFPToolkit.strings.At("o", "Joe Doe", 2); //returns 6 /// </pre> /// </summary> /// <param name="cSearchFor"> </param> /// <param name="cSearchIn"> </param> /// <param name="nOccurence"> </param> private static int At(string cSearchFor, string cSearchIn, int nOccurence) { return __at(cSearchFor, cSearchIn, nOccurence, 1); } } }
#region License // Copyright (c) Jeremy Skinner (http://www.jeremyskinner.co.uk) // // 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. // // The latest version of this file can be found at http://www.codeplex.com/FluentValidation #endregion namespace FluentValidation { using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using Internal; using Results; using Validators; /// <summary> /// Base class for entity validator classes. /// </summary> /// <typeparam name="T">The type of the object being validated</typeparam> public abstract class AbstractValidator<T> : IValidator<T>, IEnumerable<IValidationRule> { readonly TrackingCollection<IValidationRule> nestedValidators = new TrackingCollection<IValidationRule>(); // Work-around for reflection bug in .NET 4.5 static Func<CascadeMode> s_cascadeMode = () => ValidatorOptions.CascadeMode; Func<CascadeMode> cascadeMode = s_cascadeMode; /// <summary> /// Sets the cascade mode for all rules within this validator. /// </summary> public CascadeMode CascadeMode { get { return cascadeMode(); } set { cascadeMode = () => value; } } ValidationResult IValidator.Validate(object instance) { instance.Guard("Cannot pass null to Validate."); if(! ((IValidator)this).CanValidateInstancesOfType(instance.GetType())) { throw new InvalidOperationException(string.Format("Cannot validate instances of type '{0}'. This validator can only validate instances of type '{1}'.", instance.GetType().Name, typeof(T).Name)); } return Validate((T)instance); } ValidationResult IValidator.Validate(ValidationContext context) { context.Guard("Cannot pass null to Validate"); var newContext = new ValidationContext<T>((T)context.InstanceToValidate, context.PropertyChain, context.Selector) { IsChildContext = context.IsChildContext }; return Validate(newContext); } /// <summary> /// Validates the specified instance /// </summary> /// <param name="instance">The object to validate</param> /// <returns>A ValidationResult object containing any validation failures</returns> public virtual ValidationResult Validate(T instance) { return Validate(new ValidationContext<T>(instance, new PropertyChain(), new DefaultValidatorSelector())); } /// <summary> /// Validates the specified instance. /// </summary> /// <param name="context">Validation Context</param> /// <returns>A ValidationResult object containing any validation failures.</returns> public virtual ValidationResult Validate(ValidationContext<T> context) { context.Guard("Cannot pass null to Validate"); var failures = nestedValidators.SelectMany(x => x.Validate(context)).ToList(); return new ValidationResult(failures); } /// <summary> /// Adds a rule to the current validator. /// </summary> /// <param name="rule"></param> public void AddRule(IValidationRule rule) { nestedValidators.Add(rule); } /// <summary> /// Creates a <see cref="IValidatorDescriptor" /> that can be used to obtain metadata about the current validator. /// </summary> public virtual IValidatorDescriptor CreateDescriptor() { return new ValidatorDescriptor<T>(nestedValidators); } bool IValidator.CanValidateInstancesOfType(Type type) { return typeof(T).IsAssignableFrom(type); } /// <summary> /// Defines a validation rule for a specify property. /// </summary> /// <example> /// RuleFor(x => x.Surname)... /// </example> /// <typeparam name="TProperty">The type of property being validated</typeparam> /// <param name="expression">The expression representing the property to validate</param> /// <returns>an IRuleBuilder instance on which validators can be defined</returns> public IRuleBuilderInitial<T, TProperty> RuleFor<TProperty>(Expression<Func<T, TProperty>> expression) { expression.Guard("Cannot pass null to RuleFor"); var rule = PropertyRule.Create(expression, () => CascadeMode); AddRule(rule); var ruleBuilder = new RuleBuilder<T, TProperty>(rule); return ruleBuilder; } /// <summary> /// Defines a custom validation rule using a lambda expression. /// If the validation rule fails, it should return a instance of a <see cref="ValidationFailure">ValidationFailure</see> /// If the validation rule succeeds, it should return null. /// </summary> /// <param name="customValidator">A lambda that executes custom validation rules.</param> public void Custom(Func<T, ValidationFailure> customValidator) { customValidator.Guard("Cannot pass null to Custom"); AddRule(new DelegateValidator<T>(x => new[] { customValidator(x) })); } /// <summary> /// Defines a custom validation rule using a lambda expression. /// If the validation rule fails, it should return an instance of <see cref="ValidationFailure">ValidationFailure</see> /// If the validation rule succeeds, it should return null. /// </summary> /// <param name="customValidator">A lambda that executes custom validation rules</param> public void Custom(Func<T, ValidationContext<T>, ValidationFailure> customValidator) { customValidator.Guard("Cannot pass null to Custom"); AddRule(new DelegateValidator<T>((x, ctx) => new[] { customValidator(x, ctx) })); } /// <summary> /// Defines a RuleSet that can be used to group together several validators. /// </summary> /// <param name="ruleSetName">The name of the ruleset.</param> /// <param name="action">Action that encapsulates the rules in the ruleset.</param> public void RuleSet(string ruleSetName, Action action) { ruleSetName.Guard("A name must be specified when calling RuleSet."); action.Guard("A ruleset definition must be specified when calling RuleSet."); using (nestedValidators.OnItemAdded(r => r.RuleSet = ruleSetName)) { action(); } } /// <summary> /// Defines a condition that applies to several rules /// </summary> /// <param name="predicate">The condition that should apply to multiple rules</param> /// <param name="action">Action that encapsulates the rules.</param> /// <returns></returns> public void When(Func<T, bool> predicate, Action action) { var propertyRules = new List<IValidationRule>(); Action<IValidationRule> onRuleAdded = propertyRules.Add; using(nestedValidators.OnItemAdded(onRuleAdded)) { action(); } // Must apply the predictae after the rule has been fully created to ensure any rules-specific conditions have already been applied. propertyRules.ForEach(x => x.ApplyCondition(predicate.CoerceToNonGeneric())); } /// <summary> /// Defiles an inverse condition that applies to several rules /// </summary> /// <param name="predicate">The condition that should be applied to multiple rules</param> /// <param name="action">Action that encapsulates the rules</param> public void Unless(Func<T, bool> predicate, Action action) { When(x => !predicate(x), action); } /// <summary> /// Returns an enumerator that iterates through the collection of validation rules. /// </summary> /// <returns> /// A <see cref="T:System.Collections.Generic.IEnumerator`1"/> that can be used to iterate through the collection. /// </returns> /// <filterpriority>1</filterpriority> public IEnumerator<IValidationRule> GetEnumerator() { return nestedValidators.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } }
using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Styling; using Avalonia.Threading; using AvalonStudio.Extensibility.Theme; using ReactiveUI; using System; using System.Reactive; using System.Reactive.Disposables; using System.Reactive.Linq; using System.Reactive.Subjects; using System.Threading.Tasks; using WalletWasabi.Logging; namespace WalletWasabi.Gui.Controls { public class ExtendedTextBox : TextBox, IStyleable { private TextPresenter _presenter; private MenuItem _pasteItem = null; private Subject<string> _textPasted; public ExtendedTextBox() { Disposables = new CompositeDisposable(); _textPasted = new Subject<string>(); CopyCommand = ReactiveCommand.CreateFromTask(CopyAsync); PasteCommand = ReactiveCommand.CreateFromTask(async () => { try { var pastedText = await PasteAsync(); _textPasted.OnNext(pastedText); } catch (Exception exception) { _textPasted.OnError(exception); } }); Observable .Merge(CopyCommand.ThrownExceptions) .Merge(PasteCommand.ThrownExceptions) .ObserveOn(RxApp.TaskpoolScheduler) .Subscribe(ex => Logger.LogWarning(ex)); this.GetObservable(IsReadOnlyProperty).Subscribe(isReadOnly => { if (ContextMenu is null) { return; } var items = ContextMenu.Items as Avalonia.Controls.Controls; if (isReadOnly) { if (items.Contains(_pasteItem)) { items.Remove(_pasteItem); _pasteItem = null; } } else { if (!items.Contains(_pasteItem)) { CreatePasteItem(); items.Add(_pasteItem); } } }); } private CompositeDisposable Disposables { get; } public IObservable<string> TextPasted => _textPasted.AsObservable(); Type IStyleable.StyleKey => typeof(TextBox); private ReactiveCommand<Unit, Unit> CopyCommand { get; } private ReactiveCommand<Unit, Unit> PasteCommand { get; } protected virtual bool IsCopyEnabled => true; private async Task<string?> PasteAsync() { var text = await Application.Current.Clipboard.GetTextAsync(); if (text is null) { return null; } OnTextInput(new TextInputEventArgs { Text = text }); return text; } protected string GetSelection() { var text = Text; if (string.IsNullOrEmpty(text)) { return ""; } var selectionStart = SelectionStart; var selectionEnd = SelectionEnd; var start = Math.Min(selectionStart, selectionEnd); var end = Math.Max(selectionStart, selectionEnd); if (start == end || (Text?.Length ?? 0) < end) { return ""; } return text[start..end]; } protected virtual async Task CopyAsync() { var selection = GetSelection(); if (string.IsNullOrWhiteSpace(selection)) { selection = Text; } if (!string.IsNullOrWhiteSpace(selection)) { await Application.Current.Clipboard.SetTextAsync(selection); } } private DrawingPresenter? GetCopyPresenter() { if (ResourceNodeExtensions.TryFindResource(this, "Copy", out var rawIcon)) { if (rawIcon is DrawingGroup icon) { return new DrawingPresenter() { Drawing = icon }; } } return null; } private DrawingPresenter? GetPastePresenter() { if (ResourceNodeExtensions.TryFindResource(this, "Paste", out var rawIcon)) { if (rawIcon is DrawingGroup icon) { return new DrawingPresenter() { Drawing = icon }; } } return null; } protected override void OnTemplateApplied(TemplateAppliedEventArgs e) { base.OnTemplateApplied(e); _presenter = e.NameScope.Get<TextPresenter>("PART_TextPresenter"); ContextMenu = new ContextMenu { DataContext = this, Items = new Avalonia.Controls.Controls() }; Observable.FromEventPattern(ContextMenu, nameof(ContextMenu.MenuClosed)) .ObserveOn(RxApp.MainThreadScheduler) .Subscribe(_ => Focus()) .DisposeWith(Disposables); var menuItems = (ContextMenu.Items as Avalonia.Controls.Controls); if (IsCopyEnabled) { menuItems.Add(new MenuItem { Header = "Copy", Foreground = ColorTheme.CurrentTheme.Foreground, Command = CopyCommand, Icon = GetCopyPresenter() }); } if (!IsReadOnly) { CreatePasteItem(); menuItems.Add(_pasteItem); } } protected override void OnDetachedFromVisualTree(VisualTreeAttachmentEventArgs e) { base.OnDetachedFromVisualTree(e); Disposables?.Dispose(); } protected override void OnLostFocus(RoutedEventArgs e) { // Dispatch so that if there is a context menu, it can open before the selection gets cleared. Dispatcher.UIThread.PostLogException(() => { if (ContextMenu is { } && ContextMenu.IsOpen) { _presenter?.HideCaret(); } else { base.OnLostFocus(e); } }); } private void CreatePasteItem() { if (_pasteItem is { }) { return; } _pasteItem = new MenuItem { Header = "Paste", Foreground = ColorTheme.CurrentTheme.Foreground, Command = PasteCommand, Icon = GetPastePresenter() }; } } }
#region License // Copyright (c) 2010-2019, Mark Final // 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 BuildAMation 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. #endregion // License using System.Linq; namespace C { /// <summary> /// Module representing a preprocessed file /// </summary> class PreprocessedFile : CModule, IRequiresSourceModule { /// <summary> /// Path key for this module type /// </summary> public const string PreprocessedFileKey = "Preprocessed file"; /// <summary> /// Associated source module /// </summary> protected SourceFile SourceModule; /// <summary> /// Initialize this preprocessed file /// </summary> protected override void Init() { base.Init(); this.Tool = C.DefaultToolchain.Preprocessor(this.BitDepth); } /// <summary> /// Determine whether the module needs updating /// </summary> protected override void EvaluateInternal() { this.ReasonToExecute = null; foreach (var dep in this.Dependents) { if (!(dep is SourceFile) && !dep.Executed) { // TODO: need to revisit this // it's odd to spinlock on the ExecutionTask, and then do an additional double check // on whether it's got the task (when the while loop says it must) // I *thought* I had coded it so that the dependencies of execution tasks were // satisfied in the core var as_module_execution = dep as Bam.Core.IModuleExecution; while (null == as_module_execution.ExecutionTask) { Bam.Core.Log.DebugMessage($"******** Waiting for {dep.ToString()} to have an execution task assigned"); System.Threading.Thread.Yield(); } // wait for execution task to be finished var execution_task = as_module_execution.ExecutionTask; if (null == execution_task) { throw new Bam.Core.Exception( $"No execution task available for dependent {dep.ToString()}, of {this.ToString()}" ); } execution_task.Wait(); } } // does the preprocessed file exist? var preprocessedFilePath = this.GeneratedPaths[PreprocessedFileKey].ToString(); if (!System.IO.File.Exists(preprocessedFilePath)) { this.ReasonToExecute = Bam.Core.ExecuteReasoning.FileDoesNotExist(this.GeneratedPaths[PreprocessedFileKey]); return; } var preprocessedFileWriteTime = System.IO.File.GetLastWriteTime(preprocessedFilePath); // has the source file been evaluated to be rebuilt? if ((this as IRequiresSourceModule).Source.ReasonToExecute != null) { this.ReasonToExecute = Bam.Core.ExecuteReasoning.InputFileNewer( this.GeneratedPaths[PreprocessedFileKey], this.SourceModule.InputPath ); return; } // is the source file newer than the preprocessed file? var sourcePath = this.SourceModule.InputPath.ToString(); var sourceWriteTime = System.IO.File.GetLastWriteTime(sourcePath); if (sourceWriteTime > preprocessedFileWriteTime) { this.ReasonToExecute = Bam.Core.ExecuteReasoning.InputFileNewer( this.GeneratedPaths[PreprocessedFileKey], this.SourceModule.InputPath ); return; } // are there any headers as explicit dependencies (procedurally generated most likely), which are newer? var explicitHeadersUpdated = new Bam.Core.StringArray(); foreach (var dep in this.Dependents) { if (dep is HeaderFile headerDep) { if (null == dep.ReasonToExecute) { continue; } if (dep.ReasonToExecute.Reason == Bam.Core.ExecuteReasoning.EReason.InputFileIsNewer) { explicitHeadersUpdated.AddUnique(headerDep.InputPath.ToString()); } } } var includeSearchPaths = (this.Settings as C.ICommonPreprocessorSettings).IncludePaths; // implicitly search the same directory as the source path, as this is not needed to be explicitly on the include path list var currentDir = this.CreateTokenizedString("@dir($(0))", this.SourceModule.InputPath); currentDir.Parse(); includeSearchPaths.AddUnique(currentDir); var filesToSearch = new System.Collections.Generic.Queue<string>(); filesToSearch.Enqueue(sourcePath); var headerPathsFound = new Bam.Core.StringArray(); while (filesToSearch.Any()) { var fileToSearch = filesToSearch.Dequeue(); string fileContents = null; using (System.IO.TextReader reader = new System.IO.StreamReader(fileToSearch)) { fileContents = reader.ReadToEnd(); } // never know if developers are consistent with #include "header.h" or #include <header.h> so look for both // nor the amount of whitespace after #include var matches = System.Text.RegularExpressions.Regex.Matches( fileContents, "^\\s*#include\\s*[\"<]([^\\s]*)[\">]", System.Text.RegularExpressions.RegexOptions.Multiline); if (!matches.Any()) { // no #includes return; } foreach (System.Text.RegularExpressions.Match match in matches) { var headerFile = match.Groups[1].Value; bool exists = false; // search for the file on the include paths the compiler uses foreach (var includePath in includeSearchPaths) { try { var potentialPath = System.IO.Path.Combine(includePath.ToString(), headerFile); if (!System.IO.File.Exists(potentialPath)) { continue; } potentialPath = System.IO.Path.GetFullPath(potentialPath); var headerWriteTime = System.IO.File.GetLastWriteTime(potentialPath); // early out - header is newer than generated preprocessed file if (headerWriteTime > preprocessedFileWriteTime) { this.ReasonToExecute = Bam.Core.ExecuteReasoning.InputFileNewer( this.GeneratedPaths[PreprocessedFileKey], Bam.Core.TokenizedString.CreateVerbatim(potentialPath) ); return; } // found #included header in list of explicitly dependent headers that have been updated if (explicitHeadersUpdated.Contains(potentialPath)) { this.ReasonToExecute = Bam.Core.ExecuteReasoning.InputFileNewer( this.GeneratedPaths[PreprocessedFileKey], Bam.Core.TokenizedString.CreateVerbatim(potentialPath) ); return; } if (!headerPathsFound.Contains(potentialPath)) { headerPathsFound.Add(potentialPath); filesToSearch.Enqueue(potentialPath); } exists = true; break; } catch (System.Exception ex) { Bam.Core.Log.MessageAll( $"IncludeDependency Exception: Cannot locate '{headerFile}' on '{includePath}' due to {ex.Message}" ); } } if (!exists) { #if false Bam.Core.Log.DebugMessage($"***** Could not locate '{match.Groups[1]}' on any include search path, included from {fileToSearch}:\n{entry.includePaths.ToString('\n')}"); #endif } } } return; } /// <summary> /// Execute the build on this module /// </summary> /// <param name="context">in this context</param> protected override void ExecuteInternal( Bam.Core.ExecutionContext context) { switch (Bam.Core.Graph.Instance.Mode) { #if D_PACKAGE_MAKEFILEBUILDER case "MakeFile": MakeFileBuilder.Support.Add( this, redirectOutputToFile: this.GeneratedPaths[PreprocessedFileKey] ); break; #endif #if D_PACKAGE_NATIVEBUILDER case "Native": { NativeBuilder.Support.RunCommandLineTool(this, context); NativeBuilder.Support.SendCapturedOutputToFile( this, context, PreprocessedFileKey ); } break; #endif #if D_PACKAGE_VSSOLUTIONBUILDER case "VSSolution": VSSolutionSupport.GenerateFileFromToolStandardOutput( this, PreprocessedFileKey, includeEnvironmentVariables: false // since it's running the preprocessor in the IDE, no environment variables necessary ); break; #endif #if D_PACKAGE_XCODEBUILDER case "Xcode": XcodeSupport.GenerateFileFromToolStandardOutput( this, PreprocessedFileKey ); break; #endif default: throw new System.NotImplementedException(); } } SourceFile IRequiresSourceModule.Source { get { return this.SourceModule; } set { if (null != this.SourceModule) { this.SourceModule.InputPath.Parse(); throw new Bam.Core.Exception( $"Source module already set on this preprocessed file, to '{this.SourceModule.InputPath.ToString()}'" ); } this.SourceModule = value; this.DependsOn(value); this.RegisterGeneratedFile( PreprocessedFileKey, this.CreateTokenizedString( "$(packagebuilddir)/$(moduleoutputdir)/@changeextension(@isrelative(@trimstart(@relativeto($(0),$(packagedir)),../),@filename($(0))),.c)", value.GeneratedPaths[SourceFile.SourceFileKey] ) ); } } /// <summary> /// /copydoc Bam.Core.Module.InputModulePaths /// </summary> public override System.Collections.Generic.IEnumerable<(Bam.Core.Module module, string pathKey)> InputModulePaths { get { yield return (this.SourceModule, SourceFile.SourceFileKey); } } } }
using System.Collections; using System.Globalization; using BigMath; using Raksha.Asn1.X9; using Raksha.Math; using Raksha.Math.EC; using Raksha.Utilities; using Raksha.Utilities.Collections; using Raksha.Utilities.Encoders; namespace Raksha.Asn1.TeleTrust { /** * elliptic curves defined in "ECC Brainpool Standard Curves and Curve Generation" * http://www.ecc-brainpool.org/download/draft_pkix_additional_ecc_dp.txt */ public class TeleTrusTNamedCurves { internal class BrainpoolP160r1Holder : X9ECParametersHolder { private BrainpoolP160r1Holder() {} internal static readonly X9ECParametersHolder Instance = new BrainpoolP160r1Holder(); protected override X9ECParameters CreateParameters() { ECCurve curve = new FpCurve( new BigInteger("E95E4A5F737059DC60DFC7AD95B3D8139515620F", 16), // q new BigInteger("340E7BE2A280EB74E2BE61BADA745D97E8F7C300", 16), // a new BigInteger("1E589A8595423412134FAA2DBDEC95C8D8675E58", 16)); // b return new X9ECParameters( curve, curve.DecodePoint(Hex.Decode("04BED5AF16EA3F6A4F62938C4631EB5AF7BDBCDBC31667CB477A1A8EC338F94741669C976316DA6321")), // G new BigInteger("E95E4A5F737059DC60DF5991D45029409E60FC09", 16), //n new BigInteger("01", 16)); // h } } internal class BrainpoolP160t1Holder : X9ECParametersHolder { private BrainpoolP160t1Holder() {} internal static readonly X9ECParametersHolder Instance = new BrainpoolP160t1Holder(); protected override X9ECParameters CreateParameters() { ECCurve curve = new FpCurve( // new BigInteger("24DBFF5DEC9B986BBFE5295A29BFBAE45E0F5D0B", 16), // Z new BigInteger("E95E4A5F737059DC60DFC7AD95B3D8139515620F", 16), // q new BigInteger("E95E4A5F737059DC60DFC7AD95B3D8139515620C", 16), // a' new BigInteger("7A556B6DAE535B7B51ED2C4D7DAA7A0B5C55F380", 16)); // b' return new X9ECParameters( curve, curve.DecodePoint(Hex.Decode("04B199B13B9B34EFC1397E64BAEB05ACC265FF2378ADD6718B7C7C1961F0991B842443772152C9E0AD")), // G new BigInteger("E95E4A5F737059DC60DF5991D45029409E60FC09", 16), //n new BigInteger("01", 16)); // h } } internal class BrainpoolP192r1Holder : X9ECParametersHolder { private BrainpoolP192r1Holder() {} internal static readonly X9ECParametersHolder Instance = new BrainpoolP192r1Holder(); protected override X9ECParameters CreateParameters() { ECCurve curve = new FpCurve( new BigInteger("C302F41D932A36CDA7A3463093D18DB78FCE476DE1A86297", 16), // q new BigInteger("6A91174076B1E0E19C39C031FE8685C1CAE040E5C69A28EF", 16), // a new BigInteger("469A28EF7C28CCA3DC721D044F4496BCCA7EF4146FBF25C9", 16)); // b return new X9ECParameters( curve, curve.DecodePoint(Hex.Decode("04C0A0647EAAB6A48753B033C56CB0F0900A2F5C4853375FD614B690866ABD5BB88B5F4828C1490002E6773FA2FA299B8F")), // G new BigInteger("C302F41D932A36CDA7A3462F9E9E916B5BE8F1029AC4ACC1", 16), //n new BigInteger("01", 16)); // h } } internal class BrainpoolP192t1Holder : X9ECParametersHolder { private BrainpoolP192t1Holder() {} internal static readonly X9ECParametersHolder Instance = new BrainpoolP192t1Holder(); protected override X9ECParameters CreateParameters() { ECCurve curve = new FpCurve( //new BigInteger("1B6F5CC8DB4DC7AF19458A9CB80DC2295E5EB9C3732104CB") //Z new BigInteger("C302F41D932A36CDA7A3463093D18DB78FCE476DE1A86297", 16), // q new BigInteger("C302F41D932A36CDA7A3463093D18DB78FCE476DE1A86294", 16), // a' new BigInteger("13D56FFAEC78681E68F9DEB43B35BEC2FB68542E27897B79", 16)); // b' return new X9ECParameters( curve, curve.DecodePoint(Hex.Decode("043AE9E58C82F63C30282E1FE7BBF43FA72C446AF6F4618129097E2C5667C2223A902AB5CA449D0084B7E5B3DE7CCC01C9")), // G' new BigInteger("C302F41D932A36CDA7A3462F9E9E916B5BE8F1029AC4ACC1", 16), //n new BigInteger("01", 16)); // h } } internal class BrainpoolP224r1Holder : X9ECParametersHolder { private BrainpoolP224r1Holder() {} internal static readonly X9ECParametersHolder Instance = new BrainpoolP224r1Holder(); protected override X9ECParameters CreateParameters() { ECCurve curve = new FpCurve( new BigInteger("D7C134AA264366862A18302575D1D787B09F075797DA89F57EC8C0FF", 16), // q new BigInteger("68A5E62CA9CE6C1C299803A6C1530B514E182AD8B0042A59CAD29F43", 16), // a new BigInteger("2580F63CCFE44138870713B1A92369E33E2135D266DBB372386C400B", 16)); // b return new X9ECParameters( curve, curve.DecodePoint(Hex.Decode("040D9029AD2C7E5CF4340823B2A87DC68C9E4CE3174C1E6EFDEE12C07D58AA56F772C0726F24C6B89E4ECDAC24354B9E99CAA3F6D3761402CD")), // G new BigInteger("D7C134AA264366862A18302575D0FB98D116BC4B6DDEBCA3A5A7939F", 16), //n new BigInteger("01", 16)); // n } } internal class BrainpoolP224t1Holder : X9ECParametersHolder { private BrainpoolP224t1Holder() {} internal static readonly X9ECParametersHolder Instance = new BrainpoolP224t1Holder(); protected override X9ECParameters CreateParameters() { ECCurve curve = new FpCurve( //new BigInteger("2DF271E14427A346910CF7A2E6CFA7B3F484E5C2CCE1C8B730E28B3F") //Z new BigInteger("D7C134AA264366862A18302575D1D787B09F075797DA89F57EC8C0FF", 16), // q new BigInteger("D7C134AA264366862A18302575D1D787B09F075797DA89F57EC8C0FC", 16), // a' new BigInteger("4B337D934104CD7BEF271BF60CED1ED20DA14C08B3BB64F18A60888D", 16)); // b' return new X9ECParameters( curve, curve.DecodePoint(Hex.Decode("046AB1E344CE25FF3896424E7FFE14762ECB49F8928AC0C76029B4D5800374E9F5143E568CD23F3F4D7C0D4B1E41C8CC0D1C6ABD5F1A46DB4C")), // G' new BigInteger("D7C134AA264366862A18302575D0FB98D116BC4B6DDEBCA3A5A7939F", 16), //n new BigInteger("01", 16)); // h } } internal class BrainpoolP256r1Holder : X9ECParametersHolder { private BrainpoolP256r1Holder() {} internal static readonly X9ECParametersHolder Instance = new BrainpoolP256r1Holder(); protected override X9ECParameters CreateParameters() { ECCurve curve = new FpCurve( new BigInteger("A9FB57DBA1EEA9BC3E660A909D838D726E3BF623D52620282013481D1F6E5377", 16), // q new BigInteger("7D5A0975FC2C3057EEF67530417AFFE7FB8055C126DC5C6CE94A4B44F330B5D9", 16), // a new BigInteger("26DC5C6CE94A4B44F330B5D9BBD77CBF958416295CF7E1CE6BCCDC18FF8C07B6", 16)); // b return new X9ECParameters( curve, curve.DecodePoint(Hex.Decode("048BD2AEB9CB7E57CB2C4B482FFC81B7AFB9DE27E1E3BD23C23A4453BD9ACE3262547EF835C3DAC4FD97F8461A14611DC9C27745132DED8E545C1D54C72F046997")), // G new BigInteger("A9FB57DBA1EEA9BC3E660A909D838D718C397AA3B561A6F7901E0E82974856A7", 16), //n new BigInteger("01", 16)); // h } } internal class BrainpoolP256t1Holder : X9ECParametersHolder { private BrainpoolP256t1Holder() {} internal static readonly X9ECParametersHolder Instance = new BrainpoolP256t1Holder(); protected override X9ECParameters CreateParameters() { ECCurve curve = new FpCurve( //new BigInteger("3E2D4BD9597B58639AE7AA669CAB9837CF5CF20A2C852D10F655668DFC150EF0") //Z new BigInteger("A9FB57DBA1EEA9BC3E660A909D838D726E3BF623D52620282013481D1F6E5377", 16), // q new BigInteger("A9FB57DBA1EEA9BC3E660A909D838D726E3BF623D52620282013481D1F6E5374", 16), // a' new BigInteger("662C61C430D84EA4FE66A7733D0B76B7BF93EBC4AF2F49256AE58101FEE92B04", 16)); // b' return new X9ECParameters( curve, curve.DecodePoint(Hex.Decode("04A3E8EB3CC1CFE7B7732213B23A656149AFA142C47AAFBC2B79A191562E1305F42D996C823439C56D7F7B22E14644417E69BCB6DE39D027001DABE8F35B25C9BE")), // G' new BigInteger("A9FB57DBA1EEA9BC3E660A909D838D718C397AA3B561A6F7901E0E82974856A7", 16), //n new BigInteger("01", 16)); // h } } internal class BrainpoolP320r1Holder : X9ECParametersHolder { private BrainpoolP320r1Holder() {} internal static readonly X9ECParametersHolder Instance = new BrainpoolP320r1Holder(); protected override X9ECParameters CreateParameters() { ECCurve curve = new FpCurve( new BigInteger("D35E472036BC4FB7E13C785ED201E065F98FCFA6F6F40DEF4F92B9EC7893EC28FCD412B1F1B32E27", 16), // q new BigInteger("3EE30B568FBAB0F883CCEBD46D3F3BB8A2A73513F5EB79DA66190EB085FFA9F492F375A97D860EB4", 16), // a new BigInteger("520883949DFDBC42D3AD198640688A6FE13F41349554B49ACC31DCCD884539816F5EB4AC8FB1F1A6", 16)); // b return new X9ECParameters( curve, curve.DecodePoint(Hex.Decode("0443BD7E9AFB53D8B85289BCC48EE5BFE6F20137D10A087EB6E7871E2A10A599C710AF8D0D39E2061114FDD05545EC1CC8AB4093247F77275E0743FFED117182EAA9C77877AAAC6AC7D35245D1692E8EE1")), // G new BigInteger("D35E472036BC4FB7E13C785ED201E065F98FCFA5B68F12A32D482EC7EE8658E98691555B44C59311", 16), //n new BigInteger("01", 16)); // h } } internal class BrainpoolP320t1Holder : X9ECParametersHolder { private BrainpoolP320t1Holder() {} internal static readonly X9ECParametersHolder Instance = new BrainpoolP320t1Holder(); protected override X9ECParameters CreateParameters() { ECCurve curve = new FpCurve( //new BigInteger("15F75CAF668077F7E85B42EB01F0A81FF56ECD6191D55CB82B7D861458A18FEFC3E5AB7496F3C7B1") //Z new BigInteger("D35E472036BC4FB7E13C785ED201E065F98FCFA6F6F40DEF4F92B9EC7893EC28FCD412B1F1B32E27", 16), // q new BigInteger("D35E472036BC4FB7E13C785ED201E065F98FCFA6F6F40DEF4F92B9EC7893EC28FCD412B1F1B32E24", 16), // a' new BigInteger("A7F561E038EB1ED560B3D147DB782013064C19F27ED27C6780AAF77FB8A547CEB5B4FEF422340353", 16)); // b' return new X9ECParameters( curve, curve.DecodePoint(Hex.Decode("04925BE9FB01AFC6FB4D3E7D4990010F813408AB106C4F09CB7EE07868CC136FFF3357F624A21BED5263BA3A7A27483EBF6671DBEF7ABB30EBEE084E58A0B077AD42A5A0989D1EE71B1B9BC0455FB0D2C3")), // G' new BigInteger("D35E472036BC4FB7E13C785ED201E065F98FCFA5B68F12A32D482EC7EE8658E98691555B44C59311", 16), //n new BigInteger("01", 16)); // h } } internal class BrainpoolP384r1Holder : X9ECParametersHolder { private BrainpoolP384r1Holder() {} internal static readonly X9ECParametersHolder Instance = new BrainpoolP384r1Holder(); protected override X9ECParameters CreateParameters() { ECCurve curve = new FpCurve( new BigInteger("8CB91E82A3386D280F5D6F7E50E641DF152F7109ED5456B412B1DA197FB71123ACD3A729901D1A71874700133107EC53", 16), // q new BigInteger("7BC382C63D8C150C3C72080ACE05AFA0C2BEA28E4FB22787139165EFBA91F90F8AA5814A503AD4EB04A8C7DD22CE2826", 16), // a new BigInteger("4A8C7DD22CE28268B39B55416F0447C2FB77DE107DCD2A62E880EA53EEB62D57CB4390295DBC9943AB78696FA504C11", 16)); // b return new X9ECParameters( curve, curve.DecodePoint(Hex.Decode("041D1C64F068CF45FFA2A63A81B7C13F6B8847A3E77EF14FE3DB7FCAFE0CBD10E8E826E03436D646AAEF87B2E247D4AF1E8ABE1D7520F9C2A45CB1EB8E95CFD55262B70B29FEEC5864E19C054FF99129280E4646217791811142820341263C5315")), // G new BigInteger("8CB91E82A3386D280F5D6F7E50E641DF152F7109ED5456B31F166E6CAC0425A7CF3AB6AF6B7FC3103B883202E9046565", 16), //n new BigInteger("01", 16)); // h } } internal class BrainpoolP384t1Holder : X9ECParametersHolder { private BrainpoolP384t1Holder() {} internal static readonly X9ECParametersHolder Instance = new BrainpoolP384t1Holder(); protected override X9ECParameters CreateParameters() { ECCurve curve = new FpCurve( //new BigInteger("41DFE8DD399331F7166A66076734A89CD0D2BCDB7D068E44E1F378F41ECBAE97D2D63DBC87BCCDDCCC5DA39E8589291C") //Z new BigInteger("8CB91E82A3386D280F5D6F7E50E641DF152F7109ED5456B412B1DA197FB71123ACD3A729901D1A71874700133107EC53", 16), // q new BigInteger("8CB91E82A3386D280F5D6F7E50E641DF152F7109ED5456B412B1DA197FB71123ACD3A729901D1A71874700133107EC50", 16), // a' new BigInteger("7F519EADA7BDA81BD826DBA647910F8C4B9346ED8CCDC64E4B1ABD11756DCE1D2074AA263B88805CED70355A33B471EE", 16)); // b' return new X9ECParameters( curve, curve.DecodePoint(Hex.Decode("0418DE98B02DB9A306F2AFCD7235F72A819B80AB12EBD653172476FECD462AABFFC4FF191B946A5F54D8D0AA2F418808CC25AB056962D30651A114AFD2755AD336747F93475B7A1FCA3B88F2B6A208CCFE469408584DC2B2912675BF5B9E582928")), // G' new BigInteger("8CB91E82A3386D280F5D6F7E50E641DF152F7109ED5456B31F166E6CAC0425A7CF3AB6AF6B7FC3103B883202E9046565", 16), //n new BigInteger("01", 16)); // h } } internal class BrainpoolP512r1Holder : X9ECParametersHolder { private BrainpoolP512r1Holder() {} internal static readonly X9ECParametersHolder Instance = new BrainpoolP512r1Holder(); protected override X9ECParameters CreateParameters() { ECCurve curve = new FpCurve( new BigInteger("AADD9DB8DBE9C48B3FD4E6AE33C9FC07CB308DB3B3C9D20ED6639CCA703308717D4D9B009BC66842AECDA12AE6A380E62881FF2F2D82C68528AA6056583A48F3", 16), // q new BigInteger("7830A3318B603B89E2327145AC234CC594CBDD8D3DF91610A83441CAEA9863BC2DED5D5AA8253AA10A2EF1C98B9AC8B57F1117A72BF2C7B9E7C1AC4D77FC94CA", 16), // a new BigInteger("3DF91610A83441CAEA9863BC2DED5D5AA8253AA10A2EF1C98B9AC8B57F1117A72BF2C7B9E7C1AC4D77FC94CADC083E67984050B75EBAE5DD2809BD638016F723", 16)); // b return new X9ECParameters( curve, curve.DecodePoint(Hex.Decode("0481AEE4BDD82ED9645A21322E9C4C6A9385ED9F70B5D916C1B43B62EEF4D0098EFF3B1F78E2D0D48D50D1687B93B97D5F7C6D5047406A5E688B352209BCB9F8227DDE385D566332ECC0EABFA9CF7822FDF209F70024A57B1AA000C55B881F8111B2DCDE494A5F485E5BCA4BD88A2763AED1CA2B2FA8F0540678CD1E0F3AD80892")), // G new BigInteger("AADD9DB8DBE9C48B3FD4E6AE33C9FC07CB308DB3B3C9D20ED6639CCA70330870553E5C414CA92619418661197FAC10471DB1D381085DDADDB58796829CA90069", 16), //n new BigInteger("01", 16)); // h } } internal class BrainpoolP512t1Holder : X9ECParametersHolder { private BrainpoolP512t1Holder() {} internal static readonly X9ECParametersHolder Instance = new BrainpoolP512t1Holder(); protected override X9ECParameters CreateParameters() { ECCurve curve = new FpCurve( //new BigInteger("12EE58E6764838B69782136F0F2D3BA06E27695716054092E60A80BEDB212B64E585D90BCE13761F85C3F1D2A64E3BE8FEA2220F01EBA5EEB0F35DBD29D922AB") //Z new BigInteger("AADD9DB8DBE9C48B3FD4E6AE33C9FC07CB308DB3B3C9D20ED6639CCA703308717D4D9B009BC66842AECDA12AE6A380E62881FF2F2D82C68528AA6056583A48F3", 16), // q new BigInteger("AADD9DB8DBE9C48B3FD4E6AE33C9FC07CB308DB3B3C9D20ED6639CCA703308717D4D9B009BC66842AECDA12AE6A380E62881FF2F2D82C68528AA6056583A48F0", 16), // a' new BigInteger("7CBBBCF9441CFAB76E1890E46884EAE321F70C0BCB4981527897504BEC3E36A62BCDFA2304976540F6450085F2DAE145C22553B465763689180EA2571867423E", 16)); // b' return new X9ECParameters( curve, curve.DecodePoint(Hex.Decode("04640ECE5C12788717B9C1BA06CBC2A6FEBA85842458C56DDE9DB1758D39C0313D82BA51735CDB3EA499AA77A7D6943A64F7A3F25FE26F06B51BAA2696FA9035DA5B534BD595F5AF0FA2C892376C84ACE1BB4E3019B71634C01131159CAE03CEE9D9932184BEEF216BD71DF2DADF86A627306ECFF96DBB8BACE198B61E00F8B332")), // G' new BigInteger("AADD9DB8DBE9C48B3FD4E6AE33C9FC07CB308DB3B3C9D20ED6639CCA70330870553E5C414CA92619418661197FAC10471DB1D381085DDADDB58796829CA90069", 16), //n new BigInteger("01", 16)); // h } } private static readonly IDictionary objIds = Platform.CreateHashtable(); private static readonly IDictionary curves = Platform.CreateHashtable(); private static readonly IDictionary names = Platform.CreateHashtable(); private static void DefineCurve( string name, DerObjectIdentifier oid, X9ECParametersHolder holder) { objIds.Add(name, oid); names.Add(oid, name); curves.Add(oid, holder); } static TeleTrusTNamedCurves() { DefineCurve("brainpoolp160r1", TeleTrusTObjectIdentifiers.BrainpoolP160R1, BrainpoolP160r1Holder.Instance); DefineCurve("brainpoolp160t1", TeleTrusTObjectIdentifiers.BrainpoolP160T1, BrainpoolP160t1Holder.Instance); DefineCurve("brainpoolp192r1", TeleTrusTObjectIdentifiers.BrainpoolP192R1, BrainpoolP192r1Holder.Instance); DefineCurve("brainpoolp192t1", TeleTrusTObjectIdentifiers.BrainpoolP192T1, BrainpoolP192t1Holder.Instance); DefineCurve("brainpoolp224r1", TeleTrusTObjectIdentifiers.BrainpoolP224R1, BrainpoolP224r1Holder.Instance); DefineCurve("brainpoolp224t1", TeleTrusTObjectIdentifiers.BrainpoolP224T1, BrainpoolP224t1Holder.Instance); DefineCurve("brainpoolp256r1", TeleTrusTObjectIdentifiers.BrainpoolP256R1, BrainpoolP256r1Holder.Instance); DefineCurve("brainpoolp256t1", TeleTrusTObjectIdentifiers.BrainpoolP256T1, BrainpoolP256t1Holder.Instance); DefineCurve("brainpoolp320r1", TeleTrusTObjectIdentifiers.BrainpoolP320R1, BrainpoolP320r1Holder.Instance); DefineCurve("brainpoolp320t1", TeleTrusTObjectIdentifiers.BrainpoolP320T1, BrainpoolP320t1Holder.Instance); DefineCurve("brainpoolp384r1", TeleTrusTObjectIdentifiers.BrainpoolP384R1, BrainpoolP384r1Holder.Instance); DefineCurve("brainpoolp384t1", TeleTrusTObjectIdentifiers.BrainpoolP384T1, BrainpoolP384t1Holder.Instance); DefineCurve("brainpoolp512r1", TeleTrusTObjectIdentifiers.BrainpoolP512R1, BrainpoolP512r1Holder.Instance); DefineCurve("brainpoolp512t1", TeleTrusTObjectIdentifiers.BrainpoolP512T1, BrainpoolP512t1Holder.Instance); } public static X9ECParameters GetByName( string name) { DerObjectIdentifier oid = (DerObjectIdentifier) objIds[name.ToLowerInvariant()]; return oid == null ? null : GetByOid(oid); } /** * return the X9ECParameters object for the named curve represented by * the passed in object identifier. Null if the curve isn't present. * * @param oid an object identifier representing a named curve, if present. */ public static X9ECParameters GetByOid( DerObjectIdentifier oid) { X9ECParametersHolder holder = (X9ECParametersHolder) curves[oid]; return holder == null ? null : holder.Parameters; } /** * return the object identifier signified by the passed in name. Null * if there is no object identifier associated with name. * * @return the object identifier associated with name, if present. */ public static DerObjectIdentifier GetOid( string name) { return (DerObjectIdentifier) objIds[name.ToLowerInvariant()]; } /** * return the named curve name represented by the given object identifier. */ public static string GetName( DerObjectIdentifier oid) { return (string) names[oid]; } /** * returns an enumeration containing the name strings for curves * contained in this structure. */ public static IEnumerable Names { get { return new EnumerableProxy(objIds.Keys); } } public static DerObjectIdentifier GetOid( short curvesize, bool twisted) { return GetOid("brainpoolP" + curvesize + (twisted ? "t" : "r") + "1"); } } }
// 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. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // ConcatQueryOperator.cs // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System.Collections.Generic; using System.Diagnostics; using System.Threading; namespace System.Linq.Parallel { /// <summary> /// Concatenates one data source with another. Order preservation is used to ensure /// the output is actually a concatenation -- i.e. one after the other. The only /// special synchronization required is to find the largest index N in the first data /// source so that the indices of elements in the second data source can be offset /// by adding N+1. This makes it appear to the order preservation infrastructure as /// though all elements in the second came after all elements in the first, which is /// precisely what we want. /// </summary> /// <typeparam name="TSource"></typeparam> internal sealed class ConcatQueryOperator<TSource> : BinaryQueryOperator<TSource, TSource, TSource> { private readonly bool _prematureMergeLeft = false; // Whether to prematurely merge the left data source private readonly bool _prematureMergeRight = false; // Whether to prematurely merge the right data source //--------------------------------------------------------------------------------------- // Initializes a new concatenation operator. // // Arguments: // child - the child whose data we will reverse // internal ConcatQueryOperator(ParallelQuery<TSource> firstChild, ParallelQuery<TSource> secondChild) : base(firstChild, secondChild) { Debug.Assert(firstChild != null, "first child data source cannot be null"); Debug.Assert(secondChild != null, "second child data source cannot be null"); _outputOrdered = LeftChild.OutputOrdered || RightChild.OutputOrdered; _prematureMergeLeft = LeftChild.OrdinalIndexState.IsWorseThan(OrdinalIndexState.Increasing); _prematureMergeRight = RightChild.OrdinalIndexState.IsWorseThan(OrdinalIndexState.Increasing); if ((LeftChild.OrdinalIndexState == OrdinalIndexState.Indexible) && (RightChild.OrdinalIndexState == OrdinalIndexState.Indexible)) { SetOrdinalIndex(OrdinalIndexState.Indexible); } else { SetOrdinalIndex( ExchangeUtilities.Worse(OrdinalIndexState.Increasing, ExchangeUtilities.Worse(LeftChild.OrdinalIndexState, RightChild.OrdinalIndexState))); } } //--------------------------------------------------------------------------------------- // Just opens the current operator, including opening the child and wrapping it with // partitions as needed. // internal override QueryResults<TSource> Open(QuerySettings settings, bool preferStriping) { // We just open the children operators. QueryResults<TSource> leftChildResults = LeftChild.Open(settings, preferStriping); QueryResults<TSource> rightChildResults = RightChild.Open(settings, preferStriping); return ConcatQueryOperatorResults.NewResults(leftChildResults, rightChildResults, this, settings, preferStriping); } public override void WrapPartitionedStream<TLeftKey, TRightKey>( PartitionedStream<TSource, TLeftKey> leftStream, PartitionedStream<TSource, TRightKey> rightStream, IPartitionedStreamRecipient<TSource> outputRecipient, bool preferStriping, QuerySettings settings) { // Prematurely merge the left results, if necessary if (_prematureMergeLeft) { ListQueryResults<TSource> leftStreamResults = ExecuteAndCollectResults(leftStream, leftStream.PartitionCount, LeftChild.OutputOrdered, preferStriping, settings); PartitionedStream<TSource, int> leftStreamInc = leftStreamResults.GetPartitionedStream(); WrapHelper<int, TRightKey>(leftStreamInc, rightStream, outputRecipient, settings, preferStriping); } else { Debug.Assert(!ExchangeUtilities.IsWorseThan(leftStream.OrdinalIndexState, OrdinalIndexState.Increasing)); WrapHelper<TLeftKey, TRightKey>(leftStream, rightStream, outputRecipient, settings, preferStriping); } } private void WrapHelper<TLeftKey, TRightKey>( PartitionedStream<TSource, TLeftKey> leftStreamInc, PartitionedStream<TSource, TRightKey> rightStream, IPartitionedStreamRecipient<TSource> outputRecipient, QuerySettings settings, bool preferStriping) { // Prematurely merge the right results, if necessary if (_prematureMergeRight) { ListQueryResults<TSource> rightStreamResults = ExecuteAndCollectResults(rightStream, leftStreamInc.PartitionCount, LeftChild.OutputOrdered, preferStriping, settings); PartitionedStream<TSource, int> rightStreamInc = rightStreamResults.GetPartitionedStream(); WrapHelper2<TLeftKey, int>(leftStreamInc, rightStreamInc, outputRecipient); } else { Debug.Assert(!ExchangeUtilities.IsWorseThan(rightStream.OrdinalIndexState, OrdinalIndexState.Increasing)); WrapHelper2<TLeftKey, TRightKey>(leftStreamInc, rightStream, outputRecipient); } } private void WrapHelper2<TLeftKey, TRightKey>( PartitionedStream<TSource, TLeftKey> leftStreamInc, PartitionedStream<TSource, TRightKey> rightStreamInc, IPartitionedStreamRecipient<TSource> outputRecipient) { int partitionCount = leftStreamInc.PartitionCount; // Generate the shared data. IComparer<ConcatKey> comparer = ConcatKey.MakeComparer( leftStreamInc.KeyComparer, rightStreamInc.KeyComparer); var outputStream = new PartitionedStream<TSource, ConcatKey>(partitionCount, comparer, OrdinalIndexState); for (int i = 0; i < partitionCount; i++) { outputStream[i] = new ConcatQueryOperatorEnumerator<TLeftKey, TRightKey>(leftStreamInc[i], rightStreamInc[i]); } outputRecipient.Receive(outputStream); } //--------------------------------------------------------------------------------------- // Returns an enumerable that represents the query executing sequentially. // internal override IEnumerable<TSource> AsSequentialQuery(CancellationToken token) { return LeftChild.AsSequentialQuery(token).Concat(RightChild.AsSequentialQuery(token)); } //--------------------------------------------------------------------------------------- // Whether this operator performs a premature merge that would not be performed in // a similar sequential operation (i.e., in LINQ to Objects). // internal override bool LimitsParallelism { get { return false; } } //--------------------------------------------------------------------------------------- // The enumerator type responsible for concatenating two data sources. // class ConcatQueryOperatorEnumerator<TLeftKey, TRightKey> : QueryOperatorEnumerator<TSource, ConcatKey> { private QueryOperatorEnumerator<TSource, TLeftKey> _firstSource; // The first data source to enumerate. private QueryOperatorEnumerator<TSource, TRightKey> _secondSource; // The second data source to enumerate. private bool _begunSecond; // Whether this partition has begun enumerating the second source yet. //--------------------------------------------------------------------------------------- // Instantiates a new select enumerator. // internal ConcatQueryOperatorEnumerator( QueryOperatorEnumerator<TSource, TLeftKey> firstSource, QueryOperatorEnumerator<TSource, TRightKey> secondSource) { Debug.Assert(firstSource != null); Debug.Assert(secondSource != null); _firstSource = firstSource; _secondSource = secondSource; } //--------------------------------------------------------------------------------------- // MoveNext advances to the next element in the output. While the first data source has // elements, this consists of just advancing through it. After this, all partitions must // synchronize at a barrier and publish the maximum index N. Finally, all partitions can // move on to the second data source, adding N+1 to indices in order to get the correct // index offset. // internal override bool MoveNext(ref TSource currentElement, ref ConcatKey currentKey) { Debug.Assert(_firstSource != null); Debug.Assert(_secondSource != null); // If we are still enumerating the first source, fetch the next item. if (!_begunSecond) { // If elements remain, just return true and continue enumerating the left. TLeftKey leftKey = default(TLeftKey); if (_firstSource.MoveNext(ref currentElement, ref leftKey)) { currentKey = ConcatKey.MakeLeft<TLeftKey, TRightKey>(leftKey); return true; } _begunSecond = true; } // Now either move on to, or continue, enumerating the right data source. TRightKey rightKey = default(TRightKey); if (_secondSource.MoveNext(ref currentElement, ref rightKey)) { currentKey = ConcatKey.MakeRight<TLeftKey, TRightKey>(rightKey); return true; } return false; } protected override void Dispose(bool disposing) { _firstSource.Dispose(); _secondSource.Dispose(); } } //----------------------------------------------------------------------------------- // Query results for a Concat operator. The results are indexible if the child // results were indexible. // class ConcatQueryOperatorResults : BinaryQueryOperatorResults { private ConcatQueryOperator<TSource> _concatOp; // Operator that generated the results private int _leftChildCount; // The number of elements in the left child result set private int _rightChildCount; // The number of elements in the right child result set public static QueryResults<TSource> NewResults( QueryResults<TSource> leftChildQueryResults, QueryResults<TSource> rightChildQueryResults, ConcatQueryOperator<TSource> op, QuerySettings settings, bool preferStriping) { if (leftChildQueryResults.IsIndexible && rightChildQueryResults.IsIndexible) { return new ConcatQueryOperatorResults( leftChildQueryResults, rightChildQueryResults, op, settings, preferStriping); } else { return new BinaryQueryOperatorResults( leftChildQueryResults, rightChildQueryResults, op, settings, preferStriping); } } private ConcatQueryOperatorResults( QueryResults<TSource> leftChildQueryResults, QueryResults<TSource> rightChildQueryResults, ConcatQueryOperator<TSource> concatOp, QuerySettings settings, bool preferStriping) : base(leftChildQueryResults, rightChildQueryResults, concatOp, settings, preferStriping) { _concatOp = concatOp; Debug.Assert(leftChildQueryResults.IsIndexible && rightChildQueryResults.IsIndexible); _leftChildCount = leftChildQueryResults.ElementsCount; _rightChildCount = rightChildQueryResults.ElementsCount; } internal override bool IsIndexible { get { return true; } } internal override int ElementsCount { get { Debug.Assert(_leftChildCount >= 0 && _rightChildCount >= 0); return _leftChildCount + _rightChildCount; } } internal override TSource GetElement(int index) { if (index < _leftChildCount) { return _leftChildQueryResults.GetElement(index); } else { return _rightChildQueryResults.GetElement(index - _leftChildCount); } } } } //--------------------------------------------------------------------------------------- // ConcatKey represents an ordering key for the Concat operator. It knows whether the // element it is associated with is from the left source or the right source, and also // the elements ordering key. // internal struct ConcatKey { private readonly object _leftKey; private readonly object _rightKey; private readonly bool _isLeft; private ConcatKey(object leftKey, object rightKey, bool isLeft) { _leftKey = leftKey; _rightKey = rightKey; _isLeft = isLeft; } internal static ConcatKey MakeLeft<TLeftKey, TRightKey>(object leftKey) { return new ConcatKey(leftKey, default(TRightKey), true); } internal static ConcatKey MakeRight<TLeftKey, TRightKey>(object rightKey) { return new ConcatKey(default(TLeftKey), rightKey, false); } internal static IComparer<ConcatKey> MakeComparer<T, U>( IComparer<T> leftComparer, IComparer<U> rightComparer) { return new ConcatKeyComparer<T, U>(leftComparer, rightComparer); } //--------------------------------------------------------------------------------------- // ConcatKeyComparer compares ConcatKeys, so that elements from the left source come // before elements from the right source, and elements within each source are ordered // according to the corresponding order key. // private class ConcatKeyComparer<T, U> : IComparer<ConcatKey> { private IComparer<T> _leftComparer; private IComparer<U> _rightComparer; internal ConcatKeyComparer(IComparer<T> leftComparer, IComparer<U> rightComparer) { _leftComparer = leftComparer; _rightComparer = rightComparer; } public int Compare(ConcatKey x, ConcatKey y) { // If one element is from the left source and the other not, the element from the left source // comes earlier. if (x._isLeft != y._isLeft) { return x._isLeft ? -1 : 1; } // Elements are from the same source (left or right). Compare the corresponding keys. if (x._isLeft) { return _leftComparer.Compare((T)x._leftKey, (T)y._leftKey); } return _rightComparer.Compare((U)x._rightKey, (U)y._rightKey); } } } }
/* * 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 OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using System; using System.Text; using System.Xml; using System.IO; using System.Xml.Serialization; namespace OpenSim.Region.Framework.Scenes { /// <summary> /// A new version of the old Channel class, simplified /// </summary> public class TerrainChannel : ITerrainChannel { private readonly bool[,] taint; private double[,] map; public TerrainChannel() { map = new double[Constants.RegionSize, Constants.RegionSize]; taint = new bool[Constants.RegionSize / 16, Constants.RegionSize / 16]; PinHeadIsland(); } public TerrainChannel(String type) { map = new double[Constants.RegionSize, Constants.RegionSize]; taint = new bool[Constants.RegionSize / 16, Constants.RegionSize / 16]; if (type.Equals("flat")) FlatLand(); else PinHeadIsland(); } public TerrainChannel(double[,] import) { map = import; taint = new bool[import.GetLength(0),import.GetLength(1)]; } public TerrainChannel(bool createMap) { if (createMap) { map = new double[Constants.RegionSize,Constants.RegionSize]; taint = new bool[Constants.RegionSize / 16,Constants.RegionSize / 16]; } } public TerrainChannel(int w, int h) { map = new double[w,h]; taint = new bool[w / 16,h / 16]; } #region ITerrainChannel Members public int Width { get { return map.GetLength(0); } } public int Height { get { return map.GetLength(1); } } public ITerrainChannel MakeCopy() { TerrainChannel copy = new TerrainChannel(false); copy.map = (double[,]) map.Clone(); return copy; } public float[] GetFloatsSerialised() { // Move the member variables into local variables, calling // member variables 256*256 times gets expensive int w = Width; int h = Height; float[] heights = new float[w * h]; int i, j; // map coordinates int idx = 0; // index into serialized array for (i = 0; i < h; i++) { for (j = 0; j < w; j++) { heights[idx++] = (float)map[j, i]; } } return heights; } public double[,] GetDoubles() { return map; } public double this[int x, int y] { get { return map[x, y]; } set { // Will "fix" terrain hole problems. Although not fantastically. if (Double.IsNaN(value) || Double.IsInfinity(value)) return; if (map[x, y] != value) { taint[x / 16, y / 16] = true; map[x, y] = value; } } } public bool Tainted(int x, int y) { if (taint[x / 16, y / 16]) { taint[x / 16, y / 16] = false; return true; } return false; } #endregion public TerrainChannel Copy() { TerrainChannel copy = new TerrainChannel(false); copy.map = (double[,]) map.Clone(); return copy; } public string SaveToXmlString() { XmlWriterSettings settings = new XmlWriterSettings(); settings.Encoding = Util.UTF8; using (StringWriter sw = new StringWriter()) { using (XmlWriter writer = XmlWriter.Create(sw, settings)) { WriteXml(writer); } string output = sw.ToString(); return output; } } private void WriteXml(XmlWriter writer) { writer.WriteStartElement(String.Empty, "TerrainMap", String.Empty); ToXml(writer); writer.WriteEndElement(); } public void LoadFromXmlString(string data) { StringReader sr = new StringReader(data); XmlTextReader reader = new XmlTextReader(sr); reader.Read(); ReadXml(reader); reader.Close(); sr.Close(); } private void ReadXml(XmlReader reader) { reader.ReadStartElement("TerrainMap"); FromXml(reader); } private void ToXml(XmlWriter xmlWriter) { float[] mapData = GetFloatsSerialised(); byte[] buffer = new byte[mapData.Length * 4]; for (int i = 0; i < mapData.Length; i++) { byte[] value = BitConverter.GetBytes(mapData[i]); Array.Copy(value, 0, buffer, (i * 4), 4); } XmlSerializer serializer = new XmlSerializer(typeof(byte[])); serializer.Serialize(xmlWriter, buffer); } private void FromXml(XmlReader xmlReader) { XmlSerializer serializer = new XmlSerializer(typeof(byte[])); byte[] dataArray = (byte[])serializer.Deserialize(xmlReader); int index = 0; for (int y = 0; y < Height; y++) { for (int x = 0; x < Width; x++) { float value; value = BitConverter.ToSingle(dataArray, index); index += 4; this[x, y] = (double)value; } } } private void PinHeadIsland() { int x; for (x = 0; x < Constants.RegionSize; x++) { int y; for (y = 0; y < Constants.RegionSize; y++) { map[x, y] = TerrainUtil.PerlinNoise2D(x, y, 2, 0.125) * 10; double spherFacA = TerrainUtil.SphericalFactor(x, y, Constants.RegionSize / 2.0, Constants.RegionSize / 2.0, 50) * 0.01; double spherFacB = TerrainUtil.SphericalFactor(x, y, Constants.RegionSize / 2.0, Constants.RegionSize / 2.0, 100) * 0.001; if (map[x, y] < spherFacA) map[x, y] = spherFacA; if (map[x, y] < spherFacB) map[x, y] = spherFacB; } } } private void FlatLand() { int x; for (x = 0; x < Constants.RegionSize; x++) { int y; for (y = 0; y < Constants.RegionSize; y++) map[x, y] = 21; } } } }
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- namespace Microsoft.WindowsAzure.Management.Sync.Upload { using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Security.Cryptography; using System.ServiceModel.Channels; using System.Text; using System.Threading; using Microsoft.WindowsAzure.Storage; using Microsoft.WindowsAzure.Storage.Auth; using Microsoft.WindowsAzure.Storage.Blob; using Microsoft.WindowsAzure.Storage.RetryPolicies; using Sync.Upload; using Tools.Vhd; using Tools.Vhd.Model; using Tools.Vhd.Model.Persistence; using Sync.Download; public interface ICloudPageBlobObjectFactory { CloudPageBlob Create(BlobUri destination); bool CreateContainer(BlobUri destination); BlobRequestOptions CreateRequestOptions(); } public abstract class BlobCreatorBase { private const long OneTeraByte = 1024L * 1024L * 1024L * 1024L; protected FileInfo localVhd; protected readonly ICloudPageBlobObjectFactory blobObjectFactory; protected Uri destination; protected BlobUri blobDestination; protected string queryString; protected StorageCredentials credentials; protected CloudPageBlob destinationBlob; protected BlobRequestOptions requestOptions; protected bool overWrite; private readonly TimeSpan delayBetweenRetries = TimeSpan.FromSeconds(10); private const int MegaByte = 1024 * 1024; private const int PageSizeInBytes = 2 * MegaByte; private const int MaxBufferSize = 20 * MegaByte; protected BlobCreatorBase(FileInfo localVhd, BlobUri blobDestination, ICloudPageBlobObjectFactory blobObjectFactory, bool overWrite) { this.localVhd = localVhd; this.blobObjectFactory = blobObjectFactory; this.destination = new Uri(blobDestination.BlobPath); this.blobDestination = blobDestination; this.overWrite = overWrite; this.destinationBlob = blobObjectFactory.Create(blobDestination); this.requestOptions = this.blobObjectFactory.CreateRequestOptions(); } private LocalMetaData operationMetaData; public LocalMetaData OperationMetaData { get { if (this.operationMetaData == null) { this.operationMetaData = new LocalMetaData { FileMetaData = FileMetaData.Create(localVhd.FullName), SystemInformation = SystemInformation.Create() }; } return operationMetaData; } } public byte[] MD5HashOfLocalVhd { get { return OperationMetaData.FileMetaData.MD5Hash; } } private static void AssertIfValidVhdSize(FileInfo fileInfo) { using(var stream = new VirtualDiskStream(fileInfo.FullName)) { if(stream.Length > OneTeraByte) { var lengthString = stream.Length.ToString("N0", CultureInfo.CurrentCulture); var expectedLengthString = OneTeraByte.ToString("N0", CultureInfo.CurrentCulture); string message = String.Format("VHD size is too large ('{0}'), maximum allowed size is '{1}'.", lengthString, expectedLengthString); throw new InvalidOperationException(message); } } } public UploadContext Create() { AssertIfValidhVhd(localVhd); AssertIfValidVhdSize(localVhd); this.blobObjectFactory.CreateContainer(blobDestination); UploadContext context = null; bool completed = false; try { context = new UploadContext { DestinationBlob = destinationBlob, SingleInstanceMutex = AcquireSingleInstanceMutex(destinationBlob.Uri) }; if (overWrite) { destinationBlob.DeleteIfExists(DeleteSnapshotsOption.IncludeSnapshots, null, requestOptions); } if (destinationBlob.Exists(requestOptions)) { Program.SyncOutput.MessageResumingUpload(); if(destinationBlob.GetBlobMd5Hash(requestOptions) != null) { throw new InvalidOperationException( "An image already exists in blob storage with this name. If you want to upload again, use the Overwrite option."); } var metaData = destinationBlob.GetUploadMetaData(); AssertMetaDataExists(metaData); AssertMetaDataMatch(metaData, OperationMetaData); PopulateContextWithUploadableRanges(localVhd, context, true); PopulateContextWithDataToUpload(localVhd, context); } else { CreateRemoteBlobAndPopulateContext(context); } context.Md5HashOfLocalVhd = MD5HashOfLocalVhd; completed = true; } finally { if(!completed && context != null) { context.SingleInstanceMutex.ReleaseMutex(); context.SingleInstanceMutex.Close(); } } return context; } public static void AssertIfValidhVhd(FileInfo vhdFile) { var vhdValidationResults = VhdValidator.Validate(VhdValidationType.IsVhd, vhdFile.FullName); if (vhdValidationResults.Count(r => r.ErrorCode != 0) != 0) { string message = String.Format("'{0}' is not a valid VHD file.", vhdFile.FullName); throw new InvalidOperationException(message, vhdValidationResults[0].Error); } } protected abstract void CreateRemoteBlobAndPopulateContext(UploadContext context); protected static void PopulateContextWithUploadableRanges(FileInfo vhdFile, UploadContext context, bool resume) { using (var vds = new VirtualDiskStream(vhdFile.FullName)) { IEnumerable<IndexRange> ranges = vds.Extents.Select(e => e.Range).ToArray(); using(var bs = new BufferedStream(vds)) { if (resume) { var alreadyUploadedRanges = context.DestinationBlob.GetPageRanges().Select(pr => new IndexRange(pr.StartOffset, pr.EndOffset)); ranges = IndexRange.SubstractRanges(ranges, alreadyUploadedRanges); context.AlreadyUploadedDataSize = alreadyUploadedRanges.Sum(ir => ir.Length); } var uploadableRanges = IndexRangeHelper.ChunkRangesBySize(ranges, PageSizeInBytes).ToArray(); if(vds.DiskType == DiskType.Fixed) { var nonEmptyUploadableRanges = GetNonEmptyRanges(bs, uploadableRanges).ToArray(); context.UploadableDataSize = nonEmptyUploadableRanges.Sum(r => r.Length); context.UploadableRanges = nonEmptyUploadableRanges; } // else if(vds.RootDiskType == DiskType.Fixed) // { // var nonEmptyUploadableRanges = GetNonEmptyRanges(bs, uploadableRanges).ToArray(); // context.UploadableDataSize = nonEmptyUploadableRanges.Sum(r => r.Length); // context.UploadableRanges = nonEmptyUploadableRanges; // } else { context.UploadableDataSize = uploadableRanges.Sum(r => r.Length); context.UploadableRanges = uploadableRanges; } } } } protected static void PopulateContextWithDataToUpload(FileInfo vhdFile, UploadContext context) { context.UploadableDataWithRanges = GetDataWithRangesToUpload(vhdFile, context); } protected static IEnumerable<IndexRange> GetNonEmptyRanges(Stream stream, IEnumerable<IndexRange> uploadableRanges) { Program.SyncOutput.MessageDetectingActualDataBlocks(); var manager = BufferManager.CreateBufferManager(Int32.MaxValue, MaxBufferSize); int totalRangeCount = uploadableRanges.Count(); int processedRangeCount = 0; foreach (var range in uploadableRanges) { var dataWithRange = new DataWithRange(manager) { Data = ReadBytes(stream, range, manager), Range = range }; using(dataWithRange) { if(dataWithRange.IsAllZero()) { Program.SyncOutput.DebugEmptyBlockDetected(dataWithRange.Range); } else { yield return dataWithRange.Range; } } Program.SyncOutput.ProgressEmptyBlockDetection(++processedRangeCount, totalRangeCount); } Program.SyncOutput.MessageDetectingActualDataBlocksCompleted(); yield break; } protected static IEnumerable<DataWithRange> GetDataWithRangesToUpload(FileInfo vhdFile, UploadContext context) { var uploadableRanges = context.UploadableRanges; var manager = BufferManager.CreateBufferManager(Int32.MaxValue, MaxBufferSize); using (var vds = new VirtualDiskStream(vhdFile.FullName)) { foreach (var range in uploadableRanges) { var localRange = range; yield return new DataWithRange(manager) { Data = ReadBytes(vds, localRange, manager), Range = localRange }; } } yield break; } private static byte[] ReadBytes(Stream stream, IndexRange rangeToRead, BufferManager manager) { stream.Seek(rangeToRead.StartIndex, SeekOrigin.Begin); var bufferSize = (int)rangeToRead.Length; var buffer = manager.TakeBuffer(bufferSize); for (int bytesRead = stream.Read(buffer, 0, bufferSize); bytesRead < bufferSize; bytesRead += stream.Read(buffer, bytesRead, bufferSize - bytesRead)) { } return buffer; } private static void AssertMetaDataExists(LocalMetaData blobMetaData) { if(blobMetaData == null) { throw new InvalidOperationException("There is no CsUpload metadata on the blob, so CsUpload cannot resume. Use the overwrite option."); } } private static Mutex AcquireSingleInstanceMutex(Uri destinationBlobUri) { string mutexName = GetMutexName(destinationBlobUri); var singleInstanceMutex = new Mutex(false, @"Global\" + mutexName); if (!singleInstanceMutex.WaitOne(TimeSpan.FromSeconds(5), false)) { var message = String.Format("An upload is already in progress on this machine"); throw new InvalidOperationException(message); } return singleInstanceMutex; } private static string GetMutexName(Uri destinationBlobUri) { var invariant = destinationBlobUri.ToString().ToLowerInvariant(); var bytes = Encoding.Unicode.GetBytes(invariant); using(var md5 = MD5.Create()) { byte[] hash = md5.ComputeHash(bytes); return Convert.ToBase64String(hash); } } private static void AssertMetaDataMatch(LocalMetaData blobMetaData, LocalMetaData localMetaData) { var systemInformation = blobMetaData.SystemInformation; if (String.Compare(systemInformation.MachineName, Environment.MachineName, CultureInfo.InvariantCulture, CompareOptions.IgnoreCase) != 0) { var message = String.Format("An upload is already in progress on machine {0} with process id {1}", systemInformation.MachineName, systemInformation.CsUploadProcessId); throw new InvalidOperationException(message); } var fileMetaDataMessages = CompareFileMetaData(blobMetaData.FileMetaData, localMetaData.FileMetaData); if (fileMetaDataMessages.Count > 0) { throw new InvalidOperationException(fileMetaDataMessages.Aggregate((r,n)=>r + Environment.NewLine + n)); } } private static List<string> CompareFileMetaData(FileMetaData blobFileMetaData, FileMetaData localFileMetaData) { var fileMetaDataMessages = new List<string>(); if (blobFileMetaData.VhdSize != localFileMetaData.VhdSize) { var message = String.Format("Logical size of VHD file in blob storage ({0}) and local VHD file ({1}) does not match ", blobFileMetaData.VhdSize, localFileMetaData.VhdSize); fileMetaDataMessages.Add(message); } if (blobFileMetaData.Size != localFileMetaData.Size) { var message = String.Format("Size of VHD file in blob storage ({0}) and local VHD file ({1}) does not match ", blobFileMetaData.Size, localFileMetaData.Size); fileMetaDataMessages.Add(message); } if (!blobFileMetaData.MD5Hash.SequenceEqual(localFileMetaData.MD5Hash)) { var message = String.Format("MD5 hash of VHD file in blob storage ({0}) and local VHD file ({1}) does not match ", blobFileMetaData.MD5Hash.ToString(","), localFileMetaData.MD5Hash.ToString(",")); fileMetaDataMessages.Add(message); } if (DateTime.Compare(blobFileMetaData.LastModifiedDateUtc, localFileMetaData.LastModifiedDateUtc) != 0) { var message = String.Format("Last modified date of VHD file in blob storage ({0}) and local VHD file ({1}) does not match ", blobFileMetaData.LastModifiedDateUtc, localFileMetaData.LastModifiedDateUtc); fileMetaDataMessages.Add(message); } if (blobFileMetaData.FileFullName != localFileMetaData.FileFullName) { var message = String.Format("Full name of VHD file in blob storage ({0}) and local VHD file ({1}) does not match ", blobFileMetaData.FileFullName, localFileMetaData.FileFullName); fileMetaDataMessages.Add(message); } if (blobFileMetaData.CreatedDateUtc != localFileMetaData.CreatedDateUtc) { var message = String.Format("Full name of VHD file in blob storage ({0}) and local VHD file ({1}) does not match ", blobFileMetaData.CreatedDateUtc, localFileMetaData.CreatedDateUtc); fileMetaDataMessages.Add(message); } return fileMetaDataMessages; } } }
//------------------------------------------------------------------------------ // Microsoft Windows Presentation Foundation // Copyright (c) Microsoft Corporation, 2008 // // File: PixelShader.cs //------------------------------------------------------------------------------ using System; using System.IO; using MS.Internal; using MS.Win32.PresentationCore; using System.ComponentModel; using System.ComponentModel.Design.Serialization; using System.Diagnostics; using System.Reflection; using System.Collections; using System.Globalization; using System.Security; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Media.Composition; using System.Windows; using System.Text.RegularExpressions; using System.Runtime.InteropServices; using System.Windows.Markup; using SR=MS.Internal.PresentationCore.SR; using SRID=MS.Internal.PresentationCore.SRID; using System.Windows.Navigation; using System.IO.Packaging; using MS.Internal.PresentationCore; namespace System.Windows.Media.Effects { public sealed partial class PixelShader : Animatable, DUCE.IResource { // Method and not property so we don't need to hang onto the stream. public void SetStreamSource(Stream source) { WritePreamble(); LoadPixelShaderFromStreamIntoMemory(source); WritePostscript(); } /// <summary> /// The major version of the pixel shader /// </summary> internal short ShaderMajorVersion { get; private set; } /// <summary> /// The minor version of the pixel shader /// </summary> internal short ShaderMinorVersion { get; private set; } /// <summary> /// If any PixelShader cannot be processed by the render thread, this /// event will be raised. /// </summary> public static event EventHandler InvalidPixelShaderEncountered { add { // Just forward to the internal event on MediaContext MediaContext mediaContext = MediaContext.CurrentMediaContext; mediaContext.InvalidPixelShaderEncountered += value; } remove { MediaContext mediaContext = MediaContext.CurrentMediaContext; mediaContext.InvalidPixelShaderEncountered -= value; } } /// <summary> /// This method is invoked whenever the source property changes. /// </summary> private void UriSourcePropertyChangedHook(DependencyPropertyChangedEventArgs e) { // Decided against comparing the URI because the user might want to change the shader on the filesystem // and reload it. // We do not support async loading of shaders here. If that is desired the user needs to use the SetStreamSource // API. Uri newUri = (Uri)e.NewValue; Stream stream = null; try { if (newUri != null) { if (!newUri.IsAbsoluteUri) { newUri = BaseUriHelper.GetResolvedUri(BaseUriHelper.BaseUri, newUri); } Debug.Assert(newUri.IsAbsoluteUri); // Now the URI is an absolute URI. // // Only allow file and pack URIs. if (!newUri.IsFile && !PackUriHelper.IsPackUri(newUri)) { throw new ArgumentException(SR.Get(SRID.Effect_SourceUriMustBeFileOrPack)); } stream = WpfWebRequestHelper.CreateRequestAndGetResponseStream(newUri); } LoadPixelShaderFromStreamIntoMemory(stream); } finally { if (stream != null) { stream.Dispose(); } } } /// <summary> /// Reads the byte code for the pixel shader into a local byte array. If the stream is null, the byte array /// will be empty (length 0). The compositor will use an identity shader. /// </summary> /// <SecurityNote> /// SecurityCritical - because this method sets the critical shader byte code data. /// TreatAsSafe - Demands UI window permission which enforces that the caller is trusted. /// </SecurityNote> [SecurityCritical, SecurityTreatAsSafe] private void LoadPixelShaderFromStreamIntoMemory(Stream source) { SecurityHelper.DemandUIWindowPermission(); _shaderBytecode = new SecurityCriticalData<byte[]>(null); if (source != null) { if (!source.CanSeek) { throw new InvalidOperationException(SR.Get(SRID.Effect_ShaderSeekableStream)); } int len = (int)source.Length; // only works on seekable streams. if (len % sizeof(int) != 0) { throw new InvalidOperationException(SR.Get(SRID.Effect_ShaderBytecodeSize)); } BinaryReader br = new BinaryReader(source); _shaderBytecode = new SecurityCriticalData<byte[]>(new byte[len]); int lengthRead = br.Read(_shaderBytecode.Value, 0, (int)len); // // The first 4 bytes contain version info in the form of // [Minor][Major][xx][xx] // if (_shaderBytecode.Value != null && _shaderBytecode.Value.Length > 3) { ShaderMajorVersion = _shaderBytecode.Value[1]; ShaderMinorVersion = _shaderBytecode.Value[0]; } else { ShaderMajorVersion = ShaderMinorVersion = 0; } Debug.Assert(len == lengthRead); } // We received new stream data. Need to register for a async update to update the composition // engine. RegisterForAsyncUpdateResource(); // // Notify any ShaderEffects listening that the bytecode changed. // The bytecode may have changed from a ps_3_0 shader to a ps_2_0 shader, and any // ShaderEffects using this PixelShader need to check that they are using only // registers that are valid in ps_2_0. // if (_shaderBytecodeChanged != null) { _shaderBytecodeChanged(this, null); } } /// <SecurityNote> /// Critical: This code accesses unsafe code blocks /// TreatAsSafe: This code does is safe to call and calling a channel with pointers is ok /// </SecurityNote> [SecurityCritical,SecurityTreatAsSafe] private void ManualUpdateResource(DUCE.Channel channel, bool skipOnChannelCheck) { // If we're told we can skip the channel check, then we must be on channel Debug.Assert(!skipOnChannelCheck || _duceResource.IsOnChannel(channel)); if (skipOnChannelCheck || _duceResource.IsOnChannel(channel)) { checked { DUCE.MILCMD_PIXELSHADER data; data.Type = MILCMD.MilCmdPixelShader; data.Handle = _duceResource.GetHandle(channel); data.PixelShaderBytecodeSize = (_shaderBytecode.Value == null) ? 0 : (uint)(_shaderBytecode.Value).Length; data.ShaderRenderMode = ShaderRenderMode; data.CompileSoftwareShader = CompositionResourceManager.BooleanToUInt32(!(ShaderMajorVersion == 3 && ShaderMinorVersion == 0)); unsafe { channel.BeginCommand( (byte*)&data, sizeof(DUCE.MILCMD_PIXELSHADER), (int)data.PixelShaderBytecodeSize); // extra data if (data.PixelShaderBytecodeSize > 0) { fixed (byte *pPixelShaderBytecode = _shaderBytecode.Value) { channel.AppendCommandData(pPixelShaderBytecode, (int)data.PixelShaderBytecodeSize); } } } } channel.EndCommand(); } } /// <summary> /// Implementation of <see cref="System.Windows.Freezable.CloneCore(Freezable)">Freezable.CloneCore</see>. /// </summary> /// <param name="sourceFreezable"></param> protected override void CloneCore(Freezable sourceFreezable) { PixelShader shader = (PixelShader)sourceFreezable; base.CloneCore(sourceFreezable); CopyCommon(shader); } /// <summary> /// Implementation of <see cref="System.Windows.Freezable.CloneCurrentValueCore(Freezable)">Freezable.CloneCurrentValueCore</see>. /// </summary> /// <param name="sourceFreezable"></param> protected override void CloneCurrentValueCore(Freezable sourceFreezable) { PixelShader shader = (PixelShader)sourceFreezable; base.CloneCurrentValueCore(sourceFreezable); CopyCommon(shader); } /// <summary> /// Implementation of <see cref="System.Windows.Freezable.GetAsFrozenCore(Freezable)">Freezable.GetAsFrozenCore</see>. /// </summary> /// <param name="sourceFreezable"></param> protected override void GetAsFrozenCore(Freezable sourceFreezable) { PixelShader shader = (PixelShader)sourceFreezable; base.GetAsFrozenCore(sourceFreezable); CopyCommon(shader); } /// <summary> /// Implementation of <see cref="System.Windows.Freezable.GetCurrentValueAsFrozenCore(Freezable)">Freezable.GetCurrentValueAsFrozenCore</see>. /// </summary> /// <param name="sourceFreezable"></param> protected override void GetCurrentValueAsFrozenCore(Freezable sourceFreezable) { PixelShader shader = (PixelShader)sourceFreezable; base.GetCurrentValueAsFrozenCore(sourceFreezable); CopyCommon(shader); } /// <summary> /// Clones values that do not have corresponding DPs. /// </summary> /// <param name="transform"></param> /// <SecurityNote> /// SecurityCritical - critical because it access the shader byte code which is a critical resource. /// TreatAsSafe - this API is not dangereous (and could be exposed publicly) because it copies the shader /// byte code from one PixelShader to another. Since the byte code is marked security critical, the source's byte /// code is trusted (verified or provided by a trusted caller). There is also no way to modify the byte code during /// the copy. /// </SecurityNote> [SecurityCritical, SecurityTreatAsSafe] private void CopyCommon(PixelShader shader) { byte[] sourceBytecode = shader._shaderBytecode.Value; byte[] destinationBytecode = null; if (sourceBytecode != null) { destinationBytecode = new byte[sourceBytecode.Length]; sourceBytecode.CopyTo(destinationBytecode, 0); } _shaderBytecode = new SecurityCriticalData<byte[]>(destinationBytecode); } /// <SecurityNote> /// We need to ensure that _shaderByteCode contains only trusted data/shader byte code. This can be /// achieved via two means: /// 1) Verify the byte code to be safe to run on the GPU. /// 2) The shader byte code has been provided by a trusted source. /// Currently 1) is not possible since we have no means to verify shader byte code. Therefore we /// currently require that byte code provided to us can only come from a trusted source. /// </SecurityNote> private SecurityCriticalData<byte[]> _shaderBytecode; // // Introduced with ps_3_0 for ShaderEffect's use // // The scenario is setting up a ShaderEffect with a PixelShader containing a ps_3_0 shader, // setting a ps_3_0 only register (int, bool, or float registers 32 and above), then using // ShaderEffect.PixelShader.UriSource (or SetStreamSource) to swap the ps_3_0 shader out // for a ps_2_0 one. Now there's a value in a register that doesn't exist in ps_2_0. // // The fix is to have ShaderEffect listen for this event on its PixelShader, and verifying // that no invalid registers are used when switching a ps_3_0 register to a ps_2_0 one. // internal event EventHandler _shaderBytecodeChanged; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections; using System.ComponentModel; using System.Diagnostics; using System.Text; using System.Runtime.InteropServices; using System.Security.Principal; namespace System.DirectoryServices.Protocols { public enum ExtendedDNFlag { HexString = 0, StandardString = 1 } [Flags] public enum SecurityMasks { None = 0, Owner = 1, Group = 2, Dacl = 4, Sacl = 8 } [Flags] public enum DirectorySynchronizationOptions : long { None = 0, ObjectSecurity = 0x1, ParentsFirst = 0x0800, PublicDataOnly = 0x2000, IncrementalValues = 0x80000000 } public enum SearchOption { DomainScope = 1, PhantomRoot = 2 } internal class UtilityHandle { private static ConnectionHandle s_handle = new ConnectionHandle(); public static ConnectionHandle GetHandle() => s_handle; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public class SortKey { private string _name; private string _rule; private bool _order = false; public SortKey() { } public SortKey(string attributeName, string matchingRule, bool reverseOrder) { AttributeName = attributeName; _rule = matchingRule; _order = reverseOrder; } public string AttributeName { get => _name; set => _name = value ?? throw new ArgumentNullException(nameof(value)); } public string MatchingRule { get => _rule; set => _rule = value; } public bool ReverseOrder { get => _order; set => _order = value; } } public class DirectoryControl { internal byte[] _directoryControlValue; public DirectoryControl(string type, byte[] value, bool isCritical, bool serverSide) { Type = type ?? throw new ArgumentNullException(nameof(type)); if (value != null) { _directoryControlValue = new byte[value.Length]; for (int i = 0; i < value.Length; i++) { _directoryControlValue[i] = value[i]; } } IsCritical = isCritical; ServerSide = serverSide; } public virtual byte[] GetValue() { if (_directoryControlValue == null) { return Array.Empty<byte>(); } byte[] tempValue = new byte[_directoryControlValue.Length]; for (int i = 0; i < _directoryControlValue.Length; i++) { tempValue[i] = _directoryControlValue[i]; } return tempValue; } public string Type { get; } public bool IsCritical { get; set; } public bool ServerSide { get; set; } internal static void TransformControls(DirectoryControl[] controls) { for (int i = 0; i < controls.Length; i++) { Debug.Assert(controls[i] != null); byte[] value = controls[i].GetValue(); if (controls[i].Type == "1.2.840.113556.1.4.319") { // The control is a PageControl. object[] result = BerConverter.Decode("{iO}", value); Debug.Assert((result != null) && (result.Length == 2)); int size = (int)result[0]; // user expects cookie with length 0 as paged search is done. byte[] cookie = (byte[])result[1] ?? Array.Empty<byte>(); PageResultResponseControl pageControl = new PageResultResponseControl(size, cookie, controls[i].IsCritical, controls[i].GetValue()); controls[i] = pageControl; } else if (controls[i].Type == "1.2.840.113556.1.4.1504") { // The control is an AsqControl. object[] o = BerConverter.Decode("{e}", value); Debug.Assert((o != null) && (o.Length == 1)); int result = (int)o[0]; AsqResponseControl asq = new AsqResponseControl(result, controls[i].IsCritical, controls[i].GetValue()); controls[i] = asq; } else if (controls[i].Type == "1.2.840.113556.1.4.841") { // The control is a DirSyncControl. object[] o = BerConverter.Decode("{iiO}", value); Debug.Assert(o != null && o.Length == 3); int moreData = (int)o[0]; int count = (int)o[1]; byte[] dirsyncCookie = (byte[])o[2]; DirSyncResponseControl dirsync = new DirSyncResponseControl(dirsyncCookie, (moreData == 0 ? false : true), count, controls[i].IsCritical, controls[i].GetValue()); controls[i] = dirsync; } else if (controls[i].Type == "1.2.840.113556.1.4.474") { // The control is a SortControl. int result = 0; string attribute = null; object[] o = BerConverter.TryDecode("{ea}", value, out bool decodeSucceeded); // decode might fail as AD for example never returns attribute name, we don't want to unnecessarily throw and catch exception if (decodeSucceeded) { Debug.Assert(o != null && o.Length == 2); result = (int)o[0]; attribute = (string)o[1]; } else { // decoding might fail as attribute is optional o = BerConverter.Decode("{e}", value); Debug.Assert(o != null && o.Length == 1); result = (int)o[0]; } SortResponseControl sort = new SortResponseControl((ResultCode)result, attribute, controls[i].IsCritical, controls[i].GetValue()); controls[i] = sort; } else if (controls[i].Type == "2.16.840.1.113730.3.4.10") { // The control is a VlvResponseControl. int position; int count; int result; byte[] context = null; object[] o = BerConverter.TryDecode("{iieO}", value, out bool decodeSucceeded); if (decodeSucceeded) { Debug.Assert(o != null && o.Length == 4); position = (int)o[0]; count = (int)o[1]; result = (int)o[2]; context = (byte[])o[3]; } else { o = BerConverter.Decode("{iie}", value); Debug.Assert(o != null && o.Length == 3); position = (int)o[0]; count = (int)o[1]; result = (int)o[2]; } VlvResponseControl vlv = new VlvResponseControl(position, count, context, (ResultCode)result, controls[i].IsCritical, controls[i].GetValue()); controls[i] = vlv; } } } } public class AsqRequestControl : DirectoryControl { public AsqRequestControl() : base("1.2.840.113556.1.4.1504", null, true, true) { } public AsqRequestControl(string attributeName) : this() { AttributeName = attributeName; } public string AttributeName { get; set; } public override byte[] GetValue() { _directoryControlValue = BerConverter.Encode("{s}", new object[] { AttributeName }); return base.GetValue(); } } public class AsqResponseControl : DirectoryControl { internal AsqResponseControl(int result, bool criticality, byte[] controlValue) : base("1.2.840.113556.1.4.1504", controlValue, criticality, true) { Result = (ResultCode)result; } public ResultCode Result { get; } } public class CrossDomainMoveControl : DirectoryControl { public CrossDomainMoveControl() : base("1.2.840.113556.1.4.521", null, true, true) { } public CrossDomainMoveControl(string targetDomainController) : this() { TargetDomainController = targetDomainController; } public string TargetDomainController { get; set; } public override byte[] GetValue() { if (TargetDomainController != null) { UTF8Encoding encoder = new UTF8Encoding(); byte[] bytes = encoder.GetBytes(TargetDomainController); // Allocate large enough space for the '\0' character. _directoryControlValue = new byte[bytes.Length + 2]; for (int i = 0; i < bytes.Length; i++) { _directoryControlValue[i] = bytes[i]; } } return base.GetValue(); } } public class DomainScopeControl : DirectoryControl { public DomainScopeControl() : base("1.2.840.113556.1.4.1339", null, true, true) { } } public class ExtendedDNControl : DirectoryControl { private ExtendedDNFlag _flag = ExtendedDNFlag.HexString; public ExtendedDNControl() : base("1.2.840.113556.1.4.529", null, true, true) { } public ExtendedDNControl(ExtendedDNFlag flag) : this() { Flag = flag; } public ExtendedDNFlag Flag { get => _flag; set { if (value < ExtendedDNFlag.HexString || value > ExtendedDNFlag.StandardString) throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(ExtendedDNFlag)); _flag = value; } } public override byte[] GetValue() { _directoryControlValue = BerConverter.Encode("{i}", new object[] { (int)Flag }); return base.GetValue(); } } public class LazyCommitControl : DirectoryControl { public LazyCommitControl() : base("1.2.840.113556.1.4.619", null, true, true) { } } public class DirectoryNotificationControl : DirectoryControl { public DirectoryNotificationControl() : base("1.2.840.113556.1.4.528", null, true, true) { } } public class PermissiveModifyControl : DirectoryControl { public PermissiveModifyControl() : base("1.2.840.113556.1.4.1413", null, true, true) { } } public class SecurityDescriptorFlagControl : DirectoryControl { public SecurityDescriptorFlagControl() : base("1.2.840.113556.1.4.801", null, true, true) { } public SecurityDescriptorFlagControl(SecurityMasks masks) : this() { SecurityMasks = masks; } // We don't do validation to the dirsync flag here as underneath API does not check for it and we don't want to put // unnecessary limitation on it. public SecurityMasks SecurityMasks { get; set; } public override byte[] GetValue() { _directoryControlValue = BerConverter.Encode("{i}", new object[] { (int)SecurityMasks }); return base.GetValue(); } } public class SearchOptionsControl : DirectoryControl { private SearchOption _searchOption = SearchOption.DomainScope; public SearchOptionsControl() : base("1.2.840.113556.1.4.1340", null, true, true) { } public SearchOptionsControl(SearchOption flags) : this() { SearchOption = flags; } public SearchOption SearchOption { get => _searchOption; set { if (value < SearchOption.DomainScope || value > SearchOption.PhantomRoot) throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(SearchOption)); _searchOption = value; } } public override byte[] GetValue() { _directoryControlValue = BerConverter.Encode("{i}", new object[] { (int)SearchOption }); return base.GetValue(); } } public class ShowDeletedControl : DirectoryControl { public ShowDeletedControl() : base("1.2.840.113556.1.4.417", null, true, true) { } } public class TreeDeleteControl : DirectoryControl { public TreeDeleteControl() : base("1.2.840.113556.1.4.805", null, true, true) { } } public class VerifyNameControl : DirectoryControl { private string _serverName; public VerifyNameControl() : base("1.2.840.113556.1.4.1338", null, true, true) { } public VerifyNameControl(string serverName) : this() { _serverName = serverName ?? throw new ArgumentNullException(nameof(serverName)); } public VerifyNameControl(string serverName, int flag) : this(serverName) { Flag = flag; } public string ServerName { get => _serverName; set => _serverName = value ?? throw new ArgumentNullException(nameof(value)); } public int Flag { get; set; } public override byte[] GetValue() { byte[] tmpValue = null; if (ServerName != null) { UnicodeEncoding unicode = new UnicodeEncoding(); tmpValue = unicode.GetBytes(ServerName); } _directoryControlValue = BerConverter.Encode("{io}", new object[] { Flag, tmpValue }); return base.GetValue(); } } public class DirSyncRequestControl : DirectoryControl { private byte[] _dirsyncCookie; private int _count = 1048576; public DirSyncRequestControl() : base("1.2.840.113556.1.4.841", null, true, true) { } public DirSyncRequestControl(byte[] cookie) : this() { _dirsyncCookie = cookie; } public DirSyncRequestControl(byte[] cookie, DirectorySynchronizationOptions option) : this(cookie) { Option = option; } public DirSyncRequestControl(byte[] cookie, DirectorySynchronizationOptions option, int attributeCount) : this(cookie, option) { AttributeCount = attributeCount; } public byte[] Cookie { get { if (_dirsyncCookie == null) { return Array.Empty<byte>(); } byte[] tempCookie = new byte[_dirsyncCookie.Length]; for (int i = 0; i < tempCookie.Length; i++) { tempCookie[i] = _dirsyncCookie[i]; } return tempCookie; } set => _dirsyncCookie = value; } // We don't do validation to the dirsync flag here as underneath API does not check for it and we don't want to put // unnecessary limitation on it. public DirectorySynchronizationOptions Option { get; set; } public int AttributeCount { get => _count; set { if (value < 0) { throw new ArgumentException(SR.ValidValue, nameof(value)); } _count = value; } } public override byte[] GetValue() { object[] o = new object[] { (int)Option, AttributeCount, _dirsyncCookie }; _directoryControlValue = BerConverter.Encode("{iio}", o); return base.GetValue(); } } public class DirSyncResponseControl : DirectoryControl { private byte[] _dirsyncCookie; internal DirSyncResponseControl(byte[] cookie, bool moreData, int resultSize, bool criticality, byte[] controlValue) : base("1.2.840.113556.1.4.841", controlValue, criticality, true) { _dirsyncCookie = cookie; MoreData = moreData; ResultSize = resultSize; } public byte[] Cookie { get { if (_dirsyncCookie == null) { return Array.Empty<byte>(); } byte[] tempCookie = new byte[_dirsyncCookie.Length]; for (int i = 0; i < tempCookie.Length; i++) { tempCookie[i] = _dirsyncCookie[i]; } return tempCookie; } } public bool MoreData { get; } public int ResultSize { get; } } public class PageResultRequestControl : DirectoryControl { private int _size = 512; private byte[] _pageCookie; public PageResultRequestControl() : base("1.2.840.113556.1.4.319", null, true, true) { } public PageResultRequestControl(int pageSize) : this() { PageSize = pageSize; } public PageResultRequestControl(byte[] cookie) : this() { _pageCookie = cookie; } public int PageSize { get => _size; set { if (value < 0) { throw new ArgumentException(SR.ValidValue, nameof(value)); } _size = value; } } public byte[] Cookie { get { if (_pageCookie == null) { return Array.Empty<byte>(); } byte[] tempCookie = new byte[_pageCookie.Length]; for (int i = 0; i < _pageCookie.Length; i++) { tempCookie[i] = _pageCookie[i]; } return tempCookie; } set => _pageCookie = value; } public override byte[] GetValue() { object[] o = new object[] { PageSize, _pageCookie }; _directoryControlValue = BerConverter.Encode("{io}", o); return base.GetValue(); } } public class PageResultResponseControl : DirectoryControl { private byte[] _pageCookie; internal PageResultResponseControl(int count, byte[] cookie, bool criticality, byte[] controlValue) : base("1.2.840.113556.1.4.319", controlValue, criticality, true) { TotalCount = count; _pageCookie = cookie; } public byte[] Cookie { get { if (_pageCookie == null) { return Array.Empty<byte>(); } byte[] tempCookie = new byte[_pageCookie.Length]; for (int i = 0; i < _pageCookie.Length; i++) { tempCookie[i] = _pageCookie[i]; } return tempCookie; } } public int TotalCount { get; } } public class SortRequestControl : DirectoryControl { private SortKey[] _keys = new SortKey[0]; public SortRequestControl(params SortKey[] sortKeys) : base("1.2.840.113556.1.4.473", null, true, true) { if (sortKeys == null) { throw new ArgumentNullException(nameof(sortKeys)); } for (int i = 0; i < sortKeys.Length; i++) { if (sortKeys[i] == null) { throw new ArgumentException(SR.NullValueArray, nameof(sortKeys)); } } _keys = new SortKey[sortKeys.Length]; for (int i = 0; i < sortKeys.Length; i++) { _keys[i] = new SortKey(sortKeys[i].AttributeName, sortKeys[i].MatchingRule, sortKeys[i].ReverseOrder); } } public SortRequestControl(string attributeName, bool reverseOrder) : this(attributeName, null, reverseOrder) { } public SortRequestControl(string attributeName, string matchingRule, bool reverseOrder) : base("1.2.840.113556.1.4.473", null, true, true) { SortKey key = new SortKey(attributeName, matchingRule, reverseOrder); _keys = new SortKey[] { key }; } public SortKey[] SortKeys { get { if (_keys == null) { return Array.Empty<SortKey>(); } SortKey[] tempKeys = new SortKey[_keys.Length]; for (int i = 0; i < _keys.Length; i++) { tempKeys[i] = new SortKey(_keys[i].AttributeName, _keys[i].MatchingRule, _keys[i].ReverseOrder); } return tempKeys; } set { if (value == null) { throw new ArgumentNullException(nameof(value)); } for (int i = 0; i < value.Length; i++) { if (value[i] == null) { throw new ArgumentException(SR.NullValueArray, nameof(value)); } } _keys = new SortKey[value.Length]; for (int i = 0; i < value.Length; i++) { _keys[i] = new SortKey(value[i].AttributeName, value[i].MatchingRule, value[i].ReverseOrder); } } } public override byte[] GetValue() { IntPtr control = (IntPtr)0; int structSize = Marshal.SizeOf(typeof(SortKey)); int keyCount = _keys.Length; IntPtr memHandle = Utility.AllocHGlobalIntPtrArray(keyCount + 1); try { IntPtr tempPtr = (IntPtr)0; IntPtr sortPtr = (IntPtr)0; int i = 0; for (i = 0; i < keyCount; i++) { sortPtr = Marshal.AllocHGlobal(structSize); Marshal.StructureToPtr(_keys[i], sortPtr, false); tempPtr = (IntPtr)((long)memHandle + IntPtr.Size * i); Marshal.WriteIntPtr(tempPtr, sortPtr); } tempPtr = (IntPtr)((long)memHandle + IntPtr.Size * i); Marshal.WriteIntPtr(tempPtr, (IntPtr)0); bool critical = IsCritical; int error = Wldap32.ldap_create_sort_control(UtilityHandle.GetHandle(), memHandle, critical ? (byte)1 : (byte)0, ref control); if (error != 0) { if (Utility.IsLdapError((LdapError)error)) { string errorMessage = LdapErrorMappings.MapResultCode(error); throw new LdapException(error, errorMessage); } else { throw new LdapException(error); } } LdapControl managedControl = new LdapControl(); Marshal.PtrToStructure(control, managedControl); berval value = managedControl.ldctl_value; // reinitialize the value _directoryControlValue = null; if (value != null) { _directoryControlValue = new byte[value.bv_len]; Marshal.Copy(value.bv_val, _directoryControlValue, 0, value.bv_len); } } finally { if (control != (IntPtr)0) { Wldap32.ldap_control_free(control); } if (memHandle != (IntPtr)0) { //release the memory from the heap for (int i = 0; i < keyCount; i++) { IntPtr tempPtr = Marshal.ReadIntPtr(memHandle, IntPtr.Size * i); if (tempPtr != (IntPtr)0) { // free the marshalled name IntPtr ptr = Marshal.ReadIntPtr(tempPtr); if (ptr != (IntPtr)0) { Marshal.FreeHGlobal(ptr); } // free the marshalled rule ptr = Marshal.ReadIntPtr(tempPtr, IntPtr.Size); if (ptr != (IntPtr)0) { Marshal.FreeHGlobal(ptr); } Marshal.FreeHGlobal(tempPtr); } } Marshal.FreeHGlobal(memHandle); } } return base.GetValue(); } } public class SortResponseControl : DirectoryControl { internal SortResponseControl(ResultCode result, string attributeName, bool critical, byte[] value) : base("1.2.840.113556.1.4.474", value, critical, true) { Result = result; AttributeName = attributeName; } public ResultCode Result { get; } public string AttributeName { get; } } public class VlvRequestControl : DirectoryControl { private int _before = 0; private int _after = 0; private int _offset = 0; private int _estimateCount = 0; private byte[] _target; private byte[] _context; public VlvRequestControl() : base("2.16.840.1.113730.3.4.9", null, true, true) { } public VlvRequestControl(int beforeCount, int afterCount, int offset) : this() { BeforeCount = beforeCount; AfterCount = afterCount; Offset = offset; } public VlvRequestControl(int beforeCount, int afterCount, string target) : this() { BeforeCount = beforeCount; AfterCount = afterCount; if (target != null) { UTF8Encoding encoder = new UTF8Encoding(); _target = encoder.GetBytes(target); } } public VlvRequestControl(int beforeCount, int afterCount, byte[] target) : this() { BeforeCount = beforeCount; AfterCount = afterCount; Target = target; } public int BeforeCount { get => _before; set { if (value < 0) { throw new ArgumentException(SR.ValidValue, nameof(value)); } _before = value; } } public int AfterCount { get => _after; set { if (value < 0) { throw new ArgumentException(SR.ValidValue, nameof(value)); } _after = value; } } public int Offset { get => _offset; set { if (value < 0) { throw new ArgumentException(SR.ValidValue, nameof(value)); } _offset = value; } } public int EstimateCount { get => _estimateCount; set { if (value < 0) { throw new ArgumentException(SR.ValidValue, nameof(value)); } _estimateCount = value; } } public byte[] Target { get { if (_target == null) { return Array.Empty<byte>(); } byte[] tempContext = new byte[_target.Length]; for (int i = 0; i < tempContext.Length; i++) { tempContext[i] = _target[i]; } return tempContext; } set => _target = value; } public byte[] ContextId { get { if (_context == null) { return Array.Empty<byte>(); } byte[] tempContext = new byte[_context.Length]; for (int i = 0; i < tempContext.Length; i++) { tempContext[i] = _context[i]; } return tempContext; } set => _context = value; } public override byte[] GetValue() { var seq = new StringBuilder(10); var objList = new ArrayList(); // first encode the before and the after count. seq.Append("{ii"); objList.Add(BeforeCount); objList.Add(AfterCount); // encode Target if it is not null if (Target.Length != 0) { seq.Append("t"); objList.Add(0x80 | 0x1); seq.Append("o"); objList.Add(Target); } else { seq.Append("t{"); objList.Add(0xa0); seq.Append("ii"); objList.Add(Offset); objList.Add(EstimateCount); seq.Append("}"); } // encode the contextID if present if (ContextId.Length != 0) { seq.Append("o"); objList.Add(ContextId); } seq.Append("}"); object[] values = new object[objList.Count]; for (int i = 0; i < objList.Count; i++) { values[i] = objList[i]; } _directoryControlValue = BerConverter.Encode(seq.ToString(), values); return base.GetValue(); } } public class VlvResponseControl : DirectoryControl { private byte[] _context; internal VlvResponseControl(int targetPosition, int count, byte[] context, ResultCode result, bool criticality, byte[] value) : base("2.16.840.1.113730.3.4.10", value, criticality, true) { TargetPosition = targetPosition; ContentCount = count; _context = context; Result = result; } public int TargetPosition { get; } public int ContentCount { get; } public byte[] ContextId { get { if (_context == null) { return Array.Empty<byte>(); } byte[] tempContext = new byte[_context.Length]; for (int i = 0; i < tempContext.Length; i++) { tempContext[i] = _context[i]; } return tempContext; } } public ResultCode Result { get; } } public class QuotaControl : DirectoryControl { private byte[] _sid; public QuotaControl() : base("1.2.840.113556.1.4.1852", null, true, true) { } public QuotaControl(SecurityIdentifier querySid) : this() { QuerySid = querySid; } public SecurityIdentifier QuerySid { get => _sid == null ? null : new SecurityIdentifier(_sid, 0); set { if (value == null) { _sid = null; } else { _sid = new byte[value.BinaryLength]; value.GetBinaryForm(_sid, 0); } } } public override byte[] GetValue() { _directoryControlValue = BerConverter.Encode("{o}", new object[] { _sid }); return base.GetValue(); } } public class DirectoryControlCollection : CollectionBase { public DirectoryControlCollection() { } public DirectoryControl this[int index] { get => (DirectoryControl)List[index]; set => List[index] = value ?? throw new ArgumentNullException(nameof(value)); } public int Add(DirectoryControl control) { if (control == null) { throw new ArgumentNullException(nameof(control)); } return List.Add(control); } public void AddRange(DirectoryControl[] controls) { if (controls == null) { throw new ArgumentNullException(nameof(controls)); } foreach (DirectoryControl control in controls) { if (control == null) { throw new ArgumentException(SR.ContainNullControl, nameof(controls)); } } InnerList.AddRange(controls); } public void AddRange(DirectoryControlCollection controlCollection) { if (controlCollection == null) { throw new ArgumentNullException(nameof(controlCollection)); } int currentCount = controlCollection.Count; for (int i = 0; i < currentCount; i = ((i) + (1))) { Add(controlCollection[i]); } } public bool Contains(DirectoryControl value) => List.Contains(value); public void CopyTo(DirectoryControl[] array, int index) => List.CopyTo(array, index); public int IndexOf(DirectoryControl value) => List.IndexOf(value); public void Insert(int index, DirectoryControl value) { if (value == null) { throw new ArgumentNullException(nameof(value)); } List.Insert(index, value); } public void Remove(DirectoryControl value) => List.Remove(value); protected override void OnValidate(object value) { if (value == null) { throw new ArgumentNullException(nameof(value)); } if (!(value is DirectoryControl)) { throw new ArgumentException(SR.Format(SR.InvalidValueType, nameof(DirectoryControl)), nameof(value)); } } } }
#define LOG_MEMORY_PERF_COUNTERS using System; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Orleans.Runtime; namespace Orleans.Statistics { internal class LinuxEnvironmentStatistics : IHostEnvironmentStatistics, ILifecycleParticipant<ISiloLifecycle>, ILifecycleParticipant<IClusterClientLifecycle>, ILifecycleObserver, IDisposable { private readonly ILogger _logger; private const float KB = 1024f; /// <inheritdoc /> public long? TotalPhysicalMemory { get; private set; } /// <inheritdoc /> public float? CpuUsage { get; private set; } /// <inheritdoc /> public long? AvailableMemory { get; private set; } /// <inheritdoc /> private long MemoryUsage => GC.GetTotalMemory(false); private readonly TimeSpan MONITOR_PERIOD = TimeSpan.FromSeconds(5); private CancellationTokenSource _cts; private Task _monitorTask; private const string MEMINFO_FILEPATH = "/proc/meminfo"; private const string CPUSTAT_FILEPATH = "/proc/stat"; internal static readonly string[] RequiredFiles = new[] { MEMINFO_FILEPATH, CPUSTAT_FILEPATH }; public LinuxEnvironmentStatistics(ILoggerFactory loggerFactory) { _logger = loggerFactory.CreateLogger<LinuxEnvironmentStatistics>(); } public void Dispose() { _cts?.Dispose(); _monitorTask?.Dispose(); } public void Participate(ISiloLifecycle lifecycle) { lifecycle.Subscribe(ServiceLifecycleStage.RuntimeInitialize, this); } public void Participate(IClusterClientLifecycle lifecycle) { lifecycle.Subscribe(ServiceLifecycleStage.RuntimeInitialize, this); } public async Task OnStart(CancellationToken ct) { _logger.LogTrace($"Starting {nameof(LinuxEnvironmentStatistics)}"); _cts = new CancellationTokenSource(); ct.Register(() => _cts.Cancel()); _monitorTask = await Task.Factory.StartNew( () => Monitor(_cts.Token), _cts.Token, TaskCreationOptions.DenyChildAttach | TaskCreationOptions.RunContinuationsAsynchronously, TaskScheduler.Default ); _logger.LogTrace($"Started {nameof(LinuxEnvironmentStatistics)}"); } public async Task OnStop(CancellationToken ct) { if (_cts == null) return; _logger.LogTrace($"Stopping {nameof(LinuxEnvironmentStatistics)}"); try { _cts.Cancel(); try { await _monitorTask; } catch (TaskCanceledException) { } } catch (Exception ex) { _logger.LogError(ex, $"Error stopping {nameof(LinuxEnvironmentStatistics)}"); } finally { _logger.LogTrace($"Stopped {nameof(LinuxEnvironmentStatistics)}"); } } private async Task UpdateTotalPhysicalMemory() { var memTotalLine = await ReadLineStartingWithAsync(MEMINFO_FILEPATH, "MemTotal"); if (string.IsNullOrWhiteSpace(memTotalLine)) { _logger.LogWarning($"Couldn't read 'MemTotal' line from '{MEMINFO_FILEPATH}'"); return; } // Format: "MemTotal: 16426476 kB" if (!long.TryParse(new string(memTotalLine.Where(char.IsDigit).ToArray()), out var totalMemInKb)) { _logger.LogWarning($"Couldn't parse meminfo output"); return; } TotalPhysicalMemory = totalMemInKb * 1_000; } private long _prevIdleTime; private long _prevTotalTime; private async Task UpdateCpuUsage(int i) { var cpuUsageLine = await ReadLineStartingWithAsync(CPUSTAT_FILEPATH, "cpu "); if (string.IsNullOrWhiteSpace(cpuUsageLine)) { _logger.LogWarning($"Couldn't read line from '{CPUSTAT_FILEPATH}'"); return; } // Format: "cpu 20546715 4367 11631326 215282964 96602 0 584080 0 0 0" var cpuNumberStrings = cpuUsageLine.Split(' ').Skip(2); if (cpuNumberStrings.Any(n => !long.TryParse(n, out _))) { _logger.LogWarning($"Failed to parse '{CPUSTAT_FILEPATH}' output correctly. Line: {cpuUsageLine}"); return; } var cpuNumbers = cpuNumberStrings.Select(long.Parse).ToArray(); var idleTime = cpuNumbers[3]; var iowait = cpuNumbers[4]; // Iowait is not real cpu time var totalTime = cpuNumbers.Sum() - iowait; if (i > 0) { var deltaIdleTime = idleTime - _prevIdleTime; var deltaTotalTime = totalTime - _prevTotalTime; var currentCpuUsage = (1.0f - deltaIdleTime / ((float)deltaTotalTime)) * 100f; var previousCpuUsage = CpuUsage ?? 0f; CpuUsage = (previousCpuUsage + 2 * currentCpuUsage) / 3; } _prevIdleTime = idleTime; _prevTotalTime = totalTime; } private async Task UpdateAvailableMemory() { var memAvailableLine = await ReadLineStartingWithAsync(MEMINFO_FILEPATH, "MemAvailable"); if (string.IsNullOrWhiteSpace(memAvailableLine)) { memAvailableLine = await ReadLineStartingWithAsync(MEMINFO_FILEPATH, "MemFree"); if (string.IsNullOrWhiteSpace(memAvailableLine)) { _logger.LogWarning($"Couldn't read 'MemAvailable' or 'MemFree' line from '{MEMINFO_FILEPATH}'"); return; } } if (!long.TryParse(new string(memAvailableLine.Where(char.IsDigit).ToArray()), out var availableMemInKb)) { _logger.LogWarning($"Couldn't parse meminfo output: '{memAvailableLine}'"); return; } AvailableMemory = availableMemInKb * 1_000; } private void WriteToStatistics() { FloatValueStatistic.FindOrCreate(StatisticNames.RUNTIME_CPUUSAGE, () => CpuUsage.Value); IntValueStatistic.FindOrCreate(StatisticNames.RUNTIME_GC_TOTALMEMORYKB, () => (long)((MemoryUsage + KB - 1.0) / KB)); // Round up #if LOG_MEMORY_PERF_COUNTERS IntValueStatistic.FindOrCreate(StatisticNames.RUNTIME_MEMORY_TOTALPHYSICALMEMORYMB, () => (long)((TotalPhysicalMemory / KB) / KB)); IntValueStatistic.FindOrCreate(StatisticNames.RUNTIME_MEMORY_AVAILABLEMEMORYMB, () => (long)((AvailableMemory / KB) / KB)); // Round up #endif IntValueStatistic.FindOrCreate(StatisticNames.RUNTIME_DOT_NET_THREADPOOL_INUSE_WORKERTHREADS, () => { ThreadPool.GetMaxThreads(out var maXworkerThreads, out var maXcompletionPortThreads); // GetAvailableThreads Retrieves the difference between the maximum number of thread pool threads // and the number currently active. // So max-Available is the actual number in use. If it goes beyond min, it means we are stressing the thread pool. ThreadPool.GetAvailableThreads(out var workerThreads, out var completionPortThreads); return maXworkerThreads - workerThreads; }); IntValueStatistic.FindOrCreate(StatisticNames.RUNTIME_DOT_NET_THREADPOOL_INUSE_COMPLETIONPORTTHREADS, () => { ThreadPool.GetMaxThreads(out var maxWorkerThreads, out var maxCompletionPortThreads); ThreadPool.GetAvailableThreads(out var workerThreads, out var completionPortThreads); return maxCompletionPortThreads - completionPortThreads; }); } private async Task Monitor(CancellationToken ct) { int i = 0; while (true) { if (ct.IsCancellationRequested) throw new TaskCanceledException("Monitor task canceled"); try { await Task.WhenAll( i == 0 ? UpdateTotalPhysicalMemory() : Task.CompletedTask, UpdateCpuUsage(i), UpdateAvailableMemory() ); if (i == 1) WriteToStatistics(); var logStr = $"LinuxEnvironmentStatistics: CpuUsage={CpuUsage?.ToString("0.0")}, TotalPhysicalMemory={TotalPhysicalMemory}, AvailableMemory={AvailableMemory}"; _logger.LogTrace(logStr); await Task.Delay(MONITOR_PERIOD, ct); } catch (Exception ex) when (ex.GetType() != typeof(TaskCanceledException)) { _logger.LogError(ex, "LinuxEnvironmentStatistics: error"); await Task.Delay(MONITOR_PERIOD + MONITOR_PERIOD + MONITOR_PERIOD, ct); } if (i < 2) i++; } } private static async Task<string> ReadLineStartingWithAsync(string path, string lineStartsWith) { using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 512, FileOptions.SequentialScan | FileOptions.Asynchronous)) using (var r = new StreamReader(fs, Encoding.ASCII)) { string line; while ((line = await r.ReadLineAsync()) != null) { if (line.StartsWith(lineStartsWith)) return line; } } return null; } } }
//------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------ namespace System.ServiceModel.Dispatcher { using System.Collections.Generic; using System.Runtime; using System.Text; using System.Xml.XPath; using System.Xml.Xsl; internal class FunctionCallOpcode : Opcode { QueryFunction function; internal FunctionCallOpcode(QueryFunction function) : base(OpcodeID.Function) { Fx.Assert(null != function, ""); this.function = function; } internal override bool Equals(Opcode op) { if (base.Equals(op)) { FunctionCallOpcode functionCall = (FunctionCallOpcode)op; return functionCall.function.Equals(this.function); } return false; } internal override Opcode Eval(ProcessingContext context) { this.function.Eval(context); return this.next; } #if DEBUG_FILTER public override string ToString() { return string.Format("{0} {1}", base.ToString(), this.function.ToString()); } #endif } internal class XsltFunctionCallOpcode : Opcode { static object[] NullArgs = new object[0]; int argCount; XsltContext xsltContext; IXsltContextFunction function; List<NodeSequenceIterator> iterList; // REFACTOR, [....], make this a function on QueryValueModel internal XsltFunctionCallOpcode(XsltContext context, IXsltContextFunction function, int argCount) : base(OpcodeID.XsltFunction) { Fx.Assert(null != context && null != function, ""); this.xsltContext = context; this.function = function; this.argCount = argCount; for (int i = 0; i < function.Maxargs; ++i) { if (function.ArgTypes[i] == XPathResultType.NodeSet) { this.iterList = new List<NodeSequenceIterator>(); break; } } // Make sure the return type is valid switch (this.function.ReturnType) { case XPathResultType.String: case XPathResultType.Number: case XPathResultType.Boolean: case XPathResultType.NodeSet: break; default: throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new QueryCompileException(QueryCompileError.InvalidType, SR.GetString(SR.QueryFunctionTypeNotSupported, this.function.ReturnType.ToString()))); } } internal override bool Equals(Opcode op) { // We have no way of knowing if an Xslt function is stateless and can be merged return false; } internal override Opcode Eval(ProcessingContext context) { XPathNavigator nav = context.Processor.ContextNode; if (nav != null && context.Processor.ContextMessage != null) { ((SeekableMessageNavigator)nav).Atomize(); } if (this.argCount == 0) { context.PushFrame(); int count = context.IterationCount; if (count > 0) { object ret = this.function.Invoke(this.xsltContext, NullArgs, nav); switch (this.function.ReturnType) { case XPathResultType.String: context.Push((string)ret, count); break; case XPathResultType.Number: context.Push((double)ret, count); break; case XPathResultType.Boolean: context.Push((bool)ret, count); break; case XPathResultType.NodeSet: NodeSequence seq = context.CreateSequence(); XPathNodeIterator iter = (XPathNodeIterator)ret; seq.Add(iter); context.Push(seq, count); break; default: // This should never be reached throw DiagnosticUtility.ExceptionUtility.ThrowHelperCritical(new QueryProcessingException(QueryProcessingError.Unexpected, SR.GetString(SR.QueryFunctionTypeNotSupported, this.function.ReturnType.ToString()))); } } } else { // PERF, [....], see if we can cache these arrays to avoid allocations object[] xsltArgs = new object[this.argCount]; int iterationCount = context.TopArg.Count; for (int iteration = 0; iteration < iterationCount; ++iteration) { for (int i = 0; i < this.argCount; ++i) { StackFrame arg = context[i]; Fx.Assert(iteration < arg.Count, ""); switch (this.function.ArgTypes[i]) { case XPathResultType.String: xsltArgs[i] = context.PeekString(arg[iteration]); break; case XPathResultType.Number: xsltArgs[i] = context.PeekDouble(arg[iteration]); break; case XPathResultType.Boolean: xsltArgs[i] = context.PeekBoolean(arg[iteration]); break; case XPathResultType.NodeSet: NodeSequenceIterator iter = new NodeSequenceIterator(context.PeekSequence(arg[iteration])); xsltArgs[i] = iter; this.iterList.Add(iter); break; default: // This should never be reached throw DiagnosticUtility.ExceptionUtility.ThrowHelperCritical(new QueryProcessingException(QueryProcessingError.Unexpected, SR.GetString(SR.QueryFunctionTypeNotSupported, this.function.ArgTypes[i].ToString()))); } } object ret = this.function.Invoke(this.xsltContext, xsltArgs, nav); if (this.iterList != null) { for (int i = 0; i < this.iterList.Count; ++i) { this.iterList[i].Clear(); } this.iterList.Clear(); } switch (this.function.ReturnType) { case XPathResultType.String: context.SetValue(context, context[this.argCount - 1][iteration], (string)ret); break; case XPathResultType.Number: context.SetValue(context, context[this.argCount - 1][iteration], (double)ret); break; case XPathResultType.Boolean: context.SetValue(context, context[this.argCount - 1][iteration], (bool)ret); break; case XPathResultType.NodeSet: NodeSequence seq = context.CreateSequence(); XPathNodeIterator iter = (XPathNodeIterator)ret; seq.Add(iter); context.SetValue(context, context[this.argCount - 1][iteration], seq); break; default: // This should never be reached throw DiagnosticUtility.ExceptionUtility.ThrowHelperCritical(new QueryProcessingException(QueryProcessingError.Unexpected, SR.GetString(SR.QueryFunctionTypeNotSupported, this.function.ReturnType.ToString()))); } } for (int i = 0; i < this.argCount - 1; ++i) { context.PopFrame(); } } return this.next; } #if DEBUG_FILTER public override string ToString() { return string.Format("{0} IXsltContextFunction", base.ToString()); } #endif } internal enum QueryFunctionFlag { None = 0x00000000, UsesContextNode = 0x00000001 } internal abstract class QueryFunction { static ValueDataType[] emptyParams = new ValueDataType[0]; QueryFunctionFlag flags; protected string name; ValueDataType[] paramTypes; ValueDataType returnType; internal QueryFunction(string name, ValueDataType returnType) : this(name, returnType, QueryFunction.emptyParams, QueryFunctionFlag.None) { } internal QueryFunction(string name, ValueDataType returnType, QueryFunctionFlag flags) : this(name, returnType, QueryFunction.emptyParams, flags) { } internal QueryFunction(string name, ValueDataType returnType, ValueDataType[] paramTypes) : this(name, returnType, paramTypes, QueryFunctionFlag.None) { } internal QueryFunction(string name, ValueDataType returnType, ValueDataType[] paramTypes, QueryFunctionFlag flags) { Fx.Assert(null != paramTypes, ""); Fx.Assert(null != name, ""); this.name = name; this.returnType = returnType; this.paramTypes = paramTypes; this.flags = flags; } internal ValueDataType[] ParamTypes { get { return this.paramTypes; } } internal ValueDataType ReturnType { get { return this.returnType; } } internal bool Bind(string name, XPathExprList args) { Fx.Assert(null != name && null != args, ""); if ( 0 != string.CompareOrdinal(this.name, name) || this.paramTypes.Length != args.Count ) { return false; } return (this.paramTypes.Length == args.Count); } internal abstract bool Equals(QueryFunction function); internal abstract void Eval(ProcessingContext context); internal bool TestFlag(QueryFunctionFlag flag) { return (0 != (this.flags & flag)); } #if DEBUG_FILTER public override string ToString() { StringBuilder text = new StringBuilder(); text.Append(this.name); text.Append('('); for (int i = 0; i < this.paramTypes.Length; ++i) { if (i > 0) { text.Append(','); } text.Append(this.paramTypes[i].ToString()); } text.Append(')'); return text.ToString(); } #endif } internal interface IFunctionLibrary { QueryFunction Bind(string functionName, string functionNamespace, XPathExprList args); } internal enum XPathFunctionID { // Set IterateSequences, Count, Position, Last, LocalName, LocalNameDefault, Name, NameDefault, NamespaceUri, NamespaceUriDefault, // Boolean Boolean, Not, True, False, Lang, // Number Number, NumberDefault, Ceiling, Floor, Round, Sum, // String String, StringDefault, StartsWith, ConcatTwo, ConcatThree, ConcatFour, Contains, NormalizeSpace, NormalizeSpaceDefault, StringLength, StringLengthDefault, SubstringBefore, SubstringAfter, Substring, SubstringLimit, Translate } internal class XPathFunctionLibrary : IFunctionLibrary { static XPathFunction[] functionTable; static XPathFunctionLibrary() { XPathFunctionLibrary.functionTable = new XPathFunction[] { new XPathFunction(XPathFunctionID.Boolean, "boolean", ValueDataType.Boolean, new ValueDataType[] { ValueDataType.None }), new XPathFunction(XPathFunctionID.False, "false", ValueDataType.Boolean), new XPathFunction(XPathFunctionID.True, "true", ValueDataType.Boolean), new XPathFunction(XPathFunctionID.Not, "not", ValueDataType.Boolean, new ValueDataType[] { ValueDataType.Boolean }), new XPathFunction(XPathFunctionID.Lang, "lang", ValueDataType.Boolean, new ValueDataType[] { ValueDataType.String }), new XPathFunction(XPathFunctionID.Number, "number", ValueDataType.Double, new ValueDataType[] { ValueDataType.None }), new XPathFunction(XPathFunctionID.NumberDefault, "number", ValueDataType.Double), new XPathFunction(XPathFunctionID.Sum, "sum", ValueDataType.Double, new ValueDataType[] { ValueDataType.Sequence }), new XPathFunction(XPathFunctionID.Floor, "floor", ValueDataType.Double, new ValueDataType[] { ValueDataType.Double }), new XPathFunction(XPathFunctionID.Ceiling, "ceiling", ValueDataType.Double, new ValueDataType[] { ValueDataType.Double }), new XPathFunction(XPathFunctionID.Round, "round", ValueDataType.Double, new ValueDataType[] { ValueDataType.Double }), new XPathFunction(XPathFunctionID.String, "string", ValueDataType.String, new ValueDataType[] { ValueDataType.None }), new XPathFunction(XPathFunctionID.StringDefault, "string", ValueDataType.String, QueryFunctionFlag.UsesContextNode), new XPathFunction(XPathFunctionID.ConcatTwo, "concat", ValueDataType.String, new ValueDataType[] { ValueDataType.String, ValueDataType.String }), new XPathFunction(XPathFunctionID.ConcatThree, "concat", ValueDataType.String, new ValueDataType[] { ValueDataType.String, ValueDataType.String, ValueDataType.String }), new XPathFunction(XPathFunctionID.ConcatFour, "concat", ValueDataType.String, new ValueDataType[] { ValueDataType.String, ValueDataType.String, ValueDataType.String, ValueDataType.String }), new XPathFunction(XPathFunctionID.StartsWith, "starts-with", ValueDataType.Boolean, new ValueDataType[] { ValueDataType.String, ValueDataType.String }), new XPathFunction(XPathFunctionID.NormalizeSpace, "normalize-space", ValueDataType.String, new ValueDataType[] { ValueDataType.String }), new XPathFunction(XPathFunctionID.NormalizeSpaceDefault, "normalize-space", ValueDataType.String, QueryFunctionFlag.UsesContextNode), new XPathFunction(XPathFunctionID.Contains, "contains", ValueDataType.Boolean, new ValueDataType[] { ValueDataType.String, ValueDataType.String }), new XPathFunction(XPathFunctionID.SubstringBefore, "substring-before", ValueDataType.String, new ValueDataType[] { ValueDataType.String, ValueDataType.String }), new XPathFunction(XPathFunctionID.SubstringAfter, "substring-after", ValueDataType.String, new ValueDataType[] { ValueDataType.String, ValueDataType.String }), new XPathFunction(XPathFunctionID.Substring, "substring", ValueDataType.String, new ValueDataType[] { ValueDataType.String, ValueDataType.Double }), new XPathFunction(XPathFunctionID.SubstringLimit, "substring", ValueDataType.String, new ValueDataType[] { ValueDataType.String, ValueDataType.Double, ValueDataType.Double }), new XPathFunction(XPathFunctionID.StringLength, "string-length", ValueDataType.Double, new ValueDataType[] { ValueDataType.String }), new XPathFunction(XPathFunctionID.StringLengthDefault, "string-length", ValueDataType.Double, QueryFunctionFlag.UsesContextNode), new XPathFunction(XPathFunctionID.Translate, "translate", ValueDataType.String, new ValueDataType[] { ValueDataType.String, ValueDataType.String, ValueDataType.String }), new XPathFunction(XPathFunctionID.Last, "last", ValueDataType.Double, QueryFunctionFlag.UsesContextNode), new XPathFunction(XPathFunctionID.Position, "position", ValueDataType.Double, QueryFunctionFlag.UsesContextNode), new XPathFunction(XPathFunctionID.Count, "count", ValueDataType.Double, new ValueDataType[] { ValueDataType.Sequence }), new XPathFunction(XPathFunctionID.LocalName, "local-name", ValueDataType.String, new ValueDataType[] { ValueDataType.Sequence }), new XPathFunction(XPathFunctionID.LocalNameDefault, "local-name", ValueDataType.String, QueryFunctionFlag.UsesContextNode), new XPathFunction(XPathFunctionID.Name, "name", ValueDataType.String, new ValueDataType[] { ValueDataType.Sequence }), new XPathFunction(XPathFunctionID.NameDefault, "name", ValueDataType.String, QueryFunctionFlag.UsesContextNode), new XPathFunction(XPathFunctionID.NamespaceUri, "namespace-uri", ValueDataType.String, new ValueDataType[] { ValueDataType.Sequence }), new XPathFunction(XPathFunctionID.NamespaceUriDefault, "namespace-uri", ValueDataType.String, QueryFunctionFlag.UsesContextNode) }; } internal XPathFunctionLibrary() { } public QueryFunction Bind(string functionName, string functionNamespace, XPathExprList args) { Fx.Assert(null != functionName && null != args, ""); // Variable length argument list requires a special case here if (functionName == "concat" && args.Count > 4) { ConcatFunction f = new ConcatFunction(args.Count); if (f.Bind(functionName, args)) { return f; } } else { for (int i = 0; i < XPathFunctionLibrary.functionTable.Length; ++i) { // XPath functions are typeless, so don't check types if (XPathFunctionLibrary.functionTable[i].Bind(functionName, args)) { return XPathFunctionLibrary.functionTable[i]; } } } return null; } } internal class ConcatFunction : QueryFunction { int argCount; internal ConcatFunction(int argCount) : base("concat", ValueDataType.String, ConcatFunction.MakeTypes(argCount)) { Fx.Assert(argCount >= 2, ""); this.argCount = argCount; } internal override bool Equals(QueryFunction function) { ConcatFunction f = function as ConcatFunction; if (f != null && this.argCount == f.argCount) { return true; } return false; } internal override void Eval(ProcessingContext context) { Fx.Assert(context != null, ""); StackFrame[] args = new StackFrame[argCount]; for (int i = 0; i < this.argCount; ++i) { args[i] = context[i]; } StringBuilder builder = new StringBuilder(); while (args[0].basePtr <= args[0].endPtr) { builder.Length = 0; for (int i = 0; i < this.argCount; ++i) { builder.Append(context.PeekString(args[i].basePtr)); } context.SetValue(context, args[this.argCount - 1].basePtr, builder.ToString()); for (int i = 0; i < this.argCount; ++i) { args[i].basePtr++; } } for (int i = 0; i < this.argCount - 1; ++i) { context.PopFrame(); } } internal static ValueDataType[] MakeTypes(int size) { ValueDataType[] t = new ValueDataType[size]; for (int i = 0; i < size; ++i) { t[i] = ValueDataType.String; } return t; } } internal class XPathFunction : QueryFunction { XPathFunctionID functionID; internal XPathFunction(XPathFunctionID functionID, string name, ValueDataType returnType) : base(name, returnType) { this.functionID = functionID; } internal XPathFunction(XPathFunctionID functionID, string name, ValueDataType returnType, QueryFunctionFlag flags) : base(name, returnType, flags) { this.functionID = functionID; } internal XPathFunction(XPathFunctionID functionID, string name, ValueDataType returnType, ValueDataType[] argTypes) : base(name, returnType, argTypes) { this.functionID = functionID; } internal XPathFunctionID ID { get { return this.functionID; } } internal override bool Equals(QueryFunction function) { XPathFunction xpathFunction = function as XPathFunction; if (null == xpathFunction) { return false; } return (xpathFunction.ID == this.ID); } static void ConvertFirstArg(ProcessingContext context, ValueDataType type) { StackFrame arg = context.TopArg; Value[] values = context.Values; while (arg.basePtr <= arg.endPtr) { values[arg.basePtr++].ConvertTo(context, type); } } internal override void Eval(ProcessingContext context) { Fx.Assert(null != context, ""); switch (this.functionID) { default: throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotImplementedException(SR.GetString(SR.QueryNotImplemented, this.name))); case XPathFunctionID.IterateSequences: XPathFunction.IterateAndPushSequences(context); break; case XPathFunctionID.Count: XPathFunction.NodesetCount(context); break; case XPathFunctionID.Position: XPathFunction.NodesetPosition(context); break; case XPathFunctionID.Last: XPathFunction.NodesetLast(context); break; case XPathFunctionID.LocalName: XPathFunction.NodesetLocalName(context); break; case XPathFunctionID.LocalNameDefault: XPathFunction.NodesetLocalNameDefault(context); break; case XPathFunctionID.Name: XPathFunction.NodesetName(context); break; case XPathFunctionID.NameDefault: XPathFunction.NodesetNameDefault(context); break; case XPathFunctionID.NamespaceUri: XPathFunction.NodesetNamespaceUri(context); break; case XPathFunctionID.NamespaceUriDefault: XPathFunction.NodesetNamespaceUriDefault(context); break; case XPathFunctionID.Boolean: XPathFunction.BooleanBoolean(context); break; case XPathFunctionID.False: XPathFunction.BooleanFalse(context); break; case XPathFunctionID.True: XPathFunction.BooleanTrue(context); break; case XPathFunctionID.Not: XPathFunction.BooleanNot(context); break; case XPathFunctionID.Lang: XPathFunction.BooleanLang(context); break; case XPathFunctionID.Contains: XPathFunction.StringContains(context); break; case XPathFunctionID.Number: XPathFunction.NumberNumber(context); break; case XPathFunctionID.NumberDefault: XPathFunction.NumberNumberDefault(context); break; case XPathFunctionID.Ceiling: XPathFunction.NumberCeiling(context); break; case XPathFunctionID.Floor: XPathFunction.NumberFloor(context); break; case XPathFunctionID.Round: XPathFunction.NumberRound(context); break; case XPathFunctionID.Sum: XPathFunction.NumberSum(context); break; case XPathFunctionID.String: XPathFunction.StringString(context); break; case XPathFunctionID.StringDefault: XPathFunction.StringStringDefault(context); break; case XPathFunctionID.ConcatTwo: XPathFunction.StringConcatTwo(context); break; case XPathFunctionID.ConcatThree: XPathFunction.StringConcatThree(context); break; case XPathFunctionID.ConcatFour: XPathFunction.StringConcatFour(context); break; case XPathFunctionID.StartsWith: XPathFunction.StringStartsWith(context); break; case XPathFunctionID.StringLength: XPathFunction.StringLength(context); break; case XPathFunctionID.StringLengthDefault: XPathFunction.StringLengthDefault(context); break; case XPathFunctionID.SubstringBefore: XPathFunction.SubstringBefore(context); break; case XPathFunctionID.SubstringAfter: XPathFunction.SubstringAfter(context); break; case XPathFunctionID.Substring: XPathFunction.Substring(context); break; case XPathFunctionID.SubstringLimit: XPathFunction.SubstringLimit(context); break; case XPathFunctionID.Translate: XPathFunction.Translate(context); break; case XPathFunctionID.NormalizeSpace: XPathFunction.NormalizeSpace(context); break; case XPathFunctionID.NormalizeSpaceDefault: XPathFunction.NormalizeSpaceDefault(context); break; } } internal static void BooleanBoolean(ProcessingContext context) { StackFrame arg = context.TopArg; Value[] values = context.Values; while (arg.basePtr <= arg.endPtr) { values[arg.basePtr++].ConvertTo(context, ValueDataType.Boolean); } } internal static void BooleanFalse(ProcessingContext context) { context.PushFrame(); int count = context.IterationCount; if (count > 0) { context.Push(false, count); } } internal static void BooleanNot(ProcessingContext context) { StackFrame arg = context.TopArg; Value[] values = context.Values; while (arg.basePtr <= arg.endPtr) { values[arg.basePtr++].Not(); } } internal static void BooleanTrue(ProcessingContext context) { context.PushFrame(); int count = context.IterationCount; if (count > 0) { context.Push(true, count); } } internal static void BooleanLang(ProcessingContext context) { StackFrame langArg = context.TopArg; StackFrame sequences = context.TopSequenceArg; Value[] sequenceBuffer = context.Sequences; while (sequences.basePtr <= sequences.endPtr) { NodeSequence sourceSeq = sequenceBuffer[sequences.basePtr++].Sequence; for (int item = 0; item < sourceSeq.Count; ++item) { string lang = context.PeekString(langArg.basePtr).ToUpperInvariant(); QueryNode node = sourceSeq.Items[item].Node; long pos = node.Node.CurrentPosition; node.Node.CurrentPosition = node.Position; string docLang = node.Node.XmlLang.ToUpperInvariant(); node.Node.CurrentPosition = pos; if (lang.Length == docLang.Length && string.CompareOrdinal(lang, docLang) == 0) { context.SetValue(context, langArg.basePtr++, true); } else if (docLang.Length > 0 && lang.Length < docLang.Length && docLang.StartsWith(lang, StringComparison.Ordinal) && docLang[lang.Length] == '-') { context.SetValue(context, langArg.basePtr++, true); } else { context.SetValue(context, langArg.basePtr++, false); } } sequences.basePtr++; } } internal static void IterateAndPushSequences(ProcessingContext context) { StackFrame sequences = context.TopSequenceArg; Value[] sequenceBuffer = context.Sequences; context.PushFrame(); while (sequences.basePtr <= sequences.endPtr) { NodeSequence sourceSeq = sequenceBuffer[sequences.basePtr++].Sequence; int count = sourceSeq.Count; if (count == 0) { context.PushSequence(NodeSequence.Empty); } else { for (int item = 0; item < sourceSeq.Count; ++item) { NodeSequence newSequence = context.CreateSequence(); newSequence.StartNodeset(); newSequence.Add(ref sourceSeq.Items[item]); newSequence.StopNodeset(); context.Push(newSequence); } } } } internal static void NodesetCount(ProcessingContext context) { StackFrame arg = context.TopArg; while (arg.basePtr <= arg.endPtr) { context.SetValue(context, arg.basePtr, context.PeekSequence(arg.basePtr).Count); arg.basePtr++; } } internal static void NodesetLast(ProcessingContext context) { context.TransferSequenceSize(); } internal static void NodesetLocalName(ProcessingContext context) { StackFrame arg = context.TopArg; while (arg.basePtr <= arg.endPtr) { NodeSequence sequence = context.PeekSequence(arg.basePtr); context.SetValue(context, arg.basePtr, sequence.LocalName); arg.basePtr++; } } internal static void NodesetLocalNameDefault(ProcessingContext context) { XPathFunction.IterateAndPushSequences(context); XPathFunction.NodesetLocalName(context); } internal static void NodesetName(ProcessingContext context) { StackFrame arg = context.TopArg; while (arg.basePtr <= arg.endPtr) { NodeSequence sequence = context.PeekSequence(arg.basePtr); context.SetValue(context, arg.basePtr, sequence.Name); arg.basePtr++; } } internal static void NodesetNameDefault(ProcessingContext context) { XPathFunction.IterateAndPushSequences(context); XPathFunction.NodesetName(context); } internal static void NodesetNamespaceUri(ProcessingContext context) { StackFrame arg = context.TopArg; while (arg.basePtr <= arg.endPtr) { NodeSequence sequence = context.PeekSequence(arg.basePtr); context.SetValue(context, arg.basePtr, sequence.Namespace); arg.basePtr++; } } internal static void NodesetNamespaceUriDefault(ProcessingContext context) { XPathFunction.IterateAndPushSequences(context); XPathFunction.NodesetNamespaceUri(context); } internal static void NodesetPosition(ProcessingContext context) { context.TransferSequencePositions(); } internal static void NumberCeiling(ProcessingContext context) { StackFrame arg = context.TopArg; while (arg.basePtr <= arg.endPtr) { context.SetValue(context, arg.basePtr, Math.Ceiling(context.PeekDouble(arg.basePtr))); arg.basePtr++; } } internal static void NumberNumber(ProcessingContext context) { StackFrame arg = context.TopArg; Value[] values = context.Values; while (arg.basePtr <= arg.endPtr) { values[arg.basePtr++].ConvertTo(context, ValueDataType.Double); } } internal static void NumberNumberDefault(ProcessingContext context) { XPathFunction.IterateAndPushSequences(context); XPathFunction.NumberNumber(context); } internal static void NumberFloor(ProcessingContext context) { StackFrame arg = context.TopArg; while (arg.basePtr <= arg.endPtr) { context.SetValue(context, arg.basePtr, Math.Floor(context.PeekDouble(arg.basePtr))); arg.basePtr++; } } internal static void NumberRound(ProcessingContext context) { StackFrame arg = context.TopArg; while (arg.basePtr <= arg.endPtr) { double val = context.PeekDouble(arg.basePtr); context.SetValue(context, arg.basePtr, QueryValueModel.Round(context.PeekDouble(arg.basePtr))); arg.basePtr++; } } internal static void NumberSum(ProcessingContext context) { StackFrame arg = context.TopArg; while (arg.basePtr <= arg.endPtr) { NodeSequence sequence = context.PeekSequence(arg.basePtr); double sum = 0.0; for (int item = 0; item < sequence.Count; ++item) { sum += QueryValueModel.Double(sequence[item].StringValue()); } context.SetValue(context, arg.basePtr, sum); arg.basePtr++; } } internal static void StringString(ProcessingContext context) { StackFrame arg = context.TopArg; Value[] values = context.Values; while (arg.basePtr <= arg.endPtr) { values[arg.basePtr++].ConvertTo(context, ValueDataType.String); } } internal static void StringStringDefault(ProcessingContext context) { XPathFunction.IterateAndPushSequences(context); XPathFunction.StringString(context); } internal static void StringConcatTwo(ProcessingContext context) { StackFrame arg1 = context[0]; StackFrame arg2 = context[1]; while (arg1.basePtr <= arg1.endPtr) { string str1 = context.PeekString(arg1.basePtr); string str2 = context.PeekString(arg2.basePtr); context.SetValue(context, arg2.basePtr, str1 + str2); arg1.basePtr++; arg2.basePtr++; } context.PopFrame(); } internal static void StringConcatThree(ProcessingContext context) { StackFrame arg1 = context[0]; StackFrame arg2 = context[1]; StackFrame arg3 = context[2]; while (arg1.basePtr <= arg1.endPtr) { string str1 = context.PeekString(arg1.basePtr); string str2 = context.PeekString(arg2.basePtr); string str3 = context.PeekString(arg3.basePtr); context.SetValue(context, arg3.basePtr, str1 + str2 + str3); arg1.basePtr++; arg2.basePtr++; arg3.basePtr++; } context.PopFrame(); context.PopFrame(); } internal static void StringConcatFour(ProcessingContext context) { StackFrame arg1 = context[0]; StackFrame arg2 = context[1]; StackFrame arg3 = context[2]; StackFrame arg4 = context[3]; while (arg1.basePtr <= arg1.endPtr) { string str1 = context.PeekString(arg1.basePtr); string str2 = context.PeekString(arg2.basePtr); string str3 = context.PeekString(arg3.basePtr); string str4 = context.PeekString(arg4.basePtr); context.SetValue(context, arg4.basePtr, str1 + str2 + str3 + str4); arg1.basePtr++; arg2.basePtr++; arg3.basePtr++; arg4.basePtr++; } context.PopFrame(); context.PopFrame(); context.PopFrame(); } internal static void StringContains(ProcessingContext context) { StackFrame arg1 = context.TopArg; StackFrame arg2 = context.SecondArg; Fx.Assert(arg1.Count == arg2.Count, ""); while (arg1.basePtr <= arg1.endPtr) { string leftString = context.PeekString(arg1.basePtr); string rightString = context.PeekString(arg2.basePtr); context.SetValue(context, arg2.basePtr, (-1 != leftString.IndexOf(rightString, StringComparison.Ordinal))); arg1.basePtr++; arg2.basePtr++; } context.PopFrame(); } internal static void StringLength(ProcessingContext context) { StackFrame arg = context.TopArg; while (arg.basePtr <= arg.endPtr) { context.SetValue(context, arg.basePtr, context.PeekString(arg.basePtr).Length); arg.basePtr++; } } internal static void StringLengthDefault(ProcessingContext context) { XPathFunction.IterateAndPushSequences(context); XPathFunction.ConvertFirstArg(context, ValueDataType.String); XPathFunction.StringLength(context); } internal static void StringStartsWith(ProcessingContext context) { StackFrame arg1 = context.TopArg; StackFrame arg2 = context.SecondArg; Fx.Assert(arg1.Count == arg2.Count, ""); while (arg1.basePtr <= arg1.endPtr) { string leftString = context.PeekString(arg1.basePtr); string rightString = context.PeekString(arg2.basePtr); context.SetValue(context, arg2.basePtr, leftString.StartsWith(rightString, StringComparison.Ordinal)); arg1.basePtr++; arg2.basePtr++; } context.PopFrame(); } internal static void SubstringBefore(ProcessingContext context) { StackFrame arg1 = context.TopArg; StackFrame arg2 = context.SecondArg; Fx.Assert(arg1.Count == arg2.Count, ""); while (arg1.basePtr <= arg1.endPtr) { string str1 = context.PeekString(arg1.basePtr); string str2 = context.PeekString(arg2.basePtr); int idx = str1.IndexOf(str2, StringComparison.Ordinal); context.SetValue(context, arg2.basePtr, idx == -1 ? string.Empty : str1.Substring(0, idx)); arg1.basePtr++; arg2.basePtr++; } context.PopFrame(); } internal static void SubstringAfter(ProcessingContext context) { StackFrame arg1 = context.TopArg; StackFrame arg2 = context.SecondArg; Fx.Assert(arg1.Count == arg2.Count, ""); while (arg1.basePtr <= arg1.endPtr) { string str1 = context.PeekString(arg1.basePtr); string str2 = context.PeekString(arg2.basePtr); int idx = str1.IndexOf(str2, StringComparison.Ordinal); context.SetValue(context, arg2.basePtr, idx == -1 ? string.Empty : str1.Substring(idx + str2.Length)); arg1.basePtr++; arg2.basePtr++; } context.PopFrame(); } internal static void Substring(ProcessingContext context) { StackFrame arg1 = context.TopArg; StackFrame arg2 = context.SecondArg; Fx.Assert(arg1.Count == arg2.Count, ""); while (arg1.basePtr <= arg1.endPtr) { string str = context.PeekString(arg1.basePtr); int startAt = ((int)Math.Round(context.PeekDouble(arg2.basePtr))) - 1; if (startAt < 0) { startAt = 0; } context.SetValue(context, arg2.basePtr, (startAt >= str.Length) ? string.Empty : str.Substring(startAt)); arg1.basePtr++; arg2.basePtr++; } context.PopFrame(); } internal static void SubstringLimit(ProcessingContext context) { StackFrame argString = context.TopArg; StackFrame argStartAt = context.SecondArg; StackFrame argLimit = context[2]; Fx.Assert(argString.Count == argStartAt.Count, ""); Fx.Assert(argString.Count == argLimit.Count, ""); while (argString.basePtr <= argString.endPtr) { string str = context.PeekString(argString.basePtr); int startAt = ((int)Math.Round(context.PeekDouble(argStartAt.basePtr))) - 1; if (startAt < 0) { startAt = 0; } int length = (int)Math.Round(context.PeekDouble(argLimit.basePtr)); string substr; if (length < 1 || ((startAt + length) >= str.Length)) { substr = string.Empty; } else { substr = str.Substring(startAt, length); } context.SetValue(context, argLimit.basePtr, substr); argStartAt.basePtr++; argString.basePtr++; argLimit.basePtr++; } context.PopFrame(); context.PopFrame(); } internal static void Translate(ProcessingContext context) { StackFrame argSource = context.TopArg; StackFrame argKeys = context.SecondArg; StackFrame argValues = context[2]; // PERF, [....], this is really slow. StringBuilder builder = new StringBuilder(); while (argSource.basePtr <= argSource.endPtr) { builder.Length = 0; string source = context.PeekString(argSource.basePtr); string keys = context.PeekString(argKeys.basePtr); string values = context.PeekString(argValues.basePtr); for (int i = 0; i < source.Length; ++i) { char c = source[i]; int idx = keys.IndexOf(c); if (idx < 0) { builder.Append(c); } else if (idx < values.Length) { builder.Append(values[idx]); } } context.SetValue(context, argValues.basePtr, builder.ToString()); argSource.basePtr++; argKeys.basePtr++; argValues.basePtr++; } context.PopFrame(); context.PopFrame(); } internal static void NormalizeSpace(ProcessingContext context) { StackFrame argStr = context.TopArg; StringBuilder builder = new StringBuilder(); while (argStr.basePtr <= argStr.endPtr) { char[] whitespace = new char[] { ' ', '\t', '\r', '\n' }; string str = context.PeekString(argStr.basePtr).Trim(whitespace); bool eatingWhitespace = false; builder.Length = 0; for (int i = 0; i < str.Length; ++i) { char c = str[i]; if (XPathCharTypes.IsWhitespace(c)) { if (!eatingWhitespace) { builder.Append(' '); eatingWhitespace = true; } } else { builder.Append(c); eatingWhitespace = false; } } context.SetValue(context, argStr.basePtr, builder.ToString()); argStr.basePtr++; } } internal static void NormalizeSpaceDefault(ProcessingContext context) { XPathFunction.IterateAndPushSequences(context); XPathFunction.ConvertFirstArg(context, ValueDataType.String); XPathFunction.NormalizeSpace(context); } #if NO internal static bool IsWhitespace(char c) { return c == ' ' || c == '\r' || c == '\n' || c == '\t'; } #endif } }
// // C#-like events for AVFoundation classes // // Author: // Miguel de Icaza ([email protected]) // Copyright 2009, Novell, Inc. // Copyright 2010, Novell, Inc. // Copyright 2011, 2012 Xamarin Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // using System; using MonoMac.Foundation; using MonoMac.ObjCRuntime; namespace MonoMac.AVFoundation { public class AVErrorEventArgs : EventArgs { public AVErrorEventArgs (NSError error) { Error = error; } public NSError Error { get; private set; } } public class AVStatusEventArgs : EventArgs { public AVStatusEventArgs (bool status) { Status = status; } public bool Status { get; private set; } } #pragma warning disable 672 sealed class InternalAVAudioPlayerDelegate : AVAudioPlayerDelegate { internal EventHandler cbEndInterruption, cbBeginInterruption; internal EventHandler<AVStatusEventArgs> cbFinishedPlaying; internal EventHandler<AVErrorEventArgs> cbDecoderError; [Preserve (Conditional = true)] public override void FinishedPlaying (AVAudioPlayer player, bool flag) { if (cbFinishedPlaying != null) cbFinishedPlaying (player, new AVStatusEventArgs (flag)); if (player.Handle == IntPtr.Zero) throw new ObjectDisposedException ("player", "the player object was Dispose()d during the callback, this has corrupted the state of the program"); } [Preserve (Conditional = true)] public override void DecoderError (AVAudioPlayer player, NSError error) { if (cbDecoderError != null) cbDecoderError (player, new AVErrorEventArgs (error)); } [Preserve (Conditional = true)] public override void BeginInterruption (AVAudioPlayer player) { if (cbBeginInterruption != null) cbBeginInterruption (player, EventArgs.Empty); } [Preserve (Conditional = true)] public override void EndInterruption (AVAudioPlayer player) { if (cbEndInterruption != null) cbEndInterruption (player, EventArgs.Empty); } } #pragma warning restore 672 public partial class AVAudioPlayer { InternalAVAudioPlayerDelegate EnsureEventDelegate () { var del = WeakDelegate as InternalAVAudioPlayerDelegate; if (del == null){ del = new InternalAVAudioPlayerDelegate (); WeakDelegate = del; } return del; } public event EventHandler<AVStatusEventArgs> FinishedPlaying { add { EnsureEventDelegate ().cbFinishedPlaying += value; } remove { EnsureEventDelegate ().cbFinishedPlaying -= value; } } public event EventHandler<AVErrorEventArgs> DecoderError { add { EnsureEventDelegate ().cbDecoderError += value; } remove { EnsureEventDelegate ().cbDecoderError -= value; } } public event EventHandler BeginInterruption { add { EnsureEventDelegate ().cbBeginInterruption += value; } remove { EnsureEventDelegate ().cbBeginInterruption -= value; } } public event EventHandler EndInterruption { add { EnsureEventDelegate ().cbEndInterruption += value; } remove { EnsureEventDelegate ().cbEndInterruption -= value; } } } internal class InternalAVAudioRecorderDelegate : AVAudioRecorderDelegate { internal EventHandler cbEndInterruption, cbBeginInterruption; internal EventHandler<AVStatusEventArgs> cbFinishedRecording; internal EventHandler<AVErrorEventArgs> cbEncoderError; [Preserve (Conditional = true)] public override void FinishedRecording (AVAudioRecorder recorder, bool flag) { if (cbFinishedRecording != null) cbFinishedRecording (recorder, new AVStatusEventArgs (flag)); } [Preserve (Conditional = true)] public override void EncoderError (AVAudioRecorder recorder, NSError error) { if (cbEncoderError != null) cbEncoderError (recorder, new AVErrorEventArgs (error)); } [Preserve (Conditional = true)] public override void BeginInterruption (AVAudioRecorder recorder) { if (cbBeginInterruption != null) cbBeginInterruption (recorder, EventArgs.Empty); } [Preserve (Conditional = true)] [Obsolete ("Deprecated in iOS 6.0")] public override void EndInterruption (AVAudioRecorder recorder) { if (cbEndInterruption != null) cbEndInterruption (recorder, EventArgs.Empty); } } public partial class AVAudioRecorder { InternalAVAudioRecorderDelegate EnsureEventDelegate () { var del = WeakDelegate as InternalAVAudioRecorderDelegate; if (del == null){ del = new InternalAVAudioRecorderDelegate (); WeakDelegate = del; } return del; } public event EventHandler<AVStatusEventArgs> FinishedRecording { add { EnsureEventDelegate ().cbFinishedRecording += value; } remove { EnsureEventDelegate ().cbFinishedRecording -= value; } } public event EventHandler<AVErrorEventArgs> EncoderError { add { EnsureEventDelegate ().cbEncoderError += value; } remove { EnsureEventDelegate ().cbEncoderError -= value; } } public event EventHandler BeginInterruption { add { EnsureEventDelegate ().cbBeginInterruption += value; } remove { EnsureEventDelegate ().cbBeginInterruption -= value; } } public event EventHandler EndInterruption { add { EnsureEventDelegate ().cbEndInterruption += value; } remove { EnsureEventDelegate ().cbEndInterruption -= value; } } } public class AVSampleRateEventArgs : EventArgs { public AVSampleRateEventArgs (double sampleRate) { SampleRate = sampleRate; } public double SampleRate { get; private set; } } public class AVChannelsEventArgs : EventArgs { public AVChannelsEventArgs (int numberOfChannels) { NumberOfChannels = numberOfChannels; } public int NumberOfChannels { get; private set; } } public class AVCategoryEventArgs : EventArgs { public AVCategoryEventArgs (string category) { Category = category; } public string Category { get; private set; } } #if !MONOMAC internal class InternalAVAudioSessionDelegate : AVAudioSessionDelegate { internal EventHandler cbEndInterruption, cbBeginInterruption; internal EventHandler<AVCategoryEventArgs> cbCategoryChanged; internal EventHandler<AVStatusEventArgs> cbInputAvailabilityChanged; internal EventHandler<AVSampleRateEventArgs> cbSampleRateChanged; internal EventHandler<AVChannelsEventArgs> cbInputChanged; internal EventHandler<AVChannelsEventArgs> cbOutputChanged; AVAudioSession session; [Preserve (Conditional = true)] public InternalAVAudioSessionDelegate (AVAudioSession session) { this.session = session; } [Preserve (Conditional = true)] public override void BeginInterruption () { if (cbBeginInterruption != null) cbBeginInterruption (session, EventArgs.Empty); } [Preserve (Conditional = true)] public override void EndInterruption () { if (cbEndInterruption != null) cbEndInterruption (session, EventArgs.Empty); } [Preserve (Conditional = true)] public override void InputIsAvailableChanged (bool isInputAvailable) { if (cbInputAvailabilityChanged != null) cbInputAvailabilityChanged (session, new AVStatusEventArgs (isInputAvailable)); } } public partial class AVAudioSession { InternalAVAudioSessionDelegate EnsureEventDelegate () { var del = WeakDelegate as InternalAVAudioSessionDelegate; if (del == null){ del = new InternalAVAudioSessionDelegate (this); WeakDelegate = del; } return del; } public event EventHandler BeginInterruption { add { EnsureEventDelegate ().cbBeginInterruption += value; } remove { EnsureEventDelegate ().cbBeginInterruption -= value; } } public event EventHandler EndInterruption { add { EnsureEventDelegate ().cbEndInterruption += value; } remove { EnsureEventDelegate ().cbBeginInterruption -= value; } } public event EventHandler<AVCategoryEventArgs> CategoryChanged { add { EnsureEventDelegate ().cbCategoryChanged += value; } remove { EnsureEventDelegate ().cbCategoryChanged -= value; } } public event EventHandler<AVStatusEventArgs> InputAvailabilityChanged { add { EnsureEventDelegate ().cbInputAvailabilityChanged += value; } remove { EnsureEventDelegate ().cbInputAvailabilityChanged -= value; } } public event EventHandler<AVSampleRateEventArgs> SampleRateChanged { add { EnsureEventDelegate ().cbSampleRateChanged += value; } remove { EnsureEventDelegate ().cbSampleRateChanged -= value; } } public event EventHandler<AVChannelsEventArgs> InputChannelsChanged { add { EnsureEventDelegate ().cbInputChanged += value; } remove { EnsureEventDelegate ().cbOutputChanged += value; } } public event EventHandler<AVChannelsEventArgs> OutputChannelsChanged { add { EnsureEventDelegate ().cbOutputChanged += value; } remove { EnsureEventDelegate ().cbOutputChanged -= value; } } } #endif }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Reflection; using System.Text; using System.Threading.Tasks; using System.Web.Mvc; using System.Web.Mvc.Async; using Abp.Auditing; using Abp.Authorization; using Abp.Collections.Extensions; using Abp.Configuration; using Abp.Localization; using Abp.Localization.Sources; using Abp.Reflection; using Abp.Runtime.Session; using Abp.Timing; using Abp.Web.Models; using Abp.Web.Mvc.Controllers.Results; using Castle.Core.Logging; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; namespace Abp.Web.Mvc.Controllers { /// <summary> /// Base class for all MVC Controllers in Abp system. /// </summary> public abstract class AbpController : Controller { /// <summary> /// Gets current session information. /// </summary> public IAbpSession AbpSession { get; set; } /// <summary> /// Reference to the permission manager. /// </summary> public IPermissionManager PermissionManager { get; set; } /// <summary> /// Reference to the setting manager. /// </summary> public ISettingManager SettingManager { get; set; } /// <summary> /// Reference to the permission checker. /// </summary> public IPermissionChecker PermissionChecker { protected get; set; } /// <summary> /// Reference to the localization manager. /// </summary> public ILocalizationManager LocalizationManager { protected get; set; } /// <summary> /// Gets/sets name of the localization source that is used in this application service. /// It must be set in order to use <see cref="L(string)"/> and <see cref="L(string,CultureInfo)"/> methods. /// </summary> protected string LocalizationSourceName { get; set; } /// <summary> /// Gets localization source. /// It's valid if <see cref="LocalizationSourceName"/> is set. /// </summary> protected ILocalizationSource LocalizationSource { get { if (LocalizationSourceName == null) { throw new AbpException("Must set LocalizationSourceName before, in order to get LocalizationSource"); } if (_localizationSource == null || _localizationSource.Name != LocalizationSourceName) { _localizationSource = LocalizationManager.GetSource(LocalizationSourceName); } return _localizationSource; } } private ILocalizationSource _localizationSource; /// <summary> /// Reference to the logger to write logs. /// </summary> public ILogger Logger { get; set; } /// <summary> /// Gets current session information. /// </summary> [Obsolete("Use AbpSession property instead. CurrentSetting will be removed in future releases.")] protected IAbpSession CurrentSession { get { return AbpSession; } } /// <summary> /// This object i used to measure an action execute duration. /// </summary> private Stopwatch _actionStopwatch; private AuditInfo _auditInfo; public IAuditingConfiguration AuditingConfiguration { get; set; } public IAuditInfoProvider AuditInfoProvider { get; set; } public IAuditingStore AuditingStore { get; set; } /// <summary> /// Constructor. /// </summary> protected AbpController() { AbpSession = NullAbpSession.Instance; Logger = NullLogger.Instance; LocalizationManager = NullLocalizationManager.Instance; PermissionChecker = NullPermissionChecker.Instance; AuditingStore = SimpleLogAuditingStore.Instance; } /// <summary> /// Gets localized string for given key name and current language. /// </summary> /// <param name="name">Key name</param> /// <returns>Localized string</returns> protected virtual string L(string name) { return LocalizationSource.GetString(name); } /// <summary> /// Gets localized string for given key name and current language with formatting strings. /// </summary> /// <param name="name">Key name</param> /// <param name="args">Format arguments</param> /// <returns>Localized string</returns> protected string L(string name, params object[] args) { return LocalizationSource.GetString(name, args); } /// <summary> /// Gets localized string for given key name and specified culture information. /// </summary> /// <param name="name">Key name</param> /// <param name="culture">culture information</param> /// <returns>Localized string</returns> protected virtual string L(string name, CultureInfo culture) { return LocalizationSource.GetString(name, culture); } /// <summary> /// Gets localized string for given key name and current language with formatting strings. /// </summary> /// <param name="name">Key name</param> /// <param name="culture">culture information</param> /// <param name="args">Format arguments</param> /// <returns>Localized string</returns> protected string L(string name, CultureInfo culture, params object[] args) { return LocalizationSource.GetString(name, culture, args); } /// <summary> /// Checks if current user is granted for a permission. /// </summary> /// <param name="permissionName">Name of the permission</param> protected Task<bool> IsGrantedAsync(string permissionName) { return PermissionChecker.IsGrantedAsync(permissionName); } /// <summary> /// Checks if current user is granted for a permission. /// </summary> /// <param name="permissionName">Name of the permission</param> protected bool IsGranted(string permissionName) { return PermissionChecker.IsGranted(permissionName); } /// <summary> /// Json the specified data, contentType, contentEncoding and behavior. /// </summary> /// <param name="data">Data.</param> /// <param name="contentType">Content type.</param> /// <param name="contentEncoding">Content encoding.</param> /// <param name="behavior">Behavior.</param> protected override JsonResult Json(object data, string contentType, Encoding contentEncoding, JsonRequestBehavior behavior) { if (data == null) { data = new AjaxResponse(); } else if (!ReflectionHelper.IsAssignableToGenericType(data.GetType(), typeof(AjaxResponse<>))) { data = new AjaxResponse(data); } return new AbpJsonResult { Data = data, ContentType = contentType, ContentEncoding = contentEncoding, JsonRequestBehavior = behavior }; } protected override void OnActionExecuting(ActionExecutingContext filterContext) { HandleAuditingBeforeAction(filterContext); base.OnActionExecuting(filterContext); } protected override void OnActionExecuted(ActionExecutedContext filterContext) { base.OnActionExecuted(filterContext); HandleAuditingAfterAction(filterContext); } protected virtual bool ShouldSaveAudit(ActionExecutingContext filterContext) { if (AuditingConfiguration == null) { return false; } if (!AuditingConfiguration.MvcControllers.IsEnabled) { return false; } if (filterContext.IsChildAction && !AuditingConfiguration.MvcControllers.IsEnabledForChildActions) { return false; } return AuditingHelper.ShouldSaveAudit( GetMethodInfo(filterContext.ActionDescriptor), AuditingConfiguration, AbpSession, true ); } private static MethodInfo GetMethodInfo(ActionDescriptor actionDescriptor) { if (actionDescriptor is ReflectedActionDescriptor) { return ((ReflectedActionDescriptor)actionDescriptor).MethodInfo; } if (actionDescriptor is ReflectedAsyncActionDescriptor) { return ((ReflectedAsyncActionDescriptor)actionDescriptor).MethodInfo; } if (actionDescriptor is TaskAsyncActionDescriptor) { return ((TaskAsyncActionDescriptor)actionDescriptor).MethodInfo; } return null; } private void HandleAuditingBeforeAction(ActionExecutingContext filterContext) { if (!ShouldSaveAudit(filterContext)) { _auditInfo = null; return; } var methodInfo = GetMethodInfo(filterContext.ActionDescriptor); _actionStopwatch = Stopwatch.StartNew(); _auditInfo = new AuditInfo { TenantId = AbpSession.TenantId, UserId = AbpSession.UserId, ServiceName = methodInfo.DeclaringType != null ? methodInfo.DeclaringType.FullName : filterContext.ActionDescriptor.ControllerDescriptor.ControllerName, MethodName = methodInfo.Name, Parameters = ConvertArgumentsToJson(filterContext.ActionParameters), ExecutionTime = Clock.Now }; } private void HandleAuditingAfterAction(ActionExecutedContext filterContext) { if (_auditInfo == null || _actionStopwatch == null) { return; } _actionStopwatch.Stop(); _auditInfo.ExecutionDuration = Convert.ToInt32(_actionStopwatch.Elapsed.TotalMilliseconds); _auditInfo.Exception = filterContext.Exception; if (AuditInfoProvider != null) { AuditInfoProvider.Fill(_auditInfo); } AuditingStore.Save(_auditInfo); } private string ConvertArgumentsToJson(IDictionary<string, object> arguments) { try { if (arguments.IsNullOrEmpty()) { return "{}"; } var dictionary = new Dictionary<string, object>(); foreach (var argument in arguments) { dictionary[argument.Key] = argument.Value; } return JsonConvert.SerializeObject( dictionary, new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }); } catch (Exception ex) { Logger.Warn("Could not serialize arguments for method: " + _auditInfo.ServiceName + "." + _auditInfo.MethodName); Logger.Warn(ex.ToString(), ex); return "{}"; } } } }
#region License // // The Open Toolkit Library License // // Copyright (c) 2006 - 2009 the Open Toolkit library. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of // the Software, and to permit persons to whom the Software is furnished to do // so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. // #endregion using System; using System.Diagnostics; using System.Runtime.InteropServices; using System.Text; using OpenTK.Graphics; using OpenTK.Input; using System.Collections.Generic; using System.IO; #if !MINIMAL using System.Drawing; #endif namespace OpenTK.Platform.Windows { /// \internal /// <summary> /// Drives GameWindow on Windows. /// This class supports OpenTK, and is not intended for use by OpenTK programs. /// </summary> internal sealed class WinGLNative : INativeWindow, IInputDriver { #region Fields const ExtendedWindowStyle ParentStyleEx = ExtendedWindowStyle.WindowEdge | ExtendedWindowStyle.ApplicationWindow; const ExtendedWindowStyle ChildStyleEx = 0; static readonly WinKeyMap KeyMap = new WinKeyMap(); readonly IntPtr Instance = Marshal.GetHINSTANCE(typeof(WinGLNative).Module); readonly IntPtr ClassName = Marshal.StringToHGlobalAuto(Guid.NewGuid().ToString()); readonly WindowProcedure WindowProcedureDelegate; readonly uint ModalLoopTimerPeriod = 1; UIntPtr timer_handle; readonly Functions.TimerProc ModalLoopCallback; bool class_registered; bool disposed; bool exists; WinWindowInfo window, child_window; WindowBorder windowBorder = WindowBorder.Resizable; Nullable<WindowBorder> previous_window_border; // Set when changing to fullscreen state. Nullable<WindowBorder> deferred_window_border; // Set to avoid changing borders during fullscreen state. WindowState windowState = WindowState.Normal; bool borderless_maximized_window_state = false; // Hack to get maximized mode with hidden border (not normally possible). bool focused; bool mouse_outside_window = true; bool invisible_since_creation; // Set by WindowsMessage.CREATE and consumed by Visible = true (calls BringWindowToFront). int suppress_resize; // Used in WindowBorder and WindowState in order to avoid rapid, consecutive resize events. Rectangle bounds = new Rectangle(), client_rectangle = new Rectangle(), previous_bounds = new Rectangle(); // Used to restore previous size when leaving fullscreen mode. Icon icon; const ClassStyle DefaultClassStyle = ClassStyle.OwnDC; // Used for IInputDriver implementation WinMMJoystick joystick_driver = new WinMMJoystick(); KeyboardDevice keyboard = new KeyboardDevice(); MouseDevice mouse = new MouseDevice(); IList<KeyboardDevice> keyboards = new List<KeyboardDevice>(1); IList<MouseDevice> mice = new List<MouseDevice>(1); const long ExtendedBit = 1 << 24; // Used to distinguish left and right control, alt and enter keys. static readonly uint ShiftRightScanCode = Functions.MapVirtualKey(VirtualKeys.RSHIFT, 0); // Used to distinguish left and right shift keys. KeyPressEventArgs key_press = new KeyPressEventArgs((char)0); int cursor_visible_count = 0; static readonly object SyncRoot = new object(); #endregion #region Contructors public WinGLNative(int x, int y, int width, int height, string title, GameWindowFlags options, DisplayDevice device) { lock (SyncRoot) { // This is the main window procedure callback. We need the callback in order to create the window, so // don't move it below the CreateWindow calls. WindowProcedureDelegate = WindowProcedure; //// This timer callback is called periodically when the window enters a sizing / moving modal loop. //ModalLoopCallback = delegate(IntPtr handle, WindowMessage msg, UIntPtr eventId, int time) //{ // // Todo: find a way to notify the frontend that it should process queued up UpdateFrame/RenderFrame events. // if (Move != null) // Move(this, EventArgs.Empty); //}; // To avoid issues with Ati drivers on Windows 6+ with compositing enabled, the context will not be // bound to the top-level window, but rather to a child window docked in the parent. window = new WinWindowInfo( CreateWindow(x, y, width, height, title, options, device, IntPtr.Zero), null); child_window = new WinWindowInfo( CreateWindow(0, 0, ClientSize.Width, ClientSize.Height, title, options, device, window.WindowHandle), window); exists = true; keyboard.Description = "Standard Windows keyboard"; keyboard.NumberOfFunctionKeys = 12; keyboard.NumberOfKeys = 101; keyboard.NumberOfLeds = 3; mouse.Description = "Standard Windows mouse"; mouse.NumberOfButtons = 3; mouse.NumberOfWheels = 1; keyboards.Add(keyboard); mice.Add(mouse); } } #endregion #region Private Members #region WindowProcedure IntPtr WindowProcedure(IntPtr handle, WindowMessage message, IntPtr wParam, IntPtr lParam) { switch (message) { #region Size / Move / Style events case WindowMessage.ACTIVATE: // See http://msdn.microsoft.com/en-us/library/ms646274(VS.85).aspx (WM_ACTIVATE notification): // wParam: The low-order word specifies whether the window is being activated or deactivated. bool new_focused_state = Focused; if (IntPtr.Size == 4) focused = (wParam.ToInt32() & 0xFFFF) != 0; else focused = (wParam.ToInt64() & 0xFFFF) != 0; if (new_focused_state != Focused) FocusedChanged(this, EventArgs.Empty); break; case WindowMessage.ENTERMENULOOP: case WindowMessage.ENTERSIZEMOVE: // Entering the modal size/move loop: we don't want rendering to // stop during this time, so we register a timer callback to continue // processing from time to time. StartTimer(handle); break; case WindowMessage.EXITMENULOOP: case WindowMessage.EXITSIZEMOVE: // ExitingmModal size/move loop: the timer callback is no longer // necessary. StopTimer(handle); break; case WindowMessage.ERASEBKGND: return new IntPtr(1); case WindowMessage.WINDOWPOSCHANGED: unsafe { WindowPosition* pos = (WindowPosition*)lParam; if (window != null && pos->hwnd == window.WindowHandle) { Point new_location = new Point(pos->x, pos->y); if (Location != new_location) { bounds.Location = new_location; Move(this, EventArgs.Empty); } Size new_size = new Size(pos->cx, pos->cy); if (Size != new_size) { bounds.Width = pos->cx; bounds.Height = pos->cy; Win32Rectangle rect; Functions.GetClientRect(handle, out rect); client_rectangle = rect.ToRectangle(); Functions.SetWindowPos(child_window.WindowHandle, IntPtr.Zero, 0, 0, ClientRectangle.Width, ClientRectangle.Height, SetWindowPosFlags.NOZORDER | SetWindowPosFlags.NOOWNERZORDER | SetWindowPosFlags.NOACTIVATE | SetWindowPosFlags.NOSENDCHANGING); if (suppress_resize <= 0) Resize(this, EventArgs.Empty); } // Ensure cursor remains grabbed if (!CursorVisible) GrabCursor(); } } break; case WindowMessage.STYLECHANGED: unsafe { if (wParam.ToInt64() == (long)GWL.STYLE) { WindowStyle style = ((StyleStruct*)lParam)->New; if ((style & WindowStyle.Popup) != 0) windowBorder = WindowBorder.Hidden; else if ((style & WindowStyle.ThickFrame) != 0) windowBorder = WindowBorder.Resizable; else if ((style & ~(WindowStyle.ThickFrame | WindowStyle.MaximizeBox)) != 0) windowBorder = WindowBorder.Fixed; } } // Ensure cursor remains grabbed if (!CursorVisible) GrabCursor(); break; case WindowMessage.SIZE: SizeMessage state = (SizeMessage)wParam.ToInt64(); WindowState new_state = windowState; switch (state) { case SizeMessage.RESTORED: new_state = borderless_maximized_window_state ? WindowState.Maximized : WindowState.Normal; break; case SizeMessage.MINIMIZED: new_state = WindowState.Minimized; break; case SizeMessage.MAXIMIZED: new_state = WindowBorder == WindowBorder.Hidden ? WindowState.Fullscreen : WindowState.Maximized; break; } if (new_state != windowState) { windowState = new_state; WindowStateChanged(this, EventArgs.Empty); } // Ensure cursor remains grabbed if (!CursorVisible) GrabCursor(); break; #endregion #region Input events case WindowMessage.CHAR: if (IntPtr.Size == 4) key_press.KeyChar = (char)wParam.ToInt32(); else key_press.KeyChar = (char)wParam.ToInt64(); KeyPress(this, key_press); break; case WindowMessage.MOUSEMOVE: Point point = new Point( (short)((uint)lParam.ToInt32() & 0x0000FFFF), (short)(((uint)lParam.ToInt32() & 0xFFFF0000) >> 16)); mouse.Position = point; if (mouse_outside_window) { // Once we receive a mouse move event, it means that the mouse has // re-entered the window. mouse_outside_window = false; EnableMouseTracking(); MouseEnter(this, EventArgs.Empty); } break; case WindowMessage.MOUSELEAVE: mouse_outside_window = true; // Mouse tracking is disabled automatically by the OS MouseLeave(this, EventArgs.Empty); break; case WindowMessage.MOUSEWHEEL: // This is due to inconsistent behavior of the WParam value on 64bit arch, whese // wparam = 0xffffffffff880000 or wparam = 0x00000000ff100000 mouse.WheelPrecise += ((long)wParam << 32 >> 48) / 120.0f; break; case WindowMessage.LBUTTONDOWN: Functions.SetCapture(window.WindowHandle); mouse[MouseButton.Left] = true; break; case WindowMessage.MBUTTONDOWN: Functions.SetCapture(window.WindowHandle); mouse[MouseButton.Middle] = true; break; case WindowMessage.RBUTTONDOWN: Functions.SetCapture(window.WindowHandle); mouse[MouseButton.Right] = true; break; case WindowMessage.XBUTTONDOWN: Functions.SetCapture(window.WindowHandle); mouse[((wParam.ToInt32() & 0xFFFF0000) >> 16) != (int)MouseKeys.XButton1 ? MouseButton.Button1 : MouseButton.Button2] = true; break; case WindowMessage.LBUTTONUP: Functions.ReleaseCapture(); mouse[MouseButton.Left] = false; break; case WindowMessage.MBUTTONUP: Functions.ReleaseCapture(); mouse[MouseButton.Middle] = false; break; case WindowMessage.RBUTTONUP: Functions.ReleaseCapture(); mouse[MouseButton.Right] = false; break; case WindowMessage.XBUTTONUP: Functions.ReleaseCapture(); mouse[((wParam.ToInt32() & 0xFFFF0000) >> 16) != (int)MouseKeys.XButton1 ? MouseButton.Button1 : MouseButton.Button2] = false; break; // Keyboard events: case WindowMessage.KEYDOWN: case WindowMessage.KEYUP: case WindowMessage.SYSKEYDOWN: case WindowMessage.SYSKEYUP: bool pressed = message == WindowMessage.KEYDOWN || message == WindowMessage.SYSKEYDOWN; // Shift/Control/Alt behave strangely when e.g. ShiftRight is held down and ShiftLeft is pressed // and released. It looks like neither key is released in this case, or that the wrong key is // released in the case of Control and Alt. // To combat this, we are going to release both keys when either is released. Hacky, but should work. // Win95 does not distinguish left/right key constants (GetAsyncKeyState returns 0). // In this case, both keys will be reported as pressed. bool extended = (lParam.ToInt64() & ExtendedBit) != 0; switch ((VirtualKeys)wParam) { case VirtualKeys.SHIFT: // The behavior of this key is very strange. Unlike Control and Alt, there is no extended bit // to distinguish between left and right keys. Moreover, pressing both keys and releasing one // may result in both keys being held down (but not always). // The only reliable way to solve this was reported by BlueMonkMN at the forums: we should // check the scancodes. It looks like GLFW does the same thing, so it should be reliable. // Note: we release both keys when either shift is released. // Otherwise, the state of one key might be stuck to pressed. if (ShiftRightScanCode != 0 && pressed) { unchecked { if (((lParam.ToInt64() >> 16) & 0xFF) == ShiftRightScanCode) keyboard[Input.Key.ShiftRight] = pressed; else keyboard[Input.Key.ShiftLeft] = pressed; } } else { // Windows 9x and NT4.0 or key release event. keyboard[Input.Key.ShiftLeft] = keyboard[Input.Key.ShiftRight] = pressed; } return IntPtr.Zero; case VirtualKeys.CONTROL: if (extended) keyboard[Input.Key.ControlRight] = pressed; else keyboard[Input.Key.ControlLeft] = pressed; return IntPtr.Zero; case VirtualKeys.MENU: if (extended) keyboard[Input.Key.AltRight] = pressed; else keyboard[Input.Key.AltLeft] = pressed; return IntPtr.Zero; case VirtualKeys.RETURN: if (extended) keyboard[Key.KeypadEnter] = pressed; else keyboard[Key.Enter] = pressed; return IntPtr.Zero; default: if (!KeyMap.ContainsKey((VirtualKeys)wParam)) { Debug.Print("Virtual key {0} ({1}) not mapped.", (VirtualKeys)wParam, (long)lParam); break; } else { keyboard[KeyMap[(VirtualKeys)wParam]] = pressed; } return IntPtr.Zero; } break; case WindowMessage.SYSCHAR: return IntPtr.Zero; case WindowMessage.KILLFOCUS: keyboard.ClearKeys(); break; #endregion #region Creation / Destruction events case WindowMessage.CREATE: CreateStruct cs = (CreateStruct)Marshal.PtrToStructure(lParam, typeof(CreateStruct)); if (cs.hwndParent == IntPtr.Zero) { bounds.X = cs.x; bounds.Y = cs.y; bounds.Width = cs.cx; bounds.Height = cs.cy; Win32Rectangle rect; Functions.GetClientRect(handle, out rect); client_rectangle = rect.ToRectangle(); invisible_since_creation = true; } break; case WindowMessage.CLOSE: System.ComponentModel.CancelEventArgs e = new System.ComponentModel.CancelEventArgs(); Closing(this, e); if (!e.Cancel) { DestroyWindow(); break; } return IntPtr.Zero; case WindowMessage.DESTROY: exists = false; Functions.UnregisterClass(ClassName, Instance); window.Dispose(); child_window.Dispose(); Closed(this, EventArgs.Empty); break; #endregion } return Functions.DefWindowProc(handle, message, wParam, lParam); } private void EnableMouseTracking() { TrackMouseEventStructure me = new TrackMouseEventStructure(); me.Size = TrackMouseEventStructure.SizeInBytes; me.TrackWindowHandle = child_window.WindowHandle; me.Flags = TrackMouseEventFlags.LEAVE; if (!Functions.TrackMouseEvent(ref me)) Debug.Print("[Warning] Failed to enable mouse tracking, error: {0}.", Marshal.GetLastWin32Error()); } private void StartTimer(IntPtr handle) { if (timer_handle == UIntPtr.Zero) { timer_handle = Functions.SetTimer(handle, new UIntPtr(1), ModalLoopTimerPeriod, ModalLoopCallback); if (timer_handle == UIntPtr.Zero) Debug.Print("[Warning] Failed to set modal loop timer callback ({0}:{1}->{2}).", GetType().Name, handle, Marshal.GetLastWin32Error()); } } private void StopTimer(IntPtr handle) { if (timer_handle != UIntPtr.Zero) { if (!Functions.KillTimer(handle, timer_handle)) Debug.Print("[Warning] Failed to kill modal loop timer callback ({0}:{1}->{2}).", GetType().Name, handle, Marshal.GetLastWin32Error()); timer_handle = UIntPtr.Zero; } } #endregion #region IsIdle bool IsIdle { get { MSG message = new MSG(); return !Functions.PeekMessage(ref message, window.WindowHandle, 0, 0, 0); } } #endregion #region CreateWindow IntPtr CreateWindow(int x, int y, int width, int height, string title, GameWindowFlags options, DisplayDevice device, IntPtr parentHandle) { // Use win32 to create the native window. // Keep in mind that some construction code runs in the WM_CREATE message handler. // The style of a parent window is different than that of a child window. // Note: the child window should always be visible, even if the parent isn't. WindowStyle style = 0; ExtendedWindowStyle ex_style = 0; if (parentHandle == IntPtr.Zero) { style |= WindowStyle.OverlappedWindow | WindowStyle.ClipChildren; ex_style = ParentStyleEx; } else { style |= WindowStyle.Visible | WindowStyle.Child | WindowStyle.ClipSiblings; ex_style = ChildStyleEx; } // Find out the final window rectangle, after the WM has added its chrome (titlebar, sidebars etc). Win32Rectangle rect = new Win32Rectangle(); rect.left = x; rect.top = y; rect.right = x + width; rect.bottom = y + height; Functions.AdjustWindowRectEx(ref rect, style, false, ex_style); // Create the window class that we will use for this window. // The current approach is to register a new class for each top-level WinGLWindow we create. if (!class_registered) { ExtendedWindowClass wc = new ExtendedWindowClass(); wc.Size = ExtendedWindowClass.SizeInBytes; wc.Style = DefaultClassStyle; wc.Instance = Instance; wc.WndProc = WindowProcedureDelegate; wc.ClassName = ClassName; wc.Icon = Icon != null ? Icon.Handle : IntPtr.Zero; #warning "This seems to resize one of the 'large' icons, rather than using a small icon directly (multi-icon files). Investigate!" wc.IconSm = Icon != null ? new Icon(Icon, 16, 16).Handle : IntPtr.Zero; wc.Cursor = Functions.LoadCursor(CursorName.Arrow); ushort atom = Functions.RegisterClassEx(ref wc); if (atom == 0) throw new PlatformException(String.Format("Failed to register window class. Error: {0}", Marshal.GetLastWin32Error())); class_registered = true; } IntPtr window_name = Marshal.StringToHGlobalAuto(title); IntPtr handle = Functions.CreateWindowEx( ex_style, ClassName, window_name, style, rect.left, rect.top, rect.Width, rect.Height, parentHandle, IntPtr.Zero, Instance, IntPtr.Zero); if (handle == IntPtr.Zero) throw new PlatformException(String.Format("Failed to create window. Error: {0}", Marshal.GetLastWin32Error())); return handle; } #endregion #region DestroyWindow /// <summary> /// Starts the teardown sequence for the current window. /// </summary> void DestroyWindow() { if (Exists) { Debug.Print("Destroying window: {0}", window.ToString()); Functions.DestroyWindow(window.WindowHandle); exists = false; } } #endregion void HideBorder() { suppress_resize++; WindowBorder = WindowBorder.Hidden; ProcessEvents(); suppress_resize--; } void RestoreBorder() { suppress_resize++; WindowBorder = deferred_window_border.HasValue ? deferred_window_border.Value : previous_window_border.HasValue ? previous_window_border.Value : WindowBorder; ProcessEvents(); suppress_resize--; deferred_window_border = previous_window_border = null; } void ResetWindowState() { suppress_resize++; WindowState = WindowState.Normal; ProcessEvents(); suppress_resize--; } void GrabCursor() { Point pos = PointToScreen(new Point(ClientRectangle.X, ClientRectangle.Y)); Win32Rectangle rect = new Win32Rectangle(); rect.left = pos.X; rect.right = pos.X + ClientRectangle.Width; rect.top = pos.Y; rect.bottom = pos.Y + ClientRectangle.Height; if (!Functions.ClipCursor(ref rect)) Debug.WriteLine(String.Format("Failed to grab cursor. Error: {0}", Marshal.GetLastWin32Error())); } void UngrabCursor() { if (!Functions.ClipCursor(IntPtr.Zero)) Debug.WriteLine(String.Format("Failed to ungrab cursor. Error: {0}", Marshal.GetLastWin32Error())); } #endregion #region INativeWindow Members #region Bounds public Rectangle Bounds { get { return bounds; } set { // Note: the bounds variable is updated when the resize/move message arrives. Functions.SetWindowPos(window.WindowHandle, IntPtr.Zero, value.X, value.Y, value.Width, value.Height, 0); } } #endregion #region Location public Point Location { get { return Bounds.Location; } set { // Note: the bounds variable is updated when the resize/move message arrives. Functions.SetWindowPos(window.WindowHandle, IntPtr.Zero, value.X, value.Y, 0, 0, SetWindowPosFlags.NOSIZE); } } #endregion #region Size public Size Size { get { return Bounds.Size; } set { // Note: the bounds variable is updated when the resize/move message arrives. Functions.SetWindowPos(window.WindowHandle, IntPtr.Zero, 0, 0, value.Width, value.Height, SetWindowPosFlags.NOMOVE); } } #endregion #region ClientRectangle public Rectangle ClientRectangle { get { if (client_rectangle.Width == 0) client_rectangle.Width = 1; if (client_rectangle.Height == 0) client_rectangle.Height = 1; return client_rectangle; } set { ClientSize = value.Size; } } #endregion #region ClientSize public Size ClientSize { get { return ClientRectangle.Size; } set { WindowStyle style = (WindowStyle)Functions.GetWindowLong(window.WindowHandle, GetWindowLongOffsets.STYLE); Win32Rectangle rect = Win32Rectangle.From(value); Functions.AdjustWindowRect(ref rect, style, false); Size = new Size(rect.Width, rect.Height); } } #endregion #region Width public int Width { get { return ClientRectangle.Width; } set { ClientRectangle = new Rectangle(0, 0, value, Height); } } #endregion #region Height public int Height { get { return ClientRectangle.Height; } set { ClientRectangle = new Rectangle(0, 0, Width, value); } } #endregion #region X public int X { get { return Location.X; } set { Location = new Point(value, Y); } } #endregion #region Y public int Y { get { return Location.Y; } set { Location = new Point(X, value); } } #endregion #region Icon public Icon Icon { get { return icon; } set { if (value != icon) { icon = value; if (window.WindowHandle != IntPtr.Zero) { Functions.SendMessage(window.WindowHandle, WindowMessage.SETICON, (IntPtr)0, icon == null ? IntPtr.Zero : value.Handle); Functions.SendMessage(window.WindowHandle, WindowMessage.SETICON, (IntPtr)1, icon == null ? IntPtr.Zero : value.Handle); } IconChanged(this, EventArgs.Empty); } } } #endregion #region Focused public bool Focused { get { return focused; } } #endregion #region Title StringBuilder sb_title = new StringBuilder(256); public string Title { get { sb_title.Remove(0, sb_title.Length); if (Functions.GetWindowText(window.WindowHandle, sb_title, sb_title.Capacity) == 0) Debug.Print("Failed to retrieve window title (window:{0}, reason:{1}).", window.WindowHandle, Marshal.GetLastWin32Error()); return sb_title.ToString(); } set { if (Title != value) { if (!Functions.SetWindowText(window.WindowHandle, value)) Debug.Print("Failed to change window title (window:{0}, new title:{1}, reason:{2}).", window.WindowHandle, value, Marshal.GetLastWin32Error()); TitleChanged(this, EventArgs.Empty); } } } #endregion #region Visible public bool Visible { get { return Functions.IsWindowVisible(window.WindowHandle); } set { if (value != Visible) { if (value) { Functions.ShowWindow(window.WindowHandle, ShowWindowCommand.SHOW); if (invisible_since_creation) { Functions.BringWindowToTop(window.WindowHandle); Functions.SetForegroundWindow(window.WindowHandle); } } else if (!value) { Functions.ShowWindow(window.WindowHandle, ShowWindowCommand.HIDE); } VisibleChanged(this, EventArgs.Empty); } } } #endregion #region Exists public bool Exists { get { return exists; } } #endregion #region CursorVisible public bool CursorVisible { get { return cursor_visible_count >= 0; } // Not used set { if (value && cursor_visible_count < 0) { do { cursor_visible_count = Functions.ShowCursor(true); } while (cursor_visible_count < 0); UngrabCursor(); } else if (!value && cursor_visible_count >= 0) { do { cursor_visible_count = Functions.ShowCursor(false); } while (cursor_visible_count >= 0); GrabCursor(); } } } #endregion #region Close public void Close() { Functions.PostMessage(window.WindowHandle, WindowMessage.CLOSE, IntPtr.Zero, IntPtr.Zero); } #endregion #region public WindowState WindowState public WindowState WindowState { get { return windowState; } set { if (WindowState == value) return; ShowWindowCommand command = 0; bool exiting_fullscreen = false; borderless_maximized_window_state = false; switch (value) { case WindowState.Normal: command = ShowWindowCommand.RESTORE; // If we are leaving fullscreen mode we need to restore the border. if (WindowState == WindowState.Fullscreen) exiting_fullscreen = true; break; case WindowState.Maximized: // Note: if we use the MAXIMIZE command and the window border is Hidden (i.e. WS_POPUP), // we will enter fullscreen mode - we don't want that! As a workaround, we'll resize the window // manually to cover the whole working area of the current monitor. // Reset state to avoid strange interactions with fullscreen/minimized windows. ResetWindowState(); if (WindowBorder == WindowBorder.Hidden) { IntPtr current_monitor = Functions.MonitorFromWindow(window.WindowHandle, MonitorFrom.Nearest); MonitorInfo info = new MonitorInfo(); info.Size = MonitorInfo.SizeInBytes; Functions.GetMonitorInfo(current_monitor, ref info); previous_bounds = Bounds; borderless_maximized_window_state = true; Bounds = info.Work.ToRectangle(); } else { command = ShowWindowCommand.MAXIMIZE; } break; case WindowState.Minimized: command = ShowWindowCommand.MINIMIZE; break; case WindowState.Fullscreen: // We achieve fullscreen by hiding the window border and sending the MAXIMIZE command. // We cannot use the WindowState.Maximized directly, as that will not send the MAXIMIZE // command for windows with hidden borders. // Reset state to avoid strange side-effects from maximized/minimized windows. ResetWindowState(); previous_bounds = Bounds; previous_window_border = WindowBorder; HideBorder(); command = ShowWindowCommand.MAXIMIZE; Functions.SetForegroundWindow(window.WindowHandle); break; } if (command != 0) Functions.ShowWindow(window.WindowHandle, command); // Restore previous window border or apply pending border change when leaving fullscreen mode. if (exiting_fullscreen) { RestoreBorder(); } // Restore previous window size/location if necessary if (command == ShowWindowCommand.RESTORE && previous_bounds != Rectangle.Empty) { Bounds = previous_bounds; previous_bounds = Rectangle.Empty; } } } #endregion #region public WindowBorder WindowBorder public WindowBorder WindowBorder { get { return windowBorder; } set { // Do not allow border changes during fullscreen mode. // Defer them for when we leave fullscreen. if (WindowState == WindowState.Fullscreen) { deferred_window_border = value; return; } if (windowBorder == value) return; // We wish to avoid making an invisible window visible just to change the border. // However, it's a good idea to make a visible window invisible temporarily, to // avoid garbage caused by the border change. bool was_visible = Visible; // To ensure maximized/minimized windows work correctly, reset state to normal, // change the border, then go back to maximized/minimized. WindowState state = WindowState; ResetWindowState(); WindowStyle style = WindowStyle.ClipChildren | WindowStyle.ClipSiblings; switch (value) { case WindowBorder.Resizable: style |= WindowStyle.OverlappedWindow; break; case WindowBorder.Fixed: style |= WindowStyle.OverlappedWindow & ~(WindowStyle.ThickFrame | WindowStyle.MaximizeBox | WindowStyle.SizeBox); break; case WindowBorder.Hidden: style |= WindowStyle.Popup; break; } // Make sure client size doesn't change when changing the border style. Size client_size = ClientSize; Win32Rectangle rect = Win32Rectangle.From(client_size); Functions.AdjustWindowRectEx(ref rect, style, false, ParentStyleEx); // This avoids leaving garbage on the background window. if (was_visible) Visible = false; Functions.SetWindowLong(window.WindowHandle, GetWindowLongOffsets.STYLE, (IntPtr)(int)style); Functions.SetWindowPos(window.WindowHandle, IntPtr.Zero, 0, 0, rect.Width, rect.Height, SetWindowPosFlags.NOMOVE | SetWindowPosFlags.NOZORDER | SetWindowPosFlags.FRAMECHANGED); // Force window to redraw update its borders, but only if it's // already visible (invisible windows will change borders when // they become visible, so no need to make them visiable prematurely). if (was_visible) Visible = true; WindowState = state; WindowBorderChanged(this, EventArgs.Empty); } } #endregion #region PointToClient public Point PointToClient(Point point) { if (!Functions.ScreenToClient(window.WindowHandle, ref point)) throw new InvalidOperationException(String.Format( "Could not convert point {0} from screen to client coordinates. Windows error: {1}", point.ToString(), Marshal.GetLastWin32Error())); return point; } #endregion #region PointToScreen public Point PointToScreen(Point point) { if (!Functions.ClientToScreen(window.WindowHandle, ref point)) throw new InvalidOperationException(String.Format( "Could not convert point {0} from screen to client coordinates. Windows error: {1}", point.ToString(), Marshal.GetLastWin32Error())); return point; } #endregion #region Events public event EventHandler<EventArgs> Move = delegate { }; public event EventHandler<EventArgs> Resize = delegate { }; public event EventHandler<System.ComponentModel.CancelEventArgs> Closing = delegate { }; public event EventHandler<EventArgs> Closed = delegate { }; public event EventHandler<EventArgs> Disposed = delegate { }; public event EventHandler<EventArgs> IconChanged = delegate { }; public event EventHandler<EventArgs> TitleChanged = delegate { }; public event EventHandler<EventArgs> VisibleChanged = delegate { }; public event EventHandler<EventArgs> FocusedChanged = delegate { }; public event EventHandler<EventArgs> WindowBorderChanged = delegate { }; public event EventHandler<EventArgs> WindowStateChanged = delegate { }; public event EventHandler<OpenTK.Input.KeyboardKeyEventArgs> KeyDown = delegate { }; public event EventHandler<KeyPressEventArgs> KeyPress = delegate { }; public event EventHandler<OpenTK.Input.KeyboardKeyEventArgs> KeyUp = delegate { }; public event EventHandler<EventArgs> MouseEnter = delegate { }; public event EventHandler<EventArgs> MouseLeave = delegate { }; #endregion #endregion #region INativeGLWindow Members #region public void ProcessEvents() private int ret; MSG msg; public void ProcessEvents() { while (!IsIdle) { ret = Functions.GetMessage(ref msg, window.WindowHandle, 0, 0); if (ret == -1) { throw new PlatformException(String.Format( "An error happened while processing the message queue. Windows error: {0}", Marshal.GetLastWin32Error())); } Functions.TranslateMessage(ref msg); Functions.DispatchMessage(ref msg); } } #endregion #region public IInputDriver InputDriver public IInputDriver InputDriver { get { return this; } } #endregion #region public IWindowInfo WindowInfo public IWindowInfo WindowInfo { get { return child_window; } } #endregion #endregion #region IInputDriver Members public void Poll() { joystick_driver.Poll(); } #endregion #region IKeyboardDriver Members public IList<KeyboardDevice> Keyboard { get { return keyboards; } } public KeyboardState GetState() { throw new NotImplementedException(); } public KeyboardState GetState(int index) { throw new NotImplementedException(); } #endregion #region IMouseDriver Members public IList<MouseDevice> Mouse { get { return mice; } } #endregion #region IJoystickDriver Members public IList<JoystickDevice> Joysticks { get { return joystick_driver.Joysticks; } } #endregion #region IDisposable Members public void Dispose() { this.Dispose(true); GC.SuppressFinalize(this); } void Dispose(bool calledManually) { if (!disposed) { if (calledManually) { // Safe to clean managed resources DestroyWindow(); if (Icon != null) Icon.Dispose(); } else { Debug.Print("[Warning] INativeWindow leaked ({0}). Did you forget to call INativeWindow.Dispose()?", this); } Disposed(this, EventArgs.Empty); disposed = true; } } ~WinGLNative() { Dispose(false); } #endregion } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Runtime.InteropServices; using System.Drawing; // for documentation: // using System.Windows.Forms; namespace Microsoft.VisualStudio.CodeTools { /// <summary> /// Interface for property panes. /// </summary> /// <remarks> /// Implement this interface to display property pages for /// Visual Studio projects. This interface is usually implemented as part of a /// <see cref="System.Windows.Forms.UserControl">UserControl</see> in order to use /// the convenient GUI designer to draw the property pane: /// <code> /// [Guid("00000000-8795-4fe7-8E51-2904E8B5F27B")] /// public partial class MyPropertyPane : UserControl /// , Microsoft.VisualStudio.CodeTools.IPropertyPane</code> /// It is important to give the implementation class a guid (we call it {myguid})and to make it visible /// from COM, i.e. write in your <c>AssemblyInfo.cs</c>: /// <code>[assembly: ComVisible(false)]</code> /// The implementation class should also be registered as a COM class: /// <code> /// HKCR\ /// CLSID\ /// {myguid}\ /// (default) =Microsoft.VisualStudio.Contracts.PropertyPane /// InprocServer32\ /// (default) =mscoree.dll /// Assembly =MyPropertyPage, Version=1.0.0.0, Culture=neutral, PublicKeyToken=da8be8918709caaf /// Class = [full namespacepath].MyPropertyPane /// CodeBase =file:///c:/MyPropertyPage/bin/Debug/MyPropertyPage.dll /// RuntimeVersion=v2.0.50215 /// ThreadingModel=Both /// ProgId\ /// (default) =Microsoft.VisualStudio.Contracts.PropertyPane /// Implemented Categories\ /// {62C8FE65-4EBB-45e7-B440-6E39B2CDBF29}\</code> /// Next, we can register the propertypane as a CodeTools property page. First, we generate /// an extra guid to identify the property pane, the property page id '{pageid}'. We register it now under /// the CodeTools property pages: /// <code> /// {vsroot}\ /// CodeTools\ /// {mytool}\ /// PropertyPages\ /// {pageid}\ /// clsid = {myguid} /// category= {category} /// Projects\ /// CSharp="" /// VisualBasic="" /// FSharp=""</code> /// Here, {vsroot} is the Visual Studio registry root, for example <c>HKLM\Microsoft\VisualStudio\8.0</c>. /// The {mytool} is your own tool name, for example <c>FxCop</c>. Under the <c>PropertyPages</c> /// key, we associate the property page id's with the classes that implement the <see cref="IPropertyPane">IPropertyPane</see> interface. /// The {category} is the kind fo property page you need: it is either "ConfigPropertyPages" or "CommonPropertyPages" depending whether your /// property page is configuration dependent or not. The values under the "Projects" key specify for /// which projects you want to be registered; if wanted you can specify a project guid as a value /// instead of the language name. The special "CodeToolsUpdate" program looks at these /// entries and registers your property page with those projects (automatically taking care for special cases /// for FxCop for example. /// </remarks> [Guid("9F78A659-14A9-46d1-8715-4FDB037D5F86")] public interface IPropertyPane { #region Logical members /// <summary> /// The title of the property page. /// </summary> string Title { get; } /// <summary> /// The helpfile associated with the property page. /// </summary> string HelpFile { get; } /// <summary> /// The help context. /// </summary> int HelpContext { get; } /// <summary> /// Set the host of the property pane. /// </summary> /// <remarks> /// This method is called at initialization by the host itself /// to allow the property pane to notify the host on property changes. /// </remarks> /// <param name="host"></param> void SetHost(IPropertyPaneHost host); /// <summary> /// Load the page properties from a <see cref="IPropertyStorage">storage</see> /// for a specific set of configurations. Called when the property page is loaded. /// </summary> /// <remarks> /// For configuration independent pages, the configuration names are a single empty /// string (<c>""</c>). /// </remarks> /// <param name="configNames">The selected configuration names.</param> /// <param name="storage">The <see cref="IPropertyStorage">property storage</see>.</param> void LoadProperties(string[] configNames, IPropertyStorage storage); /// <summary> /// Save the page properties to a <see cref="IPropertyStorage">property storage</see> /// for a specific set of configurations. Called when the property page is closed /// and <see cref="IsDirty">dirty</see>. /// </summary> /// <remarks> /// For configuration independent pages, the configuration names are a single empty /// string (<c>""</c>). /// </remarks> /// <param name="configNames">The selected configuration names.</param> /// <param name="storage">The <see cref="IPropertyStorage">property storage</see>.</param> void SaveProperties(string[] configNames, IPropertyStorage storage); #endregion #region UI members // these are usually implemented already by a UserControl /// <summary> /// The windows handle of the property pane. /// </summary> /// <remarks> /// Usually implemented by an inherited <see cref="System.Windows.Forms.UserControl">UserControl</see>. /// </remarks> IntPtr Handle { get; } /// <summary> /// The pixel size of the property pane. /// </summary> /// <remarks> /// Usually implemented by an inherited <see cref="System.Windows.Forms.UserControl">UserControl</see>. /// </remarks> Size Size { get; set; } /// <summary> /// The location of the property pane. /// </summary> /// <remarks> /// Usually implemented by an inherited <see cref="System.Windows.Forms.UserControl">UserControl</see>. /// </remarks> Point Location { get; set; } /// <summary> /// Show the property pane. /// </summary> /// <remarks> /// Usually implemented by an inherited <see cref="System.Windows.Forms.UserControl">UserControl</see>. /// </remarks> void Show(); /// <summary> /// Hide the property pane. /// </summary> /// <remarks> /// Usually implemented by an inherited <see cref="System.Windows.Forms.UserControl">UserControl</see>. /// </remarks> void Hide(); #endregion } /// <summary> /// Abstract interface to property page storage. /// </summary> /// <remarks> /// The properties can be stored per user, or per project (group). Each of /// properties are identified by a name and can be accessed by the MSBuild /// system (and for example passed to MSBuild tasks). /// /// The property storage will automatically use 'primitive' properties directly /// stored on the project object itself if possible. Otherwise, it will store the /// properties in the associated project build storage. /// </remarks> [Guid("38A3802C-F18A-4eac-A7D9-191AD5F38B42")] public interface IPropertyStorage { /// <summary> /// Get the (common) value of a property for a set of configurations. /// </summary> /// <param name="perUser">Is this property stored per user?</param> /// <param name="configNames">The set of configuration names.</param> /// <param name="propertyName">The name of the property.</param> /// <param name="defaultValue">The default value of the property, this can not be <c>null</c>.</param> /// <returns>If the value of the property is the same (under <see cref="Object.Equals">Equals</see>) /// for configuration, this value is returned. Otherwise, the method returns <c>null</c> (i.e. an /// indeterminate value).</returns> object GetProperties(bool perUser, string[] configNames, string propertyName, object defaultValue); /// <summary> /// Set the value of a property for multiple configurations. /// </summary> /// <param name="perUser">Is this property stored per user?</param> /// <param name="configNames">The set of configuration names.</param> /// <param name="propertyName">The name of the property.</param> /// <param name="value">The value of the property.</param> /// <returns>0 on success, otherwise an <c>HRESULT</c> error code.</returns> int SetProperties(bool perUser, string[] configNames, string propertyName, object value); /// <summary> /// Get a value of a property for a given configuration. /// </summary> /// <param name="perUser">Is this property stored per user?</param> /// <param name="configName">The configuration name, use <c>""</c> for a configuration independent property.</param> /// <param name="propertyName">The name of the property.</param> /// <param name="defaultValue">The default value of the property, this can not be <c>null</c>.</param> /// <returns>The value of the property, or the <c>defaultValue</c> if it /// could not be found (or read, or cast to the <c>defaultValue</c> type). /// This method never returns <c>null</c>.</returns> object GetProperty(bool perUser, string configName, string propertyName, object defaultValue); /// <summary> /// Set the value of a property for a given configuration. /// </summary> /// <param name="perUser">Is this property stored per user?</param> /// <param name="configName">The configuration name, use <c>""</c> for a configuration independent property.</param> /// <param name="propertyName">The name of the property.</param> /// <param name="value">The value of the property.</param> /// <returns>0 on success, otherwise an <c>HRESULT</c> error code.</returns> int SetProperty(bool perUser, string configName, string propertyName, object value); /// <summary> /// Get a value of a property for a given configuration. /// </summary> /// <param name="perUser">Is this property stored per user?</param> /// <param name="configName">The configuration name, use <c>""</c> for a configuration independent property.</param> /// <param name="propertyName">The name of the property.</param> /// <param name="defaultValue">The default value of the property.</param> /// <param name="found">Set to true if the property was found</param> /// <returns>The value of the property, or the <c>defaultValue</c> if it /// could not be found (or read, or cast to the <c>defaultValue</c> type). T GetProperty<T>(bool perUser, string configName, string propertyName, T defaultValue, out bool found); /// <summary> /// Get the (common) value of a property for a set of configurations. /// </summary> /// <param name="perUser">Is this property stored per user?</param> /// <param name="configNames">The set of configuration names.</param> /// <param name="propertyName">The name of the property.</param> /// <param name="defaultValue">The default value of the property that is assumed if the property was not explicitly set</param> /// <param name="anyFound">Set to true if at least one the properties was explicitly set</param> /// <param name="indeterminate">Set to true if the configurations differed in their values</param> /// <returns>If the value of the property is the same for each configuration, this value is returned. /// Otherwise, the method returns the default value. Properties that were not found get a default value, so if none of the /// properties was set, the default value is also returned. This case can be distinguished through the anyfound parameter.</returns> T GetProperties<T>(bool perUser, string[] configNames, string propertyName, T defaultValue, out bool anyFound, out bool indeterminate) where T : IComparable<T>; /// <summary> /// Remove a property for a given configuration /// </summary> /// <param name="perUser">Was this property stored per user?</param> /// <param name="configName">The configuration name, use <c>""</c> for a configuration independent property</param> /// <param name="propertyName">The name of the property</param> /// <returns>0 on success, an <c>HRESULT</c> error code otherwise</returns> int RemoveProperty(bool perUser, string configName, string propertyName); } /// <summary> /// Abstract interface to the host of a <see href="IPropertyPane">property pane</see>. /// </summary> /// <remarks> /// This interface is passed to an <see href="IPropertyPane">property pane</see> who /// calls this interface to notify the host when the properties change due to user /// UI actions. /// </remarks> [Guid("D382C8FB-487E-4b00-ACBE-35CBB86B5337")] public interface IPropertyPaneHost { /// <summary> /// Notify the property pane host that the properties have changed (due to a user action). /// </summary> /// <remarks> /// Calling this method ensures that properties are properly saved through a call to /// <see cref="IPropertyPane.SaveProperties">IPropertyPane.SaveProperties</see>. /// </remarks> void PropertiesChanged(); } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure.Management.SiteRecovery; using Microsoft.Azure.Management.SiteRecovery.Models; namespace Microsoft.Azure.Management.SiteRecovery { public static partial class ProtectionContainerMappingOperationsExtensions { /// <summary> /// Configures protection for given protection container /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IProtectionContainerMappingOperations. /// </param> /// <param name='fabricName'> /// Required. Fabric name. /// </param> /// <param name='protectionContainerName'> /// Required. Protection container name. /// </param> /// <param name='mappingName'> /// Required. Container mapping name. /// </param> /// <param name='input'> /// Required. Create mapping input. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static LongRunningOperationResponse BeginConfigureProtection(this IProtectionContainerMappingOperations operations, string fabricName, string protectionContainerName, string mappingName, CreateProtectionContainerMappingInput input, CustomRequestHeaders customRequestHeaders) { return Task.Factory.StartNew((object s) => { return ((IProtectionContainerMappingOperations)s).BeginConfigureProtectionAsync(fabricName, protectionContainerName, mappingName, input, customRequestHeaders); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Configures protection for given protection container /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IProtectionContainerMappingOperations. /// </param> /// <param name='fabricName'> /// Required. Fabric name. /// </param> /// <param name='protectionContainerName'> /// Required. Protection container name. /// </param> /// <param name='mappingName'> /// Required. Container mapping name. /// </param> /// <param name='input'> /// Required. Create mapping input. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static Task<LongRunningOperationResponse> BeginConfigureProtectionAsync(this IProtectionContainerMappingOperations operations, string fabricName, string protectionContainerName, string mappingName, CreateProtectionContainerMappingInput input, CustomRequestHeaders customRequestHeaders) { return operations.BeginConfigureProtectionAsync(fabricName, protectionContainerName, mappingName, input, customRequestHeaders, CancellationToken.None); } /// <summary> /// Purges protection for given protection container /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IProtectionContainerMappingOperations. /// </param> /// <param name='fabricName'> /// Required. Fabric name. /// </param> /// <param name='protectionContainerName'> /// Required. Protection container name. /// </param> /// <param name='mappingName'> /// Required. Protection container mapping name. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static LongRunningOperationResponse BeginPurgeProtection(this IProtectionContainerMappingOperations operations, string fabricName, string protectionContainerName, string mappingName, CustomRequestHeaders customRequestHeaders) { return Task.Factory.StartNew((object s) => { return ((IProtectionContainerMappingOperations)s).BeginPurgeProtectionAsync(fabricName, protectionContainerName, mappingName, customRequestHeaders); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Purges protection for given protection container /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IProtectionContainerMappingOperations. /// </param> /// <param name='fabricName'> /// Required. Fabric name. /// </param> /// <param name='protectionContainerName'> /// Required. Protection container name. /// </param> /// <param name='mappingName'> /// Required. Protection container mapping name. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static Task<LongRunningOperationResponse> BeginPurgeProtectionAsync(this IProtectionContainerMappingOperations operations, string fabricName, string protectionContainerName, string mappingName, CustomRequestHeaders customRequestHeaders) { return operations.BeginPurgeProtectionAsync(fabricName, protectionContainerName, mappingName, customRequestHeaders, CancellationToken.None); } /// <summary> /// Unconfigures protection for given protection container /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IProtectionContainerMappingOperations. /// </param> /// <param name='fabricName'> /// Required. Fabric name. /// </param> /// <param name='protectionContainerName'> /// Required. Protection container name. /// </param> /// <param name='mappingName'> /// Required. Container mapping name. /// </param> /// <param name='input'> /// Required. Unconfigure protection input. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static LongRunningOperationResponse BeginUnconfigureProtection(this IProtectionContainerMappingOperations operations, string fabricName, string protectionContainerName, string mappingName, RemoveProtectionContainerMappingInput input, CustomRequestHeaders customRequestHeaders) { return Task.Factory.StartNew((object s) => { return ((IProtectionContainerMappingOperations)s).BeginUnconfigureProtectionAsync(fabricName, protectionContainerName, mappingName, input, customRequestHeaders); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Unconfigures protection for given protection container /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IProtectionContainerMappingOperations. /// </param> /// <param name='fabricName'> /// Required. Fabric name. /// </param> /// <param name='protectionContainerName'> /// Required. Protection container name. /// </param> /// <param name='mappingName'> /// Required. Container mapping name. /// </param> /// <param name='input'> /// Required. Unconfigure protection input. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static Task<LongRunningOperationResponse> BeginUnconfigureProtectionAsync(this IProtectionContainerMappingOperations operations, string fabricName, string protectionContainerName, string mappingName, RemoveProtectionContainerMappingInput input, CustomRequestHeaders customRequestHeaders) { return operations.BeginUnconfigureProtectionAsync(fabricName, protectionContainerName, mappingName, input, customRequestHeaders, CancellationToken.None); } /// <summary> /// Configures protection for given protection container /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IProtectionContainerMappingOperations. /// </param> /// <param name='fabricName'> /// Required. Fabric name. /// </param> /// <param name='protectionContainerName'> /// Required. Protection container name. /// </param> /// <param name='mappingName'> /// Required. Container mapping name. /// </param> /// <param name='input'> /// Required. Create mapping input. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static LongRunningOperationResponse ConfigureProtection(this IProtectionContainerMappingOperations operations, string fabricName, string protectionContainerName, string mappingName, CreateProtectionContainerMappingInput input, CustomRequestHeaders customRequestHeaders) { return Task.Factory.StartNew((object s) => { return ((IProtectionContainerMappingOperations)s).ConfigureProtectionAsync(fabricName, protectionContainerName, mappingName, input, customRequestHeaders); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Configures protection for given protection container /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IProtectionContainerMappingOperations. /// </param> /// <param name='fabricName'> /// Required. Fabric name. /// </param> /// <param name='protectionContainerName'> /// Required. Protection container name. /// </param> /// <param name='mappingName'> /// Required. Container mapping name. /// </param> /// <param name='input'> /// Required. Create mapping input. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static Task<LongRunningOperationResponse> ConfigureProtectionAsync(this IProtectionContainerMappingOperations operations, string fabricName, string protectionContainerName, string mappingName, CreateProtectionContainerMappingInput input, CustomRequestHeaders customRequestHeaders) { return operations.ConfigureProtectionAsync(fabricName, protectionContainerName, mappingName, input, customRequestHeaders, CancellationToken.None); } /// <summary> /// Get the protected container mapping by name. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IProtectionContainerMappingOperations. /// </param> /// <param name='fabricName'> /// Required. Fabric Name. /// </param> /// <param name='protectionContainerName'> /// Required. Protection Container Name. /// </param> /// <param name='mappingName'> /// Required. Container mapping name. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// The response model for the Protection Container mapping object. /// </returns> public static ProtectionContainerMappingResponse Get(this IProtectionContainerMappingOperations operations, string fabricName, string protectionContainerName, string mappingName, CustomRequestHeaders customRequestHeaders) { return Task.Factory.StartNew((object s) => { return ((IProtectionContainerMappingOperations)s).GetAsync(fabricName, protectionContainerName, mappingName, customRequestHeaders); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get the protected container mapping by name. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IProtectionContainerMappingOperations. /// </param> /// <param name='fabricName'> /// Required. Fabric Name. /// </param> /// <param name='protectionContainerName'> /// Required. Protection Container Name. /// </param> /// <param name='mappingName'> /// Required. Container mapping name. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// The response model for the Protection Container mapping object. /// </returns> public static Task<ProtectionContainerMappingResponse> GetAsync(this IProtectionContainerMappingOperations operations, string fabricName, string protectionContainerName, string mappingName, CustomRequestHeaders customRequestHeaders) { return operations.GetAsync(fabricName, protectionContainerName, mappingName, customRequestHeaders, CancellationToken.None); } /// <summary> /// The Get Operation Status operation returns the status of the /// specified operation. After calling an asynchronous operation, you /// can call Get Operation Status to determine whether the operation /// has succeeded, failed, or is still in progress. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IProtectionContainerMappingOperations. /// </param> /// <param name='operationStatusLink'> /// Required. Location value returned by the Begin operation. /// </param> /// <returns> /// Service response for operation which change status of mapping for /// protection container. /// </returns> public static MappingOperationResponse GetConfigureProtectionStatus(this IProtectionContainerMappingOperations operations, string operationStatusLink) { return Task.Factory.StartNew((object s) => { return ((IProtectionContainerMappingOperations)s).GetConfigureProtectionStatusAsync(operationStatusLink); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The Get Operation Status operation returns the status of the /// specified operation. After calling an asynchronous operation, you /// can call Get Operation Status to determine whether the operation /// has succeeded, failed, or is still in progress. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IProtectionContainerMappingOperations. /// </param> /// <param name='operationStatusLink'> /// Required. Location value returned by the Begin operation. /// </param> /// <returns> /// Service response for operation which change status of mapping for /// protection container. /// </returns> public static Task<MappingOperationResponse> GetConfigureProtectionStatusAsync(this IProtectionContainerMappingOperations operations, string operationStatusLink) { return operations.GetConfigureProtectionStatusAsync(operationStatusLink, CancellationToken.None); } /// <summary> /// The Get Operation Status operation returns the status of the /// specified operation. After calling an asynchronous operation, you /// can call Get Operation Status to determine whether the operation /// has succeeded, failed, or is still in progress. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IProtectionContainerMappingOperations. /// </param> /// <param name='operationStatusLink'> /// Required. Location value returned by the Begin operation. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static LongRunningOperationResponse GetPurgeProtectionStatus(this IProtectionContainerMappingOperations operations, string operationStatusLink) { return Task.Factory.StartNew((object s) => { return ((IProtectionContainerMappingOperations)s).GetPurgeProtectionStatusAsync(operationStatusLink); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The Get Operation Status operation returns the status of the /// specified operation. After calling an asynchronous operation, you /// can call Get Operation Status to determine whether the operation /// has succeeded, failed, or is still in progress. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IProtectionContainerMappingOperations. /// </param> /// <param name='operationStatusLink'> /// Required. Location value returned by the Begin operation. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static Task<LongRunningOperationResponse> GetPurgeProtectionStatusAsync(this IProtectionContainerMappingOperations operations, string operationStatusLink) { return operations.GetPurgeProtectionStatusAsync(operationStatusLink, CancellationToken.None); } /// <summary> /// The Get Operation Status operation returns the status of the /// specified operation. After calling an asynchronous operation, you /// can call Get Operation Status to determine whether the operation /// has succeeded, failed, or is still in progress. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IProtectionContainerMappingOperations. /// </param> /// <param name='operationStatusLink'> /// Required. Location value returned by the Begin operation. /// </param> /// <returns> /// Service response for operation which change status of mapping for /// protection container. /// </returns> public static MappingOperationResponse GetUnconfigureProtectionStatus(this IProtectionContainerMappingOperations operations, string operationStatusLink) { return Task.Factory.StartNew((object s) => { return ((IProtectionContainerMappingOperations)s).GetUnconfigureProtectionStatusAsync(operationStatusLink); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The Get Operation Status operation returns the status of the /// specified operation. After calling an asynchronous operation, you /// can call Get Operation Status to determine whether the operation /// has succeeded, failed, or is still in progress. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IProtectionContainerMappingOperations. /// </param> /// <param name='operationStatusLink'> /// Required. Location value returned by the Begin operation. /// </param> /// <returns> /// Service response for operation which change status of mapping for /// protection container. /// </returns> public static Task<MappingOperationResponse> GetUnconfigureProtectionStatusAsync(this IProtectionContainerMappingOperations operations, string operationStatusLink) { return operations.GetUnconfigureProtectionStatusAsync(operationStatusLink, CancellationToken.None); } /// <summary> /// Get the list of all protection container mapping for the given /// container under a fabric. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IProtectionContainerMappingOperations. /// </param> /// <param name='fabricName'> /// Required. Fabric Unique name. /// </param> /// <param name='protectionContainerName'> /// Required. Protection Container Name. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// The definition of a Protection Container mapping collection object. /// </returns> public static ProtectionContainerMappingListResponse List(this IProtectionContainerMappingOperations operations, string fabricName, string protectionContainerName, CustomRequestHeaders customRequestHeaders) { return Task.Factory.StartNew((object s) => { return ((IProtectionContainerMappingOperations)s).ListAsync(fabricName, protectionContainerName, customRequestHeaders); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get the list of all protection container mapping for the given /// container under a fabric. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IProtectionContainerMappingOperations. /// </param> /// <param name='fabricName'> /// Required. Fabric Unique name. /// </param> /// <param name='protectionContainerName'> /// Required. Protection Container Name. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// The definition of a Protection Container mapping collection object. /// </returns> public static Task<ProtectionContainerMappingListResponse> ListAsync(this IProtectionContainerMappingOperations operations, string fabricName, string protectionContainerName, CustomRequestHeaders customRequestHeaders) { return operations.ListAsync(fabricName, protectionContainerName, customRequestHeaders, CancellationToken.None); } /// <summary> /// Get the list of all protection container mapping under a vault. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IProtectionContainerMappingOperations. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// The definition of a Protection Container mapping collection object. /// </returns> public static ProtectionContainerMappingListResponse ListAll(this IProtectionContainerMappingOperations operations, CustomRequestHeaders customRequestHeaders) { return Task.Factory.StartNew((object s) => { return ((IProtectionContainerMappingOperations)s).ListAllAsync(customRequestHeaders); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get the list of all protection container mapping under a vault. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IProtectionContainerMappingOperations. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// The definition of a Protection Container mapping collection object. /// </returns> public static Task<ProtectionContainerMappingListResponse> ListAllAsync(this IProtectionContainerMappingOperations operations, CustomRequestHeaders customRequestHeaders) { return operations.ListAllAsync(customRequestHeaders, CancellationToken.None); } /// <summary> /// Purges protection for given protection container /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IProtectionContainerMappingOperations. /// </param> /// <param name='fabricName'> /// Required. Fabric name. /// </param> /// <param name='protectionContainerName'> /// Required. Protection container name. /// </param> /// <param name='mappingName'> /// Required. Protection container mapping name. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static LongRunningOperationResponse PurgeProtection(this IProtectionContainerMappingOperations operations, string fabricName, string protectionContainerName, string mappingName, CustomRequestHeaders customRequestHeaders) { return Task.Factory.StartNew((object s) => { return ((IProtectionContainerMappingOperations)s).PurgeProtectionAsync(fabricName, protectionContainerName, mappingName, customRequestHeaders); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Purges protection for given protection container /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IProtectionContainerMappingOperations. /// </param> /// <param name='fabricName'> /// Required. Fabric name. /// </param> /// <param name='protectionContainerName'> /// Required. Protection container name. /// </param> /// <param name='mappingName'> /// Required. Protection container mapping name. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static Task<LongRunningOperationResponse> PurgeProtectionAsync(this IProtectionContainerMappingOperations operations, string fabricName, string protectionContainerName, string mappingName, CustomRequestHeaders customRequestHeaders) { return operations.PurgeProtectionAsync(fabricName, protectionContainerName, mappingName, customRequestHeaders, CancellationToken.None); } /// <summary> /// Unconfigures protection for given protection container /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IProtectionContainerMappingOperations. /// </param> /// <param name='fabricName'> /// Required. Fabric name. /// </param> /// <param name='protectionContainerName'> /// Required. Protection container name. /// </param> /// <param name='mappingName'> /// Required. Container mapping name. /// </param> /// <param name='input'> /// Required. Unconfigure protection input. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static LongRunningOperationResponse UnconfigureProtection(this IProtectionContainerMappingOperations operations, string fabricName, string protectionContainerName, string mappingName, RemoveProtectionContainerMappingInput input, CustomRequestHeaders customRequestHeaders) { return Task.Factory.StartNew((object s) => { return ((IProtectionContainerMappingOperations)s).UnconfigureProtectionAsync(fabricName, protectionContainerName, mappingName, input, customRequestHeaders); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Unconfigures protection for given protection container /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IProtectionContainerMappingOperations. /// </param> /// <param name='fabricName'> /// Required. Fabric name. /// </param> /// <param name='protectionContainerName'> /// Required. Protection container name. /// </param> /// <param name='mappingName'> /// Required. Container mapping name. /// </param> /// <param name='input'> /// Required. Unconfigure protection input. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static Task<LongRunningOperationResponse> UnconfigureProtectionAsync(this IProtectionContainerMappingOperations operations, string fabricName, string protectionContainerName, string mappingName, RemoveProtectionContainerMappingInput input, CustomRequestHeaders customRequestHeaders) { return operations.UnconfigureProtectionAsync(fabricName, protectionContainerName, mappingName, input, customRequestHeaders, CancellationToken.None); } } }
using System; using System.Collections.Generic; using System.Data; using System.Diagnostics; using System.Globalization; using System.Linq; using Nop.Core; using Nop.Core.Caching; using Nop.Core.Data; using Nop.Core.Domain.Blogs; using Nop.Core.Domain.Catalog; using Nop.Core.Domain.Common; using Nop.Core.Domain.Customers; using Nop.Core.Domain.Forums; using Nop.Core.Domain.News; using Nop.Core.Domain.Orders; using Nop.Core.Domain.Polls; using Nop.Core.Domain.Shipping; using Nop.Data; using Nop.Services.Common; using Nop.Services.Events; namespace Nop.Services.Customers { /// <summary> /// Customer service /// </summary> public partial class CustomerService : ICustomerService { #region Constants /// <summary> /// Key for caching /// </summary> /// <remarks> /// {0} : show hidden records? /// </remarks> private const string CUSTOMERROLES_ALL_KEY = "Nop.customerrole.all-{0}"; /// <summary> /// Key for caching /// </summary> /// <remarks> /// {0} : system name /// </remarks> private const string CUSTOMERROLES_BY_SYSTEMNAME_KEY = "Nop.customerrole.systemname-{0}"; /// <summary> /// Key pattern to clear cache /// </summary> private const string CUSTOMERROLES_PATTERN_KEY = "Nop.customerrole."; #endregion #region Fields private readonly IRepository<Customer> _customerRepository; private readonly IRepository<CustomerPassword> _customerPasswordRepository; private readonly IRepository<CustomerRole> _customerRoleRepository; private readonly IRepository<GenericAttribute> _gaRepository; private readonly IRepository<Order> _orderRepository; private readonly IRepository<ForumPost> _forumPostRepository; private readonly IRepository<ForumTopic> _forumTopicRepository; private readonly IRepository<BlogComment> _blogCommentRepository; private readonly IRepository<NewsComment> _newsCommentRepository; private readonly IRepository<PollVotingRecord> _pollVotingRecordRepository; private readonly IRepository<ProductReview> _productReviewRepository; private readonly IRepository<ProductReviewHelpfulness> _productReviewHelpfulnessRepository; private readonly IGenericAttributeService _genericAttributeService; private readonly IDataProvider _dataProvider; private readonly IDbContext _dbContext; private readonly ICacheManager _cacheManager; private readonly IEventPublisher _eventPublisher; private readonly CustomerSettings _customerSettings; private readonly CommonSettings _commonSettings; #endregion #region Ctor public CustomerService(ICacheManager cacheManager, IRepository<Customer> customerRepository, IRepository<CustomerPassword> customerPasswordRepository, IRepository<CustomerRole> customerRoleRepository, IRepository<GenericAttribute> gaRepository, IRepository<Order> orderRepository, IRepository<ForumPost> forumPostRepository, IRepository<ForumTopic> forumTopicRepository, IRepository<BlogComment> blogCommentRepository, IRepository<NewsComment> newsCommentRepository, IRepository<PollVotingRecord> pollVotingRecordRepository, IRepository<ProductReview> productReviewRepository, IRepository<ProductReviewHelpfulness> productReviewHelpfulnessRepository, IGenericAttributeService genericAttributeService, IDataProvider dataProvider, IDbContext dbContext, IEventPublisher eventPublisher, CustomerSettings customerSettings, CommonSettings commonSettings) { this._cacheManager = cacheManager; this._customerRepository = customerRepository; this._customerPasswordRepository = customerPasswordRepository; this._customerRoleRepository = customerRoleRepository; this._gaRepository = gaRepository; this._orderRepository = orderRepository; this._forumPostRepository = forumPostRepository; this._forumTopicRepository = forumTopicRepository; this._blogCommentRepository = blogCommentRepository; this._newsCommentRepository = newsCommentRepository; this._pollVotingRecordRepository = pollVotingRecordRepository; this._productReviewRepository = productReviewRepository; this._productReviewHelpfulnessRepository = productReviewHelpfulnessRepository; this._genericAttributeService = genericAttributeService; this._dataProvider = dataProvider; this._dbContext = dbContext; this._eventPublisher = eventPublisher; this._customerSettings = customerSettings; this._commonSettings = commonSettings; } #endregion #region Methods #region Customers /// <summary> /// Gets all customers /// </summary> /// <param name="createdFromUtc">Created date from (UTC); null to load all records</param> /// <param name="createdToUtc">Created date to (UTC); null to load all records</param> /// <param name="affiliateId">Affiliate identifier</param> /// <param name="vendorId">Vendor identifier</param> /// <param name="customerRoleIds">A list of customer role identifiers to filter by (at least one match); pass null or empty list in order to load all customers; </param> /// <param name="email">Email; null to load all customers</param> /// <param name="username">Username; null to load all customers</param> /// <param name="firstName">First name; null to load all customers</param> /// <param name="lastName">Last name; null to load all customers</param> /// <param name="dayOfBirth">Day of birth; 0 to load all customers</param> /// <param name="monthOfBirth">Month of birth; 0 to load all customers</param> /// <param name="company">Company; null to load all customers</param> /// <param name="phone">Phone; null to load all customers</param> /// <param name="zipPostalCode">Phone; null to load all customers</param> /// <param name="ipAddress">IP address; null to load all customers</param> /// <param name="loadOnlyWithShoppingCart">Value indicating whether to load customers only with shopping cart</param> /// <param name="sct">Value indicating what shopping cart type to filter; userd when 'loadOnlyWithShoppingCart' param is 'true'</param> /// <param name="pageIndex">Page index</param> /// <param name="pageSize">Page size</param> /// <returns>Customers</returns> public virtual IPagedList<Customer> GetAllCustomers(DateTime? createdFromUtc = null, DateTime? createdToUtc = null, int affiliateId = 0, int vendorId = 0, int[] customerRoleIds = null, string email = null, string username = null, string firstName = null, string lastName = null, int dayOfBirth = 0, int monthOfBirth = 0, string company = null, string phone = null, string zipPostalCode = null, string ipAddress = null, bool loadOnlyWithShoppingCart = false, ShoppingCartType? sct = null, int pageIndex = 0, int pageSize = int.MaxValue) { var query = _customerRepository.Table; if (createdFromUtc.HasValue) query = query.Where(c => createdFromUtc.Value <= c.CreatedOnUtc); if (createdToUtc.HasValue) query = query.Where(c => createdToUtc.Value >= c.CreatedOnUtc); if (affiliateId > 0) query = query.Where(c => affiliateId == c.AffiliateId); if (vendorId > 0) query = query.Where(c => vendorId == c.VendorId); query = query.Where(c => !c.Deleted); if (customerRoleIds != null && customerRoleIds.Length > 0) query = query.Where(c => c.CustomerRoles.Select(cr => cr.Id).Intersect(customerRoleIds).Any()); if (!String.IsNullOrWhiteSpace(email)) query = query.Where(c => c.Email.Contains(email)); if (!String.IsNullOrWhiteSpace(username)) query = query.Where(c => c.Username.Contains(username)); if (!String.IsNullOrWhiteSpace(firstName)) { query = query .Join(_gaRepository.Table, x => x.Id, y => y.EntityId, (x, y) => new { Customer = x, Attribute = y }) .Where((z => z.Attribute.KeyGroup == "Customer" && z.Attribute.Key == SystemCustomerAttributeNames.FirstName && z.Attribute.Value.Contains(firstName))) .Select(z => z.Customer); } if (!String.IsNullOrWhiteSpace(lastName)) { query = query .Join(_gaRepository.Table, x => x.Id, y => y.EntityId, (x, y) => new { Customer = x, Attribute = y }) .Where((z => z.Attribute.KeyGroup == "Customer" && z.Attribute.Key == SystemCustomerAttributeNames.LastName && z.Attribute.Value.Contains(lastName))) .Select(z => z.Customer); } //date of birth is stored as a string into database. //we also know that date of birth is stored in the following format YYYY-MM-DD (for example, 1983-02-18). //so let's search it as a string if (dayOfBirth > 0 && monthOfBirth > 0) { //both are specified string dateOfBirthStr = monthOfBirth.ToString("00", CultureInfo.InvariantCulture) + "-" + dayOfBirth.ToString("00", CultureInfo.InvariantCulture); //EndsWith is not supported by SQL Server Compact //so let's use the following workaround http://social.msdn.microsoft.com/Forums/is/sqlce/thread/0f810be1-2132-4c59-b9ae-8f7013c0cc00 //we also cannot use Length function in SQL Server Compact (not supported in this context) //z.Attribute.Value.Length - dateOfBirthStr.Length = 5 //dateOfBirthStr.Length = 5 query = query .Join(_gaRepository.Table, x => x.Id, y => y.EntityId, (x, y) => new { Customer = x, Attribute = y }) .Where((z => z.Attribute.KeyGroup == "Customer" && z.Attribute.Key == SystemCustomerAttributeNames.DateOfBirth && z.Attribute.Value.Substring(5, 5) == dateOfBirthStr)) .Select(z => z.Customer); } else if (dayOfBirth > 0) { //only day is specified string dateOfBirthStr = dayOfBirth.ToString("00", CultureInfo.InvariantCulture); //EndsWith is not supported by SQL Server Compact //so let's use the following workaround http://social.msdn.microsoft.com/Forums/is/sqlce/thread/0f810be1-2132-4c59-b9ae-8f7013c0cc00 //we also cannot use Length function in SQL Server Compact (not supported in this context) //z.Attribute.Value.Length - dateOfBirthStr.Length = 8 //dateOfBirthStr.Length = 2 query = query .Join(_gaRepository.Table, x => x.Id, y => y.EntityId, (x, y) => new { Customer = x, Attribute = y }) .Where((z => z.Attribute.KeyGroup == "Customer" && z.Attribute.Key == SystemCustomerAttributeNames.DateOfBirth && z.Attribute.Value.Substring(8, 2) == dateOfBirthStr)) .Select(z => z.Customer); } else if (monthOfBirth > 0) { //only month is specified string dateOfBirthStr = "-" + monthOfBirth.ToString("00", CultureInfo.InvariantCulture) + "-"; query = query .Join(_gaRepository.Table, x => x.Id, y => y.EntityId, (x, y) => new { Customer = x, Attribute = y }) .Where((z => z.Attribute.KeyGroup == "Customer" && z.Attribute.Key == SystemCustomerAttributeNames.DateOfBirth && z.Attribute.Value.Contains(dateOfBirthStr))) .Select(z => z.Customer); } //search by company if (!String.IsNullOrWhiteSpace(company)) { query = query .Join(_gaRepository.Table, x => x.Id, y => y.EntityId, (x, y) => new { Customer = x, Attribute = y }) .Where((z => z.Attribute.KeyGroup == "Customer" && z.Attribute.Key == SystemCustomerAttributeNames.Company && z.Attribute.Value.Contains(company))) .Select(z => z.Customer); } //search by phone if (!String.IsNullOrWhiteSpace(phone)) { query = query .Join(_gaRepository.Table, x => x.Id, y => y.EntityId, (x, y) => new { Customer = x, Attribute = y }) .Where((z => z.Attribute.KeyGroup == "Customer" && z.Attribute.Key == SystemCustomerAttributeNames.Phone && z.Attribute.Value.Contains(phone))) .Select(z => z.Customer); } //search by zip if (!String.IsNullOrWhiteSpace(zipPostalCode)) { query = query .Join(_gaRepository.Table, x => x.Id, y => y.EntityId, (x, y) => new { Customer = x, Attribute = y }) .Where((z => z.Attribute.KeyGroup == "Customer" && z.Attribute.Key == SystemCustomerAttributeNames.ZipPostalCode && z.Attribute.Value.Contains(zipPostalCode))) .Select(z => z.Customer); } //search by IpAddress if (!String.IsNullOrWhiteSpace(ipAddress) && CommonHelper.IsValidIpAddress(ipAddress)) { query = query.Where(w => w.LastIpAddress == ipAddress); } if (loadOnlyWithShoppingCart) { int? sctId = null; if (sct.HasValue) sctId = (int)sct.Value; query = sct.HasValue ? query.Where(c => c.ShoppingCartItems.Any(x => x.ShoppingCartTypeId == sctId)) : query.Where(c => c.ShoppingCartItems.Any()); } query = query.OrderByDescending(c => c.CreatedOnUtc); var customers = new PagedList<Customer>(query, pageIndex, pageSize); return customers; } /// <summary> /// Gets online customers /// </summary> /// <param name="lastActivityFromUtc">Customer last activity date (from)</param> /// <param name="customerRoleIds">A list of customer role identifiers to filter by (at least one match); pass null or empty list in order to load all customers; </param> /// <param name="pageIndex">Page index</param> /// <param name="pageSize">Page size</param> /// <returns>Customers</returns> public virtual IPagedList<Customer> GetOnlineCustomers(DateTime lastActivityFromUtc, int[] customerRoleIds, int pageIndex = 0, int pageSize = int.MaxValue) { var query = _customerRepository.Table; query = query.Where(c => lastActivityFromUtc <= c.LastActivityDateUtc); query = query.Where(c => !c.Deleted); if (customerRoleIds != null && customerRoleIds.Length > 0) query = query.Where(c => c.CustomerRoles.Select(cr => cr.Id).Intersect(customerRoleIds).Any()); query = query.OrderByDescending(c => c.LastActivityDateUtc); var customers = new PagedList<Customer>(query, pageIndex, pageSize); return customers; } /// <summary> /// Delete a customer /// </summary> /// <param name="customer">Customer</param> public virtual void DeleteCustomer(Customer customer) { if (customer == null) throw new ArgumentNullException("customer"); if (customer.IsSystemAccount) throw new NopException(string.Format("System customer account ({0}) could not be deleted", customer.SystemName)); customer.Deleted = true; if (_customerSettings.SuffixDeletedCustomers) { if (!String.IsNullOrEmpty(customer.Email)) customer.Email += "-DELETED"; if (!String.IsNullOrEmpty(customer.Username)) customer.Username += "-DELETED"; } UpdateCustomer(customer); //event notification _eventPublisher.EntityDeleted(customer); } /// <summary> /// Gets a customer /// </summary> /// <param name="customerId">Customer identifier</param> /// <returns>A customer</returns> public virtual Customer GetCustomerById(int customerId) { if (customerId == 0) return null; return _customerRepository.GetById(customerId); } /// <summary> /// Get customers by identifiers /// </summary> /// <param name="customerIds">Customer identifiers</param> /// <returns>Customers</returns> public virtual IList<Customer> GetCustomersByIds(int[] customerIds) { if (customerIds == null || customerIds.Length == 0) return new List<Customer>(); var query = from c in _customerRepository.Table where customerIds.Contains(c.Id) && !c.Deleted select c; var customers = query.ToList(); //sort by passed identifiers var sortedCustomers = new List<Customer>(); foreach (int id in customerIds) { var customer = customers.Find(x => x.Id == id); if (customer != null) sortedCustomers.Add(customer); } return sortedCustomers; } /// <summary> /// Gets a customer by GUID /// </summary> /// <param name="customerGuid">Customer GUID</param> /// <returns>A customer</returns> public virtual Customer GetCustomerByGuid(Guid customerGuid) { if (customerGuid == Guid.Empty) return null; var query = from c in _customerRepository.Table where c.CustomerGuid == customerGuid orderby c.Id select c; var customer = query.FirstOrDefault(); return customer; } /// <summary> /// Get customer by email /// </summary> /// <param name="email">Email</param> /// <returns>Customer</returns> public virtual Customer GetCustomerByEmail(string email) { if (string.IsNullOrWhiteSpace(email)) return null; var query = from c in _customerRepository.Table orderby c.Id where c.Email == email select c; var customer = query.FirstOrDefault(); return customer; } /// <summary> /// Get customer by system name /// </summary> /// <param name="systemName">System name</param> /// <returns>Customer</returns> public virtual Customer GetCustomerBySystemName(string systemName) { if (string.IsNullOrWhiteSpace(systemName)) return null; var query = from c in _customerRepository.Table orderby c.Id where c.SystemName == systemName select c; var customer = query.FirstOrDefault(); return customer; } /// <summary> /// Get customer by username /// </summary> /// <param name="username">Username</param> /// <returns>Customer</returns> public virtual Customer GetCustomerByUsername(string username) { if (string.IsNullOrWhiteSpace(username)) return null; var query = from c in _customerRepository.Table orderby c.Id where c.Username == username select c; var customer = query.FirstOrDefault(); return customer; } /// <summary> /// Insert a guest customer /// </summary> /// <returns>Customer</returns> public virtual Customer InsertGuestCustomer() { var customer = new Customer { CustomerGuid = Guid.NewGuid(), Active = true, CreatedOnUtc = DateTime.UtcNow, LastActivityDateUtc = DateTime.UtcNow, }; //add to 'Guests' role var guestRole = GetCustomerRoleBySystemName(SystemCustomerRoleNames.Guests); if (guestRole == null) throw new NopException("'Guests' role could not be loaded"); customer.CustomerRoles.Add(guestRole); _customerRepository.Insert(customer); return customer; } /// <summary> /// Insert a customer /// </summary> /// <param name="customer">Customer</param> public virtual void InsertCustomer(Customer customer) { if (customer == null) throw new ArgumentNullException("customer"); _customerRepository.Insert(customer); //event notification _eventPublisher.EntityInserted(customer); } /// <summary> /// Updates the customer /// </summary> /// <param name="customer">Customer</param> public virtual void UpdateCustomer(Customer customer) { if (customer == null) throw new ArgumentNullException("customer"); _customerRepository.Update(customer); //event notification _eventPublisher.EntityUpdated(customer); } /// <summary> /// Reset data required for checkout /// </summary> /// <param name="customer">Customer</param> /// <param name="storeId">Store identifier</param> /// <param name="clearCouponCodes">A value indicating whether to clear coupon code</param> /// <param name="clearCheckoutAttributes">A value indicating whether to clear selected checkout attributes</param> /// <param name="clearRewardPoints">A value indicating whether to clear "Use reward points" flag</param> /// <param name="clearShippingMethod">A value indicating whether to clear selected shipping method</param> /// <param name="clearPaymentMethod">A value indicating whether to clear selected payment method</param> public virtual void ResetCheckoutData(Customer customer, int storeId, bool clearCouponCodes = false, bool clearCheckoutAttributes = false, bool clearRewardPoints = true, bool clearShippingMethod = true, bool clearPaymentMethod = true) { if (customer == null) throw new ArgumentNullException(); //clear entered coupon codes if (clearCouponCodes) { _genericAttributeService.SaveAttribute<ShippingOption>(customer, SystemCustomerAttributeNames.DiscountCouponCode, null); _genericAttributeService.SaveAttribute<ShippingOption>(customer, SystemCustomerAttributeNames.GiftCardCouponCodes, null); } //clear checkout attributes if (clearCheckoutAttributes) { _genericAttributeService.SaveAttribute<ShippingOption>(customer, SystemCustomerAttributeNames.CheckoutAttributes, null, storeId); } //clear reward points flag if (clearRewardPoints) { _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.UseRewardPointsDuringCheckout, false, storeId); } //clear selected shipping method if (clearShippingMethod) { _genericAttributeService.SaveAttribute<ShippingOption>(customer, SystemCustomerAttributeNames.SelectedShippingOption, null, storeId); _genericAttributeService.SaveAttribute<ShippingOption>(customer, SystemCustomerAttributeNames.OfferedShippingOptions, null, storeId); _genericAttributeService.SaveAttribute<ShippingOption>(customer, SystemCustomerAttributeNames.SelectedPickupPoint, null, storeId); } //clear selected payment method if (clearPaymentMethod) { _genericAttributeService.SaveAttribute<string>(customer, SystemCustomerAttributeNames.SelectedPaymentMethod, null, storeId); } UpdateCustomer(customer); } /// <summary> /// Delete guest customer records /// </summary> /// <param name="createdFromUtc">Created date from (UTC); null to load all records</param> /// <param name="createdToUtc">Created date to (UTC); null to load all records</param> /// <param name="onlyWithoutShoppingCart">A value indicating whether to delete customers only without shopping cart</param> /// <returns>Number of deleted customers</returns> public virtual int DeleteGuestCustomers(DateTime? createdFromUtc, DateTime? createdToUtc, bool onlyWithoutShoppingCart) { if (_commonSettings.UseStoredProceduresIfSupported && _dataProvider.StoredProceduredSupported) { //stored procedures are enabled and supported by the database. //It's much faster than the LINQ implementation below #region Stored procedure //prepare parameters var pOnlyWithoutShoppingCart = _dataProvider.GetParameter(); pOnlyWithoutShoppingCart.ParameterName = "OnlyWithoutShoppingCart"; pOnlyWithoutShoppingCart.Value = onlyWithoutShoppingCart; pOnlyWithoutShoppingCart.DbType = DbType.Boolean; var pCreatedFromUtc = _dataProvider.GetParameter(); pCreatedFromUtc.ParameterName = "CreatedFromUtc"; pCreatedFromUtc.Value = createdFromUtc.HasValue ? (object)createdFromUtc.Value : DBNull.Value; pCreatedFromUtc.DbType = DbType.DateTime; var pCreatedToUtc = _dataProvider.GetParameter(); pCreatedToUtc.ParameterName = "CreatedToUtc"; pCreatedToUtc.Value = createdToUtc.HasValue ? (object)createdToUtc.Value : DBNull.Value; pCreatedToUtc.DbType = DbType.DateTime; var pTotalRecordsDeleted = _dataProvider.GetParameter(); pTotalRecordsDeleted.ParameterName = "TotalRecordsDeleted"; pTotalRecordsDeleted.Direction = ParameterDirection.Output; pTotalRecordsDeleted.DbType = DbType.Int32; //invoke stored procedure _dbContext.ExecuteSqlCommand( "EXEC [DeleteGuests] @OnlyWithoutShoppingCart, @CreatedFromUtc, @CreatedToUtc, @TotalRecordsDeleted OUTPUT", false, null, pOnlyWithoutShoppingCart, pCreatedFromUtc, pCreatedToUtc, pTotalRecordsDeleted); int totalRecordsDeleted = (pTotalRecordsDeleted.Value != DBNull.Value) ? Convert.ToInt32(pTotalRecordsDeleted.Value) : 0; return totalRecordsDeleted; #endregion } else { //stored procedures aren't supported. Use LINQ #region No stored procedure var guestRole = GetCustomerRoleBySystemName(SystemCustomerRoleNames.Guests); if (guestRole == null) throw new NopException("'Guests' role could not be loaded"); var query = _customerRepository.Table; if (createdFromUtc.HasValue) query = query.Where(c => createdFromUtc.Value <= c.CreatedOnUtc); if (createdToUtc.HasValue) query = query.Where(c => createdToUtc.Value >= c.CreatedOnUtc); query = query.Where(c => c.CustomerRoles.Select(cr => cr.Id).Contains(guestRole.Id)); if (onlyWithoutShoppingCart) query = query.Where(c => !c.ShoppingCartItems.Any()); //no orders query = from c in query join o in _orderRepository.Table on c.Id equals o.CustomerId into c_o from o in c_o.DefaultIfEmpty() where !c_o.Any() select c; //no blog comments query = from c in query join bc in _blogCommentRepository.Table on c.Id equals bc.CustomerId into c_bc from bc in c_bc.DefaultIfEmpty() where !c_bc.Any() select c; //no news comments query = from c in query join nc in _newsCommentRepository.Table on c.Id equals nc.CustomerId into c_nc from nc in c_nc.DefaultIfEmpty() where !c_nc.Any() select c; //no product reviews query = from c in query join pr in _productReviewRepository.Table on c.Id equals pr.CustomerId into c_pr from pr in c_pr.DefaultIfEmpty() where !c_pr.Any() select c; //no product reviews helpfulness query = from c in query join prh in _productReviewHelpfulnessRepository.Table on c.Id equals prh.CustomerId into c_prh from prh in c_prh.DefaultIfEmpty() where !c_prh.Any() select c; //no poll voting query = from c in query join pvr in _pollVotingRecordRepository.Table on c.Id equals pvr.CustomerId into c_pvr from pvr in c_pvr.DefaultIfEmpty() where !c_pvr.Any() select c; //no forum posts query = from c in query join fp in _forumPostRepository.Table on c.Id equals fp.CustomerId into c_fp from fp in c_fp.DefaultIfEmpty() where !c_fp.Any() select c; //no forum topics query = from c in query join ft in _forumTopicRepository.Table on c.Id equals ft.CustomerId into c_ft from ft in c_ft.DefaultIfEmpty() where !c_ft.Any() select c; //don't delete system accounts query = query.Where(c => !c.IsSystemAccount); //only distinct customers (group by ID) query = from c in query group c by c.Id into cGroup orderby cGroup.Key select cGroup.FirstOrDefault(); query = query.OrderBy(c => c.Id); var customers = query.ToList(); int totalRecordsDeleted = 0; foreach (var c in customers) { try { //delete attributes var attributes = _genericAttributeService.GetAttributesForEntity(c.Id, "Customer"); _genericAttributeService.DeleteAttributes(attributes); //delete from database _customerRepository.Delete(c); totalRecordsDeleted++; } catch (Exception exc) { Debug.WriteLine(exc); } } return totalRecordsDeleted; #endregion } } #endregion #region Customer roles /// <summary> /// Delete a customer role /// </summary> /// <param name="customerRole">Customer role</param> public virtual void DeleteCustomerRole(CustomerRole customerRole) { if (customerRole == null) throw new ArgumentNullException("customerRole"); if (customerRole.IsSystemRole) throw new NopException("System role could not be deleted"); _customerRoleRepository.Delete(customerRole); _cacheManager.RemoveByPattern(CUSTOMERROLES_PATTERN_KEY); //event notification _eventPublisher.EntityDeleted(customerRole); } /// <summary> /// Gets a customer role /// </summary> /// <param name="customerRoleId">Customer role identifier</param> /// <returns>Customer role</returns> public virtual CustomerRole GetCustomerRoleById(int customerRoleId) { if (customerRoleId == 0) return null; return _customerRoleRepository.GetById(customerRoleId); } /// <summary> /// Gets a customer role /// </summary> /// <param name="systemName">Customer role system name</param> /// <returns>Customer role</returns> public virtual CustomerRole GetCustomerRoleBySystemName(string systemName) { if (String.IsNullOrWhiteSpace(systemName)) return null; string key = string.Format(CUSTOMERROLES_BY_SYSTEMNAME_KEY, systemName); return _cacheManager.Get(key, () => { var query = from cr in _customerRoleRepository.Table orderby cr.Id where cr.SystemName == systemName select cr; var customerRole = query.FirstOrDefault(); return customerRole; }); } /// <summary> /// Gets all customer roles /// </summary> /// <param name="showHidden">A value indicating whether to show hidden records</param> /// <returns>Customer roles</returns> public virtual IList<CustomerRole> GetAllCustomerRoles(bool showHidden = false) { string key = string.Format(CUSTOMERROLES_ALL_KEY, showHidden); return _cacheManager.Get(key, () => { var query = from cr in _customerRoleRepository.Table orderby cr.Name where showHidden || cr.Active select cr; var customerRoles = query.ToList(); return customerRoles; }); } /// <summary> /// Inserts a customer role /// </summary> /// <param name="customerRole">Customer role</param> public virtual void InsertCustomerRole(CustomerRole customerRole) { if (customerRole == null) throw new ArgumentNullException("customerRole"); _customerRoleRepository.Insert(customerRole); _cacheManager.RemoveByPattern(CUSTOMERROLES_PATTERN_KEY); //event notification _eventPublisher.EntityInserted(customerRole); } /// <summary> /// Updates the customer role /// </summary> /// <param name="customerRole">Customer role</param> public virtual void UpdateCustomerRole(CustomerRole customerRole) { if (customerRole == null) throw new ArgumentNullException("customerRole"); _customerRoleRepository.Update(customerRole); _cacheManager.RemoveByPattern(CUSTOMERROLES_PATTERN_KEY); //event notification _eventPublisher.EntityUpdated(customerRole); } #endregion #region Customer passwords /// <summary> /// Gets customer passwords /// </summary> /// <param name="customerId">Customer identifier; pass null to load all records</param> /// <param name="passwordFormat">Password format; pass null to load all records</param> /// <param name="passwordsToReturn">Number of returning passwords; pass null to load all records</param> /// <returns>List of customer passwords</returns> public virtual IList<CustomerPassword> GetCustomerPasswords(int? customerId = null, PasswordFormat? passwordFormat = null, int? passwordsToReturn = null) { var query = _customerPasswordRepository.Table; //filter by customer if (customerId.HasValue) query = query.Where(password => password.CustomerId == customerId.Value); //filter by password format if (passwordFormat.HasValue) query = query.Where(password => password.PasswordFormatId == (int)(passwordFormat.Value)); //get the latest passwords if (passwordsToReturn.HasValue) query = query.OrderByDescending(password => password.CreatedOnUtc).Take(passwordsToReturn.Value); return query.ToList(); } /// <summary> /// Get current customer password /// </summary> /// <param name="customerId">Customer identifier</param> /// <returns>Customer password</returns> public virtual CustomerPassword GetCurrentPassword(int customerId) { if (customerId == 0) return null; //return the latest password return GetCustomerPasswords(customerId, passwordsToReturn: 1).FirstOrDefault(); } /// <summary> /// Insert a customer password /// </summary> /// <param name="customerPassword">Customer password</param> public virtual void InsertCustomerPassword(CustomerPassword customerPassword) { if (customerPassword == null) throw new ArgumentNullException("customerPassword"); _customerPasswordRepository.Insert(customerPassword); //event notification _eventPublisher.EntityInserted(customerPassword); } /// <summary> /// Update a customer password /// </summary> /// <param name="customerPassword">Customer password</param> public virtual void UpdateCustomerPassword(CustomerPassword customerPassword) { if (customerPassword == null) throw new ArgumentNullException("customerPassword"); _customerPasswordRepository.Update(customerPassword); //event notification _eventPublisher.EntityUpdated(customerPassword); } #endregion #endregion } }
// Visual Studio Shared Project // Copyright(c) Microsoft Corporation // 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 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABILITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.IO; using System.Runtime.InteropServices; using Microsoft.Build.Construction; using Microsoft.VisualStudio; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudioTools.Infrastructure; using MSBuild = Microsoft.Build.Evaluation; namespace Microsoft.VisualStudioTools.Project { /// <summary> /// Creates projects within the solution /// </summary> public abstract class ProjectFactory : FlavoredProjectFactoryBase, IVsProjectUpgradeViaFactory4, IVsProjectUpgradeViaFactory { #region fields private IServiceProvider _site; /// <summary> /// The msbuild engine that we are going to use. /// </summary> private readonly MSBuild.ProjectCollection _buildEngine; /// <summary> /// The msbuild project for the project file. /// </summary> private MSBuild.Project _buildProject; private readonly Lazy<IVsTaskSchedulerService> taskSchedulerService; // (See GetSccInfo below.) // When we upgrade a project, we need to cache the SCC info in case // somebody calls to ask for it via GetSccInfo. // We only need to know about the most recently upgraded project, and // can fail for other projects. private string _cachedSccProject; private string _cachedSccProjectName, _cachedSccAuxPath, _cachedSccLocalPath, _cachedSccProvider; #endregion #region properties [Obsolete("Use Site instead")] protected Microsoft.VisualStudio.Shell.Package Package { get { return (Microsoft.VisualStudio.Shell.Package)_site; } } protected internal System.IServiceProvider Site { get { return _site; } internal set { _site = value; } } /// <summary> /// The msbuild project for the project file. /// </summary> protected MSBuild.Project BuildProject => _buildProject; #endregion #region ctor [Obsolete("Provide an IServiceProvider instead of a package")] protected ProjectFactory(Microsoft.VisualStudio.Shell.Package package) : this((IServiceProvider)package) { } protected ProjectFactory(IServiceProvider serviceProvider) : base(serviceProvider) { _site = serviceProvider; _buildEngine = MSBuild.ProjectCollection.GlobalProjectCollection; taskSchedulerService = new Lazy<IVsTaskSchedulerService>(() => Site.GetService(typeof(SVsTaskSchedulerService)) as IVsTaskSchedulerService); } #endregion #region abstract methods internal abstract ProjectNode CreateProject(); #endregion #region overriden methods /// <summary> /// Rather than directly creating the project, ask VS to initate the process of /// creating an aggregated project in case we are flavored. We will be called /// on the IVsAggregatableProjectFactory to do the real project creation. /// </summary> /// <param name="fileName">Project file</param> /// <param name="location">Path of the project</param> /// <param name="name">Project Name</param> /// <param name="flags">Creation flags</param> /// <param name="projectGuid">Guid of the project</param> /// <param name="project">Project that end up being created by this method</param> /// <param name="canceled">Was the project creation canceled</param> protected override void CreateProject(string fileName, string location, string name, uint flags, ref Guid projectGuid, out IntPtr project, out int canceled) { using (new DebugTimer("CreateProject")) { project = IntPtr.Zero; canceled = 0; // Get the list of GUIDs from the project/template string guidsList = ProjectTypeGuids(fileName); // Launch the aggregate creation process (we should be called back on our IVsAggregatableProjectFactoryCorrected implementation) IVsCreateAggregateProject aggregateProjectFactory = (IVsCreateAggregateProject)Site.GetService(typeof(SVsCreateAggregateProject)); int hr = aggregateProjectFactory.CreateAggregateProject(guidsList, fileName, location, name, flags, ref projectGuid, out project); if (hr == VSConstants.E_ABORT) canceled = 1; CommonUtils.ThrowOnFailure(hr); _buildProject = null; } } /// <summary> /// Instantiate the project class, but do not proceed with the /// initialization just yet. /// Delegate to CreateProject implemented by the derived class. /// </summary> protected override object PreCreateForOuter(IntPtr outerProjectIUnknown) { Utilities.CheckNotNull(_buildProject, "The build project should have been initialized before calling PreCreateForOuter."); // Please be very carefull what is initialized here on the ProjectNode. Normally this should only instantiate and return a project node. // The reason why one should very carefully add state to the project node here is that at this point the aggregation has not yet been created and anything that would cause a CCW for the project to be created would cause the aggregation to fail // Our reasoning is that there is no other place where state on the project node can be set that is known by the Factory and has to execute before the Load method. ProjectNode node = CreateProject(); Utilities.CheckNotNull(node, "The project failed to be created"); node.BuildEngine = _buildEngine; node.BuildProject = _buildProject; return node; } /// <summary> /// Retrives the list of project guids from the project file. /// If you don't want your project to be flavorable, override /// to only return your project factory Guid: /// return this.GetType().GUID.ToString("B"); /// </summary> /// <param name="file">Project file to look into to find the Guid list</param> /// <returns>List of semi-colon separated GUIDs</returns> protected override string ProjectTypeGuids(string file) { // Load the project so we can extract the list of GUIDs _buildProject = Utilities.ReinitializeMsBuildProject(_buildEngine, file, _buildProject); // Retrieve the list of GUIDs, if it is not specify, make it our GUID string guids = _buildProject.GetPropertyValue(ProjectFileConstants.ProjectTypeGuids); if (string.IsNullOrEmpty(guids)) guids = GetType().GUID.ToString("B"); return guids; } #endregion #if DEV11_OR_LATER public virtual bool CanCreateProjectAsynchronously(ref Guid rguidProjectID, string filename, uint flags) { return false; } public void OnBeforeCreateProjectAsync(ref Guid rguidProjectID, string filename, string location, string pszName, uint flags) { } public IVsTask CreateProjectAsync(ref Guid rguidProjectID, string filename, string location, string pszName, uint flags) { Guid iid = typeof(IVsHierarchy).GUID; return VsTaskLibraryHelper.CreateAndStartTask(taskSchedulerService.Value, VsTaskRunContext.UIThreadBackgroundPriority, VsTaskLibraryHelper.CreateTaskBody(() => { IntPtr project; int cancelled; CreateProject(filename, location, pszName, flags, ref iid, out project, out cancelled); if (cancelled != 0) { throw new OperationCanceledException(); } return Marshal.GetObjectForIUnknown(project); })); } #endif #region Project Upgrades /// <summary> /// Override this method to upgrade project files. /// </summary> /// <param name="projectXml"> /// The XML of the project file being upgraded. This may be modified /// directly or replaced with a new element. /// </param> /// <param name="userProjectXml"> /// The XML of the user file being upgraded. This may be modified /// directly or replaced with a new element. /// /// If there is no user file before upgrading, this may be null. If it /// is non-null on return, the file is created. /// </param> /// <param name="log"> /// Callback to log messages. These messages will be added to the /// migration log that is displayed after upgrading completes. /// </param> protected virtual void UpgradeProject( ref ProjectRootElement projectXml, ref ProjectRootElement userProjectXml, Action<__VSUL_ERRORLEVEL, string> log ) { } /// <summary> /// Determines whether a project needs to be upgraded. /// </summary> /// <param name="projectXml"> /// The XML of the project file being upgraded. /// </param> /// <param name="userProjectXml"> /// The XML of the user file being upgraded, or null if no user file /// exists. /// </param> /// <param name="log"> /// Callback to log messages. These messages will be added to the /// migration log that is displayed after upgrading completes. /// </param> /// <param name="projectFactory"> /// The project factory that will be used. This may be replaced with /// another Guid if a new project factory should be used to upgrade the /// project. /// </param> /// <param name="backupSupport"> /// The level of backup support requested for the project. By default, /// the project file (and user file, if any) will be copied alongside /// the originals with ".old" added to the filenames. /// </param> /// <returns> /// The form of upgrade required. /// </returns> protected virtual ProjectUpgradeState UpgradeProjectCheck( ProjectRootElement projectXml, ProjectRootElement userProjectXml, Action<__VSUL_ERRORLEVEL, string> log, ref Guid projectFactory, ref __VSPPROJECTUPGRADEVIAFACTORYFLAGS backupSupport ) { return ProjectUpgradeState.NotNeeded; } class UpgradeLogger { private readonly string _projectFile; private readonly string _projectName; private readonly IVsUpgradeLogger _logger; public UpgradeLogger(string projectFile, IVsUpgradeLogger logger) { _projectFile = projectFile; _projectName = Path.GetFileNameWithoutExtension(projectFile); _logger = logger; } public void Log(__VSUL_ERRORLEVEL level, string text) { if (_logger != null) { CommonUtils.ThrowOnFailure(_logger.LogMessage((uint)level, _projectName, _projectFile, text)); } } } int IVsProjectUpgradeViaFactory.GetSccInfo( string bstrProjectFileName, out string pbstrSccProjectName, out string pbstrSccAuxPath, out string pbstrSccLocalPath, out string pbstrProvider ) { if (string.Equals(_cachedSccProject, bstrProjectFileName, StringComparison.OrdinalIgnoreCase)) { pbstrSccProjectName = _cachedSccProjectName; pbstrSccAuxPath = _cachedSccAuxPath; pbstrSccLocalPath = _cachedSccLocalPath; pbstrProvider = _cachedSccProvider; return VSConstants.S_OK; } pbstrSccProjectName = null; pbstrSccAuxPath = null; pbstrSccLocalPath = null; pbstrProvider = null; return VSConstants.E_FAIL; } int IVsProjectUpgradeViaFactory.UpgradeProject( string bstrFileName, uint fUpgradeFlag, string bstrCopyLocation, out string pbstrUpgradedFullyQualifiedFileName, IVsUpgradeLogger pLogger, out int pUpgradeRequired, out Guid pguidNewProjectFactory ) { pbstrUpgradedFullyQualifiedFileName = null; // We first run (or re-run) the upgrade check and bail out early if // there is actually no need to upgrade. uint dummy; var hr = ((IVsProjectUpgradeViaFactory)this).UpgradeProject_CheckOnly( bstrFileName, pLogger, out pUpgradeRequired, out pguidNewProjectFactory, out dummy ); if (!CommonUtils.Succeeded(hr)) { return hr; } var logger = new UpgradeLogger(bstrFileName, pLogger); var backup = (__VSPPROJECTUPGRADEVIAFACTORYFLAGS)fUpgradeFlag; bool anyBackup, sxsBackup, copyBackup; anyBackup = backup.HasFlag(__VSPPROJECTUPGRADEVIAFACTORYFLAGS.PUVFF_BACKUPSUPPORTED); if (anyBackup) { sxsBackup = backup.HasFlag(__VSPPROJECTUPGRADEVIAFACTORYFLAGS.PUVFF_SXSBACKUP); copyBackup = !sxsBackup && backup.HasFlag(__VSPPROJECTUPGRADEVIAFACTORYFLAGS.PUVFF_COPYBACKUP); } else { sxsBackup = copyBackup = false; } if (copyBackup) { throw new NotSupportedException("PUVFF_COPYBACKUP is not supported"); } pbstrUpgradedFullyQualifiedFileName = bstrFileName; if (pUpgradeRequired == 0 && !copyBackup) { // No upgrade required, and no backup required. logger.Log(__VSUL_ERRORLEVEL.VSUL_INFORMATIONAL, SR.GetString(SR.UpgradeNotRequired)); return VSConstants.S_OK; } try { UpgradeLogger logger2 = null; var userFileName = bstrFileName + ".user"; if (File.Exists(userFileName)) { logger2 = new UpgradeLogger(userFileName, pLogger); } else { userFileName = null; } if (sxsBackup) { // For SxS backups we want to put the old project file alongside // the current one. bstrCopyLocation = Path.GetDirectoryName(bstrFileName); } if (anyBackup) { var namePart = Path.GetFileNameWithoutExtension(bstrFileName); var extPart = Path.GetExtension(bstrFileName) + (sxsBackup ? ".old" : ""); var projectFileBackup = Path.Combine(bstrCopyLocation, namePart + extPart); for (int i = 1; File.Exists(projectFileBackup); ++i) { projectFileBackup = Path.Combine( bstrCopyLocation, string.Format("{0}{1}{2}", namePart, i, extPart) ); } File.Copy(bstrFileName, projectFileBackup); // Back up the .user file if there is one if (userFileName != null) { if (sxsBackup) { File.Copy( userFileName, Path.ChangeExtension(projectFileBackup, ".user.old") ); } else { File.Copy(userFileName, projectFileBackup + ".old"); } } // TODO: Implement support for backing up all files //if (copyBackup) { // - Open the project // - Inspect all Items // - Copy those items that are referenced relative to the // project file into bstrCopyLocation //} } var queryEdit = _site.GetService(typeof(SVsQueryEditQuerySave)) as IVsQueryEditQuerySave2; if (queryEdit != null) { uint editVerdict; uint queryEditMoreInfo; var tagVSQueryEditFlags_QEF_AllowUnopenedProjects = (tagVSQueryEditFlags)0x80; CommonUtils.ThrowOnFailure(queryEdit.QueryEditFiles( (uint)(tagVSQueryEditFlags.QEF_ForceEdit_NoPrompting | tagVSQueryEditFlags.QEF_DisallowInMemoryEdits | tagVSQueryEditFlags_QEF_AllowUnopenedProjects), 1, new[] { bstrFileName }, null, null, out editVerdict, out queryEditMoreInfo )); if (editVerdict != (uint)tagVSQueryEditResult.QER_EditOK) { logger.Log(__VSUL_ERRORLEVEL.VSUL_ERROR, SR.GetString(SR.UpgradeCannotCheckOutProject)); return VSConstants.E_FAIL; } // File may have been updated during checkout, so check // again whether we need to upgrade. if ((queryEditMoreInfo & (uint)tagVSQueryEditResultFlags.QER_MaybeChanged) != 0) { hr = ((IVsProjectUpgradeViaFactory)this).UpgradeProject_CheckOnly( bstrFileName, pLogger, out pUpgradeRequired, out pguidNewProjectFactory, out dummy ); if (!CommonUtils.Succeeded(hr)) { return hr; } if (pUpgradeRequired == 0) { logger.Log(__VSUL_ERRORLEVEL.VSUL_INFORMATIONAL, SR.GetString(SR.UpgradeNotRequired)); return VSConstants.S_OK; } } } // Load the project file and user file into MSBuild as plain // XML to make it easier for subclasses. var projectXml = ProjectRootElement.Open(bstrFileName); if (projectXml == null) { throw new Exception(SR.GetString(SR.UpgradeCannotLoadProject)); } var userXml = userFileName != null ? ProjectRootElement.Open(userFileName) : null; // Invoke our virtual UpgradeProject function. If it fails, it // will throw and we will log the exception. UpgradeProject(ref projectXml, ref userXml, logger.Log); // Get the SCC info from the project file. if (projectXml != null) { _cachedSccProject = bstrFileName; _cachedSccProjectName = string.Empty; _cachedSccAuxPath = string.Empty; _cachedSccLocalPath = string.Empty; _cachedSccProvider = string.Empty; foreach (var property in projectXml.Properties) { switch (property.Name) { case ProjectFileConstants.SccProjectName: _cachedSccProjectName = property.Value; break; case ProjectFileConstants.SccAuxPath: _cachedSccAuxPath = property.Value; break; case ProjectFileConstants.SccLocalPath: _cachedSccLocalPath = property.Value; break; case ProjectFileConstants.SccProvider: _cachedSccProvider = property.Value; break; default: break; } } } // Save the updated files. if (projectXml != null) { projectXml.Save(); } if (userXml != null) { userXml.Save(); } // Need to add "Converted" (unlocalized) to the report because // the XSLT refers to it. logger.Log(__VSUL_ERRORLEVEL.VSUL_STATUSMSG, "Converted"); return VSConstants.S_OK; } catch (Exception ex) { if (ex.IsCriticalException()) { throw; } logger.Log(__VSUL_ERRORLEVEL.VSUL_ERROR, SR.GetString(SR.UnexpectedUpgradeError, ex.Message)); CommonUtils.ActivityLogError(GetType().FullName, ex.ToString()); return VSConstants.E_FAIL; } } int IVsProjectUpgradeViaFactory.UpgradeProject_CheckOnly( string bstrFileName, IVsUpgradeLogger pLogger, out int pUpgradeRequired, out Guid pguidNewProjectFactory, out uint pUpgradeProjectCapabilityFlags ) { pUpgradeRequired = 0; pguidNewProjectFactory = Guid.Empty; if (!File.Exists(bstrFileName)) { pUpgradeProjectCapabilityFlags = 0; return VSConstants.E_INVALIDARG; } var backupSupport = __VSPPROJECTUPGRADEVIAFACTORYFLAGS.PUVFF_BACKUPSUPPORTED | __VSPPROJECTUPGRADEVIAFACTORYFLAGS.PUVFF_COPYBACKUP | __VSPPROJECTUPGRADEVIAFACTORYFLAGS.PUVFF_SXSBACKUP; var logger = new UpgradeLogger(bstrFileName, pLogger); try { var projectXml = ProjectRootElement.Open(bstrFileName); var userProjectName = bstrFileName + ".user"; var userProjectXml = File.Exists(userProjectName) ? ProjectRootElement.Open(userProjectName) : null; var upgradeRequired = UpgradeProjectCheck( projectXml, userProjectXml, logger.Log, ref pguidNewProjectFactory, ref backupSupport ); if (upgradeRequired != ProjectUpgradeState.NotNeeded) { pUpgradeRequired = 1; } } catch (Exception ex) { if (ex.IsCriticalException()) { throw; } // Log the error and don't attempt to upgrade the project. logger.Log(__VSUL_ERRORLEVEL.VSUL_ERROR, SR.GetString(SR.UnexpectedUpgradeError, ex.Message)); CommonUtils.ActivityLogError(GetType().FullName, ex.ToString()); pUpgradeRequired = 0; } pUpgradeProjectCapabilityFlags = (uint)backupSupport; // If the upgrade checker set the factory GUID to ourselves, we need // to clear it if (pguidNewProjectFactory == GetType().GUID) { pguidNewProjectFactory = Guid.Empty; } return VSConstants.S_OK; } #if DEV11_OR_LATER void IVsProjectUpgradeViaFactory4.UpgradeProject_CheckOnly( string bstrFileName, IVsUpgradeLogger pLogger, out uint pUpgradeRequired, out Guid pguidNewProjectFactory, out uint pUpgradeProjectCapabilityFlags ) { pguidNewProjectFactory = Guid.Empty; if (!File.Exists(bstrFileName)) { pUpgradeRequired = 0; pUpgradeProjectCapabilityFlags = 0; return; } var backupSupport = __VSPPROJECTUPGRADEVIAFACTORYFLAGS.PUVFF_BACKUPSUPPORTED | __VSPPROJECTUPGRADEVIAFACTORYFLAGS.PUVFF_COPYBACKUP | __VSPPROJECTUPGRADEVIAFACTORYFLAGS.PUVFF_SXSBACKUP; var logger = new UpgradeLogger(bstrFileName, pLogger); try { var projectXml = ProjectRootElement.Open(bstrFileName); var userProjectName = bstrFileName + ".user"; var userProjectXml = File.Exists(userProjectName) ? ProjectRootElement.Open(userProjectName) : null; var upgradeRequired = UpgradeProjectCheck( projectXml, userProjectXml, logger.Log, ref pguidNewProjectFactory, ref backupSupport ); switch (upgradeRequired) { case ProjectUpgradeState.SafeRepair: pUpgradeRequired = (uint)__VSPPROJECTUPGRADEVIAFACTORYREPAIRFLAGS.VSPUVF_PROJECT_SAFEREPAIR; break; case ProjectUpgradeState.UnsafeRepair: pUpgradeRequired = (uint)__VSPPROJECTUPGRADEVIAFACTORYREPAIRFLAGS.VSPUVF_PROJECT_UNSAFEREPAIR; break; case ProjectUpgradeState.OneWayUpgrade: pUpgradeRequired = (uint)__VSPPROJECTUPGRADEVIAFACTORYREPAIRFLAGS.VSPUVF_PROJECT_ONEWAYUPGRADE; break; case ProjectUpgradeState.Incompatible: pUpgradeRequired = (uint)__VSPPROJECTUPGRADEVIAFACTORYREPAIRFLAGS.VSPUVF_PROJECT_INCOMPATIBLE; break; case ProjectUpgradeState.Deprecated: pUpgradeRequired = (uint)__VSPPROJECTUPGRADEVIAFACTORYREPAIRFLAGS.VSPUVF_PROJECT_DEPRECATED; break; default: case ProjectUpgradeState.NotNeeded: pUpgradeRequired = (uint)__VSPPROJECTUPGRADEVIAFACTORYREPAIRFLAGS.VSPUVF_PROJECT_NOREPAIR; break; } } catch (Exception ex) { if (ex.IsCriticalException()) { throw; } // Log the error and don't attempt to upgrade the project. logger.Log(__VSUL_ERRORLEVEL.VSUL_ERROR, SR.GetString(SR.UnexpectedUpgradeError, ex.Message)); CommonUtils.ActivityLogError(GetType().FullName, ex.ToString()); pUpgradeRequired = (uint)__VSPPROJECTUPGRADEVIAFACTORYREPAIRFLAGS.VSPUVF_PROJECT_NOREPAIR; } pUpgradeProjectCapabilityFlags = (uint)backupSupport; // If the upgrade checker set the factory GUID to ourselves, we need // to clear it if (pguidNewProjectFactory == GetType().GUID) { pguidNewProjectFactory = Guid.Empty; } } #endif #endregion } /// <summary> /// Status indicating whether a project upgrade should occur and how the /// project will be affected. /// </summary> public enum ProjectUpgradeState { /// <summary> /// No action will be taken. /// </summary> NotNeeded, /// <summary> /// The project will be upgraded without asking the user. /// </summary> SafeRepair, /// <summary> /// The project will be upgraded with the user's permission. /// </summary> UnsafeRepair, /// <summary> /// The project will be upgraded with the user's permission and they /// will be informed that the project will no longer work with earlier /// versions of Visual Studio. /// </summary> OneWayUpgrade, /// <summary> /// The project will be marked as incompatible. /// </summary> Incompatible, /// <summary> /// The project will be marked as deprecated. /// </summary> Deprecated } }
// 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 // // 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 CommandLine; using Google.Ads.GoogleAds.Lib; using Google.Ads.GoogleAds.Util; using Google.Ads.GoogleAds.V10.Common; using Google.Ads.GoogleAds.V10.Enums; using Google.Ads.GoogleAds.V10.Errors; using Google.Ads.GoogleAds.V10.Resources; using Google.Ads.GoogleAds.V10.Services; using static Google.Ads.GoogleAds.V10.Enums.AdGroupTypeEnum.Types; using static Google.Ads.GoogleAds.V10.Enums.AdvertisingChannelTypeEnum.Types; using static Google.Ads.GoogleAds.V10.Enums.AdvertisingChannelSubTypeEnum.Types; using static Google.Ads.GoogleAds.V10.Enums.BudgetTypeEnum.Types; using static Google.Ads.GoogleAds.V10.Enums.CampaignStatusEnum.Types; using static Google.Ads.GoogleAds.V10.Enums.CriterionTypeEnum.Types; using static Google.Ads.GoogleAds.V10.Services.SmartCampaignSuggestionInfo.Types; namespace Google.Ads.GoogleAds.Examples.V10 { /// <summary> /// This example shows how to create a Smart Campaign. /// /// More details on Smart Campaigns can be found here: /// https://support.google.com/google-ads/answer/7652860 /// </summary> public class AddSmartCampaign : ExampleBase { /// <summary> /// Command line options for running the <see cref="AddSmartCampaign"/> example. /// </summary> public class Options : OptionsBase { /// <summary> /// The Google Ads customer ID. /// </summary> [Option("customerId", Required = true, HelpText = "The Google Ads customer ID.")] public long CustomerId { get; set; } /// <summary> /// A keyword text used to retrieve keyword theme constant suggestions from the /// KeywordThemeConstantService. These keyword theme suggestions are generated /// using auto-completion data for the given text and may help improve the /// performance of the Smart campaign. /// </summary> [Option("keywordText", Required = false, HelpText = "A keyword text used to retrieve keyword theme constant suggestions from the " + "KeywordThemeConstantService. These keyword theme suggestions are generated " + "using auto-completion data for the given text and may help improve the " + "performance of the Smart campaign.", Default = DEFAULT_KEYWORD_TEXT)] public string Keyword { get; set; } /// <summary> /// A keyword text used to create a freeform keyword theme, which is entirely /// user-specified and not derived from any suggestion service. Using free-form /// keyword themes is typically not recommended because they are less effective /// than suggested keyword themes, however they are useful in situations where a /// very specific term needs to be targeted. /// </summary> [Option("keywordText", Required = false, HelpText = "A keyword text used to create a freeform keyword theme, which is entirely " + "user-specified and not derived from any suggestion service. Using free-form " + "keyword themes is typically not recommended because they are less effective " + "than suggested keyword themes, however they are useful in situations where a " + "very specific term needs to be targeted.", Default = DEFAULT_KEYWORD_TEXT)] public string FreeformKeywordText { get; set; } /// <summary> /// The ID of a Business Profile location. This is required if a business name /// is not provided. This ID can be retrieved using the Business Profile API, for /// details see: /// https://developers.google.com/my-business/reference/rest/v4/accounts.locations /// </summary> [Option("businessLocationId", Required = false, HelpText = "The ID of a Business Profile location. This is required if a business " + "name is not provided.\n" + "This ID can be retrieved using the Business Profile API; for details see: " + "https://developers.google.com/my-business/reference/rest/v4/accounts.locations")] public ulong? BusinessLocationId { get; set; } /// <summary> /// The name of a Business Profile business. This is required if a business /// location ID is not provided. /// </summary> [Option("businessName", Required = false, HelpText = "The name of a Business Profile business. This is required if a " + "business location ID is not provided.")] public string BusinessName { get; set; } } /// <summary> /// Main method, to run this code example as a standalone application. /// </summary> /// <param name="args">The command line arguments.</param> public static void Main(string[] args) { Options options = new Options(); Parser.Default.ParseArguments<Options>(args).MapResult( delegate (Options o) { options = o; return 0; }, delegate (IEnumerable<Error> errors) { // The Google Ads customer ID. options.CustomerId = long.Parse("INSERT_CUSTOMER_ID_HERE"); // A keyword text used to generate a set of keyword themes, which are used to // improve the budget recommendation and performance of the Smart Campaign. options.Keyword = DEFAULT_KEYWORD_TEXT; // A keyword used to create a free-form keyword theme. options.FreeformKeywordText = DEFAULT_KEYWORD_TEXT; // The ID of a Business Profile location. This is required if a // business name is not provided. options.BusinessLocationId = ulong.Parse("INSERT_BUSINESS_LOCATION_ID_HERE"); // The name of a Business Profile business. This is required if a // business location ID is not provided. options.BusinessName = "INSERT_BUSINESS_NAME_HERE"; return 0; }); AddSmartCampaign codeExample = new AddSmartCampaign(); Console.WriteLine(codeExample.Description); codeExample.Run(new GoogleAdsClient(), options.CustomerId, options.Keyword, options.FreeformKeywordText, options.BusinessLocationId, options.BusinessName); } private const string DEFAULT_KEYWORD_TEXT = "travel"; // Geo target constant for New York City. private const long GEO_TARGET_CONSTANT = 1023191; private const string COUNTRY_CODE = "US"; private const string LANGUAGE_CODE = "en"; private const string LANDING_PAGE_URL = "http://www.example.com"; private const string PHONE_NUMBER = "555-555-5555"; private const long BUDGET_TEMPORARY_ID = -1; private const long SMART_CAMPAIGN_TEMPORARY_ID = -2; private const long AD_GROUP_TEMPORARY_ID = -3; private const int NUM_REQUIRED_HEADLINES = 3; private const int NUM_REQUIRED_DESCRIPTIONS = 2; /// <summary> /// Returns a description about the code example. /// </summary> public override string Description => "This example shows how to create a Smart Campaign.\nMore details on Smart " + "Campaigns can be found here: https: //support.google.com/google-ads/answer/7652860"; /// <summary> /// Runs the code example. /// </summary> /// <param name="client">The Google Ads client.</param> /// <param name="customerId">The Google Ads customer ID.</param> /// <param name="keywordText">A keyword string used for generating keyword themes.</param> /// <param name="freeFormKeywordText">A keyword used to create a free-form keyword theme. /// </param> /// <param name="businessLocationId">The ID of a Business Profile location.</param> /// <param name="businessName">The name of a Business Profile business.</param> public void Run(GoogleAdsClient client, long customerId, string keywordText, string freeFormKeywordText, ulong? businessLocationId, string businessName) { GoogleAdsServiceClient googleAdsServiceClient = client.GetService(Services.V10.GoogleAdsService); try { // [START add_smart_campaign_12] // Gets the SmartCampaignSuggestionInfo object which acts as the basis for many // of the entities necessary to create a Smart campaign. It will be reused a number // of times to retrieve suggestions for keyword themes, budget amount, ad //creatives, and campaign criteria. SmartCampaignSuggestionInfo suggestionInfo = GetSmartCampaignSuggestionInfo(client, businessLocationId, businessName); // Generates a list of keyword themes using the SuggestKeywordThemes method on the // SmartCampaignSuggestService. It is strongly recommended that you use this // strategy for generating keyword themes. List<KeywordThemeConstant> keywordThemeConstants = GetKeywordThemeSuggestions(client, customerId, suggestionInfo); // Optionally retrieves auto-complete suggestions for the given keyword text and // adds them to the list of keyWordThemeConstants. if (keywordText != null) { keywordThemeConstants.AddRange(GetKeywordTextAutoCompletions( client, keywordText)); } // Converts the KeywordThemeConstants to KeywordThemeInfos. List<KeywordThemeInfo> keywordThemeInfos = keywordThemeConstants.Select( constant => new KeywordThemeInfo { KeywordThemeConstant = constant.ResourceName }) .ToList(); // Optionally includes any freeform keywords verbatim. if (freeFormKeywordText != null) { keywordThemeInfos.Add(new KeywordThemeInfo() { FreeFormKeywordTheme = freeFormKeywordText }); } // Includes the keyword suggestions in the overall SuggestionInfo object. // [START add_smart_campaign_13] suggestionInfo.KeywordThemes.Add(keywordThemeInfos); // [END add_smart_campaign_13] // [END add_smart_campaign_12] SmartCampaignAdInfo adSuggestions = GetAdSuggestions(client, customerId, suggestionInfo); long suggestedBudgetAmount = GetBudgetSuggestion(client, customerId, suggestionInfo); // [START add_smart_campaign_7] // The below methods create and return MutateOperations that we later provide to // the GoogleAdsService.Mutate method in order to create the entities in a single // request. Since the entities for a Smart campaign are closely tied to one-another // it's considered a best practice to create them in a single Mutate request; the // entities will either all complete successfully or fail entirely, leaving no // orphaned entities. See: // https://developers.google.com/google-ads/api/docs/mutating/overview MutateOperation campaignBudgetOperation = CreateCampaignBudgetOperation(customerId, suggestedBudgetAmount); MutateOperation smartCampaignOperation = CreateSmartCampaignOperation(customerId); MutateOperation smartCampaignSettingOperation = CreateSmartCampaignSettingOperation(customerId, businessLocationId, businessName); IEnumerable<MutateOperation> campaignCriterionOperations = CreateCampaignCriterionOperations(customerId, keywordThemeInfos, suggestionInfo); MutateOperation adGroupOperation = CreateAdGroupOperation(customerId); MutateOperation adGroupAdOperation = CreateAdGroupAdOperation(customerId, adSuggestions); // Send the operations in a single mutate request. MutateGoogleAdsRequest mutateGoogleAdsRequest = new MutateGoogleAdsRequest { CustomerId = customerId.ToString() }; // It's important to create these entities in this order because they depend on // each other, for example the SmartCampaignSetting and ad group depend on the // campaign, and the ad group ad depends on the ad group. mutateGoogleAdsRequest.MutateOperations.Add(campaignBudgetOperation); mutateGoogleAdsRequest.MutateOperations.Add(smartCampaignOperation); mutateGoogleAdsRequest.MutateOperations.Add(smartCampaignSettingOperation); mutateGoogleAdsRequest.MutateOperations.Add(campaignCriterionOperations); mutateGoogleAdsRequest.MutateOperations.Add(adGroupOperation); mutateGoogleAdsRequest.MutateOperations.Add(adGroupAdOperation); MutateGoogleAdsResponse response = googleAdsServiceClient.Mutate(mutateGoogleAdsRequest); PrintResponseDetails(response); // [END add_smart_campaign_7] } catch (GoogleAdsException e) { Console.WriteLine("Failure:"); Console.WriteLine($"Message: {e.Message}"); Console.WriteLine($"Failure: {e.Failure}"); Console.WriteLine($"Request ID: {e.RequestId}"); throw; } } // [START add_smart_campaign_11] /// <summary> /// Retrieves KeywordThemeConstants suggestions with the SmartCampaignSuggestService. /// </summary> /// <param name="client">The Google Ads client.</param> /// <param name="customerId">The Google Ads customer ID.</param> /// <param name="suggestionInfo">The suggestion information.</param> /// <returns>The suggestions.</returns> private List<KeywordThemeConstant> GetKeywordThemeSuggestions( GoogleAdsClient client, long customerId, SmartCampaignSuggestionInfo suggestionInfo) { SmartCampaignSuggestServiceClient smartCampaignSuggestService = client.GetService(Services.V10.SmartCampaignSuggestService); SuggestKeywordThemesRequest request = new SuggestKeywordThemesRequest() { SuggestionInfo = suggestionInfo, CustomerId = customerId.ToString() }; SuggestKeywordThemesResponse response = smartCampaignSuggestService.SuggestKeywordThemes(request); // Prints some information about the result. Console.WriteLine($"Retrieved {response.KeywordThemes.Count} keyword theme " + $"constant suggestions from the SuggestKeywordThemes method."); return response.KeywordThemes.ToList(); } // [END add_smart_campaign_11] // [START add_smart_campaign] /// <summary> /// Retrieves KeywordThemeConstants that are derived from autocomplete data for the /// given keyword text. /// </summary> /// <param name="client">The Google Ads client.</param> /// <param name="keywordText">A keyword used for generating keyword auto completions. /// </param> /// <returns>A list of KeywordThemeConstants.</returns> private IEnumerable<KeywordThemeConstant> GetKeywordTextAutoCompletions( GoogleAdsClient client, string keywordText) { KeywordThemeConstantServiceClient keywordThemeConstantServiceClient = client.GetService(Services.V10.KeywordThemeConstantService); SuggestKeywordThemeConstantsRequest request = new SuggestKeywordThemeConstantsRequest { QueryText = keywordText, CountryCode = COUNTRY_CODE, LanguageCode = LANGUAGE_CODE }; SuggestKeywordThemeConstantsResponse response = keywordThemeConstantServiceClient.SuggestKeywordThemeConstants(request); Console.WriteLine($"Retrieved {response.KeywordThemeConstants.Count} keyword theme " + $"constants using the keyword '{keywordText}'."); return response.KeywordThemeConstants.ToList(); } // [END add_smart_campaign] // [START add_smart_campaign_9] /// <summary> /// Builds a SmartCampaignSuggestionInfo object with business details. /// /// The details are used by the SmartCampaignSuggestService to suggest a /// budget amount as well as creatives for the ad. /// /// Note that when retrieving ad creative suggestions it's required that the /// "final_url", "language_code" and "keyword_themes" fields are set on the /// SmartCampaignSuggestionInfo instance. /// </summary> /// <param name="client">The Google Ads client.</param> /// <param name="businessLocationId">The ID of a Business Profile location.</param> /// <param name="businessName">The name of a Business Profile.</param> /// <returns>A SmartCampaignSuggestionInfo instance .</returns> private SmartCampaignSuggestionInfo GetSmartCampaignSuggestionInfo(GoogleAdsClient client, ulong? businessLocationId, string businessName) { SmartCampaignSuggestServiceClient smartCampaignSuggestServiceClient = client.GetService(Services.V10.SmartCampaignSuggestService); SmartCampaignSuggestionInfo suggestionInfo = new SmartCampaignSuggestionInfo { // Add the URL of the campaign's landing page. FinalUrl = LANDING_PAGE_URL, LanguageCode = LANGUAGE_CODE, // Construct location information using the given geo target constant. It's // also possible to provide a geographic proximity using the "proximity" // field on suggestion_info, for example: // Proximity = new ProximityInfo // { // Address = new AddressInfo // { // PostalCode = "INSERT_POSTAL_CODE", // ProvinceCode = "INSERT_PROVINCE_CODE", // CountryCode = "INSERT_COUNTRY_CODE", // ProvinceName = "INSERT_PROVINCE_NAME", // StreetAddress = "INSERT_STREET_ADDRESS", // StreetAddress2 = "INSERT_STREET_ADDRESS_2", // CityName = "INSERT_CITY_NAME" // }, // Radius = Double.Parse("INSERT_RADIUS"), // RadiusUnits = ProximityRadiusUnits.Kilometers // } // For more information on proximities see: // https://developers.google.com/google-ads/api/reference/rpc/latest/ProximityInfo LocationList = new LocationList() { Locations = { new LocationInfo { // Set the location to the resource name of the given geo target // constant. GeoTargetConstant = ResourceNames.GeoTargetConstant(GEO_TARGET_CONSTANT) } } } }; // Add the Business Profile location ID if provided. if (businessLocationId.HasValue) { // Transform Google Business Location ID to a compatible format before // passing it onto the API. suggestionInfo.BusinessLocationId = ConvertBusinessLocationId(businessLocationId.Value); } else { suggestionInfo.BusinessContext = new BusinessContext { BusinessName = businessName, }; } // Add a schedule detailing which days of the week the business is open. This schedule // describes a business that is open on Mondays from 9:00 AM to 5:00 PM. AdScheduleInfo adScheduleInfo = new AdScheduleInfo { // Set the day of this schedule as Monday. DayOfWeek = DayOfWeekEnum.Types.DayOfWeek.Monday, // Set the start hour to 9 AM. StartHour = 9, // Set the end hour to 5 PM. EndHour = 17, // Set the start and end minutes to zero. StartMinute = MinuteOfHourEnum.Types.MinuteOfHour.Zero, EndMinute = MinuteOfHourEnum.Types.MinuteOfHour.Zero }; suggestionInfo.AdSchedules.Add(adScheduleInfo); return suggestionInfo; } // [END add_smart_campaign_9] // [START add_smart_campaign_1] /// <summary> /// Retrieves a suggested budget amount for a new budget. /// Using the SmartCampaignSuggestService to determine a daily budget for new and existing /// Smart campaigns is highly recommended because it helps the campaigns achieve optimal /// performance. /// </summary> /// <param name="client">The Google Ads client.</param> /// <param name="customerId">The Google Ads customer ID.</param> /// <param name="suggestionInfo"></param> /// <returns>A daily budget amount in micros.</returns> private long GetBudgetSuggestion(GoogleAdsClient client, long customerId, SmartCampaignSuggestionInfo suggestionInfo) { SmartCampaignSuggestServiceClient smartCampaignSuggestServiceClient = client.GetService (Services.V10.SmartCampaignSuggestService); SuggestSmartCampaignBudgetOptionsRequest request = new SuggestSmartCampaignBudgetOptionsRequest { CustomerId = customerId.ToString(), // You can retrieve suggestions for an existing campaign by setting the // "Campaign" field of the request to the resource name of a campaign and // leaving the rest of the request fields below unset: // Campaign = "INSERT_CAMPAIGN_RESOURCE_NAME_HERE", // Since these suggestions are for a new campaign, we're going to use the // SuggestionInfo field instead. SuggestionInfo = suggestionInfo, }; LocationInfo locationInfo = new LocationInfo { // Set the location to the resource name of the given geo target constant. GeoTargetConstant = ResourceNames.GeoTargetConstant(GEO_TARGET_CONSTANT) }; // Issue a request to retrieve a budget suggestion. SuggestSmartCampaignBudgetOptionsResponse response = smartCampaignSuggestServiceClient.SuggestSmartCampaignBudgetOptions(request); // Three tiers of options will be returned: "low", "high", and "recommended". // Here we will use the "recommended" option. The amount is specified in micros, where // one million is equivalent to one currency unit. Console.WriteLine($"A daily budget amount of " + $"{response.Recommended.DailyAmountMicros}" + $" was suggested, garnering an estimated minimum of " + $"{response.Recommended.Metrics.MinDailyClicks} clicks and an estimated " + $"maximum of {response.Recommended.Metrics.MaxDailyClicks} clicks per day."); return response.Recommended.DailyAmountMicros; } // [END add_smart_campaign_1] // [START add_smart_campaign_10] /// <summary> /// Retrieves creative suggestions for a Smart campaign ad. /// /// Using the SmartCampaignSuggestService to suggest creatives for new /// and existing Smart campaigns is highly recommended because it helps /// the campaigns achieve optimal performance. /// </summary> /// <param name="client"></param> /// <param name="customerId">The Google Ads customer ID.</param> /// <param name="suggestionInfo">a SmartCampaignSuggestionInfo instance /// with details about the business being advertised.</param> /// <returns>A SmartCampaignAdInfo instance with suggested headlines and /// descriptions.</returns> private SmartCampaignAdInfo GetAdSuggestions(GoogleAdsClient client, long customerId, SmartCampaignSuggestionInfo suggestionInfo) { SmartCampaignSuggestServiceClient smartCampaignSuggestService = client.GetService(Services.V10.SmartCampaignSuggestService); SuggestSmartCampaignAdRequest request = new SuggestSmartCampaignAdRequest { CustomerId = customerId.ToString(), // Unlike the SuggestSmartCampaignBudgetOptions method, it's only possible to // use suggestion_info to retrieve ad creative suggestions. SuggestionInfo = suggestionInfo }; // Issue a request to retrieve ad creative suggestions. SuggestSmartCampaignAdResponse response = smartCampaignSuggestService.SuggestSmartCampaignAd(request); // The SmartCampaignAdInfo object in the response contains a list of up to // three headlines and two descriptions. Note that some of the suggestions // may have empty strings as text. Before setting these on the ad you should // review them and filter out any empty values. SmartCampaignAdInfo adSuggestions = response.AdInfo; if (adSuggestions != null) { Console.WriteLine($"The following headlines were suggested:"); foreach (AdTextAsset headline in adSuggestions.Headlines) { Console.WriteLine($"\t{headline.Text}"); } Console.WriteLine($"And the following descriptions were suggested:"); foreach (AdTextAsset description in adSuggestions.Descriptions) { Console.WriteLine($"\t{description.Text}"); } } else { Console.WriteLine("No ad suggestions were found."); adSuggestions = new SmartCampaignAdInfo(); } return adSuggestions; } // [END add_smart_campaign_10] // [START add_smart_campaign_2] /// <summary> /// Creates a MutateOperation that creates a new CampaignBudget. /// A temporary ID will be assigned to this campaign budget so that it can be referenced by /// other objects being created in the same Mutate request. /// </summary> /// <param name="customerId">The Google Ads customer ID.</param> /// <param name="suggestedBudgetAmount">A daily amount budget in micros.</param> /// <returns>A MutateOperation that creates a CampaignBudget</returns> private MutateOperation CreateCampaignBudgetOperation(long customerId, long suggestedBudgetAmount) { return new MutateOperation { CampaignBudgetOperation = new CampaignBudgetOperation { Create = new CampaignBudget { Name = $"Smart campaign budget #{ExampleUtilities.GetRandomString()}", // A budget used for Smart campaigns must have the type SMART_CAMPAIGN. Type = BudgetType.SmartCampaign, // The suggested budget amount from the SmartCampaignSuggestService is a // daily budget. We don't need to specify that here, because the budget // period already defaults to DAILY. AmountMicros = suggestedBudgetAmount, // Set a temporary ID in the budget's resource name so it can be referenced // by the campaign in later steps. ResourceName = ResourceNames.CampaignBudget( customerId, BUDGET_TEMPORARY_ID) } } }; } // [END add_smart_campaign_2] // [START add_smart_campaign_3] /// <summary> /// Creates a MutateOperation that creates a new Smart campaign. /// A temporary ID will be assigned to this campaign so that it can be referenced by other /// objects being created in the same Mutate request. /// </summary> /// <param name="customerId">The Google Ads customer ID.</param> /// <returns>A MutateOperation that creates a campaign.</returns> private MutateOperation CreateSmartCampaignOperation(long customerId) { return new MutateOperation { CampaignOperation = new CampaignOperation { Create = new Campaign { Name = $"Smart campaign #{ExampleUtilities.GetRandomString()}", // Set the campaign status as PAUSED. The campaign is the only entity in // the mutate request that should have its status set. Status = CampaignStatus.Paused, // AdvertisingChannelType must be SMART. AdvertisingChannelType = AdvertisingChannelType.Smart, // AdvertisingChannelSubType must be SMART_CAMPAIGN. AdvertisingChannelSubType = AdvertisingChannelSubType.SmartCampaign, // Assign the resource name with a temporary ID. ResourceName = ResourceNames.Campaign(customerId, SMART_CAMPAIGN_TEMPORARY_ID), // Set the budget using the given budget resource name. CampaignBudget = ResourceNames.CampaignBudget(customerId, BUDGET_TEMPORARY_ID) } } }; } // [END add_smart_campaign_3] // [START add_smart_campaign_4] /// <summary> /// Creates a MutateOperation to create a new SmartCampaignSetting. SmartCampaignSettings /// are unique in that they only support UPDATE operations, which are used to update and /// create them. Below we will use a temporary ID in the resource name to associate it with /// the campaign created in the previous step. /// </summary> /// <param name="customerId">The Google Ads customer ID.</param> /// <param name="businessLocationId">The ID of a Business Profile location.</param> /// <param name="businessName">The name of a Business Profile business.</param> /// <returns>A MutateOperation that creates a SmartCampaignSetting.</returns> private MutateOperation CreateSmartCampaignSettingOperation(long customerId, ulong? businessLocationId, string businessName) { SmartCampaignSetting smartCampaignSetting = new SmartCampaignSetting { // Set a temporary ID in the campaign setting's resource name to associate it with // the campaign created in the previous step. ResourceName = ResourceNames.SmartCampaignSetting(customerId, SMART_CAMPAIGN_TEMPORARY_ID), // Below we configure the SmartCampaignSetting using many of the same details used // to generate a budget suggestion. PhoneNumber = new SmartCampaignSetting.Types.PhoneNumber { CountryCode = COUNTRY_CODE, PhoneNumber_ = PHONE_NUMBER }, FinalUrl = LANDING_PAGE_URL, AdvertisingLanguageCode = LANGUAGE_CODE }; // Either a business location ID or a business name must be added to the // SmartCampaignSetting. if (businessLocationId.HasValue) { // Transform Google Business Location ID to a compatible format before // passing it onto the API. smartCampaignSetting.BusinessLocationId = ConvertBusinessLocationId(businessLocationId.Value); } else { smartCampaignSetting.BusinessName = businessName; } return new MutateOperation { SmartCampaignSettingOperation = new SmartCampaignSettingOperation { Update = smartCampaignSetting, // Set the update mask on the operation. This is required since the smart // campaign setting is created in an UPDATE operation. Here the update mask // will be a list of all the fields that were set on the SmartCampaignSetting. UpdateMask = FieldMasks.AllSetFieldsOf(smartCampaignSetting) } }; } // [END add_smart_campaign_4] // [START add_smart_campaign_8] /// <summary> /// Creates a list of MutateOperations that create new campaign criteria. /// </summary> /// <param name="customerId">The Google Ads customer ID.</param> /// <param name="keywordThemeInfos">A list of KeywordThemeInfos.</param> /// <param name="suggestionInfo">A SmartCampaignSuggestionInfo instance.</param> /// <returns>A list of MutateOperations that create new campaign criteria.</returns> private IEnumerable<MutateOperation> CreateCampaignCriterionOperations(long customerId, IEnumerable<KeywordThemeInfo> keywordThemeInfos, SmartCampaignSuggestionInfo suggestionInfo) { List<MutateOperation> mutateOperations = keywordThemeInfos.Select( keywordThemeInfo => new MutateOperation { CampaignCriterionOperation = new CampaignCriterionOperation { Create = new CampaignCriterion { // Set the campaign ID to a temporary ID. Campaign = ResourceNames.Campaign( customerId, SMART_CAMPAIGN_TEMPORARY_ID), // Set the keyword theme to each KeywordThemeInfo in turn. KeywordTheme = keywordThemeInfo, } } }).ToList(); // Create a location criterion for each location in the suggestion info. mutateOperations.AddRange( suggestionInfo.LocationList.Locations.Select( locationInfo => new MutateOperation() { CampaignCriterionOperation = new CampaignCriterionOperation() { Create = new CampaignCriterion() { // Set the campaign ID to a temporary ID. Campaign = ResourceNames.Campaign(customerId, SMART_CAMPAIGN_TEMPORARY_ID), // Set the location to the given location. Location = locationInfo } } }).ToList() ); return mutateOperations; } // [END add_smart_campaign_8] // [START add_smart_campaign_5] /// <summary> /// Creates a MutateOperation that creates a new ad group. /// A temporary ID will be used in the campaign resource name for this ad group to /// associate it with the Smart campaign created in earlier steps. A temporary ID will /// also be used for its own resource name so that we can associate an ad group ad with /// it later in the process. /// Only one ad group can be created for a given Smart campaign. /// </summary> /// <param name="customerId">The Google Ads customer ID.</param> /// <returns>A MutateOperation that creates a new ad group.</returns> private MutateOperation CreateAdGroupOperation(long customerId) { return new MutateOperation { AdGroupOperation = new AdGroupOperation { Create = new AdGroup { // Set the ad group ID to a temporary ID. ResourceName = ResourceNames.AdGroup(customerId, AD_GROUP_TEMPORARY_ID), Name = $"Smart campaign ad group #{ExampleUtilities.GetRandomString()}", // Set the campaign ID to a temporary ID. Campaign = ResourceNames.Campaign(customerId, SMART_CAMPAIGN_TEMPORARY_ID), // The ad group type must be SmartCampaignAds. Type = AdGroupType.SmartCampaignAds } } }; } // [END add_smart_campaign_5] // [START add_smart_campaign_6] /// <summary> /// Creates a MutateOperation that creates a new ad group ad. /// A temporary ID will be used in the ad group resource name for this ad group ad to /// associate it with the ad group created in earlier steps. /// </summary> /// <param name="customerId">The Google Ads customer ID.</param> /// <param name="adSuggestions">SmartCampaignAdInfo with ad creative /// suggestions.</param> /// <returns>A MutateOperation that creates a new ad group ad.</returns> private MutateOperation CreateAdGroupAdOperation(long customerId, SmartCampaignAdInfo adSuggestions) { AdGroupAd adGroupAd = new AdGroupAd { AdGroup = ResourceNames.AdGroup(customerId, AD_GROUP_TEMPORARY_ID), Ad = new Ad { SmartCampaignAd = new SmartCampaignAdInfo(), }, }; SmartCampaignAdInfo ad = adGroupAd.Ad.SmartCampaignAd; // The SmartCampaignAdInfo object includes headlines and descriptions // retrieved from the SmartCampaignSuggestService.SuggestSmartCampaignAd // method. It's recommended that users review and approve or update these // creatives before they're set on the ad. It's possible that some or all of // these assets may contain empty texts, which should not be set on the ad // and instead should be replaced with meaninful texts from the user. Below // we just accept the creatives that were suggested while filtering out empty // assets. If no headlines or descriptions were suggested, then we manually // add some, otherwise this operation will generate an INVALID_ARGUMENT // error. Individual workflows will likely vary here. ad.Headlines.Add(adSuggestions.Headlines); ad.Descriptions.Add(adSuggestions.Descriptions); // If there are fewer headlines than are required, we manually add additional // headlines to make up for the difference. if (adSuggestions.Headlines.Count() < NUM_REQUIRED_HEADLINES) { for (int i = 0; i < NUM_REQUIRED_HEADLINES - adSuggestions.Headlines.Count(); i++) { ad.Headlines.Add(new AdTextAsset() { Text = $"Placeholder headline {i + 1}" }); } } // If there are fewer descriptions than are required, we manually add // additional descriptions to make up for the difference. if (adSuggestions.Descriptions.Count() < NUM_REQUIRED_DESCRIPTIONS) { for (int i = 0; i < NUM_REQUIRED_DESCRIPTIONS - adSuggestions.Descriptions.Count(); i++) { ad.Descriptions.Add(new AdTextAsset() { Text = $"Placeholder description {i + 1}" }); } } return new MutateOperation { AdGroupAdOperation = new AdGroupAdOperation { Create = adGroupAd } }; } // [END add_smart_campaign_6] // [START add_smart_campaign_14] /// <summary> /// Converts the business location ID from the format returned by Business Profile /// to the format expected by the API. /// </summary> /// <param name="businessLocationId">The business location identifier.</param> /// <returns>The transformed ID.</returns> private long ConvertBusinessLocationId(ulong businessLocationId) { // The business location ID is an unsigned 64-bit integer. However, the Google Ads API // expects a signed 64-bit integer. So we convert the unsigned ID into a signed ID, // while allowing an overflow, so that the ID wraps around if it is too large. return unchecked((long) businessLocationId); } // [END add_smart_campaign_14] /// <summary> /// Prints the details of a MutateGoogleAdsResponse. Parses the "response" oneof field name /// and uses it to extract the new entity's name and resource name. /// </summary> /// <param name="response">A MutateGoogleAdsResponse instance.</param> private void PrintResponseDetails(MutateGoogleAdsResponse response) { // Parse the Mutate response to print details about the entities that were created // in the request. foreach (MutateOperationResponse operationResponse in response.MutateOperationResponses) { string resourceName = "<not found>"; string entityName = operationResponse.ResponseCase.ToString(); // Trim the substring "Result" from the end of the entity name. entityName = entityName.Remove(entityName.Length - 6); switch (operationResponse.ResponseCase) { case MutateOperationResponse.ResponseOneofCase.AdGroupResult: resourceName = operationResponse.AdGroupResult.ResourceName; break; case MutateOperationResponse.ResponseOneofCase.AdGroupAdResult: resourceName = operationResponse.AdGroupAdResult.ResourceName; break; case MutateOperationResponse.ResponseOneofCase.CampaignResult: resourceName = operationResponse.CampaignResult.ResourceName; break; case MutateOperationResponse.ResponseOneofCase.CampaignBudgetResult: resourceName = operationResponse.CampaignBudgetResult.ResourceName; break; case MutateOperationResponse.ResponseOneofCase.CampaignCriterionResult: resourceName = operationResponse.CampaignCriterionResult.ResourceName; break; case MutateOperationResponse.ResponseOneofCase.SmartCampaignSettingResult: resourceName = operationResponse.SmartCampaignSettingResult.ResourceName; break; } Console.WriteLine( $"Created a(n) {entityName} with resource name: '{resourceName}'."); } } } }
#region Using using System.Collections.Generic; using System.Diagnostics; using System.Drawing; using System.Linq; using System.Windows.Forms; using TribalWars.Maps.Manipulators.EventArg; using TribalWars.Villages; using TribalWars.Worlds.Events; using TribalWars.Worlds.Events.Impls; #endregion namespace TribalWars.Maps.Manipulators.Implementations { /// <summary> /// Draws circles around the villages of the owner /// of the village the user last hovered over /// </summary> internal class ActiveVillageManipulator : ManipulatorBase { #region Fields private Tribe _pinPointedTribe; private Village _selectedVillage; private Village _pinPointedVillage; private Village _unpinpointedVillage; private bool _lockPinpointedVillage; private readonly Pen _pinpointedPen; private readonly Pen _pinpointedAnimationPen; private int _pinpointedAnimationCounter; private readonly Pen _newVillagesPen; private readonly Pen _lostVillagesPen; private readonly Pen _otherVillagesPen; #endregion #region Constructors public ActiveVillageManipulator(Map map) : base(map) { _newVillagesPen = new Pen(Color.Chartreuse, 2); _lostVillagesPen = new Pen(Color.Violet, 2); _otherVillagesPen = new Pen(Color.White, 2); _pinpointedPen = new Pen(Color.CornflowerBlue, 2); _pinpointedAnimationPen = new Pen(Color.Black, 2); _map.EventPublisher.VillagesSelected += EventPublisher_VillagesSelected; _map.EventPublisher.PlayerSelected += EventPublisher_VillagesSelected; _map.EventPublisher.TribeSelected += EventPublisher_VillagesSelected; } #endregion #region Methods protected internal override bool MouseMoveCore(MapMouseMoveEventArgs e) { if (e.Village != null && _pinPointedVillage == null && _unpinpointedVillage != e.Village) { if (_selectedVillage != e.Village) { _map.EventPublisher.SelectVillages(this, e.Village, VillageTools.SelectVillage); _selectedVillage = e.Village; _unpinpointedVillage = null; return true; } } if (e.Village == null && _pinPointedVillage == null && _selectedVillage != null) { _selectedVillage = null; _map.EventPublisher.Deselect(this); return true; } return false; } public override void Paint(MapPaintEventArgs e, bool isActiveManipulator) { if (isActiveManipulator) { Rectangle gameSize = _map.Display.GetGameRectangle(); Debug.Assert(new Rectangle(new Point(0, 0), _map.CanvasSize) == e.FullMapRectangle); var villageDimension = _map.Display.Dimensions.SizeWithSpacing; if (_pinPointedTribe != null) { foreach (Player player in _pinPointedTribe.Players) { IEnumerable<Village> uneventfulVillages = GetUneventfulVillages(player); DrawVillageMarkers(e.Graphics, uneventfulVillages, gameSize, _otherVillagesPen, villageDimension); } // Gained & lost villages: foreach (Player player in _pinPointedTribe.Players) { DrawVillageMarkers(e.Graphics, player.GainedVillages, gameSize, _newVillagesPen, villageDimension); DrawVillageMarkers(e.Graphics, player.LostVillages, gameSize, _lostVillagesPen, villageDimension); } } else { Village village = _pinPointedVillage ?? _selectedVillage; if (village != null) { if (village.HasPlayer) { IEnumerable<Village> uneventfulVillages = GetUneventfulVillages(village.Player); DrawVillageMarkers(e.Graphics, uneventfulVillages, gameSize, _otherVillagesPen, villageDimension); // Gained & lost villages: DrawVillageMarkers(e.Graphics, village.Player.GainedVillages, gameSize, _newVillagesPen, villageDimension); DrawVillageMarkers(e.Graphics, village.Player.LostVillages, gameSize, _lostVillagesPen, villageDimension); } else if (village.PreviousVillageDetails != null && village.PreviousVillageDetails.HasPlayer) { // Newly barbarian DrawVillageMarkers(e.Graphics, village.PreviousVillageDetails.Player.Villages, gameSize, _otherVillagesPen, villageDimension); } } } } } protected internal override bool OnVillageClickCore(MapVillageEventArgs e) { if (_pinPointedVillage != null) { if (_pinPointedVillage == e.Village) { _unpinpointedVillage = e.Village; _pinPointedVillage = null; _selectedVillage = null; _lockPinpointedVillage = false; _map.EventPublisher.Deselect(this); return true; } else if (_lockPinpointedVillage) { return false; } else { _pinPointedVillage = e.Village; _map.EventPublisher.SelectVillages(this, e.Village, VillageTools.PinPoint); return true; } } _map.EventPublisher.SelectVillages(this, e.Village, VillageTools.PinPoint); return _selectedVillage != e.Village; } protected internal override bool OnKeyDownCore(MapKeyEventArgs e) { if (e.KeyEventArgs.KeyData == Keys.L && _pinPointedVillage != null) { _lockPinpointedVillage = !_lockPinpointedVillage; } return false; } /// <summary> /// Cleanup anything when switching worlds or settings /// </summary> protected internal override void CleanUp() { _selectedVillage = null; _pinPointedTribe = null; _lockPinpointedVillage = false; _unpinpointedVillage = null; } public override void TimerPaint(MapTimerPaintEventArgs e) { if (e.IsActiveManipulator) { e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; Village village = _pinPointedVillage ?? _selectedVillage; if (village != null) { var villageSize = _map.Display.Dimensions.SizeWithSpacing; Point mapLocation = _map.Display.GetMapLocation(village.Location); const int xOff = 5; const int yOff = 10; _pinpointedAnimationCounter += 5; if (_pinpointedAnimationCounter > 360) _pinpointedAnimationCounter = 0; e.Graphics.DrawEllipse( _lockPinpointedVillage ? _pinpointedAnimationPen : _pinpointedPen, mapLocation.X - xOff, mapLocation.Y - xOff, villageSize.Width + yOff, villageSize.Height + yOff); e.Graphics.DrawArc( _lockPinpointedVillage ? _pinpointedPen : _pinpointedAnimationPen, mapLocation.X - xOff, mapLocation.Y - xOff, villageSize.Width + yOff, villageSize.Height + yOff, _pinpointedAnimationCounter, 30); } } } private void EventPublisher_VillagesSelected(object sender, VillagesEventArgs e) { if (e.Tool == VillageTools.PinPoint) { var tribe = e.Villages as Tribe; if (tribe != null) { _pinPointedTribe = tribe; _pinPointedVillage = null; _selectedVillage = null; _lockPinpointedVillage = false; } else { _pinPointedTribe = null; _pinPointedVillage = e.FirstVillage; } } } public override void Dispose() { _newVillagesPen.Dispose(); _lostVillagesPen.Dispose(); _otherVillagesPen.Dispose(); _pinpointedPen.Dispose(); _pinpointedAnimationPen.Dispose(); } #endregion #region Privates private IEnumerable<Village> GetUneventfulVillages(Player player) { return player.Where(x => !player.GainedVillages.Contains(x) && !player.LostVillages.Contains(x)); } private void DrawVillageMarkers(Graphics g, IEnumerable<Village> villages, Rectangle gameSize, Pen pen, Size villageDimension) { foreach (Village village in villages) { if (gameSize.Contains(village.Location)) { Point villageLocation = _map.Display.GetMapLocation(village.Location); g.DrawEllipse( pen, villageLocation.X, villageLocation.Y, villageDimension.Width, villageDimension.Height); } } } #endregion } }
/* Copyright (c) Citrix Systems Inc. * All rights reserved. * * Redistribution and use in source and binary forms, * with or without modification, are permitted provided * that the following conditions are met: * * * Redistributions of source code must retain the above * copyright notice, this list of conditions and the * following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the * following disclaimer in the documentation and/or other * materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ using System; using System.Drawing; using System.Drawing.Drawing2D; using System.Runtime.InteropServices; using System.Windows.Forms; using XenAdmin.Core; namespace XenAdmin.Controls { /// <summary> /// Taken from /// http://209.85.165.104/search?q=cache:hnUUN2Zhi7YJ:www.developersdex.com/vb/message.asp%3Fp%3D2927%26r%3D5855234+NativeMethods.GetDCEx&hl=en&ct=clnk&cd=1&gl=uk&client=firefox-a /// </summary> public class BlueBorderPanel : DoubleBufferedPanel { private Color borderColor = Drawing.XPBorderColor; public Color BorderColor { get { return borderColor; } set { if (borderColor != value) { borderColor = value; NativeMethods.SendMessage(this.Handle, NativeMethods.WM_NCPAINT, (IntPtr)1, IntPtr.Zero); } } } protected override void OnResize(EventArgs e) { base.OnResize(e); NativeMethods.SendMessage(this.Handle, NativeMethods.WM_NCPAINT, (IntPtr)1, IntPtr.Zero); } protected override void WndProc(ref Message m) { if (m.Msg == NativeMethods.WM_NCPAINT) { if (this.Parent != null) { NCPaint(); m.WParam = GetHRegion(); base.DefWndProc(ref m); NativeMethods.DeleteObject(m.WParam); m.Result = (IntPtr)1; } } base.WndProc(ref m); } private void NCPaint() { if (this.Parent == null) return; if (this.Width <= 0 || this.Height <= 0) return; IntPtr windowDC = NativeMethods.GetDCEx(this.Handle, IntPtr.Zero, NativeMethods.DCX_CACHE | NativeMethods.DCX_WINDOW | NativeMethods.DCX_CLIPSIBLINGS | NativeMethods.DCX_LOCKWINDOWUPDATE); if (windowDC.Equals(IntPtr.Zero)) return; using (Bitmap bm = new Bitmap(this.Width, this.Height, System.Drawing.Imaging.PixelFormat.Format32bppPArgb)) { using (Graphics g = Graphics.FromImage(bm)) { Rectangle borderRect = new Rectangle(0, 0, Width - 1, Height - 1); using (Pen borderPen = new Pen(this.borderColor, 1)) { borderPen.Alignment = PenAlignment.Inset; g.DrawRectangle(borderPen, borderRect); } // Create and Apply a Clip Region to the WindowDC using (Region Rgn = new Region(new Rectangle(0, 0, Width, Height))) { Rgn.Exclude(new Rectangle(1, 1, Width - 2, Height - 2)); IntPtr hRgn = Rgn.GetHrgn(g); if (!hRgn.Equals(IntPtr.Zero)) NativeMethods.SelectClipRgn(windowDC, hRgn); IntPtr bmDC = g.GetHdc(); IntPtr hBmp = bm.GetHbitmap(); IntPtr oldDC = NativeMethods.SelectObject(bmDC, hBmp); NativeMethods.BitBlt(windowDC, 0, 0, bm.Width, bm.Height, bmDC, 0, 0, NativeMethods.SRCCOPY); NativeMethods.SelectClipRgn(windowDC, IntPtr.Zero); NativeMethods.DeleteObject(hRgn); g.ReleaseHdc(bmDC); NativeMethods.SelectObject(oldDC, hBmp); NativeMethods.DeleteObject(hBmp); bm.Dispose(); } } } NativeMethods.ReleaseDC(this.Handle, windowDC); } private IntPtr GetHRegion() { //Define a Clip Region to pass back to WM_NCPAINTs wParam. //Must be in Screen Coordinates. IntPtr hRgn; Rectangle winRect = this.Parent.RectangleToScreen(this.Bounds); Rectangle clientRect = this.RectangleToScreen(this.ClientRectangle); Region updateRegion = new Region(winRect); updateRegion.Complement(clientRect); using (Graphics g = this.CreateGraphics()) hRgn = updateRegion.GetHrgn(g); updateRegion.Dispose(); return hRgn; } } internal class NativeMethods { [DllImport("user32.dll")] public static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam); [DllImport("gdi32.dll")] public static extern int SelectClipRgn(IntPtr hdc, IntPtr hrgn); [DllImport("gdi32.dll")] public static extern IntPtr SelectObject(IntPtr hdc, IntPtr hgdiobj); [DllImport("gdi32.dll")] public static extern bool BitBlt(IntPtr hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, IntPtr hdcSrc, int nXSrc, int nYSrc, int dwRop); [DllImport("gdi32.dll")] public static extern bool DeleteObject(IntPtr hObject); [DllImport("user32.dll")] public static extern IntPtr GetDCEx(IntPtr hWnd, IntPtr hrgnClip, int flags); [DllImport("user32.dll")] public static extern int ReleaseDC(IntPtr hWnd, IntPtr hDC); public const int WM_NCPAINT = 0x85; public const int DCX_WINDOW = 0x1; public const int DCX_CACHE = 0x2; public const int DCX_CLIPCHILDREN = 0x8; public const int DCX_CLIPSIBLINGS = 0x10; public const int DCX_LOCKWINDOWUPDATE = 0x400; public const int SRCCOPY = 0xCC0020; } }
// // System.Web.HttpPostedFile.cs // // Author: // Dick Porter <[email protected]> // Ben Maurer <[email protected]> // Miguel de Icaza <[email protected]> // // Copyright (C) 2005 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System.IO; using System.Security.Permissions; using System; namespace HTTP.Net { public sealed class HttpPostedFile { string name; string content_type; Stream stream; class ReadSubStream : Stream { Stream s; long offset; long end; long position; public ReadSubStream (Stream s, long offset, long length) { this.s = s; this.offset = offset; this.end = offset + length; position = offset; } public override void Flush () { } public override int Read (byte [] buffer, int dest_offset, int count) { if (buffer == null) throw new ArgumentNullException ("buffer"); if (dest_offset < 0) throw new ArgumentOutOfRangeException ("dest_offset", "< 0"); if (count < 0) throw new ArgumentOutOfRangeException ("count", "< 0"); int len = buffer.Length; if (dest_offset > len) throw new ArgumentException ("destination offset is beyond array size"); // reordered to avoid possible integer overflow if (dest_offset > len - count) throw new ArgumentException ("Reading would overrun buffer"); if (count > end - position) count = (int) (end - position); if (count <= 0) return 0; s.Position = position; int result = s.Read (buffer, dest_offset, count); if (result > 0) position += result; else position = end; return result; } public override int ReadByte () { if (position >= end) return -1; s.Position = position; int result = s.ReadByte (); if (result < 0) position = end; else position++; return result; } public override long Seek (long d, SeekOrigin origin) { long real; switch (origin) { case SeekOrigin.Begin: real = offset + d; break; case SeekOrigin.End: real = end + d; break; case SeekOrigin.Current: real = position + d; break; default: throw new ArgumentException (); } long virt = real - offset; if (virt < 0 || virt > Length) throw new ArgumentException (); position = s.Seek (real, SeekOrigin.Begin); return position; } public override void SetLength (long value) { throw new NotSupportedException (); } public override void Write (byte [] buffer, int offset, int count) { throw new NotSupportedException (); } public override bool CanRead { get { return true; } } public override bool CanSeek { get { return true; } } public override bool CanWrite { get { return false; } } public override long Length { get { return end - offset; } } public override long Position { get { return position - offset; } set { if (value > Length) throw new ArgumentOutOfRangeException (); position = Seek (value, SeekOrigin.Begin); } } } internal HttpPostedFile (string name, string content_type, Stream base_stream, long offset, long length) { this.name = name; this.content_type = content_type; this.stream = new ReadSubStream (base_stream, offset, length); } public string ContentType { get { return (content_type); } } public int ContentLength { get { return (int)stream.Length; } } public string FileName { get { return (name); } } public Stream InputStream { get { return (stream); } } public void SaveAs (string filename) { byte [] buffer = new byte [16*1024]; long old_post = stream.Position; try { File.Delete (filename); using (FileStream fs = File.Create (filename)){ stream.Position = 0; int n; while ((n = stream.Read (buffer, 0, 16*1024)) != 0){ fs.Write (buffer, 0, n); } } } finally { stream.Position = old_post; } } } }
// 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.Linq; using System.Net.Http.Headers; using System.Net.Mail; using System.Text; using Xunit; namespace System.Net.Http.Tests { public class HttpRequestHeadersTest { private HttpRequestHeaders headers; public HttpRequestHeadersTest() { headers = new HttpRequestHeaders(); } #region Request headers [Fact] public void Accept_AddInvalidValueUsingUnusualCasing_ParserRetrievedUsingCaseInsensitiveComparison() { // Use uppercase header name to make sure the parser gets retrieved using case-insensitive comparison. Assert.Throws<FormatException>(() => { headers.Add("AcCePt", "this is invalid"); }); } [Fact] public void Accept_ReadAndWriteProperty_ValueMatchesPriorSetValue() { MediaTypeWithQualityHeaderValue value1 = new MediaTypeWithQualityHeaderValue("text/plain"); value1.CharSet = "utf-8"; value1.Quality = 0.5; value1.Parameters.Add(new NameValueHeaderValue("custom", "value")); MediaTypeWithQualityHeaderValue value2 = new MediaTypeWithQualityHeaderValue("text/plain"); value2.CharSet = "iso-8859-1"; value2.Quality = 0.3868; Assert.Equal(0, headers.Accept.Count); headers.Accept.Add(value1); headers.Accept.Add(value2); Assert.Equal(2, headers.Accept.Count); Assert.Equal(value1, headers.Accept.ElementAt(0)); Assert.Equal(value2, headers.Accept.ElementAt(1)); headers.Accept.Clear(); Assert.Equal(0, headers.Accept.Count); } [Fact] public void Accept_ReadEmptyProperty_EmptyCollection() { HttpRequestMessage request = new HttpRequestMessage(); Assert.Equal(0, request.Headers.Accept.Count); // Copy to another list List<MediaTypeWithQualityHeaderValue> accepts = request.Headers.Accept.ToList(); Assert.Equal(0, accepts.Count); accepts = new List<MediaTypeWithQualityHeaderValue>(request.Headers.Accept); Assert.Equal(0, accepts.Count); } [Fact] public void Accept_UseAddMethod_AddedValueCanBeRetrievedUsingProperty() { headers.TryAddWithoutValidation("Accept", ",, , ,,text/plain; charset=iso-8859-1; q=1.0,\r\n */xml; charset=utf-8; q=0.5,,,"); MediaTypeWithQualityHeaderValue value1 = new MediaTypeWithQualityHeaderValue("text/plain"); value1.CharSet = "iso-8859-1"; value1.Quality = 1.0; MediaTypeWithQualityHeaderValue value2 = new MediaTypeWithQualityHeaderValue("*/xml"); value2.CharSet = "utf-8"; value2.Quality = 0.5; Assert.Equal(value1, headers.Accept.ElementAt(0)); Assert.Equal(value2, headers.Accept.ElementAt(1)); } [Fact] public void Accept_UseAddMethodWithInvalidValue_InvalidValueRecognized() { // Add a valid media-type with an invalid quality value headers.TryAddWithoutValidation("Accept", "text/plain; q=a"); // invalid quality Assert.NotNull(headers.Accept.First()); Assert.Null(headers.Accept.First().Quality); Assert.Equal("text/plain; q=a", headers.Accept.First().ToString()); headers.Clear(); headers.TryAddWithoutValidation("Accept", "text/plain application/xml"); // no separator Assert.Equal(0, headers.Accept.Count); Assert.Equal(1, headers.GetValues("Accept").Count()); Assert.Equal("text/plain application/xml", headers.GetValues("Accept").First()); } [Fact] public void AcceptCharset_ReadAndWriteProperty_ValueMatchesPriorSetValue() { Assert.Equal(0, headers.AcceptCharset.Count); headers.AcceptCharset.Add(new StringWithQualityHeaderValue("iso-8859-5")); headers.AcceptCharset.Add(new StringWithQualityHeaderValue("unicode-1-1", 0.8)); Assert.Equal(2, headers.AcceptCharset.Count); Assert.Equal(new StringWithQualityHeaderValue("iso-8859-5"), headers.AcceptCharset.ElementAt(0)); Assert.Equal(new StringWithQualityHeaderValue("unicode-1-1", 0.8), headers.AcceptCharset.ElementAt(1)); headers.AcceptCharset.Clear(); Assert.Equal(0, headers.AcceptCharset.Count); } [Fact] public void AcceptCharset_UseAddMethod_AddedValueCanBeRetrievedUsingProperty() { headers.TryAddWithoutValidation("Accept-Charset", ", ,,iso-8859-5 , \r\n utf-8 ; q=0.300 ,,,"); Assert.Equal(new StringWithQualityHeaderValue("iso-8859-5"), headers.AcceptCharset.ElementAt(0)); Assert.Equal(new StringWithQualityHeaderValue("utf-8", 0.3), headers.AcceptCharset.ElementAt(1)); } [Fact] public void AcceptCharset_UseAddMethodWithInvalidValue_InvalidValueRecognized() { headers.TryAddWithoutValidation("Accept-Charset", "iso-8859-5 utf-8"); // no separator Assert.Equal(0, headers.AcceptCharset.Count); Assert.Equal(1, headers.GetValues("Accept-Charset").Count()); Assert.Equal("iso-8859-5 utf-8", headers.GetValues("Accept-Charset").First()); headers.Clear(); headers.TryAddWithoutValidation("Accept-Charset", "utf-8; q=1; q=0.3"); Assert.Equal(0, headers.AcceptCharset.Count); Assert.Equal(1, headers.GetValues("Accept-Charset").Count()); Assert.Equal("utf-8; q=1; q=0.3", headers.GetValues("Accept-Charset").First()); } [Fact] public void AcceptCharset_AddMultipleValuesAndGetValueString_AllValuesAddedUsingTheCorrectDelimiter() { headers.TryAddWithoutValidation("Accept-Charset", "invalid value"); headers.Add("Accept-Charset", "utf-8"); headers.AcceptCharset.Add(new StringWithQualityHeaderValue("iso-8859-5", 0.5)); foreach (var header in headers.GetHeaderStrings()) { Assert.Equal("Accept-Charset", header.Key); Assert.Equal("utf-8, iso-8859-5; q=0.5, invalid value", header.Value); } } [Fact] public void AcceptEncoding_ReadAndWriteProperty_ValueMatchesPriorSetValue() { Assert.Equal(0, headers.AcceptEncoding.Count); headers.AcceptEncoding.Add(new StringWithQualityHeaderValue("compress", 0.9)); headers.AcceptEncoding.Add(new StringWithQualityHeaderValue("gzip")); Assert.Equal(2, headers.AcceptEncoding.Count); Assert.Equal(new StringWithQualityHeaderValue("compress", 0.9), headers.AcceptEncoding.ElementAt(0)); Assert.Equal(new StringWithQualityHeaderValue("gzip"), headers.AcceptEncoding.ElementAt(1)); headers.AcceptEncoding.Clear(); Assert.Equal(0, headers.AcceptEncoding.Count); } [Fact] public void AcceptEncoding_UseAddMethod_AddedValueCanBeRetrievedUsingProperty() { headers.TryAddWithoutValidation("Accept-Encoding", ", gzip; q=1.0, identity; q=0.5, *;q=0, "); Assert.Equal(new StringWithQualityHeaderValue("gzip", 1), headers.AcceptEncoding.ElementAt(0)); Assert.Equal(new StringWithQualityHeaderValue("identity", 0.5), headers.AcceptEncoding.ElementAt(1)); Assert.Equal(new StringWithQualityHeaderValue("*", 0), headers.AcceptEncoding.ElementAt(2)); headers.AcceptEncoding.Clear(); headers.TryAddWithoutValidation("Accept-Encoding", ""); Assert.Equal(0, headers.AcceptEncoding.Count); Assert.False(headers.Contains("Accept-Encoding")); } [Fact] public void AcceptEncoding_UseAddMethodWithInvalidValue_InvalidValueRecognized() { headers.TryAddWithoutValidation("Accept-Encoding", "gzip deflate"); // no separator Assert.Equal(0, headers.AcceptEncoding.Count); Assert.Equal(1, headers.GetValues("Accept-Encoding").Count()); Assert.Equal("gzip deflate", headers.GetValues("Accept-Encoding").First()); headers.Clear(); headers.TryAddWithoutValidation("Accept-Encoding", "compress; q=1; gzip"); Assert.Equal(0, headers.AcceptEncoding.Count); Assert.Equal(1, headers.GetValues("Accept-Encoding").Count()); Assert.Equal("compress; q=1; gzip", headers.GetValues("Accept-Encoding").First()); } [Fact] public void AcceptLanguage_ReadAndWriteProperty_ValueMatchesPriorSetValue() { Assert.Equal(0, headers.AcceptLanguage.Count); headers.AcceptLanguage.Add(new StringWithQualityHeaderValue("da")); headers.AcceptLanguage.Add(new StringWithQualityHeaderValue("en-GB", 0.8)); headers.AcceptLanguage.Add(new StringWithQualityHeaderValue("en", 0.7)); Assert.Equal(3, headers.AcceptLanguage.Count); Assert.Equal(new StringWithQualityHeaderValue("da"), headers.AcceptLanguage.ElementAt(0)); Assert.Equal(new StringWithQualityHeaderValue("en-GB", 0.8), headers.AcceptLanguage.ElementAt(1)); Assert.Equal(new StringWithQualityHeaderValue("en", 0.7), headers.AcceptLanguage.ElementAt(2)); headers.AcceptLanguage.Clear(); Assert.Equal(0, headers.AcceptLanguage.Count); } [Fact] public void AcceptLanguage_UseAddMethod_AddedValueCanBeRetrievedUsingProperty() { headers.TryAddWithoutValidation("Accept-Language", " , de-DE;q=0.9,de-AT;q=0.5,*;q=0.010 , "); Assert.Equal(new StringWithQualityHeaderValue("de-DE", 0.9), headers.AcceptLanguage.ElementAt(0)); Assert.Equal(new StringWithQualityHeaderValue("de-AT", 0.5), headers.AcceptLanguage.ElementAt(1)); Assert.Equal(new StringWithQualityHeaderValue("*", 0.01), headers.AcceptLanguage.ElementAt(2)); headers.AcceptLanguage.Clear(); headers.TryAddWithoutValidation("Accept-Language", ""); Assert.Equal(0, headers.AcceptLanguage.Count); Assert.False(headers.Contains("Accept-Language")); } [Fact] public void AcceptLanguage_UseAddMethodWithInvalidValue_InvalidValueRecognized() { headers.TryAddWithoutValidation("Accept-Language", "de -DE"); // no separator Assert.Equal(0, headers.AcceptLanguage.Count); Assert.Equal(1, headers.GetValues("Accept-Language").Count()); Assert.Equal("de -DE", headers.GetValues("Accept-Language").First()); headers.Clear(); headers.TryAddWithoutValidation("Accept-Language", "en; q=0.4,["); Assert.Equal(0, headers.AcceptLanguage.Count); Assert.Equal(1, headers.GetValues("Accept-Language").Count()); Assert.Equal("en; q=0.4,[", headers.GetValues("Accept-Language").First()); } [Fact] public void Expect_Add100Continue_Success() { // use non-default casing to make sure we do case-insensitive comparison. headers.Expect.Add(new NameValueWithParametersHeaderValue("100-CONTINUE")); Assert.True(headers.ExpectContinue == true); Assert.Equal(1, headers.Expect.Count); } [Fact] public void Expect_ReadAndWriteProperty_ValueMatchesPriorSetValue() { Assert.Equal(0, headers.Expect.Count); Assert.Null(headers.ExpectContinue); headers.Expect.Add(new NameValueWithParametersHeaderValue("custom1")); headers.Expect.Add(new NameValueWithParametersHeaderValue("custom2")); headers.ExpectContinue = true; // Connection collection has 2 values plus '100-Continue' Assert.Equal(3, headers.Expect.Count); Assert.Equal(3, headers.GetValues("Expect").Count()); Assert.True(headers.ExpectContinue == true, "ExpectContinue == true"); Assert.Equal(new NameValueWithParametersHeaderValue("custom1"), headers.Expect.ElementAt(0)); Assert.Equal(new NameValueWithParametersHeaderValue("custom2"), headers.Expect.ElementAt(1)); // Remove '100-continue' value from store. But leave other 'Expect' values. headers.ExpectContinue = false; Assert.True(headers.ExpectContinue == false, "ExpectContinue == false"); Assert.Equal(2, headers.Expect.Count); Assert.Equal(new NameValueWithParametersHeaderValue("custom1"), headers.Expect.ElementAt(0)); Assert.Equal(new NameValueWithParametersHeaderValue("custom2"), headers.Expect.ElementAt(1)); headers.ExpectContinue = true; headers.Expect.Clear(); Assert.True(headers.ExpectContinue == false, "ExpectContinue should be modified by Expect.Clear()."); Assert.Equal(0, headers.Expect.Count); IEnumerable<string> dummyArray; Assert.False(headers.TryGetValues("Expect", out dummyArray), "Expect header count after Expect.Clear()."); // Remove '100-continue' value from store. Since there are no other 'Expect' values, remove whole header. headers.ExpectContinue = false; Assert.True(headers.ExpectContinue == false, "ExpectContinue == false"); Assert.Equal(0, headers.Expect.Count); Assert.False(headers.Contains("Expect")); headers.ExpectContinue = null; Assert.Null(headers.ExpectContinue); } [Fact] public void Expect_UseAddMethod_AddedValueCanBeRetrievedUsingProperty() { headers.TryAddWithoutValidation("Expect", ", , 100-continue, name1 = value1, name2; param2=paramValue2, name3=value3; param3 ,"); // Connection collection has 3 values plus '100-continue' Assert.Equal(4, headers.Expect.Count); Assert.Equal(4, headers.GetValues("Expect").Count()); Assert.True(headers.ExpectContinue == true, "ExpectContinue expected to be true."); Assert.Equal(new NameValueWithParametersHeaderValue("100-continue"), headers.Expect.ElementAt(0)); Assert.Equal(new NameValueWithParametersHeaderValue("name1", "value1"), headers.Expect.ElementAt(1)); NameValueWithParametersHeaderValue expected2 = new NameValueWithParametersHeaderValue("name2"); expected2.Parameters.Add(new NameValueHeaderValue("param2", "paramValue2")); Assert.Equal(expected2, headers.Expect.ElementAt(2)); NameValueWithParametersHeaderValue expected3 = new NameValueWithParametersHeaderValue("name3", "value3"); expected3.Parameters.Add(new NameValueHeaderValue("param3")); Assert.Equal(expected3, headers.Expect.ElementAt(3)); headers.Expect.Clear(); Assert.Null(headers.ExpectContinue); Assert.Equal(0, headers.Expect.Count); IEnumerable<string> dummyArray; Assert.False(headers.TryGetValues("Expect", out dummyArray), "Expect header count after Expect.Clear()."); } [Fact] public void Expect_UseAddMethodWithInvalidValue_InvalidValueRecognized() { headers.TryAddWithoutValidation("Expect", "100-continue other"); // no separator Assert.Equal(0, headers.Expect.Count); Assert.Equal(1, headers.GetValues("Expect").Count()); Assert.Equal("100-continue other", headers.GetValues("Expect").First()); } [Fact] public void Host_ReadAndWriteProperty_ValueMatchesPriorSetValue() { Assert.Null(headers.Host); headers.Host = "host"; Assert.Equal("host", headers.Host); headers.Host = null; Assert.Null(headers.Host); Assert.False(headers.Contains("Host"), "Header store should not contain a header 'Host' after setting it to null."); Assert.Throws<FormatException>(() => { headers.Host = "invalid host"; }); } [Fact] public void Host_UseAddMethod_AddedValueCanBeRetrievedUsingProperty() { headers.TryAddWithoutValidation("Host", "host:80"); Assert.Equal("host:80", headers.Host); } [Fact] public void IfMatch_ReadAndWriteProperty_ValueMatchesPriorSetValue() { Assert.Equal(0, headers.IfMatch.Count); headers.IfMatch.Add(new EntityTagHeaderValue("\"custom1\"")); headers.IfMatch.Add(new EntityTagHeaderValue("\"custom2\"", true)); Assert.Equal(2, headers.IfMatch.Count); Assert.Equal(2, headers.GetValues("If-Match").Count()); Assert.Equal(new EntityTagHeaderValue("\"custom1\""), headers.IfMatch.ElementAt(0)); Assert.Equal(new EntityTagHeaderValue("\"custom2\"", true), headers.IfMatch.ElementAt(1)); headers.IfMatch.Clear(); Assert.Equal(0, headers.IfMatch.Count); Assert.False(headers.Contains("If-Match"), "Header store should not contain 'If-Match'"); } [Fact] public void IfMatch_UseAddMethod_AddedValueCanBeRetrievedUsingProperty() { headers.TryAddWithoutValidation("If-Match", ", , W/\"tag1\", \"tag2\", W/\"tag3\" ,"); Assert.Equal(3, headers.IfMatch.Count); Assert.Equal(3, headers.GetValues("If-Match").Count()); Assert.Equal(new EntityTagHeaderValue("\"tag1\"", true), headers.IfMatch.ElementAt(0)); Assert.Equal(new EntityTagHeaderValue("\"tag2\"", false), headers.IfMatch.ElementAt(1)); Assert.Equal(new EntityTagHeaderValue("\"tag3\"", true), headers.IfMatch.ElementAt(2)); headers.IfMatch.Clear(); headers.Add("If-Match", "*"); Assert.Equal(1, headers.IfMatch.Count); Assert.Same(EntityTagHeaderValue.Any, headers.IfMatch.ElementAt(0)); } [Fact] public void IfMatch_UseAddMethodWithInvalidInput_PropertyNotUpdated() { headers.TryAddWithoutValidation("If-Match", "W/\"tag1\" \"tag2\""); // no separator Assert.Equal(0, headers.IfMatch.Count); Assert.Equal(1, headers.GetValues("If-Match").Count()); } [Fact] public void IfNoneMatch_ReadAndWriteProperty_ValueMatchesPriorSetValue() { Assert.Equal(0, headers.IfNoneMatch.Count); headers.IfNoneMatch.Add(new EntityTagHeaderValue("\"custom1\"")); headers.IfNoneMatch.Add(new EntityTagHeaderValue("\"custom2\"", true)); Assert.Equal(2, headers.IfNoneMatch.Count); Assert.Equal(2, headers.GetValues("If-None-Match").Count()); Assert.Equal(new EntityTagHeaderValue("\"custom1\""), headers.IfNoneMatch.ElementAt(0)); Assert.Equal(new EntityTagHeaderValue("\"custom2\"", true), headers.IfNoneMatch.ElementAt(1)); headers.IfNoneMatch.Clear(); Assert.Equal(0, headers.IfNoneMatch.Count); Assert.False(headers.Contains("If-None-Match"), "Header store should not contain 'If-None-Match'"); } [Fact] public void IfNoneMatch_UseAddMethod_AddedValueCanBeRetrievedUsingProperty() { headers.TryAddWithoutValidation("If-None-Match", "W/\"tag1\", \"tag2\", W/\"tag3\""); Assert.Equal(3, headers.IfNoneMatch.Count); Assert.Equal(3, headers.GetValues("If-None-Match").Count()); Assert.Equal(new EntityTagHeaderValue("\"tag1\"", true), headers.IfNoneMatch.ElementAt(0)); Assert.Equal(new EntityTagHeaderValue("\"tag2\"", false), headers.IfNoneMatch.ElementAt(1)); Assert.Equal(new EntityTagHeaderValue("\"tag3\"", true), headers.IfNoneMatch.ElementAt(2)); headers.IfNoneMatch.Clear(); headers.Add("If-None-Match", "*"); Assert.Equal(1, headers.IfNoneMatch.Count); Assert.Same(EntityTagHeaderValue.Any, headers.IfNoneMatch.ElementAt(0)); } [Fact] public void TE_ReadAndWriteProperty_ValueMatchesPriorSetValue() { TransferCodingWithQualityHeaderValue value1 = new TransferCodingWithQualityHeaderValue("custom"); value1.Quality = 0.5; value1.Parameters.Add(new NameValueHeaderValue("name", "value")); TransferCodingWithQualityHeaderValue value2 = new TransferCodingWithQualityHeaderValue("custom"); value2.Quality = 0.3868; Assert.Equal(0, headers.TE.Count); headers.TE.Add(value1); headers.TE.Add(value2); Assert.Equal(2, headers.TE.Count); Assert.Equal(value1, headers.TE.ElementAt(0)); Assert.Equal(value2, headers.TE.ElementAt(1)); headers.TE.Clear(); Assert.Equal(0, headers.TE.Count); } [Fact] public void TE_UseAddMethod_AddedValueCanBeRetrievedUsingProperty() { headers.TryAddWithoutValidation("TE", ",custom1; param1=value1; q=1.0,,\r\n custom2; param2=value2; q=0.5 ,"); TransferCodingWithQualityHeaderValue value1 = new TransferCodingWithQualityHeaderValue("custom1"); value1.Parameters.Add(new NameValueHeaderValue("param1", "value1")); value1.Quality = 1.0; TransferCodingWithQualityHeaderValue value2 = new TransferCodingWithQualityHeaderValue("custom2"); value2.Parameters.Add(new NameValueHeaderValue("param2", "value2")); value2.Quality = 0.5; Assert.Equal(value1, headers.TE.ElementAt(0)); Assert.Equal(value2, headers.TE.ElementAt(1)); headers.Clear(); headers.TryAddWithoutValidation("TE", ""); Assert.False(headers.Contains("TE"), "'TE' header should not be added if it just has empty values."); } [Fact] public void Range_ReadAndWriteProperty_ValueMatchesPriorSetValue() { Assert.Null(headers.Range); RangeHeaderValue value = new RangeHeaderValue(1, 2); headers.Range = value; Assert.Equal(value, headers.Range); headers.Range = null; Assert.Null(headers.Range); } [Fact] public void Range_UseAddMethod_AddedValueCanBeRetrievedUsingProperty() { headers.TryAddWithoutValidation("Range", "custom= , ,1-2, -4 , "); RangeHeaderValue value = new RangeHeaderValue(); value.Unit = "custom"; value.Ranges.Add(new RangeItemHeaderValue(1, 2)); value.Ranges.Add(new RangeItemHeaderValue(null, 4)); Assert.Equal(value, headers.Range); } [Fact] public void Authorization_ReadAndWriteProperty_ValueMatchesPriorSetValue() { Assert.Null(headers.Authorization); headers.Authorization = new AuthenticationHeaderValue("Basic", "QWxhZGRpbjpvcGVuIHNlc2FtZQ=="); Assert.Equal(new AuthenticationHeaderValue("Basic", "QWxhZGRpbjpvcGVuIHNlc2FtZQ=="), headers.Authorization); headers.Authorization = null; Assert.Null(headers.Authorization); Assert.False(headers.Contains("Authorization"), "Header store should not contain a header 'Authorization' after setting it to null."); } [Fact] public void Authorization_UseAddMethod_AddedValueCanBeRetrievedUsingProperty() { headers.TryAddWithoutValidation("Authorization", "NTLM blob"); Assert.Equal(new AuthenticationHeaderValue("NTLM", "blob"), headers.Authorization); } [Fact] public void ProxyAuthorization_ReadAndWriteProperty_ValueMatchesPriorSetValue() { Assert.Null(headers.ProxyAuthorization); headers.ProxyAuthorization = new AuthenticationHeaderValue("Basic", "QWxhZGRpbjpvcGVuIHNlc2FtZQ=="); Assert.Equal(new AuthenticationHeaderValue("Basic", "QWxhZGRpbjpvcGVuIHNlc2FtZQ=="), headers.ProxyAuthorization); headers.ProxyAuthorization = null; Assert.Null(headers.ProxyAuthorization); Assert.False(headers.Contains("ProxyAuthorization"), "Header store should not contain a header 'ProxyAuthorization' after setting it to null."); } [Fact] public void ProxyAuthorization_UseAddMethod_AddedValueCanBeRetrievedUsingProperty() { headers.TryAddWithoutValidation("Proxy-Authorization", "NTLM blob"); Assert.Equal(new AuthenticationHeaderValue("NTLM", "blob"), headers.ProxyAuthorization); } [Fact] public void UserAgent_ReadAndWriteProperty_ValueMatchesPriorSetValue() { Assert.Equal(0, headers.UserAgent.Count); headers.UserAgent.Add(new ProductInfoHeaderValue("(custom1)")); headers.UserAgent.Add(new ProductInfoHeaderValue("custom2", "1.1")); Assert.Equal(2, headers.UserAgent.Count); Assert.Equal(2, headers.GetValues("User-Agent").Count()); Assert.Equal(new ProductInfoHeaderValue("(custom1)"), headers.UserAgent.ElementAt(0)); Assert.Equal(new ProductInfoHeaderValue("custom2", "1.1"), headers.UserAgent.ElementAt(1)); headers.UserAgent.Clear(); Assert.Equal(0, headers.UserAgent.Count); Assert.False(headers.Contains("User-Agent"), "User-Agent header should be removed after calling Clear()."); headers.UserAgent.Add(new ProductInfoHeaderValue("(comment)")); headers.UserAgent.Remove(new ProductInfoHeaderValue("(comment)")); Assert.Equal(0, headers.UserAgent.Count); Assert.False(headers.Contains("User-Agent"), "User-Agent header should be removed after removing last value."); } [Fact] public void UserAgent_UseAddMethod_AddedValueCanBeRetrievedUsingProperty() { headers.TryAddWithoutValidation("User-Agent", "Opera/9.80 (Windows NT 6.1; U; en) Presto/2.6.30 Version/10.63"); Assert.Equal(4, headers.UserAgent.Count); Assert.Equal(4, headers.GetValues("User-Agent").Count()); Assert.Equal(new ProductInfoHeaderValue("Opera", "9.80"), headers.UserAgent.ElementAt(0)); Assert.Equal(new ProductInfoHeaderValue("(Windows NT 6.1; U; en)"), headers.UserAgent.ElementAt(1)); Assert.Equal(new ProductInfoHeaderValue("Presto", "2.6.30"), headers.UserAgent.ElementAt(2)); Assert.Equal(new ProductInfoHeaderValue("Version", "10.63"), headers.UserAgent.ElementAt(3)); headers.UserAgent.Clear(); Assert.Equal(0, headers.UserAgent.Count); Assert.False(headers.Contains("User-Agent"), "User-Agent header should be removed after calling Clear()."); } [Fact] public void UserAgent_TryGetValuesAndGetValues_Malformed() { string malformedUserAgent = "Mozilla/4.0 (compatible (compatible; MSIE 8.0; Windows NT 6.1; Trident/7.0)"; headers.TryAddWithoutValidation("User-Agent", malformedUserAgent); Assert.True(headers.TryGetValues("User-Agent", out IEnumerable<string> ua)); Assert.Equal(1, ua.Count()); Assert.Equal(malformedUserAgent, ua.First()); Assert.Equal(malformedUserAgent, headers.GetValues("User-Agent").First()); } [Fact] public void UserAgent_UseAddMethodWithInvalidValue_InvalidValueRecognized() { headers.TryAddWithoutValidation("User-Agent", "custom\u4F1A"); Assert.Null(headers.GetParsedValues(KnownHeaders.UserAgent.Descriptor)); Assert.Equal(1, headers.GetValues("User-Agent").Count()); Assert.Equal("custom\u4F1A", headers.GetValues("User-Agent").First()); headers.Clear(); // Note that "User-Agent" uses whitespace as separators, so the following is an invalid value headers.TryAddWithoutValidation("User-Agent", "custom1, custom2"); Assert.Null(headers.GetParsedValues(KnownHeaders.UserAgent.Descriptor)); Assert.Equal(1, headers.GetValues("User-Agent").Count()); Assert.Equal("custom1, custom2", headers.GetValues("User-Agent").First()); headers.Clear(); headers.TryAddWithoutValidation("User-Agent", "custom1, "); Assert.Null(headers.GetParsedValues(KnownHeaders.UserAgent.Descriptor)); Assert.Equal(1, headers.GetValues("User-Agent").Count()); Assert.Equal("custom1, ", headers.GetValues("User-Agent").First()); headers.Clear(); headers.TryAddWithoutValidation("User-Agent", ",custom1"); Assert.Null(headers.GetParsedValues(KnownHeaders.UserAgent.Descriptor)); Assert.Equal(1, headers.GetValues("User-Agent").Count()); Assert.Equal(",custom1", headers.GetValues("User-Agent").First()); } [Fact] public void UserAgent_AddMultipleValuesAndGetValueString_AllValuesAddedUsingTheCorrectDelimiter() { headers.TryAddWithoutValidation("User-Agent", "custom\u4F1A"); headers.Add("User-Agent", "custom2/1.1"); headers.UserAgent.Add(new ProductInfoHeaderValue("(comment)")); foreach (var header in headers.GetHeaderStrings()) { Assert.Equal("User-Agent", header.Key); Assert.Equal("custom2/1.1 (comment) custom\u4F1A", header.Value); } } [Fact] public void IfRange_ReadAndWriteProperty_ValueMatchesPriorSetValue() { Assert.Null(headers.IfRange); headers.IfRange = new RangeConditionHeaderValue("\"x\""); Assert.Equal(1, headers.GetValues("If-Range").Count()); Assert.Equal(new RangeConditionHeaderValue("\"x\""), headers.IfRange); headers.IfRange = null; Assert.Null(headers.IfRange); Assert.False(headers.Contains("If-Range"), "If-Range header should be removed after calling Clear()."); } [Fact] public void IfRange_UseAddMethod_AddedValueCanBeRetrievedUsingProperty() { headers.TryAddWithoutValidation("If-Range", " W/\"tag\" "); Assert.Equal(new RangeConditionHeaderValue(new EntityTagHeaderValue("\"tag\"", true)), headers.IfRange); Assert.Equal(1, headers.GetValues("If-Range").Count()); headers.IfRange = null; Assert.Null(headers.IfRange); Assert.False(headers.Contains("If-Range"), "If-Range header should be removed after calling Clear()."); } [Fact] public void IfRange_UseAddMethodWithInvalidValue_InvalidValueRecognized() { headers.TryAddWithoutValidation("If-Range", "\"tag\"\u4F1A"); Assert.Null(headers.GetParsedValues(KnownHeaders.IfRange.Descriptor)); Assert.Equal(1, headers.GetValues("If-Range").Count()); Assert.Equal("\"tag\"\u4F1A", headers.GetValues("If-Range").First()); headers.Clear(); headers.TryAddWithoutValidation("If-Range", " \"tag\", "); Assert.Null(headers.GetParsedValues(KnownHeaders.IfRange.Descriptor)); Assert.Equal(1, headers.GetValues("If-Range").Count()); Assert.Equal(" \"tag\", ", headers.GetValues("If-Range").First()); } [Fact] public void From_ReadAndWriteProperty_ValueMatchesPriorSetValue() { Assert.Null(headers.From); headers.From = "[email protected]"; Assert.Equal("[email protected]", headers.From); headers.From = null; Assert.Null(headers.From); Assert.False(headers.Contains("From"), "Header store should not contain a header 'From' after setting it to null."); Assert.Throws<FormatException>(() => { headers.From = " "; }); Assert.Throws<FormatException>(() => { headers.From = "invalid email address"; }); } [Fact] public void From_UseAddMethod_AddedValueCanBeRetrievedUsingProperty() { headers.TryAddWithoutValidation("From", " \"My Name\" [email protected] "); Assert.Equal("\"My Name\" [email protected] ", headers.From); // The following encoded string represents the character sequence "\u4F1A\u5458\u670D\u52A1". headers.Clear(); headers.TryAddWithoutValidation("From", "=?utf-8?Q?=E4=BC=9A=E5=91=98=E6=9C=8D=E5=8A=A1?= <[email protected]>"); Assert.Equal("=?utf-8?Q?=E4=BC=9A=E5=91=98=E6=9C=8D=E5=8A=A1?= <[email protected]>", headers.From); } [Fact] public void From_UseAddMethodWithInvalidValue_InvalidValueRecognized() { headers.TryAddWithoutValidation("From", " [email protected] ,"); Assert.Null(headers.GetParsedValues(KnownHeaders.From.Descriptor)); Assert.Equal(1, headers.GetValues("From").Count()); Assert.Equal(" [email protected] ,", headers.GetValues("From").First()); headers.Clear(); headers.TryAddWithoutValidation("From", "info@"); Assert.Null(headers.GetParsedValues(KnownHeaders.From.Descriptor)); Assert.Equal(1, headers.GetValues("From").Count()); Assert.Equal("info@", headers.GetValues("From").First()); } [Fact] public void IfModifiedSince_ReadAndWriteProperty_ValueMatchesPriorSetValue() { Assert.Null(headers.IfModifiedSince); DateTimeOffset expected = DateTimeOffset.Now; headers.IfModifiedSince = expected; Assert.Equal(expected, headers.IfModifiedSince); headers.IfModifiedSince = null; Assert.Null(headers.IfModifiedSince); Assert.False(headers.Contains("If-Modified-Since"), "Header store should not contain a header 'IfModifiedSince' after setting it to null."); } [Fact] public void IfModifiedSince_UseAddMethod_AddedValueCanBeRetrievedUsingProperty() { headers.TryAddWithoutValidation("If-Modified-Since", " Sun, 06 Nov 1994 08:49:37 GMT "); Assert.Equal(new DateTimeOffset(1994, 11, 6, 8, 49, 37, TimeSpan.Zero), headers.IfModifiedSince); headers.Clear(); headers.TryAddWithoutValidation("If-Modified-Since", "Sun, 06 Nov 1994 08:49:37 GMT"); Assert.Equal(new DateTimeOffset(1994, 11, 6, 8, 49, 37, TimeSpan.Zero), headers.IfModifiedSince); } [Fact] public void IfModifiedSince_UseAddMethodWithInvalidValue_InvalidValueRecognized() { headers.TryAddWithoutValidation("If-Modified-Since", " Sun, 06 Nov 1994 08:49:37 GMT ,"); Assert.Null(headers.GetParsedValues(KnownHeaders.IfModifiedSince.Descriptor)); Assert.Equal(1, headers.GetValues("If-Modified-Since").Count()); Assert.Equal(" Sun, 06 Nov 1994 08:49:37 GMT ,", headers.GetValues("If-Modified-Since").First()); headers.Clear(); headers.TryAddWithoutValidation("If-Modified-Since", " Sun, 06 Nov "); Assert.Null(headers.GetParsedValues(KnownHeaders.IfModifiedSince.Descriptor)); Assert.Equal(1, headers.GetValues("If-Modified-Since").Count()); Assert.Equal(" Sun, 06 Nov ", headers.GetValues("If-Modified-Since").First()); } [Fact] public void IfUnmodifiedSince_ReadAndWriteProperty_ValueMatchesPriorSetValue() { Assert.Null(headers.IfUnmodifiedSince); DateTimeOffset expected = DateTimeOffset.Now; headers.IfUnmodifiedSince = expected; Assert.Equal(expected, headers.IfUnmodifiedSince); headers.IfUnmodifiedSince = null; Assert.Null(headers.IfUnmodifiedSince); Assert.False(headers.Contains("If-Unmodified-Since"), "Header store should not contain a header 'IfUnmodifiedSince' after setting it to null."); } [Fact] public void IfUnmodifiedSince_UseAddMethod_AddedValueCanBeRetrievedUsingProperty() { headers.TryAddWithoutValidation("If-Unmodified-Since", " Sun, 06 Nov 1994 08:49:37 GMT "); Assert.Equal(new DateTimeOffset(1994, 11, 6, 8, 49, 37, TimeSpan.Zero), headers.IfUnmodifiedSince); headers.Clear(); headers.TryAddWithoutValidation("If-Unmodified-Since", "Sun, 06 Nov 1994 08:49:37 GMT"); Assert.Equal(new DateTimeOffset(1994, 11, 6, 8, 49, 37, TimeSpan.Zero), headers.IfUnmodifiedSince); } [Fact] public void IfUnmodifiedSince_UseAddMethodWithInvalidValue_InvalidValueRecognized() { headers.TryAddWithoutValidation("If-Unmodified-Since", " Sun, 06 Nov 1994 08:49:37 GMT ,"); Assert.Null(headers.GetParsedValues(KnownHeaders.IfUnmodifiedSince.Descriptor)); Assert.Equal(1, headers.GetValues("If-Unmodified-Since").Count()); Assert.Equal(" Sun, 06 Nov 1994 08:49:37 GMT ,", headers.GetValues("If-Unmodified-Since").First()); headers.Clear(); headers.TryAddWithoutValidation("If-Unmodified-Since", " Sun, 06 Nov "); Assert.Null(headers.GetParsedValues(KnownHeaders.IfUnmodifiedSince.Descriptor)); Assert.Equal(1, headers.GetValues("If-Unmodified-Since").Count()); Assert.Equal(" Sun, 06 Nov ", headers.GetValues("If-Unmodified-Since").First()); } [Fact] public void Referrer_ReadAndWriteProperty_ValueMatchesPriorSetValue() { Assert.Null(headers.Referrer); Uri expected = new Uri("http://example.com/path/"); headers.Referrer = expected; Assert.Equal(expected, headers.Referrer); headers.Referrer = null; Assert.Null(headers.Referrer); Assert.False(headers.Contains("Referer"), "Header store should not contain a header 'Referrer' after setting it to null."); } [Fact] public void Referrer_UseAddMethod_AddedValueCanBeRetrievedUsingProperty() { headers.TryAddWithoutValidation("Referer", " http://www.example.com/path/?q=v "); Assert.Equal(new Uri("http://www.example.com/path/?q=v"), headers.Referrer); headers.Clear(); headers.TryAddWithoutValidation("Referer", "/relative/uri/"); Assert.Equal(new Uri("/relative/uri/", UriKind.Relative), headers.Referrer); } [Fact] public void Referrer_UseAddMethodWithInvalidValue_InvalidValueRecognized() { headers.TryAddWithoutValidation("Referer", " http://example.com http://other"); Assert.Null(headers.GetParsedValues(KnownHeaders.Referer.Descriptor)); Assert.Equal(1, headers.GetValues("Referer").Count()); Assert.Equal(" http://example.com http://other", headers.GetValues("Referer").First()); headers.Clear(); headers.TryAddWithoutValidation("Referer", "http://host /other"); Assert.Null(headers.GetParsedValues(KnownHeaders.Referer.Descriptor)); Assert.Equal(1, headers.GetValues("Referer").Count()); Assert.Equal("http://host /other", headers.GetValues("Referer").First()); } [Fact] public void MaxForwards_ReadAndWriteProperty_ValueMatchesPriorSetValue() { Assert.Null(headers.MaxForwards); headers.MaxForwards = 15; Assert.Equal(15, headers.MaxForwards); headers.MaxForwards = null; Assert.Null(headers.MaxForwards); Assert.False(headers.Contains("Max-Forwards"), "Header store should not contain a header 'MaxForwards' after setting it to null."); // Make sure the header gets serialized correctly headers.MaxForwards = 12345; Assert.Equal("12345", headers.GetValues("Max-Forwards").First()); } [Fact] public void MaxForwards_UseAddMethod_AddedValueCanBeRetrievedUsingProperty() { headers.TryAddWithoutValidation("Max-Forwards", " 00123 "); Assert.Equal(123, headers.MaxForwards); headers.Clear(); headers.TryAddWithoutValidation("Max-Forwards", "0"); Assert.Equal(0, headers.MaxForwards); } [Fact] public void MaxForwards_UseAddMethodWithInvalidValue_InvalidValueRecognized() { headers.TryAddWithoutValidation("Max-Forwards", "15,"); Assert.Null(headers.GetParsedValues(KnownHeaders.MaxForwards.Descriptor)); Assert.Equal(1, headers.GetValues("Max-Forwards").Count()); Assert.Equal("15,", headers.GetValues("Max-Forwards").First()); headers.Clear(); headers.TryAddWithoutValidation("Max-Forwards", "1.0"); Assert.Null(headers.GetParsedValues(KnownHeaders.MaxForwards.Descriptor)); Assert.Equal(1, headers.GetValues("Max-Forwards").Count()); Assert.Equal("1.0", headers.GetValues("Max-Forwards").First()); } [Fact] public void AddHeaders_SpecialHeaderValuesOnSourceNotOnDestination_Copied() { // Positive HttpRequestHeaders source = new HttpRequestHeaders(); source.ExpectContinue = true; source.TransferEncodingChunked = true; source.ConnectionClose = true; HttpRequestHeaders destination = new HttpRequestHeaders(); Assert.Null(destination.ExpectContinue); Assert.Null(destination.TransferEncodingChunked); Assert.Null(destination.ConnectionClose); destination.AddHeaders(source); Assert.NotNull(destination.ExpectContinue); Assert.NotNull(destination.TransferEncodingChunked); Assert.NotNull(destination.ConnectionClose); Assert.True(destination.ExpectContinue.Value); Assert.True(destination.TransferEncodingChunked.Value); Assert.True(destination.ConnectionClose.Value); // Negative source = new HttpRequestHeaders(); source.ExpectContinue = false; source.TransferEncodingChunked = false; source.ConnectionClose = false; destination = new HttpRequestHeaders(); Assert.Null(destination.ExpectContinue); Assert.Null(destination.TransferEncodingChunked); Assert.Null(destination.ConnectionClose); destination.AddHeaders(source); Assert.NotNull(destination.ExpectContinue); Assert.NotNull(destination.TransferEncodingChunked); Assert.NotNull(destination.ConnectionClose); Assert.False(destination.ExpectContinue.Value); Assert.False(destination.TransferEncodingChunked.Value); Assert.False(destination.ConnectionClose.Value); } [Fact] public void AddHeaders_SpecialHeaderValuesOnDestinationNotOnSource_NotCopied() { // Positive HttpRequestHeaders destination = new HttpRequestHeaders(); destination.ExpectContinue = true; destination.TransferEncodingChunked = true; destination.ConnectionClose = true; Assert.NotNull(destination.ExpectContinue); Assert.NotNull(destination.TransferEncodingChunked); Assert.NotNull(destination.ConnectionClose); Assert.True(destination.ExpectContinue.Value); Assert.True(destination.TransferEncodingChunked.Value); Assert.True(destination.ConnectionClose.Value); HttpRequestHeaders source = new HttpRequestHeaders(); Assert.Null(source.ExpectContinue); Assert.Null(source.TransferEncodingChunked); Assert.Null(source.ConnectionClose); destination.AddHeaders(source); Assert.Null(source.ExpectContinue); Assert.Null(source.TransferEncodingChunked); Assert.Null(source.ConnectionClose); Assert.NotNull(destination.ExpectContinue); Assert.NotNull(destination.TransferEncodingChunked); Assert.NotNull(destination.ConnectionClose); Assert.True(destination.ExpectContinue.Value); Assert.True(destination.TransferEncodingChunked.Value); Assert.True(destination.ConnectionClose.Value); // Negative destination = new HttpRequestHeaders(); destination.ExpectContinue = false; destination.TransferEncodingChunked = false; destination.ConnectionClose = false; Assert.NotNull(destination.ExpectContinue); Assert.NotNull(destination.TransferEncodingChunked); Assert.NotNull(destination.ConnectionClose); Assert.False(destination.ExpectContinue.Value); Assert.False(destination.TransferEncodingChunked.Value); Assert.False(destination.ConnectionClose.Value); source = new HttpRequestHeaders(); Assert.Null(source.ExpectContinue); Assert.Null(source.TransferEncodingChunked); Assert.Null(source.ConnectionClose); destination.AddHeaders(source); Assert.Null(source.ExpectContinue); Assert.Null(source.TransferEncodingChunked); Assert.Null(source.ConnectionClose); Assert.NotNull(destination.ExpectContinue); Assert.NotNull(destination.TransferEncodingChunked); Assert.NotNull(destination.ConnectionClose); Assert.False(destination.ExpectContinue.Value); Assert.False(destination.TransferEncodingChunked.Value); Assert.False(destination.ConnectionClose.Value); } #endregion #region General headers [Fact] public void Connection_AddClose_Success() { headers.Connection.Add("CLOSE"); // use non-default casing to make sure we do case-insensitive comparison. Assert.True(headers.ConnectionClose == true); Assert.Equal(1, headers.Connection.Count); } [Fact] public void Connection_ReadAndWriteProperty_ValueMatchesPriorSetValue() { Assert.Equal(0, headers.Connection.Count); Assert.Null(headers.ConnectionClose); headers.Connection.Add("custom1"); headers.Connection.Add("custom2"); headers.ConnectionClose = true; // Connection collection has 2 values plus 'close' Assert.Equal(3, headers.Connection.Count); Assert.Equal(3, headers.GetValues("Connection").Count()); Assert.True(headers.ConnectionClose == true, "ConnectionClose"); Assert.Equal("custom1", headers.Connection.ElementAt(0)); Assert.Equal("custom2", headers.Connection.ElementAt(1)); // Remove 'close' value from store. But leave other 'Connection' values. headers.ConnectionClose = false; Assert.True(headers.ConnectionClose == false, "ConnectionClose == false"); Assert.Equal(2, headers.Connection.Count); Assert.Equal("custom1", headers.Connection.ElementAt(0)); Assert.Equal("custom2", headers.Connection.ElementAt(1)); headers.ConnectionClose = true; headers.Connection.Clear(); Assert.True(headers.ConnectionClose == false, "ConnectionClose should be modified by Connection.Clear()."); Assert.Equal(0, headers.Connection.Count); IEnumerable<string> dummyArray; Assert.False(headers.TryGetValues("Connection", out dummyArray), "Connection header count after Connection.Clear()."); // Remove 'close' value from store. Since there are no other 'Connection' values, remove whole header. headers.ConnectionClose = false; Assert.True(headers.ConnectionClose == false, "ConnectionClose == false"); Assert.Equal(0, headers.Connection.Count); Assert.False(headers.Contains("Connection")); headers.ConnectionClose = null; Assert.Null(headers.ConnectionClose); } [Fact] public void Connection_UseAddMethod_AddedValueCanBeRetrievedUsingProperty() { headers.TryAddWithoutValidation("Connection", "custom1, close, custom2, custom3"); // Connection collection has 3 values plus 'close' Assert.Equal(4, headers.Connection.Count); Assert.Equal(4, headers.GetValues("Connection").Count()); Assert.True(headers.ConnectionClose == true); Assert.Equal("custom1", headers.Connection.ElementAt(0)); Assert.Equal("close", headers.Connection.ElementAt(1)); Assert.Equal("custom2", headers.Connection.ElementAt(2)); Assert.Equal("custom3", headers.Connection.ElementAt(3)); headers.Connection.Clear(); Assert.Null(headers.ConnectionClose); Assert.Equal(0, headers.Connection.Count); IEnumerable<string> dummyArray; Assert.False(headers.TryGetValues("Connection", out dummyArray), "Connection header count after Connection.Clear()."); } [Fact] public void Connection_AddInvalidValue_Throw() { Assert.Throws<FormatException>(() => { headers.Connection.Add("this is invalid"); }); } [Fact] public void TransferEncoding_AddChunked_Success() { // use non-default casing to make sure we do case-insensitive comparison. headers.TransferEncoding.Add(new TransferCodingHeaderValue("CHUNKED")); Assert.True(headers.TransferEncodingChunked == true); Assert.Equal(1, headers.TransferEncoding.Count); } [Fact] public void TransferEncoding_ReadAndWriteProperty_ValueMatchesPriorSetValue() { Assert.Equal(0, headers.TransferEncoding.Count); Assert.Null(headers.TransferEncodingChunked); headers.TransferEncoding.Add(new TransferCodingHeaderValue("custom1")); headers.TransferEncoding.Add(new TransferCodingHeaderValue("custom2")); headers.TransferEncodingChunked = true; // Connection collection has 2 values plus 'chunked' Assert.Equal(3, headers.TransferEncoding.Count); Assert.Equal(3, headers.GetValues("Transfer-Encoding").Count()); Assert.True(headers.TransferEncodingChunked); Assert.Equal(new TransferCodingHeaderValue("custom1"), headers.TransferEncoding.ElementAt(0)); Assert.Equal(new TransferCodingHeaderValue("custom2"), headers.TransferEncoding.ElementAt(1)); // Remove 'chunked' value from store. But leave other 'Transfer-Encoding' values. Note that according to // the RFC this is not valid, since 'chunked' must always be present. However this check is done // in the transport handler since the user can add invalid header values anyways. headers.TransferEncodingChunked = false; Assert.True(headers.TransferEncodingChunked == false, "TransferEncodingChunked == false"); Assert.Equal(2, headers.TransferEncoding.Count); Assert.Equal(new TransferCodingHeaderValue("custom1"), headers.TransferEncoding.ElementAt(0)); Assert.Equal(new TransferCodingHeaderValue("custom2"), headers.TransferEncoding.ElementAt(1)); headers.TransferEncodingChunked = true; headers.TransferEncoding.Clear(); Assert.True(headers.TransferEncodingChunked == false, "TransferEncodingChunked should be modified by TransferEncoding.Clear()."); Assert.Equal(0, headers.TransferEncoding.Count); Assert.False(headers.Contains("Transfer-Encoding")); // Remove 'chunked' value from store. Since there are no other 'Transfer-Encoding' values, remove whole // header. headers.TransferEncodingChunked = false; Assert.True(headers.TransferEncodingChunked == false, "TransferEncodingChunked == false"); Assert.Equal(0, headers.TransferEncoding.Count); Assert.False(headers.Contains("Transfer-Encoding")); headers.TransferEncodingChunked = null; Assert.Null(headers.TransferEncodingChunked); } [Fact] public void TransferEncoding_UseAddMethod_AddedValueCanBeRetrievedUsingProperty() { headers.TryAddWithoutValidation("Transfer-Encoding", " , custom1, , custom2, custom3, chunked ,"); // Connection collection has 3 values plus 'chunked' Assert.Equal(4, headers.TransferEncoding.Count); Assert.Equal(4, headers.GetValues("Transfer-Encoding").Count()); Assert.True(headers.TransferEncodingChunked == true, "TransferEncodingChunked expected to be true."); Assert.Equal(new TransferCodingHeaderValue("custom1"), headers.TransferEncoding.ElementAt(0)); Assert.Equal(new TransferCodingHeaderValue("custom2"), headers.TransferEncoding.ElementAt(1)); Assert.Equal(new TransferCodingHeaderValue("custom3"), headers.TransferEncoding.ElementAt(2)); headers.TransferEncoding.Clear(); Assert.Null(headers.TransferEncodingChunked); Assert.Equal(0, headers.TransferEncoding.Count); Assert.False(headers.Contains("Transfer-Encoding"), "Transfer-Encoding header after TransferEncoding.Clear()."); } [Fact] public void TransferEncoding_UseAddMethodWithInvalidValue_InvalidValueRecognized() { headers.TryAddWithoutValidation("Transfer-Encoding", "custom\u4F1A"); Assert.Null(headers.GetParsedValues(KnownHeaders.TransferEncoding.Descriptor)); Assert.Equal(1, headers.GetValues("Transfer-Encoding").Count()); Assert.Equal("custom\u4F1A", headers.GetValues("Transfer-Encoding").First()); headers.Clear(); headers.TryAddWithoutValidation("Transfer-Encoding", "custom1 custom2"); Assert.Null(headers.GetParsedValues(KnownHeaders.TransferEncoding.Descriptor)); Assert.Equal(1, headers.GetValues("Transfer-Encoding").Count()); Assert.Equal("custom1 custom2", headers.GetValues("Transfer-Encoding").First()); headers.Clear(); headers.TryAddWithoutValidation("Transfer-Encoding", ""); Assert.False(headers.Contains("Transfer-Encoding"), "'Transfer-Encoding' header should not be added if it just has empty values."); } [Fact] public void Upgrade_ReadAndWriteProperty_ValueMatchesPriorSetValue() { Assert.Equal(0, headers.Upgrade.Count); headers.Upgrade.Add(new ProductHeaderValue("custom1")); headers.Upgrade.Add(new ProductHeaderValue("custom2", "1.1")); Assert.Equal(2, headers.Upgrade.Count); Assert.Equal(2, headers.GetValues("Upgrade").Count()); Assert.Equal(new ProductHeaderValue("custom1"), headers.Upgrade.ElementAt(0)); Assert.Equal(new ProductHeaderValue("custom2", "1.1"), headers.Upgrade.ElementAt(1)); headers.Upgrade.Clear(); Assert.Equal(0, headers.Upgrade.Count); Assert.False(headers.Contains("Upgrade"), "Upgrade header should be removed after calling Clear()."); } [Fact] public void Upgrade_UseAddMethod_AddedValueCanBeRetrievedUsingProperty() { headers.TryAddWithoutValidation("Upgrade", " , custom1 / 1.0, , custom2, custom3/2.0,"); Assert.Equal(3, headers.Upgrade.Count); Assert.Equal(3, headers.GetValues("Upgrade").Count()); Assert.Equal(new ProductHeaderValue("custom1", "1.0"), headers.Upgrade.ElementAt(0)); Assert.Equal(new ProductHeaderValue("custom2"), headers.Upgrade.ElementAt(1)); Assert.Equal(new ProductHeaderValue("custom3", "2.0"), headers.Upgrade.ElementAt(2)); headers.Upgrade.Clear(); Assert.Equal(0, headers.Upgrade.Count); Assert.False(headers.Contains("Upgrade"), "Upgrade header should be removed after calling Clear()."); } [Fact] public void Upgrade_UseAddMethodWithInvalidValue_InvalidValueRecognized() { headers.TryAddWithoutValidation("Upgrade", "custom\u4F1A"); Assert.Null(headers.GetParsedValues(KnownHeaders.Upgrade.Descriptor)); Assert.Equal(1, headers.GetValues("Upgrade").Count()); Assert.Equal("custom\u4F1A", headers.GetValues("Upgrade").First()); headers.Clear(); headers.TryAddWithoutValidation("Upgrade", "custom1 custom2"); Assert.Null(headers.GetParsedValues(KnownHeaders.Upgrade.Descriptor)); Assert.Equal(1, headers.GetValues("Upgrade").Count()); Assert.Equal("custom1 custom2", headers.GetValues("Upgrade").First()); } [Fact] public void Date_ReadAndWriteProperty_ValueMatchesPriorSetValue() { Assert.Null(headers.Date); DateTimeOffset expected = DateTimeOffset.Now; headers.Date = expected; Assert.Equal(expected, headers.Date); headers.Date = null; Assert.Null(headers.Date); Assert.False(headers.Contains("Date"), "Header store should not contain a header 'Date' after setting it to null."); // Make sure the header gets serialized correctly headers.Date = (new DateTimeOffset(1994, 11, 6, 8, 49, 37, TimeSpan.Zero)); Assert.Equal("Sun, 06 Nov 1994 08:49:37 GMT", headers.GetValues("Date").First()); } [Fact] public void Date_UseAddMethod_AddedValueCanBeRetrievedUsingProperty() { headers.TryAddWithoutValidation("Date", " Sun, 06 Nov 1994 08:49:37 GMT "); Assert.Equal(new DateTimeOffset(1994, 11, 6, 8, 49, 37, TimeSpan.Zero), headers.Date); headers.Clear(); headers.TryAddWithoutValidation("Date", "Sun, 06 Nov 1994 08:49:37 GMT"); Assert.Equal(new DateTimeOffset(1994, 11, 6, 8, 49, 37, TimeSpan.Zero), headers.Date); } [Fact] public void Date_UseAddMethodWithInvalidValue_InvalidValueRecognized() { headers.TryAddWithoutValidation("Date", " Sun, 06 Nov 1994 08:49:37 GMT ,"); Assert.Null(headers.GetParsedValues(KnownHeaders.Date.Descriptor)); Assert.Equal(1, headers.GetValues("Date").Count()); Assert.Equal(" Sun, 06 Nov 1994 08:49:37 GMT ,", headers.GetValues("Date").First()); headers.Clear(); headers.TryAddWithoutValidation("Date", " Sun, 06 Nov "); Assert.Null(headers.GetParsedValues(KnownHeaders.Date.Descriptor)); Assert.Equal(1, headers.GetValues("Date").Count()); Assert.Equal(" Sun, 06 Nov ", headers.GetValues("Date").First()); } [Fact] public void Via_ReadAndWriteProperty_ValueMatchesPriorSetValue() { Assert.Equal(0, headers.Via.Count); headers.Via.Add(new ViaHeaderValue("x11", "host")); headers.Via.Add(new ViaHeaderValue("1.1", "example.com:8080", "HTTP", "(comment)")); Assert.Equal(2, headers.Via.Count); Assert.Equal(new ViaHeaderValue("x11", "host"), headers.Via.ElementAt(0)); Assert.Equal(new ViaHeaderValue("1.1", "example.com:8080", "HTTP", "(comment)"), headers.Via.ElementAt(1)); headers.Via.Clear(); Assert.Equal(0, headers.Via.Count); } [Fact] public void Via_UseAddMethod_AddedValueCanBeRetrievedUsingProperty() { headers.TryAddWithoutValidation("Via", ", 1.1 host, WS/1.0 [::1],X/11 192.168.0.1 (c(comment)) "); Assert.Equal(new ViaHeaderValue("1.1", "host"), headers.Via.ElementAt(0)); Assert.Equal(new ViaHeaderValue("1.0", "[::1]", "WS"), headers.Via.ElementAt(1)); Assert.Equal(new ViaHeaderValue("11", "192.168.0.1", "X", "(c(comment))"), headers.Via.ElementAt(2)); headers.Via.Clear(); headers.TryAddWithoutValidation("Via", ""); Assert.Equal(0, headers.Via.Count); Assert.False(headers.Contains("Via")); } [Fact] public void Via_UseAddMethodWithInvalidValue_InvalidValueRecognized() { headers.TryAddWithoutValidation("Via", "1.1 host1 1.1 host2"); // no separator Assert.Equal(0, headers.Via.Count); Assert.Equal(1, headers.GetValues("Via").Count()); Assert.Equal("1.1 host1 1.1 host2", headers.GetValues("Via").First()); headers.Clear(); headers.TryAddWithoutValidation("Via", "X/11 host/1"); Assert.Equal(0, headers.Via.Count); Assert.Equal(1, headers.GetValues("Via").Count()); Assert.Equal("X/11 host/1", headers.GetValues("Via").First()); } [Fact] public void Warning_ReadAndWriteProperty_ValueMatchesPriorSetValue() { Assert.Equal(0, headers.Warning.Count); headers.Warning.Add(new WarningHeaderValue(199, "microsoft.com", "\"Miscellaneous warning\"")); headers.Warning.Add(new WarningHeaderValue(113, "example.com", "\"Heuristic expiration\"")); Assert.Equal(2, headers.Warning.Count); Assert.Equal(new WarningHeaderValue(199, "microsoft.com", "\"Miscellaneous warning\""), headers.Warning.ElementAt(0)); Assert.Equal(new WarningHeaderValue(113, "example.com", "\"Heuristic expiration\""), headers.Warning.ElementAt(1)); headers.Warning.Clear(); Assert.Equal(0, headers.Warning.Count); } [Fact] public void Warning_UseAddMethod_AddedValueCanBeRetrievedUsingProperty() { headers.TryAddWithoutValidation("Warning", "112 example.com \"Disconnected operation\", 111 example.org \"Revalidation failed\""); Assert.Equal(new WarningHeaderValue(112, "example.com", "\"Disconnected operation\""), headers.Warning.ElementAt(0)); Assert.Equal(new WarningHeaderValue(111, "example.org", "\"Revalidation failed\""), headers.Warning.ElementAt(1)); headers.Warning.Clear(); headers.TryAddWithoutValidation("Warning", ""); Assert.Equal(0, headers.Warning.Count); Assert.False(headers.Contains("Warning")); } [Fact] public void Warning_UseAddMethodWithInvalidValue_InvalidValueRecognized() { headers.TryAddWithoutValidation("Warning", "123 host1 \"\" 456 host2 \"\""); // no separator Assert.Equal(0, headers.Warning.Count); Assert.Equal(1, headers.GetValues("Warning").Count()); Assert.Equal("123 host1 \"\" 456 host2 \"\"", headers.GetValues("Warning").First()); headers.Clear(); headers.TryAddWithoutValidation("Warning", "123 host1\"text\""); Assert.Equal(0, headers.Warning.Count); Assert.Equal(1, headers.GetValues("Warning").Count()); Assert.Equal("123 host1\"text\"", headers.GetValues("Warning").First()); } [Fact] public void CacheControl_ReadAndWriteProperty_ValueMatchesPriorSetValue() { Assert.Null(headers.CacheControl); CacheControlHeaderValue value = new CacheControlHeaderValue(); value.NoCache = true; value.NoCacheHeaders.Add("token1"); value.NoCacheHeaders.Add("token2"); value.MustRevalidate = true; value.SharedMaxAge = new TimeSpan(1, 2, 3); headers.CacheControl = value; Assert.Equal(value, headers.CacheControl); headers.CacheControl = null; Assert.Null(headers.CacheControl); Assert.False(headers.Contains("Cache-Control"), "Header store should not contain a header 'Cache-Control' after setting it to null."); } [Fact] public void CacheControl_UseAddMethod_AddedValueCanBeRetrievedUsingProperty() { headers.TryAddWithoutValidation("Cache-Control", "no-cache=\"token1, token2\", must-revalidate, max-age=3"); headers.Add("Cache-Control", ""); headers.Add("Cache-Control", "public, s-maxage=15"); headers.TryAddWithoutValidation("Cache-Control", ""); CacheControlHeaderValue value = new CacheControlHeaderValue(); value.NoCache = true; value.NoCacheHeaders.Add("token1"); value.NoCacheHeaders.Add("token2"); value.MustRevalidate = true; value.MaxAge = new TimeSpan(0, 0, 3); value.Public = true; value.SharedMaxAge = new TimeSpan(0, 0, 15); Assert.Equal(value, headers.CacheControl); } [Fact] public void Trailer_ReadAndWriteProperty_ValueMatchesPriorSetValue() { Assert.Equal(0, headers.Trailer.Count); headers.Trailer.Add("custom1"); headers.Trailer.Add("custom2"); Assert.Equal(2, headers.Trailer.Count); Assert.Equal(2, headers.GetValues("Trailer").Count()); Assert.Equal("custom1", headers.Trailer.ElementAt(0)); Assert.Equal("custom2", headers.Trailer.ElementAt(1)); headers.Trailer.Clear(); Assert.Equal(0, headers.Trailer.Count); Assert.False(headers.Contains("Trailer"), "There should be no Trailer header after calling Clear()."); } [Fact] public void Trailer_UseAddMethod_AddedValueCanBeRetrievedUsingProperty() { headers.TryAddWithoutValidation("Trailer", ",custom1, custom2, custom3,"); Assert.Equal(3, headers.Trailer.Count); Assert.Equal(3, headers.GetValues("Trailer").Count()); Assert.Equal("custom1", headers.Trailer.ElementAt(0)); Assert.Equal("custom2", headers.Trailer.ElementAt(1)); Assert.Equal("custom3", headers.Trailer.ElementAt(2)); headers.Trailer.Clear(); Assert.Equal(0, headers.Trailer.Count); Assert.False(headers.Contains("Trailer"), "There should be no Trailer header after calling Clear()."); } [Fact] public void Trailer_UseAddMethodWithInvalidValue_InvalidValueRecognized() { headers.TryAddWithoutValidation("Trailer", "custom1 custom2"); // no separator Assert.Equal(0, headers.Trailer.Count); Assert.Equal(1, headers.GetValues("Trailer").Count()); Assert.Equal("custom1 custom2", headers.GetValues("Trailer").First()); } [Fact] public void Pragma_ReadAndWriteProperty_ValueMatchesPriorSetValue() { Assert.Equal(0, headers.Pragma.Count); headers.Pragma.Add(new NameValueHeaderValue("custom1", "value1")); headers.Pragma.Add(new NameValueHeaderValue("custom2")); Assert.Equal(2, headers.Pragma.Count); Assert.Equal(2, headers.GetValues("Pragma").Count()); Assert.Equal(new NameValueHeaderValue("custom1", "value1"), headers.Pragma.ElementAt(0)); Assert.Equal(new NameValueHeaderValue("custom2"), headers.Pragma.ElementAt(1)); headers.Pragma.Clear(); Assert.Equal(0, headers.Pragma.Count); Assert.False(headers.Contains("Pragma"), "There should be no Pragma header after calling Clear()."); } [Fact] public void Pragma_UseAddMethod_AddedValueCanBeRetrievedUsingProperty() { headers.TryAddWithoutValidation("Pragma", ",custom1=value1, custom2, custom3=value3,"); Assert.Equal(3, headers.Pragma.Count); Assert.Equal(3, headers.GetValues("Pragma").Count()); Assert.Equal(new NameValueHeaderValue("custom1", "value1"), headers.Pragma.ElementAt(0)); Assert.Equal(new NameValueHeaderValue("custom2"), headers.Pragma.ElementAt(1)); Assert.Equal(new NameValueHeaderValue("custom3", "value3"), headers.Pragma.ElementAt(2)); headers.Pragma.Clear(); Assert.Equal(0, headers.Pragma.Count); Assert.False(headers.Contains("Pragma"), "There should be no Pragma header after calling Clear()."); } [Fact] public void Pragma_UseAddMethodWithInvalidValue_InvalidValueRecognized() { headers.TryAddWithoutValidation("Pragma", "custom1, custom2="); Assert.Equal(0, headers.Pragma.Count()); Assert.Equal(1, headers.GetValues("Pragma").Count()); Assert.Equal("custom1, custom2=", headers.GetValues("Pragma").First()); } #endregion [Fact] public void ToString_SeveralRequestHeaders_Success() { HttpRequestMessage request = new HttpRequestMessage(); string expected = string.Empty; request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml")); request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("*/xml")); expected += HttpKnownHeaderNames.Accept + ": application/xml, */xml" + Environment.NewLine; request.Headers.Authorization = new AuthenticationHeaderValue("Basic"); expected += HttpKnownHeaderNames.Authorization + ": Basic" + Environment.NewLine; request.Headers.ExpectContinue = true; expected += HttpKnownHeaderNames.Expect + ": 100-continue" + Environment.NewLine; request.Headers.TransferEncodingChunked = true; expected += HttpKnownHeaderNames.TransferEncoding + ": chunked" + Environment.NewLine; Assert.Equal(expected, request.Headers.ToString()); } [Fact] public void CustomHeaders_ResponseHeadersAsCustomHeaders_Success() { // Header names reserved for response headers are permitted as custom request headers. headers.Add("Accept-Ranges", "v"); headers.TryAddWithoutValidation("age", "v"); headers.Add("ETag", "v"); headers.Add("Location", "v"); headers.Add("Proxy-Authenticate", "v"); headers.Add("Retry-After", "v"); headers.Add("Server", "v"); headers.Add("Vary", "v"); headers.Add("WWW-Authenticate", "v"); } [Fact] public void InvalidHeaders_AddContentHeaders_Throw() { // Try adding content headers. Use different casing to make sure case-insensitive comparison // is used. Assert.Throws<InvalidOperationException>(() => { headers.Add("Allow", "v"); }); Assert.Throws<InvalidOperationException>(() => { headers.Add("Content-Encoding", "v"); }); Assert.Throws<InvalidOperationException>(() => { headers.Add("Content-Language", "v"); }); Assert.Throws<InvalidOperationException>(() => { headers.Add("content-length", "v"); }); Assert.Throws<InvalidOperationException>(() => { headers.Add("Content-Location", "v"); }); Assert.Throws<InvalidOperationException>(() => { headers.Add("Content-MD5", "v"); }); Assert.Throws<InvalidOperationException>(() => { headers.Add("Content-Range", "v"); }); Assert.Throws<InvalidOperationException>(() => { headers.Add("CONTENT-TYPE", "v"); }); Assert.Throws<InvalidOperationException>(() => { headers.Add("Expires", "v"); }); Assert.Throws<InvalidOperationException>(() => { headers.Add("Last-Modified", "v"); }); } } }