context
stringlengths
2.52k
185k
gt
stringclasses
1 value
using System.Linq; using NetGore; using NetGore.Features.ActionDisplays; using NetGore.World; using SFML.Graphics; namespace DemoGame { /// <summary> /// Contains static data and methods for the game that describes how some different aspects of the general game works. /// </summary> /// <seealso cref="EngineSettingsInitializer"/> public static class GameData { /// <summary> /// If a User is allowed to move while they have a chat dialog open with a NPC. /// </summary> public const bool AllowMovementWhileChattingToNPC = false; /// <summary> /// The velocity to assume all character movement animations are made at. That is, if the character is moving /// with a velocity equal to this value, the animation will update at the usual speed. If it is twice as much /// as this value, the character's animation will update twice as fast. This is to make the rate a character /// moves proportionate to the rate their animation is moving. /// </summary> public const float AnimationSpeedModifier = 0.13f; /// <summary> /// The base (default) attack timeout value for all characters. /// </summary> public const int AttackTimeoutDefault = 500; /// <summary> /// The minimum attack timeout value. The attack timeout may never be less than this value. /// </summary> public const int AttackTimeoutMin = 150; /// <summary> /// The IP address to use by default when creating accounts when no IP can be specified, such as if the account /// is created from the console. /// </summary> public const uint DefaultCreateAccountIP = 0; /// <summary> /// Maximum number of characters allowed in a single account. /// If you update this value, you must also update the `max_character_count` parameter in the /// stored database function `create_user_on_account`. /// </summary> public const byte MaxCharactersPerAccount = 9; /// <summary> /// Maximum length of a Say packet's string from the client to the server. /// </summary> public const int MaxClientSayLength = 250; /// <summary> /// The maximum size (number of different item sets) of the Inventory. Any slot greater than or equal to /// the MaxInventorySize is considered invalid. /// </summary> public const int MaxInventorySize = 6 * 6; /// <summary> /// The maximum number of pixels a user may be away from a NPC to be able to talk to it. /// </summary> public const int MaxNPCChatDistance = 16; /// <summary> /// Maximum length of each parameter string in the server's SendMessage. /// </summary> public const int MaxServerMessageParameterLength = 250; /// <summary> /// Maximum length of a Say packet's string from the server to the client. /// </summary> public const int MaxServerSayLength = 500; /// <summary> /// Maximum length of the Name string used by the server's Say messages. /// </summary> public const int MaxServerSayNameLength = 60; /// <summary> /// The maximum distance a target can be from a character for them to be targeted. /// </summary> public const float MaxTargetDistance = 500f; static readonly StringRules _accountEmail = new StringRules(3, 30, CharType.Alpha | CharType.Numeric | CharType.Punctuation); static readonly StringRules _accountName = new StringRules(3, 30, CharType.Alpha | CharType.Numeric); static readonly StringRules _accountPassword = new StringRules(3, 30, CharType.Alpha | CharType.Numeric | CharType.Punctuation); static readonly StringRules _characterName = new StringRules(1, 30, CharType.Alpha | CharType.Numeric | CharType.Whitespace); static readonly ActionDisplayID _defaultActionDisplayID = new ActionDisplayID(0); static readonly Vector2 _screenSize = new Vector2(1024, 768); static readonly StringRules _userName = new StringRules(3, 15, CharType.Alpha); /// <summary> /// Gets the rules for the account email addresses. /// </summary> public static StringRules AccountEmail { get { return _accountEmail; } } /// <summary> /// Gets the rules for the account names. /// </summary> public static StringRules AccountName { get { return _accountName; } } /// <summary> /// Gets the rules for the account passwords. /// </summary> public static StringRules AccountPassword { get { return _accountPassword; } } /// <summary> /// Gets the rules for the character names. /// </summary> public static StringRules CharacterName { get { return _characterName; } } /// <summary> /// Gets the default <see cref="ActionDisplayID"/> to use when none is specified. /// </summary> public static ActionDisplayID DefaultActionDisplayID { get { return _defaultActionDisplayID; } } /// <summary> /// Gets the maximum delta time between draws for any kind of drawable component. If the delta time between /// draw calls on the component exceeds this value, the delta time should then be reduced to be equal to this value. /// </summary> public static int MaxDrawDeltaTime { get { return 100; } } /// <summary> /// Gets the size of the screen display. /// </summary> public static Vector2 ScreenSize { get { return _screenSize; } } /// <summary> /// Gets the rules for the user names. /// </summary> public static StringRules UserName { get { return _userName; } } /// <summary> /// Gets the number of milliseconds between each World update step. This only applies to the synchronized /// physics, not client-side visuals. /// </summary> public static int WorldPhysicsUpdateRate { get { return 20; } } /// <summary> /// Gets a <see cref="Rectangle"/> containing the hit area for a melee attack. /// </summary> /// <param name="c">The <see cref="CharacterEntity"/> that is attacking.</param> /// <param name="range">The range of the attack.</param> /// <returns>The <see cref="Rectangle"/> that describes the hit area for a melee attack.</returns> public static Rectangle GetMeleeAttackArea(CharacterEntity c, ushort range) { // Start with the rect for the char's area var ret = c.ToRectangle(); // Add the range to the width ret.Width += range; // If looking left, subtract the range from the X position so that the area is to the left, not right if (c.Heading == Direction.West || c.Heading == Direction.SouthWest || c.Heading == Direction.NorthWest) ret.X -= range; return ret; } /// <summary> /// Gets a <see cref="Rectangle"/> that represents the valid area that items can be picked up at from /// the given <paramref name="spatial"/>. /// </summary> /// <param name="spatial">The <see cref="ISpatial"/> doing the picking-up.</param> /// <returns>A <see cref="Rectangle"/> that represents the area region that items can be picked up at from /// the given <paramref name="spatial"/>.</returns> public static Rectangle GetPickupArea(ISpatial spatial) { const int padding = 70; return spatial.ToRectangle().Inflate(padding); } /// <summary> /// Gets a <see cref="Rectangle"/> that describes all of the potential area that /// a ranged attack can reach. /// </summary> /// <param name="c">The <see cref="Entity"/> that is attacking.</param> /// <param name="range">The range of the attack.</param> /// <returns>A <see cref="Rectangle"/> that describes all of the potential area that /// a ranged attack can reach.</returns> public static Rectangle GetRangedAttackArea(Entity c, ushort range) { return c.ToRectangle().Inflate(range); } /// <summary> /// Gets a <see cref="Rectangle"/> containing the area that the <paramref name="shopper"/> may use to /// shop. Any <see cref="Entity"/> that owns a shop and intersects with this area is considered in a valid /// distance to shop with. /// </summary> /// <param name="shopper">The <see cref="Entity"/> doing the shopping.</param> /// <returns>A <see cref="Rectangle"/> containing the area that the <paramref name="shopper"/> may use to /// shop.</returns> public static Rectangle GetValidShopArea(ISpatial shopper) { return shopper.ToRectangle(); } /// <summary> /// Gets if the <paramref name="shopper"/> is close enough to the <paramref name="shopOwner"/> to shop. /// </summary> /// <param name="shopper">The <see cref="Entity"/> doing the shopping.</param> /// <param name="shopOwner">The <see cref="Entity"/> that owns the shop.</param> /// <returns>True if the <paramref name="shopper"/> is close enough to the <paramref name="shopOwner"/> to /// shop; otherwise false.</returns> public static bool IsValidDistanceToShop(ISpatial shopper, ISpatial shopOwner) { var area = GetValidShopArea(shopper); return shopOwner.Intersects(area); } /// <summary> /// Checks if an <see cref="ISpatial"/> is close enough to another <see cref="ISpatial"/> to pick it up. /// </summary> /// <param name="grabber">The <see cref="ISpatial"/> doing the picking up.</param> /// <param name="toGrab">The <see cref="ISpatial"/> being picked up.</param> /// <returns>True if the <paramref name="grabber"/> is close enough to the <paramref name="toGrab"/> /// to pick it up; otherwise false.</returns> public static bool IsValidPickupDistance(ISpatial grabber, ISpatial toGrab) { var region = GetPickupArea(grabber); return toGrab.Intersects(region); } /// <summary> /// Gets the experience required for a given level. /// </summary> /// <param name="x">Level to check (current level).</param> /// <returns>Experience required for the given level.</returns> public static int LevelCost(int x) { return x * 30; } /// <summary> /// Converts the integer-based movement speed to a real velocity value. /// </summary> /// <param name="movementSpeed">The integer-based movement speed.</param> /// <returns>The real velocity value for the given integer-based movement speed.</returns> public static float MovementSpeedToVelocity(int movementSpeed) { return movementSpeed / 10000.0f; } /// <summary> /// Gets the points required for a given stat level. /// </summary> /// <param name="x">Stat level to check (current stat level).</param> /// <returns>Points required for the given stat level.</returns> public static int StatCost(int x) { return 1; } /// <summary> /// Converts a real velocity value to the integer-based movement speed. /// </summary> /// <param name="velocity">The real velocity value.</param> /// <returns>The integer-based movement speed for the given real velocity value.</returns> public static int VelocityToMovementSpeed(float velocity) { return (int)(velocity * 10000.0f); } } }
using System.Collections.Generic; using Microsoft.VisualStudio.TestTools.UnitTesting; using Testing.Common; namespace Nmap.Testing { public partial class MapperTesting { [TestMethod] public void Map_WithMapper_Succeeds() { //Arrange var typeMap = MapBuilder.Instance.CreateMap<MainEntity, MainEntityModel>().As( delegate(MainEntity source, MainEntityModel dest, TypeMappingContext ctxt) { dest.Simple = source.Simple; dest.SimpleConverter = source.SimpleConverter.ToString(); }); var mainEntity = CommonHelper.CreateMainEntityWithSimpleProperties(); var context = new MapperTesting.CustomMappingContext { Data = "data1" }; Mapper<MapperTesting.MapperTester>.Instance.AddMap(typeMap); Mapper<MapperTesting.MapperTester>.Instance.Setup(); //Act var array = ActMapping(mainEntity, context); //Assert for (int i = 0; i < array.Length; i++) { MainEntityModel mainEntityModel = array[i]; Assert.AreEqual<int>(mainEntity.Simple, mainEntityModel.Simple); Assert.AreEqual<string>(mainEntity.SimpleConverter.ToString(), mainEntityModel.SimpleConverter); } } [TestMethod] public void Map_EnumerableWithMapper_Succeeds() { //Arrange var typeMap = MapBuilder.Instance.CreateMap<MainEntity, MainEntityModel>().As( delegate(MainEntity source, MainEntityModel dest, TypeMappingContext ctxt) { dest.Simple = source.Simple; dest.SimpleConverter = source.SimpleConverter.ToString(); }); var mainEntity = CommonHelper.CreateMainEntityWithSimpleProperties(); var entities = new MainEntity[] { mainEntity, mainEntity }; var context = new MapperTesting.CustomMappingContext { Data = "data1" }; Mapper<MapperTesting.MapperTester>.Instance.AddMap(typeMap); Mapper<MapperTesting.MapperTester>.Instance.Setup(); //Act var array = ActEnumerableMapping(entities, context); //Assert for (int i = 0; i < array.Length; i++) { var enumerable = array[i]; foreach (MainEntityModel current in enumerable) { Assert.AreEqual<int>(mainEntity.Simple, current.Simple); Assert.AreEqual<string>(mainEntity.SimpleConverter.ToString(), current.SimpleConverter); } } } [TestMethod] public void Map_EnumerableWithDerivedWithMappers_Succeeds() { //Arrange var typeMap = MapBuilder.Instance.CreateMap<MainEntity, MainEntityModel>().As( delegate(MainEntity source, MainEntityModel dest, TypeMappingContext ctxt) { dest.Simple = source.Simple; dest.SimpleConverter = source.SimpleConverter.ToString(); }); var typeMap2 = MapBuilder.Instance.CreateMap<DerivedMainEntity, DerivedMainEntityModel>().As( delegate(DerivedMainEntity source, DerivedMainEntityModel dest, TypeMappingContext ctxt) { dest.Simple = source.Simple; dest.SimpleConverter = source.SimpleConverter.ToString(); dest.DerivedSimple = source.DerivedSimple; }); var mainEntity = CommonHelper.CreateMainEntityWithSimpleProperties(); var derivedMainEntity = CommonHelper.CreateDerivedMainEntityWithSimpleProperties(); var entities = new MainEntity[] { mainEntity, derivedMainEntity }; var context = new MapperTesting.CustomMappingContext { Data = "data1" }; Mapper<MapperTesting.MapperTester>.Instance.AddMap(typeMap); Mapper<MapperTesting.MapperTester>.Instance.AddMap(typeMap2); Mapper<MapperTesting.MapperTester>.Instance.Setup(); //Act var array = ActEnumerableMapping(entities, context); //Assert for (int i = 0; i < array.Length; i++) { var enumerable = array[i]; foreach (MainEntityModel current in enumerable) { if (current is DerivedMainEntityModel) { Assert.AreEqual<int>(derivedMainEntity.Simple, current.Simple); Assert.AreEqual<string>(derivedMainEntity.SimpleConverter.ToString(), current.SimpleConverter); Assert.AreEqual<int>(derivedMainEntity.DerivedSimple, ((DerivedMainEntityModel)current).DerivedSimple); } else { Assert.AreEqual<int>(mainEntity.Simple, current.Simple); Assert.AreEqual<string>(mainEntity.SimpleConverter.ToString(), current.SimpleConverter); } } } } [TestMethod] public void Map_WithSimple_Succeeds() { //Arrange var map = MapBuilder.Instance.CreateMap<MainEntity, MainEntityModel>().Map; var entity = CommonHelper.CreateMainEntityWithSimpleProperties(); var context = new MapperTesting.CustomMappingContext { Data = "data1" }; Mapper<MapperTesting.MapperTester>.Instance.AddMap(map); Mapper<MapperTesting.MapperTester>.Instance.Setup(); //Act MainEntityModel[] array = ActMapping(entity, context); //Assert for (int i = 0; i < array.Length; i++) { MainEntityModel model = array[i]; AssertEntityModel(entity, model); } } [TestMethod] public void Map_EnumerableWithSimple_Succeeds() { //Arrange var map = MapBuilder.Instance.CreateMap<MainEntity, MainEntityModel>().Map; var mainEntity = CommonHelper.CreateMainEntityWithSimpleProperties(); var entities = new MainEntity[] { mainEntity, mainEntity }; var context = new MapperTesting.CustomMappingContext { Data = "data1" }; Mapper<MapperTesting.MapperTester>.Instance.AddMap(map); Mapper<MapperTesting.MapperTester>.Instance.Setup(); //Act var array = ActEnumerableMapping(entities, context); //Assert for (int i = 0; i < array.Length; i++) { var enumerable = array[i]; foreach (MainEntityModel current in enumerable) { AssertEntityModel(mainEntity, current); } } } [TestMethod] public void Map_EnumerableWithDerivedWithSimple_Succeeds() { //Arrange var map = MapBuilder.Instance.CreateMap<MainEntity, MainEntityModel>().Map; var map2 = MapBuilder.Instance.CreateMap<DerivedMainEntity, DerivedMainEntityModel>().Map; var mainEntity = CommonHelper.CreateMainEntityWithSimpleProperties(); var derivedMainEntity = CommonHelper.CreateDerivedMainEntityWithSimpleProperties(); var entities = new MainEntity[] { mainEntity, derivedMainEntity }; var context = new MapperTesting.CustomMappingContext { Data = "data1" }; Mapper<MapperTesting.MapperTester>.Instance.AddMap(map); Mapper<MapperTesting.MapperTester>.Instance.AddMap(map2); Mapper<MapperTesting.MapperTester>.Instance.Setup(); //Act var array = ActEnumerableMapping(entities, context); //Assert for (int i = 0; i < array.Length; i++) { var enumerable = array[i]; foreach (MainEntityModel current in enumerable) { if (current is DerivedMainEntityModel) { AssertEntityModel(derivedMainEntity, current); } else { AssertEntityModel(mainEntity, current); } } } } [TestMethod] public void Map_NestedWithPropertyMapsWithMappers_Succeeds() { //Arrange var map = MapBuilder.Instance.CreateMap<MainEntity, MainEntityModel>().MapProperty((MainEntity p) => p.SubEntity, delegate(MainEntity source, MainEntityModel dest, TypeMappingContext ctxt) { dest.SubEntity = new SubEntityModel(); dest.SubEntity.Simple = source.SubEntity.Simple; dest.SubEntity.EntitySimpleNaming = source.SubEntity.SimpleNaming; dest.SubEntity.EntitySimpleConverterNaming = source.SubEntity.SimpleConverterNaming.ToString(); }).Map; var mainEntity = CommonHelper.CreateMainEntityWithAllProperties(false); var context = new MapperTesting.CustomMappingContext { Data = "data1" }; Mapper<MapperTesting.MapperTester>.Instance.AddMap(map); Mapper<MapperTesting.MapperTester>.Instance.Setup(); //Act MainEntityModel[] array = ActMapping(mainEntity, context); //Assert for (int i = 0; i < array.Length; i++) { var mainEntityModel = array[i]; Assert.AreEqual<int>(mainEntity.SubEntity.Simple, mainEntityModel.SubEntity.Simple); Assert.AreEqual<int>(mainEntity.SubEntity.SimpleNaming, mainEntityModel.SubEntity.EntitySimpleNaming); Assert.AreEqual<string>(mainEntity.SubEntity.SimpleConverterNaming.ToString(), mainEntityModel.SubEntity.EntitySimpleConverterNaming.ToString()); } } [TestMethod] public void Map_NestedWithPropertyMapsWithSimple_Succeeds() { //Arrange var array = new TypeMap[] { MapBuilder.Instance.CreateMap<SubSubEntity, SubSubEntityModel>().Map }; var array2 = new TypeMap[] { MapBuilder.Instance.CreateMap<SubEntity, SubEntityModel>().MapProperty((SubEntity p) => p.SubSubEntity, (SubEntityModel p) => p.SubSubEntity, array).MapProperty((SubEntity p) => p.SubSubEntityArrayToArray, (SubEntityModel p) => p.SubSubEntityArrayToArray, array) .MapProperty((SubEntity p) => p.SubSubEntityArrayToList, (SubEntityModel p) => p.SubSubEntityArrayToList, array).MapProperty((SubEntity p) => p.SubSubEntityListToArray, (SubEntityModel p) => p.SubSubEntityListToArray, array).MapProperty((SubEntity p) => p.SubSubEntityListToList, (SubEntityModel p) => p.SubSubEntityListToList, array).Map }; var map = MapBuilder.Instance.CreateMap<MainEntity, MainEntityModel>().MapProperty((MainEntity p) => p.SubEntity, (MainEntityModel p) => p.SubEntity, array2).MapProperty((MainEntity p) => p.SubEntityArrayToArray, (MainEntityModel p) => p.SubEntityArrayToArray, array2) .MapProperty((MainEntity p) => p.SubEntityArrayToList, (MainEntityModel p) => p.SubEntityArrayToList, array2).MapProperty((MainEntity p) => p.SubEntityListToArray, (MainEntityModel p) => p.SubEntityListToArray, array2).MapProperty((MainEntity p) => p.SubEntityListToList, (MainEntityModel p) => p.SubEntityListToList, array2).Map; var entity = CommonHelper.CreateMainEntityWithAllProperties(false); var context = new MapperTesting.CustomMappingContext { Data = "data1" }; Mapper<MapperTesting.MapperTester>.Instance.AddMap(map); Mapper<MapperTesting.MapperTester>.Instance.Setup(); //Act MainEntityModel[] array3 = ActMapping(entity, context); //Asserts for (int i = 0; i < array3.Length; i++) { MainEntityModel model = array3[i]; AssertEntityModel(entity, model); } } [TestMethod] public void Map_NestedWithPropertyMapsWithDerivedInheritanceMaps_Succeeds() { //Arrange var array = new TypeMap[] { MapBuilder.Instance.CreateMap<SubSubEntity, SubSubEntityModel>().Map, MapBuilder.Instance.CreateMap<DerivedSubSubEntity, DerivedSubSubEntityModel>().Map }; var array2 = new TypeMap[] { MapBuilder.Instance.CreateMap<SubEntity, SubEntityModel>().MapProperty((SubEntity p) => p.SubSubEntity, (SubEntityModel p) => p.SubSubEntity, array).MapProperty((SubEntity p) => p.SubSubEntityArrayToArray, (SubEntityModel p) => p.SubSubEntityArrayToArray, array).MapProperty((SubEntity p) => p.SubSubEntityArrayToList, (SubEntityModel p) => p.SubSubEntityArrayToList, array).MapProperty((SubEntity p) => p.SubSubEntityListToArray, (SubEntityModel p) => p.SubSubEntityListToArray, array).MapProperty((SubEntity p) => p.SubSubEntityListToList, (SubEntityModel p) => p.SubSubEntityListToList, array).Map, MapBuilder.Instance.CreateMap<DerivedSubEntity, DerivedSubEntityModel>().MapProperty((DerivedSubEntity p) => p.SubSubEntity, (DerivedSubEntityModel p) => p.SubSubEntity, array).MapProperty((DerivedSubEntity p) => p.SubSubEntityArrayToArray, (DerivedSubEntityModel p) => p.SubSubEntityArrayToArray, array) .MapProperty((DerivedSubEntity p) => p.SubSubEntityArrayToList, (DerivedSubEntityModel p) => p.SubSubEntityArrayToList, array).MapProperty((DerivedSubEntity p) => p.SubSubEntityListToArray, (DerivedSubEntityModel p) => p.SubSubEntityListToArray, array).MapProperty((DerivedSubEntity p) => p.SubSubEntityListToList, (DerivedSubEntityModel p) => p.SubSubEntityListToList, array).Map }; var map = MapBuilder.Instance.CreateMap<MainEntity, MainEntityModel>().MapProperty((MainEntity p) => p.SubEntity, (MainEntityModel p) => p.SubEntity, array2).MapProperty((MainEntity p) => p.SubEntityArrayToArray, (MainEntityModel p) => p.SubEntityArrayToArray, array2).MapProperty((MainEntity p) => p.SubEntityArrayToList, (MainEntityModel p) => p.SubEntityArrayToList, array2).MapProperty((MainEntity p) => p.SubEntityListToArray, (MainEntityModel p) => p.SubEntityListToArray, array2).MapProperty((MainEntity p) => p.SubEntityListToList, (MainEntityModel p) => p.SubEntityListToList, array2).Map; var entity = CommonHelper.CreateMainEntityWithAllProperties(true); var context = new MapperTesting.CustomMappingContext { Data = "data1" }; Mapper<MapperTesting.MapperTester>.Instance.AddMap(map); Mapper<MapperTesting.MapperTester>.Instance.Setup(); //Act MainEntityModel[] array3 = ActMapping(entity, context); //Assert for (int i = 0; i < array3.Length; i++) { MainEntityModel model = array3[i]; AssertEntityModel(entity, model); } } [TestMethod] public void Map_SecondToFirstLevelFlattening_Succeeds() { var array = new TypeMap[] { MapBuilder.Instance.CreateMap<SubEntity, FlattenedSecondLevelModel>().Map }; var map = MapBuilder.Instance.CreateMap<MainEntity, FlattenedSecondLevelModel>() .MapProperty((MainEntity p) => p.SubEntity, null, array).Map; var mainEntity = CommonHelper.CreateMainEntityWithAllProperties(false); var customMappingContext = new MapperTesting.CustomMappingContext { Data = "data1" }; Mapper<MapperTesting.MapperTester>.Instance.AddMap(map); Mapper<MapperTesting.MapperTester>.Instance.Setup(); //Act var flattenedSecondLevelModel = Mapper<MapperTesting.MapperTester>.Instance.Map<FlattenedSecondLevelModel>( mainEntity, customMappingContext); var flattenedSecondLevelModel2 = Mapper<MapperTesting.MapperTester>.Instance.Map<FlattenedSecondLevelModel>( mainEntity, new FlattenedSecondLevelModel(), customMappingContext); var flattenedSecondLevelModel3 = Mapper<MapperTesting.MapperTester>.Instance.Map( mainEntity, typeof(FlattenedSecondLevelModel), customMappingContext) as FlattenedSecondLevelModel; var array2 = new FlattenedSecondLevelModel[] { flattenedSecondLevelModel, flattenedSecondLevelModel2, flattenedSecondLevelModel3 }; //Assert for (int i = 0; i < array2.Length; i++) { FlattenedSecondLevelModel model = array2[i]; AssertSimpleFlattenedEntityModel(mainEntity.SubEntity, model, "SubEntity"); } } [TestMethod] public void Map_ThirdToFirstLevelFlattening_Succeeds() { //Arrange var array = new TypeMap[] { MapBuilder.Instance.CreateMap<SubSubEntity, FlattenedThirdLevelModel>().Map }; var array2 = new TypeMap[] { MapBuilder.Instance.CreateMap<SubEntity, FlattenedThirdLevelModel>().MapProperty( (SubEntity p) => p.SubSubEntity, null, array).Map }; var map = MapBuilder.Instance.CreateMap<MainEntity, FlattenedThirdLevelModel>().MapProperty( (MainEntity p) => p.SubEntity, null, array2).Map; var mainEntity = CommonHelper.CreateMainEntityWithAllProperties(false); var customMappingContext = new MapperTesting.CustomMappingContext { Data = "data1" }; Mapper<MapperTesting.MapperTester>.Instance.AddMap(map); Mapper<MapperTesting.MapperTester>.Instance.Setup(); //Act var flattenedThirdLevelModel = Mapper<MapperTesting.MapperTester>.Instance .Map<FlattenedThirdLevelModel>(mainEntity, customMappingContext); var flattenedThirdLevelModel2 = Mapper<MapperTesting.MapperTester>.Instance .Map<FlattenedThirdLevelModel>(mainEntity, new FlattenedThirdLevelModel(), customMappingContext); var flattenedThirdLevelModel3 = Mapper<MapperTesting.MapperTester>.Instance .Map(mainEntity, typeof(FlattenedThirdLevelModel), customMappingContext) as FlattenedThirdLevelModel; //Assert var array3 = new FlattenedThirdLevelModel[] { flattenedThirdLevelModel, flattenedThirdLevelModel2, flattenedThirdLevelModel3 }; for (int i = 0; i < array3.Length; i++) { var model = array3[i]; AssertSimpleFlattenedEntityModel(mainEntity.SubEntity.SubSubEntity, model, "SubEntitySubSubEntity"); } } [TestMethod] public void Map_ThirdToSecondLevelFlattening_Succeeds() { //Arrange var array = new TypeMap[] { MapBuilder.Instance.CreateMap<SubSubEntity, SubFlattenedThirdToSecondLevelModel>().Map }; var array2 = new TypeMap[] { MapBuilder.Instance.CreateMap<SubEntity, SubFlattenedThirdToSecondLevelModel>() .MapProperty((SubEntity p) => p.SubSubEntity, null, array).Map }; var map = MapBuilder.Instance.CreateMap<MainEntity, FlattenedThirdToSecondLevelModel>() .MapProperty((MainEntity p) => p.SubEntity, (FlattenedThirdToSecondLevelModel p) => p.SubEntityModel, array2).Map; var mainEntity = CommonHelper.CreateMainEntityWithAllProperties(false); var customMappingContext = new MapperTesting.CustomMappingContext { Data = "data1" }; Mapper<MapperTesting.MapperTester>.Instance.AddMap(map); Mapper<MapperTesting.MapperTester>.Instance.Setup(); //Act var flattenedThirdToSecondLevelModel = Mapper<MapperTesting.MapperTester>.Instance .Map<FlattenedThirdToSecondLevelModel>(mainEntity, customMappingContext); var flattenedThirdToSecondLevelModel2 = Mapper<MapperTesting.MapperTester>.Instance .Map<FlattenedThirdToSecondLevelModel>(mainEntity, new FlattenedThirdToSecondLevelModel(), customMappingContext); var flattenedThirdToSecondLevelModel3 = Mapper<MapperTesting.MapperTester>.Instance .Map(mainEntity, typeof(FlattenedThirdToSecondLevelModel), customMappingContext) as FlattenedThirdToSecondLevelModel; var array3 = new FlattenedThirdToSecondLevelModel[] { flattenedThirdToSecondLevelModel, flattenedThirdToSecondLevelModel2, flattenedThirdToSecondLevelModel3 }; //Assert for (int i = 0; i < array3.Length; i++) { var flattenedThirdToSecondLevelModel4 = array3[i]; AssertSimpleFlattenedEntityModel(mainEntity.SubEntity.SubSubEntity, flattenedThirdToSecondLevelModel4.SubEntityModel, "SubSubEntity"); } } } }
/* * CP20297.cs - IBM EBCDIC (France) code page. * * Copyright (c) 2002 Southern Storm Software, Pty Ltd * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ // Generated from "ibm-297.ucm". namespace I18N.Rare { using System; using I18N.Common; public class CP20297 : ByteEncoding { public CP20297() : base(20297, ToChars, "IBM EBCDIC (France)", "IBM297", "IBM297", "IBM297", false, false, false, false, 1252) {} private static readonly char[] ToChars = { '\u0000', '\u0001', '\u0002', '\u0003', '\u009C', '\u0009', '\u0086', '\u007F', '\u0097', '\u008D', '\u008E', '\u000B', '\u000C', '\u000D', '\u000E', '\u000F', '\u0010', '\u0011', '\u0012', '\u0013', '\u009D', '\u0085', '\u0008', '\u0087', '\u0018', '\u0019', '\u0092', '\u008F', '\u001C', '\u001D', '\u001E', '\u001F', '\u0080', '\u0081', '\u0082', '\u0083', '\u0084', '\u000A', '\u0017', '\u001B', '\u0088', '\u0089', '\u008A', '\u008B', '\u008C', '\u0005', '\u0006', '\u0007', '\u0090', '\u0091', '\u0016', '\u0093', '\u0094', '\u0095', '\u0096', '\u0004', '\u0098', '\u0099', '\u009A', '\u009B', '\u0014', '\u0015', '\u009E', '\u001A', '\u0020', '\u00A0', '\u00E2', '\u00E4', '\u0040', '\u00E1', '\u00E3', '\u00E5', '\u005C', '\u00F1', '\u00B0', '\u002E', '\u003C', '\u0028', '\u002B', '\u0021', '\u0026', '\u007B', '\u00EA', '\u00EB', '\u007D', '\u00ED', '\u00EE', '\u00EF', '\u00EC', '\u00DF', '\u00A7', '\u0024', '\u002A', '\u0029', '\u003B', '\u005E', '\u002D', '\u002F', '\u00C2', '\u00C4', '\u00C0', '\u00C1', '\u00C3', '\u00C5', '\u00C7', '\u00D1', '\u00F9', '\u002C', '\u0025', '\u005F', '\u003E', '\u003F', '\u00F8', '\u00C9', '\u00CA', '\u00CB', '\u00C8', '\u00CD', '\u00CE', '\u00CF', '\u00CC', '\u00B5', '\u003A', '\u00A3', '\u00E0', '\u0027', '\u003D', '\u0022', '\u00D8', '\u0061', '\u0062', '\u0063', '\u0064', '\u0065', '\u0066', '\u0067', '\u0068', '\u0069', '\u00AB', '\u00BB', '\u00F0', '\u00FD', '\u00FE', '\u00B1', '\u005B', '\u006A', '\u006B', '\u006C', '\u006D', '\u006E', '\u006F', '\u0070', '\u0071', '\u0072', '\u00AA', '\u00BA', '\u00E6', '\u00B8', '\u00C6', '\u00A4', '\u0060', '\u00A8', '\u0073', '\u0074', '\u0075', '\u0076', '\u0077', '\u0078', '\u0079', '\u007A', '\u00A1', '\u00BF', '\u00D0', '\u00DD', '\u00DE', '\u00AE', '\u00A2', '\u0023', '\u00A5', '\u00B7', '\u00A9', '\u005D', '\u00B6', '\u00BC', '\u00BD', '\u00BE', '\u00AC', '\u007C', '\u00AF', '\u007E', '\u00B4', '\u00D7', '\u00E9', '\u0041', '\u0042', '\u0043', '\u0044', '\u0045', '\u0046', '\u0047', '\u0048', '\u0049', '\u00AD', '\u00F4', '\u00F6', '\u00F2', '\u00F3', '\u00F5', '\u00E8', '\u004A', '\u004B', '\u004C', '\u004D', '\u004E', '\u004F', '\u0050', '\u0051', '\u0052', '\u00B9', '\u00FB', '\u00FC', '\u00A6', '\u00FA', '\u00FF', '\u00E7', '\u00F7', '\u0053', '\u0054', '\u0055', '\u0056', '\u0057', '\u0058', '\u0059', '\u005A', '\u00B2', '\u00D4', '\u00D6', '\u00D2', '\u00D3', '\u00D5', '\u0030', '\u0031', '\u0032', '\u0033', '\u0034', '\u0035', '\u0036', '\u0037', '\u0038', '\u0039', '\u00B3', '\u00DB', '\u00DC', '\u00D9', '\u00DA', '\u009F', }; protected override void ToBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex) { int ch; while(charCount > 0) { ch = (int)(chars[charIndex++]); if(ch >= 4) switch(ch) { case 0x000B: case 0x000C: case 0x000D: case 0x000E: case 0x000F: case 0x0010: case 0x0011: case 0x0012: case 0x0013: case 0x0018: case 0x0019: case 0x001C: case 0x001D: case 0x001E: case 0x001F: case 0x00B6: break; case 0x0004: ch = 0x37; break; case 0x0005: ch = 0x2D; break; case 0x0006: ch = 0x2E; break; case 0x0007: ch = 0x2F; break; case 0x0008: ch = 0x16; break; case 0x0009: ch = 0x05; break; case 0x000A: ch = 0x25; break; case 0x0014: ch = 0x3C; break; case 0x0015: ch = 0x3D; break; case 0x0016: ch = 0x32; break; case 0x0017: ch = 0x26; break; case 0x001A: ch = 0x3F; break; case 0x001B: ch = 0x27; break; case 0x0020: ch = 0x40; break; case 0x0021: ch = 0x4F; break; case 0x0022: ch = 0x7F; break; case 0x0023: ch = 0xB1; break; case 0x0024: ch = 0x5B; break; case 0x0025: ch = 0x6C; break; case 0x0026: ch = 0x50; break; case 0x0027: ch = 0x7D; break; case 0x0028: ch = 0x4D; break; case 0x0029: ch = 0x5D; break; case 0x002A: ch = 0x5C; break; case 0x002B: ch = 0x4E; break; case 0x002C: ch = 0x6B; break; case 0x002D: ch = 0x60; break; case 0x002E: ch = 0x4B; break; case 0x002F: ch = 0x61; break; case 0x0030: case 0x0031: case 0x0032: case 0x0033: case 0x0034: case 0x0035: case 0x0036: case 0x0037: case 0x0038: case 0x0039: ch += 0x00C0; break; case 0x003A: ch = 0x7A; break; case 0x003B: ch = 0x5E; break; case 0x003C: ch = 0x4C; break; case 0x003D: ch = 0x7E; break; case 0x003E: ch = 0x6E; break; case 0x003F: ch = 0x6F; break; case 0x0040: ch = 0x44; break; case 0x0041: case 0x0042: case 0x0043: case 0x0044: case 0x0045: case 0x0046: case 0x0047: case 0x0048: case 0x0049: ch += 0x0080; break; case 0x004A: case 0x004B: case 0x004C: case 0x004D: case 0x004E: case 0x004F: case 0x0050: case 0x0051: case 0x0052: ch += 0x0087; break; case 0x0053: case 0x0054: case 0x0055: case 0x0056: case 0x0057: case 0x0058: case 0x0059: case 0x005A: ch += 0x008F; break; case 0x005B: ch = 0x90; break; case 0x005C: ch = 0x48; break; case 0x005D: ch = 0xB5; break; case 0x005E: ch = 0x5F; break; case 0x005F: ch = 0x6D; break; case 0x0060: ch = 0xA0; break; case 0x0061: case 0x0062: case 0x0063: case 0x0064: case 0x0065: case 0x0066: case 0x0067: case 0x0068: case 0x0069: ch += 0x0020; break; case 0x006A: case 0x006B: case 0x006C: case 0x006D: case 0x006E: case 0x006F: case 0x0070: case 0x0071: case 0x0072: ch += 0x0027; break; case 0x0073: case 0x0074: case 0x0075: case 0x0076: case 0x0077: case 0x0078: case 0x0079: case 0x007A: ch += 0x002F; break; case 0x007B: ch = 0x51; break; case 0x007C: ch = 0xBB; break; case 0x007D: ch = 0x54; break; case 0x007E: ch = 0xBD; break; case 0x007F: ch = 0x07; break; case 0x0080: case 0x0081: case 0x0082: case 0x0083: case 0x0084: ch -= 0x0060; break; case 0x0085: ch = 0x15; break; case 0x0086: ch = 0x06; break; case 0x0087: ch = 0x17; break; case 0x0088: case 0x0089: case 0x008A: case 0x008B: case 0x008C: ch -= 0x0060; break; case 0x008D: ch = 0x09; break; case 0x008E: ch = 0x0A; break; case 0x008F: ch = 0x1B; break; case 0x0090: ch = 0x30; break; case 0x0091: ch = 0x31; break; case 0x0092: ch = 0x1A; break; case 0x0093: case 0x0094: case 0x0095: case 0x0096: ch -= 0x0060; break; case 0x0097: ch = 0x08; break; case 0x0098: case 0x0099: case 0x009A: case 0x009B: ch -= 0x0060; break; case 0x009C: ch = 0x04; break; case 0x009D: ch = 0x14; break; case 0x009E: ch = 0x3E; break; case 0x009F: ch = 0xFF; break; case 0x00A0: ch = 0x41; break; case 0x00A1: ch = 0xAA; break; case 0x00A2: ch = 0xB0; break; case 0x00A3: ch = 0x7B; break; case 0x00A4: ch = 0x9F; break; case 0x00A5: ch = 0xB2; break; case 0x00A6: ch = 0xDD; break; case 0x00A7: ch = 0x5A; break; case 0x00A8: ch = 0xA1; break; case 0x00A9: ch = 0xB4; break; case 0x00AA: ch = 0x9A; break; case 0x00AB: ch = 0x8A; break; case 0x00AC: ch = 0xBA; break; case 0x00AD: ch = 0xCA; break; case 0x00AE: ch = 0xAF; break; case 0x00AF: ch = 0xBC; break; case 0x00B0: ch = 0x4A; break; case 0x00B1: ch = 0x8F; break; case 0x00B2: ch = 0xEA; break; case 0x00B3: ch = 0xFA; break; case 0x00B4: ch = 0xBE; break; case 0x00B5: ch = 0x79; break; case 0x00B7: ch = 0xB3; break; case 0x00B8: ch = 0x9D; break; case 0x00B9: ch = 0xDA; break; case 0x00BA: ch = 0x9B; break; case 0x00BB: ch = 0x8B; break; case 0x00BC: ch = 0xB7; break; case 0x00BD: ch = 0xB8; break; case 0x00BE: ch = 0xB9; break; case 0x00BF: ch = 0xAB; break; case 0x00C0: ch = 0x64; break; case 0x00C1: ch = 0x65; break; case 0x00C2: ch = 0x62; break; case 0x00C3: ch = 0x66; break; case 0x00C4: ch = 0x63; break; case 0x00C5: ch = 0x67; break; case 0x00C6: ch = 0x9E; break; case 0x00C7: ch = 0x68; break; case 0x00C8: ch = 0x74; break; case 0x00C9: ch = 0x71; break; case 0x00CA: ch = 0x72; break; case 0x00CB: ch = 0x73; break; case 0x00CC: ch = 0x78; break; case 0x00CD: ch = 0x75; break; case 0x00CE: ch = 0x76; break; case 0x00CF: ch = 0x77; break; case 0x00D0: ch = 0xAC; break; case 0x00D1: ch = 0x69; break; case 0x00D2: ch = 0xED; break; case 0x00D3: ch = 0xEE; break; case 0x00D4: ch = 0xEB; break; case 0x00D5: ch = 0xEF; break; case 0x00D6: ch = 0xEC; break; case 0x00D7: ch = 0xBF; break; case 0x00D8: ch = 0x80; break; case 0x00D9: ch = 0xFD; break; case 0x00DA: ch = 0xFE; break; case 0x00DB: ch = 0xFB; break; case 0x00DC: ch = 0xFC; break; case 0x00DD: ch = 0xAD; break; case 0x00DE: ch = 0xAE; break; case 0x00DF: ch = 0x59; break; case 0x00E0: ch = 0x7C; break; case 0x00E1: ch = 0x45; break; case 0x00E2: ch = 0x42; break; case 0x00E3: ch = 0x46; break; case 0x00E4: ch = 0x43; break; case 0x00E5: ch = 0x47; break; case 0x00E6: ch = 0x9C; break; case 0x00E7: ch = 0xE0; break; case 0x00E8: ch = 0xD0; break; case 0x00E9: ch = 0xC0; break; case 0x00EA: ch = 0x52; break; case 0x00EB: ch = 0x53; break; case 0x00EC: ch = 0x58; break; case 0x00ED: ch = 0x55; break; case 0x00EE: ch = 0x56; break; case 0x00EF: ch = 0x57; break; case 0x00F0: ch = 0x8C; break; case 0x00F1: ch = 0x49; break; case 0x00F2: ch = 0xCD; break; case 0x00F3: ch = 0xCE; break; case 0x00F4: ch = 0xCB; break; case 0x00F5: ch = 0xCF; break; case 0x00F6: ch = 0xCC; break; case 0x00F7: ch = 0xE1; break; case 0x00F8: ch = 0x70; break; case 0x00F9: ch = 0x6A; break; case 0x00FA: ch = 0xDE; break; case 0x00FB: ch = 0xDB; break; case 0x00FC: ch = 0xDC; break; case 0x00FD: ch = 0x8D; break; case 0x00FE: ch = 0x8E; break; case 0x00FF: ch = 0xDF; break; case 0x0110: ch = 0xAC; break; case 0x203E: ch = 0xBC; break; case 0xFF01: ch = 0x4F; break; case 0xFF02: ch = 0x7F; break; case 0xFF03: ch = 0xB1; break; case 0xFF04: ch = 0x5B; break; case 0xFF05: ch = 0x6C; break; case 0xFF06: ch = 0x50; break; case 0xFF07: ch = 0x7D; break; case 0xFF08: ch = 0x4D; break; case 0xFF09: ch = 0x5D; break; case 0xFF0A: ch = 0x5C; break; case 0xFF0B: ch = 0x4E; break; case 0xFF0C: ch = 0x6B; break; case 0xFF0D: ch = 0x60; break; case 0xFF0E: ch = 0x4B; break; case 0xFF0F: ch = 0x61; break; case 0xFF10: case 0xFF11: case 0xFF12: case 0xFF13: case 0xFF14: case 0xFF15: case 0xFF16: case 0xFF17: case 0xFF18: case 0xFF19: ch -= 0xFE20; break; case 0xFF1A: ch = 0x7A; break; case 0xFF1B: ch = 0x5E; break; case 0xFF1C: ch = 0x4C; break; case 0xFF1D: ch = 0x7E; break; case 0xFF1E: ch = 0x6E; break; case 0xFF1F: ch = 0x6F; break; case 0xFF20: ch = 0x44; break; case 0xFF21: case 0xFF22: case 0xFF23: case 0xFF24: case 0xFF25: case 0xFF26: case 0xFF27: case 0xFF28: case 0xFF29: ch -= 0xFE60; break; case 0xFF2A: case 0xFF2B: case 0xFF2C: case 0xFF2D: case 0xFF2E: case 0xFF2F: case 0xFF30: case 0xFF31: case 0xFF32: ch -= 0xFE59; break; case 0xFF33: case 0xFF34: case 0xFF35: case 0xFF36: case 0xFF37: case 0xFF38: case 0xFF39: case 0xFF3A: ch -= 0xFE51; break; case 0xFF3B: ch = 0x90; break; case 0xFF3C: ch = 0x48; break; case 0xFF3D: ch = 0xB5; break; case 0xFF3E: ch = 0x5F; break; case 0xFF3F: ch = 0x6D; break; case 0xFF40: ch = 0xA0; break; case 0xFF41: case 0xFF42: case 0xFF43: case 0xFF44: case 0xFF45: case 0xFF46: case 0xFF47: case 0xFF48: case 0xFF49: ch -= 0xFEC0; break; case 0xFF4A: case 0xFF4B: case 0xFF4C: case 0xFF4D: case 0xFF4E: case 0xFF4F: case 0xFF50: case 0xFF51: case 0xFF52: ch -= 0xFEB9; break; case 0xFF53: case 0xFF54: case 0xFF55: case 0xFF56: case 0xFF57: case 0xFF58: case 0xFF59: case 0xFF5A: ch -= 0xFEB1; break; case 0xFF5B: ch = 0x51; break; case 0xFF5C: ch = 0xBB; break; case 0xFF5D: ch = 0x54; break; case 0xFF5E: ch = 0xBD; break; default: ch = 0x3F; break; } bytes[byteIndex++] = (byte)ch; --charCount; } } protected override void ToBytes(String s, int charIndex, int charCount, byte[] bytes, int byteIndex) { int ch; while(charCount > 0) { ch = (int)(s[charIndex++]); if(ch >= 4) switch(ch) { case 0x000B: case 0x000C: case 0x000D: case 0x000E: case 0x000F: case 0x0010: case 0x0011: case 0x0012: case 0x0013: case 0x0018: case 0x0019: case 0x001C: case 0x001D: case 0x001E: case 0x001F: case 0x00B6: break; case 0x0004: ch = 0x37; break; case 0x0005: ch = 0x2D; break; case 0x0006: ch = 0x2E; break; case 0x0007: ch = 0x2F; break; case 0x0008: ch = 0x16; break; case 0x0009: ch = 0x05; break; case 0x000A: ch = 0x25; break; case 0x0014: ch = 0x3C; break; case 0x0015: ch = 0x3D; break; case 0x0016: ch = 0x32; break; case 0x0017: ch = 0x26; break; case 0x001A: ch = 0x3F; break; case 0x001B: ch = 0x27; break; case 0x0020: ch = 0x40; break; case 0x0021: ch = 0x4F; break; case 0x0022: ch = 0x7F; break; case 0x0023: ch = 0xB1; break; case 0x0024: ch = 0x5B; break; case 0x0025: ch = 0x6C; break; case 0x0026: ch = 0x50; break; case 0x0027: ch = 0x7D; break; case 0x0028: ch = 0x4D; break; case 0x0029: ch = 0x5D; break; case 0x002A: ch = 0x5C; break; case 0x002B: ch = 0x4E; break; case 0x002C: ch = 0x6B; break; case 0x002D: ch = 0x60; break; case 0x002E: ch = 0x4B; break; case 0x002F: ch = 0x61; break; case 0x0030: case 0x0031: case 0x0032: case 0x0033: case 0x0034: case 0x0035: case 0x0036: case 0x0037: case 0x0038: case 0x0039: ch += 0x00C0; break; case 0x003A: ch = 0x7A; break; case 0x003B: ch = 0x5E; break; case 0x003C: ch = 0x4C; break; case 0x003D: ch = 0x7E; break; case 0x003E: ch = 0x6E; break; case 0x003F: ch = 0x6F; break; case 0x0040: ch = 0x44; break; case 0x0041: case 0x0042: case 0x0043: case 0x0044: case 0x0045: case 0x0046: case 0x0047: case 0x0048: case 0x0049: ch += 0x0080; break; case 0x004A: case 0x004B: case 0x004C: case 0x004D: case 0x004E: case 0x004F: case 0x0050: case 0x0051: case 0x0052: ch += 0x0087; break; case 0x0053: case 0x0054: case 0x0055: case 0x0056: case 0x0057: case 0x0058: case 0x0059: case 0x005A: ch += 0x008F; break; case 0x005B: ch = 0x90; break; case 0x005C: ch = 0x48; break; case 0x005D: ch = 0xB5; break; case 0x005E: ch = 0x5F; break; case 0x005F: ch = 0x6D; break; case 0x0060: ch = 0xA0; break; case 0x0061: case 0x0062: case 0x0063: case 0x0064: case 0x0065: case 0x0066: case 0x0067: case 0x0068: case 0x0069: ch += 0x0020; break; case 0x006A: case 0x006B: case 0x006C: case 0x006D: case 0x006E: case 0x006F: case 0x0070: case 0x0071: case 0x0072: ch += 0x0027; break; case 0x0073: case 0x0074: case 0x0075: case 0x0076: case 0x0077: case 0x0078: case 0x0079: case 0x007A: ch += 0x002F; break; case 0x007B: ch = 0x51; break; case 0x007C: ch = 0xBB; break; case 0x007D: ch = 0x54; break; case 0x007E: ch = 0xBD; break; case 0x007F: ch = 0x07; break; case 0x0080: case 0x0081: case 0x0082: case 0x0083: case 0x0084: ch -= 0x0060; break; case 0x0085: ch = 0x15; break; case 0x0086: ch = 0x06; break; case 0x0087: ch = 0x17; break; case 0x0088: case 0x0089: case 0x008A: case 0x008B: case 0x008C: ch -= 0x0060; break; case 0x008D: ch = 0x09; break; case 0x008E: ch = 0x0A; break; case 0x008F: ch = 0x1B; break; case 0x0090: ch = 0x30; break; case 0x0091: ch = 0x31; break; case 0x0092: ch = 0x1A; break; case 0x0093: case 0x0094: case 0x0095: case 0x0096: ch -= 0x0060; break; case 0x0097: ch = 0x08; break; case 0x0098: case 0x0099: case 0x009A: case 0x009B: ch -= 0x0060; break; case 0x009C: ch = 0x04; break; case 0x009D: ch = 0x14; break; case 0x009E: ch = 0x3E; break; case 0x009F: ch = 0xFF; break; case 0x00A0: ch = 0x41; break; case 0x00A1: ch = 0xAA; break; case 0x00A2: ch = 0xB0; break; case 0x00A3: ch = 0x7B; break; case 0x00A4: ch = 0x9F; break; case 0x00A5: ch = 0xB2; break; case 0x00A6: ch = 0xDD; break; case 0x00A7: ch = 0x5A; break; case 0x00A8: ch = 0xA1; break; case 0x00A9: ch = 0xB4; break; case 0x00AA: ch = 0x9A; break; case 0x00AB: ch = 0x8A; break; case 0x00AC: ch = 0xBA; break; case 0x00AD: ch = 0xCA; break; case 0x00AE: ch = 0xAF; break; case 0x00AF: ch = 0xBC; break; case 0x00B0: ch = 0x4A; break; case 0x00B1: ch = 0x8F; break; case 0x00B2: ch = 0xEA; break; case 0x00B3: ch = 0xFA; break; case 0x00B4: ch = 0xBE; break; case 0x00B5: ch = 0x79; break; case 0x00B7: ch = 0xB3; break; case 0x00B8: ch = 0x9D; break; case 0x00B9: ch = 0xDA; break; case 0x00BA: ch = 0x9B; break; case 0x00BB: ch = 0x8B; break; case 0x00BC: ch = 0xB7; break; case 0x00BD: ch = 0xB8; break; case 0x00BE: ch = 0xB9; break; case 0x00BF: ch = 0xAB; break; case 0x00C0: ch = 0x64; break; case 0x00C1: ch = 0x65; break; case 0x00C2: ch = 0x62; break; case 0x00C3: ch = 0x66; break; case 0x00C4: ch = 0x63; break; case 0x00C5: ch = 0x67; break; case 0x00C6: ch = 0x9E; break; case 0x00C7: ch = 0x68; break; case 0x00C8: ch = 0x74; break; case 0x00C9: ch = 0x71; break; case 0x00CA: ch = 0x72; break; case 0x00CB: ch = 0x73; break; case 0x00CC: ch = 0x78; break; case 0x00CD: ch = 0x75; break; case 0x00CE: ch = 0x76; break; case 0x00CF: ch = 0x77; break; case 0x00D0: ch = 0xAC; break; case 0x00D1: ch = 0x69; break; case 0x00D2: ch = 0xED; break; case 0x00D3: ch = 0xEE; break; case 0x00D4: ch = 0xEB; break; case 0x00D5: ch = 0xEF; break; case 0x00D6: ch = 0xEC; break; case 0x00D7: ch = 0xBF; break; case 0x00D8: ch = 0x80; break; case 0x00D9: ch = 0xFD; break; case 0x00DA: ch = 0xFE; break; case 0x00DB: ch = 0xFB; break; case 0x00DC: ch = 0xFC; break; case 0x00DD: ch = 0xAD; break; case 0x00DE: ch = 0xAE; break; case 0x00DF: ch = 0x59; break; case 0x00E0: ch = 0x7C; break; case 0x00E1: ch = 0x45; break; case 0x00E2: ch = 0x42; break; case 0x00E3: ch = 0x46; break; case 0x00E4: ch = 0x43; break; case 0x00E5: ch = 0x47; break; case 0x00E6: ch = 0x9C; break; case 0x00E7: ch = 0xE0; break; case 0x00E8: ch = 0xD0; break; case 0x00E9: ch = 0xC0; break; case 0x00EA: ch = 0x52; break; case 0x00EB: ch = 0x53; break; case 0x00EC: ch = 0x58; break; case 0x00ED: ch = 0x55; break; case 0x00EE: ch = 0x56; break; case 0x00EF: ch = 0x57; break; case 0x00F0: ch = 0x8C; break; case 0x00F1: ch = 0x49; break; case 0x00F2: ch = 0xCD; break; case 0x00F3: ch = 0xCE; break; case 0x00F4: ch = 0xCB; break; case 0x00F5: ch = 0xCF; break; case 0x00F6: ch = 0xCC; break; case 0x00F7: ch = 0xE1; break; case 0x00F8: ch = 0x70; break; case 0x00F9: ch = 0x6A; break; case 0x00FA: ch = 0xDE; break; case 0x00FB: ch = 0xDB; break; case 0x00FC: ch = 0xDC; break; case 0x00FD: ch = 0x8D; break; case 0x00FE: ch = 0x8E; break; case 0x00FF: ch = 0xDF; break; case 0x0110: ch = 0xAC; break; case 0x203E: ch = 0xBC; break; case 0xFF01: ch = 0x4F; break; case 0xFF02: ch = 0x7F; break; case 0xFF03: ch = 0xB1; break; case 0xFF04: ch = 0x5B; break; case 0xFF05: ch = 0x6C; break; case 0xFF06: ch = 0x50; break; case 0xFF07: ch = 0x7D; break; case 0xFF08: ch = 0x4D; break; case 0xFF09: ch = 0x5D; break; case 0xFF0A: ch = 0x5C; break; case 0xFF0B: ch = 0x4E; break; case 0xFF0C: ch = 0x6B; break; case 0xFF0D: ch = 0x60; break; case 0xFF0E: ch = 0x4B; break; case 0xFF0F: ch = 0x61; break; case 0xFF10: case 0xFF11: case 0xFF12: case 0xFF13: case 0xFF14: case 0xFF15: case 0xFF16: case 0xFF17: case 0xFF18: case 0xFF19: ch -= 0xFE20; break; case 0xFF1A: ch = 0x7A; break; case 0xFF1B: ch = 0x5E; break; case 0xFF1C: ch = 0x4C; break; case 0xFF1D: ch = 0x7E; break; case 0xFF1E: ch = 0x6E; break; case 0xFF1F: ch = 0x6F; break; case 0xFF20: ch = 0x44; break; case 0xFF21: case 0xFF22: case 0xFF23: case 0xFF24: case 0xFF25: case 0xFF26: case 0xFF27: case 0xFF28: case 0xFF29: ch -= 0xFE60; break; case 0xFF2A: case 0xFF2B: case 0xFF2C: case 0xFF2D: case 0xFF2E: case 0xFF2F: case 0xFF30: case 0xFF31: case 0xFF32: ch -= 0xFE59; break; case 0xFF33: case 0xFF34: case 0xFF35: case 0xFF36: case 0xFF37: case 0xFF38: case 0xFF39: case 0xFF3A: ch -= 0xFE51; break; case 0xFF3B: ch = 0x90; break; case 0xFF3C: ch = 0x48; break; case 0xFF3D: ch = 0xB5; break; case 0xFF3E: ch = 0x5F; break; case 0xFF3F: ch = 0x6D; break; case 0xFF40: ch = 0xA0; break; case 0xFF41: case 0xFF42: case 0xFF43: case 0xFF44: case 0xFF45: case 0xFF46: case 0xFF47: case 0xFF48: case 0xFF49: ch -= 0xFEC0; break; case 0xFF4A: case 0xFF4B: case 0xFF4C: case 0xFF4D: case 0xFF4E: case 0xFF4F: case 0xFF50: case 0xFF51: case 0xFF52: ch -= 0xFEB9; break; case 0xFF53: case 0xFF54: case 0xFF55: case 0xFF56: case 0xFF57: case 0xFF58: case 0xFF59: case 0xFF5A: ch -= 0xFEB1; break; case 0xFF5B: ch = 0x51; break; case 0xFF5C: ch = 0xBB; break; case 0xFF5D: ch = 0x54; break; case 0xFF5E: ch = 0xBD; break; default: ch = 0x3F; break; } bytes[byteIndex++] = (byte)ch; --charCount; } } }; // class CP20297 public class ENCibm297 : CP20297 { public ENCibm297() : base() {} }; // class ENCibm297 }; // namespace I18N.Rare
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Linq; using NUnit.Framework; using QuantConnect.Data; using System.Collections.Generic; using QuantConnect.Securities.Option; namespace QuantConnect.Tests.Common { [TestFixture] public class SymbolTests { [Theory] [TestCaseSource(nameof(GetSymbolCreateTestCaseData))] public void SymbolCreate(string ticker, SecurityType securityType, string market, Symbol expected) { Assert.AreEqual(Symbol.Create(ticker, securityType, market), expected); } private static TestCaseData[] GetSymbolCreateTestCaseData() { return new [] { new TestCaseData("SPY", SecurityType.Equity, Market.USA, new Symbol(SecurityIdentifier.GenerateEquity("SPY", Market.USA), "SPY")), new TestCaseData("EURUSD", SecurityType.Forex, Market.FXCM, new Symbol(SecurityIdentifier.GenerateForex("EURUSD", Market.FXCM), "EURUSD")), new TestCaseData("SPY", SecurityType.Option, Market.USA, new Symbol(SecurityIdentifier.GenerateOption(SecurityIdentifier.DefaultDate, Symbols.SPY.ID, Market.USA, 0, default(OptionRight), default(OptionStyle)), "?SPY")) }; } [Test] public void SymbolCreateBaseWithUnderlyingEquity() { var type = typeof(BaseData); var equitySymbol = Symbol.Create("TWX", SecurityType.Equity, Market.USA); var symbol = Symbol.CreateBase(type, equitySymbol, Market.USA); var symbolIDSymbol = symbol.ID.Symbol.Split(new[] { ".BaseData" }, StringSplitOptions.None).First(); Assert.IsTrue(symbol.SecurityType == SecurityType.Base); Assert.IsTrue(symbol.HasUnderlying); Assert.AreEqual(symbol.Underlying, equitySymbol); Assert.AreEqual(symbol.ID.Date, new DateTime(1998, 1, 2)); Assert.AreEqual("AOL", symbolIDSymbol); Assert.AreEqual(symbol.Underlying.ID.Symbol, symbolIDSymbol); Assert.AreEqual(symbol.Underlying.ID.Date, symbol.ID.Date); Assert.AreEqual(symbol.Underlying.Value, equitySymbol.Value); Assert.AreEqual(symbol.Underlying.Value, symbol.Value); } [Test] public void SymbolCreateBaseWithUnderlyingOption() { var type = typeof(BaseData); var optionSymbol = Symbol.CreateOption("TWX", Market.USA, OptionStyle.American, OptionRight.Call, 100, new DateTime(2050, 12, 31)); var symbol = Symbol.CreateBase(type, optionSymbol, Market.USA); var symbolIDSymbol = symbol.ID.Symbol.Split(new[] { ".BaseData" }, StringSplitOptions.None).First(); Assert.IsTrue(symbol.SecurityType == SecurityType.Base); Assert.IsTrue(symbol.HasUnderlying); Assert.AreEqual(symbol.Underlying, optionSymbol); Assert.IsTrue(symbol.Underlying.HasUnderlying); Assert.AreEqual(symbol.Underlying.Underlying.SecurityType, SecurityType.Equity); Assert.AreEqual(new DateTime(2050, 12, 31), symbol.ID.Date); Assert.AreEqual("AOL", symbolIDSymbol); Assert.AreEqual(symbol.Underlying.ID.Symbol, symbolIDSymbol); Assert.AreEqual(symbol.Underlying.ID.Date, symbol.ID.Date); Assert.AreEqual(symbol.Underlying.Value, symbol.Value); Assert.AreEqual(symbol.Underlying.Underlying.ID.Symbol, symbolIDSymbol); Assert.AreNotEqual(symbol.Underlying.Underlying.ID.Date, symbol.ID.Date); Assert.IsTrue(symbol.Value.StartsWith(symbol.Underlying.Underlying.Value)); Assert.AreEqual(symbol.Underlying.Underlying.ID.Symbol, symbol.Underlying.ID.Symbol); Assert.AreNotEqual(symbol.Underlying.Underlying.ID.Date, symbol.Underlying.ID.Date); Assert.IsTrue(symbol.Underlying.Value.StartsWith(symbol.Underlying.Underlying.Value)); } [Test] public void SymbolCreateWithOptionSecurityTypeCreatesCanonicalOptionSymbol() { var symbol = Symbol.Create("SPY", SecurityType.Option, Market.USA); var sid = symbol.ID; Assert.AreEqual(SecurityIdentifier.DefaultDate, sid.Date); Assert.AreEqual(0m, sid.StrikePrice); Assert.AreEqual(default(OptionRight), sid.OptionRight); Assert.AreEqual(default(OptionStyle), sid.OptionStyle); } [Test] public void CanonicalOptionSymbolAliasHasQuestionMark() { var symbol = Symbol.Create("SPY", SecurityType.Option, Market.USA); Assert.AreEqual("?SPY", symbol.Value); } [Test] public void UsesSidForDictionaryKey() { var sid = SecurityIdentifier.GenerateEquity("SPY", Market.USA); var dictionary = new Dictionary<Symbol, int> { {new Symbol(sid, "value"), 1} }; var key = new Symbol(sid, "other value"); Assert.IsTrue(dictionary.ContainsKey(key)); } [Test] public void CreatesOptionWithUnderlying() { var option = Symbol.CreateOption("XLRE", Market.USA, OptionStyle.American, OptionRight.Call, 21m, new DateTime(2016, 08, 19)); Assert.AreEqual(option.ID.Date, new DateTime(2016, 08, 19)); Assert.AreEqual(option.ID.StrikePrice, 21m); Assert.AreEqual(option.ID.OptionRight, OptionRight.Call); Assert.AreEqual(option.ID.OptionStyle, OptionStyle.American); Assert.AreEqual(option.Underlying.ID.Symbol, "XLRE"); } [Test] public void CompareToItselfReturnsZero() { var sym = new Symbol(SecurityIdentifier.GenerateForex("sym", Market.FXCM), "sym"); Assert.AreEqual(0, sym.CompareTo(sym)); } [Test] public void ComparesTheSameAsStringCompare() { var a = new Symbol(SecurityIdentifier.GenerateForex("a", Market.FXCM), "a"); var z = new Symbol(SecurityIdentifier.GenerateForex("z", Market.FXCM), "z"); Assert.AreEqual(string.Compare("a", "z", StringComparison.Ordinal), a.CompareTo(z)); Assert.AreEqual(string.Compare("z", "a", StringComparison.Ordinal), z.CompareTo(a)); } [Test] public void ComparesTheSameAsStringCompareAndIgnoresCase() { var a = new Symbol(SecurityIdentifier.GenerateForex("a", Market.FXCM), "a"); var z = new Symbol(SecurityIdentifier.GenerateForex("z", Market.FXCM), "z"); Assert.AreEqual(string.Compare("a", "Z", StringComparison.OrdinalIgnoreCase), a.CompareTo(z)); Assert.AreEqual(string.Compare("z", "A", StringComparison.OrdinalIgnoreCase), z.CompareTo(a)); } [Test] public void ComparesAgainstStringWithoutException() { var a = new Symbol(SecurityIdentifier.GenerateForex("a", Market.FXCM), "a"); Assert.AreEqual(0, a.CompareTo("a")); } [Test] public void ComparesAgainstStringIgnoringCase() { var a = new Symbol(SecurityIdentifier.GenerateForex("a", Market.FXCM), "a"); Assert.AreEqual(0, a.CompareTo("A")); } [Test] public void EqualsAgainstNullOrEmpty() { var validSymbol = Symbols.SPY; var emptySymbol = Symbol.Empty; var emptySymbolInstance = new Symbol(SecurityIdentifier.Empty, string.Empty); Symbol nullSymbol = null; Assert.IsTrue(emptySymbol.Equals(nullSymbol)); Assert.IsTrue(Symbol.Empty.Equals(nullSymbol)); Assert.IsTrue(emptySymbolInstance.Equals(nullSymbol)); Assert.IsTrue(emptySymbol.Equals(emptySymbol)); Assert.IsTrue(Symbol.Empty.Equals(emptySymbol)); Assert.IsTrue(emptySymbolInstance.Equals(emptySymbol)); Assert.IsFalse(validSymbol.Equals(nullSymbol)); Assert.IsFalse(validSymbol.Equals(emptySymbol)); Assert.IsFalse(validSymbol.Equals(emptySymbolInstance)); Assert.IsFalse(Symbol.Empty.Equals(validSymbol)); } [Test] public void ComparesAgainstNullOrEmpty() { var validSymbol = Symbols.SPY; var emptySymbol = Symbol.Empty; Symbol nullSymbol = null; Assert.IsTrue(nullSymbol == emptySymbol); Assert.IsFalse(nullSymbol != emptySymbol); Assert.IsTrue(emptySymbol == nullSymbol); Assert.IsFalse(emptySymbol != nullSymbol); Assert.IsTrue(validSymbol != null); Assert.IsTrue(emptySymbol == null); Assert.IsTrue(nullSymbol == null); Assert.IsFalse(validSymbol == null); Assert.IsFalse(emptySymbol != null); Assert.IsFalse(nullSymbol != null); Assert.IsTrue(validSymbol != Symbol.Empty); Assert.IsTrue(emptySymbol == Symbol.Empty); Assert.IsTrue(nullSymbol == Symbol.Empty); Assert.IsFalse(validSymbol == Symbol.Empty); Assert.IsFalse(emptySymbol != Symbol.Empty); Assert.IsFalse(nullSymbol != Symbol.Empty); Assert.IsTrue(null != validSymbol); Assert.IsTrue(null == emptySymbol); Assert.IsTrue(null == nullSymbol); Assert.IsFalse(null == validSymbol); Assert.IsFalse(null != emptySymbol); Assert.IsFalse(null != nullSymbol); Assert.IsTrue(Symbol.Empty != validSymbol); Assert.IsTrue(Symbol.Empty == emptySymbol); Assert.IsTrue(Symbol.Empty == nullSymbol); Assert.IsFalse(Symbol.Empty == validSymbol); Assert.IsFalse(Symbol.Empty != emptySymbol); Assert.IsFalse(Symbol.Empty != nullSymbol); } [Test] public void ImplicitOperatorsAreInverseFunctions() { #pragma warning disable 0618 // This test requires implicit operators var eurusd = new Symbol(SecurityIdentifier.GenerateForex("EURUSD", Market.FXCM), "EURUSD"); string stringEurusd = eurusd; Symbol symbolEurusd = stringEurusd; Assert.AreEqual(eurusd, symbolEurusd); #pragma warning restore 0618 } [Test] public void ImplicitOperatorsReturnSIDOnFailure() { #pragma warning disable 0618 // This test requires implicit operators // this doesn't exist in the symbol cache var eurusd = new Symbol(SecurityIdentifier.GenerateForex("NOT-A-SECURITY", Market.FXCM), "EURUSD"); string stringEurusd = eurusd; Assert.AreEqual(eurusd.ID.ToString(), stringEurusd); Assert.Throws<ArgumentException>(() => { Symbol symbol = "this will not resolve to a proper Symbol instance"; }); Symbol notASymbol = "NotASymbol"; Assert.AreNotEqual(Symbol.Empty, notASymbol); Assert.IsTrue(notASymbol.ToString().Contains("NotASymbol")); #pragma warning restore 0618 } [Test] public void ImplicitFromStringChecksSymbolCache() { #pragma warning disable 0618 // This test requires implicit operators SymbolCache.Set("EURUSD", Symbol.Create("EURUSD", SecurityType.Forex, Market.FXCM)); string ticker = "EURUSD"; Symbol actual = ticker; var expected = SymbolCache.GetSymbol(ticker); Assert.AreEqual(expected, actual); SymbolCache.Clear(); #pragma warning restore 0618 } [Test] public void ImplicitFromStringParsesSid() { #pragma warning disable 0618 // This test requires implicit operators SymbolCache.Set("EURUSD", Symbol.Create("EURUSD", SecurityType.Forex, Market.FXCM)); var expected = SymbolCache.GetSymbol("EURUSD"); string sid = expected.ID.ToString(); Symbol actual = sid; Assert.AreEqual(expected, actual); SymbolCache.Clear(); #pragma warning restore 0618 } [Test] public void ImplicitFromWithinStringLiftsSecondArgument() { #pragma warning disable 0618 // This test requires implicit operators SymbolCache.Clear(); SymbolCache.Set("EURUSD", Symbols.EURUSD); var expected = SymbolCache.GetSymbol("EURUSD"); string stringValue = expected; string notFound = "EURGBP 8G"; var expectedNotFoundSymbol = Symbols.EURGBP; string sid = expected.ID.ToString(); Symbol actual = sid; if (!(expected == stringValue)) { Assert.Fail("Failed expected == string"); } else if (!(stringValue == expected)) { Assert.Fail("Failed string == expected"); } else if (expected != stringValue) { Assert.Fail("Failed expected != string"); } else if (stringValue != expected) { Assert.Fail("Failed string != expected"); } Symbol notFoundSymbol = notFound; Assert.AreEqual(expectedNotFoundSymbol, notFoundSymbol); SymbolCache.Clear(); #pragma warning restore 0618 } [Test] public void TestIfWeDetectCorrectlyWeekliesAndStandardOptionsBeforeFeb2015() { var symbol = Symbol.CreateOption("SPY", Market.USA, OptionStyle.American, OptionRight.Call, 200, new DateTime(2012, 09, 22)); var weeklySymbol = Symbol.CreateOption("SPY", Market.USA, OptionStyle.American, OptionRight.Call, 200, new DateTime(2012, 09, 07)); Assert.True(OptionSymbol.IsStandard(symbol)); Assert.False(OptionSymbol.IsStandard(weeklySymbol)); Assert.AreEqual(new DateTime(2012, 09, 21)/*Friday*/, OptionSymbol.GetLastDayOfTrading(symbol)); Assert.AreEqual(new DateTime(2012, 09, 07)/*Friday*/, OptionSymbol.GetLastDayOfTrading(weeklySymbol)); } [Test] public void TestIfWeDetectCorrectlyWeekliesAndStandardOptionsAfterFeb2015() { var symbol = Symbol.CreateOption("SPY", Market.USA, OptionStyle.American, OptionRight.Call, 200, new DateTime(2016, 02, 19)); var weeklySymbol = Symbol.CreateOption("SPY", Market.USA, OptionStyle.American, OptionRight.Call, 200, new DateTime(2016, 02, 05)); Assert.True(OptionSymbol.IsStandard(symbol)); Assert.False(OptionSymbol.IsStandard(weeklySymbol)); Assert.AreEqual(new DateTime(2016, 02, 19)/*Friday*/, OptionSymbol.GetLastDayOfTrading(symbol)); Assert.AreEqual(new DateTime(2016, 02, 05)/*Friday*/, OptionSymbol.GetLastDayOfTrading(weeklySymbol)); } [Test] public void TestIfWeDetectCorrectlyWeeklies() { var weeklySymbol = Symbol.CreateOption("SPY", Market.USA, OptionStyle.American, OptionRight.Call, 200, new DateTime(2020, 04, 10)); var monthlysymbol = Symbol.CreateOption("SPY", Market.USA, OptionStyle.American, OptionRight.Call, 200, new DateTime(2020, 04, 17)); Assert.True(OptionSymbol.IsWeekly(weeklySymbol)); Assert.False(OptionSymbol.IsWeekly(monthlysymbol)); Assert.AreEqual(new DateTime(2020, 04, 17)/*Friday*/, OptionSymbol.GetLastDayOfTrading(monthlysymbol)); //Good Friday on 10th so should be 9th Assert.AreEqual(new DateTime(2020, 04, 09)/*Thursday*/, OptionSymbol.GetLastDayOfTrading(weeklySymbol)); } [Test] public void HasUnderlyingSymbolReturnsTrueWhenSpecifyingCorrectUnderlying() { Assert.IsTrue(Symbols.SPY_C_192_Feb19_2016.HasUnderlyingSymbol(Symbols.SPY)); } [Test] public void HasUnderlyingSymbolReturnsFalsWhenSpecifyingIncorrectUnderlying() { Assert.IsFalse(Symbols.SPY_C_192_Feb19_2016.HasUnderlyingSymbol(Symbols.AAPL)); } [Test] public void TestIfFridayLastTradingDayIsHolidaysThenMoveToPreviousThursday() { var saturdayAfterGoodFriday = new DateTime(2014, 04, 19); var thursdayBeforeGoodFriday = saturdayAfterGoodFriday.AddDays(-2); var symbol = Symbol.CreateOption("SPY", Market.USA, OptionStyle.American, OptionRight.Call, 200, saturdayAfterGoodFriday); Assert.AreEqual(thursdayBeforeGoodFriday, OptionSymbol.GetLastDayOfTrading(symbol)); } [TestCase("ES", "ES")] [TestCase("GC", "OG")] [TestCase("ZT", "OZT")] public void FutureOptionsWithDifferentUnderlyingGlobexTickersAreMapped(string futureTicker, string expectedFutureOptionTicker) { var future = Symbol.CreateFuture(futureTicker, Market.CME, DateTime.UtcNow.Date); var canonicalFutureOption = Symbol.CreateOption( future, Market.CME, default(OptionStyle), default(OptionRight), default(decimal), SecurityIdentifier.DefaultDate); var nonCanonicalFutureOption = Symbol.CreateOption( future, Market.CME, default(OptionStyle), default(OptionRight), default(decimal), new DateTime(2020, 12, 18)); Assert.AreEqual(canonicalFutureOption.Underlying.ID.Symbol, futureTicker); Assert.AreEqual(canonicalFutureOption.ID.Symbol, expectedFutureOptionTicker); Assert.IsTrue(canonicalFutureOption.Value.StartsWith("?" + futureTicker)); Assert.AreEqual(nonCanonicalFutureOption.Underlying.ID.Symbol, futureTicker); Assert.AreEqual(nonCanonicalFutureOption.ID.Symbol, expectedFutureOptionTicker); Assert.IsTrue(nonCanonicalFutureOption.Value.StartsWith(expectedFutureOptionTicker)); } [Test] public void SymbolWithSidContainingUnderlyingCreatedWithoutNullUnderlying() { var future = Symbol.CreateFuture("ES", Market.CME, new DateTime(2020, 6, 19)); var optionSid = SecurityIdentifier.GenerateOption( future.ID.Date, future.ID, future.ID.Market, 3500m, OptionRight.Call, OptionStyle.American); var option = new Symbol(optionSid, "ES"); Assert.IsNotNull(option.Underlying); Assert.AreEqual(future, option.Underlying); } [TestCase("CL XKJAZ588SI4H", "CL", "CL21F21")] // Future [TestCase("CL JL", "CL", "/CL")] // Canonical Future [TestCase("ES 1S4 | ES XLDTU1KH5XC1", "CL", "?ES21F21")] // Future Option Canonical [TestCase("ES XKGCMV4QK9VO | ES XLDTU1KH5XC1", "ES", "ES21F21 201218C00000000")] // Future Option [TestCase("SPY 2U | SPY R735QTJ8XC9X", "SPY", "?SPY")] // Option Canonical [TestCase("GOOCV 305RBQ2BZBZT2 | GOOCV VP83T1ZUHROL", "GOOCV", "GOOCV 151224P00750000")] // Option [TestCase("SPY R735QTJ8XC9X", "SPY", "SPY")] // Equity [TestCase("EURGBP 8G", "EURGBP", "EURGBP")] // Forex [TestCase("BTCUSD XJ", "BTCUSD", "BTCUSD")] // Crypto public void SymbolAlias(string identifier, string ticker, string expectedValue) { var symbol = new Symbol(SecurityIdentifier.Parse(identifier), ticker); Assert.AreEqual(expectedValue, symbol.Value); } [TestCase("CL XKJAZ588SI4H", "CL", "CL21F21")] // Future [TestCase("CL JL", "CL", "/CL")] // Canonical Future [TestCase("ES 1S4 | ES XLDTU1KH5XC1", "ES", "?ES21F21")] // Future Option Canonical [TestCase("ES XKGCMV4QK9VO | ES XLDTU1KH5XC1", "ES", "ES21F21 201218C00000000")] // Future Option [TestCase("SPY 2U | SPY R735QTJ8XC9X", "SPY", "?SPY")] // Option Canonical [TestCase("GOOCV 305RBQ2BZBZT2 | GOOCV VP83T1ZUHROL", "GOOCV", "GOOCV 151224P00750000")] // Option [TestCase("SPY R735QTJ8XC9X", "SPY", null)] // Equity [TestCase("EURGBP 8G", "EURGBP", null)] // Forex [TestCase("BTCUSD XJ", "BTCUSD", null)] // Crypto public void SymbolCanonical(string identifier, string ticker, string expectedValue) { var symbol = new Symbol(SecurityIdentifier.Parse(identifier), ticker); if (expectedValue != null) { var result = symbol.Canonical; Assert.IsNotNull(result); Assert.AreSame(result, symbol.Canonical); Assert.IsTrue(result.IsCanonical()); Assert.IsTrue(result.Value.Contains(ticker)); Assert.AreEqual(symbol.SecurityType, result.SecurityType); Assert.AreEqual(symbol.ID.Market, result.ID.Market); } else { Assert.Throws<InvalidOperationException>(() => { var canonical = symbol.Canonical; }); } } [TestCase("SPY", "SPY", "SPY 2T")] [TestCase("NWSA", "FOXA", "NWSA 2T")] [TestCase("NWSA", "FOXA", "NWSA 2S|NWSA 2T")] [TestCase("QQQQ", "QQQ", "QQQQ 2S|QQQQ 31|QQQQ 2T")] public void SymbolAndUnderlyingSymbolsMapped(string ticker, string mappedTicker, string sid) { var symbol = new Symbol(SecurityIdentifier.Parse(sid), ticker); var symbolChain = symbol; do { Assert.AreEqual(symbolChain.Value, ticker); symbolChain = symbolChain.Underlying; } while (symbolChain != null); symbol = symbol.UpdateMappedSymbol(mappedTicker); symbolChain = symbol; do { Console.WriteLine(symbolChain.ToString() + "; Value: " + symbolChain.Value); if (symbolChain.SecurityType == SecurityType.Base || symbolChain.SecurityType.RequiresMapping()) { Assert.AreEqual(mappedTicker, symbolChain.Value); } else { Assert.AreNotEqual(mappedTicker, symbolChain.Value); } symbolChain = symbolChain.Underlying; } while (symbolChain != null); } [Test] public void SymbolReferenceNotMappedOnUpdate() { var symbol = Symbol.Create("NWSA", SecurityType.Equity, Market.USA); var customSymbol = Symbol.CreateBase(typeof(BaseData), symbol, Market.USA); var mappedSymbol = customSymbol.UpdateMappedSymbol("FOXA"); Assert.AreNotEqual(customSymbol.Value, mappedSymbol.Value); Assert.AreNotEqual(customSymbol.Underlying.Value, mappedSymbol.Underlying.Value); Assert.AreNotEqual(symbol.Value, mappedSymbol.Underlying.Value); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using Xunit; namespace System.Linq.Expressions.Tests { public static class BinaryAndTests { #region Test methods [Theory, ClassData(typeof(CompilationTypes))] public static void CheckByteAndTest(bool useInterpreter) { byte[] array = new byte[] { 0, 1, byte.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyByteAnd(array[i], array[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckSByteAndTest(bool useInterpreter) { sbyte[] array = new sbyte[] { 0, 1, -1, sbyte.MinValue, sbyte.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifySByteAnd(array[i], array[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckUShortAndTest(bool useInterpreter) { ushort[] array = new ushort[] { 0, 1, ushort.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyUShortAnd(array[i], array[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckShortAndTest(bool useInterpreter) { short[] array = new short[] { 0, 1, -1, short.MinValue, short.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyShortAnd(array[i], array[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckUIntAndTest(bool useInterpreter) { uint[] array = new uint[] { 0, 1, uint.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyUIntAnd(array[i], array[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckIntAndTest(bool useInterpreter) { int[] array = new int[] { 0, 1, -1, int.MinValue, int.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyIntAnd(array[i], array[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckULongAndTest(bool useInterpreter) { ulong[] array = new ulong[] { 0, 1, ulong.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyULongAnd(array[i], array[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckLongAndTest(bool useInterpreter) { long[] array = new long[] { 0, 1, -1, long.MinValue, long.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyLongAnd(array[i], array[j], useInterpreter); } } } #endregion #region Test verifiers private static void VerifyByteAnd(byte a, byte b, bool useInterpreter) { Expression<Func<byte>> e = Expression.Lambda<Func<byte>>( Expression.And( Expression.Constant(a, typeof(byte)), Expression.Constant(b, typeof(byte))), Enumerable.Empty<ParameterExpression>()); Func<byte> f = e.Compile(useInterpreter); Assert.Equal((byte)(a & b), f()); } private static void VerifySByteAnd(sbyte a, sbyte b, bool useInterpreter) { Expression<Func<sbyte>> e = Expression.Lambda<Func<sbyte>>( Expression.And( Expression.Constant(a, typeof(sbyte)), Expression.Constant(b, typeof(sbyte))), Enumerable.Empty<ParameterExpression>()); Func<sbyte> f = e.Compile(useInterpreter); Assert.Equal((sbyte)(a & b), f()); } private static void VerifyUShortAnd(ushort a, ushort b, bool useInterpreter) { Expression<Func<ushort>> e = Expression.Lambda<Func<ushort>>( Expression.And( Expression.Constant(a, typeof(ushort)), Expression.Constant(b, typeof(ushort))), Enumerable.Empty<ParameterExpression>()); Func<ushort> f = e.Compile(useInterpreter); Assert.Equal((ushort)(a & b), f()); } private static void VerifyShortAnd(short a, short b, bool useInterpreter) { Expression<Func<short>> e = Expression.Lambda<Func<short>>( Expression.And( Expression.Constant(a, typeof(short)), Expression.Constant(b, typeof(short))), Enumerable.Empty<ParameterExpression>()); Func<short> f = e.Compile(useInterpreter); Assert.Equal((short)(a & b), f()); } private static void VerifyUIntAnd(uint a, uint b, bool useInterpreter) { Expression<Func<uint>> e = Expression.Lambda<Func<uint>>( Expression.And( Expression.Constant(a, typeof(uint)), Expression.Constant(b, typeof(uint))), Enumerable.Empty<ParameterExpression>()); Func<uint> f = e.Compile(useInterpreter); Assert.Equal(a & b, f()); } private static void VerifyIntAnd(int a, int b, bool useInterpreter) { Expression<Func<int>> e = Expression.Lambda<Func<int>>( Expression.And( Expression.Constant(a, typeof(int)), Expression.Constant(b, typeof(int))), Enumerable.Empty<ParameterExpression>()); Func<int> f = e.Compile(useInterpreter); Assert.Equal(a & b, f()); } private static void VerifyULongAnd(ulong a, ulong b, bool useInterpreter) { Expression<Func<ulong>> e = Expression.Lambda<Func<ulong>>( Expression.And( Expression.Constant(a, typeof(ulong)), Expression.Constant(b, typeof(ulong))), Enumerable.Empty<ParameterExpression>()); Func<ulong> f = e.Compile(useInterpreter); Assert.Equal(a & b, f()); } private static void VerifyLongAnd(long a, long b, bool useInterpreter) { Expression<Func<long>> e = Expression.Lambda<Func<long>>( Expression.And( Expression.Constant(a, typeof(long)), Expression.Constant(b, typeof(long))), Enumerable.Empty<ParameterExpression>()); Func<long> f = e.Compile(useInterpreter); Assert.Equal(a & b, f()); } #endregion [Fact] public static void CannotReduce() { Expression exp = Expression.And(Expression.Constant(0), Expression.Constant(0)); Assert.False(exp.CanReduce); Assert.Same(exp, exp.Reduce()); Assert.Throws<ArgumentException>(null, () => exp.ReduceAndCheck()); } [Fact] public static void ThrowsOnLeftNull() { Assert.Throws<ArgumentNullException>("left", () => Expression.And(null, Expression.Constant(""))); } [Fact] public static void ThrowsOnRightNull() { Assert.Throws<ArgumentNullException>("right", () => Expression.And(Expression.Constant(""), null)); } private static class Unreadable<T> { public static T WriteOnly { set { } } } [Fact] public static void ThrowsOnLeftUnreadable() { Expression value = Expression.Property(null, typeof(Unreadable<int>), "WriteOnly"); Assert.Throws<ArgumentException>("left", () => Expression.And(value, Expression.Constant(1))); } [Fact] public static void ThrowsOnRightUnreadable() { Expression value = Expression.Property(null, typeof(Unreadable<int>), "WriteOnly"); Assert.Throws<ArgumentException>("right", () => Expression.And(Expression.Constant(1), value)); } [Fact] public static void ToStringTest() { var e1 = Expression.And(Expression.Parameter(typeof(int), "a"), Expression.Parameter(typeof(int), "b")); Assert.Equal("(a & b)", e1.ToString()); var e2 = Expression.And(Expression.Parameter(typeof(bool), "a"), Expression.Parameter(typeof(bool), "b")); Assert.Equal("(a And b)", e2.ToString()); var e3 = Expression.And(Expression.Parameter(typeof(bool?), "a"), Expression.Parameter(typeof(bool?), "b")); Assert.Equal("(a And b)", e3.ToString()); } } }
/* FluorineFx open source library Copyright (C) 2007 Zoltan Csibi, zoltan@TheSilentGroup.com, FluorineFx.com 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 */ using System; using System.Collections; using System.Text; using System.IO; #if !(NET_1_1) using System.Collections.Generic; #endif using FluorineFx.Messaging; using FluorineFx.Messaging.Messages; namespace FluorineFx.IO { /// <summary> /// This type supports the Fluorine infrastructure and is not intended to be used directly from your code. /// </summary> [CLSCompliant(false)] public class AMFBody { /// <summary> /// This member supports the Fluorine infrastructure and is not intended to be used directly from your code. /// </summary> public const string Recordset = "rs://"; /// <summary> /// Suffix to denote a success. /// </summary> public const string OnResult = "/onResult"; /// <summary> /// Suffix to denote a failure. /// </summary> public const string OnStatus = "/onStatus"; /// <summary> /// This member supports the Fluorine infrastructure and is not intended to be used directly from your code. /// </summary> public const string OnDebugEvents = "/onDebugEvents"; /// <summary> /// The actual data associated with the operation. /// </summary> protected object _content; /// <summary> /// Response URI which specifies a unique operation name that will be used to match the response to the client invocation. /// </summary> protected string _response; /// <summary> /// Target URI describes which operation, function, or method is to be remotely invoked. /// </summary> protected string _target; /// <summary> /// IgnoreResults is a flag to tell the serializer to ignore the results of the body message. /// </summary> protected bool _ignoreResults; /// <summary> /// This member supports the Fluorine infrastructure and is not intended to be used directly from your code. /// </summary> protected bool _isAuthenticationAction; /// <summary> /// This member supports the Fluorine infrastructure and is not intended to be used directly from your code. /// </summary> protected bool _isDebug; /// <summary> /// This member supports the Fluorine infrastructure and is not intended to be used directly from your code. /// </summary> protected bool _isDescribeService; /// <summary> /// Initializes a new instance of the AMFBody class. /// </summary> public AMFBody() { } /// <summary> /// Initializes a new instance of the AMFBody class. /// </summary> /// <param name="target"></param> /// <param name="response"></param> /// <param name="content"></param> public AMFBody(string target, string response, object content) { this._target = target; this._response = response; this._content = content; } /// <summary> /// Gets or set the target URI. /// The target URI describes which operation, function, or method is to be remotely invoked. /// </summary> public string Target { get{ return _target; } set { _target = value; } } /// <summary> /// Indicates an empty target. /// </summary> public bool IsEmptyTarget { get { return _target == null || _target == string.Empty || _target == "null"; } } /// <summary> /// Gets or sets the response URI. /// Response URI which specifies a unique operation name that will be used to match the response to the client invocation. /// </summary> public string Response { get{ return _response; } set{ _response = value; } } /// <summary> /// Gets or sets the actual data associated with the operation. /// </summary> public object Content { get{ return _content; } set{ _content = value; } } /// <summary> /// This member supports the Fluorine infrastructure and is not intended to be used directly from your code. /// </summary> public bool IsAuthenticationAction { get{ return _isAuthenticationAction; } set{ _isAuthenticationAction = value; } } /// <summary> /// This member supports the Fluorine infrastructure and is not intended to be used directly from your code. /// </summary> public bool IgnoreResults { get{ return _ignoreResults; } set{ _ignoreResults = value; } } /// <summary> /// This member supports the Fluorine infrastructure and is not intended to be used directly from your code. /// </summary> public bool IsDebug { get{ return _isDebug; } set{ _isDebug = value; } } /// <summary> /// This member supports the Fluorine infrastructure and is not intended to be used directly from your code. /// </summary> public bool IsDescribeService { get{ return _isDescribeService; } set{ _isDescribeService = value; } } /// <summary> /// This member supports the Fluorine infrastructure and is not intended to be used directly from your code. /// </summary> public bool IsWebService { get { if( this.TypeName != null ) { if (this.TypeName.ToLower().EndsWith(".asmx")) return true; } return false; } } /// <summary> /// This member supports the Fluorine infrastructure and is not intended to be used directly from your code. /// </summary> public bool IsRecordsetDelivery { get { if( _target.StartsWith(AMFBody.Recordset) ) return true; else return false; } } /// <summary> /// This member supports the Fluorine infrastructure and is not intended to be used directly from your code. /// </summary> public string GetRecordsetArgs() { if( _target != null ) { if( this.IsRecordsetDelivery ) { string args = _target.Substring( AMFBody.Recordset.Length ); args = args.Substring( 0, args.IndexOf("/") ); return args; } } return null; } /// <summary> /// This member supports the Fluorine infrastructure and is not intended to be used directly from your code. /// </summary> public string TypeName { get { if( _target != "null" && _target != null && _target != string.Empty ) { if( _target.LastIndexOf('.') != -1 ) { string target = _target.Substring(0, _target.LastIndexOf('.')); if( this.IsRecordsetDelivery ) { target = target.Substring( AMFBody.Recordset.Length ); target = target.Substring( target.IndexOf("/") + 1 ); target = target.Substring(0, target.LastIndexOf('.')); } return target; } } return null; } } /// <summary> /// This member supports the Fluorine infrastructure and is not intended to be used directly from your code. /// </summary> public string Method { get { if( _target != "null" && _target != null && _target != string.Empty ) { if( _target != null && _target.LastIndexOf('.') != -1 ) { string target = _target; if( this.IsRecordsetDelivery ) { target = target.Substring( AMFBody.Recordset.Length ); target = target.Substring( target.IndexOf("/") + 1 ); } if( this.IsRecordsetDelivery ) target = target.Substring(0, target.LastIndexOf('.')); string method = target.Substring(target.LastIndexOf('.')+1); return method; } } return null; } } /// <summary> /// This member supports the Fluorine infrastructure and is not intended to be used directly from your code. /// </summary> public string Call { get{ return this.TypeName + "." + this.Method; } } /// <summary> /// This method supports the Fluorine infrastructure and is not intended to be used directly from your code. /// </summary> public string GetSignature() { StringBuilder sb = new StringBuilder(); sb.Append( this.Target ); IList parameterList = GetParameterList(); for(int i = 0; i < parameterList.Count; i++) { object parameter = parameterList[i]; sb.Append( parameter.GetType().FullName ); } return sb.ToString(); } /// <summary> /// This method supports the Fluorine infrastructure and is not intended to be used directly from your code. /// The returned IList has property IsFixedSize set to true, no new elements can be added to it. /// </summary> public virtual IList GetParameterList() { IList list = null; if( !this.IsEmptyTarget )//Flash RPC parameters { if(!(_content is IList)) { #if !(NET_1_1) list = new List<object>(); #else list = new ArrayList(); #endif list.Add(_content ); } else list = _content as IList; } else { object content = this.Content; if( content is IList ) content = (content as IList)[0]; IMessage message = content as IMessage; if( message != null ) { //for RemotingMessages only now if( message is RemotingMessage ) { list = message.body as IList; } } } #if !(NET_1_1) if( list == null ) list = new List<object>(); #else if( list == null ) list = new ArrayList(); #endif return list; } internal void WriteBody(ObjectEncoding objectEncoding, AMFWriter writer) { writer.Reset(); if (this.Target == null) writer.WriteUTF("null"); else writer.WriteUTF(this.Target); if (this.Response == null) writer.WriteUTF("null"); else writer.WriteUTF(this.Response); writer.WriteInt32(-1); WriteBodyData(objectEncoding, writer); } /// <summary> /// This method supports the Fluorine infrastructure and is not intended to be used directly from your code. /// </summary> protected virtual void WriteBodyData(ObjectEncoding objectEncoding, AMFWriter writer) { object content = this.Content; writer.WriteData(objectEncoding, content); } } }
using Lucene.Net.Documents; using Lucene.Net.Randomized.Generators; using Lucene.Net.Support; using Lucene.Net.Support.Threading; using NUnit.Framework; using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using Console = Lucene.Net.Support.SystemConsole; namespace Lucene.Net.Index { using IBits = Lucene.Net.Util.IBits; using BytesRef = Lucene.Net.Util.BytesRef; /* * 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 Codec = Lucene.Net.Codecs.Codec; using Constants = Lucene.Net.Util.Constants; using Directory = Lucene.Net.Store.Directory; using Document = Documents.Document; //using DocValuesType = Lucene.Net.Index.DocValuesType; using Field = Field; using FieldsConsumer = Lucene.Net.Codecs.FieldsConsumer; using FieldsProducer = Lucene.Net.Codecs.FieldsProducer; using FieldType = FieldType; using FixedBitSet = Lucene.Net.Util.FixedBitSet; using FlushInfo = Lucene.Net.Store.FlushInfo; using IOContext = Lucene.Net.Store.IOContext; using PostingsConsumer = Lucene.Net.Codecs.PostingsConsumer; using TermsConsumer = Lucene.Net.Codecs.TermsConsumer; using TermStats = Lucene.Net.Codecs.TermStats; using TestUtil = Lucene.Net.Util.TestUtil; /// <summary> /// Abstract class to do basic tests for a postings format. /// NOTE: this test focuses on the postings /// (docs/freqs/positions/payloads/offsets) impl, not the /// terms dict. The [stretch] goal is for this test to be /// so thorough in testing a new PostingsFormat that if this /// test passes, then all Lucene/Solr tests should also pass. Ie, /// if there is some bug in a given PostingsFormat that this /// test fails to catch then this test needs to be improved! /// </summary> // TODO can we make it easy for testing to pair up a "random terms dict impl" with your postings base format... // TODO test when you reuse after skipping a term or two, eg the block reuse case /* TODO - threads - assert doc=-1 before any nextDoc - if a PF passes this test but fails other tests then this test has a bug!! - test tricky reuse cases, eg across fields - verify you get null if you pass needFreq/needOffset but they weren't indexed */ [TestFixture] public abstract class BasePostingsFormatTestCase : BaseIndexFileFormatTestCase { private enum Option { // Sometimes use .Advance(): SKIPPING, // Sometimes reuse the Docs/AndPositionsEnum across terms: REUSE_ENUMS, // Sometimes pass non-null live docs: LIVE_DOCS, // Sometimes seek to term using previously saved TermState: TERM_STATE, // Sometimes don't fully consume docs from the enum PARTIAL_DOC_CONSUME, // Sometimes don't fully consume positions at each doc PARTIAL_POS_CONSUME, // Sometimes check payloads PAYLOADS, // Test w/ multiple threads THREADS } /// <summary> /// Given the same random seed this always enumerates the /// same random postings /// </summary> private class SeedPostings : DocsAndPositionsEnum { // Used only to generate docIDs; this way if you pull w/ // or w/o positions you get the same docID sequence: internal readonly Random DocRandom; internal readonly Random Random; public int DocFreq; internal readonly int MaxDocSpacing; internal readonly int PayloadSize; internal readonly bool FixedPayloads; internal readonly IBits LiveDocs; internal readonly BytesRef Payload_Renamed; internal readonly IndexOptions Options; internal readonly bool DoPositions; internal int DocID_Renamed; internal int Freq_Renamed; public int Upto; internal int Pos; internal int Offset; internal int StartOffset_Renamed; internal int EndOffset_Renamed; internal int PosSpacing; internal int PosUpto; public SeedPostings(long seed, int minDocFreq, int maxDocFreq, IBits liveDocs, IndexOptions options) { Random = new Random((int)seed); DocRandom = new Random(Random.Next()); DocFreq = TestUtil.NextInt(Random, minDocFreq, maxDocFreq); this.LiveDocs = liveDocs; // TODO: more realistic to inversely tie this to numDocs: MaxDocSpacing = TestUtil.NextInt(Random, 1, 100); if (Random.Next(10) == 7) { // 10% of the time create big payloads: PayloadSize = 1 + Random.Next(3); } else { PayloadSize = 1 + Random.Next(1); } FixedPayloads = Random.NextBoolean(); var payloadBytes = new byte[PayloadSize]; Payload_Renamed = new BytesRef(payloadBytes); this.Options = options; DoPositions = IndexOptions.DOCS_AND_FREQS_AND_POSITIONS.CompareTo(options) <= 0; } public override int NextDoc() { while (true) { _nextDoc(); if (LiveDocs == null || DocID_Renamed == NO_MORE_DOCS || LiveDocs.Get(DocID_Renamed)) { return DocID_Renamed; } } } internal virtual int _nextDoc() { // Must consume random: while (PosUpto < Freq_Renamed) { NextPosition(); } if (Upto < DocFreq) { if (Upto == 0 && DocRandom.NextBoolean()) { // Sometimes index docID = 0 } else if (MaxDocSpacing == 1) { DocID_Renamed++; } else { // TODO: sometimes have a biggish gap here! DocID_Renamed += TestUtil.NextInt(DocRandom, 1, MaxDocSpacing); } if (Random.Next(200) == 17) { Freq_Renamed = TestUtil.NextInt(Random, 1, 1000); } else if (Random.Next(10) == 17) { Freq_Renamed = TestUtil.NextInt(Random, 1, 20); } else { Freq_Renamed = TestUtil.NextInt(Random, 1, 4); } Pos = 0; Offset = 0; PosUpto = 0; PosSpacing = TestUtil.NextInt(Random, 1, 100); Upto++; return DocID_Renamed; } else { return DocID_Renamed = NO_MORE_DOCS; } } public override int DocID { get { return DocID_Renamed; } } public override int Freq { get { return Freq_Renamed; } } public override int NextPosition() { if (!DoPositions) { PosUpto = Freq_Renamed; return 0; } Debug.Assert(PosUpto < Freq_Renamed); if (PosUpto == 0 && Random.NextBoolean()) { // Sometimes index pos = 0 } else if (PosSpacing == 1) { Pos++; } else { Pos += TestUtil.NextInt(Random, 1, PosSpacing); } if (PayloadSize != 0) { if (FixedPayloads) { Payload_Renamed.Length = PayloadSize; Random.NextBytes(Payload_Renamed.Bytes); } else { int thisPayloadSize = Random.Next(PayloadSize); if (thisPayloadSize != 0) { Payload_Renamed.Length = PayloadSize; Random.NextBytes(Payload_Renamed.Bytes); } else { Payload_Renamed.Length = 0; } } } else { Payload_Renamed.Length = 0; } StartOffset_Renamed = Offset + Random.Next(5); EndOffset_Renamed = StartOffset_Renamed + Random.Next(10); Offset = EndOffset_Renamed; PosUpto++; return Pos; } public override int StartOffset { get { return StartOffset_Renamed; } } public override int EndOffset { get { return EndOffset_Renamed; } } public override BytesRef GetPayload() { return Payload_Renamed.Length == 0 ? null : Payload_Renamed; } public override int Advance(int target) { return SlowAdvance(target); } public override long GetCost() { return DocFreq; } } private class FieldAndTerm { internal string Field; internal BytesRef Term; public FieldAndTerm(string field, BytesRef term) { this.Field = field; this.Term = BytesRef.DeepCopyOf(term); } } // Holds all postings: private static SortedDictionary<string, SortedDictionary<BytesRef, long>> Fields; private static FieldInfos FieldInfos; private static FixedBitSet GlobalLiveDocs; private static IList<FieldAndTerm> AllTerms; private static int MaxDoc; private static long TotalPostings; private static long TotalPayloadBytes; private static SeedPostings GetSeedPostings(string term, long seed, bool withLiveDocs, IndexOptions options) { int minDocFreq, maxDocFreq; if (term.StartsWith("big_", StringComparison.Ordinal)) { minDocFreq = RANDOM_MULTIPLIER * 50000; maxDocFreq = RANDOM_MULTIPLIER * 70000; } else if (term.StartsWith("medium_", StringComparison.Ordinal)) { minDocFreq = RANDOM_MULTIPLIER * 3000; maxDocFreq = RANDOM_MULTIPLIER * 6000; } else if (term.StartsWith("low_", StringComparison.Ordinal)) { minDocFreq = RANDOM_MULTIPLIER; maxDocFreq = RANDOM_MULTIPLIER * 40; } else { minDocFreq = 1; maxDocFreq = 3; } return new SeedPostings(seed, minDocFreq, maxDocFreq, withLiveDocs ? GlobalLiveDocs : null, options); } [OneTimeSetUp] public override void BeforeClass() // Renamed from CreatePostings to ensure the base class setup is called before this one { base.BeforeClass(); TotalPostings = 0; TotalPayloadBytes = 0; // LUCENENET specific: Use StringComparer.Ordinal to get the same ordering as Java Fields = new SortedDictionary<string, SortedDictionary<BytesRef, long>>(StringComparer.Ordinal); int numFields = TestUtil.NextInt(Random(), 1, 5); if (VERBOSE) { Console.WriteLine("TEST: " + numFields + " fields"); } MaxDoc = 0; FieldInfo[] fieldInfoArray = new FieldInfo[numFields]; int fieldUpto = 0; while (fieldUpto < numFields) { string field = TestUtil.RandomSimpleString(Random()); if (Fields.ContainsKey(field)) { continue; } fieldInfoArray[fieldUpto] = new FieldInfo(field, true, fieldUpto, false, false, true, IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS, DocValuesType.NONE, DocValuesType.NUMERIC, null); fieldUpto++; SortedDictionary<BytesRef, long> postings = new SortedDictionary<BytesRef, long>(); Fields[field] = postings; HashSet<string> seenTerms = new HashSet<string>(); int numTerms; if (Random().Next(10) == 7) { numTerms = AtLeast(50); } else { numTerms = TestUtil.NextInt(Random(), 2, 20); } for (int termUpto = 0; termUpto < numTerms; termUpto++) { string term = TestUtil.RandomSimpleString(Random()); if (seenTerms.Contains(term)) { continue; } seenTerms.Add(term); if (TEST_NIGHTLY && termUpto == 0 && fieldUpto == 1) { // Make 1 big term: term = "big_" + term; } else if (termUpto == 1 && fieldUpto == 1) { // Make 1 medium term: term = "medium_" + term; } else if (Random().NextBoolean()) { // Low freq term: term = "low_" + term; } else { // Very low freq term (don't multiply by RANDOM_MULTIPLIER): term = "verylow_" + term; } long termSeed = Random().NextLong(); postings[new BytesRef(term)] = termSeed; // NOTE: sort of silly: we enum all the docs just to // get the maxDoc DocsEnum docsEnum = GetSeedPostings(term, termSeed, false, IndexOptions.DOCS_ONLY); int doc; int lastDoc = 0; while ((doc = docsEnum.NextDoc()) != DocsEnum.NO_MORE_DOCS) { lastDoc = doc; } MaxDoc = Math.Max(lastDoc, MaxDoc); } } FieldInfos = new FieldInfos(fieldInfoArray); // It's the count, not the last docID: MaxDoc++; GlobalLiveDocs = new FixedBitSet(MaxDoc); double liveRatio = Random().NextDouble(); for (int i = 0; i < MaxDoc; i++) { if (Random().NextDouble() <= liveRatio) { GlobalLiveDocs.Set(i); } } AllTerms = new List<FieldAndTerm>(); foreach (KeyValuePair<string, SortedDictionary<BytesRef, long>> fieldEnt in Fields) { string field = fieldEnt.Key; foreach (KeyValuePair<BytesRef, long> termEnt in fieldEnt.Value.EntrySet()) { AllTerms.Add(new FieldAndTerm(field, termEnt.Key)); } } if (VERBOSE) { Console.WriteLine("TEST: done init postings; " + AllTerms.Count + " total terms, across " + FieldInfos.Count + " fields"); } } [OneTimeTearDown] public override void AfterClass() { AllTerms = null; FieldInfos = null; Fields = null; GlobalLiveDocs = null; base.AfterClass(); } // TODO maybe instead of @BeforeClass just make a single test run: build postings & index & test it? private FieldInfos CurrentFieldInfos; // maxAllowed = the "highest" we can index, but we will still // randomly index at lower IndexOption private FieldsProducer BuildIndex(Directory dir, IndexOptions maxAllowed, bool allowPayloads, bool alwaysTestMax) { Codec codec = Codec; SegmentInfo segmentInfo = new SegmentInfo(dir, Constants.LUCENE_MAIN_VERSION, "_0", MaxDoc, false, codec, null); int maxIndexOption = Enum.GetValues(typeof(IndexOptions)).Cast<IndexOptions>().ToList().IndexOf(maxAllowed); if (VERBOSE) { Console.WriteLine("\nTEST: now build index"); } int maxIndexOptionNoOffsets = Enum.GetValues(typeof(IndexOptions)).Cast<IndexOptions>().ToList().IndexOf(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS); // TODO use allowPayloads var newFieldInfoArray = new FieldInfo[Fields.Count]; for (int fieldUpto = 0; fieldUpto < Fields.Count; fieldUpto++) { FieldInfo oldFieldInfo = FieldInfos.FieldInfo(fieldUpto); string pf = TestUtil.GetPostingsFormat(codec, oldFieldInfo.Name); int fieldMaxIndexOption; if (DoesntSupportOffsets.Contains(pf)) { fieldMaxIndexOption = Math.Min(maxIndexOptionNoOffsets, maxIndexOption); } else { fieldMaxIndexOption = maxIndexOption; } // Randomly picked the IndexOptions to index this // field with: IndexOptions indexOptions = Enum.GetValues(typeof(IndexOptions)).Cast<IndexOptions>().ToArray()[alwaysTestMax ? fieldMaxIndexOption : Random().Next(1, 1 + fieldMaxIndexOption)]; // LUCENENET: Skipping NONE option bool doPayloads = indexOptions.CompareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) >= 0 && allowPayloads; newFieldInfoArray[fieldUpto] = new FieldInfo(oldFieldInfo.Name, true, fieldUpto, false, false, doPayloads, indexOptions, DocValuesType.NONE, DocValuesType.NUMERIC, null); } FieldInfos newFieldInfos = new FieldInfos(newFieldInfoArray); // Estimate that flushed segment size will be 25% of // what we use in RAM: long bytes = TotalPostings * 8 + TotalPayloadBytes; SegmentWriteState writeState = new SegmentWriteState(null, dir, segmentInfo, newFieldInfos, 32, null, new IOContext(new FlushInfo(MaxDoc, bytes))); // LUCENENET specific - BUG: we must wrap this in a using block in case anything in the below loop throws using (FieldsConsumer fieldsConsumer = codec.PostingsFormat.FieldsConsumer(writeState)) { foreach (KeyValuePair<string, SortedDictionary<BytesRef, long>> fieldEnt in Fields) { string field = fieldEnt.Key; IDictionary<BytesRef, long> terms = fieldEnt.Value; FieldInfo fieldInfo = newFieldInfos.FieldInfo(field); IndexOptions indexOptions = fieldInfo.IndexOptions; if (VERBOSE) { Console.WriteLine("field=" + field + " indexOtions=" + indexOptions); } bool doFreq = indexOptions.CompareTo(IndexOptions.DOCS_AND_FREQS) >= 0; bool doPos = indexOptions.CompareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) >= 0; bool doPayloads = indexOptions.CompareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) >= 0 && allowPayloads; bool doOffsets = indexOptions.CompareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS) >= 0; TermsConsumer termsConsumer = fieldsConsumer.AddField(fieldInfo); long sumTotalTF = 0; long sumDF = 0; FixedBitSet seenDocs = new FixedBitSet(MaxDoc); foreach (KeyValuePair<BytesRef, long> termEnt in terms) { BytesRef term = termEnt.Key; SeedPostings postings = GetSeedPostings(term.Utf8ToString(), termEnt.Value, false, maxAllowed); if (VERBOSE) { Console.WriteLine(" term=" + field + ":" + term.Utf8ToString() + " docFreq=" + postings.DocFreq + " seed=" + termEnt.Value); } PostingsConsumer postingsConsumer = termsConsumer.StartTerm(term); long totalTF = 0; int docID = 0; while ((docID = postings.NextDoc()) != DocsEnum.NO_MORE_DOCS) { int freq = postings.Freq; if (VERBOSE) { Console.WriteLine(" " + postings.Upto + ": docID=" + docID + " freq=" + postings.Freq_Renamed); } postingsConsumer.StartDoc(docID, doFreq ? postings.Freq_Renamed : -1); seenDocs.Set(docID); if (doPos) { totalTF += postings.Freq_Renamed; for (int posUpto = 0; posUpto < freq; posUpto++) { int pos = postings.NextPosition(); BytesRef payload = postings.GetPayload(); if (VERBOSE) { if (doPayloads) { Console.WriteLine(" pos=" + pos + " payload=" + (payload == null ? "null" : payload.Length + " bytes")); } else { Console.WriteLine(" pos=" + pos); } } postingsConsumer.AddPosition(pos, doPayloads ? payload : null, doOffsets ? postings.StartOffset : -1, doOffsets ? postings.EndOffset : -1); } } else if (doFreq) { totalTF += freq; } else { totalTF++; } postingsConsumer.FinishDoc(); } termsConsumer.FinishTerm(term, new TermStats(postings.DocFreq, doFreq ? totalTF : -1)); sumTotalTF += totalTF; sumDF += postings.DocFreq; } termsConsumer.Finish(doFreq ? sumTotalTF : -1, sumDF, seenDocs.Cardinality()); } } if (VERBOSE) { Console.WriteLine("TEST: after indexing: files="); foreach (string file in dir.ListAll()) { Console.WriteLine(" " + file + ": " + dir.FileLength(file) + " bytes"); } } CurrentFieldInfos = newFieldInfos; SegmentReadState readState = new SegmentReadState(dir, segmentInfo, newFieldInfos, IOContext.READ, 1); return codec.PostingsFormat.FieldsProducer(readState); } private class ThreadState { // Only used with REUSE option: public DocsEnum ReuseDocsEnum; public DocsAndPositionsEnum ReuseDocsAndPositionsEnum; } private void VerifyEnum(ThreadState threadState, string field, BytesRef term, TermsEnum termsEnum, // Maximum options (docs/freqs/positions/offsets) to test: IndexOptions maxTestOptions, IndexOptions maxIndexOptions, ISet<Option> options, bool alwaysTestMax) { if (VERBOSE) { Console.WriteLine(" verifyEnum: options=" + options + " maxTestOptions=" + maxTestOptions); } // Make sure TermsEnum really is positioned on the // expected term: Assert.AreEqual(term, termsEnum.Term); // 50% of the time time pass liveDocs: bool useLiveDocs = options.Contains(Option.LIVE_DOCS) && Random().NextBoolean(); IBits liveDocs; if (useLiveDocs) { liveDocs = GlobalLiveDocs; if (VERBOSE) { Console.WriteLine(" use liveDocs"); } } else { liveDocs = null; if (VERBOSE) { Console.WriteLine(" no liveDocs"); } } FieldInfo fieldInfo = CurrentFieldInfos.FieldInfo(field); // NOTE: can be empty list if we are using liveDocs: SeedPostings expected = GetSeedPostings(term.Utf8ToString(), Fields[field][term], useLiveDocs, maxIndexOptions); Assert.AreEqual(expected.DocFreq, termsEnum.DocFreq); bool allowFreqs = fieldInfo.IndexOptions.CompareTo(IndexOptions.DOCS_AND_FREQS) >= 0 && maxTestOptions.CompareTo(IndexOptions.DOCS_AND_FREQS) >= 0; bool doCheckFreqs = allowFreqs && (alwaysTestMax || Random().Next(3) <= 2); bool allowPositions = fieldInfo.IndexOptions.CompareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) >= 0 && maxTestOptions.CompareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) >= 0; bool doCheckPositions = allowPositions && (alwaysTestMax || Random().Next(3) <= 2); bool allowOffsets = fieldInfo.IndexOptions.CompareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS) >=0 && maxTestOptions.CompareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS) >= 0; bool doCheckOffsets = allowOffsets && (alwaysTestMax || Random().Next(3) <= 2); bool doCheckPayloads = options.Contains(Option.PAYLOADS) && allowPositions && fieldInfo.HasPayloads && (alwaysTestMax || Random().Next(3) <= 2); DocsEnum prevDocsEnum = null; DocsEnum docsEnum; DocsAndPositionsEnum docsAndPositionsEnum; if (!doCheckPositions) { if (allowPositions && Random().Next(10) == 7) { // 10% of the time, even though we will not check positions, pull a DocsAndPositions enum if (options.Contains(Option.REUSE_ENUMS) && Random().Next(10) < 9) { prevDocsEnum = threadState.ReuseDocsAndPositionsEnum; } DocsAndPositionsFlags flags = 0; if (alwaysTestMax || Random().NextBoolean()) { flags |= DocsAndPositionsFlags.OFFSETS; } if (alwaysTestMax || Random().NextBoolean()) { flags |= DocsAndPositionsFlags.PAYLOADS; } if (VERBOSE) { Console.WriteLine(" get DocsAndPositionsEnum (but we won't check positions) flags=" + flags); } threadState.ReuseDocsAndPositionsEnum = termsEnum.DocsAndPositions(liveDocs, (DocsAndPositionsEnum)prevDocsEnum, flags); docsEnum = threadState.ReuseDocsAndPositionsEnum; docsAndPositionsEnum = threadState.ReuseDocsAndPositionsEnum; } else { if (VERBOSE) { Console.WriteLine(" get DocsEnum"); } if (options.Contains(Option.REUSE_ENUMS) && Random().Next(10) < 9) { prevDocsEnum = threadState.ReuseDocsEnum; } threadState.ReuseDocsEnum = termsEnum.Docs(liveDocs, prevDocsEnum, doCheckFreqs ? DocsFlags.FREQS : DocsFlags.NONE); docsEnum = threadState.ReuseDocsEnum; docsAndPositionsEnum = null; } } else { if (options.Contains(Option.REUSE_ENUMS) && Random().Next(10) < 9) { prevDocsEnum = threadState.ReuseDocsAndPositionsEnum; } DocsAndPositionsFlags flags = 0; if (alwaysTestMax || doCheckOffsets || Random().Next(3) == 1) { flags |= DocsAndPositionsFlags.OFFSETS; } if (alwaysTestMax || doCheckPayloads || Random().Next(3) == 1) { flags |= DocsAndPositionsFlags.PAYLOADS; } if (VERBOSE) { Console.WriteLine(" get DocsAndPositionsEnum flags=" + flags); } threadState.ReuseDocsAndPositionsEnum = termsEnum.DocsAndPositions(liveDocs, (DocsAndPositionsEnum)prevDocsEnum, flags); docsEnum = threadState.ReuseDocsAndPositionsEnum; docsAndPositionsEnum = threadState.ReuseDocsAndPositionsEnum; } Assert.IsNotNull(docsEnum, "null DocsEnum"); int initialDocID = docsEnum.DocID; Assert.AreEqual(-1, initialDocID, "inital docID should be -1" + docsEnum); if (VERBOSE) { if (prevDocsEnum == null) { Console.WriteLine(" got enum=" + docsEnum); } else if (prevDocsEnum == docsEnum) { Console.WriteLine(" got reuse enum=" + docsEnum); } else { Console.WriteLine(" got enum=" + docsEnum + " (reuse of " + prevDocsEnum + " failed)"); } } // 10% of the time don't consume all docs: int stopAt; if (!alwaysTestMax && options.Contains(Option.PARTIAL_DOC_CONSUME) && expected.DocFreq > 1 && Random().Next(10) == 7) { stopAt = Random().Next(expected.DocFreq - 1); if (VERBOSE) { Console.WriteLine(" will not consume all docs (" + stopAt + " vs " + expected.DocFreq + ")"); } } else { stopAt = expected.DocFreq; if (VERBOSE) { Console.WriteLine(" consume all docs"); } } double skipChance = alwaysTestMax ? 0.5 : Random().NextDouble(); int numSkips = expected.DocFreq < 3 ? 1 : TestUtil.NextInt(Random(), 1, Math.Min(20, expected.DocFreq / 3)); int skipInc = expected.DocFreq / numSkips; int skipDocInc = MaxDoc / numSkips; // Sometimes do 100% skipping: bool doAllSkipping = options.Contains(Option.SKIPPING) && Random().Next(7) == 1; double freqAskChance = alwaysTestMax ? 1.0 : Random().NextDouble(); double payloadCheckChance = alwaysTestMax ? 1.0 : Random().NextDouble(); double offsetCheckChance = alwaysTestMax ? 1.0 : Random().NextDouble(); if (VERBOSE) { if (options.Contains(Option.SKIPPING)) { Console.WriteLine(" skipChance=" + skipChance + " numSkips=" + numSkips); } else { Console.WriteLine(" no skipping"); } if (doCheckFreqs) { Console.WriteLine(" freqAskChance=" + freqAskChance); } if (doCheckPayloads) { Console.WriteLine(" payloadCheckChance=" + payloadCheckChance); } if (doCheckOffsets) { Console.WriteLine(" offsetCheckChance=" + offsetCheckChance); } } while (expected.Upto <= stopAt) { if (expected.Upto == stopAt) { if (stopAt == expected.DocFreq) { Assert.AreEqual(DocsEnum.NO_MORE_DOCS, docsEnum.NextDoc(), "DocsEnum should have ended but didn't"); // Common bug is to forget to set this.Doc=NO_MORE_DOCS in the enum!: Assert.AreEqual(DocsEnum.NO_MORE_DOCS, docsEnum.DocID, "DocsEnum should have ended but didn't"); } break; } if (options.Contains(Option.SKIPPING) && (doAllSkipping || Random().NextDouble() <= skipChance)) { int targetDocID = -1; if (expected.Upto < stopAt && Random().NextBoolean()) { // Pick target we know exists: int skipCount = TestUtil.NextInt(Random(), 1, skipInc); for (int skip = 0; skip < skipCount; skip++) { if (expected.NextDoc() == DocsEnum.NO_MORE_DOCS) { break; } } } else { // Pick random target (might not exist): int skipDocIDs = TestUtil.NextInt(Random(), 1, skipDocInc); if (skipDocIDs > 0) { targetDocID = expected.DocID + skipDocIDs; expected.Advance(targetDocID); } } if (expected.Upto >= stopAt) { int target = Random().NextBoolean() ? MaxDoc : DocsEnum.NO_MORE_DOCS; if (VERBOSE) { Console.WriteLine(" now advance to end (target=" + target + ")"); } Assert.AreEqual(DocsEnum.NO_MORE_DOCS, docsEnum.Advance(target), "DocsEnum should have ended but didn't"); break; } else { if (VERBOSE) { if (targetDocID != -1) { Console.WriteLine(" now advance to random target=" + targetDocID + " (" + expected.Upto + " of " + stopAt + ") current=" + docsEnum.DocID); } else { Console.WriteLine(" now advance to known-exists target=" + expected.DocID + " (" + expected.Upto + " of " + stopAt + ") current=" + docsEnum.DocID); } } int docID = docsEnum.Advance(targetDocID != -1 ? targetDocID : expected.DocID); Assert.AreEqual(expected.DocID, docID, "docID is wrong"); } } else { expected.NextDoc(); if (VERBOSE) { Console.WriteLine(" now nextDoc to " + expected.DocID + " (" + expected.Upto + " of " + stopAt + ")"); } int docID = docsEnum.NextDoc(); Assert.AreEqual(expected.DocID, docID, "docID is wrong"); if (docID == DocsEnum.NO_MORE_DOCS) { break; } } if (doCheckFreqs && Random().NextDouble() <= freqAskChance) { if (VERBOSE) { Console.WriteLine(" now freq()=" + expected.Freq); } int freq = docsEnum.Freq; Assert.AreEqual(expected.Freq, freq, "freq is wrong"); } if (doCheckPositions) { int freq = docsEnum.Freq; int numPosToConsume; if (!alwaysTestMax && options.Contains(Option.PARTIAL_POS_CONSUME) && Random().Next(5) == 1) { numPosToConsume = Random().Next(freq); } else { numPosToConsume = freq; } for (int i = 0; i < numPosToConsume; i++) { int pos = expected.NextPosition(); if (VERBOSE) { Console.WriteLine(" now nextPosition to " + pos); } Assert.AreEqual(pos, docsAndPositionsEnum.NextPosition(), "position is wrong"); if (doCheckPayloads) { BytesRef expectedPayload = expected.GetPayload(); if (Random().NextDouble() <= payloadCheckChance) { if (VERBOSE) { Console.WriteLine(" now check expectedPayload length=" + (expectedPayload == null ? 0 : expectedPayload.Length)); } if (expectedPayload == null || expectedPayload.Length == 0) { Assert.IsNull(docsAndPositionsEnum.GetPayload(), "should not have payload"); } else { BytesRef payload = docsAndPositionsEnum.GetPayload(); Assert.IsNotNull(payload, "should have payload but doesn't"); Assert.AreEqual(expectedPayload.Length, payload.Length, "payload length is wrong"); for (int byteUpto = 0; byteUpto < expectedPayload.Length; byteUpto++) { Assert.AreEqual(expectedPayload.Bytes[expectedPayload.Offset + byteUpto], payload.Bytes[payload.Offset + byteUpto], "payload bytes are wrong"); } // make a deep copy payload = BytesRef.DeepCopyOf(payload); Assert.AreEqual(payload, docsAndPositionsEnum.GetPayload(), "2nd call to getPayload returns something different!"); } } else { if (VERBOSE) { Console.WriteLine(" skip check payload length=" + (expectedPayload == null ? 0 : expectedPayload.Length)); } } } if (doCheckOffsets) { if (Random().NextDouble() <= offsetCheckChance) { if (VERBOSE) { Console.WriteLine(" now check offsets: startOff=" + expected.StartOffset + " endOffset=" + expected.EndOffset); } Assert.AreEqual(expected.StartOffset, docsAndPositionsEnum.StartOffset, "startOffset is wrong"); Assert.AreEqual(expected.EndOffset, docsAndPositionsEnum.EndOffset, "endOffset is wrong"); } else { if (VERBOSE) { Console.WriteLine(" skip check offsets"); } } } else if (fieldInfo.IndexOptions.CompareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS) < 0) { if (VERBOSE) { Console.WriteLine(" now check offsets are -1"); } Assert.AreEqual(-1, docsAndPositionsEnum.StartOffset, "startOffset isn't -1"); Assert.AreEqual(-1, docsAndPositionsEnum.EndOffset, "endOffset isn't -1"); } } } } } new private class TestThread : ThreadClass { internal Fields FieldsSource; internal ISet<Option> Options; internal IndexOptions MaxIndexOptions; internal IndexOptions MaxTestOptions; internal bool AlwaysTestMax; internal BasePostingsFormatTestCase TestCase; public TestThread(BasePostingsFormatTestCase testCase, Fields fieldsSource, ISet<Option> options, IndexOptions maxTestOptions, IndexOptions maxIndexOptions, bool alwaysTestMax) { this.FieldsSource = fieldsSource; this.Options = options; this.MaxTestOptions = maxTestOptions; this.MaxIndexOptions = maxIndexOptions; this.AlwaysTestMax = alwaysTestMax; this.TestCase = testCase; } public override void Run() { try { try { TestCase.TestTermsOneThread(FieldsSource, Options, MaxTestOptions, MaxIndexOptions, AlwaysTestMax); } catch (Exception t) { throw new Exception(t.Message, t); } } finally { FieldsSource = null; TestCase = null; } } } private void TestTerms(Fields fieldsSource, ISet<Option> options, IndexOptions maxTestOptions, IndexOptions maxIndexOptions, bool alwaysTestMax) { if (options.Contains(Option.THREADS)) { int numThreads = TestUtil.NextInt(Random(), 2, 5); ThreadClass[] threads = new ThreadClass[numThreads]; for (int threadUpto = 0; threadUpto < numThreads; threadUpto++) { threads[threadUpto] = new TestThread(this, fieldsSource, options, maxTestOptions, maxIndexOptions, alwaysTestMax); threads[threadUpto].Start(); } for (int threadUpto = 0; threadUpto < numThreads; threadUpto++) { threads[threadUpto].Join(); } } else { TestTermsOneThread(fieldsSource, options, maxTestOptions, maxIndexOptions, alwaysTestMax); } } private void TestTermsOneThread(Fields fieldsSource, ISet<Option> options, IndexOptions maxTestOptions, IndexOptions maxIndexOptions, bool alwaysTestMax) { ThreadState threadState = new ThreadState(); // Test random terms/fields: IList<TermState> termStates = new List<TermState>(); IList<FieldAndTerm> termStateTerms = new List<FieldAndTerm>(); Collections.Shuffle(AllTerms); int upto = 0; while (upto < AllTerms.Count) { bool useTermState = termStates.Count != 0 && Random().Next(5) == 1; FieldAndTerm fieldAndTerm; TermsEnum termsEnum; TermState termState = null; if (!useTermState) { // Seek by random field+term: fieldAndTerm = AllTerms[upto++]; if (VERBOSE) { Console.WriteLine("\nTEST: seek to term=" + fieldAndTerm.Field + ":" + fieldAndTerm.Term.Utf8ToString()); } } else { // Seek by previous saved TermState int idx = Random().Next(termStates.Count); fieldAndTerm = termStateTerms[idx]; if (VERBOSE) { Console.WriteLine("\nTEST: seek using TermState to term=" + fieldAndTerm.Field + ":" + fieldAndTerm.Term.Utf8ToString()); } termState = termStates[idx]; } Terms terms = fieldsSource.GetTerms(fieldAndTerm.Field); Assert.IsNotNull(terms); termsEnum = terms.GetIterator(null); if (!useTermState) { Assert.IsTrue(termsEnum.SeekExact(fieldAndTerm.Term)); } else { termsEnum.SeekExact(fieldAndTerm.Term, termState); } bool savedTermState = false; if (options.Contains(Option.TERM_STATE) && !useTermState && Random().Next(5) == 1) { // Save away this TermState: termStates.Add(termsEnum.GetTermState()); termStateTerms.Add(fieldAndTerm); savedTermState = true; } VerifyEnum(threadState, fieldAndTerm.Field, fieldAndTerm.Term, termsEnum, maxTestOptions, maxIndexOptions, options, alwaysTestMax); // Sometimes save term state after pulling the enum: if (options.Contains(Option.TERM_STATE) && !useTermState && !savedTermState && Random().Next(5) == 1) { // Save away this TermState: termStates.Add(termsEnum.GetTermState()); termStateTerms.Add(fieldAndTerm); useTermState = true; } // 10% of the time make sure you can pull another enum // from the same term: if (alwaysTestMax || Random().Next(10) == 7) { // Try same term again if (VERBOSE) { Console.WriteLine("TEST: try enum again on same term"); } VerifyEnum(threadState, fieldAndTerm.Field, fieldAndTerm.Term, termsEnum, maxTestOptions, maxIndexOptions, options, alwaysTestMax); } } } private void TestFields(Fields fields) { IEnumerator<string> iterator = fields.GetEnumerator(); while (iterator.MoveNext()) { var dummy = iterator.Current; // .NET: Testing for iterator.Remove() isn't applicable } Assert.IsFalse(iterator.MoveNext()); // .NET: Testing for NoSuchElementException with .NET iterators isn't applicable } /// <summary> /// Indexes all fields/terms at the specified /// IndexOptions, and fully tests at that IndexOptions. /// </summary> private void TestFull(IndexOptions options, bool withPayloads) { DirectoryInfo path = CreateTempDir("testPostingsFormat.testExact"); using (Directory dir = NewFSDirectory(path)) { // TODO test thread safety of buildIndex too var fieldsProducer = BuildIndex(dir, options, withPayloads, true); TestFields(fieldsProducer); var allOptions = ((IndexOptions[])Enum.GetValues(typeof(IndexOptions))).Skip(1).ToArray(); // LUCENENET: Skip our NONE option //IndexOptions_e.values(); int maxIndexOption = Arrays.AsList(allOptions).IndexOf(options); for (int i = 0; i <= maxIndexOption; i++) { ISet<Option> allOptionsHashSet = new HashSet<Option>(Enum.GetValues(typeof (Option)).Cast<Option>()); TestTerms(fieldsProducer, allOptionsHashSet, allOptions[i], options, true); if (withPayloads) { // If we indexed w/ payloads, also test enums w/o accessing payloads: ISet<Option> payloadsHashSet = new HashSet<Option>() {Option.PAYLOADS}; var complementHashSet = new HashSet<Option>(allOptionsHashSet.Except(payloadsHashSet)); TestTerms(fieldsProducer, complementHashSet, allOptions[i], options, true); } } fieldsProducer.Dispose(); } } // [Test] // LUCENENET NOTE: For now, we are overriding this test in every subclass to pull it into the right context for the subclass public virtual void TestDocsOnly() { TestFull(IndexOptions.DOCS_ONLY, false); } // [Test] // LUCENENET NOTE: For now, we are overriding this test in every subclass to pull it into the right context for the subclass public virtual void TestDocsAndFreqs() { TestFull(IndexOptions.DOCS_AND_FREQS, false); } // [Test] // LUCENENET NOTE: For now, we are overriding this test in every subclass to pull it into the right context for the subclass public virtual void TestDocsAndFreqsAndPositions() { TestFull(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS, false); } // [Test] // LUCENENET NOTE: For now, we are overriding this test in every subclass to pull it into the right context for the subclass public virtual void TestDocsAndFreqsAndPositionsAndPayloads() { TestFull(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS, true); } // [Test] // LUCENENET NOTE: For now, we are overriding this test in every subclass to pull it into the right context for the subclass public virtual void TestDocsAndFreqsAndPositionsAndOffsets() { TestFull(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS, false); } // [Test] // LUCENENET NOTE: For now, we are overriding this test in every subclass to pull it into the right context for the subclass public virtual void TestDocsAndFreqsAndPositionsAndOffsetsAndPayloads() { TestFull(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS, true); } // [Test] // LUCENENET NOTE: For now, we are overriding this test in every subclass to pull it into the right context for the subclass public virtual void TestRandom() { int iters = 5; for (int iter = 0; iter < iters; iter++) { DirectoryInfo path = CreateTempDir("testPostingsFormat"); Directory dir = NewFSDirectory(path); bool indexPayloads = Random().NextBoolean(); // TODO test thread safety of buildIndex too FieldsProducer fieldsProducer = BuildIndex(dir, IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS, indexPayloads, false); TestFields(fieldsProducer); // NOTE: you can also test "weaker" index options than // you indexed with: TestTerms(fieldsProducer, // LUCENENET: Skip our NONE option new HashSet<Option>(Enum.GetValues(typeof(Option)).Cast<Option>().Skip(1)), IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS, IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS, false); fieldsProducer.Dispose(); fieldsProducer = null; dir.Dispose(); System.IO.Directory.Delete(path.FullName, true); } } protected internal override void AddRandomFields(Document doc) { foreach (IndexOptions opts in Enum.GetValues(typeof(IndexOptions))) { // LUCENENET: Skip our NONE option if (opts == IndexOptions.NONE) { continue; } string field = "f_" + opts; string pf = TestUtil.GetPostingsFormat(Codec.Default, field); if (opts == IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS && DoesntSupportOffsets.Contains(pf)) { continue; } var ft = new FieldType { IndexOptions = opts, IsIndexed = true, OmitNorms = true}; ft.Freeze(); int numFields = Random().Next(5); for (int j = 0; j < numFields; ++j) { doc.Add(new Field("f_" + opts, TestUtil.RandomSimpleString(Random(), 2), ft)); } } } } }
using System; /// <summary> /// DataType representing an bin containing a number of item's. /// 1.) Initialising create's empty template. /// 2.) Use Load to fill in variable's. /// </summary> public class bin { string[,,] stringBin = new string[2, 4, 2]; ioINI iniDetails = new ioINI(); //Bin Information public string _Path; public string _File; int _Store; int _Level; int _Shelf; int _Bin; int _Quantity; int _Price; //Article Information int _Storage; int _Section; int _Article; article articleSelected; /// <summary> /// Retrieve Value from given Category && Option. /// </summary> /// <param name="Category">Category as string.</param> /// <param name="Option">Option as string.</param> /// <returns>Single string with Value.</returns> string Retrieve(string Category, string Option) { for (int intC = 0; intC <= stringBin.GetUpperBound(0); intC++) { if (stringBin[intC, 0, 0] == Category) { for (int intO = 0; intO <= stringBin.GetUpperBound(1); intO++) { if (stringBin[intC, intO, 0] == Option) { return stringBin[intC, intO, 1]; } } } } return null; } /// <summary> /// Change the Value of a Option in a given Category. /// </summary> /// <param name="Category">Category as string.</param> /// <param name="Option">Option as string.</param> /// <param name="Value">Value as string.</param> void Change(string Category, string Option, string Value) { for (int intC = 0; intC <= stringBin.GetUpperBound(0); intC++) { if (stringBin[intC, 0, 0] == Category) { for (int intO = 0; intO <= stringBin.GetUpperBound(1); intO++) { if (stringBin[intC, intO, 0] == Option) { stringBin[intC, intO, 1] = Value; } } } } } /// <summary> /// Loads the bin through Store, Level, Shelf and Bin. /// </summary> /// <param name="Store">Store of Bin.</param> /// <param name="Level">Level of Bin.</param> /// <param name="Shelf">Shelf of Bin.</param> /// <param name="Bin">Designated Bin.</param> public void Load(int Store, int Level, int Shelf, int Bin) { _Store = Store; _Level = Level; _Shelf = Shelf; _Bin = Bin; // Check if bin exists, yes=load no=new. if (System.IO.File.Exists(System.IO.Directory.GetCurrentDirectory() + (char)92 + "save" + (char)92 + gamecache.currentPlayer.ProfileID + (char)92 + "store" + (char)92 + Store + (char)92 + Level + (char)92 + Shelf + (char)92 + Bin + (char)92 + "details.ini")) { //Bin Information _Store = Store; _Level = Level; _Shelf = Shelf; _Bin = Bin; _Path = "save" + (char)92 + gamecache.currentPlayer.ProfileID + (char)92 + "store" + (char)92 + Store + (char)92 + Level + (char)92 + Shelf + (Char)92 + Bin; _File = "details.ini"; stringBin = iniDetails.Load(_Path, _File); //Load bin ini _Quantity = Convert.ToInt32(Retrieve("Bin Information", "Quantity of article")); _Price = Convert.ToInt32(Retrieve("Bin Information", "Price of article")); //Article Information _Storage = Convert.ToInt32(Retrieve("Article Information", "Storage of article")); _Section = Convert.ToInt32(Retrieve("Article Information", "Section of article")); _Article = Convert.ToInt32(Retrieve("Article Information", "Designated article")); articleSelected = new article(); articleSelected.Load(_Storage, _Section, _Article); } else { //Bin Information stringBin[0, 0, 0] = "Bin Information"; stringBin[0, 1, 0] = "Quantity of article"; stringBin[0, 1, 1] = "0"; _Quantity = 0; stringBin[0, 2, 0] = "Price of article"; stringBin[0, 2, 1] = "0"; _Price = 0; //Article Information stringBin[1, 0, 0] = "Article Information"; stringBin[1, 1, 0] = "Storage of article"; stringBin[1, 1, 1] = "0"; _Storage = 0; stringBin[1, 2, 0] = "Section of article"; stringBin[1, 2, 1] = "0"; _Section = 0; stringBin[1, 3, 0] = "Designated article"; stringBin[1, 3, 1] = "0"; _Article = 0; binSave(); } } void binSave() { iniDetails.Save("save" + (char)92 + gamecache.currentPlayer.ProfileID + (char)92 + "store" + (char)92 + _Store + (char)92 + _Level + (char)92 + _Shelf + (char)92 + _Bin, "details.ini", stringBin); } /// <summary> /// Get/Sets the Quantity of the Article in the bin-slot WITH Change() and binSave(). /// </summary> public int Quantity { get { return _Quantity; } set { _Quantity = value; Change("Bin Information", "Quantity of article", value.ToString()); binSave(); } } /// <summary> /// Get/Sets the Price of the article in the bin-slot WITH Change() and binSave(). /// </summary> public int Price { get { return _Price; } set { _Price = value; Change("Bin Information", "Price of article", value.ToString()); binSave(); } } /// <summary> /// Get/Sets the Storage of the article in the bin-slot WITH Change() and WITHOUT binSave() & articleSelected.Load(). /// When setting the designated article it will do binSave() & articleSelected.Load(). /// </summary> public int Storage { get { return _Storage; } set { _Storage = value; Change("Article Information", "Storage of article", value.ToString()); } } /// <summary> /// Get/Sets the Section of the article in the bin-slot WITH Change() and WITHOUT binSave() & articleSelected.Load(). /// When setting the designated article it will do binSave() & articleSelected.Load(). /// </summary> public int Section { get { return _Section; } set { _Section = value; Change("Article Information", "Section of article", value.ToString()); } } /// <summary> /// Get/Sets the designated article in the bin-slot WITH Change(), binSave() & articleSelected.Load(). /// </summary> public int Article { get { return _Article; } set { _Article = value; Change("Article Information", "Designated article", value.ToString()); binSave(); articleSelected.Load(_Storage, _Section, _Article); } } /// <summary> /// Get the article datatype. For setting use Storage(), Section() & Article(). /// </summary> public article Article_Data { get { return articleSelected; } } }
// Structures.cs // // Copyright (c) 2013 Brent Knowles (http://www.brentknowles.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. // // Review documentation at http://www.yourothermind.com for updated implementation notes, license updates // or other general information/ // // Author information available at http://www.brentknowles.com or http://www.amazon.com/Brent-Knowles/e/B0035WW7OW // Full source code: https://github.com/BrentKnowles/YourOtherMind //### //#define USE_HASH_TABLE using System; using System.Collections; namespace DiffEngine { public interface IDiffList { int Count(); IComparable GetByIndex(int index); } internal enum DiffStatus { Matched = 1, NoMatch = -1, Unknown = -2 } internal class DiffState { private const int BAD_INDEX = -1; private int _startIndex; private int _length; public int StartIndex {get{return _startIndex;}} public int EndIndex {get{return ((_startIndex + _length) - 1);}} public int Length { get { int len; if (_length > 0) { len = _length; } else { if (_length == 0) { len = 1; } else { len = 0; } } return len; } } public DiffStatus Status { get { DiffStatus stat; if (_length > 0) { stat = DiffStatus.Matched; } else { switch (_length) { case -1: stat = DiffStatus.NoMatch; break; default: System.Diagnostics.Debug.Assert(_length == -2,"Invalid status: _length < -2"); stat = DiffStatus.Unknown; break; } } return stat; } } public DiffState() { SetToUnkown(); } protected void SetToUnkown() { _startIndex = BAD_INDEX; _length = (int)DiffStatus.Unknown; } public void SetMatch(int start, int length) { System.Diagnostics.Debug.Assert(length > 0,"Length must be greater than zero"); System.Diagnostics.Debug.Assert(start >= 0,"Start must be greater than or equal to zero"); _startIndex = start; _length = length; } public void SetNoMatch() { _startIndex = BAD_INDEX; _length = (int)DiffStatus.NoMatch; } public bool HasValidLength(int newStart, int newEnd, int maxPossibleDestLength) { if (_length > 0) //have unlocked match { if ((maxPossibleDestLength < _length)|| ((_startIndex < newStart)||(EndIndex > newEnd))) { SetToUnkown(); } } return (_length != (int)DiffStatus.Unknown); } } internal class DiffStateList { #if USE_HASH_TABLE private Hashtable _table; #else private DiffState[] _array; #endif public DiffStateList(int destCount) { #if USE_HASH_TABLE _table = new Hashtable(Math.Max(9,destCount/10)); #else _array = new DiffState[destCount]; #endif } public DiffState GetByIndex(int index) { #if USE_HASH_TABLE DiffState retval = (DiffState)_table[index]; if (retval == null) { retval = new DiffState(); _table.Add(index,retval); } #else DiffState retval = _array[index]; if (retval == null) { retval = new DiffState(); _array[index] = retval; } #endif return retval; } } public enum DiffResultSpanStatus { NoChange, Replace, DeleteSource, AddDestination } public class DiffResultSpan : IComparable { private const int BAD_INDEX = -1; private int _destIndex; private int _sourceIndex; private int _length; private DiffResultSpanStatus _status; public int DestIndex {get{return _destIndex;}} public int SourceIndex {get{return _sourceIndex;}} public int Length {get{return _length;}} public DiffResultSpanStatus Status {get{return _status;}} protected DiffResultSpan( DiffResultSpanStatus status, int destIndex, int sourceIndex, int length) { _status = status; _destIndex = destIndex; _sourceIndex = sourceIndex; _length = length; } public static DiffResultSpan CreateNoChange(int destIndex, int sourceIndex, int length) { return new DiffResultSpan(DiffResultSpanStatus.NoChange,destIndex,sourceIndex,length); } public static DiffResultSpan CreateReplace(int destIndex, int sourceIndex, int length) { return new DiffResultSpan(DiffResultSpanStatus.Replace,destIndex,sourceIndex,length); } public static DiffResultSpan CreateDeleteSource(int sourceIndex, int length) { return new DiffResultSpan(DiffResultSpanStatus.DeleteSource,BAD_INDEX,sourceIndex,length); } public static DiffResultSpan CreateAddDestination(int destIndex, int length) { return new DiffResultSpan(DiffResultSpanStatus.AddDestination,destIndex,BAD_INDEX,length); } public void AddLength(int i) { _length += i; } public override string ToString() { return string.Format("{0} (Dest: {1},Source: {2}) {3}", _status.ToString(), _destIndex.ToString(), _sourceIndex.ToString(), _length.ToString()); } #region IComparable Members public int CompareTo(object obj) { return _destIndex.CompareTo(((DiffResultSpan)obj)._destIndex); } #endregion } }
using System; using System.CodeDom.Compiler; using System.Collections.Generic; namespace EduHub.Data.Entities { /// <summary> /// Schools /// </summary> [GeneratedCode("EduHub Data", "0.9")] public sealed partial class SKGS : EduHubEntity { #region Foreign Navigation Properties private IReadOnlyList<DF_TFR> Cache_SCHOOL_DF_TFR_ORIG_SCHOOL; private IReadOnlyList<FDT_EXP> Cache_SCHOOL_FDT_EXP_DEST; private IReadOnlyList<FER_FDT> Cache_SCHOOL_FER_FDT_SOURCE; private IReadOnlyList<KCD_TFR> Cache_SCHOOL_KCD_TFR_ORIG_SCHOOL; private IReadOnlyList<KCM_TFR> Cache_SCHOOL_KCM_TFR_ORIG_SCHOOL; private IReadOnlyList<KGO_TFR> Cache_SCHOOL_KGO_TFR_ORIG_SCHOOL; private SCI Cache_SCHOOL_SCI_SCHOOL_LINK; private IReadOnlyList<SCI> Cache_SCHOOL_SCI_DESTINATION_SCHOOL; private IReadOnlyList<SKGS_OLD> Cache_SCHOOL_SKGS_OLD_NEW_SCHOOL; private IReadOnlyList<SMC_TFR> Cache_SCHOOL_SMC_TFR_ORIG_SCHOOL; private IReadOnlyList<ST> Cache_SCHOOL_ST_PREVIOUS_SCHOOL; private IReadOnlyList<ST> Cache_SCHOOL_ST_NEXT_SCHOOL; private IReadOnlyList<ST_TFR> Cache_SCHOOL_ST_TFR_ORIG_SCHOOL; private IReadOnlyList<ST_TFRIO> Cache_SCHOOL_ST_TFRIO_DEST_SCHOOL; private IReadOnlyList<STAR_TFR> Cache_SCHOOL_STAR_TFR_ORIG_SCHOOL; private IReadOnlyList<STNAT_TR> Cache_SCHOOL_STNAT_TR_ORIG_SCHOOL; private IReadOnlyList<STPS> Cache_SCHOOL_STPS_SCHOOL; private IReadOnlyList<STPS_TFR> Cache_SCHOOL_STPS_TFR_ORIG_SCHOOL; private IReadOnlyList<STPT> Cache_SCHOOL_STPT_SCHL_NUM; private IReadOnlyList<STRE> Cache_SCHOOL_STRE_ST_PREVIOUS_SCHOOL; private IReadOnlyList<STRE> Cache_SCHOOL_STRE_STPT_SCHL_NUM01; private IReadOnlyList<STRE> Cache_SCHOOL_STRE_STPT_SCHL_NUM02; private IReadOnlyList<STRE> Cache_SCHOOL_STRE_STPT_SCHL_NUM03; private IReadOnlyList<STRE> Cache_SCHOOL_STRE_STPT_SCHL_NUM04; private IReadOnlyList<STRE> Cache_SCHOOL_STRE_ST_NEXT_SCHOOL; private IReadOnlyList<STSUP_TR> Cache_SCHOOL_STSUP_TR_ORIG_SCHOOL; private IReadOnlyList<STVDI> Cache_SCHOOL_STVDI_ORIGINAL_SCHOOL; private IReadOnlyList<STVDI_TR> Cache_SCHOOL_STVDI_TR_ORIG_SCHOOL; private IReadOnlyList<STVDO> Cache_SCHOOL_STVDO_ORIGINAL_SCHOOL; private IReadOnlyList<STVDO_TR> Cache_SCHOOL_STVDO_TR_ORIG_SCHOOL; private IReadOnlyList<UM_TFR> Cache_SCHOOL_UM_TFR_ORIG_SCHOOL; #endregion /// <inheritdoc /> public override DateTime? EntityLastModified { get { return LW_DATE; } } #region Field Properties /// <summary> /// School ID /// [Uppercase Alphanumeric (8)] /// </summary> public string SCHOOL { get; internal set; } /// <summary> /// School Name /// [Alphanumeric (40)] /// </summary> public string NAME { get; internal set; } /// <summary> /// School type: Primary, Secondary, Special, etc /// [Alphanumeric (33)] /// </summary> public string SCHOOL_TYPE { get; internal set; } /// <summary> /// School type: Government, Private, etc /// [Uppercase Alphanumeric (2)] /// </summary> public string ENTITY { get; internal set; } /// <summary> /// DEET-defined school ID /// [Uppercase Alphanumeric (4)] /// </summary> public string SCHOOL_ID { get; internal set; } /// <summary> /// (Was SCHOOL_CAMPUS) Campus number /// [Uppercase Alphanumeric (2)] /// </summary> public string SCHOOL_NUMBER { get; internal set; } /// <summary> /// Campus type: Primary, etc /// [Alphanumeric (33)] /// </summary> public string CAMPUS_TYPE { get; internal set; } /// <summary> /// Campus name /// [Alphanumeric (40)] /// </summary> public string CAMPUS_NAME { get; internal set; } /// <summary> /// Region /// </summary> public short? REGION { get; internal set; } /// <summary> /// Name of Region /// [Alphanumeric (30)] /// </summary> public string REGION_NAME { get; internal set; } /// <summary> /// Two address lines /// [Alphanumeric (30)] /// </summary> public string ADDRESS01 { get; internal set; } /// <summary> /// Two address lines /// [Alphanumeric (30)] /// </summary> public string ADDRESS02 { get; internal set; } /// <summary> /// Suburb name /// [Alphanumeric (30)] /// </summary> public string SUBURB { get; internal set; } /// <summary> /// State code /// [Uppercase Alphanumeric (3)] /// </summary> public string STATE { get; internal set; } /// <summary> /// Postcode /// [Alphanumeric (4)] /// </summary> public string POSTCODE { get; internal set; } /// <summary> /// Phone no /// [Uppercase Alphanumeric (20)] /// </summary> public string TELEPHONE { get; internal set; } /// <summary> /// Fax no /// [Uppercase Alphanumeric (20)] /// </summary> public string FAX { get; internal set; } /// <summary> /// Two address lines /// [Alphanumeric (30)] /// </summary> public string MAILING_ADDRESS01 { get; internal set; } /// <summary> /// Two address lines /// [Alphanumeric (30)] /// </summary> public string MAILING_ADDRESS02 { get; internal set; } /// <summary> /// Suburb name for Mailing /// [Alphanumeric (30)] /// </summary> public string MAILING_SUBURB { get; internal set; } /// <summary> /// State code for Mailing /// [Uppercase Alphanumeric (3)] /// </summary> public string MAILING_STATE { get; internal set; } /// <summary> /// Postcode for Mailing /// [Alphanumeric (4)] /// </summary> public string MAILING_POSTCODE { get; internal set; } /// <summary> /// Two address lines for Delivery /// [Alphanumeric (30)] /// </summary> public string DELIVERY_ADDRESS01 { get; internal set; } /// <summary> /// Two address lines for Delivery /// [Alphanumeric (30)] /// </summary> public string DELIVERY_ADDRESS02 { get; internal set; } /// <summary> /// Suburb name for Delivery /// [Alphanumeric (30)] /// </summary> public string DELIVERY_SUBURB { get; internal set; } /// <summary> /// State code for Delivery /// [Uppercase Alphanumeric (3)] /// </summary> public string DELIVERY_STATE { get; internal set; } /// <summary> /// Postcode for Delivery /// [Alphanumeric (4)] /// </summary> public string DELIVERY_POSTCODE { get; internal set; } /// <summary> /// Phone no. for Delivery /// [Uppercase Alphanumeric (20)] /// </summary> public string DELIVERY_TELEPHONE { get; internal set; } /// <summary> /// Fax no for Delivery /// [Uppercase Alphanumeric (20)] /// </summary> public string DELIVERY_FAX { get; internal set; } /// <summary> /// (Was E_MAIL_ADDRESS) E-mail address /// [Alphanumeric (255)] /// </summary> public string E_MAIL { get; internal set; } /// <summary> /// Internet address /// [Alphanumeric (255)] /// </summary> public string INTERNET_ADDRESS { get; internal set; } /// <summary> /// CASES 21 release no /// [Uppercase Alphanumeric (12)] /// </summary> public string CASES21_RELEASE { get; internal set; } /// <summary> /// Melway, VicRoads, Country Fire Authority, etc /// [Uppercase Alphanumeric (1)] /// </summary> public string MAP_TYPE { get; internal set; } /// <summary> /// Map no /// [Uppercase Alphanumeric (4)] /// </summary> public string MAP_NUM { get; internal set; } /// <summary> /// Horizontal grid reference /// [Uppercase Alphanumeric (2)] /// </summary> public string X_AXIS { get; internal set; } /// <summary> /// Vertical grid reference /// [Uppercase Alphanumeric (2)] /// </summary> public string Y_AXIS { get; internal set; } /// <summary> /// School Principal's Title: Mr, Mrs, etc /// [Titlecase (4)] /// </summary> public string SCH_PRINCIPAL_SALUTATION { get; internal set; } /// <summary> /// School Principal's First Name /// [Titlecase (20)] /// </summary> public string SCH_PRINCIPAL_FIRST_NAME { get; internal set; } /// <summary> /// School Principal's Surname /// [Uppercase Alphanumeric (30)] /// </summary> public string SCH_PRINCIPAL_SURNAME { get; internal set; } /// <summary> /// School Principal's Phone no /// [Uppercase Alphanumeric (20)] /// </summary> public string SCH_PRINCIPAL_TELEPHONE { get; internal set; } /// <summary> /// Campus Principal's title: Mr, Mrs, etc /// [Titlecase (4)] /// </summary> public string SALUTATION { get; internal set; } /// <summary> /// Campus Principal's surname /// [Uppercase Alphanumeric (30)] /// </summary> public string SURNAME { get; internal set; } /// <summary> /// Campus Principal's first given name /// [Titlecase (20)] /// </summary> public string FIRST_NAME { get; internal set; } /// <summary> /// School closed? (Y/N) /// [Uppercase Alphanumeric (1)] /// </summary> public string CLOSED { get; internal set; } /// <summary> /// Concurrent enrolment Y/N /// [Uppercase Alphanumeric (1)] /// </summary> public string CONCURRENT_ENROL { get; internal set; } /// <summary> /// Last write date /// </summary> public DateTime? LW_DATE { get; internal set; } /// <summary> /// Last write time /// </summary> public short? LW_TIME { get; internal set; } /// <summary> /// Last write operator /// [Uppercase Alphanumeric (128)] /// </summary> public string LW_USER { get; internal set; } #endregion #region Foreign Navigation Properties /// <summary> /// DF_TFR (DF Transfer) related entities by [SKGS.SCHOOL]-&gt;[DF_TFR.ORIG_SCHOOL] /// School ID /// </summary> public IReadOnlyList<DF_TFR> SCHOOL_DF_TFR_ORIG_SCHOOL { get { if (Cache_SCHOOL_DF_TFR_ORIG_SCHOOL == null && !Context.DF_TFR.TryFindByORIG_SCHOOL(SCHOOL, out Cache_SCHOOL_DF_TFR_ORIG_SCHOOL)) { Cache_SCHOOL_DF_TFR_ORIG_SCHOOL = new List<DF_TFR>().AsReadOnly(); } return Cache_SCHOOL_DF_TFR_ORIG_SCHOOL; } } /// <summary> /// FDT_EXP (Financial Data Export) related entities by [SKGS.SCHOOL]-&gt;[FDT_EXP.DEST] /// School ID /// </summary> public IReadOnlyList<FDT_EXP> SCHOOL_FDT_EXP_DEST { get { if (Cache_SCHOOL_FDT_EXP_DEST == null && !Context.FDT_EXP.TryFindByDEST(SCHOOL, out Cache_SCHOOL_FDT_EXP_DEST)) { Cache_SCHOOL_FDT_EXP_DEST = new List<FDT_EXP>().AsReadOnly(); } return Cache_SCHOOL_FDT_EXP_DEST; } } /// <summary> /// FER_FDT (FDT Financal Holding Table) related entities by [SKGS.SCHOOL]-&gt;[FER_FDT.SOURCE] /// School ID /// </summary> public IReadOnlyList<FER_FDT> SCHOOL_FER_FDT_SOURCE { get { if (Cache_SCHOOL_FER_FDT_SOURCE == null && !Context.FER_FDT.TryFindBySOURCE(SCHOOL, out Cache_SCHOOL_FER_FDT_SOURCE)) { Cache_SCHOOL_FER_FDT_SOURCE = new List<FER_FDT>().AsReadOnly(); } return Cache_SCHOOL_FER_FDT_SOURCE; } } /// <summary> /// KCD_TFR (KCD Transfer) related entities by [SKGS.SCHOOL]-&gt;[KCD_TFR.ORIG_SCHOOL] /// School ID /// </summary> public IReadOnlyList<KCD_TFR> SCHOOL_KCD_TFR_ORIG_SCHOOL { get { if (Cache_SCHOOL_KCD_TFR_ORIG_SCHOOL == null && !Context.KCD_TFR.TryFindByORIG_SCHOOL(SCHOOL, out Cache_SCHOOL_KCD_TFR_ORIG_SCHOOL)) { Cache_SCHOOL_KCD_TFR_ORIG_SCHOOL = new List<KCD_TFR>().AsReadOnly(); } return Cache_SCHOOL_KCD_TFR_ORIG_SCHOOL; } } /// <summary> /// KCM_TFR (KCM Transfer) related entities by [SKGS.SCHOOL]-&gt;[KCM_TFR.ORIG_SCHOOL] /// School ID /// </summary> public IReadOnlyList<KCM_TFR> SCHOOL_KCM_TFR_ORIG_SCHOOL { get { if (Cache_SCHOOL_KCM_TFR_ORIG_SCHOOL == null && !Context.KCM_TFR.TryFindByORIG_SCHOOL(SCHOOL, out Cache_SCHOOL_KCM_TFR_ORIG_SCHOOL)) { Cache_SCHOOL_KCM_TFR_ORIG_SCHOOL = new List<KCM_TFR>().AsReadOnly(); } return Cache_SCHOOL_KCM_TFR_ORIG_SCHOOL; } } /// <summary> /// KGO_TFR (KGO Transfer) related entities by [SKGS.SCHOOL]-&gt;[KGO_TFR.ORIG_SCHOOL] /// School ID /// </summary> public IReadOnlyList<KGO_TFR> SCHOOL_KGO_TFR_ORIG_SCHOOL { get { if (Cache_SCHOOL_KGO_TFR_ORIG_SCHOOL == null && !Context.KGO_TFR.TryFindByORIG_SCHOOL(SCHOOL, out Cache_SCHOOL_KGO_TFR_ORIG_SCHOOL)) { Cache_SCHOOL_KGO_TFR_ORIG_SCHOOL = new List<KGO_TFR>().AsReadOnly(); } return Cache_SCHOOL_KGO_TFR_ORIG_SCHOOL; } } /// <summary> /// SCI (School Information) related entity by [SKGS.SCHOOL]-&gt;[SCI.SCHOOL_LINK] /// School ID /// </summary> public SCI SCHOOL_SCI_SCHOOL_LINK { get { if (Cache_SCHOOL_SCI_SCHOOL_LINK == null && !Context.SCI.TryFindBySCHOOL_LINK(SCHOOL, out Cache_SCHOOL_SCI_SCHOOL_LINK)) { Cache_SCHOOL_SCI_SCHOOL_LINK = null; } return Cache_SCHOOL_SCI_SCHOOL_LINK; } } /// <summary> /// SCI (School Information) related entities by [SKGS.SCHOOL]-&gt;[SCI.DESTINATION_SCHOOL] /// School ID /// </summary> public IReadOnlyList<SCI> SCHOOL_SCI_DESTINATION_SCHOOL { get { if (Cache_SCHOOL_SCI_DESTINATION_SCHOOL == null && !Context.SCI.TryFindByDESTINATION_SCHOOL(SCHOOL, out Cache_SCHOOL_SCI_DESTINATION_SCHOOL)) { Cache_SCHOOL_SCI_DESTINATION_SCHOOL = new List<SCI>().AsReadOnly(); } return Cache_SCHOOL_SCI_DESTINATION_SCHOOL; } } /// <summary> /// SKGS_OLD (Old SKGS Schools) related entities by [SKGS.SCHOOL]-&gt;[SKGS_OLD.NEW_SCHOOL] /// School ID /// </summary> public IReadOnlyList<SKGS_OLD> SCHOOL_SKGS_OLD_NEW_SCHOOL { get { if (Cache_SCHOOL_SKGS_OLD_NEW_SCHOOL == null && !Context.SKGS_OLD.TryFindByNEW_SCHOOL(SCHOOL, out Cache_SCHOOL_SKGS_OLD_NEW_SCHOOL)) { Cache_SCHOOL_SKGS_OLD_NEW_SCHOOL = new List<SKGS_OLD>().AsReadOnly(); } return Cache_SCHOOL_SKGS_OLD_NEW_SCHOOL; } } /// <summary> /// SMC_TFR (SMC Transfer) related entities by [SKGS.SCHOOL]-&gt;[SMC_TFR.ORIG_SCHOOL] /// School ID /// </summary> public IReadOnlyList<SMC_TFR> SCHOOL_SMC_TFR_ORIG_SCHOOL { get { if (Cache_SCHOOL_SMC_TFR_ORIG_SCHOOL == null && !Context.SMC_TFR.TryFindByORIG_SCHOOL(SCHOOL, out Cache_SCHOOL_SMC_TFR_ORIG_SCHOOL)) { Cache_SCHOOL_SMC_TFR_ORIG_SCHOOL = new List<SMC_TFR>().AsReadOnly(); } return Cache_SCHOOL_SMC_TFR_ORIG_SCHOOL; } } /// <summary> /// ST (Students) related entities by [SKGS.SCHOOL]-&gt;[ST.PREVIOUS_SCHOOL] /// School ID /// </summary> public IReadOnlyList<ST> SCHOOL_ST_PREVIOUS_SCHOOL { get { if (Cache_SCHOOL_ST_PREVIOUS_SCHOOL == null && !Context.ST.TryFindByPREVIOUS_SCHOOL(SCHOOL, out Cache_SCHOOL_ST_PREVIOUS_SCHOOL)) { Cache_SCHOOL_ST_PREVIOUS_SCHOOL = new List<ST>().AsReadOnly(); } return Cache_SCHOOL_ST_PREVIOUS_SCHOOL; } } /// <summary> /// ST (Students) related entities by [SKGS.SCHOOL]-&gt;[ST.NEXT_SCHOOL] /// School ID /// </summary> public IReadOnlyList<ST> SCHOOL_ST_NEXT_SCHOOL { get { if (Cache_SCHOOL_ST_NEXT_SCHOOL == null && !Context.ST.TryFindByNEXT_SCHOOL(SCHOOL, out Cache_SCHOOL_ST_NEXT_SCHOOL)) { Cache_SCHOOL_ST_NEXT_SCHOOL = new List<ST>().AsReadOnly(); } return Cache_SCHOOL_ST_NEXT_SCHOOL; } } /// <summary> /// ST_TFR (ST Transfer) related entities by [SKGS.SCHOOL]-&gt;[ST_TFR.ORIG_SCHOOL] /// School ID /// </summary> public IReadOnlyList<ST_TFR> SCHOOL_ST_TFR_ORIG_SCHOOL { get { if (Cache_SCHOOL_ST_TFR_ORIG_SCHOOL == null && !Context.ST_TFR.TryFindByORIG_SCHOOL(SCHOOL, out Cache_SCHOOL_ST_TFR_ORIG_SCHOOL)) { Cache_SCHOOL_ST_TFR_ORIG_SCHOOL = new List<ST_TFR>().AsReadOnly(); } return Cache_SCHOOL_ST_TFR_ORIG_SCHOOL; } } /// <summary> /// ST_TFRIO (Student Data Transfer Table) related entities by [SKGS.SCHOOL]-&gt;[ST_TFRIO.DEST_SCHOOL] /// School ID /// </summary> public IReadOnlyList<ST_TFRIO> SCHOOL_ST_TFRIO_DEST_SCHOOL { get { if (Cache_SCHOOL_ST_TFRIO_DEST_SCHOOL == null && !Context.ST_TFRIO.TryFindByDEST_SCHOOL(SCHOOL, out Cache_SCHOOL_ST_TFRIO_DEST_SCHOOL)) { Cache_SCHOOL_ST_TFRIO_DEST_SCHOOL = new List<ST_TFRIO>().AsReadOnly(); } return Cache_SCHOOL_ST_TFRIO_DEST_SCHOOL; } } /// <summary> /// STAR_TFR (STAR Transfer) related entities by [SKGS.SCHOOL]-&gt;[STAR_TFR.ORIG_SCHOOL] /// School ID /// </summary> public IReadOnlyList<STAR_TFR> SCHOOL_STAR_TFR_ORIG_SCHOOL { get { if (Cache_SCHOOL_STAR_TFR_ORIG_SCHOOL == null && !Context.STAR_TFR.TryFindByORIG_SCHOOL(SCHOOL, out Cache_SCHOOL_STAR_TFR_ORIG_SCHOOL)) { Cache_SCHOOL_STAR_TFR_ORIG_SCHOOL = new List<STAR_TFR>().AsReadOnly(); } return Cache_SCHOOL_STAR_TFR_ORIG_SCHOOL; } } /// <summary> /// STNAT_TR (STNAT Transfer) related entities by [SKGS.SCHOOL]-&gt;[STNAT_TR.ORIG_SCHOOL] /// School ID /// </summary> public IReadOnlyList<STNAT_TR> SCHOOL_STNAT_TR_ORIG_SCHOOL { get { if (Cache_SCHOOL_STNAT_TR_ORIG_SCHOOL == null && !Context.STNAT_TR.TryFindByORIG_SCHOOL(SCHOOL, out Cache_SCHOOL_STNAT_TR_ORIG_SCHOOL)) { Cache_SCHOOL_STNAT_TR_ORIG_SCHOOL = new List<STNAT_TR>().AsReadOnly(); } return Cache_SCHOOL_STNAT_TR_ORIG_SCHOOL; } } /// <summary> /// STPS (Student Previous School) related entities by [SKGS.SCHOOL]-&gt;[STPS.SCHOOL] /// School ID /// </summary> public IReadOnlyList<STPS> SCHOOL_STPS_SCHOOL { get { if (Cache_SCHOOL_STPS_SCHOOL == null && !Context.STPS.TryFindBySCHOOL(SCHOOL, out Cache_SCHOOL_STPS_SCHOOL)) { Cache_SCHOOL_STPS_SCHOOL = new List<STPS>().AsReadOnly(); } return Cache_SCHOOL_STPS_SCHOOL; } } /// <summary> /// STPS_TFR (STPS Transfer) related entities by [SKGS.SCHOOL]-&gt;[STPS_TFR.ORIG_SCHOOL] /// School ID /// </summary> public IReadOnlyList<STPS_TFR> SCHOOL_STPS_TFR_ORIG_SCHOOL { get { if (Cache_SCHOOL_STPS_TFR_ORIG_SCHOOL == null && !Context.STPS_TFR.TryFindByORIG_SCHOOL(SCHOOL, out Cache_SCHOOL_STPS_TFR_ORIG_SCHOOL)) { Cache_SCHOOL_STPS_TFR_ORIG_SCHOOL = new List<STPS_TFR>().AsReadOnly(); } return Cache_SCHOOL_STPS_TFR_ORIG_SCHOOL; } } /// <summary> /// STPT (Student Part-Time Enrolments) related entities by [SKGS.SCHOOL]-&gt;[STPT.SCHL_NUM] /// School ID /// </summary> public IReadOnlyList<STPT> SCHOOL_STPT_SCHL_NUM { get { if (Cache_SCHOOL_STPT_SCHL_NUM == null && !Context.STPT.TryFindBySCHL_NUM(SCHOOL, out Cache_SCHOOL_STPT_SCHL_NUM)) { Cache_SCHOOL_STPT_SCHL_NUM = new List<STPT>().AsReadOnly(); } return Cache_SCHOOL_STPT_SCHL_NUM; } } /// <summary> /// STRE (Student Re-Enrolment) related entities by [SKGS.SCHOOL]-&gt;[STRE.ST_PREVIOUS_SCHOOL] /// School ID /// </summary> public IReadOnlyList<STRE> SCHOOL_STRE_ST_PREVIOUS_SCHOOL { get { if (Cache_SCHOOL_STRE_ST_PREVIOUS_SCHOOL == null && !Context.STRE.TryFindByST_PREVIOUS_SCHOOL(SCHOOL, out Cache_SCHOOL_STRE_ST_PREVIOUS_SCHOOL)) { Cache_SCHOOL_STRE_ST_PREVIOUS_SCHOOL = new List<STRE>().AsReadOnly(); } return Cache_SCHOOL_STRE_ST_PREVIOUS_SCHOOL; } } /// <summary> /// STRE (Student Re-Enrolment) related entities by [SKGS.SCHOOL]-&gt;[STRE.STPT_SCHL_NUM01] /// School ID /// </summary> public IReadOnlyList<STRE> SCHOOL_STRE_STPT_SCHL_NUM01 { get { if (Cache_SCHOOL_STRE_STPT_SCHL_NUM01 == null && !Context.STRE.TryFindBySTPT_SCHL_NUM01(SCHOOL, out Cache_SCHOOL_STRE_STPT_SCHL_NUM01)) { Cache_SCHOOL_STRE_STPT_SCHL_NUM01 = new List<STRE>().AsReadOnly(); } return Cache_SCHOOL_STRE_STPT_SCHL_NUM01; } } /// <summary> /// STRE (Student Re-Enrolment) related entities by [SKGS.SCHOOL]-&gt;[STRE.STPT_SCHL_NUM02] /// School ID /// </summary> public IReadOnlyList<STRE> SCHOOL_STRE_STPT_SCHL_NUM02 { get { if (Cache_SCHOOL_STRE_STPT_SCHL_NUM02 == null && !Context.STRE.TryFindBySTPT_SCHL_NUM02(SCHOOL, out Cache_SCHOOL_STRE_STPT_SCHL_NUM02)) { Cache_SCHOOL_STRE_STPT_SCHL_NUM02 = new List<STRE>().AsReadOnly(); } return Cache_SCHOOL_STRE_STPT_SCHL_NUM02; } } /// <summary> /// STRE (Student Re-Enrolment) related entities by [SKGS.SCHOOL]-&gt;[STRE.STPT_SCHL_NUM03] /// School ID /// </summary> public IReadOnlyList<STRE> SCHOOL_STRE_STPT_SCHL_NUM03 { get { if (Cache_SCHOOL_STRE_STPT_SCHL_NUM03 == null && !Context.STRE.TryFindBySTPT_SCHL_NUM03(SCHOOL, out Cache_SCHOOL_STRE_STPT_SCHL_NUM03)) { Cache_SCHOOL_STRE_STPT_SCHL_NUM03 = new List<STRE>().AsReadOnly(); } return Cache_SCHOOL_STRE_STPT_SCHL_NUM03; } } /// <summary> /// STRE (Student Re-Enrolment) related entities by [SKGS.SCHOOL]-&gt;[STRE.STPT_SCHL_NUM04] /// School ID /// </summary> public IReadOnlyList<STRE> SCHOOL_STRE_STPT_SCHL_NUM04 { get { if (Cache_SCHOOL_STRE_STPT_SCHL_NUM04 == null && !Context.STRE.TryFindBySTPT_SCHL_NUM04(SCHOOL, out Cache_SCHOOL_STRE_STPT_SCHL_NUM04)) { Cache_SCHOOL_STRE_STPT_SCHL_NUM04 = new List<STRE>().AsReadOnly(); } return Cache_SCHOOL_STRE_STPT_SCHL_NUM04; } } /// <summary> /// STRE (Student Re-Enrolment) related entities by [SKGS.SCHOOL]-&gt;[STRE.ST_NEXT_SCHOOL] /// School ID /// </summary> public IReadOnlyList<STRE> SCHOOL_STRE_ST_NEXT_SCHOOL { get { if (Cache_SCHOOL_STRE_ST_NEXT_SCHOOL == null && !Context.STRE.TryFindByST_NEXT_SCHOOL(SCHOOL, out Cache_SCHOOL_STRE_ST_NEXT_SCHOOL)) { Cache_SCHOOL_STRE_ST_NEXT_SCHOOL = new List<STRE>().AsReadOnly(); } return Cache_SCHOOL_STRE_ST_NEXT_SCHOOL; } } /// <summary> /// STSUP_TR (STSUP Transfer) related entities by [SKGS.SCHOOL]-&gt;[STSUP_TR.ORIG_SCHOOL] /// School ID /// </summary> public IReadOnlyList<STSUP_TR> SCHOOL_STSUP_TR_ORIG_SCHOOL { get { if (Cache_SCHOOL_STSUP_TR_ORIG_SCHOOL == null && !Context.STSUP_TR.TryFindByORIG_SCHOOL(SCHOOL, out Cache_SCHOOL_STSUP_TR_ORIG_SCHOOL)) { Cache_SCHOOL_STSUP_TR_ORIG_SCHOOL = new List<STSUP_TR>().AsReadOnly(); } return Cache_SCHOOL_STSUP_TR_ORIG_SCHOOL; } } /// <summary> /// STVDI (VELS Dimension Results) related entities by [SKGS.SCHOOL]-&gt;[STVDI.ORIGINAL_SCHOOL] /// School ID /// </summary> public IReadOnlyList<STVDI> SCHOOL_STVDI_ORIGINAL_SCHOOL { get { if (Cache_SCHOOL_STVDI_ORIGINAL_SCHOOL == null && !Context.STVDI.TryFindByORIGINAL_SCHOOL(SCHOOL, out Cache_SCHOOL_STVDI_ORIGINAL_SCHOOL)) { Cache_SCHOOL_STVDI_ORIGINAL_SCHOOL = new List<STVDI>().AsReadOnly(); } return Cache_SCHOOL_STVDI_ORIGINAL_SCHOOL; } } /// <summary> /// STVDI_TR (STVDI Transfer) related entities by [SKGS.SCHOOL]-&gt;[STVDI_TR.ORIG_SCHOOL] /// School ID /// </summary> public IReadOnlyList<STVDI_TR> SCHOOL_STVDI_TR_ORIG_SCHOOL { get { if (Cache_SCHOOL_STVDI_TR_ORIG_SCHOOL == null && !Context.STVDI_TR.TryFindByORIG_SCHOOL(SCHOOL, out Cache_SCHOOL_STVDI_TR_ORIG_SCHOOL)) { Cache_SCHOOL_STVDI_TR_ORIG_SCHOOL = new List<STVDI_TR>().AsReadOnly(); } return Cache_SCHOOL_STVDI_TR_ORIG_SCHOOL; } } /// <summary> /// STVDO (VELS Domain Results) related entities by [SKGS.SCHOOL]-&gt;[STVDO.ORIGINAL_SCHOOL] /// School ID /// </summary> public IReadOnlyList<STVDO> SCHOOL_STVDO_ORIGINAL_SCHOOL { get { if (Cache_SCHOOL_STVDO_ORIGINAL_SCHOOL == null && !Context.STVDO.TryFindByORIGINAL_SCHOOL(SCHOOL, out Cache_SCHOOL_STVDO_ORIGINAL_SCHOOL)) { Cache_SCHOOL_STVDO_ORIGINAL_SCHOOL = new List<STVDO>().AsReadOnly(); } return Cache_SCHOOL_STVDO_ORIGINAL_SCHOOL; } } /// <summary> /// STVDO_TR (STVDO Transfer) related entities by [SKGS.SCHOOL]-&gt;[STVDO_TR.ORIG_SCHOOL] /// School ID /// </summary> public IReadOnlyList<STVDO_TR> SCHOOL_STVDO_TR_ORIG_SCHOOL { get { if (Cache_SCHOOL_STVDO_TR_ORIG_SCHOOL == null && !Context.STVDO_TR.TryFindByORIG_SCHOOL(SCHOOL, out Cache_SCHOOL_STVDO_TR_ORIG_SCHOOL)) { Cache_SCHOOL_STVDO_TR_ORIG_SCHOOL = new List<STVDO_TR>().AsReadOnly(); } return Cache_SCHOOL_STVDO_TR_ORIG_SCHOOL; } } /// <summary> /// UM_TFR (UM Transfer) related entities by [SKGS.SCHOOL]-&gt;[UM_TFR.ORIG_SCHOOL] /// School ID /// </summary> public IReadOnlyList<UM_TFR> SCHOOL_UM_TFR_ORIG_SCHOOL { get { if (Cache_SCHOOL_UM_TFR_ORIG_SCHOOL == null && !Context.UM_TFR.TryFindByORIG_SCHOOL(SCHOOL, out Cache_SCHOOL_UM_TFR_ORIG_SCHOOL)) { Cache_SCHOOL_UM_TFR_ORIG_SCHOOL = new List<UM_TFR>().AsReadOnly(); } return Cache_SCHOOL_UM_TFR_ORIG_SCHOOL; } } #endregion } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using JugueteriaEntity.Areas.HelpPage.ModelDescriptions; using JugueteriaEntity.Areas.HelpPage.Models; namespace JugueteriaEntity.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
// 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; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Security; using System.Security.AccessControl; using System.Security.Permissions; using System.Text; namespace Microsoft.Win32 { /// <summary>Registry encapsulation. To get an instance of a RegistryKey use the Registry class's static members then call OpenSubKey.</summary> #if REGISTRY_ASSEMBLY public #else internal #endif sealed partial class RegistryKey : MarshalByRefObject, IDisposable { private static readonly IntPtr HKEY_CLASSES_ROOT = new IntPtr(unchecked((int)0x80000000)); private static readonly IntPtr HKEY_CURRENT_USER = new IntPtr(unchecked((int)0x80000001)); private static readonly IntPtr HKEY_LOCAL_MACHINE = new IntPtr(unchecked((int)0x80000002)); private static readonly IntPtr HKEY_USERS = new IntPtr(unchecked((int)0x80000003)); private static readonly IntPtr HKEY_PERFORMANCE_DATA = new IntPtr(unchecked((int)0x80000004)); private static readonly IntPtr HKEY_CURRENT_CONFIG = new IntPtr(unchecked((int)0x80000005)); /// <summary>Names of keys. This array must be in the same order as the HKEY values listed above.</summary> private static readonly string[] s_hkeyNames = new string[] { "HKEY_CLASSES_ROOT", "HKEY_CURRENT_USER", "HKEY_LOCAL_MACHINE", "HKEY_USERS", "HKEY_PERFORMANCE_DATA", "HKEY_CURRENT_CONFIG" }; // MSDN defines the following limits for registry key names & values: // Key Name: 255 characters // Value name: 16,383 Unicode characters // Value: either 1 MB or current available memory, depending on registry format. private const int MaxKeyLength = 255; private const int MaxValueLength = 16383; private volatile SafeRegistryHandle _hkey; private volatile string _keyName; private volatile bool _remoteKey; private volatile StateFlags _state; private volatile RegistryKeyPermissionCheck _checkMode; private volatile RegistryView _regView = RegistryView.Default; /// <summary> /// Creates a RegistryKey. This key is bound to hkey, if writable is <b>false</b> then no write operations will be allowed. /// </summary> private RegistryKey(SafeRegistryHandle hkey, bool writable, RegistryView view) : this(hkey, writable, false, false, false, view) { } /// <summary> /// Creates a RegistryKey. /// This key is bound to hkey, if writable is <b>false</b> then no write operations /// will be allowed. If systemkey is set then the hkey won't be released /// when the object is GC'ed. /// The remoteKey flag when set to true indicates that we are dealing with registry entries /// on a remote machine and requires the program making these calls to have full trust. /// </summary> private RegistryKey(SafeRegistryHandle hkey, bool writable, bool systemkey, bool remoteKey, bool isPerfData, RegistryView view) { ValidateKeyView(view); _hkey = hkey; _keyName = ""; _remoteKey = remoteKey; _regView = view; if (systemkey) { _state |= StateFlags.SystemKey; } if (writable) { _state |= StateFlags.WriteAccess; } if (isPerfData) { _state |= StateFlags.PerfData; } } public void Flush() { FlushCore(); } public void Close() { Dispose(); } public void Dispose() { if (_hkey != null) { if (!IsSystemKey()) { try { _hkey.Dispose(); } catch (IOException) { // we don't really care if the handle is invalid at this point } finally { _hkey = null; } } else if (IsPerfDataKey()) { ClosePerfDataKey(); } } } /// <summary>Creates a new subkey, or opens an existing one.</summary> /// <param name="subkey">Name or path to subkey to create or open.</param> /// <returns>The subkey, or <b>null</b> if the operation failed.</returns> [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "Reviewed for thread safety")] public RegistryKey CreateSubKey(string subkey) { return CreateSubKey(subkey, _checkMode); } public RegistryKey CreateSubKey(string subkey, bool writable) { return CreateSubKeyInternal(subkey, writable ? RegistryKeyPermissionCheck.ReadWriteSubTree : RegistryKeyPermissionCheck.ReadSubTree, null, RegistryOptions.None); } public RegistryKey CreateSubKey(string subkey, bool writable, RegistryOptions options) { return CreateSubKeyInternal(subkey, writable ? RegistryKeyPermissionCheck.ReadWriteSubTree : RegistryKeyPermissionCheck.ReadSubTree, null, options); } public RegistryKey CreateSubKey(string subkey, RegistryKeyPermissionCheck permissionCheck) { return CreateSubKeyInternal(subkey, permissionCheck, null, RegistryOptions.None); } public RegistryKey CreateSubKey(string subkey, RegistryKeyPermissionCheck permissionCheck, RegistryOptions registryOptions) { return CreateSubKeyInternal(subkey, permissionCheck, null, registryOptions); } public RegistryKey CreateSubKey(string subkey, RegistryKeyPermissionCheck permissionCheck, RegistryOptions registryOptions, RegistrySecurity registrySecurity) { return CreateSubKeyInternal(subkey, permissionCheck, registrySecurity, registryOptions); } public RegistryKey CreateSubKey(string subkey, RegistryKeyPermissionCheck permissionCheck, RegistrySecurity registrySecurity) { return CreateSubKeyInternal(subkey, permissionCheck, registrySecurity, RegistryOptions.None); } private RegistryKey CreateSubKeyInternal(string subkey, RegistryKeyPermissionCheck permissionCheck, object registrySecurityObj, RegistryOptions registryOptions) { ValidateKeyOptions(registryOptions); ValidateKeyName(subkey); ValidateKeyMode(permissionCheck); EnsureWriteable(); subkey = FixupName(subkey); // Fixup multiple slashes to a single slash // only keys opened under read mode is not writable if (!_remoteKey) { RegistryKey key = InternalOpenSubKeyWithoutSecurityChecks(subkey, (permissionCheck != RegistryKeyPermissionCheck.ReadSubTree)); if (key != null) { // Key already exits key._checkMode = permissionCheck; return key; } } return CreateSubKeyInternalCore(subkey, permissionCheck, registrySecurityObj, registryOptions); } /// <summary> /// Deletes the specified subkey. Will throw an exception if the subkey has /// subkeys. To delete a tree of subkeys use, DeleteSubKeyTree. /// </summary> /// <param name="subkey">SubKey to delete.</param> /// <exception cref="InvalidOperationException">Thrown if the subkey has child subkeys.</exception> public void DeleteSubKey(string subkey) { DeleteSubKey(subkey, true); } public void DeleteSubKey(string subkey, bool throwOnMissingSubKey) { ValidateKeyName(subkey); EnsureWriteable(); subkey = FixupName(subkey); // Fixup multiple slashes to a single slash // Open the key we are deleting and check for children. Be sure to // explicitly call close to avoid keeping an extra HKEY open. // RegistryKey key = InternalOpenSubKeyWithoutSecurityChecks(subkey, false); if (key != null) { using (key) { if (key.InternalSubKeyCount() > 0) { ThrowHelper.ThrowInvalidOperationException(SR.InvalidOperation_RegRemoveSubKey); } } DeleteSubKeyCore(subkey, throwOnMissingSubKey); } else // there is no key which also means there is no subkey { if (throwOnMissingSubKey) { ThrowHelper.ThrowArgumentException(SR.Arg_RegSubKeyAbsent); } } } /// <summary>Recursively deletes a subkey and any child subkeys.</summary> /// <param name="subkey">SubKey to delete.</param> public void DeleteSubKeyTree(string subkey) { DeleteSubKeyTree(subkey, throwOnMissingSubKey: true); } public void DeleteSubKeyTree(string subkey, bool throwOnMissingSubKey) { ValidateKeyName(subkey); // Security concern: Deleting a hive's "" subkey would delete all // of that hive's contents. Don't allow "". if (subkey.Length == 0 && IsSystemKey()) { ThrowHelper.ThrowArgumentException(SR.Arg_RegKeyDelHive); } EnsureWriteable(); subkey = FixupName(subkey); // Fixup multiple slashes to a single slash RegistryKey key = InternalOpenSubKeyWithoutSecurityChecks(subkey, true); if (key != null) { using (key) { if (key.InternalSubKeyCount() > 0) { string[] keys = key.InternalGetSubKeyNames(); for (int i = 0; i < keys.Length; i++) { key.DeleteSubKeyTreeInternal(keys[i]); } } } DeleteSubKeyTreeCore(subkey); } else if (throwOnMissingSubKey) { ThrowHelper.ThrowArgumentException(SR.Arg_RegSubKeyAbsent); } } /// <summary> /// An internal version which does no security checks or argument checking. Skipping the /// security checks should give us a slight perf gain on large trees. /// </summary> private void DeleteSubKeyTreeInternal(string subkey) { RegistryKey key = InternalOpenSubKeyWithoutSecurityChecks(subkey, true); if (key != null) { using (key) { if (key.InternalSubKeyCount() > 0) { string[] keys = key.InternalGetSubKeyNames(); for (int i = 0; i < keys.Length; i++) { key.DeleteSubKeyTreeInternal(keys[i]); } } } DeleteSubKeyTreeCore(subkey); } else { ThrowHelper.ThrowArgumentException(SR.Arg_RegSubKeyAbsent); } } /// <summary>Deletes the specified value from this key.</summary> /// <param name="name">Name of value to delete.</param> public void DeleteValue(string name) { DeleteValue(name, true); } public void DeleteValue(string name, bool throwOnMissingValue) { EnsureWriteable(); DeleteValueCore(name, throwOnMissingValue); } public static RegistryKey OpenBaseKey(RegistryHive hKey, RegistryView view) { ValidateKeyView(view); return OpenBaseKeyCore(hKey, view); } /// <summary>Retrieves a new RegistryKey that represents the requested key on a foreign machine.</summary> /// <param name="hKey">hKey HKEY_* to open.</param> /// <param name="machineName">Name the machine to connect to.</param> /// <returns>The RegistryKey requested.</returns> public static RegistryKey OpenRemoteBaseKey(RegistryHive hKey, string machineName) { return OpenRemoteBaseKey(hKey, machineName, RegistryView.Default); } public static RegistryKey OpenRemoteBaseKey(RegistryHive hKey, string machineName, RegistryView view) { if (machineName == null) { throw new ArgumentNullException(nameof(machineName)); } ValidateKeyView(view); return OpenRemoteBaseKeyCore(hKey, machineName, view); } /// <summary>Returns a subkey with read only permissions.</summary> /// <param name="name">Name or path of subkey to open.</param> /// <returns>The Subkey requested, or <b>null</b> if the operation failed.</returns> public RegistryKey OpenSubKey(string name) { return OpenSubKey(name, false); } /// <summary> /// Retrieves a subkey. If readonly is <b>true</b>, then the subkey is opened with /// read-only access. /// </summary> /// <param name="name">Name or the path of subkey to open.</param> /// <param name="writable">Set to <b>true</b> if you only need readonly access.</param> /// <returns>the Subkey requested, or <b>null</b> if the operation failed.</returns> public RegistryKey OpenSubKey(string name, bool writable) { ValidateKeyName(name); EnsureNotDisposed(); name = FixupName(name); return InternalOpenSubKeyCore(name, writable, true); } public RegistryKey OpenSubKey(string name, RegistryKeyPermissionCheck permissionCheck) { ValidateKeyMode(permissionCheck); return InternalOpenSubKey(name, permissionCheck, GetRegistryKeyAccess(permissionCheck)); } public RegistryKey OpenSubKey(string name, RegistryRights rights) { return InternalOpenSubKey(name, this._checkMode, (int)rights); } public RegistryKey OpenSubKey(string name, RegistryKeyPermissionCheck permissionCheck, RegistryRights rights) { return InternalOpenSubKey(name, permissionCheck, (int)rights); } private RegistryKey InternalOpenSubKey(string name, RegistryKeyPermissionCheck permissionCheck, int rights) { ValidateKeyName(name); ValidateKeyMode(permissionCheck); ValidateKeyRights(rights); EnsureNotDisposed(); name = FixupName(name); // Fixup multiple slashes to a single slash return InternalOpenSubKeyCore(name, permissionCheck, rights, true); } internal RegistryKey InternalOpenSubKeyWithoutSecurityChecks(string name, bool writable) { ValidateKeyName(name); EnsureNotDisposed(); return InternalOpenSubKeyWithoutSecurityChecksCore(name, writable); } public RegistrySecurity GetAccessControl() { return GetAccessControl(AccessControlSections.Access | AccessControlSections.Owner | AccessControlSections.Group); } [SecuritySafeCritical] public RegistrySecurity GetAccessControl(AccessControlSections includeSections) { EnsureNotDisposed(); return new RegistrySecurity(Handle, Name, includeSections); } [SecuritySafeCritical] public void SetAccessControl(RegistrySecurity registrySecurity) { EnsureWriteable(); if (registrySecurity == null) { throw new ArgumentNullException(nameof(registrySecurity)); } registrySecurity.Persist(Handle, Name); } /// <summary>Retrieves the count of subkeys.</summary> /// <returns>A count of subkeys.</returns> public int SubKeyCount { get { return InternalSubKeyCount(); } } public RegistryView View { get { EnsureNotDisposed(); return _regView; } } public SafeRegistryHandle Handle { get { EnsureNotDisposed(); return IsSystemKey() ? SystemKeyHandle : _hkey; } } public static RegistryKey FromHandle(SafeRegistryHandle handle) { return FromHandle(handle, RegistryView.Default); } public static RegistryKey FromHandle(SafeRegistryHandle handle, RegistryView view) { if (handle == null) throw new ArgumentNullException(nameof(handle)); ValidateKeyView(view); return new RegistryKey(handle, writable: true, view: view); } private int InternalSubKeyCount() { EnsureNotDisposed(); return InternalSubKeyCountCore(); } /// <summary>Retrieves an array of strings containing all the subkey names.</summary> /// <returns>All subkey names.</returns> public string[] GetSubKeyNames() { return InternalGetSubKeyNames(); } private string[] InternalGetSubKeyNames() { EnsureNotDisposed(); int subkeys = InternalSubKeyCount(); return subkeys > 0 ? InternalGetSubKeyNamesCore(subkeys) : Array.Empty<string>(); } /// <summary>Retrieves the count of values.</summary> /// <returns>A count of values.</returns> public int ValueCount { get { return InternalValueCount(); } } private int InternalValueCount() { EnsureNotDisposed(); return InternalValueCountCore(); } /// <summary>Retrieves an array of strings containing all the value names.</summary> /// <returns>All value names.</returns> public string[] GetValueNames() { EnsureNotDisposed(); int values = InternalValueCount(); return values > 0 ? GetValueNamesCore(values) : Array.Empty<string>(); } /// <summary>Retrieves the specified value. <b>null</b> is returned if the value doesn't exist</summary> /// <remarks> /// Note that <var>name</var> can be null or "", at which point the /// unnamed or default value of this Registry key is returned, if any. /// </remarks> /// <param name="name">Name of value to retrieve.</param> /// <returns>The data associated with the value.</returns> public object GetValue(string name) { return InternalGetValue(name, null, false, true); } /// <summary>Retrieves the specified value. <i>defaultValue</i> is returned if the value doesn't exist.</summary> /// <remarks> /// Note that <var>name</var> can be null or "", at which point the /// unnamed or default value of this Registry key is returned, if any. /// The default values for RegistryKeys are OS-dependent. NT doesn't /// have them by default, but they can exist and be of any type. On /// Win95, the default value is always an empty key of type REG_SZ. /// Win98 supports default values of any type, but defaults to REG_SZ. /// </remarks> /// <param name="name">Name of value to retrieve.</param> /// <param name="defaultValue">Value to return if <i>name</i> doesn't exist.</param> /// <returns>The data associated with the value.</returns> public object GetValue(string name, object defaultValue) { return InternalGetValue(name, defaultValue, false, true); } public object GetValue(string name, object defaultValue, RegistryValueOptions options) { if (options < RegistryValueOptions.None || options > RegistryValueOptions.DoNotExpandEnvironmentNames) { throw new ArgumentException(SR.Format(SR.Arg_EnumIllegalVal, (int)options), nameof(options)); } bool doNotExpand = (options == RegistryValueOptions.DoNotExpandEnvironmentNames); return InternalGetValue(name, defaultValue, doNotExpand, checkSecurity: true); } private object InternalGetValue(string name, object defaultValue, bool doNotExpand, bool checkSecurity) { if (checkSecurity) { EnsureNotDisposed(); } // Name can be null! It's the most common use of RegQueryValueEx return InternalGetValueCore(name, defaultValue, doNotExpand); } public RegistryValueKind GetValueKind(string name) { EnsureNotDisposed(); return GetValueKindCore(name); } public string Name { get { EnsureNotDisposed(); return _keyName; } } /// <summary>Sets the specified value.</summary> /// <param name="name">Name of value to store data in.</param> /// <param name="value">Data to store.</param> public void SetValue(string name, object value) { SetValue(name, value, RegistryValueKind.Unknown); } public void SetValue(string name, object value, RegistryValueKind valueKind) { if (value == null) { ThrowHelper.ThrowArgumentNullException(nameof(value)); } if (name != null && name.Length > MaxValueLength) { throw new ArgumentException(SR.Arg_RegValStrLenBug, nameof(name)); } if (!Enum.IsDefined(typeof(RegistryValueKind), valueKind)) { throw new ArgumentException(SR.Arg_RegBadKeyKind, nameof(valueKind)); } EnsureWriteable(); if (valueKind == RegistryValueKind.Unknown) { // this is to maintain compatibility with the old way of autodetecting the type. // SetValue(string, object) will come through this codepath. valueKind = CalculateValueKind(value); } SetValueCore(name, value, valueKind); } private RegistryValueKind CalculateValueKind(object value) { // This logic matches what used to be in SetValue(string name, object value) in the v1.0 and v1.1 days. // Even though we could add detection for an int64 in here, we want to maintain compatibility with the // old behavior. if (value is int) { return RegistryValueKind.DWord; } else if (value is Array) { if (value is byte[]) { return RegistryValueKind.Binary; } else if (value is string[]) { return RegistryValueKind.MultiString; } else { throw new ArgumentException(SR.Format(SR.Arg_RegSetBadArrType, value.GetType().Name)); } } else { return RegistryValueKind.String; } } /// <summary>Retrieves a string representation of this key.</summary> /// <returns>A string representing the key.</returns> public override string ToString() { EnsureNotDisposed(); return _keyName; } private static string FixupName(string name) { Debug.Assert(name != null, "[FixupName]name!=null"); if (name.IndexOf('\\') == -1) { return name; } StringBuilder sb = new StringBuilder(name); FixupPath(sb); int temp = sb.Length - 1; if (temp >= 0 && sb[temp] == '\\') // Remove trailing slash { sb.Length = temp; } return sb.ToString(); } private static void FixupPath(StringBuilder path) { Debug.Assert(path != null); int length = path.Length; bool fixup = false; char markerChar = (char)0xFFFF; int i = 1; while (i < length - 1) { if (path[i] == '\\') { i++; while (i < length && path[i] == '\\') { path[i] = markerChar; i++; fixup = true; } } i++; } if (fixup) { i = 0; int j = 0; while (i < length) { if (path[i] == markerChar) { i++; continue; } path[j] = path[i]; i++; j++; } path.Length += j - i; } } private void EnsureNotDisposed() { if (_hkey == null) { ThrowHelper.ThrowObjectDisposedException(_keyName, SR.ObjectDisposed_RegKeyClosed); } } private void EnsureWriteable() { EnsureNotDisposed(); if (!IsWritable()) { ThrowHelper.ThrowUnauthorizedAccessException(SR.UnauthorizedAccess_RegistryNoWrite); } } private RegistryKeyPermissionCheck GetSubKeyPermissionCheck(bool subkeyWritable) { if (_checkMode == RegistryKeyPermissionCheck.Default) { return _checkMode; } if (subkeyWritable) { return RegistryKeyPermissionCheck.ReadWriteSubTree; } else { return RegistryKeyPermissionCheck.ReadSubTree; } } private static void ValidateKeyName(string name) { if (name == null) { ThrowHelper.ThrowArgumentNullException(nameof(name)); } int nextSlash = name.IndexOf("\\", StringComparison.OrdinalIgnoreCase); int current = 0; while (nextSlash != -1) { if ((nextSlash - current) > MaxKeyLength) { ThrowHelper.ThrowArgumentException(SR.Arg_RegKeyStrLenBug, nameof(name)); } current = nextSlash + 1; nextSlash = name.IndexOf("\\", current, StringComparison.OrdinalIgnoreCase); } if ((name.Length - current) > MaxKeyLength) { ThrowHelper.ThrowArgumentException(SR.Arg_RegKeyStrLenBug, nameof(name)); } } private static void ValidateKeyMode(RegistryKeyPermissionCheck mode) { if (mode < RegistryKeyPermissionCheck.Default || mode > RegistryKeyPermissionCheck.ReadWriteSubTree) { ThrowHelper.ThrowArgumentException(SR.Argument_InvalidRegistryKeyPermissionCheck, nameof(mode)); } } private static void ValidateKeyOptions(RegistryOptions options) { if (options < RegistryOptions.None || options > RegistryOptions.Volatile) { ThrowHelper.ThrowArgumentException(SR.Argument_InvalidRegistryOptionsCheck, nameof(options)); } } private static void ValidateKeyView(RegistryView view) { if (view != RegistryView.Default && view != RegistryView.Registry32 && view != RegistryView.Registry64) { ThrowHelper.ThrowArgumentException(SR.Argument_InvalidRegistryViewCheck, nameof(view)); } } private static void ValidateKeyRights(int rights) { if (0 != (rights & ~((int)RegistryRights.FullControl))) { // We need to throw SecurityException here for compatiblity reason, // although UnauthorizedAccessException will make more sense. ThrowHelper.ThrowSecurityException(SR.Security_RegistryPermission); } } /// <summary>Retrieves the current state of the dirty property.</summary> /// <remarks>A key is marked as dirty if any operation has occurred that modifies the contents of the key.</remarks> /// <returns><b>true</b> if the key has been modified.</returns> private bool IsDirty() => (_state & StateFlags.Dirty) != 0; private bool IsSystemKey() => (_state & StateFlags.SystemKey) != 0; private bool IsWritable() => (_state & StateFlags.WriteAccess) != 0; private bool IsPerfDataKey() => (_state & StateFlags.PerfData) != 0; private void SetDirty() => _state |= StateFlags.Dirty; [Flags] private enum StateFlags { /// <summary>Dirty indicates that we have munged data that should be potentially written to disk.</summary> Dirty = 0x0001, /// <summary>SystemKey indicates that this is a "SYSTEMKEY" and shouldn't be "opened" or "closed".</summary> SystemKey = 0x0002, /// <summary>Access</summary> WriteAccess = 0x0004, /// <summary>Indicates if this key is for HKEY_PERFORMANCE_DATA</summary> PerfData = 0x0008 } } }
/* * Copyright 2005 OpenXRI Foundation * Subsequently ported and altered by Andrew Arnott and Troels Thomsen * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System.Collections.Generic; using System.Text; using DotNetXri.Syntax.Xri3.Impl.Parser; namespace DotNetXri.Syntax.Xri3.Impl { public class XRI3SubSegment : XRI3SyntaxComponent, XRISubSegment { private Rule rule; private char gcs; private char lcs; private XRI3Literal literal; private XRI3XRef xref; public XRI3SubSegment(string value) { this.rule = XRI3Util.getParser().parse("subseg", value); this.read(); } public XRI3SubSegment(char gcs, XRISubSegment localSubSegment) { StringBuilder buffer = new StringBuilder(); buffer.Append(gcs); buffer.Append(localSubSegment.ToString()); this.rule = XRI3Util.getParser().parse("subseg", buffer.ToString()); this.read(); } public XRI3SubSegment(char cs, string uri) { StringBuilder buffer = new StringBuilder(); buffer.Append(cs.ToString()); buffer.Append(XRI3Constants.XREF_START); buffer.Append(uri); buffer.Append(XRI3Constants.XREF_END); this.rule = XRI3Util.getParser().parse("subseg", buffer.ToString()); this.read(); } internal XRI3SubSegment(Rule rule) { this.rule = rule; this.read(); } private void reset() { this.gcs = null; this.lcs = null; this.literal = null; this.xref = null; } private void read() { this.reset(); object obj = this.rule; // subseg or global_subseg or local_subseg or rel_subseg or rel_subseg_nc // subseg? if (obj is Parser.Parser.subseg) { // read global_subseg or local_subseg from subseg IList<Rule> list_subseg = ((Parser.Parser.subseg)obj).rules; if (list_subseg.Count < 1) return; obj = list_subseg[0]; // global_subseg or local_subseg } // global_subseg? if (obj is Parser.Parser.global_subseg) { // read gcs_char from global_subseg; IList<Rule> list_global_subseg = ((Parser.Parser.global_subseg)obj).rules; if (list_global_subseg.Count < 1) return; obj = list_global_subseg[0]; // gcs_char this.gcs = ((Parser.Parser.gcs_char)obj).spelling[0]; // read rel_subseg or local_subseg from global_subseg if (list_global_subseg.Count < 2) return; obj = list_global_subseg[1]; // rel_subseg or local_subseg } // local_subseg? if (obj is Parser.Parser.local_subseg) { // read lcs_char from local_subseg; IList<Rule> list_local_subseg = ((Parser.Parser.local_subseg)obj).rules; if (list_local_subseg.Count < 1) return; obj = list_local_subseg[0]; // lcs_char this.lcs = ((Parser.Parser.lcs_char)obj).spelling[0]; // read rel_subseg from local_subseg if (list_local_subseg.Count < 2) return; obj = list_local_subseg[1]; // rel_subseg } // rel_subseg or rel_subseg_nc? if (obj is Parser.Parser.rel_subseg) { // read literal or xref from rel_subseg IList<Rule> list_rel_subseg = ((Parser.Parser.rel_subseg)obj).rules; if (list_rel_subseg.Count < 1) return; obj = list_rel_subseg[0]; // literal or xref } else if (obj is Parser.Parser.rel_subseg_nc) { // read literal_nc or xref from rel_subseg_nc IList<Rule> list_rel_subseg_nc = ((Parser.Parser.rel_subseg_nc)obj).rules; if (list_rel_subseg_nc.Count < 1) return; obj = list_rel_subseg_nc[0]; // literal_nc or xref } else { return; } // literal or literal_nc or xref? if (obj is Parser.Parser.literal) { this.literal = new XRI3Literal((Parser.Parser.literal)obj); } else if (obj is Parser.Parser.literal_nc) { this.literal = new XRI3Literal((Parser.Parser.literal_nc)obj); } else if (obj is Parser.Parser.xref) { this.xref = new XRI3XRef((Parser.Parser.xref)obj); } else { return; } } public Rule ParserObject { get { return this.rule; } } public bool hasGCS() { return (this.gcs != null); } public bool hasLCS() { return (this.lcs != null); } public bool hasLiteral() { return (this.literal != null); } public bool hasXRef() { return (this.xref != null); } public char GCS { get { return this.gcs; } } public char LCS { get { return this.lcs; } } public XRILiteral Literal { get { return this.literal; } } public XRIXRef XRef { get { return this.xref; } } public bool isGlobal() { return (this.hasGCS()); } public bool isLocal() { return (this.hasLCS() && !this.hasGCS()); } public bool isPersistent() { return (this.hasLCS() && this.LCS.Equals(XRI3Constants.LCS_BANG)); } public bool isReassignable() { return ((this.hasGCS() && !this.hasLCS()) || (this.hasLCS() && this.LCS.Equals(XRI3Constants.LCS_STAR))); } } }
/* * 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 Nini.Config; using log4net; using System; using System.Reflection; using System.IO; using System.Net; using System.Text; using System.Text.RegularExpressions; using System.Xml; using System.Xml.Serialization; using System.Collections.Generic; using OpenSim.Server.Base; using OpenSim.Services.Interfaces; using FriendInfo = OpenSim.Services.Interfaces.FriendInfo; using OpenSim.Framework; using OpenSim.Framework.Servers.HttpServer; using OpenMetaverse; namespace OpenSim.Server.Handlers.Friends { public class FriendsServerPostHandler : BaseStreamHandler { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private IFriendsService m_FriendsService; public FriendsServerPostHandler(IFriendsService service) : base("POST", "/friends") { m_FriendsService = service; } public override byte[] Handle(string path, Stream requestData, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { StreamReader sr = new StreamReader(requestData); string body = sr.ReadToEnd(); sr.Close(); body = body.Trim(); //m_log.DebugFormat("[XXX]: query String: {0}", body); try { Dictionary<string, object> request = ServerUtils.ParseQueryString(body); if (!request.ContainsKey("METHOD")) return FailureResult(); string method = request["METHOD"].ToString(); switch (method) { case "getfriends": return GetFriends(request); case "getfriends_string": return GetFriendsString(request); case "storefriend": return StoreFriend(request); case "deletefriend": return DeleteFriend(request); case "deletefriend_string": return DeleteFriendString(request); } m_log.DebugFormat("[FRIENDS HANDLER]: unknown method request {0}", method); } catch (Exception e) { m_log.DebugFormat("[FRIENDS HANDLER]: Exception {0}", e); } return FailureResult(); } #region Method-specific handlers byte[] GetFriends(Dictionary<string, object> request) { UUID principalID = UUID.Zero; if (request.ContainsKey("PRINCIPALID")) UUID.TryParse(request["PRINCIPALID"].ToString(), out principalID); else m_log.WarnFormat("[FRIENDS HANDLER]: no principalID in request to get friends"); FriendInfo[] finfos = m_FriendsService.GetFriends(principalID); return PackageFriends(finfos); } byte[] GetFriendsString(Dictionary<string, object> request) { string principalID = string.Empty; if (request.ContainsKey("PRINCIPALID")) principalID = request["PRINCIPALID"].ToString(); else m_log.WarnFormat("[FRIENDS HANDLER]: no principalID in request to get friends"); FriendInfo[] finfos = m_FriendsService.GetFriends(principalID); return PackageFriends(finfos); } private byte[] PackageFriends(FriendInfo[] finfos) { Dictionary<string, object> result = new Dictionary<string, object>(); if ((finfos == null) || ((finfos != null) && (finfos.Length == 0))) result["result"] = "null"; else { int i = 0; foreach (FriendInfo finfo in finfos) { Dictionary<string, object> rinfoDict = finfo.ToKeyValuePairs(); result["friend" + i] = rinfoDict; i++; } } string xmlString = ServerUtils.BuildXmlResponse(result); //m_log.DebugFormat("[FRIENDS HANDLER]: resp string: {0}", xmlString); return Util.UTF8NoBomEncoding.GetBytes(xmlString); } byte[] StoreFriend(Dictionary<string, object> request) { string principalID = string.Empty, friend = string.Empty; int flags = 0; FromKeyValuePairs(request, out principalID, out friend, out flags); bool success = m_FriendsService.StoreFriend(principalID, friend, flags); if (success) return SuccessResult(); else return FailureResult(); } byte[] DeleteFriend(Dictionary<string, object> request) { UUID principalID = UUID.Zero; if (request.ContainsKey("PRINCIPALID")) UUID.TryParse(request["PRINCIPALID"].ToString(), out principalID); else m_log.WarnFormat("[FRIENDS HANDLER]: no principalID in request to delete friend"); string friend = string.Empty; if (request.ContainsKey("FRIEND")) friend = request["FRIEND"].ToString(); bool success = m_FriendsService.Delete(principalID, friend); if (success) return SuccessResult(); else return FailureResult(); } byte[] DeleteFriendString(Dictionary<string, object> request) { string principalID = string.Empty; if (request.ContainsKey("PRINCIPALID")) principalID = request["PRINCIPALID"].ToString(); else m_log.WarnFormat("[FRIENDS HANDLER]: no principalID in request to delete friend"); string friend = string.Empty; if (request.ContainsKey("FRIEND")) friend = request["FRIEND"].ToString(); bool success = m_FriendsService.Delete(principalID, friend); if (success) return SuccessResult(); else return FailureResult(); } #endregion #region Misc private byte[] SuccessResult() { XmlDocument doc = new XmlDocument(); XmlNode xmlnode = doc.CreateNode(XmlNodeType.XmlDeclaration, "", ""); doc.AppendChild(xmlnode); XmlElement rootElement = doc.CreateElement("", "ServerResponse", ""); doc.AppendChild(rootElement); XmlElement result = doc.CreateElement("", "Result", ""); result.AppendChild(doc.CreateTextNode("Success")); rootElement.AppendChild(result); return DocToBytes(doc); } private byte[] FailureResult() { return FailureResult(String.Empty); } private byte[] FailureResult(string msg) { XmlDocument doc = new XmlDocument(); XmlNode xmlnode = doc.CreateNode(XmlNodeType.XmlDeclaration, "", ""); doc.AppendChild(xmlnode); XmlElement rootElement = doc.CreateElement("", "ServerResponse", ""); doc.AppendChild(rootElement); XmlElement result = doc.CreateElement("", "Result", ""); result.AppendChild(doc.CreateTextNode("Failure")); rootElement.AppendChild(result); XmlElement message = doc.CreateElement("", "Message", ""); message.AppendChild(doc.CreateTextNode(msg)); rootElement.AppendChild(message); return DocToBytes(doc); } private byte[] DocToBytes(XmlDocument doc) { MemoryStream ms = new MemoryStream(); XmlTextWriter xw = new XmlTextWriter(ms, null); xw.Formatting = Formatting.Indented; doc.WriteTo(xw); xw.Flush(); return ms.ToArray(); } void FromKeyValuePairs(Dictionary<string, object> kvp, out string principalID, out string friend, out int flags) { principalID = string.Empty; if (kvp.ContainsKey("PrincipalID") && kvp["PrincipalID"] != null) principalID = kvp["PrincipalID"].ToString(); friend = string.Empty; if (kvp.ContainsKey("Friend") && kvp["Friend"] != null) friend = kvp["Friend"].ToString(); flags = 0; if (kvp.ContainsKey("MyFlags") && kvp["MyFlags"] != null) Int32.TryParse(kvp["MyFlags"].ToString(), out flags); } #endregion } }
//------------------------------------------------------------------------------ // <copyright file="PropertyInformation.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ using System; using System.Configuration; using System.Collections.Specialized; using System.ComponentModel; using System.Collections; using System.Runtime.Serialization; namespace System.Configuration { // PropertyInformation // // Contains information about a property // public sealed class PropertyInformation { private ConfigurationElement ThisElement = null; private string PropertyName; private ConfigurationProperty _Prop = null; private const string LockAll = "*"; private ConfigurationProperty Prop { get { if (_Prop == null) { _Prop = ThisElement.Properties[PropertyName]; } return _Prop; } } internal PropertyInformation(ConfigurationElement thisElement, string propertyName) { PropertyName = propertyName; ThisElement = thisElement; } public string Name { get { return PropertyName; } } internal string ProvidedName { get { return Prop.ProvidedName; } } public object Value { get { return ThisElement[PropertyName]; } set { ThisElement[PropertyName] = value; } } // DefaultValue // // What is the default value for this property // public object DefaultValue { get { return Prop.DefaultValue; } } // ValueOrigin // // Where was the property retrieved from // public PropertyValueOrigin ValueOrigin { get { if (ThisElement.Values[PropertyName] == null) { return PropertyValueOrigin.Default; } if (ThisElement.Values.IsInherited(PropertyName)) { return PropertyValueOrigin.Inherited; } return PropertyValueOrigin.SetHere; } } // IsModified // // Was the property Modified // public bool IsModified { get { if (ThisElement.Values[PropertyName] == null) { return false; } if (ThisElement.Values.IsModified(PropertyName)) { return true; } return false; } } // IsKey // // Is this property a key? // public bool IsKey { get { return Prop.IsKey; } } // IsRequired // // Is this property required? // public bool IsRequired { get { return Prop.IsRequired; } } // IsLocked // // Is this property locked? // public bool IsLocked { get { return ((ThisElement.LockedAllExceptAttributesList != null && !ThisElement.LockedAllExceptAttributesList.DefinedInParent(PropertyName)) || (ThisElement.LockedAttributesList != null && (ThisElement.LockedAttributesList.DefinedInParent(PropertyName) || ThisElement.LockedAttributesList.DefinedInParent(LockAll))) || (((ThisElement.ItemLocked & ConfigurationValueFlags.Locked) != 0) && ((ThisElement.ItemLocked & ConfigurationValueFlags.Inherited) != 0))); } } // Source // // What is the source file where this data came from // public string Source { get { PropertySourceInfo psi = ThisElement.Values.GetSourceInfo(PropertyName); if (psi == null) { psi = ThisElement.Values.GetSourceInfo(String.Empty); } if (psi == null) { return String.Empty; } return psi.FileName; } } // LineNumber // // What is the line number associated with the source // // Note: // 1 is the first line in the file. 0 is returned when there is no // source // public int LineNumber { get { PropertySourceInfo psi = ThisElement.Values.GetSourceInfo(PropertyName); if (psi == null) { psi = ThisElement.Values.GetSourceInfo(String.Empty); } if (psi == null) { return 0; } return psi.LineNumber; } } // Type // // What is the type for the property // public Type Type { get { return Prop.Type; } } // Validator // public ConfigurationValidatorBase Validator { get { return Prop.Validator; } } // Converter // public TypeConverter Converter { get { return Prop.Converter; } } // Property description ( comments etc ) public string Description { get { return Prop.Description; } } } }
/* ==================================================================== 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. ==================================================================== */ /* ================================================================ * About NPOI * Author: Tony Qu * Author's email: tonyqus (at) gmail.com * Author's Blog: tonyqus.wordpress.com.cn (wp.tonyqus.cn) * HomePage: http://www.codeplex.com/npoi * Contributors: * * ==============================================================*/ namespace NStorage.Utility { using System; using System.IO; public class PushbackStream:Stream { private int buf = -1; private Stream s; public PushbackStream( Stream s) { this.s = s; } protected override void Dispose(bool disposing) { this.s = null; base.Dispose(disposing); } /// <summary> /// Reads a byte from the stream and advances the position within the stream by one byte, or returns -1 if at the end of the stream. /// </summary> /// <returns> /// The unsigned byte cast to an Int32, or -1 if at the end of the stream. /// </returns> /// <exception cref="T:System.NotSupportedException"> /// The stream does not support reading. /// </exception> /// <exception cref="T:System.ObjectDisposedException"> /// Methods were called after the stream was closed. /// </exception> public override int ReadByte() { if (buf != -1) { int tmp = buf; buf = -1; return tmp; } return s.ReadByte(); } /// <summary> /// When overridden in a derived class, reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read. /// </summary> /// <param name="buffer">An array of bytes. When this method returns, the buffer contains the specified byte array with the values between <paramref name="offset"/> and (<paramref name="offset"/> + <paramref name="count"/> - 1) replaced by the bytes read from the current source.</param> /// <param name="offset">The zero-based byte offset in <paramref name="buffer"/> at which to begin storing the data read from the current stream.</param> /// <param name="count">The maximum number of bytes to be read from the current stream.</param> /// <returns> /// The total number of bytes read into the buffer. This can be less than the number of bytes requested if that many bytes are not currently available, or zero (0) if the end of the stream has been reached. /// </returns> /// <exception cref="T:System.ArgumentException"> /// The sum of <paramref name="offset"/> and <paramref name="count"/> is larger than the buffer length. /// </exception> /// <exception cref="T:System.ArgumentNullException"> /// <paramref name="buffer"/> is null. /// </exception> /// <exception cref="T:System.ArgumentOutOfRangeException"> /// <paramref name="offset"/> or <paramref name="count"/> is negative. /// </exception> /// <exception cref="T:System.IO.IOException"> /// An I/O error occurs. /// </exception> /// <exception cref="T:System.NotSupportedException"> /// The stream does not support reading. /// </exception> /// <exception cref="T:System.ObjectDisposedException"> /// Methods were called after the stream was closed. /// </exception> public override int Read(byte[] buffer, int offset, int count) { if (buf != -1 && count > 0) { // TODO Can this case be made more efficient? buffer[offset] = (byte) buf; buf = -1; return 1; } return s.Read(buffer, offset, count); } /// <summary> /// Unreads the specified b. /// </summary> /// <param name="b">The b.</param> public virtual void Unread(int b) { if (buf != -1) throw new InvalidOperationException("Can only push back one byte"); buf = b & 0xFF; s.Position -= b; } /// <summary> /// When overridden in a derived class, gets a value indicating whether the current stream supports reading. /// </summary> /// <value></value> /// <returns>true if the stream supports reading; otherwise, false. /// </returns> public override bool CanRead { get { return s.CanRead; } } /// <summary> /// When overridden in a derived class, gets a value indicating whether the current stream supports seeking. /// </summary> /// <value></value> /// <returns>true if the stream supports seeking; otherwise, false. /// </returns> public override bool CanSeek { get { return s.CanSeek; } } /// <summary> /// When overridden in a derived class, gets a value indicating whether the current stream supports writing. /// </summary> /// <value></value> /// <returns>true if the stream supports writing; otherwise, false. /// </returns> public override bool CanWrite { get { return s.CanWrite; } } /// <summary> /// When overridden in a derived class, gets the length in bytes of the stream. /// </summary> /// <value></value> /// <returns> /// A long value representing the length of the stream in bytes. /// </returns> /// <exception cref="T:System.NotSupportedException"> /// A class derived from Stream does not support seeking. /// </exception> /// <exception cref="T:System.ObjectDisposedException"> /// Methods were called after the stream was closed. /// </exception> public override long Length { get { return s.Length; } } /// <summary> /// When overridden in a derived class, gets or sets the position within the current stream. /// </summary> /// <value></value> /// <returns> /// The current position within the stream. /// </returns> /// <exception cref="T:System.IO.IOException"> /// An I/O error occurs. /// </exception> /// <exception cref="T:System.NotSupportedException"> /// The stream does not support seeking. /// </exception> /// <exception cref="T:System.ObjectDisposedException"> /// Methods were called after the stream was closed. /// </exception> public override long Position { get { return s.Position; } set { s.Position = value; } } /// <summary> /// Closes the current stream and releases any resources (such as sockets and file handles) associated with the current stream. /// </summary> public override void Close() { s.Close(); } /// <summary> /// When overridden in a derived class, clears all buffers for this stream and causes any buffered data to be written to the underlying device. /// </summary> /// <exception cref="T:System.IO.IOException"> /// An I/O error occurs. /// </exception> public override void Flush() { s.Flush(); } /// <summary> /// When overridden in a derived class, sets the position within the current stream. /// </summary> /// <param name="offset">A byte offset relative to the <paramref name="origin"/> parameter.</param> /// <param name="origin">A value of type <see cref="T:System.IO.SeekOrigin"/> indicating the reference point used to obtain the new position.</param> /// <returns> /// The new position within the current stream. /// </returns> /// <exception cref="T:System.IO.IOException"> /// An I/O error occurs. /// </exception> /// <exception cref="T:System.NotSupportedException"> /// The stream does not support seeking, such as if the stream is constructed from a pipe or console output. /// </exception> /// <exception cref="T:System.ObjectDisposedException"> /// Methods were called after the stream was closed. /// </exception> public override long Seek(long offset, SeekOrigin origin) { return s.Seek(offset, origin); } /// <summary> /// When overridden in a derived class, sets the length of the current stream. /// </summary> /// <param name="value">The desired length of the current stream in bytes.</param> /// <exception cref="T:System.IO.IOException"> /// An I/O error occurs. /// </exception> /// <exception cref="T:System.NotSupportedException"> /// The stream does not support both writing and seeking, such as if the stream is constructed from a pipe or console output. /// </exception> /// <exception cref="T:System.ObjectDisposedException"> /// Methods were called after the stream was closed. /// </exception> public override void SetLength(long value) { s.SetLength(value); } /// <summary> /// When overridden in a derived class, writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written. /// </summary> /// <param name="buffer">An array of bytes. This method copies <paramref name="count"/> bytes from <paramref name="buffer"/> to the current stream.</param> /// <param name="offset">The zero-based byte offset in <paramref name="buffer"/> at which to begin copying bytes to the current stream.</param> /// <param name="count">The number of bytes to be written to the current stream.</param> /// <exception cref="T:System.ArgumentException"> /// The sum of <paramref name="offset"/> and <paramref name="count"/> is greater than the buffer length. /// </exception> /// <exception cref="T:System.ArgumentNullException"> /// <paramref name="buffer"/> is null. /// </exception> /// <exception cref="T:System.ArgumentOutOfRangeException"> /// <paramref name="offset"/> or <paramref name="count"/> is negative. /// </exception> /// <exception cref="T:System.IO.IOException"> /// An I/O error occurs. /// </exception> /// <exception cref="T:System.NotSupportedException"> /// The stream does not support writing. /// </exception> /// <exception cref="T:System.ObjectDisposedException"> /// Methods were called after the stream was closed. /// </exception> public override void Write(byte[] buffer, int offset, int count) { s.Write(buffer, offset, count); } /// <summary> /// Writes a byte to the current position in the stream and advances the position within the stream by one byte. /// </summary> /// <param name="value">The byte to write to the stream.</param> /// <exception cref="T:System.IO.IOException"> /// An I/O error occurs. /// </exception> /// <exception cref="T:System.NotSupportedException"> /// The stream does not support writing, or the stream is already closed. /// </exception> /// <exception cref="T:System.ObjectDisposedException"> /// Methods were called after the stream was closed. /// </exception> public override void WriteByte(byte value) { s.WriteByte(value); } } }
using System; using Org.BouncyCastle.Crypto.Macs; using Org.BouncyCastle.Crypto.Modes.Gcm; using Org.BouncyCastle.Crypto.Parameters; using Org.BouncyCastle.Crypto.Utilities; using Org.BouncyCastle.Math; using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Crypto.Modes { /// <summary> /// Implements the Galois/Counter mode (GCM) detailed in /// NIST Special Publication 800-38D. /// </summary> public class GcmBlockCipher : IAeadBlockCipher { private const int BlockSize = 16; private static readonly byte[] Zeroes = new byte[BlockSize]; private readonly IBlockCipher cipher; private readonly IGcmMultiplier multiplier; // These fields are set by Init and not modified by processing private bool forEncryption; private int macSize; private byte[] nonce; private byte[] A; private KeyParameter keyParam; private byte[] H; private byte[] initS; private byte[] J0; // These fields are modified during processing private byte[] bufBlock; private byte[] macBlock; private byte[] S; private byte[] counter; private int bufOff; private ulong totalLength; public GcmBlockCipher( IBlockCipher c) : this(c, null) { } public GcmBlockCipher( IBlockCipher c, IGcmMultiplier m) { if (c.GetBlockSize() != BlockSize) throw new ArgumentException("cipher required with a block size of " + BlockSize + "."); if (m == null) { // TODO Consider a static property specifying default multiplier m = new Tables8kGcmMultiplier(); } this.cipher = c; this.multiplier = m; } public virtual string AlgorithmName { get { return cipher.AlgorithmName + "/GCM"; } } public virtual int GetBlockSize() { return BlockSize; } public virtual void Init( bool forEncryption, ICipherParameters parameters) { this.forEncryption = forEncryption; this.macBlock = null; if (parameters is AeadParameters) { AeadParameters param = (AeadParameters)parameters; nonce = param.GetNonce(); A = param.GetAssociatedText(); int macSizeBits = param.MacSize; if (macSizeBits < 96 || macSizeBits > 128 || macSizeBits % 8 != 0) { throw new ArgumentException("Invalid value for MAC size: " + macSizeBits); } macSize = macSizeBits / 8; keyParam = param.Key; } else if (parameters is ParametersWithIV) { ParametersWithIV param = (ParametersWithIV)parameters; nonce = param.GetIV(); A = null; macSize = 16; keyParam = (KeyParameter)param.Parameters; } else { throw new ArgumentException("invalid parameters passed to GCM"); } int bufLength = forEncryption ? BlockSize : (BlockSize + macSize); this.bufBlock = new byte[bufLength]; if (nonce == null || nonce.Length < 1) { throw new ArgumentException("IV must be at least 1 byte"); } if (A == null) { // Avoid lots of null checks A = new byte[0]; } // Cipher always used in forward mode cipher.Init(true, keyParam); // TODO This should be configurable by Init parameters // (but must be 16 if nonce length not 12) (BlockSize?) // this.tagLength = 16; this.H = new byte[BlockSize]; cipher.ProcessBlock(H, 0, H, 0); multiplier.Init(H); this.initS = gHASH(A); if (nonce.Length == 12) { this.J0 = new byte[16]; Array.Copy(nonce, 0, J0, 0, nonce.Length); this.J0[15] = 0x01; } else { this.J0 = gHASH(nonce); byte[] X = new byte[16]; packLength((ulong)nonce.Length * 8UL, X, 8); GcmUtilities.Xor(this.J0, X); multiplier.MultiplyH(this.J0); } this.S = Arrays.Clone(initS); this.counter = Arrays.Clone(J0); this.bufOff = 0; this.totalLength = 0; } public virtual byte[] GetMac() { return Arrays.Clone(macBlock); } public virtual int GetOutputSize( int len) { if (forEncryption) { return len + bufOff + macSize; } return len + bufOff - macSize; } public virtual int GetUpdateOutputSize( int len) { return ((len + bufOff) / BlockSize) * BlockSize; } public virtual int ProcessByte( byte input, byte[] output, int outOff) { return Process(input, output, outOff); } public virtual int ProcessBytes( byte[] input, int inOff, int len, byte[] output, int outOff) { int resultLen = 0; for (int i = 0; i != len; i++) { // resultLen += Process(input[inOff + i], output, outOff + resultLen); bufBlock[bufOff++] = input[inOff + i]; if (bufOff == bufBlock.Length) { gCTRBlock(bufBlock, BlockSize, output, outOff + resultLen); if (!forEncryption) { Array.Copy(bufBlock, BlockSize, bufBlock, 0, macSize); } // bufOff = 0; bufOff = bufBlock.Length - BlockSize; // return bufBlock.Length; resultLen += BlockSize; } } return resultLen; } private int Process( byte input, byte[] output, int outOff) { bufBlock[bufOff++] = input; if (bufOff == bufBlock.Length) { gCTRBlock(bufBlock, BlockSize, output, outOff); if (!forEncryption) { Array.Copy(bufBlock, BlockSize, bufBlock, 0, macSize); } // bufOff = 0; bufOff = bufBlock.Length - BlockSize; // return bufBlock.Length; return BlockSize; } return 0; } public int DoFinal(byte[] output, int outOff) { int extra = bufOff; if (!forEncryption) { if (extra < macSize) throw new InvalidCipherTextException("data too short"); extra -= macSize; } if (extra > 0) { byte[] tmp = new byte[BlockSize]; Array.Copy(bufBlock, 0, tmp, 0, extra); gCTRBlock(tmp, extra, output, outOff); } // Final gHASH byte[] X = new byte[16]; packLength((ulong)A.Length * 8UL, X, 0); packLength(totalLength * 8UL, X, 8); GcmUtilities.Xor(S, X); multiplier.MultiplyH(S); // TODO Fix this if tagLength becomes configurable // T = MSBt(GCTRk(J0,S)) byte[] tag = new byte[BlockSize]; cipher.ProcessBlock(J0, 0, tag, 0); GcmUtilities.Xor(tag, S); int resultLen = extra; // We place into macBlock our calculated value for T this.macBlock = new byte[macSize]; Array.Copy(tag, 0, macBlock, 0, macSize); if (forEncryption) { // Append T to the message Array.Copy(macBlock, 0, output, outOff + bufOff, macSize); resultLen += macSize; } else { // Retrieve the T value from the message and compare to calculated one byte[] msgMac = new byte[macSize]; Array.Copy(bufBlock, extra, msgMac, 0, macSize); if (!Arrays.ConstantTimeAreEqual(this.macBlock, msgMac)) throw new InvalidCipherTextException("mac check in GCM failed"); } Reset(false); return resultLen; } public virtual void Reset() { Reset(true); } private void Reset( bool clearMac) { S = Arrays.Clone(initS); counter = Arrays.Clone(J0); bufOff = 0; totalLength = 0; if (bufBlock != null) { Array.Clear(bufBlock, 0, bufBlock.Length); } if (clearMac) { macBlock = null; } cipher.Reset(); } private void gCTRBlock(byte[] buf, int bufCount, byte[] output, int outOff) { // inc(counter); for (int i = 15; i >= 12; --i) { if (++counter[i] != 0) break; } byte[] tmp = new byte[BlockSize]; cipher.ProcessBlock(counter, 0, tmp, 0); byte[] hashBytes; if (forEncryption) { Array.Copy(Zeroes, bufCount, tmp, bufCount, BlockSize - bufCount); hashBytes = tmp; } else { hashBytes = buf; } for (int i = bufCount - 1; i >= 0; --i) { tmp[i] ^= buf[i]; output[outOff + i] = tmp[i]; } // gHASHBlock(hashBytes); GcmUtilities.Xor(S, hashBytes); multiplier.MultiplyH(S); totalLength += (ulong)bufCount; } private byte[] gHASH(byte[] b) { byte[] Y = new byte[16]; for (int pos = 0; pos < b.Length; pos += 16) { byte[] X = new byte[16]; int num = System.Math.Min(b.Length - pos, 16); Array.Copy(b, pos, X, 0, num); GcmUtilities.Xor(Y, X); multiplier.MultiplyH(Y); } return Y; } // private void gHASHBlock(byte[] block) // { // GcmUtilities.Xor(S, block); // multiplier.MultiplyH(S); // } // private static void inc(byte[] block) // { // for (int i = 15; i >= 12; --i) // { // if (++block[i] != 0) break; // } // } private static void packLength(ulong len, byte[] bs, int off) { Pack.UInt32_To_BE((uint)(len >> 32), bs, off); Pack.UInt32_To_BE((uint)len, bs, off + 4); } } }
namespace android.app { [global::MonoJavaBridge.JavaClass()] public partial class Dialog : java.lang.Object, android.content.DialogInterface, android.view.Window.Callback, android.view.KeyEvent.Callback, android.view.View.OnCreateContextMenuListener { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static Dialog() { InitJNI(); } protected Dialog(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } internal static global::MonoJavaBridge.MethodId _getContext460; public virtual global::android.content.Context getContext() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.app.Dialog._getContext460)) as android.content.Context; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.app.Dialog.staticClass, global::android.app.Dialog._getContext460)) as android.content.Context; } internal static global::MonoJavaBridge.MethodId _cancel461; public virtual void cancel() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.app.Dialog._cancel461); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.app.Dialog.staticClass, global::android.app.Dialog._cancel461); } internal static global::MonoJavaBridge.MethodId _onCreate462; protected virtual void onCreate(android.os.Bundle arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.app.Dialog._onCreate462, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.app.Dialog.staticClass, global::android.app.Dialog._onCreate462, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _onStart463; protected virtual void onStart() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.app.Dialog._onStart463); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.app.Dialog.staticClass, global::android.app.Dialog._onStart463); } internal static global::MonoJavaBridge.MethodId _getWindow464; public virtual global::android.view.Window getWindow() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.app.Dialog._getWindow464)) as android.view.Window; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.app.Dialog.staticClass, global::android.app.Dialog._getWindow464)) as android.view.Window; } internal static global::MonoJavaBridge.MethodId _getCurrentFocus465; public virtual global::android.view.View getCurrentFocus() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.app.Dialog._getCurrentFocus465)) as android.view.View; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.app.Dialog.staticClass, global::android.app.Dialog._getCurrentFocus465)) as android.view.View; } internal static global::MonoJavaBridge.MethodId _onRestoreInstanceState466; public virtual void onRestoreInstanceState(android.os.Bundle arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.app.Dialog._onRestoreInstanceState466, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.app.Dialog.staticClass, global::android.app.Dialog._onRestoreInstanceState466, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _onSaveInstanceState467; public virtual global::android.os.Bundle onSaveInstanceState() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.app.Dialog._onSaveInstanceState467)) as android.os.Bundle; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.app.Dialog.staticClass, global::android.app.Dialog._onSaveInstanceState467)) as android.os.Bundle; } internal static global::MonoJavaBridge.MethodId _onStop468; protected virtual void onStop() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.app.Dialog._onStop468); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.app.Dialog.staticClass, global::android.app.Dialog._onStop468); } internal static global::MonoJavaBridge.MethodId _findViewById469; public virtual global::android.view.View findViewById(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.app.Dialog._findViewById469, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.view.View; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.app.Dialog.staticClass, global::android.app.Dialog._findViewById469, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.view.View; } internal static global::MonoJavaBridge.MethodId _setContentView470; public virtual void setContentView(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.app.Dialog._setContentView470, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.app.Dialog.staticClass, global::android.app.Dialog._setContentView470, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _setContentView471; public virtual void setContentView(android.view.View arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.app.Dialog._setContentView471, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.app.Dialog.staticClass, global::android.app.Dialog._setContentView471, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _setContentView472; public virtual void setContentView(android.view.View arg0, android.view.ViewGroup.LayoutParams arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.app.Dialog._setContentView472, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.app.Dialog.staticClass, global::android.app.Dialog._setContentView472, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _addContentView473; public virtual void addContentView(android.view.View arg0, android.view.ViewGroup.LayoutParams arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.app.Dialog._addContentView473, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.app.Dialog.staticClass, global::android.app.Dialog._addContentView473, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _onKeyDown474; public virtual bool onKeyDown(int arg0, android.view.KeyEvent arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.app.Dialog._onKeyDown474, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.app.Dialog.staticClass, global::android.app.Dialog._onKeyDown474, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _onKeyLongPress475; public virtual bool onKeyLongPress(int arg0, android.view.KeyEvent arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.app.Dialog._onKeyLongPress475, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.app.Dialog.staticClass, global::android.app.Dialog._onKeyLongPress475, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _onKeyUp476; public virtual bool onKeyUp(int arg0, android.view.KeyEvent arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.app.Dialog._onKeyUp476, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.app.Dialog.staticClass, global::android.app.Dialog._onKeyUp476, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _onKeyMultiple477; public virtual bool onKeyMultiple(int arg0, int arg1, android.view.KeyEvent arg2) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.app.Dialog._onKeyMultiple477, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.app.Dialog.staticClass, global::android.app.Dialog._onKeyMultiple477, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } internal static global::MonoJavaBridge.MethodId _onBackPressed478; public virtual void onBackPressed() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.app.Dialog._onBackPressed478); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.app.Dialog.staticClass, global::android.app.Dialog._onBackPressed478); } internal static global::MonoJavaBridge.MethodId _onTouchEvent479; public virtual bool onTouchEvent(android.view.MotionEvent arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.app.Dialog._onTouchEvent479, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.app.Dialog.staticClass, global::android.app.Dialog._onTouchEvent479, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _onTrackballEvent480; public virtual bool onTrackballEvent(android.view.MotionEvent arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.app.Dialog._onTrackballEvent480, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.app.Dialog.staticClass, global::android.app.Dialog._onTrackballEvent480, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _onWindowAttributesChanged481; public virtual void onWindowAttributesChanged(android.view.WindowManager_LayoutParams arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.app.Dialog._onWindowAttributesChanged481, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.app.Dialog.staticClass, global::android.app.Dialog._onWindowAttributesChanged481, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _onContentChanged482; public virtual void onContentChanged() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.app.Dialog._onContentChanged482); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.app.Dialog.staticClass, global::android.app.Dialog._onContentChanged482); } internal static global::MonoJavaBridge.MethodId _onWindowFocusChanged483; public virtual void onWindowFocusChanged(bool arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.app.Dialog._onWindowFocusChanged483, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.app.Dialog.staticClass, global::android.app.Dialog._onWindowFocusChanged483, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _onAttachedToWindow484; public virtual void onAttachedToWindow() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.app.Dialog._onAttachedToWindow484); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.app.Dialog.staticClass, global::android.app.Dialog._onAttachedToWindow484); } internal static global::MonoJavaBridge.MethodId _onDetachedFromWindow485; public virtual void onDetachedFromWindow() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.app.Dialog._onDetachedFromWindow485); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.app.Dialog.staticClass, global::android.app.Dialog._onDetachedFromWindow485); } internal static global::MonoJavaBridge.MethodId _dispatchKeyEvent486; public virtual bool dispatchKeyEvent(android.view.KeyEvent arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.app.Dialog._dispatchKeyEvent486, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.app.Dialog.staticClass, global::android.app.Dialog._dispatchKeyEvent486, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _dispatchTouchEvent487; public virtual bool dispatchTouchEvent(android.view.MotionEvent arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.app.Dialog._dispatchTouchEvent487, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.app.Dialog.staticClass, global::android.app.Dialog._dispatchTouchEvent487, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _dispatchTrackballEvent488; public virtual bool dispatchTrackballEvent(android.view.MotionEvent arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.app.Dialog._dispatchTrackballEvent488, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.app.Dialog.staticClass, global::android.app.Dialog._dispatchTrackballEvent488, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _dispatchPopulateAccessibilityEvent489; public virtual bool dispatchPopulateAccessibilityEvent(android.view.accessibility.AccessibilityEvent arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.app.Dialog._dispatchPopulateAccessibilityEvent489, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.app.Dialog.staticClass, global::android.app.Dialog._dispatchPopulateAccessibilityEvent489, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _onCreatePanelView490; public virtual global::android.view.View onCreatePanelView(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.app.Dialog._onCreatePanelView490, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.view.View; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.app.Dialog.staticClass, global::android.app.Dialog._onCreatePanelView490, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.view.View; } internal static global::MonoJavaBridge.MethodId _onCreatePanelMenu491; public virtual bool onCreatePanelMenu(int arg0, android.view.Menu arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.app.Dialog._onCreatePanelMenu491, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.app.Dialog.staticClass, global::android.app.Dialog._onCreatePanelMenu491, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _onPreparePanel492; public virtual bool onPreparePanel(int arg0, android.view.View arg1, android.view.Menu arg2) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.app.Dialog._onPreparePanel492, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.app.Dialog.staticClass, global::android.app.Dialog._onPreparePanel492, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } internal static global::MonoJavaBridge.MethodId _onMenuOpened493; public virtual bool onMenuOpened(int arg0, android.view.Menu arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.app.Dialog._onMenuOpened493, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.app.Dialog.staticClass, global::android.app.Dialog._onMenuOpened493, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _onMenuItemSelected494; public virtual bool onMenuItemSelected(int arg0, android.view.MenuItem arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.app.Dialog._onMenuItemSelected494, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.app.Dialog.staticClass, global::android.app.Dialog._onMenuItemSelected494, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _onPanelClosed495; public virtual void onPanelClosed(int arg0, android.view.Menu arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.app.Dialog._onPanelClosed495, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.app.Dialog.staticClass, global::android.app.Dialog._onPanelClosed495, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _onCreateOptionsMenu496; public virtual bool onCreateOptionsMenu(android.view.Menu arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.app.Dialog._onCreateOptionsMenu496, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.app.Dialog.staticClass, global::android.app.Dialog._onCreateOptionsMenu496, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _onPrepareOptionsMenu497; public virtual bool onPrepareOptionsMenu(android.view.Menu arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.app.Dialog._onPrepareOptionsMenu497, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.app.Dialog.staticClass, global::android.app.Dialog._onPrepareOptionsMenu497, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _onOptionsItemSelected498; public virtual bool onOptionsItemSelected(android.view.MenuItem arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.app.Dialog._onOptionsItemSelected498, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.app.Dialog.staticClass, global::android.app.Dialog._onOptionsItemSelected498, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _onOptionsMenuClosed499; public virtual void onOptionsMenuClosed(android.view.Menu arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.app.Dialog._onOptionsMenuClosed499, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.app.Dialog.staticClass, global::android.app.Dialog._onOptionsMenuClosed499, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _openOptionsMenu500; public virtual void openOptionsMenu() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.app.Dialog._openOptionsMenu500); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.app.Dialog.staticClass, global::android.app.Dialog._openOptionsMenu500); } internal static global::MonoJavaBridge.MethodId _closeOptionsMenu501; public virtual void closeOptionsMenu() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.app.Dialog._closeOptionsMenu501); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.app.Dialog.staticClass, global::android.app.Dialog._closeOptionsMenu501); } internal static global::MonoJavaBridge.MethodId _onCreateContextMenu502; public virtual void onCreateContextMenu(android.view.ContextMenu arg0, android.view.View arg1, android.view.ContextMenu_ContextMenuInfo arg2) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.app.Dialog._onCreateContextMenu502, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.app.Dialog.staticClass, global::android.app.Dialog._onCreateContextMenu502, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } internal static global::MonoJavaBridge.MethodId _registerForContextMenu503; public virtual void registerForContextMenu(android.view.View arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.app.Dialog._registerForContextMenu503, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.app.Dialog.staticClass, global::android.app.Dialog._registerForContextMenu503, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _unregisterForContextMenu504; public virtual void unregisterForContextMenu(android.view.View arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.app.Dialog._unregisterForContextMenu504, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.app.Dialog.staticClass, global::android.app.Dialog._unregisterForContextMenu504, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _openContextMenu505; public virtual void openContextMenu(android.view.View arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.app.Dialog._openContextMenu505, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.app.Dialog.staticClass, global::android.app.Dialog._openContextMenu505, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _onContextItemSelected506; public virtual bool onContextItemSelected(android.view.MenuItem arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.app.Dialog._onContextItemSelected506, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.app.Dialog.staticClass, global::android.app.Dialog._onContextItemSelected506, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _onContextMenuClosed507; public virtual void onContextMenuClosed(android.view.Menu arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.app.Dialog._onContextMenuClosed507, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.app.Dialog.staticClass, global::android.app.Dialog._onContextMenuClosed507, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _onSearchRequested508; public virtual bool onSearchRequested() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.app.Dialog._onSearchRequested508); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.app.Dialog.staticClass, global::android.app.Dialog._onSearchRequested508); } internal static global::MonoJavaBridge.MethodId _takeKeyEvents509; public virtual void takeKeyEvents(bool arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.app.Dialog._takeKeyEvents509, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.app.Dialog.staticClass, global::android.app.Dialog._takeKeyEvents509, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _requestWindowFeature510; public virtual bool requestWindowFeature(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.app.Dialog._requestWindowFeature510, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.app.Dialog.staticClass, global::android.app.Dialog._requestWindowFeature510, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _setFeatureDrawableResource511; public virtual void setFeatureDrawableResource(int arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.app.Dialog._setFeatureDrawableResource511, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.app.Dialog.staticClass, global::android.app.Dialog._setFeatureDrawableResource511, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _setFeatureDrawableUri512; public virtual void setFeatureDrawableUri(int arg0, android.net.Uri arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.app.Dialog._setFeatureDrawableUri512, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.app.Dialog.staticClass, global::android.app.Dialog._setFeatureDrawableUri512, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _setFeatureDrawable513; public virtual void setFeatureDrawable(int arg0, android.graphics.drawable.Drawable arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.app.Dialog._setFeatureDrawable513, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.app.Dialog.staticClass, global::android.app.Dialog._setFeatureDrawable513, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _setFeatureDrawableAlpha514; public virtual void setFeatureDrawableAlpha(int arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.app.Dialog._setFeatureDrawableAlpha514, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.app.Dialog.staticClass, global::android.app.Dialog._setFeatureDrawableAlpha514, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _getLayoutInflater515; public virtual global::android.view.LayoutInflater getLayoutInflater() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.app.Dialog._getLayoutInflater515)) as android.view.LayoutInflater; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.app.Dialog.staticClass, global::android.app.Dialog._getLayoutInflater515)) as android.view.LayoutInflater; } internal static global::MonoJavaBridge.MethodId _setTitle516; public virtual void setTitle(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.app.Dialog._setTitle516, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.app.Dialog.staticClass, global::android.app.Dialog._setTitle516, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _setTitle517; public virtual void setTitle(java.lang.CharSequence arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.app.Dialog._setTitle517, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.app.Dialog.staticClass, global::android.app.Dialog._setTitle517, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } public void setTitle(string arg0) { setTitle((global::java.lang.CharSequence)(global::java.lang.String)arg0); } internal static global::MonoJavaBridge.MethodId _setVolumeControlStream518; public virtual void setVolumeControlStream(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.app.Dialog._setVolumeControlStream518, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.app.Dialog.staticClass, global::android.app.Dialog._setVolumeControlStream518, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getVolumeControlStream519; public virtual int getVolumeControlStream() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.app.Dialog._getVolumeControlStream519); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.app.Dialog.staticClass, global::android.app.Dialog._getVolumeControlStream519); } internal static global::MonoJavaBridge.MethodId _setOnKeyListener520; public virtual void setOnKeyListener(android.content.DialogInterface_OnKeyListener arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.app.Dialog._setOnKeyListener520, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.app.Dialog.staticClass, global::android.app.Dialog._setOnKeyListener520, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _setOwnerActivity521; public virtual void setOwnerActivity(android.app.Activity arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.app.Dialog._setOwnerActivity521, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.app.Dialog.staticClass, global::android.app.Dialog._setOwnerActivity521, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getOwnerActivity522; public virtual global::android.app.Activity getOwnerActivity() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.app.Dialog._getOwnerActivity522)) as android.app.Activity; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.app.Dialog.staticClass, global::android.app.Dialog._getOwnerActivity522)) as android.app.Activity; } internal static global::MonoJavaBridge.MethodId _isShowing523; public virtual bool isShowing() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.app.Dialog._isShowing523); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.app.Dialog.staticClass, global::android.app.Dialog._isShowing523); } internal static global::MonoJavaBridge.MethodId _show524; public virtual void show() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.app.Dialog._show524); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.app.Dialog.staticClass, global::android.app.Dialog._show524); } internal static global::MonoJavaBridge.MethodId _hide525; public virtual void hide() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.app.Dialog._hide525); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.app.Dialog.staticClass, global::android.app.Dialog._hide525); } internal static global::MonoJavaBridge.MethodId _dismiss526; public virtual void dismiss() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.app.Dialog._dismiss526); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.app.Dialog.staticClass, global::android.app.Dialog._dismiss526); } internal static global::MonoJavaBridge.MethodId _setCancelable527; public virtual void setCancelable(bool arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.app.Dialog._setCancelable527, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.app.Dialog.staticClass, global::android.app.Dialog._setCancelable527, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _setCanceledOnTouchOutside528; public virtual void setCanceledOnTouchOutside(bool arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.app.Dialog._setCanceledOnTouchOutside528, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.app.Dialog.staticClass, global::android.app.Dialog._setCanceledOnTouchOutside528, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _setOnCancelListener529; public virtual void setOnCancelListener(android.content.DialogInterface_OnCancelListener arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.app.Dialog._setOnCancelListener529, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.app.Dialog.staticClass, global::android.app.Dialog._setOnCancelListener529, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _setCancelMessage530; public virtual void setCancelMessage(android.os.Message arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.app.Dialog._setCancelMessage530, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.app.Dialog.staticClass, global::android.app.Dialog._setCancelMessage530, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _setOnDismissListener531; public virtual void setOnDismissListener(android.content.DialogInterface_OnDismissListener arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.app.Dialog._setOnDismissListener531, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.app.Dialog.staticClass, global::android.app.Dialog._setOnDismissListener531, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _setOnShowListener532; public virtual void setOnShowListener(android.content.DialogInterface_OnShowListener arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.app.Dialog._setOnShowListener532, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.app.Dialog.staticClass, global::android.app.Dialog._setOnShowListener532, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _setDismissMessage533; public virtual void setDismissMessage(android.os.Message arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.app.Dialog._setDismissMessage533, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.app.Dialog.staticClass, global::android.app.Dialog._setDismissMessage533, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _Dialog534; public Dialog(android.content.Context arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.app.Dialog.staticClass, global::android.app.Dialog._Dialog534, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); Init(@__env, handle); } internal static global::MonoJavaBridge.MethodId _Dialog535; public Dialog(android.content.Context arg0, int arg1) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.app.Dialog.staticClass, global::android.app.Dialog._Dialog535, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); Init(@__env, handle); } internal static global::MonoJavaBridge.MethodId _Dialog536; protected Dialog(android.content.Context arg0, bool arg1, android.content.DialogInterface_OnCancelListener arg2) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.app.Dialog.staticClass, global::android.app.Dialog._Dialog536, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); Init(@__env, handle); } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.app.Dialog.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/app/Dialog")); global::android.app.Dialog._getContext460 = @__env.GetMethodIDNoThrow(global::android.app.Dialog.staticClass, "getContext", "()Landroid/content/Context;"); global::android.app.Dialog._cancel461 = @__env.GetMethodIDNoThrow(global::android.app.Dialog.staticClass, "cancel", "()V"); global::android.app.Dialog._onCreate462 = @__env.GetMethodIDNoThrow(global::android.app.Dialog.staticClass, "onCreate", "(Landroid/os/Bundle;)V"); global::android.app.Dialog._onStart463 = @__env.GetMethodIDNoThrow(global::android.app.Dialog.staticClass, "onStart", "()V"); global::android.app.Dialog._getWindow464 = @__env.GetMethodIDNoThrow(global::android.app.Dialog.staticClass, "getWindow", "()Landroid/view/Window;"); global::android.app.Dialog._getCurrentFocus465 = @__env.GetMethodIDNoThrow(global::android.app.Dialog.staticClass, "getCurrentFocus", "()Landroid/view/View;"); global::android.app.Dialog._onRestoreInstanceState466 = @__env.GetMethodIDNoThrow(global::android.app.Dialog.staticClass, "onRestoreInstanceState", "(Landroid/os/Bundle;)V"); global::android.app.Dialog._onSaveInstanceState467 = @__env.GetMethodIDNoThrow(global::android.app.Dialog.staticClass, "onSaveInstanceState", "()Landroid/os/Bundle;"); global::android.app.Dialog._onStop468 = @__env.GetMethodIDNoThrow(global::android.app.Dialog.staticClass, "onStop", "()V"); global::android.app.Dialog._findViewById469 = @__env.GetMethodIDNoThrow(global::android.app.Dialog.staticClass, "findViewById", "(I)Landroid/view/View;"); global::android.app.Dialog._setContentView470 = @__env.GetMethodIDNoThrow(global::android.app.Dialog.staticClass, "setContentView", "(I)V"); global::android.app.Dialog._setContentView471 = @__env.GetMethodIDNoThrow(global::android.app.Dialog.staticClass, "setContentView", "(Landroid/view/View;)V"); global::android.app.Dialog._setContentView472 = @__env.GetMethodIDNoThrow(global::android.app.Dialog.staticClass, "setContentView", "(Landroid/view/View;Landroid/view/ViewGroup$LayoutParams;)V"); global::android.app.Dialog._addContentView473 = @__env.GetMethodIDNoThrow(global::android.app.Dialog.staticClass, "addContentView", "(Landroid/view/View;Landroid/view/ViewGroup$LayoutParams;)V"); global::android.app.Dialog._onKeyDown474 = @__env.GetMethodIDNoThrow(global::android.app.Dialog.staticClass, "onKeyDown", "(ILandroid/view/KeyEvent;)Z"); global::android.app.Dialog._onKeyLongPress475 = @__env.GetMethodIDNoThrow(global::android.app.Dialog.staticClass, "onKeyLongPress", "(ILandroid/view/KeyEvent;)Z"); global::android.app.Dialog._onKeyUp476 = @__env.GetMethodIDNoThrow(global::android.app.Dialog.staticClass, "onKeyUp", "(ILandroid/view/KeyEvent;)Z"); global::android.app.Dialog._onKeyMultiple477 = @__env.GetMethodIDNoThrow(global::android.app.Dialog.staticClass, "onKeyMultiple", "(IILandroid/view/KeyEvent;)Z"); global::android.app.Dialog._onBackPressed478 = @__env.GetMethodIDNoThrow(global::android.app.Dialog.staticClass, "onBackPressed", "()V"); global::android.app.Dialog._onTouchEvent479 = @__env.GetMethodIDNoThrow(global::android.app.Dialog.staticClass, "onTouchEvent", "(Landroid/view/MotionEvent;)Z"); global::android.app.Dialog._onTrackballEvent480 = @__env.GetMethodIDNoThrow(global::android.app.Dialog.staticClass, "onTrackballEvent", "(Landroid/view/MotionEvent;)Z"); global::android.app.Dialog._onWindowAttributesChanged481 = @__env.GetMethodIDNoThrow(global::android.app.Dialog.staticClass, "onWindowAttributesChanged", "(Landroid/view/WindowManager$LayoutParams;)V"); global::android.app.Dialog._onContentChanged482 = @__env.GetMethodIDNoThrow(global::android.app.Dialog.staticClass, "onContentChanged", "()V"); global::android.app.Dialog._onWindowFocusChanged483 = @__env.GetMethodIDNoThrow(global::android.app.Dialog.staticClass, "onWindowFocusChanged", "(Z)V"); global::android.app.Dialog._onAttachedToWindow484 = @__env.GetMethodIDNoThrow(global::android.app.Dialog.staticClass, "onAttachedToWindow", "()V"); global::android.app.Dialog._onDetachedFromWindow485 = @__env.GetMethodIDNoThrow(global::android.app.Dialog.staticClass, "onDetachedFromWindow", "()V"); global::android.app.Dialog._dispatchKeyEvent486 = @__env.GetMethodIDNoThrow(global::android.app.Dialog.staticClass, "dispatchKeyEvent", "(Landroid/view/KeyEvent;)Z"); global::android.app.Dialog._dispatchTouchEvent487 = @__env.GetMethodIDNoThrow(global::android.app.Dialog.staticClass, "dispatchTouchEvent", "(Landroid/view/MotionEvent;)Z"); global::android.app.Dialog._dispatchTrackballEvent488 = @__env.GetMethodIDNoThrow(global::android.app.Dialog.staticClass, "dispatchTrackballEvent", "(Landroid/view/MotionEvent;)Z"); global::android.app.Dialog._dispatchPopulateAccessibilityEvent489 = @__env.GetMethodIDNoThrow(global::android.app.Dialog.staticClass, "dispatchPopulateAccessibilityEvent", "(Landroid/view/accessibility/AccessibilityEvent;)Z"); global::android.app.Dialog._onCreatePanelView490 = @__env.GetMethodIDNoThrow(global::android.app.Dialog.staticClass, "onCreatePanelView", "(I)Landroid/view/View;"); global::android.app.Dialog._onCreatePanelMenu491 = @__env.GetMethodIDNoThrow(global::android.app.Dialog.staticClass, "onCreatePanelMenu", "(ILandroid/view/Menu;)Z"); global::android.app.Dialog._onPreparePanel492 = @__env.GetMethodIDNoThrow(global::android.app.Dialog.staticClass, "onPreparePanel", "(ILandroid/view/View;Landroid/view/Menu;)Z"); global::android.app.Dialog._onMenuOpened493 = @__env.GetMethodIDNoThrow(global::android.app.Dialog.staticClass, "onMenuOpened", "(ILandroid/view/Menu;)Z"); global::android.app.Dialog._onMenuItemSelected494 = @__env.GetMethodIDNoThrow(global::android.app.Dialog.staticClass, "onMenuItemSelected", "(ILandroid/view/MenuItem;)Z"); global::android.app.Dialog._onPanelClosed495 = @__env.GetMethodIDNoThrow(global::android.app.Dialog.staticClass, "onPanelClosed", "(ILandroid/view/Menu;)V"); global::android.app.Dialog._onCreateOptionsMenu496 = @__env.GetMethodIDNoThrow(global::android.app.Dialog.staticClass, "onCreateOptionsMenu", "(Landroid/view/Menu;)Z"); global::android.app.Dialog._onPrepareOptionsMenu497 = @__env.GetMethodIDNoThrow(global::android.app.Dialog.staticClass, "onPrepareOptionsMenu", "(Landroid/view/Menu;)Z"); global::android.app.Dialog._onOptionsItemSelected498 = @__env.GetMethodIDNoThrow(global::android.app.Dialog.staticClass, "onOptionsItemSelected", "(Landroid/view/MenuItem;)Z"); global::android.app.Dialog._onOptionsMenuClosed499 = @__env.GetMethodIDNoThrow(global::android.app.Dialog.staticClass, "onOptionsMenuClosed", "(Landroid/view/Menu;)V"); global::android.app.Dialog._openOptionsMenu500 = @__env.GetMethodIDNoThrow(global::android.app.Dialog.staticClass, "openOptionsMenu", "()V"); global::android.app.Dialog._closeOptionsMenu501 = @__env.GetMethodIDNoThrow(global::android.app.Dialog.staticClass, "closeOptionsMenu", "()V"); global::android.app.Dialog._onCreateContextMenu502 = @__env.GetMethodIDNoThrow(global::android.app.Dialog.staticClass, "onCreateContextMenu", "(Landroid/view/ContextMenu;Landroid/view/View;Landroid/view/ContextMenu$ContextMenuInfo;)V"); global::android.app.Dialog._registerForContextMenu503 = @__env.GetMethodIDNoThrow(global::android.app.Dialog.staticClass, "registerForContextMenu", "(Landroid/view/View;)V"); global::android.app.Dialog._unregisterForContextMenu504 = @__env.GetMethodIDNoThrow(global::android.app.Dialog.staticClass, "unregisterForContextMenu", "(Landroid/view/View;)V"); global::android.app.Dialog._openContextMenu505 = @__env.GetMethodIDNoThrow(global::android.app.Dialog.staticClass, "openContextMenu", "(Landroid/view/View;)V"); global::android.app.Dialog._onContextItemSelected506 = @__env.GetMethodIDNoThrow(global::android.app.Dialog.staticClass, "onContextItemSelected", "(Landroid/view/MenuItem;)Z"); global::android.app.Dialog._onContextMenuClosed507 = @__env.GetMethodIDNoThrow(global::android.app.Dialog.staticClass, "onContextMenuClosed", "(Landroid/view/Menu;)V"); global::android.app.Dialog._onSearchRequested508 = @__env.GetMethodIDNoThrow(global::android.app.Dialog.staticClass, "onSearchRequested", "()Z"); global::android.app.Dialog._takeKeyEvents509 = @__env.GetMethodIDNoThrow(global::android.app.Dialog.staticClass, "takeKeyEvents", "(Z)V"); global::android.app.Dialog._requestWindowFeature510 = @__env.GetMethodIDNoThrow(global::android.app.Dialog.staticClass, "requestWindowFeature", "(I)Z"); global::android.app.Dialog._setFeatureDrawableResource511 = @__env.GetMethodIDNoThrow(global::android.app.Dialog.staticClass, "setFeatureDrawableResource", "(II)V"); global::android.app.Dialog._setFeatureDrawableUri512 = @__env.GetMethodIDNoThrow(global::android.app.Dialog.staticClass, "setFeatureDrawableUri", "(ILandroid/net/Uri;)V"); global::android.app.Dialog._setFeatureDrawable513 = @__env.GetMethodIDNoThrow(global::android.app.Dialog.staticClass, "setFeatureDrawable", "(ILandroid/graphics/drawable/Drawable;)V"); global::android.app.Dialog._setFeatureDrawableAlpha514 = @__env.GetMethodIDNoThrow(global::android.app.Dialog.staticClass, "setFeatureDrawableAlpha", "(II)V"); global::android.app.Dialog._getLayoutInflater515 = @__env.GetMethodIDNoThrow(global::android.app.Dialog.staticClass, "getLayoutInflater", "()Landroid/view/LayoutInflater;"); global::android.app.Dialog._setTitle516 = @__env.GetMethodIDNoThrow(global::android.app.Dialog.staticClass, "setTitle", "(I)V"); global::android.app.Dialog._setTitle517 = @__env.GetMethodIDNoThrow(global::android.app.Dialog.staticClass, "setTitle", "(Ljava/lang/CharSequence;)V"); global::android.app.Dialog._setVolumeControlStream518 = @__env.GetMethodIDNoThrow(global::android.app.Dialog.staticClass, "setVolumeControlStream", "(I)V"); global::android.app.Dialog._getVolumeControlStream519 = @__env.GetMethodIDNoThrow(global::android.app.Dialog.staticClass, "getVolumeControlStream", "()I"); global::android.app.Dialog._setOnKeyListener520 = @__env.GetMethodIDNoThrow(global::android.app.Dialog.staticClass, "setOnKeyListener", "(Landroid/content/DialogInterface$OnKeyListener;)V"); global::android.app.Dialog._setOwnerActivity521 = @__env.GetMethodIDNoThrow(global::android.app.Dialog.staticClass, "setOwnerActivity", "(Landroid/app/Activity;)V"); global::android.app.Dialog._getOwnerActivity522 = @__env.GetMethodIDNoThrow(global::android.app.Dialog.staticClass, "getOwnerActivity", "()Landroid/app/Activity;"); global::android.app.Dialog._isShowing523 = @__env.GetMethodIDNoThrow(global::android.app.Dialog.staticClass, "isShowing", "()Z"); global::android.app.Dialog._show524 = @__env.GetMethodIDNoThrow(global::android.app.Dialog.staticClass, "show", "()V"); global::android.app.Dialog._hide525 = @__env.GetMethodIDNoThrow(global::android.app.Dialog.staticClass, "hide", "()V"); global::android.app.Dialog._dismiss526 = @__env.GetMethodIDNoThrow(global::android.app.Dialog.staticClass, "dismiss", "()V"); global::android.app.Dialog._setCancelable527 = @__env.GetMethodIDNoThrow(global::android.app.Dialog.staticClass, "setCancelable", "(Z)V"); global::android.app.Dialog._setCanceledOnTouchOutside528 = @__env.GetMethodIDNoThrow(global::android.app.Dialog.staticClass, "setCanceledOnTouchOutside", "(Z)V"); global::android.app.Dialog._setOnCancelListener529 = @__env.GetMethodIDNoThrow(global::android.app.Dialog.staticClass, "setOnCancelListener", "(Landroid/content/DialogInterface$OnCancelListener;)V"); global::android.app.Dialog._setCancelMessage530 = @__env.GetMethodIDNoThrow(global::android.app.Dialog.staticClass, "setCancelMessage", "(Landroid/os/Message;)V"); global::android.app.Dialog._setOnDismissListener531 = @__env.GetMethodIDNoThrow(global::android.app.Dialog.staticClass, "setOnDismissListener", "(Landroid/content/DialogInterface$OnDismissListener;)V"); global::android.app.Dialog._setOnShowListener532 = @__env.GetMethodIDNoThrow(global::android.app.Dialog.staticClass, "setOnShowListener", "(Landroid/content/DialogInterface$OnShowListener;)V"); global::android.app.Dialog._setDismissMessage533 = @__env.GetMethodIDNoThrow(global::android.app.Dialog.staticClass, "setDismissMessage", "(Landroid/os/Message;)V"); global::android.app.Dialog._Dialog534 = @__env.GetMethodIDNoThrow(global::android.app.Dialog.staticClass, "<init>", "(Landroid/content/Context;)V"); global::android.app.Dialog._Dialog535 = @__env.GetMethodIDNoThrow(global::android.app.Dialog.staticClass, "<init>", "(Landroid/content/Context;I)V"); global::android.app.Dialog._Dialog536 = @__env.GetMethodIDNoThrow(global::android.app.Dialog.staticClass, "<init>", "(Landroid/content/Context;ZLandroid/content/DialogInterface$OnCancelListener;)V"); } } }
// Copyright (C) 2014 dot42 // // Original filename: HttpWebRequest.cs // // 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.IO; using System.Net.Cache; using Android.Net.Http; using Android.Util; using Org.Apache.Http; using Org.Apache.Http.Client.Methods; using Org.Apache.Http.Client.Params; using Org.Apache.Http.Entity; using Org.Apache.Http.Message; using Org.Apache.Http.Params; namespace System.Net { /// <summary> /// Provides an HTTP-specific implementation of the WebRequest class. /// </summary> public class HttpWebRequest : WebRequest { private Uri _requestUri; private Uri _address; private Stream _requestStream; private HttpRequestBase _request; static HttpWebRequest() { DefaultMaximumErrorResponseLength = -1; } internal HttpWebRequest(Uri requestUri) { _requestUri = requestUri; Headers = new WebHeaderCollection(); MaximumAutomaticRedirections = 50; AllowAutoRedirect = true; AllowWriteStreamBuffering = true; Timeout = 100000; //(100 Seconds) Method = "GET"; ProtocolVersion = HttpVersion.Version11; } /// <summary> /// Gets or sets the value of the Accept HTTP header. /// </summary> public string Accept { get { return Headers[HttpRequestHeader.Accept]; } set { Headers[HttpRequestHeader.Accept ] = value; } } /// <summary> /// Gets the Uniform Resource Identifier (URI) of the Internet resource that actually responds to the request. /// </summary> public Uri Address { get { return _address; } } /// <summary> /// Whether the request should follow redirection responses (default is true). /// </summary> public bool AllowAutoRedirect { get; set; } /// <summary> /// Whether to buffer the data sent to the Internet resource (default is true). /// </summary> public bool AllowWriteStreamBuffering { get; set; } /// <summary> /// The type of decompression that is used. /// </summary> public DecompressionMethods AutomaticDecompression { get; set; } /* /// <summary> /// The collection of security certificates that are associated with this request. /// </summary> public X509CertificateCollection ClientCertificates { get; set; } */ /// <summary> /// The value of the Connection HTTP header. /// </summary> public string Connection { get { return Headers[HttpRequestHeader.Connection]; } set { Headers[HttpRequestHeader.Connection] = value; } } /// <summary> /// the name of the connection group for the request (default = null). /// </summary> public override string ConnectionGroupName { get; set; } /// <summary> /// The Content-length HTTP header (default = -1, meaning no request data to send). /// </summary> public override long ContentLength { get { var contentLength = Headers[HttpRequestHeader.ContentLength]; if (string.IsNullOrEmpty(contentLength)) return -1L; return long.Parse(contentLength); } set { Headers.Set(HttpRequestHeader.ContentLength, value.ToString()); } } /// <summary> /// he value of the Content-type HTTP header (default = null). /// </summary> public override string ContentType { get { return Headers[HttpRequestHeader.ContentType]; } set { Headers[HttpRequestHeader.ContentType] = value; } } /// <summary> /// The delegate method called when an HTTP 100-continue response is received from the Internet resource. /// </summary> public HttpContinueDelegate ContinueDelegate { get; set; } /* /// <summary> /// The cookies associated with the request. /// </summary> public CookieContainer CookieContainer { get; set; } */ /// <summary> /// The authentication information for the request (default = null). /// </summary> public override ICredentials Credentials { get; set; } /// <summary> /// The Date HTTP header value to use in an HTTP request. /// </summary> public DateTime Date { get { var date = Headers[HttpRequestHeader.Date]; if (string.IsNullOrEmpty(date)) return DateTime.MinValue; return DateTime.Parse(date); } set { Headers[HttpRequestHeader.Date] = value.ToString(); } } /// <summary> /// The default cache policy for this request. /// </summary> public static RequestCachePolicy DefaultCachePolicy { get; set; } /// <summary> /// The default maximum length of an HTTP error response (defualt is -1, meaning unlimited). /// </summary> public static int DefaultMaximumErrorResponseLength { get; set; } /// <summary> /// The default for the MaximumResponseHeadersLength property. /// </summary> public static int DefaultMaximumResponseHeadersLength { get; set; } /// <summary> /// The value of the Expect HTTP header. /// </summary> public string Expect { get { return Headers[HttpRequestHeader.Expect]; } set { Headers[HttpRequestHeader.Expect] = value; } } /// <summary> /// Whether a response has been received from an Internet resource. /// </summary> public bool HaveResponse { get { return _address != null; } } /// <summary> /// Specifies a collection of the name/value pairs that make up the HTTP headers. /// </summary> public override WebHeaderCollection Headers { get; set; } /// <summary> /// The Host header value to use in an HTTP request independent from the request URI. /// </summary> public string Host { get; set; } /// <summary> /// The value of the If-Modified-Since HTTP header (default is current). /// </summary> public DateTime IfModifiedSince { get { var date = Headers[HttpRequestHeader.Date]; if (string.IsNullOrEmpty(date)) return DateTime.Now; return DateTime.Parse(date); } set { Headers[HttpRequestHeader.Date] = value.ToString(); } } /// <summary> /// Whether to make a persistent connection to the Internet resource (default = true). /// </summary> public bool KeepAlive { get { var keepAlive = Headers[HttpRequestHeader.KeepAlive]; if (string.IsNullOrEmpty(keepAlive)) return true; return bool.Parse(keepAlive); } set { Headers[HttpRequestHeader.Date] = value.ToString(); } } /// <summary> /// The maximum number of redirects that the request follows (default = 50). /// </summary> public int MaximumAutomaticRedirections { get; set; } /// <summary> /// the maximum allowed length of the response headers (in kilobytes; default = -1) /// </summary> public int MaximumResponseHeadersLength { get; set; } /// <summary> /// The media type of the request. /// </summary> public string MediaType { get; set; } /// <summary> /// The method for the request (default = GET). /// </summary> public override string Method { get; set; } /// <summary> /// whether to pipeline the request to the Internet resource. /// </summary> public bool Pipelined { get; set; } /// <summary> /// Whether to send an Authorization header with the request. /// </summary> public override bool PreAuthenticate { get; set; } /// <summary> /// The version of HTTP to use for the request (default = Version 1.1) /// </summary> public Version ProtocolVersion { get; set; } /// <summary> /// Proxy information for the request. /// </summary> public override IWebProxy Proxy { get; set; } /// <summary> /// The time-out in milliseconds when writing to or reading from a stream (default = 300.000 [5 min]). /// </summary> public int ReadWriteTimeout { get; set; } /// <summary> /// The value of the Referer HTTP header (default = null). /// </summary> public string Referer { get { return Headers[HttpRequestHeader.Referer]; } set { Headers[HttpRequestHeader.Referer] = value; } } // // Summary: // Gets the original Uniform Resource Identifier (URI) of the request. // // Returns: // A System.Uri that contains the URI of the Internet resource passed to the // System.Net.WebRequest.Create(System.String) method. public override Uri RequestUri { get { return _requestUri; } } /// <summary> /// Whether to send data in segments to the Internet resource (default = false). /// </summary> public bool SendChunked { get; set; } /* /// <summary> /// The service point to use for the request. /// </summary> public ServicePoint ServicePoint { get; } */ /// <summary> /// the time-out value in milliseconds for the GetResponse() GetRequestStream() methods (default = 100,000 [100 seconds]). /// </summary> public override int Timeout { get; set; } /// <summary> /// The value of the Transfer-encoding HTTP header. /// </summary> public string TransferEncoding { get { return Headers[HttpRequestHeader.TransferEncoding]; } set { Headers[HttpRequestHeader.TransferEncoding] = value; } } /// <summary> /// Whether to allow high-speed NTLM-authenticated connection sharing. /// </summary> public bool UnsafeAuthenticatedConnectionSharing { get; set; } /// <summary> /// Whether default credentials are sent with requests (default = false). /// </summary> public override bool UseDefaultCredentials { get; set; } /// <summary> /// The value of the User-agent HTTP header. /// </summary> public string UserAgent { get { return Headers[HttpRequestHeader.UserAgent]; } set { Headers[HttpRequestHeader.UserAgent ] = value; } } /// <summary> /// Cancels a request to an Internet resource. /// </summary> public override void Abort() { if (_request != null) _request.Abort(); } /// <summary> /// Adds a byte range header to a request for a specific range from the beginning or end of the requested data. /// </summary> /// <param name="range"></param> public void AddRange(int range) { throw new NotImplementedException(); } /// <summary> /// Adds a byte range header to a request for a specific range from the beginning or end of the requested data. /// </summary> /// <param name="range"></param> public void AddRange(long range) { throw new NotImplementedException(); } /// <summary> /// Adds a byte range header to the request for a specified range. /// </summary> public void AddRange(int from, int to) { throw new NotImplementedException(); } /// <summary> /// Adds a byte range header to the request for a specified range. /// </summary> public void AddRange(long from, long to) { throw new NotImplementedException(); } /// <summary> /// Adds a Range header to a request for a specific range from the beginning or end of the requested data. /// </summary> public void AddRange(string rangeSpecifier, int range) { throw new NotImplementedException(); } /// <summary> /// Adds a Range header to a request for a specific range from the beginning or end of the requested data. /// </summary> /// <param name="rangeSpecifier"></param> /// <param name="range"></param> public void AddRange(string rangeSpecifier, long range) { throw new NotImplementedException(); } /// <summary> /// Adds a range header to a request for a specified range. /// </summary> /// <param name="rangeSpecifier"></param> /// <param name="from"></param> /// <param name="to"></param> public void AddRange(string rangeSpecifier, int from, int to) { throw new NotImplementedException(); } /// <summary> /// Adds a range header to a request for a specified range. /// </summary> public void AddRange(string rangeSpecifier, long from, long to) { throw new NotImplementedException(); } /// <summary> /// Begins an asynchronous request for a System.IO.Stream object to use to write data. /// </summary> public override IAsyncResult BeginGetRequestStream(AsyncCallback callback, object state) { throw new NotImplementedException(); } /// <summary> /// Begins an asynchronous request to an Internet resource. /// </summary> public override IAsyncResult BeginGetResponse(AsyncCallback callback, object state) { throw new NotImplementedException(); } /// <summary> /// Ends an asynchronous request for a Stream object to use to write data. /// </summary> public override Stream EndGetRequestStream(IAsyncResult asyncResult) { throw new NotImplementedException(); } /* /// <summary> /// Ends an asynchronous request to an Internet resource and outputs the context. /// </summary> public Stream EndGetRequestStream(IAsyncResult asyncResult, out TransportContext context); */ /// <summary> /// Ends an asynchronous request to an Internet resource. /// </summary> public override WebResponse EndGetResponse(IAsyncResult asyncResult) { throw new NotImplementedException(); } /// <summary> /// Gets a Stream object to use to write request data. /// </summary> public override Stream GetRequestStream() { return _requestStream ?? (_requestStream = new MemoryStream()); } /* /// <summary> /// Gets a Stream object to use to write request data and outputs the context. /// </summary> public Stream GetRequestStream(out TransportContext context); */ /// <summary> /// Returns a response from an Internet resource. /// </summary> /// <remarks> /// You must close the returned response to avoid socket and memory leaks. /// </remarks> public override WebResponse GetResponse() { #if ANDROID_8P var method = this.Method.ToLower(); switch (method) { case "get": _request = new HttpGet(); break; case "post": _request = new HttpPost(); break; case "put": _request = new HttpPut(); break; case "delete": _request = new HttpDelete(); break; default: //the switch below is to prevent a C# compiler bug with 7 case statements. switch (method) { case "options": _request = new HttpOptions(); break; case "head": _request = new HttpHead(); break; case "trace": _request = new HttpTrace(); break; default: throw new NotSupportedException(string.Format("Unsupported Method: {0}", this.Method)); } break; } _request.SetURI(_requestUri); if (ContentLength != -1) { var entityRequest = _request as HttpEntityEnclosingRequestBase; if (entityRequest == null) throw new NotSupportedException(string.Format("Method: {0} does not support a request stream", this.Method)); if (_requestStream.Length < ContentLength) throw new ArgumentException( string.Format("ContentLength={0}, however the request stream contains only {1} bytes", ContentLength, _requestStream.Length)); _requestStream.Seek(0L, SeekOrigin.Begin); entityRequest.SetEntity(new InputStreamEntity(_requestStream, ContentLength)); } if (Headers != null) { var count = Headers.Count; for (var i = 0; i < count; i++) { var key = Headers.GetKey(i); if (key != "content-length") //The content length is set above. _request.AddHeader(key, Headers.Get(i)); } } AndroidHttpClient client = null; try { client = AndroidHttpClient.NewInstance(UserAgent); HttpClientParams.SetRedirecting(client.GetParams(), this.AllowAutoRedirect); var response = client.Execute(_request); if (response == null) { throw new Exception("Response is null"); } var header = response.GetFirstHeader(WebHeaderCollection.HeaderToString(HttpResponseHeader.Location)); var uri = header != null ? header.GetValue() : null; _address = new Uri(!string.IsNullOrEmpty(uri) ? uri : _requestUri.ToString()); var result = new HttpWebResponse(this, response, client); client = null; // So we won't release it, HttpWebResponse should now release it. return result; } finally { if(client != null) client.Close(); } #else throw new NotSupportedException("The HttpWebRequest is not supported on Android v2.1, but available as of v2.2"); #endif } } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. using System; using System.Linq; using System.Linq.Expressions; using System.Collections.Generic; using Microsoft.Research.AbstractDomains; using System.Diagnostics.Contracts; using Microsoft.Research.DataStructures; using Microsoft.Research.AbstractDomains.Expressions; using Microsoft.Research.AbstractDomains.Numerical; namespace Microsoft.Research.CodeAnalysis { public static partial class AnalysisWrapper { public static SyntacticInformation<Method, Field, Variable> RunDisjunctionRecoveryAnalysis<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Expression, Variable> ( string methodName, IMethodDriver<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Expression, Variable, ILogOptions> driver, Predicate<APC> cachePCs ) where Variable : IEquatable<Variable> where Expression : IEquatable<Expression> where Type : IEquatable<Type> { Contract.Requires(driver != null); var analysis = new TypeBindings<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Expression, Variable>.DisjunctionsRecoveryAnalysis (methodName, driver, cachePCs); var closure = driver.HybridLayer.CreateForward<TypeBindings<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Expression, Variable>.DisjunctiveRefinement>( analysis, new DFAOptions { Trace = driver.Options.TraceDFA, Timeout = driver.Options.Timeout, EnforceFairJoin = driver.Options.EnforceFairJoin, IterationsBeforeWidening = driver.Options.IterationsBeforeWidening, TraceTimePerInstruction = driver.Options.TraceTimings, TraceMemoryPerInstruction = driver.Options.TraceMemoryConsumption }, null); closure(analysis.GetTopValue()); // Do the analysis analysis.ClearCaches(); return new SyntacticInformation<Method,Field, Variable>(analysis, analysis.Tests, analysis.RightExpressions, analysis.FirstViewAt, analysis.MayUpdateFields, analysis.MethodCalls, analysis.liveVariablesInRenamings, analysis.RenamingsLength, analysis.HasThrow, analysis.HasExceptionHandlers); } #region Void Options public class VoidOptions : IValueAnalysisOptions { readonly private ILogOptions options; public VoidOptions(ILogOptions options) { Contract.Requires(options != null); this.options = options; } public ILogOptions LogOptions { get { return this.options; } } public bool NoProofObligations { get { return false; } } public int Steps { get { return 0; } } public ReductionAlgorithm Algorithm { get { return ReductionAlgorithm.None; } } public bool Use2DConvexHull { get { return false; } } public bool InferOctagonConstraints { get { return false; } } public bool UseMorePreciseWidening { get { return false; } } public bool UseTracePartitioning { get { return false; } } public bool TrackDisequalities { get { return false; } } public bool TracePartitionAnalysis { get { return false; } } public bool TraceNumericalAnalysis { get { return false; } } } #endregion /// <summary> /// This class is just for binding types for the internal clases /// </summary> public static partial class TypeBindings<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Expression, Variable> where Variable : IEquatable<Variable> where Expression : IEquatable<Expression> where Type : IEquatable<Type> { public class DisjunctionsRecoveryAnalysis : GenericValueAnalysis<DisjunctiveRefinement, VoidOptions>, IDisjunctiveExpressionRefiner<Variable, BoxedExpression> { #region Consts const int MAXDEPTH = 15; #endregion #region Object invariant [ContractInvariantMethod] private void ObjectInvariant() { Contract.Invariant(this.Tests != null); Contract.Invariant(this.liveVariablesInRenamings != null); } #endregion #region State readonly public List<SyntacticTest> Tests; readonly public List<RightExpression> RightExpressions; readonly public Dictionary<Variable, APC> FirstViewAt; readonly public List<Field> MayUpdateFields; readonly public List<MethodCallInfo<Method, Variable>> MethodCalls; readonly public Set<string> StringsForPostconditions; readonly public List<Tuple<Pair<APC, APC>, Dictionary<Variable, HashSet<Variable>>>> liveVariablesInRenamings; readonly public List<Tuple<Pair<APC, APC>, int>> RenamingsLength; public bool HasThrow { get; private set; } public bool HasExceptionHandlers { get; private set; } #endregion #region Constructor public DisjunctionsRecoveryAnalysis( string methodName, IMethodDriver<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Expression, Variable, ILogOptions> mdriver, Predicate<APC> cachePCs) : base(methodName, mdriver, new VoidOptions(mdriver.Options), cachePCs) { this.Tests = new List<SyntacticTest>(); this.RightExpressions = new List<RightExpression>(); this.FirstViewAt = new Dictionary<Variable, APC>(); this.MayUpdateFields = new List<Field>(); this.MethodCalls = new List<MethodCallInfo<Method, Variable>>(); this.StringsForPostconditions = new Set<string>(); this.liveVariablesInRenamings = new List<Tuple<Pair<APC, APC>, Dictionary<Variable, HashSet<Variable>>>>(); this.RenamingsLength = new List<Tuple<Pair<APC, APC>, int>>(); this.HasThrow = false; } #endregion #region Transfer functions public override DisjunctiveRefinement Assume(APC pc, string tag, Variable source, object provenance, DisjunctiveRefinement data) { Contract.Assume(data != null); this.InferExceptionHandlers(pc); var refinedExp = new LazyEval<BoxedExpression>( () => BoxedExpression.Convert(this.Context.ExpressionContext.Refine(pc, source), this.MethodDriver.ExpressionDecoder, MAXDEPTH)); if (tag != "false") { var toRefine = source; // in clousot1 we refine "assume refinedExp". // in clousot2 we refinedExp may be exp != 0 and in this case we refine "assume exp" if (!this.MethodDriver.SyntacticComplexity.TooManyJoinsForBackwardsChecking && refinedExp.Value != null && CanRefineAVariableTruthValue(refinedExp.Value, ref toRefine)) { Log("Trying to refine the variable {0} to one containing logical connectives", refinedExp.Value.UnderlyingVariable.ToString); BoxedExpression refinedExpWithConnectives; if (TryToBoxedExpressionWithBooleanConnectives(pc, tag, toRefine, false, TopNumericalDomain<BoxedVariable<Variable>, BoxedExpression>.Singleton, out refinedExpWithConnectives)) { Log("Succeeded. Got {0}", refinedExpWithConnectives.ToString); data[new BoxedVariable<Variable>(source)] = new SetOfConstraints<BoxedExpression>(refinedExpWithConnectives); } } } APC pcForExpression; if (!this.FirstViewAt.TryGetValue(source, out pcForExpression)) { pcForExpression = pc; } this.Tests.Add(new SyntacticTest(SyntacticTest.Polarity.Assume, pcForExpression, tag, refinedExp)); // We do not call the base Assume as it performs too many things not needed here return data; } private bool CanRefineAVariableTruthValue(BoxedExpression exp, ref Variable v) { Contract.Requires(exp != null); if (exp.IsVariable) { return true; } BinaryOperator bop; int k; return exp.IsCheckExpOpConst(out bop, out v, out k) && ( (bop == BinaryOperator.Ceq && k != 0) || (bop == BinaryOperator.Cne_Un && k == 0)); } public override DisjunctiveRefinement Assert(APC pc, string tag, Variable condition, object provenance, DisjunctiveRefinement data) { this.InferExceptionHandlers(pc); var md = this.MethodDriver; Func<BoxedExpression> closure = () => { BoxedExpression newPost; if ( (newPost = md.AsExistsIndexed(pc, condition)) != null || (newPost = md.AsForAllIndexed(pc, condition)) != null) { return newPost; } else { return BoxedExpression.Convert(this.Context.ExpressionContext.Refine(pc, condition), md.ExpressionDecoder, MAXDEPTH, false); } }; this.Tests.Add(new SyntacticTest(SyntacticTest.Polarity.Assert, pc, tag, new LazyEval<BoxedExpression>(closure))); return this.Assume(pc, tag, condition, provenance, data); } public override DisjunctiveRefinement Binary(APC pc, BinaryOperator op, Variable dest, Variable s1, Variable s2, DisjunctiveRefinement data) { this.InferExceptionHandlers(pc); // We want to save the PC where "dest" first appeared. // We will need this information in the code fixes, because we need the expression source context, and not the statement where it appears if (!this.FirstViewAt.ContainsKey(dest)) { this.FirstViewAt[dest] = pc; } if (!op.IsComparisonBinaryOperator()) { var rValueExp = new LazyEval<BoxedExpression>( () => { var left = BoxedExpression.Convert(this.Context.ExpressionContext.Refine(pc, s1), this.MethodDriver.ExpressionDecoder, MAXDEPTH); var right = BoxedExpression.Convert(this.Context.ExpressionContext.Refine(pc, s2), this.MethodDriver.ExpressionDecoder, MAXDEPTH); // conversion may fail, so let us check it return (left != null && right != null)? BoxedExpression.Binary(op, left, right, dest) : null; }); this.RightExpressions.Add(new RightExpression(pc, rValueExp)); } return data; } public override DisjunctiveRefinement Throw(APC pc, Variable exn, DisjunctiveRefinement data) { this.HasThrow = true; this.InferExceptionHandlers(pc); return base.Throw(pc, exn, data); } public override DisjunctiveRefinement Ldelem(APC pc, Type type, Variable dest, Variable array, Variable index, DisjunctiveRefinement data) { this.InferExceptionHandlers(pc); data[new BoxedVariable<Variable>(dest)] = new SetOfConstraints<BoxedExpression>(new BoxedExpression.ArrayIndexExpression<Type>(ToBoxedExpression(pc, array), ToBoxedExpression(pc, index), type)); return data; } public override DisjunctiveRefinement Stfld(APC pc, Field field, bool @volatile, Variable obj, Variable value, DisjunctiveRefinement data) { this.InferExceptionHandlers(pc); this.MayUpdateFields.Add(field); return data; } public override DisjunctiveRefinement Call<TypeList, ArgList>(APC pc, Method method, bool tail, bool virt, TypeList extraVarargs, Variable dest, ArgList args, DisjunctiveRefinement data) { this.InferExceptionHandlers(pc); var asForAll = this.MethodDriver.AsForAllIndexed(pc.Post(), dest); if (asForAll != null) { data[new BoxedVariable<Variable>(dest)] = new SetOfConstraints<BoxedExpression>(asForAll); } else { this.MethodCalls.Add(new MethodCallInfo<Method, Variable>(pc, method, args.Enumerate().ToList())); } return data; } public override DisjunctiveRefinement Return(APC pc, Variable source, DisjunctiveRefinement data) { this.InferExceptionHandlers(pc); var md = this.MethodDriver; var mdd = md.MetaDataDecoder; BoxedExpression refinedExpWithConnectives; if (!mdd.System_Void.Equals(mdd.ReturnType(md.CurrentMethod)) && TryToBoxedExpressionWithBooleanConnectives(pc, "ret", source, true, TopNumericalDomain<BoxedVariable<Variable>, BoxedExpression>.Singleton, out refinedExpWithConnectives)) { Log("Succeeded. Got {0}", refinedExpWithConnectives.ToString); data[new BoxedVariable<Variable>(source)] = new SetOfConstraints<BoxedExpression>(refinedExpWithConnectives); } return data; } public override DisjunctiveRefinement HelperForAssignInParallel(DisjunctiveRefinement state, Pair<APC, APC> edge, Dictionary<BoxedVariable<Variable>, FList<BoxedVariable<Variable>>> refinedMap, Converter<BoxedVariable<Variable>, BoxedExpression> convert) { if(refinedMap != null) { this.RenamingsLength.Add(new Tuple<Pair<APC, APC>, int>(edge, refinedMap.Count)); } return state.AssignInParallelFunctional(refinedMap, convert); } public override DisjunctiveRefinement Join(Pair<APC, APC> edge, DisjunctiveRefinement newState, DisjunctiveRefinement prevState, out bool changed, bool widen) { // this.SaveRenamings(edge, prevState.varsInAssignment, newState.varsInAssignment); return base.Join(edge, newState, prevState, out changed, widen); } protected override DisjunctiveRefinement Default(APC pc, DisjunctiveRefinement data) { this.InferExceptionHandlers(pc); return base.Default(pc, data); } private void SaveRenamings(Pair<APC, APC> edge, Dictionary<Variable, HashSet<Variable>> dictionary1, Dictionary<Variable, HashSet<Variable>> dictionary2) { this.liveVariablesInRenamings.Add(new Tuple<Pair<APC, APC>, Dictionary<Variable, HashSet<Variable>>>(edge, dictionary1)); this.liveVariablesInRenamings.Add(new Tuple<Pair<APC, APC>, Dictionary<Variable, HashSet<Variable>>>(edge, dictionary2)); } #endregion #region Overridden public override bool SuggestAnalysisSpecificPostconditions(ContractInferenceManager inferenceManager, IFixpointInfo<APC, DisjunctiveRefinement> fixpointInfo, List<BoxedExpression> postconditions) { // does nothing return false; } public override bool TrySuggestPostconditionForOutParameters(IFixpointInfo<APC, DisjunctiveRefinement> fixpointInfo, List<BoxedExpression> postconditions, Variable p, FList<PathElement> path) { // does nothing return false; } public override DisjunctiveRefinement GetTopValue() { return new DisjunctiveRefinement(this.ExpressionManager); } public override IFactQuery<BoxedExpression, Variable> FactQuery(IFixpointInfo<APC, DisjunctiveRefinement> fixpoint) { return null; } #endregion #region IDisjunctiveExpressionRefined public bool TryRefineExpression(APC pc, Variable toRefine, out BoxedExpression refined) { DisjunctiveRefinement state; if (PreStateLookup(pc, out state)) { SetOfConstraints<BoxedExpression> candidates; if (state.TryGetValue(new BoxedVariable<Variable>(toRefine), out candidates) && candidates.IsNormal() && candidates.Count == 1) { refined = candidates.Values.First(); return refined != null; } } refined = null; return false; } public bool TryApplyModusPonens(APC pc, BoxedExpression premise, Predicate<BoxedExpression> IsTrue, out List<BoxedExpression> consequences) { DisjunctiveRefinement state; if (PreStateLookup(pc, out state)) { return state.TryApplyModusPonens(premise, IsTrue, out consequences); } consequences = null; return false; } #endregion #region Info private void InferExceptionHandlers(APC pc) { if (this.HasExceptionHandlers) { return; } var handlers = this.Context.MethodContext.CFG.ExceptionHandlers<int, int>(pc, 0, null); foreach (var h in handlers) { if (!pc.Block.Subroutine.ExceptionExit.Equals(h.Block)) { this.HasExceptionHandlers = true; return; } } } #endregion } #region Abstract domain public class DisjunctiveRefinement : FunctionalAbstractDomainEnvironment<DisjunctiveRefinement, BoxedVariable<Variable>, SetOfConstraints<BoxedExpression>, BoxedVariable<Variable>, BoxedExpression> { #region ExtraState public readonly Dictionary<Variable, HashSet<Variable>> varsInAssignment = null; #endregion #region Constructor public DisjunctiveRefinement(ExpressionManager<BoxedVariable<Variable>, BoxedExpression> expManager) : base(expManager) { Contract.Requires(expManager != null); } private DisjunctiveRefinement(DisjunctiveRefinement other, Dictionary<Variable, HashSet<Variable>> vars) : this(other) { Contract.Requires(other != null); this.varsInAssignment = vars; } private DisjunctiveRefinement(DisjunctiveRefinement other) : base(other) { } #endregion #region Abstract Domain specific public IEnumerable<BoxedExpression> Disjunctions { get { if (this.IsNormal()) { foreach (var pair in this.Elements) { if (pair.Value.IsNormal()) { foreach (var exp in pair.Value.Values) { yield return exp; } } } } } } public bool TryApplyModusPonens(BoxedExpression premise, Predicate<BoxedExpression> oracle, out List<BoxedExpression> consequences) { Contract.Requires(premise != null); Contract.Ensures(!Contract.Result<bool>() || Contract.ValueAtReturn(out consequences) != null); if (this.IsNormal()) { consequences = new List<BoxedExpression>(); foreach (var exp in this.Disjunctions) { BinaryOperator bop; BoxedExpression left, right; if (exp.IsBinaryExpression(out bop, out left, out right) && bop == BinaryOperator.LogicalOr) { left = RemoveKnownFacts(left, oracle); right = RemoveKnownFacts(right, oracle); if (left != null && this.ExtendedExpressionEquals(left, premise)) { consequences.AddIfNotNull(RemoveShortCutExpression(right, premise)); } else if (right != null && this.ExtendedExpressionEquals(right, premise)) { consequences.AddIfNotNull(RemoveShortCutExpression(left, premise)); } } } return consequences.Count != 0; } consequences = null; return false; } private BoxedExpression RemoveKnownFacts(BoxedExpression original, Predicate<BoxedExpression> isKnown) { if (isKnown == null) { return original; } var splitted = original.SplitConjunctions(); BoxedExpression result = null; foreach (var exp in splitted) { if (exp == null || isKnown(exp)) { continue; } result = result == null ? exp : BoxedExpression.Binary(BinaryOperator.LogicalAnd, result, exp); } return result; } /// <summary> /// Because of shortcut we may have P && !premise /// </summary> private BoxedExpression RemoveShortCutExpression(BoxedExpression exp, BoxedExpression premise) { if (exp == null) { return null; } BinaryOperator bop; BoxedExpression left, right; if (exp.IsBinaryExpression(out bop, out left, out right) && bop == BinaryOperator.LogicalAnd) { var negatedPremise = premise.Negate(); if (left.Equals(negatedPremise)) { return right; } else if (right.Equals(negatedPremise)) { return left; } } return exp; } private bool ExtendedExpressionEquals(BoxedExpression e1, BoxedExpression e2) { if (e1 == null || e2 == null) { return false; } if (e1.Equals(e2)) { return true; } UnaryOperator uop1, uop2; BoxedExpression inner1, inner2; if (e1.IsUnaryExpression(out uop1, out inner1) && e2.IsUnaryExpression(out uop2, out inner2) && uop1 == UnaryOperator.Not && uop1 == uop2) { BoxedExpression innerExp; if (inner1.IsVariable) { return inner2.IsExpressionNotEqualToNull(out innerExp) && ExtendedExpressionEquals(inner1, innerExp); } if (inner2.IsVariable) { return inner1.IsExpressionNotEqualToNull(out innerExp) && ExtendedExpressionEquals(inner2, innerExp); } } return false; } #endregion #region Overridden public override object Clone() { return new DisjunctiveRefinement(this); } protected override DisjunctiveRefinement Factory() { return new DisjunctiveRefinement(this.ExpressionManager); } public override List<BoxedVariable<Variable>> Variables { get { var result = new List<BoxedVariable<Variable>>(); if (this.IsNormal()) { foreach (var pair in this.Elements) { result.Add(pair.Key); if (pair.Value.IsNormal()) { foreach (var el in pair.Value.Values) { result.AddRange(el.Variables<Variable>().ConvertAll(v => new BoxedVariable<Variable>(v))); } } } } return result; } } public override void Assign(BoxedExpression x, BoxedExpression exp) { // do nothing } public override void ProjectVariable(BoxedVariable<Variable> var) { this.RemoveVariable(var); } public override void RemoveVariable(BoxedVariable<Variable> var) { if (this.IsNormal()) { if (this.ContainsKey(var)) { this.RemoveElement(var); } else { var toUpdate = new List<Pair<BoxedVariable<Variable>, SetOfConstraints<BoxedExpression>>>(); foreach (var pair in this.Elements) { if (pair.Value.IsNormal()) { var toRemove = new List<BoxedExpression>(); foreach (var el in pair.Value.Values) { if (el.Variables<Variable>().ConvertAll(v => new BoxedVariable<Variable>(v)).Contains(var)) { toRemove.Add(el); } } if (toRemove.Count > 0) { toUpdate.Add(pair.Key, new SetOfConstraints<BoxedExpression>(pair.Value.Values.Except(toRemove))); } } } if (toUpdate.Count > 0) { foreach (var pair in toUpdate) { this[pair.One] = pair.Two; } } } } } public override void RenameVariable(BoxedVariable<Variable> OldName, BoxedVariable<Variable> NewName) { throw new AbstractInterpretationTODOException(); } public override DisjunctiveRefinement TestTrue(BoxedExpression guard) { return this; } public override DisjunctiveRefinement TestFalse(BoxedExpression guard) { return this; } public override FlatAbstractDomain<bool> CheckIfHolds(BoxedExpression exp) { return CheckOutcome.Top; } public override void AssignInParallel( Dictionary<BoxedVariable<Variable>, FList<BoxedVariable<Variable>>> sourcesToTargets, Converter<BoxedVariable<Variable>, BoxedExpression> convert) { throw new NotImplementedException(); } public DisjunctiveRefinement AssignInParallelFunctional( Dictionary<BoxedVariable<Variable>, FList<BoxedVariable<Variable>>> sourcesToTargets, Converter<BoxedVariable<Variable>, BoxedExpression> convert) { // var varsInRenaming = ComputeVarsInRenaming(sourcesToTargets, convert); Dictionary<Variable, HashSet<Variable>> varsInRenaming = null; // We do not use them now, and as the cost of the call is too high, we just gave up if (this.IsNormal()) { var result = this.Factory(); foreach (var pair in this.Elements) { if (pair.Value.IsNormal()) { var renamed = new List<BoxedExpression>(); FList<BoxedVariable<Variable>> newNames; if (sourcesToTargets.TryGetValue(pair.Key, out newNames)) { foreach (var exp in pair.Value.Values) { renamed.AddIfNotNull(exp.Rename(sourcesToTargets)); } if (renamed.Count > 0) { var newConstraints = new SetOfConstraints<BoxedExpression>(renamed); foreach (var newName in newNames.GetEnumerable()) { result[newName] = newConstraints; } } } else { // do nothing -> the variable goes away } } } return new DisjunctiveRefinement(result, varsInRenaming); } else { return new DisjunctiveRefinement(this, varsInRenaming); } } private Dictionary<Variable, HashSet<Variable>> ComputeVarsInRenaming(Dictionary<BoxedVariable<Variable>, FList<BoxedVariable<Variable>>> sourcesToTargets, Converter<BoxedVariable<Variable>, BoxedExpression> convert) { var result = new Dictionary<Variable, HashSet<Variable>>(); foreach(var pair in sourcesToTargets) { Variable source; if (pair.Key.TryUnpackVariable(out source)) { var set = new HashSet<Variable>(); foreach (var v in pair.Value.GetEnumerable()) { set.UnionWith(convert(v).Variables<Variable>()); } result[source] = set; } } return result; } #endregion } #endregion } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using System.Diagnostics; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Caching; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Primitives; using osu.Framework.Graphics.Shaders; using osu.Framework.Graphics.Textures; using osu.Framework.Graphics.UserInterface; using osu.Framework.IO.Stores; using osu.Framework.Localisation; using osu.Framework.MathUtils; using osuTK; using osuTK.Graphics; namespace osu.Framework.Graphics.Sprites { /// <summary> /// A container for simple text rendering purposes. If more complex text rendering is required, use <see cref="TextFlowContainer"/> instead. /// </summary> public partial class SpriteText : Drawable, IHasLineBaseHeight, IHasText, IHasFilterTerms, IFillFlowContainer, IHasCurrentValue<string> { private const float default_text_size = 20; private static readonly Vector2 shadow_offset = new Vector2(0, 0.06f); [Resolved] private FontStore store { get; set; } [Resolved] private LocalisationManager localisation { get; set; } private ILocalisedBindableString localisedText; private float spaceWidth; public SpriteText() { current.BindValueChanged(e => Text = e.NewValue); } [BackgroundDependencyLoader] private void load(ShaderManager shaders) { localisedText = localisation.GetLocalisedString(text); localisedText.BindValueChanged(e => { if (string.IsNullOrEmpty(e.NewValue)) { // We'll become not present and won't update the characters to set the size to 0, so do it manually if (requiresAutoSizedWidth) base.Width = Padding.TotalHorizontal; if (requiresAutoSizedHeight) base.Height = Padding.TotalVertical; } invalidate(true); }, true); spaceWidth = getTextureForCharacter('.')?.DisplayWidth * 2 ?? 1; sharedData.TextureShader = shaders?.Load(VertexShaderDescriptor.TEXTURE_2, FragmentShaderDescriptor.TEXTURE); sharedData.RoundedTextureShader = shaders?.Load(VertexShaderDescriptor.TEXTURE_2, FragmentShaderDescriptor.TEXTURE_ROUNDED); // Pre-cache the characters in the texture store foreach (var character in displayedText) getTextureForCharacter(character); } private LocalisedString text = string.Empty; /// <summary> /// Gets or sets the text to be displayed. /// </summary> public LocalisedString Text { get => text; set { if (text == value) return; text = value; current.Value = text; if (localisedText != null) localisedText.Text = value; } } private readonly Bindable<string> current = new Bindable<string>(); public Bindable<string> Current { get => current; set { if (value == null) throw new ArgumentNullException(nameof(value)); current.UnbindBindings(); current.BindTo(value); } } private string displayedText => localisedText?.Value ?? text.Text.Original; string IHasText.Text { get => Text; set => Text = value; } private FontUsage font = FontUsage.Default; /// <summary> /// Contains information on the font used to display the text. /// </summary> public FontUsage Font { get => font; set { // The implicit operator can be used to convert strings to fonts, which discards size + fixedwidth in doing so // For the time being, we'll forward those members from the original value // Todo: Remove this along with all other obsolete members if (value.Legacy) value = new FontUsage(value.Family, font.Size, value.Weight, value.Italics, font.FixedWidth); font = value; invalidate(true); shadowOffsetCache.Invalidate(); } } /// <summary> /// The size of the text in local space. This means that if TextSize is set to 16, a single line will have a height of 16. /// </summary> [Obsolete("Setting TextSize directly is deprecated. Use `Font = text.Font.With(size: value)` (see: https://github.com/ppy/osu-framework/pull/2043)")] public float TextSize { get => Font.Size; set => Font = Font.With(size: value); } /// <summary> /// True if all characters should be spaced apart the same distance. /// </summary> [Obsolete("Setting FixedWidth directly is deprecated. Use `Font = text.Font.With(fixedWidth: value)` (see: https://github.com/ppy/osu-framework/pull/2043)")] public bool FixedWidth { get => Font.FixedWidth; set => Font = Font.With(fixedWidth: value); } private bool allowMultiline = true; /// <summary> /// True if the text should be wrapped if it gets too wide. Note that \n does NOT cause a line break. If you need explicit line breaks, use <see cref="TextFlowContainer"/> instead. /// </summary> public bool AllowMultiline { get => allowMultiline; set { if (allowMultiline == value) return; allowMultiline = value; invalidate(true); } } private bool shadow; /// <summary> /// True if a shadow should be displayed around the text. /// </summary> public bool Shadow { get => shadow; set { if (shadow == value) return; shadow = value; Invalidate(Invalidation.DrawNode); } } private Color4 shadowColour = new Color4(0, 0, 0, 0.2f); /// <summary> /// The colour of the shadow displayed around the text. A shadow will only be displayed if the <see cref="Shadow"/> property is set to true. /// </summary> public Color4 ShadowColour { get => shadowColour; set { if (shadowColour == value) return; shadowColour = value; Invalidate(Invalidation.DrawNode); } } private bool useFullGlyphHeight = true; /// <summary> /// True if the <see cref="SpriteText"/>'s vertical size should be equal to <see cref="FontUsage.Size"/> (the full height) or precisely the size of used characters. /// Set to false to allow better centering of individual characters/numerals/etc. /// </summary> public bool UseFullGlyphHeight { get => useFullGlyphHeight; set { if (useFullGlyphHeight == value) return; useFullGlyphHeight = value; invalidate(true); } } private bool requiresAutoSizedWidth => explicitWidth == null && (RelativeSizeAxes & Axes.X) == 0; private bool requiresAutoSizedHeight => explicitHeight == null && (RelativeSizeAxes & Axes.Y) == 0; private float? explicitWidth; /// <summary> /// Gets or sets the width of this <see cref="SpriteText"/>. The <see cref="SpriteText"/> will maintain this width when set. /// </summary> public override float Width { get { if (requiresAutoSizedWidth) computeCharacters(); return base.Width; } set { if (explicitWidth == value) return; base.Width = value; explicitWidth = value; invalidate(true); } } private float? explicitHeight; /// <summary> /// Gets or sets the height of this <see cref="SpriteText"/>. The <see cref="SpriteText"/> will maintain this height when set. /// </summary> public override float Height { get { if (requiresAutoSizedHeight) computeCharacters(); return base.Height; } set { if (explicitHeight == value) return; base.Height = value; explicitHeight = value; invalidate(true); } } /// <summary> /// Gets or sets the size of this <see cref="SpriteText"/>. The <see cref="SpriteText"/> will maintain this size when set. /// </summary> public override Vector2 Size { get { if (requiresAutoSizedWidth || requiresAutoSizedHeight) computeCharacters(); return base.Size; } set { Width = value.X; Height = value.Y; } } private Vector2 spacing; /// <summary> /// Gets or sets the spacing between characters of this <see cref="SpriteText"/>. /// </summary> public Vector2 Spacing { get => spacing; set { if (spacing == value) return; spacing = value; invalidate(true); } } private MarginPadding padding; /// <summary> /// Shrinks the space which may be occupied by characters of this <see cref="SpriteText"/> by the specified amount on each side. /// </summary> public MarginPadding Padding { get => padding; set { if (padding.Equals(value)) return; if (!Validation.IsFinite(value)) throw new ArgumentException($@"{nameof(Padding)} must be finite, but is {value}."); padding = value; invalidate(true); } } public override bool IsPresent => base.IsPresent && (AlwaysPresent || !string.IsNullOrEmpty(displayedText)); #region Characters private Cached charactersCache = new Cached(); private readonly List<CharacterPart> charactersBacking = new List<CharacterPart>(); /// <summary> /// The characters in local space. /// </summary> private List<CharacterPart> characters { get { computeCharacters(); return charactersBacking; } } private bool isComputingCharacters; private void computeCharacters() { if (store == null) return; if (charactersCache.IsValid) return; charactersBacking.Clear(); Debug.Assert(!isComputingCharacters, "Cyclic invocation of computeCharacters()!"); isComputingCharacters = true; Vector2 currentPos = new Vector2(Padding.Left, Padding.Top); try { if (string.IsNullOrEmpty(displayedText)) return; float maxWidth = float.PositiveInfinity; if (!requiresAutoSizedWidth) maxWidth = ApplyRelativeAxes(RelativeSizeAxes, new Vector2(base.Width, base.Height), FillMode).X - Padding.Right; float currentRowHeight = 0; foreach (var character in displayedText) { bool useFixedWidth = Font.FixedWidth && UseFixedWidthForCharacter(character); // Unscaled size (i.e. not multiplied by Font.Size) Vector2 textureSize; Texture texture = null; // Retrieve the texture + size if (char.IsWhiteSpace(character)) { float size = useFixedWidth ? constantWidth : spaceWidth; if (character == 0x3000) { // Double-width space size *= 2; } textureSize = new Vector2(size); } else { texture = getTextureForCharacter(character); textureSize = texture == null ? new Vector2(useFixedWidth ? constantWidth : spaceWidth) : new Vector2(texture.DisplayWidth, texture.DisplayHeight); } // Scaled glyph size to be used for positioning Vector2 glyphSize = new Vector2(useFixedWidth ? constantWidth : textureSize.X, UseFullGlyphHeight ? 1 : textureSize.Y) * Font.Size; // Texture size scaled by Font.Size Vector2 scaledTextureSize = textureSize * Font.Size; // Check if we need to go onto the next line if (AllowMultiline && currentPos.X + glyphSize.X >= maxWidth) { currentPos.X = Padding.Left; currentPos.Y += currentRowHeight + spacing.Y; currentRowHeight = 0; } // The height of the row depends on whether we want to use the full glyph height or not currentRowHeight = Math.Max(currentRowHeight, glyphSize.Y); if (!char.IsWhiteSpace(character) && texture != null) { // If we have fixed width, we'll need to centre the texture to the glyph size float offset = (glyphSize.X - scaledTextureSize.X) / 2; charactersBacking.Add(new CharacterPart { Texture = texture, DrawRectangle = new RectangleF(new Vector2(currentPos.X + offset, currentPos.Y), scaledTextureSize), }); } currentPos.X += glyphSize.X + spacing.X; } // When we added the last character, we also added the spacing, but we should remove it to get the correct size currentPos.X -= spacing.X; // The last row needs to be included in the height currentPos.Y += currentRowHeight; } finally { if (requiresAutoSizedWidth) base.Width = currentPos.X + Padding.Right; if (requiresAutoSizedHeight) base.Height = currentPos.Y + Padding.Bottom; isComputingCharacters = false; charactersCache.Validate(); } } private Cached screenSpaceCharactersCache = new Cached(); private readonly List<ScreenSpaceCharacterPart> screenSpaceCharactersBacking = new List<ScreenSpaceCharacterPart>(); /// <summary> /// The characters in screen space. These are ready to be drawn. /// </summary> private List<ScreenSpaceCharacterPart> screenSpaceCharacters { get { computeScreenSpaceCharacters(); return screenSpaceCharactersBacking; } } private void computeScreenSpaceCharacters() { if (screenSpaceCharactersCache.IsValid) return; screenSpaceCharactersBacking.Clear(); foreach (var character in characters) { screenSpaceCharactersBacking.Add(new ScreenSpaceCharacterPart { DrawQuad = ToScreenSpace(character.DrawRectangle), Texture = character.Texture }); } screenSpaceCharactersCache.Validate(); } private Cached<float> constantWidthCache; private float constantWidth => constantWidthCache.IsValid ? constantWidthCache.Value : constantWidthCache.Value = getTextureForCharacter('D')?.DisplayWidth ?? 0; private Cached<Vector2> shadowOffsetCache; private Vector2 shadowOffset => shadowOffsetCache.IsValid ? shadowOffsetCache.Value : shadowOffsetCache.Value = ToScreenSpace(shadow_offset * Font.Size) - ToScreenSpace(Vector2.Zero); #endregion #region Invalidation private void invalidate(bool layout = false) { if (layout) charactersCache.Invalidate(); screenSpaceCharactersCache.Invalidate(); Invalidate(Invalidation.DrawNode, shallPropagate: false); } public override bool Invalidate(Invalidation invalidation = Invalidation.All, Drawable source = null, bool shallPropagate = true) { base.Invalidate(invalidation, source, shallPropagate); if (source == Parent) { // Colour captures presence changes if ((invalidation & (Invalidation.DrawSize | Invalidation.Presence)) > 0) invalidate(true); if ((invalidation & Invalidation.DrawInfo) > 0) { invalidate(); shadowOffsetCache.Invalidate(); } } else if ((invalidation & Invalidation.MiscGeometry) > 0) invalidate(); return true; } #endregion #region DrawNode private readonly SpriteTextDrawNodeSharedData sharedData = new SpriteTextDrawNodeSharedData(); protected override DrawNode CreateDrawNode() => new SpriteTextDrawNode(); protected override void ApplyDrawNode(DrawNode node) { base.ApplyDrawNode(node); var n = (SpriteTextDrawNode)node; n.Shared = sharedData; n.Parts.Clear(); n.Parts.AddRange(screenSpaceCharacters); n.Shadow = Shadow; if (Shadow) { n.ShadowColour = ShadowColour; n.ShadowOffset = shadowOffset; } } #endregion private Texture getTextureForCharacter(char c) => GetTextureForCharacter(c) ?? GetFallbackTextureForCharacter(c); /// <summary> /// Gets the texture for the given character. /// </summary> /// <param name="c">The character to get the texture for.</param> /// <returns>The texture for the given character.</returns> protected virtual Texture GetTextureForCharacter(char c) { if (store == null) return null; return store.GetCharacter(Font.FontName, c) ?? store.GetCharacter(null, c); } /// <summary> /// Gets a <see cref="Texture"/> that represents a character which doesn't exist in the current font. /// </summary> /// <param name="c">The character which doesn't exist in the current font.</param> /// <returns>The texture for the given character.</returns> protected virtual Texture GetFallbackTextureForCharacter(char c) => GetTextureForCharacter('?'); /// <summary> /// Whether the visual representation of a character should use fixed width when <see cref="FontUsage.FixedWidth"/> is true. /// By default, this includes the following characters, commonly used in numerical formatting: '.' ',' ':' and ' ' /// </summary> /// <param name="c">The character.</param> /// <returns>Whether the visual representation of <paramref name="c"/> should use a fixed width.</returns> protected virtual bool UseFixedWidthForCharacter(char c) { switch (c) { case '.': case ',': case ':': case ' ': return false; } return true; } public override string ToString() { return $@"""{displayedText}"" " + base.ToString(); } /// <summary> /// Gets the base height of the font used by this text. If the font of this text is invalid, 0 is returned. /// </summary> public float LineBaseHeight { get { var baseHeight = store.GetBaseHeight(Font.FontName); if (baseHeight.HasValue) return baseHeight.Value * Font.Size; if (string.IsNullOrEmpty(displayedText)) return 0; return store.GetBaseHeight(displayedText[0]).GetValueOrDefault() * Font.Size; } } public IEnumerable<string> FilterTerms { get { yield return displayedText; } } } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using gagr = Google.Api.Gax.ResourceNames; using gcav = Google.Cloud.ArtifactRegistry.V1; using sys = System; namespace Google.Cloud.ArtifactRegistry.V1 { /// <summary>Resource name for the <c>Repository</c> resource.</summary> public sealed partial class RepositoryName : gax::IResourceName, sys::IEquatable<RepositoryName> { /// <summary>The possible contents of <see cref="RepositoryName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern <c>projects/{project}/locations/{location}/repositories/{repository}</c>. /// </summary> ProjectLocationRepository = 1, } private static gax::PathTemplate s_projectLocationRepository = new gax::PathTemplate("projects/{project}/locations/{location}/repositories/{repository}"); /// <summary>Creates a <see cref="RepositoryName"/> containing an unparsed resource name.</summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="RepositoryName"/> containing the provided /// <paramref name="unparsedResourceName"/>. /// </returns> public static RepositoryName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new RepositoryName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="RepositoryName"/> with the pattern /// <c>projects/{project}/locations/{location}/repositories/{repository}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="repositoryId">The <c>Repository</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="RepositoryName"/> constructed from the provided ids.</returns> public static RepositoryName FromProjectLocationRepository(string projectId, string locationId, string repositoryId) => new RepositoryName(ResourceNameType.ProjectLocationRepository, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), repositoryId: gax::GaxPreconditions.CheckNotNullOrEmpty(repositoryId, nameof(repositoryId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="RepositoryName"/> with pattern /// <c>projects/{project}/locations/{location}/repositories/{repository}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="repositoryId">The <c>Repository</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="RepositoryName"/> with pattern /// <c>projects/{project}/locations/{location}/repositories/{repository}</c>. /// </returns> public static string Format(string projectId, string locationId, string repositoryId) => FormatProjectLocationRepository(projectId, locationId, repositoryId); /// <summary> /// Formats the IDs into the string representation of this <see cref="RepositoryName"/> with pattern /// <c>projects/{project}/locations/{location}/repositories/{repository}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="repositoryId">The <c>Repository</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="RepositoryName"/> with pattern /// <c>projects/{project}/locations/{location}/repositories/{repository}</c>. /// </returns> public static string FormatProjectLocationRepository(string projectId, string locationId, string repositoryId) => s_projectLocationRepository.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(repositoryId, nameof(repositoryId))); /// <summary>Parses the given resource name string into a new <see cref="RepositoryName"/> instance.</summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>projects/{project}/locations/{location}/repositories/{repository}</c></description> /// </item> /// </list> /// </remarks> /// <param name="repositoryName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="RepositoryName"/> if successful.</returns> public static RepositoryName Parse(string repositoryName) => Parse(repositoryName, false); /// <summary> /// Parses the given resource name string into a new <see cref="RepositoryName"/> instance; optionally allowing /// an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>projects/{project}/locations/{location}/repositories/{repository}</c></description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="repositoryName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="RepositoryName"/> if successful.</returns> public static RepositoryName Parse(string repositoryName, bool allowUnparsed) => TryParse(repositoryName, allowUnparsed, out RepositoryName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary> /// Tries to parse the given resource name string into a new <see cref="RepositoryName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>projects/{project}/locations/{location}/repositories/{repository}</c></description> /// </item> /// </list> /// </remarks> /// <param name="repositoryName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="RepositoryName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string repositoryName, out RepositoryName result) => TryParse(repositoryName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="RepositoryName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>projects/{project}/locations/{location}/repositories/{repository}</c></description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="repositoryName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="RepositoryName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string repositoryName, bool allowUnparsed, out RepositoryName result) { gax::GaxPreconditions.CheckNotNull(repositoryName, nameof(repositoryName)); gax::TemplatedResourceName resourceName; if (s_projectLocationRepository.TryParseName(repositoryName, out resourceName)) { result = FromProjectLocationRepository(resourceName[0], resourceName[1], resourceName[2]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(repositoryName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private RepositoryName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string locationId = null, string projectId = null, string repositoryId = null) { Type = type; UnparsedResource = unparsedResourceName; LocationId = locationId; ProjectId = projectId; RepositoryId = repositoryId; } /// <summary> /// Constructs a new instance of a <see cref="RepositoryName"/> class from the component parts of pattern /// <c>projects/{project}/locations/{location}/repositories/{repository}</c> /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="repositoryId">The <c>Repository</c> ID. Must not be <c>null</c> or empty.</param> public RepositoryName(string projectId, string locationId, string repositoryId) : this(ResourceNameType.ProjectLocationRepository, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), repositoryId: gax::GaxPreconditions.CheckNotNullOrEmpty(repositoryId, nameof(repositoryId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>Location</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string LocationId { get; } /// <summary> /// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string ProjectId { get; } /// <summary> /// The <c>Repository</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string RepositoryId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.ProjectLocationRepository: return s_projectLocationRepository.Expand(ProjectId, LocationId, RepositoryId); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as RepositoryName); /// <inheritdoc/> public bool Equals(RepositoryName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(RepositoryName a, RepositoryName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(RepositoryName a, RepositoryName b) => !(a == b); } public partial class Repository { /// <summary> /// <see cref="gcav::RepositoryName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcav::RepositoryName RepositoryName { get => string.IsNullOrEmpty(Name) ? null : gcav::RepositoryName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class ListRepositoriesRequest { /// <summary> /// <see cref="gagr::LocationName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public gagr::LocationName ParentAsLocationName { get => string.IsNullOrEmpty(Parent) ? null : gagr::LocationName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } } public partial class GetRepositoryRequest { /// <summary> /// <see cref="gcav::RepositoryName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcav::RepositoryName RepositoryName { get => string.IsNullOrEmpty(Name) ? null : gcav::RepositoryName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } }
using UnityEngine; using System.Collections.Generic; namespace Pathfinding { using Pathfinding.Util; using Pathfinding.Serialization; public interface INavmesh { void GetNodes (System.Action<GraphNode> del); } /** Generates graphs based on navmeshes. * \ingroup graphs * Navmeshes are meshes where each triangle defines a walkable area. * These are great because the AI can get so much more information on how it can walk. * Polygons instead of points mean that the funnel smoother can produce really nice looking paths and the graphs are also really fast to search * and have a low memory footprint because fewer nodes are usually needed to describe the same area compared to grid graphs. * * \see Pathfinding.RecastGraph * * \shadowimage{navmeshgraph_graph.png} * \shadowimage{navmeshgraph_inspector.png} */ [JsonOptIn] public class NavMeshGraph : NavmeshBase, IUpdatableGraph { /** Mesh to construct navmesh from */ [JsonMember] public Mesh sourceMesh; /** Offset in world space */ [JsonMember] public Vector3 offset; /** Rotation in degrees */ [JsonMember] public Vector3 rotation; /** Scale of the graph */ [JsonMember] public float scale = 1; /** Determines how normals are calculated. * Disable for spherical graphs or other complicated surfaces that allow the agents to e.g walk on walls or ceilings. * * By default the normals of the mesh will be flipped so that they point as much as possible in the upwards direction. * The normals are important when connecting adjacent nodes. Two adjacent nodes will only be connected if they are oriented the same way. * This is particularly important if you have a navmesh on the walls or even on the ceiling of a room. Or if you are trying to make a spherical navmesh. * If you do one of those things then you should set disable this setting and make sure the normals in your source mesh are properly set. * * If you for example take a look at the image below. In the upper case then the nodes on the bottom half of the * mesh haven't been connected with the nodes on the upper half because the normals on the lower half will have been * modified to point inwards (as that is the direction that makes them face upwards the most) while the normals on * the upper half point outwards. This causes the nodes to not connect properly along the seam. When this option * is set to false instead the nodes are connected properly as in the original mesh all normals point outwards. * \shadowimage{navmesh_normals.jpg} * * The default value of this field is true to reduce the risk for errors in the common case. If a mesh is supplied that * has all normals pointing downwards and this option is false, then some methods like #PointOnNavmesh will not work correctly * as they assume that the normals point upwards. For a more complicated surface like a spherical graph those methods make no sense anyway * as there is no clear definition of what it means to be "inside" a triangle when there is no clear up direction. */ [JsonMember] public bool recalculateNormals = true; protected override bool RecalculateNormals { get { return recalculateNormals; } } public override float TileWorldSizeX { get { return forcedBoundsSize.x; } } public override float TileWorldSizeZ { get { return forcedBoundsSize.z; } } protected override float MaxTileConnectionEdgeDistance { get { // Tiles are not supported, so this is irrelevant return 0f; } } public override GraphTransform CalculateTransform () { return new GraphTransform(Matrix4x4.TRS(offset, Quaternion.Euler(rotation), Vector3.one) * Matrix4x4.TRS(sourceMesh != null ? sourceMesh.bounds.min * scale : Vector3.zero, Quaternion.identity, Vector3.one)); } GraphUpdateThreading IUpdatableGraph.CanUpdateAsync (GraphUpdateObject o) { return GraphUpdateThreading.UnityThread; } void IUpdatableGraph.UpdateAreaInit (GraphUpdateObject o) {} void IUpdatableGraph.UpdateAreaPost (GraphUpdateObject o) {} void IUpdatableGraph.UpdateArea (GraphUpdateObject o) { UpdateArea(o, this); } public static void UpdateArea (GraphUpdateObject o, INavmeshHolder graph) { Bounds bounds = graph.transform.InverseTransform(o.bounds); // Bounding rectangle with integer coordinates var irect = new IntRect( Mathf.FloorToInt(bounds.min.x*Int3.Precision), Mathf.FloorToInt(bounds.min.z*Int3.Precision), Mathf.CeilToInt(bounds.max.x*Int3.Precision), Mathf.CeilToInt(bounds.max.z*Int3.Precision) ); // Corners of the bounding rectangle var a = new Int3(irect.xmin, 0, irect.ymin); var b = new Int3(irect.xmin, 0, irect.ymax); var c = new Int3(irect.xmax, 0, irect.ymin); var d = new Int3(irect.xmax, 0, irect.ymax); var ymin = ((Int3)bounds.min).y; var ymax = ((Int3)bounds.max).y; // Loop through all nodes and check if they intersect the bounding box graph.GetNodes(_node => { var node = _node as TriangleMeshNode; bool inside = false; int allLeft = 0; int allRight = 0; int allTop = 0; int allBottom = 0; // Check bounding box rect in XZ plane for (int v = 0; v < 3; v++) { Int3 p = node.GetVertexInGraphSpace(v); if (irect.Contains(p.x, p.z)) { inside = true; break; } if (p.x < irect.xmin) allLeft++; if (p.x > irect.xmax) allRight++; if (p.z < irect.ymin) allTop++; if (p.z > irect.ymax) allBottom++; } if (!inside && (allLeft == 3 || allRight == 3 || allTop == 3 || allBottom == 3)) { return; } // Check if the polygon edges intersect the bounding rect for (int v = 0; v < 3; v++) { int v2 = v > 1 ? 0 : v+1; Int3 vert1 = node.GetVertexInGraphSpace(v); Int3 vert2 = node.GetVertexInGraphSpace(v2); if (VectorMath.SegmentsIntersectXZ(a, b, vert1, vert2)) { inside = true; break; } if (VectorMath.SegmentsIntersectXZ(a, c, vert1, vert2)) { inside = true; break; } if (VectorMath.SegmentsIntersectXZ(c, d, vert1, vert2)) { inside = true; break; } if (VectorMath.SegmentsIntersectXZ(d, b, vert1, vert2)) { inside = true; break; } } // Check if the node contains any corner of the bounding rect if (inside || node.ContainsPointInGraphSpace(a) || node.ContainsPointInGraphSpace(b) || node.ContainsPointInGraphSpace(c) || node.ContainsPointInGraphSpace(d)) { inside = true; } if (!inside) { return; } int allAbove = 0; int allBelow = 0; // Check y coordinate for (int v = 0; v < 3; v++) { Int3 p = node.GetVertexInGraphSpace(v); if (p.y < ymin) allBelow++; if (p.y > ymax) allAbove++; } // Polygon is either completely above the bounding box or completely below it if (allBelow == 3 || allAbove == 3) return; // Triangle is inside the bounding box! // Update it! o.WillUpdateNode(node); o.Apply(node); }); } /** Scans the graph using the path to an .obj mesh */ [System.Obsolete("Set the mesh to ObjImporter.ImportFile(...) and scan the graph the normal way instead")] public void ScanInternal (string objMeshPath) { Mesh mesh = ObjImporter.ImportFile(objMeshPath); if (mesh == null) { Debug.LogError("Couldn't read .obj file at '"+objMeshPath+"'"); return; } sourceMesh = mesh; var scan = ScanInternal().GetEnumerator(); while (scan.MoveNext()) {} } protected override IEnumerable<Progress> ScanInternal () { transform = CalculateTransform(); tileZCount = tileXCount = 1; tiles = new NavmeshTile[tileZCount*tileXCount]; TriangleMeshNode.SetNavmeshHolder(AstarPath.active.data.GetGraphIndex(this), this); if (sourceMesh == null) { FillWithEmptyTiles(); yield break; } yield return new Progress(0.0f, "Transforming Vertices"); forcedBoundsSize = sourceMesh.bounds.size * scale; Vector3[] vectorVertices = sourceMesh.vertices; var intVertices = ListPool<Int3>.Claim(vectorVertices.Length); var matrix = Matrix4x4.TRS(-sourceMesh.bounds.min * scale, Quaternion.identity, Vector3.one * scale); // Convert the vertices to integer coordinates and also position them in graph space // so that the minimum of the bounding box of the mesh is at the origin // (the vertices will later be transformed to world space) for (int i = 0; i < vectorVertices.Length; i++) { intVertices.Add((Int3)matrix.MultiplyPoint3x4(vectorVertices[i])); } yield return new Progress(0.1f, "Compressing Vertices"); // Remove duplicate vertices Int3[] compressedVertices = null; int[] compressedTriangles = null; Polygon.CompressMesh(intVertices, new List<int>(sourceMesh.triangles), out compressedVertices, out compressedTriangles); ListPool<Int3>.Release(ref intVertices); yield return new Progress(0.2f, "Building Nodes"); ReplaceTile(0, 0, compressedVertices, compressedTriangles); // This may be used by the TileHandlerHelper script to update the tiles // while taking NavmeshCuts into account after the graph has been completely recalculated. if (OnRecalculatedTiles != null) { OnRecalculatedTiles(tiles.Clone() as NavmeshTile[]); } } protected override void DeserializeSettingsCompatibility (GraphSerializationContext ctx) { base.DeserializeSettingsCompatibility(ctx); sourceMesh = ctx.DeserializeUnityObject() as Mesh; offset = ctx.DeserializeVector3(); rotation = ctx.DeserializeVector3(); scale = ctx.reader.ReadSingle(); nearestSearchOnlyXZ = !ctx.reader.ReadBoolean(); } } }
//------------------------------------------------------------------------------ // <copyright file="NameValuePermission.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // <owner current="true" primary="true">[....]</owner> // <owner current="true" primary="false">[....]</owner> //------------------------------------------------------------------------------ namespace System.Data.Common { using System.Collections; using System.Data.Common; using System.Diagnostics; using System.Globalization; using System.Security; using System.Security.Permissions; using System.Text; [Serializable] // MDAC 83147 sealed internal class NameValuePermission : IComparable { // reused as both key and value nodes // key nodes link to value nodes // value nodes link to key nodes private string _value; // value node with (null != _restrictions) are allowed to match connection strings private DBConnectionString _entry; private NameValuePermission[] _tree; // with branches static internal readonly NameValuePermission Default = null;// = new NameValuePermission(String.Empty, new string[] { "File Name" }, KeyRestrictionBehavior.AllowOnly); internal NameValuePermission() { // root node } private NameValuePermission(string keyword) { _value = keyword; } private NameValuePermission(string value, DBConnectionString entry) { _value = value; _entry = entry; } private NameValuePermission(NameValuePermission permit) { // deep-copy _value = permit._value; _entry = permit._entry; _tree = permit._tree; if (null != _tree) { NameValuePermission[] tree = (_tree.Clone() as NameValuePermission[]); for(int i = 0; i < tree.Length; ++i) { if (null != tree[i]) { // WebData 98488 tree[i] = tree[i].CopyNameValue(); // deep copy } } _tree = tree; } } int IComparable.CompareTo(object a) { return StringComparer.Ordinal.Compare(_value, ((NameValuePermission)a)._value); } static internal void AddEntry(NameValuePermission kvtree, ArrayList entries, DBConnectionString entry) { Debug.Assert(null != entry, "null DBConnectionString"); if (null != entry.KeyChain) { for(NameValuePair keychain = entry.KeyChain; null != keychain; keychain = keychain.Next) { NameValuePermission kv; kv = kvtree.CheckKeyForValue(keychain.Name); if (null == kv) { kv = new NameValuePermission(keychain.Name); kvtree.Add(kv); // add directly into live tree } kvtree = kv; kv = kvtree.CheckKeyForValue(keychain.Value); if (null == kv) { DBConnectionString insertValue = ((null != keychain.Next) ? null : entry); kv = new NameValuePermission(keychain.Value, insertValue); kvtree.Add(kv); // add directly into live tree if (null != insertValue) { entries.Add(insertValue); } } else if (null == keychain.Next) { // shorter chain potential if (null != kv._entry) { Debug.Assert(entries.Contains(kv._entry), "entries doesn't contain entry"); entries.Remove(kv._entry); kv._entry = kv._entry.Intersect(entry); // union new restrictions into existing tree } else { kv._entry = entry; } entries.Add(kv._entry); } kvtree = kv; } } else { // global restrictions, MDAC 84443 DBConnectionString kentry = kvtree._entry; if (null != kentry) { Debug.Assert(entries.Contains(kentry), "entries doesn't contain entry"); entries.Remove(kentry); kvtree._entry = kentry.Intersect(entry); } else { kvtree._entry = entry; } entries.Add(kvtree._entry); } } internal void Intersect(ArrayList entries, NameValuePermission target) { if (null == target) { _tree = null; _entry = null; } else { if (null != _entry) { entries.Remove(_entry); _entry = _entry.Intersect(target._entry); entries.Add(_entry); } else if (null != target._entry) { _entry = target._entry.Intersect(null); entries.Add(_entry); } if (null != _tree) { int count = _tree.Length; for(int i = 0; i < _tree.Length; ++i) { NameValuePermission kvtree = target.CheckKeyForValue(_tree[i]._value); if (null != kvtree) { // does target tree contain our value _tree[i].Intersect(entries, kvtree); } else { _tree[i] = null; --count; } } if (0 == count) { _tree = null; } else if (count < _tree.Length) { NameValuePermission[] kvtree = new NameValuePermission[count]; for (int i = 0, j = 0; i < _tree.Length; ++i) { if(null != _tree[i]) { kvtree[j++] = _tree[i]; } } _tree = kvtree; } } } } private void Add(NameValuePermission permit) { NameValuePermission[] tree = _tree; int length = ((null != tree) ? tree.Length : 0); NameValuePermission[] newtree = new NameValuePermission[1+length]; for(int i = 0; i < newtree.Length-1; ++i) { newtree[i] = tree[i]; } newtree[length] = permit; Array.Sort(newtree); _tree = newtree; } internal bool CheckValueForKeyPermit(DBConnectionString parsetable) { if (null == parsetable) { return false; } bool hasMatch = false; NameValuePermission[] keytree = _tree; // _tree won't mutate but Add will replace it if (null != keytree) { hasMatch = parsetable.IsEmpty; // MDAC 86773 if (!hasMatch) { // which key do we follow the key-value chain on for (int i = 0; i < keytree.Length; ++i) { NameValuePermission permitKey = keytree[i]; if (null != permitKey) { string keyword = permitKey._value; #if DEBUG Debug.Assert(null == permitKey._entry, "key member has no restrictions"); #endif if (parsetable.ContainsKey(keyword)) { string valueInQuestion = (string)parsetable[keyword]; // keyword is restricted to certain values NameValuePermission permitValue = permitKey.CheckKeyForValue(valueInQuestion); if (null != permitValue) { //value does match - continue the chain down that branch if (permitValue.CheckValueForKeyPermit(parsetable)) { hasMatch = true; // adding a break statement is tempting, but wrong // user can safetly extend their restrictions for current rule to include missing keyword // i.e. Add("provider=sqloledb;integrated security=sspi", "data provider=", KeyRestrictionBehavior.AllowOnly); // i.e. Add("data provider=msdatashape;provider=sqloledb;integrated security=sspi", "", KeyRestrictionBehavior.AllowOnly); } else { // failed branch checking return false; } } else { // value doesn't match to expected values - fail here return false; } } } // else try next keyword } } // partial chain match, either leaf-node by shorter chain or fail mid-chain if (null == _restrictions) } DBConnectionString entry = _entry; if (null != entry) { // also checking !hasMatch is tempting, but wrong // user can safetly extend their restrictions for current rule to include missing keyword // i.e. Add("provider=sqloledb;integrated security=sspi", "data provider=", KeyRestrictionBehavior.AllowOnly); // i.e. Add("provider=sqloledb;", "integrated security=;", KeyRestrictionBehavior.AllowOnly); hasMatch = entry.IsSupersetOf(parsetable); } return hasMatch; // mid-chain failure } private NameValuePermission CheckKeyForValue(string keyInQuestion) { NameValuePermission[] valuetree = _tree; // _tree won't mutate but Add will replace it if (null != valuetree) { for (int i = 0; i < valuetree.Length; ++i) { NameValuePermission permitValue = valuetree[i]; if (String.Equals(keyInQuestion, permitValue._value, StringComparison.OrdinalIgnoreCase)) { return permitValue; } } } return null; } internal NameValuePermission CopyNameValue() { return new NameValuePermission(this); } } }
// // 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.WindowsAzure; using Microsoft.WindowsAzure.Management.Network.Models; namespace Microsoft.WindowsAzure.Management.Network { /// <summary> /// The Network Management API includes operations for managing the routes /// for your subscription. /// </summary> public partial interface IRouteOperations { /// <summary> /// Set the specified route table for the provided subnet in the /// provided virtual network in this subscription. /// </summary> /// <param name='vnetName'> /// The name of the virtual network that contains the provided subnet. /// </param> /// <param name='subnetName'> /// The name of the subnet that the route table will be added to. /// </param> /// <param name='parameters'> /// The parameters necessary to add a route table to the provided /// subnet. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request, and also includes error /// information regarding the failure. /// </returns> Task<OperationStatusResponse> AddRouteTableToSubnetAsync(string vnetName, string subnetName, AddRouteTableToSubnetParameters parameters, CancellationToken cancellationToken); /// <summary> /// Set the specified route table for the provided subnet in the /// provided virtual network in this subscription. /// </summary> /// <param name='vnetName'> /// The name of the virtual network that contains the provided subnet. /// </param> /// <param name='subnetName'> /// The name of the subnet that the route table will be added to. /// </param> /// <param name='parameters'> /// The parameters necessary to add a route table to the provided /// subnet. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> Task<OperationResponse> BeginAddRouteTableToSubnetAsync(string vnetName, string subnetName, AddRouteTableToSubnetParameters parameters, CancellationToken cancellationToken); /// <summary> /// Create the specified route table for this subscription. /// </summary> /// <param name='parameters'> /// The parameters necessary to create a new route table. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> Task<OperationResponse> BeginCreateRouteTableAsync(CreateRouteTableParameters parameters, CancellationToken cancellationToken); /// <summary> /// Set the specified route for the provided table in this subscription. /// </summary> /// <param name='routeTableName'> /// The name of the route table where the provided route will be set. /// </param> /// <param name='routeName'> /// The name of the route that will be set on the provided route table. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> Task<OperationResponse> BeginDeleteRouteAsync(string routeTableName, string routeName, CancellationToken cancellationToken); /// <summary> /// Delete the specified route table for this subscription. /// </summary> /// <param name='routeTableName'> /// The name of the route table to delete. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> Task<OperationResponse> BeginDeleteRouteTableAsync(string routeTableName, CancellationToken cancellationToken); /// <summary> /// Remove the route table from the provided subnet in the provided /// virtual network in this subscription. /// </summary> /// <param name='vnetName'> /// The name of the virtual network that contains the provided subnet. /// </param> /// <param name='subnetName'> /// The name of the subnet that the route table will be removed from. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> Task<OperationResponse> BeginRemoveRouteTableFromSubnetAsync(string vnetName, string subnetName, CancellationToken cancellationToken); /// <summary> /// Set the specified route for the provided table in this subscription. /// </summary> /// <param name='routeTableName'> /// The name of the route table where the provided route will be set. /// </param> /// <param name='routeName'> /// The name of the route that will be set on the provided route table. /// </param> /// <param name='parameters'> /// The parameters necessary to create a new route table. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> Task<OperationResponse> BeginSetRouteAsync(string routeTableName, string routeName, SetRouteParameters parameters, CancellationToken cancellationToken); /// <summary> /// Create the specified route table for this subscription. /// </summary> /// <param name='parameters'> /// The parameters necessary to create a new route table. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request, and also includes error /// information regarding the failure. /// </returns> Task<OperationStatusResponse> CreateRouteTableAsync(CreateRouteTableParameters parameters, CancellationToken cancellationToken); /// <summary> /// Set the specified route for the provided table in this subscription. /// </summary> /// <param name='routeTableName'> /// The name of the route table where the provided route will be set. /// </param> /// <param name='routeName'> /// The name of the route that will be set on the provided route table. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request, and also includes error /// information regarding the failure. /// </returns> Task<OperationStatusResponse> DeleteRouteAsync(string routeTableName, string routeName, CancellationToken cancellationToken); /// <summary> /// Delete the specified route table for this subscription. /// </summary> /// <param name='routeTableName'> /// The name of the route table to delete. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request, and also includes error /// information regarding the failure. /// </returns> Task<OperationStatusResponse> DeleteRouteTableAsync(string routeTableName, CancellationToken cancellationToken); /// <summary> /// Get the specified route table for this subscription. /// </summary> /// <param name='routeTableName'> /// The name of the route table in this subscription to retrieve. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> Task<GetRouteTableResponse> GetRouteTableAsync(string routeTableName, CancellationToken cancellationToken); /// <summary> /// Get the specified route table for the provided subnet in the /// provided virtual network in this subscription. /// </summary> /// <param name='vnetName'> /// The name of the virtual network that contains the provided subnet. /// </param> /// <param name='subnetName'> /// The name of the subnet. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> Task<GetRouteTableForSubnetResponse> GetRouteTableForSubnetAsync(string vnetName, string subnetName, CancellationToken cancellationToken); /// <summary> /// Get the specified route table for this subscription. /// </summary> /// <param name='routeTableName'> /// The name of the route table in this subscription to retrieve. /// </param> /// <param name='detailLevel'> /// The amount of detail about the requested route table that will be /// returned. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> Task<GetRouteTableResponse> GetRouteTableWithDetailsAsync(string routeTableName, string detailLevel, CancellationToken cancellationToken); /// <summary> /// List the existing route tables for this subscription. /// </summary> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> Task<ListRouteTablesResponse> ListRouteTablesAsync(CancellationToken cancellationToken); /// <summary> /// Remove the route table from the provided subnet in the provided /// virtual network in this subscription. /// </summary> /// <param name='vnetName'> /// The name of the virtual network that contains the provided subnet. /// </param> /// <param name='subnetName'> /// The name of the subnet that the route table will be removed from. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request, and also includes error /// information regarding the failure. /// </returns> Task<OperationStatusResponse> RemoveRouteTableFromSubnetAsync(string vnetName, string subnetName, CancellationToken cancellationToken); /// <summary> /// Set the specified route for the provided table in this subscription. /// </summary> /// <param name='routeTableName'> /// The name of the route table where the provided route will be set. /// </param> /// <param name='routeName'> /// The name of the route that will be set on the provided route table. /// </param> /// <param name='parameters'> /// The parameters necessary to create a new route table. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request, and also includes error /// information regarding the failure. /// </returns> Task<OperationStatusResponse> SetRouteAsync(string routeTableName, string routeName, SetRouteParameters parameters, CancellationToken cancellationToken); } }
#if !UNITY_METRO && !UNITY_WP_8_1 && !UNITY_WINRT && !UNITY_WINRT_8_1 #define ENABLE_REFLECTION using System.Reflection; #endif using System.Diagnostics; using UnityEngine; using System.Collections.Generic; using System.Linq; using System.Collections; using Debug = UnityEngine.Debug; namespace PrefabEvolution { [System.Serializable] public class PEExposedProperties : ISerializationCallbackReceiver { [System.NonSerialized] internal List<BaseExposedData> InheritedProperties; [System.NonSerialized] public PEPrefabScript PrefabScript; public List<ExposedProperty> Properties = Utils.Create<List<ExposedProperty>>(); public List<ExposedPropertyGroup> Groups = Utils.Create<List<ExposedPropertyGroup>>(); [SerializeField] private List<int> Hidden = Utils.Create<List<int>>(); #region ISerializationCallbackReceiver implementation public void OnBeforeSerialize() { } public void OnAfterDeserialize() { #if UNITY_EDITOR InheritedProperties = null; foreach (var item in Properties.OfType<BaseExposedData>().Concat(Groups.OfType<BaseExposedData>())) { item.Container = this; } #endif } #endregion public IEnumerable<BaseExposedData> GetInheritedProperties() { if (InheritedProperties == null) { InheritedProperties = new List<BaseExposedData>(); if (this.PrefabScript == null) return InheritedProperties; if (this.PrefabScript.ParentPrefab != null) { var parentScript = PrefabScript.ParentPrefab.GetComponent<PEPrefabScript>(); if (parentScript == null) { Debug.Log("Inherited property Error: Prefab script not found on", this.PrefabScript); return InheritedProperties; } InheritedProperties.AddRange(parentScript.Properties.Items.Where(i => !i.Hidden).Select(p => { var r = p.Clone(); r.Container = this; return r; })); this.Properties.RemoveAll(p => p.Inherited); this.Groups.RemoveAll(p => p.Inherited); this.Hidden.RemoveAll(p => this.Items.All(item => item.Id != p)); foreach (var property in InheritedProperties.OfType<ExposedProperty>()) { var link = PrefabScript.Links[parentScript.Links[property.Target]]; property.Target = link == null ? null : link.InstanceTarget; if (property.Target == null) Debug.Log("Inherited property Error: Local target is not found Path:" + property.PropertyPath, this.PrefabScript); } } } return InheritedProperties; } public void Add(BaseExposedData exposed) { exposed.Container = this; var exposedProperty = exposed as ExposedProperty; if (exposedProperty != null) Add(exposedProperty); else Add(exposed as ExposedPropertyGroup); } public void Add(ExposedProperty exposed) { exposed.Container = this; if (!Properties.Contains(exposed)) Properties.Add(exposed); } public void Add(ExposedPropertyGroup exposed) { exposed.Container = this; if (!Groups.Contains(exposed)) Groups.Add(exposed); } public void Remove(int id) { Properties.RemoveAll(p => p.Id == id); Groups.RemoveAll(p => p.Id == id); } public ExposedProperty FindProperty(string label) { return Items.OfType<ExposedProperty>().FirstOrDefault(p => p.Label == label); } public ExposedProperty FindProperty(int id) { var result = Items.OfType<ExposedProperty>().FirstOrDefault(p => p.Id == id); return result; } public ExposedProperty FindProperty(uint id) { return Items.OfType<ExposedProperty>().FirstOrDefault(p => p.Id == (int)id); } public BaseExposedData this[int id] { get { return Items.FirstOrDefault(p => p.Id == id); } } public BaseExposedData this[string label] { get { return OrderedItems.FirstOrDefault(p => p.Label == label); } } public IEnumerable<BaseExposedData> Items { get { return GetInheritedProperties().Concat(Properties.OfType<BaseExposedData>().Concat(Groups.OfType <BaseExposedData>())); } } public IEnumerable<BaseExposedData> OrderedItems { get { var comparer = new BaseExposedData.Comparer(); var list = Items.ToList(); list.Sort(comparer); return list; } } public bool GetInherited(int id) { return GetInheritedProperties().Any(i => i.Id == id); } public bool GetHidden(int id) { return Hidden.Any(i => i == id); } public void SetHide(BaseExposedData property, bool state) { if (state == Hidden.Contains(property.Id)) return; if (state) Hidden.Add(property.Id); else Hidden.Remove(property.Id); Hidden.Sort(); } } public class BaseExposedData : ISerializationCallbackReceiver { [System.NonSerialized] public PEExposedProperties Container; [SerializeField] private int guid = System.Guid.NewGuid().GetHashCode(); public string Label; public int ParentId; public float Order; #region ISerializationCallbackReceiver implementation public virtual void OnBeforeSerialize() { } public virtual void OnAfterDeserialize() { } #endregion public int SiblingIndex { get { return this.Brothers.ToList().IndexOf(this); } } public float GetOrder(bool next) { var index = next ? SiblingIndex + 1 : SiblingIndex - 1; var nextBrother = this.Brothers.ElementAtOrDefault(index); return nextBrother == null ? this.Order + (next ? 1 : -1) : (this.Order + nextBrother.Order) * 0.5f; } public virtual BaseExposedData Clone() { var copy = System.Activator.CreateInstance(this.GetType()) as BaseExposedData; copy.ParentId = this.ParentId; copy.Label = this.Label; copy.guid = this.guid; copy.Order = this.Order; return copy; } public int Id { get { return guid; } } public BaseExposedData Parent { get { return this.Container[ParentId]; } set { this.ParentId = value.Id; } } public IEnumerable<BaseExposedData> Children { get { return this.Container.OrderedItems.Where(item => item.ParentId == this.Id); } } public IEnumerable<BaseExposedData> Brothers { get { var parent = this.Parent; return Container.OrderedItems.Where(i => i.Parent == parent); } } public bool Inherited { get { return Container.GetInherited(this.Id); } } public bool Hidden { get { return Container.GetHidden(Id); } set { Container.SetHide(this, value); } } public struct Comparer : IComparer<BaseExposedData> { public int Compare(BaseExposedData x, BaseExposedData y) { return (int)Mathf.Sign(x.Order - y.Order); } } } [System.Serializable] public class ExposedPropertyGroup : BaseExposedData { static public Dictionary<int, bool> expandedDict = new Dictionary<int, bool>(); private bool expandedLoaded; private bool expanded = true; public bool Expanded { get { if (!expandedLoaded) { expandedDict.TryGetValue(this.Id, out expanded); expandedLoaded = true; } return expanded; } set { if (value == expanded) return; if (!expandedDict.ContainsKey(this.Id)) expandedDict.Add(this.Id, true); expandedDict[this.Id] = value; this.expanded = value; } } } [System.Serializable] public class ExposedProperty : BaseExposedData { public Object Target; public string PropertyPath; public override BaseExposedData Clone() { var copy = (ExposedProperty)(base.Clone()); copy.Target = this.Target; copy.PropertyPath = this.PropertyPath; return copy; } #if ENABLE_REFLECTION public override void OnAfterDeserialize() { base.OnAfterDeserialize(); _invocationChain = null; } private PropertyInvocationChain _invocationChain; private PropertyInvocationChain invocationChain { get { if (_invocationChain == null) { _invocationChain = new PropertyInvocationChain(this.Target, this.PropertyPath); try { this.Value = this.Value; } catch (System.Exception e) { Debug.LogException(e); _invocationChain.members = null; } } return _invocationChain; } } public bool IsValid { get { return invocationChain.isValid; } } public object Value { get { if (!IsValid) { Debug.LogWarning("Trying to get value from invalid prefab property. Target:" + this.Target + " Property path:" + this.PropertyPath); return null; } return invocationChain.value; } set { if (!IsValid) { Debug.LogWarning("Trying to set value to invalid prefab property. [Target:" + this.Target + ", Property path:" + this.PropertyPath + "]"); return; } invocationChain.value = value; } #endif } #if ENABLE_REFLECTION public class PropertyInvocationChain { public object root; public string path; public InvokeInfo[] members; public PropertyInvocationChain(object root, string path) { this.root = root; this.path = path; GetInstance(root, path, out members); } public object value { get { var v = root; GetValidFieldName(ref v, this.path); for (var i = 0; i < members.Length; i++) { v = members[i].GetValue(v); } return v; } set { var v = root; GetValidFieldName(ref v, this.path); for (var i = 0; i < members.Length - 1; i++) { v = members[i].GetValue(v); } members[members.Length - 1].SetValue(v, value); for (var i = members.Length - 2; i >= 0; i--) { var member = members[i]; var nextMember = members[i + 1]; if (member.member.MemberType == MemberTypes.Property || member.valueType.IsValueType || nextMember.valueType.IsValueType) { member.SetValue(nextMember.tempTarget); } } } } public bool isValid { get { return members != null; } } public class InvokeInfo { public MemberInfo member; public int index = -1; public object tempTarget; public System.Type valueType; public object GetValue(object target) { tempTarget = target; return GetMemberValue(target, member, index); } public void SetValue(object target, object value) { tempTarget = target; setValue(target, member, value, index); } public void SetValue(object value) { setValue(tempTarget, member, value, index); } } static internal object GetInstance(object obj, string path, out InvokeInfo[] members) { path = path.Replace(".Array.data", ""); var split = path.Split('.'); var stack = split; object v = obj; members = new InvokeInfo[stack.Length]; try { var i = 0; foreach (var name in stack) { members[i] = new InvokeInfo(); if (name.Contains("[")) { var n = name.Split('[', ']'); var index = int.Parse(n[1]); members[i].index = index; v = getField(v, n[0], out members[i].member, index); } else v = getField(v, name, out members[i].member); var propertyMember = members[i].member as PropertyInfo; var fieldMember = members[i].member as FieldInfo; if (fieldMember != null) members[i].valueType = fieldMember.FieldType; else if (propertyMember != null) members[i].valueType = propertyMember.PropertyType; i++; } } catch (System.Exception e) { members = null; Debug.LogException(e); return null; } return v; } private static object GetMemberValue(object target, MemberInfo member, int index = -1) { object result = null; var fieldInfo = member as FieldInfo; if (fieldInfo != null) result = fieldInfo.GetValue(target); var propertyInfo = member as PropertyInfo; if (propertyInfo != null) result = propertyInfo.GetValue(target, null); return result != null ? index == -1 ? result : (result as IList)[index] : null; } private static void setValue(object target, MemberInfo member, object value, int index = -1) { if (index != -1) { target = GetMemberValue(target, member); (target as IList)[index] = value; return; } var fieldInfo = member as FieldInfo; if (fieldInfo != null) fieldInfo.SetValue(target, value); var propertyInfo = member as PropertyInfo; if (propertyInfo != null) propertyInfo.SetValue(target, value, null); } static public string GetValidFieldName(ref object obj, string fieldName) { if (obj is Renderer && fieldName == "m_Materials") return "sharedMaterials"; if (obj is MeshFilter && fieldName == "m_Mesh") return "sharedMesh"; if (obj is GameObject && fieldName == "m_IsActive") obj = new GameObjectWrapper(obj as GameObject); return fieldName; } private static object getField(object obj, string field, out MemberInfo member, int index = -1) { member = null; try { var flags = BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase; if (obj == null) return null; field = GetValidFieldName(ref obj, field); var type = obj.GetType(); member = type.GetField(field, flags); if (member == null && field.StartsWith("m_")) member = type.GetField(field.Remove(0, 2), flags); member = type.GetProperty(field, flags); if (member == null && field.StartsWith("m_")) member = type.GetProperty(field.Remove(0, 2), flags); if (member == null) member = type.GetMembers(flags).First(m => m.Name.ToUpper() == field.ToUpper()); if (member != null) return GetMemberValue(obj, member, index); member = null; return null; } catch (System.Exception) { member = null; return null; } } } } #endif #region Wrappers static public class Wrappers { } public class GameObjectWrapper { public GameObject target; public bool m_IsActive { get { return target.activeSelf; } set { target.SetActive(value); } } public GameObjectWrapper(GameObject target) { this.target = target; } } #endregion }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure; using Microsoft.Azure.Management.Compute; using Microsoft.Azure.Management.Compute.Models; namespace Microsoft.Azure.Management.Compute { /// <summary> /// The Compute Management Client. /// </summary> public static partial class AvailabilitySetOperationsExtensions { /// <summary> /// The operation to create or update the availability set. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Compute.IAvailabilitySetOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the Create Availability Set /// operation. /// </param> /// <returns> /// The Create Availability Set operation response. /// </returns> public static AvailabilitySetCreateOrUpdateResponse CreateOrUpdate(this IAvailabilitySetOperations operations, string resourceGroupName, AvailabilitySet parameters) { return Task.Factory.StartNew((object s) => { return ((IAvailabilitySetOperations)s).CreateOrUpdateAsync(resourceGroupName, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The operation to create or update the availability set. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Compute.IAvailabilitySetOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the Create Availability Set /// operation. /// </param> /// <returns> /// The Create Availability Set operation response. /// </returns> public static Task<AvailabilitySetCreateOrUpdateResponse> CreateOrUpdateAsync(this IAvailabilitySetOperations operations, string resourceGroupName, AvailabilitySet parameters) { return operations.CreateOrUpdateAsync(resourceGroupName, parameters, CancellationToken.None); } /// <summary> /// The operation to delete the availability set. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Compute.IAvailabilitySetOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='availabilitySetName'> /// Required. The name of the availability set. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static AzureOperationResponse Delete(this IAvailabilitySetOperations operations, string resourceGroupName, string availabilitySetName) { return Task.Factory.StartNew((object s) => { return ((IAvailabilitySetOperations)s).DeleteAsync(resourceGroupName, availabilitySetName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The operation to delete the availability set. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Compute.IAvailabilitySetOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='availabilitySetName'> /// Required. The name of the availability set. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static Task<AzureOperationResponse> DeleteAsync(this IAvailabilitySetOperations operations, string resourceGroupName, string availabilitySetName) { return operations.DeleteAsync(resourceGroupName, availabilitySetName, CancellationToken.None); } /// <summary> /// The operation to get the availability set. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Compute.IAvailabilitySetOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='availabilitySetName'> /// Required. The name of the availability set. /// </param> /// <returns> /// GET Availability Set operation response. /// </returns> public static AvailabilitySetGetResponse Get(this IAvailabilitySetOperations operations, string resourceGroupName, string availabilitySetName) { return Task.Factory.StartNew((object s) => { return ((IAvailabilitySetOperations)s).GetAsync(resourceGroupName, availabilitySetName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The operation to get the availability set. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Compute.IAvailabilitySetOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='availabilitySetName'> /// Required. The name of the availability set. /// </param> /// <returns> /// GET Availability Set operation response. /// </returns> public static Task<AvailabilitySetGetResponse> GetAsync(this IAvailabilitySetOperations operations, string resourceGroupName, string availabilitySetName) { return operations.GetAsync(resourceGroupName, availabilitySetName, CancellationToken.None); } /// <summary> /// The operation to list the availability sets. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Compute.IAvailabilitySetOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <returns> /// The List Availability Set operation response. /// </returns> public static AvailabilitySetListResponse List(this IAvailabilitySetOperations operations, string resourceGroupName) { return Task.Factory.StartNew((object s) => { return ((IAvailabilitySetOperations)s).ListAsync(resourceGroupName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The operation to list the availability sets. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Compute.IAvailabilitySetOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <returns> /// The List Availability Set operation response. /// </returns> public static Task<AvailabilitySetListResponse> ListAsync(this IAvailabilitySetOperations operations, string resourceGroupName) { return operations.ListAsync(resourceGroupName, CancellationToken.None); } /// <summary> /// Lists virtual-machine-sizes available to be used for an /// availability set. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Compute.IAvailabilitySetOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='availabilitySetName'> /// Required. The name of the availability set. /// </param> /// <returns> /// The List Virtual Machine operation response. /// </returns> public static VirtualMachineSizeListResponse ListAvailableSizes(this IAvailabilitySetOperations operations, string resourceGroupName, string availabilitySetName) { return Task.Factory.StartNew((object s) => { return ((IAvailabilitySetOperations)s).ListAvailableSizesAsync(resourceGroupName, availabilitySetName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Lists virtual-machine-sizes available to be used for an /// availability set. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Compute.IAvailabilitySetOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='availabilitySetName'> /// Required. The name of the availability set. /// </param> /// <returns> /// The List Virtual Machine operation response. /// </returns> public static Task<VirtualMachineSizeListResponse> ListAvailableSizesAsync(this IAvailabilitySetOperations operations, string resourceGroupName, string availabilitySetName) { return operations.ListAvailableSizesAsync(resourceGroupName, availabilitySetName, CancellationToken.None); } } }
/* * 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: * * 1) Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2) 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.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using Newtonsoft.Json; namespace XenAPI { /// <summary> /// The metrics associated with a host /// First published in XenServer 4.0. /// </summary> public partial class Host_metrics : XenObject<Host_metrics> { #region Constructors public Host_metrics() { } public Host_metrics(string uuid, long memory_total, long memory_free, bool live, DateTime last_updated, Dictionary<string, string> other_config) { this.uuid = uuid; this.memory_total = memory_total; this.memory_free = memory_free; this.live = live; this.last_updated = last_updated; this.other_config = other_config; } /// <summary> /// Creates a new Host_metrics from a Hashtable. /// Note that the fields not contained in the Hashtable /// will be created with their default values. /// </summary> /// <param name="table"></param> public Host_metrics(Hashtable table) : this() { UpdateFrom(table); } /// <summary> /// Creates a new Host_metrics from a Proxy_Host_metrics. /// </summary> /// <param name="proxy"></param> public Host_metrics(Proxy_Host_metrics proxy) { UpdateFrom(proxy); } #endregion /// <summary> /// Updates each field of this instance with the value of /// the corresponding field of a given Host_metrics. /// </summary> public override void UpdateFrom(Host_metrics update) { uuid = update.uuid; memory_total = update.memory_total; memory_free = update.memory_free; live = update.live; last_updated = update.last_updated; other_config = update.other_config; } internal void UpdateFrom(Proxy_Host_metrics proxy) { uuid = proxy.uuid == null ? null : proxy.uuid; memory_total = proxy.memory_total == null ? 0 : long.Parse(proxy.memory_total); memory_free = proxy.memory_free == null ? 0 : long.Parse(proxy.memory_free); live = (bool)proxy.live; last_updated = proxy.last_updated; other_config = proxy.other_config == null ? null : Maps.convert_from_proxy_string_string(proxy.other_config); } public Proxy_Host_metrics ToProxy() { Proxy_Host_metrics result_ = new Proxy_Host_metrics(); result_.uuid = uuid ?? ""; result_.memory_total = memory_total.ToString(); result_.memory_free = memory_free.ToString(); result_.live = live; result_.last_updated = last_updated; result_.other_config = Maps.convert_to_proxy_string_string(other_config); return result_; } /// <summary> /// Given a Hashtable with field-value pairs, it updates the fields of this Host_metrics /// with the values listed in the Hashtable. Note that only the fields contained /// in the Hashtable will be updated and the rest will remain the same. /// </summary> /// <param name="table"></param> public void UpdateFrom(Hashtable table) { if (table.ContainsKey("uuid")) uuid = Marshalling.ParseString(table, "uuid"); if (table.ContainsKey("memory_total")) memory_total = Marshalling.ParseLong(table, "memory_total"); if (table.ContainsKey("memory_free")) memory_free = Marshalling.ParseLong(table, "memory_free"); if (table.ContainsKey("live")) live = Marshalling.ParseBool(table, "live"); if (table.ContainsKey("last_updated")) last_updated = Marshalling.ParseDateTime(table, "last_updated"); if (table.ContainsKey("other_config")) other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config")); } public bool DeepEquals(Host_metrics other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return Helper.AreEqual2(this._uuid, other._uuid) && Helper.AreEqual2(this._memory_total, other._memory_total) && Helper.AreEqual2(this._memory_free, other._memory_free) && Helper.AreEqual2(this._live, other._live) && Helper.AreEqual2(this._last_updated, other._last_updated) && Helper.AreEqual2(this._other_config, other._other_config); } internal static List<Host_metrics> ProxyArrayToObjectList(Proxy_Host_metrics[] input) { var result = new List<Host_metrics>(); foreach (var item in input) result.Add(new Host_metrics(item)); return result; } public override string SaveChanges(Session session, string opaqueRef, Host_metrics server) { if (opaqueRef == null) { System.Diagnostics.Debug.Assert(false, "Cannot create instances of this type on the server"); return ""; } else { if (!Helper.AreEqual2(_other_config, server._other_config)) { Host_metrics.set_other_config(session, opaqueRef, _other_config); } return null; } } /// <summary> /// Get a record containing the current state of the given host_metrics. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_host_metrics">The opaque_ref of the given host_metrics</param> public static Host_metrics get_record(Session session, string _host_metrics) { if (session.JsonRpcClient != null) return session.JsonRpcClient.host_metrics_get_record(session.opaque_ref, _host_metrics); else return new Host_metrics(session.proxy.host_metrics_get_record(session.opaque_ref, _host_metrics ?? "").parse()); } /// <summary> /// Get a reference to the host_metrics instance with the specified UUID. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_uuid">UUID of object to return</param> public static XenRef<Host_metrics> get_by_uuid(Session session, string _uuid) { if (session.JsonRpcClient != null) return session.JsonRpcClient.host_metrics_get_by_uuid(session.opaque_ref, _uuid); else return XenRef<Host_metrics>.Create(session.proxy.host_metrics_get_by_uuid(session.opaque_ref, _uuid ?? "").parse()); } /// <summary> /// Get the uuid field of the given host_metrics. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_host_metrics">The opaque_ref of the given host_metrics</param> public static string get_uuid(Session session, string _host_metrics) { if (session.JsonRpcClient != null) return session.JsonRpcClient.host_metrics_get_uuid(session.opaque_ref, _host_metrics); else return session.proxy.host_metrics_get_uuid(session.opaque_ref, _host_metrics ?? "").parse(); } /// <summary> /// Get the memory/total field of the given host_metrics. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_host_metrics">The opaque_ref of the given host_metrics</param> public static long get_memory_total(Session session, string _host_metrics) { if (session.JsonRpcClient != null) return session.JsonRpcClient.host_metrics_get_memory_total(session.opaque_ref, _host_metrics); else return long.Parse(session.proxy.host_metrics_get_memory_total(session.opaque_ref, _host_metrics ?? "").parse()); } /// <summary> /// Get the memory/free field of the given host_metrics. /// First published in XenServer 4.0. /// Deprecated since XenServer 5.6. /// </summary> /// <param name="session">The session</param> /// <param name="_host_metrics">The opaque_ref of the given host_metrics</param> [Deprecated("XenServer 5.6")] public static long get_memory_free(Session session, string _host_metrics) { if (session.JsonRpcClient != null) return session.JsonRpcClient.host_metrics_get_memory_free(session.opaque_ref, _host_metrics); else return long.Parse(session.proxy.host_metrics_get_memory_free(session.opaque_ref, _host_metrics ?? "").parse()); } /// <summary> /// Get the live field of the given host_metrics. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_host_metrics">The opaque_ref of the given host_metrics</param> public static bool get_live(Session session, string _host_metrics) { if (session.JsonRpcClient != null) return session.JsonRpcClient.host_metrics_get_live(session.opaque_ref, _host_metrics); else return (bool)session.proxy.host_metrics_get_live(session.opaque_ref, _host_metrics ?? "").parse(); } /// <summary> /// Get the last_updated field of the given host_metrics. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_host_metrics">The opaque_ref of the given host_metrics</param> public static DateTime get_last_updated(Session session, string _host_metrics) { if (session.JsonRpcClient != null) return session.JsonRpcClient.host_metrics_get_last_updated(session.opaque_ref, _host_metrics); else return session.proxy.host_metrics_get_last_updated(session.opaque_ref, _host_metrics ?? "").parse(); } /// <summary> /// Get the other_config field of the given host_metrics. /// First published in XenServer 5.0. /// </summary> /// <param name="session">The session</param> /// <param name="_host_metrics">The opaque_ref of the given host_metrics</param> public static Dictionary<string, string> get_other_config(Session session, string _host_metrics) { if (session.JsonRpcClient != null) return session.JsonRpcClient.host_metrics_get_other_config(session.opaque_ref, _host_metrics); else return Maps.convert_from_proxy_string_string(session.proxy.host_metrics_get_other_config(session.opaque_ref, _host_metrics ?? "").parse()); } /// <summary> /// Set the other_config field of the given host_metrics. /// First published in XenServer 5.0. /// </summary> /// <param name="session">The session</param> /// <param name="_host_metrics">The opaque_ref of the given host_metrics</param> /// <param name="_other_config">New value to set</param> public static void set_other_config(Session session, string _host_metrics, Dictionary<string, string> _other_config) { if (session.JsonRpcClient != null) session.JsonRpcClient.host_metrics_set_other_config(session.opaque_ref, _host_metrics, _other_config); else session.proxy.host_metrics_set_other_config(session.opaque_ref, _host_metrics ?? "", Maps.convert_to_proxy_string_string(_other_config)).parse(); } /// <summary> /// Add the given key-value pair to the other_config field of the given host_metrics. /// First published in XenServer 5.0. /// </summary> /// <param name="session">The session</param> /// <param name="_host_metrics">The opaque_ref of the given host_metrics</param> /// <param name="_key">Key to add</param> /// <param name="_value">Value to add</param> public static void add_to_other_config(Session session, string _host_metrics, string _key, string _value) { if (session.JsonRpcClient != null) session.JsonRpcClient.host_metrics_add_to_other_config(session.opaque_ref, _host_metrics, _key, _value); else session.proxy.host_metrics_add_to_other_config(session.opaque_ref, _host_metrics ?? "", _key ?? "", _value ?? "").parse(); } /// <summary> /// Remove the given key and its corresponding value from the other_config field of the given host_metrics. If the key is not in that Map, then do nothing. /// First published in XenServer 5.0. /// </summary> /// <param name="session">The session</param> /// <param name="_host_metrics">The opaque_ref of the given host_metrics</param> /// <param name="_key">Key to remove</param> public static void remove_from_other_config(Session session, string _host_metrics, string _key) { if (session.JsonRpcClient != null) session.JsonRpcClient.host_metrics_remove_from_other_config(session.opaque_ref, _host_metrics, _key); else session.proxy.host_metrics_remove_from_other_config(session.opaque_ref, _host_metrics ?? "", _key ?? "").parse(); } /// <summary> /// Return a list of all the host_metrics instances known to the system. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> public static List<XenRef<Host_metrics>> get_all(Session session) { if (session.JsonRpcClient != null) return session.JsonRpcClient.host_metrics_get_all(session.opaque_ref); else return XenRef<Host_metrics>.Create(session.proxy.host_metrics_get_all(session.opaque_ref).parse()); } /// <summary> /// Get all the host_metrics Records at once, in a single XML RPC call /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> public static Dictionary<XenRef<Host_metrics>, Host_metrics> get_all_records(Session session) { if (session.JsonRpcClient != null) return session.JsonRpcClient.host_metrics_get_all_records(session.opaque_ref); else return XenRef<Host_metrics>.Create<Proxy_Host_metrics>(session.proxy.host_metrics_get_all_records(session.opaque_ref).parse()); } /// <summary> /// Unique identifier/object reference /// </summary> public virtual string uuid { get { return _uuid; } set { if (!Helper.AreEqual(value, _uuid)) { _uuid = value; Changed = true; NotifyPropertyChanged("uuid"); } } } private string _uuid = ""; /// <summary> /// Total host memory (bytes) /// </summary> public virtual long memory_total { get { return _memory_total; } set { if (!Helper.AreEqual(value, _memory_total)) { _memory_total = value; Changed = true; NotifyPropertyChanged("memory_total"); } } } private long _memory_total; /// <summary> /// Free host memory (bytes) /// </summary> public virtual long memory_free { get { return _memory_free; } set { if (!Helper.AreEqual(value, _memory_free)) { _memory_free = value; Changed = true; NotifyPropertyChanged("memory_free"); } } } private long _memory_free; /// <summary> /// Pool master thinks this host is live /// </summary> public virtual bool live { get { return _live; } set { if (!Helper.AreEqual(value, _live)) { _live = value; Changed = true; NotifyPropertyChanged("live"); } } } private bool _live; /// <summary> /// Time at which this information was last updated /// </summary> [JsonConverter(typeof(XenDateTimeConverter))] public virtual DateTime last_updated { get { return _last_updated; } set { if (!Helper.AreEqual(value, _last_updated)) { _last_updated = value; Changed = true; NotifyPropertyChanged("last_updated"); } } } private DateTime _last_updated; /// <summary> /// additional configuration /// First published in XenServer 5.0. /// </summary> [JsonConverter(typeof(StringStringMapConverter))] public virtual Dictionary<string, string> other_config { get { return _other_config; } set { if (!Helper.AreEqual(value, _other_config)) { _other_config = value; Changed = true; NotifyPropertyChanged("other_config"); } } } private Dictionary<string, string> _other_config = new Dictionary<string, string>() {}; } }
/* **************************************************************************** * * Copyright (c) Microsoft Corporation. * * This source code is subject to terms and conditions of the Apache License, Version 2.0. A * copy of the license can be found in the License.html file at the root of this distribution. If * you cannot locate the Apache License, Version 2.0, please send an email to * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound * by the terms of the Apache License, Version 2.0. * * You must not remove this notice, or any other, from this software. * * * ***************************************************************************/ using System; using System.Reflection; using Microsoft.Scripting; using RowanTest.Common; using MutableTuple = Microsoft.Scripting.MutableTuple; using System.Runtime.CompilerServices; namespace TestInternalDLR { // Strongbox should not ever be sealed class MyStrongBox<T> : System.Runtime.CompilerServices.StrongBox<T> { public MyStrongBox(T value) : base(value) { } } class TestTuple : BaseTest { public void VerifyTuple(int size) { //Construct a tuple of the right type MethodInfo mi = typeof(MutableTuple).GetMethod("MakeTupleType",BindingFlags.Public | BindingFlags.Static); Assert(mi!=null,"Could not find Tuple.MakeTupleType"); Type[] args = new Type[size]; object[] values = new object[size]; for (int i = 0; i < size; i++) { args[i] = typeof(int); values[i] = 0; } Type tupleType = (Type)mi.Invoke(null, new object[] { args }); MutableTuple t = MutableTuple.MakeTuple(tupleType, values); ///////////////////// //Properties //Write for (int i=0; i< size; i++){ object o = t; foreach (PropertyInfo pi in MutableTuple.GetAccessPath(tupleType,i)){ if (typeof(MutableTuple).IsAssignableFrom(pi.PropertyType)) o = pi.GetValue(o, null); else pi.SetValue(o, i * 5, null); } } //Read for (int i=0; i< size; i++){ object o = t; foreach (PropertyInfo pi in MutableTuple.GetAccessPath(tupleType,i)) o = pi.GetValue(o,null); AreEqual(typeof(int),o.GetType()); AreEqual((int)o,i*5); } //Negative cases for properties AssertError<ArgumentException>(delegate() { foreach (PropertyInfo pi in MutableTuple.GetAccessPath(tupleType, -1)) Console.WriteLine(pi.Name); //This won't run, but we need it so that this call isn't inlined }); ///////////////////// //GetTupleValues values = MutableTuple.GetTupleValues(t); AreEqual(values.Length, size); for(int i=0; i<size; i++) { AreEqual(typeof(int), values[i].GetType()); AreEqual((int)(values[i]), i * 5); } ///////////////////// //Access methods if (size <= MutableTuple.MaxSize) { //SetValue for (int i=0; i < size; i++) t.SetValue(i, i * 3); //GetValue for (int i=0; i < size; i++) AreEqual(t.GetValue(i), i * 3); //Ensure there are no extras if(tupleType.GetGenericArguments().Length<=size){ //We're requesting an index beyond the end of this tuple. AssertError<ArgumentException>(delegate() { t.SetValue(size, 3); }); AssertError<ArgumentException>(delegate() { t.GetValue(size); }); } else { /*We're requesting an index in the scope of this tuple but beyond the scope of our requested capacity (in which case the field's type will be Microsoft.Scripting.None and we won't be able to convert "3" to that). Imagine asking for a tuple of 3 ints, we'd actually get a Tuple<int,int,int,Microsoft.Scripting.None> since there is no Tuple that takes only 3 generic arguments.*/ AssertError<InvalidCastException>(delegate() { t.SetValue(size, 3); }); //Verify the type of the field AreEqual(typeof(Microsoft.Scripting.Runtime.DynamicNull), tupleType.GetGenericArguments()[size]); //Verify the value of the field is null AreEqual(null, t.GetValue(size)); } } } public void TestBasic() { foreach (int i in new int[] { 1, 2, 4, 8, 16, 32, 64, 127, 128, 129, 256, 512, 1024, 24, 96 }) { VerifyTuple(i); } } // Quick validation of this. public void TestStrongBox() { MyStrongBox<int> sb = new MyStrongBox<int>(5); AreEqual(sb.Value, 5); } } // Basic tests for ReadOnlyCollectionBuilder<T> class TestROCBuilder : BaseTest { public void TestReadOnlyCollectionBuilder() { int cnt = 0; // Empty ReadOnlyCollectionBuilder<int> a = new ReadOnlyCollectionBuilder<int>(); AreEqual(0, a.Count); AreEqual(0, a.Capacity ); AreEqual(a.ToReadOnlyCollection().Count, 0); AreEqual(a.ToReadOnlyCollection().Count, 0); // Simple case a.Add(5); AreEqual(1, a.Count); AreEqual(4, a.Capacity); AreEqual(a.ToReadOnlyCollection()[0], 5); AreEqual(a.ToReadOnlyCollection().Count, 0); // Will reset a = new ReadOnlyCollectionBuilder<int>(0); AreEqual(0, a.Count); AssertError<ArgumentException>(() => a = new ReadOnlyCollectionBuilder<int>(-1)); a = new ReadOnlyCollectionBuilder<int>(5); for (int i = 1; i <= 10; i++) { a.Add(i); } AreEqual(10, a.Capacity); System.Collections.ObjectModel.ReadOnlyCollection<int> readonlyCollection = a.ToReadOnlyCollection(); AreEqual(0, a.Capacity); AreEqual(readonlyCollection.Count , 10); ReadOnlyCollectionBuilder<int> b = new ReadOnlyCollectionBuilder<int>(readonlyCollection); b.Add(11); AreEqual(b.Count, 11); AssertError<ArgumentException>(() => a = new ReadOnlyCollectionBuilder<int>(null)); // Capacity tests b.Capacity = 11; AssertError<ArgumentException>(() => b.Capacity = 10); b.Capacity = 50; AreEqual(b.Count, 11); AreEqual(b.Capacity , 50); // IndexOf cases AreEqual(b.IndexOf(5), 4); AreEqual(b[4], 5); a = new ReadOnlyCollectionBuilder<int>(); AreEqual(a.IndexOf(5), -1); // Insert cases b = new ReadOnlyCollectionBuilder<int>(readonlyCollection); AssertError<ArgumentException>(() => b.Insert(11,11)); b.Insert(2, 24); AreEqual(b.Count, 11); AreEqual(b[1], 2); AreEqual(b[2], 24); AreEqual(b[3], 3); b.Insert(11, 1234); AssertError<ArgumentException>(() => b.Insert(-1, 55)); AreEqual(b[11], 1234); AreEqual(b.ToReadOnlyCollection().Count, 12); // Remove b = new ReadOnlyCollectionBuilder<int>(readonlyCollection); AreEqual(b.Remove(2),true); AreEqual(b[0], 1); AreEqual(b[1], 3); AreEqual(b[2], 4); AreEqual(b.Remove(2), false); // RemoveAt b = new ReadOnlyCollectionBuilder<int>(readonlyCollection); b.RemoveAt(2); AreEqual(b[1], 2); AreEqual(b[2], 4); AreEqual(b[3], 5); AssertError<ArgumentException>(() => b.RemoveAt(-5)); AssertError<ArgumentException>(() => b.RemoveAt(9)); // Clear b.Clear(); AreEqual(b.Count, 0); AreEqual(b.ToReadOnlyCollection().Count , 0); b = new ReadOnlyCollectionBuilder<int>(); b.Clear(); AreEqual(b.Count, 0); // Contains b = new ReadOnlyCollectionBuilder<int>(readonlyCollection); AreEqual(b.Contains(5), true); AreEqual(b.Contains(-3), false); ReadOnlyCollectionBuilder<object> c = new ReadOnlyCollectionBuilder<object>(); c.Add("HI"); AreEqual(c.Contains("HI"), true); AreEqual(c.Contains(null), false); c.Add(null); AreEqual(c.Contains(null), true); // CopyTo b = new ReadOnlyCollectionBuilder<int>(readonlyCollection); int[] ary = new int[10]; b.CopyTo(ary, 0); AreEqual(ary[0], 1); AreEqual(ary[9], 10); // Reverse b = new ReadOnlyCollectionBuilder<int>(readonlyCollection); b.Reverse(); // 1..10 cnt = 10; for (int i = 0; i < 10; i++) { AreEqual(b[i], cnt--); } b = new ReadOnlyCollectionBuilder<int>(readonlyCollection); AssertError<ArgumentException>(() => b.Reverse(-1,5)); AssertError<ArgumentException>(() => b.Reverse(5,-1)); b.Reverse(3, 3); // 1,2,3,4,5,6,7,8,9.10 // 1,2,3,6,5,4,7,8,9,10 AreEqual(b[1], 2); AreEqual(b[2], 3); AreEqual(b[3], 6); AreEqual(b[4], 5); AreEqual(b[5], 4); AreEqual(b[6], 7); // ToArray b = new ReadOnlyCollectionBuilder<int>(readonlyCollection); int[] intAry = b.ToArray(); AreEqual(intAry[0], 1); AreEqual(intAry[9], 10); b = new ReadOnlyCollectionBuilder<int>(); intAry = b.ToArray(); AreEqual(intAry.Length, 0); // IEnumerable cases b = new ReadOnlyCollectionBuilder<int>(readonlyCollection); cnt = 0; foreach (int i in b) { cnt++; } AreEqual(cnt, 10); b = new ReadOnlyCollectionBuilder<int>(); cnt = 0; foreach (int i in b) { cnt++; } AreEqual(cnt, 0); // Error case AssertError<InvalidOperationException>(() => ChangeWhileEnumeratingAdd()); AssertError<InvalidOperationException>(() => ChangeWhileEnumeratingRemove()); // IList members b = new ReadOnlyCollectionBuilder<int>(readonlyCollection); System.Collections.IList lst = b; // IsReadOnly AreEqual(lst.IsReadOnly, false); // Add AreEqual(lst.Add(11), 10); AreEqual(lst.Count,11); AssertError<ArgumentException>(() => lst.Add("MOM")); AssertError<ArgumentException>(() => lst.Add(null)); c = new ReadOnlyCollectionBuilder<object>(); c.Add("HI"); c.Add(null); lst = c; lst.Add(null); AreEqual(lst.Count, 3); // Contains lst = b; AreEqual(lst.Contains(5), true); AreEqual(lst.Contains(null), false); lst = c; AreEqual(lst.Contains("HI"), true); AreEqual(lst.Contains("hi"), false); AreEqual(lst.Contains(null), true); // IndexOf lst = b; AreEqual(lst.IndexOf(null), -1); AreEqual(lst.IndexOf(1234), -1); AreEqual(lst.IndexOf(5), 4); // Insert b = new ReadOnlyCollectionBuilder<int>(readonlyCollection); lst = b; AssertError<ArgumentException>(() => lst.Insert(11, 11)); lst.Insert(2, 24); AreEqual(lst.Count, 11); AreEqual(lst[1], 2); AreEqual(lst[2], 24); AreEqual(lst[3], 3); lst.Insert(11, 1234); AssertError<ArgumentException>(() => lst.Insert(-1, 55)); AreEqual(lst[11], 1234); AssertError<ArgumentException>(() => lst.Insert(3,"MOM")); // IsFixedSize AreEqual(lst.IsFixedSize, false); // Remove b = new ReadOnlyCollectionBuilder<int>(readonlyCollection); lst = b; lst.Remove(2); AreEqual(lst[0], 1); AreEqual(lst[1], 3); AreEqual(lst[2], 4); lst.Remove(2); // Indexing lst[3] = 234; AreEqual(lst[3], 234); AssertError<ArgumentException>(() => lst[3] = null); AssertError<ArgumentException>(() => lst[3] = "HI"); // ICollection<T> // IsReadOnly System.Collections.Generic.ICollection<int> col = b; AreEqual(col.IsReadOnly, false); // ICollection b = new ReadOnlyCollectionBuilder<int>(readonlyCollection); System.Collections.ICollection col2 = b; AreEqual(col2.IsSynchronized, false); Assert(col2.SyncRoot != null); intAry = new int[10]; col2.CopyTo(intAry, 0); AreEqual(intAry[0], 1); AreEqual(intAry[9], 10); string[] str = new string[50]; AssertError<ArrayTypeMismatchException>(() => col2.CopyTo(str,0)); } void ChangeWhileEnumeratingAdd() { ReadOnlyCollectionBuilder<int> b = new ReadOnlyCollectionBuilder<int>(); b.Add(5); b.Add(6); foreach (int i in b) { b.Add(234); } } void ChangeWhileEnumeratingRemove() { ReadOnlyCollectionBuilder<int> b = new ReadOnlyCollectionBuilder<int>(); b.Add(5); b.Add(6); foreach (int i in b) { b.Remove(5); } } } }
using System; using System.Collections; using System.Data; using System.Data.SqlClient; using System.Text.RegularExpressions; using System.Threading; using System.Transactions; using MbUnit.Framework; using Northwind; namespace SubSonic.Tests { /// <summary> /// Tests SubSonics behavior with regard to using TransactionScope and SharedDbConnectionScope /// when the DTC is turned off. /// </summary> [TestFixture] public class TransactionWithDtcOffTests { private const int MaxRandomNumber = 10000; private readonly Regex _dtcErrorMessage = new Regex("MSDTC on server '.*' is unavailable"); private readonly Regex errorMessageTransAbort = new Regex("The transaction has aborted."); /// <summary> /// Used to generate random numbers that are embedded in strings that get presisted to the database /// </summary> private readonly Random _rand = new Random(); private readonly MsDtcService msdtc = new MsDtcService(); /// <summary> /// Tests the fixture set up. /// </summary> [FixtureSetUp] public void TestFixtureSetUp() { msdtc.Stop(); } /// <summary> /// Tests the fixture tear down. /// </summary> [FixtureTearDown] public void TestFixtureTearDown() { msdtc.Revert(); } /// <summary> /// Noes the transaction scope_ can retrieve single product. /// </summary> [Test] public void NoTransactionScope_CanRetrieveSingleProduct() { Product p1 = new Product(1); Assert.AreEqual(1, p1.ProductID); } /// <summary> /// Noes the transaction scope_ can retrieve multiple products. /// </summary> [Test] public void NoTransactionScope_CanRetrieveMultipleProducts() { Product p1 = new Product(1); Product p2 = new Product(2); Assert.AreEqual(1, p1.ProductID); Assert.AreEqual(2, p2.ProductID); } /// <summary> /// Retrieves the multiple products_ fails without shared connection. /// </summary> [Test] public void RetrieveMultipleProducts_FailsWithoutSharedConnection() { string errorMessage = String.Empty; try { using(TransactionScope ts = new TransactionScope()) { Product p1 = new Product(1); Product p2 = new Product(2); Assert.AreEqual(1, p1.ProductID); Assert.AreEqual(2, p2.ProductID); } } catch(Exception e) { errorMessage = e.Message; } Assert.IsTrue(_dtcErrorMessage.IsMatch(errorMessage) || errorMessageTransAbort.IsMatch(errorMessage), errorMessage); } /// <summary> /// Determines whether this instance [can retrieve multiple entities_ fails without shared connection scope]. /// </summary> [Test] public void CanRetrieveMultipleEntities_FailsWithoutSharedConnectionScope() { string errorMessage = String.Empty; try { using(TransactionScope ts = new TransactionScope()) { Product p1 = new Product(1); Product p2 = new Product(2); Order o1 = new Order(1); Order o2 = new Order(2); Assert.AreEqual(1, p1.ProductID); Assert.AreEqual(2, p2.ProductID); Assert.AreEqual(1, o1.OrderID); Assert.AreEqual(2, o2.OrderID); } } catch(Exception e) { errorMessage = e.Message; } Assert.IsTrue(_dtcErrorMessage.IsMatch(errorMessage) || errorMessageTransAbort.IsMatch(errorMessage), errorMessage); } /// <summary> /// Determines whether this instance [can retrieve multiple entities_ succeeds with shared connection scope]. /// </summary> [Test] public void CanRetrieveMultipleEntities_SucceedsWithSharedConnectionScope() { using(TransactionScope ts = new TransactionScope()) { using(SharedDbConnectionScope connScope = new SharedDbConnectionScope()) { Product p1 = new Product(1); Product p2 = new Product(2); Order o1 = new Order(10248); Order o2 = new Order(10249); Assert.AreEqual(1, p1.ProductID); Assert.AreEqual(2, p2.ProductID); Assert.AreEqual(10248, o1.OrderID); Assert.AreEqual(10249, o2.OrderID); } } } /// <summary> /// Updates the single product_ succeeds using shared connection. /// </summary> [Test] public void UpdateSingleProduct_SucceedsUsingSharedConnection() { using(TransactionScope ts = new TransactionScope()) { using(SharedDbConnectionScope connScope = new SharedDbConnectionScope()) SaveProduct(1, "new name of product"); } } /// <summary> /// Updates the single product retrieve multiple products_ fails without shared connection. /// </summary> [Test] public void UpdateSingleProductRetrieveMultipleProducts_FailsWithoutSharedConnection() { string errorMessage = String.Empty; try { using(TransactionScope ts = new TransactionScope()) { SaveProduct(1, "new name of product"); Product p2 = new Product(2); Product p3 = new Product(3); } } catch(Exception e) { errorMessage = e.Message; } Assert.IsTrue(_dtcErrorMessage.IsMatch(errorMessage) || errorMessageTransAbort.IsMatch(errorMessage), errorMessage); } /// <summary> /// Updates the single product retrieve multiple products_ succeeds with shared connection. /// </summary> [Test] public void UpdateSingleProductRetrieveMultipleProducts_SucceedsWithSharedConnection() { string p1OriginalProductName = new Product(1).ProductName; using(TransactionScope ts = new TransactionScope()) { using(SharedDbConnectionScope connScope = new SharedDbConnectionScope()) { SaveProduct(1, "new name of product"); Product p2 = new Product(2); Product p3 = new Product(3); } } Assert.AreEqual(p1OriginalProductName, new Product(1).ProductName, "Transaction NOT rolled back"); } /// <summary> /// Updates the single product_ commit change to database. /// </summary> [Test] public void UpdateSingleProduct_CommitChangeToDatabase() { string newProductName = "new name of product 20: " + _rand.Next(MaxRandomNumber); using(TransactionScope ts = new TransactionScope()) { using(SharedDbConnectionScope connScope = new SharedDbConnectionScope()) { SaveProduct(20, newProductName); Product p2 = new Product(2); Product p3 = new Product(3); ts.Complete(); } } Assert.AreEqual(newProductName, new Product(20).ProductName, "Transaction Not Committed"); } /// <summary> /// Updates the multiple products_ fails without shared connection. /// </summary> [Test] public void UpdateMultipleProducts_FailsWithoutSharedConnection() { string errorMessage = String.Empty; try { using(TransactionScope ts = new TransactionScope()) { SaveProduct(1, "new name of product 1"); SaveProduct(2, "new name of product 2"); } } catch(Exception e) { errorMessage = e.Message; } Assert.IsTrue(_dtcErrorMessage.IsMatch(errorMessage) || errorMessageTransAbort.IsMatch(errorMessage), errorMessage); } /// <summary> /// Updates the multiple products_ succeeds with shared connection. /// </summary> [Test] public void UpdateMultipleProducts_SucceedsWithSharedConnection() { string p1OriginalProductName = new Product(1).ProductName; string p2OriginalProductName = new Product(2).ProductName; using(TransactionScope ts = new TransactionScope()) { using(SharedDbConnectionScope connScope = new SharedDbConnectionScope()) { SaveProduct(1, "new name of product 1"); SaveProduct(2, "new name of product 2"); } } Assert.AreEqual(p1OriginalProductName, new Product(1).ProductName, "Transaction NOT rolled back"); Assert.AreEqual(p2OriginalProductName, new Product(2).ProductName, "Transaction NOT rolled back"); } /// <summary> /// Determines whether this instance [can nest shared connections]. /// </summary> [Test] public void CanNestSharedConnections() { SortedList originalNames = new SortedList(); for(int i = 1; i <= 4; i++) originalNames[i] = new Product(i).ProductName; using(TransactionScope outerTransactionScope = new TransactionScope()) { using(SharedDbConnectionScope outerConnectionScope = new SharedDbConnectionScope()) { Product p1 = UpdateProduct(1, "new name of product 1: " + _rand.Next(MaxRandomNumber)); Product p2 = UpdateProduct(2, "new name of product 2: " + _rand.Next(MaxRandomNumber)); using(TransactionScope innerTransactionScope = new TransactionScope()) { using(SharedDbConnectionScope innerConnectionScope = new SharedDbConnectionScope()) { Assert.AreSame(outerConnectionScope.CurrentConnection, innerConnectionScope.CurrentConnection); SaveProduct(3, "new name of product 3: " + +_rand.Next(MaxRandomNumber)); SaveProduct(4, "new name of product 4: " + +_rand.Next(MaxRandomNumber)); innerTransactionScope.Complete(); } } // ensure the connection hasn't been disposed by the inner scope Assert.IsTrue(outerConnectionScope.CurrentConnection.State == ConnectionState.Open); p1.Save(); p2.Save(); } } for(int i = 1; i <= 4; i++) Assert.AreEqual(originalNames[i], new Product(i).ProductName, "Product {0} is incorrect", i); } /// <summary> /// Multis the threaded test. /// </summary> private static ManualResetEvent[] resetEvents; // Retire this test for now - it's causing too many problems even with waiting for the threads to complete // - transactions are not failing gracefully ... BMc //[Test, MTAThreadAttribute()] public void MultiThreadedTest() { // TODO: this should be improved to wait for threads to complete and consolidate any error messages. // Right now, if there is a problem, this test will succeed and (a) other tests will fail (b) the VsTestHost.exe // will fail with an unhandled exception. // Threading wait added Jun 2011 BMc // thanks to: http://www.switchonthecode.com/tutorials/csharp-tutorial-using-the-threadpool string p1OriginalProductName = new Product(1).ProductName; string p2OriginalProductName = new Product(2).ProductName; const int iterations = 50; resetEvents = new ManualResetEvent[iterations]; for (int i = 0; i < iterations; i++) { resetEvents[i] = new ManualResetEvent(false); ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadingTarget), (object)i); } WaitHandle.WaitAll(resetEvents); SaveProduct(1, p1OriginalProductName); SaveProduct(2, p2OriginalProductName); } /// <summary> /// Threadings the target. /// </summary> /// <param name="state">The state.</param> public void ThreadingTarget(object state) { int index = (int)state; //string p1OriginalProductName = new Product(1).ProductName; //string p2OriginalProductName = new Product(2).ProductName; //using(TransactionScope ts = new TransactionScope()) //{ // using(SharedDbConnectionScope connScope = new SharedDbConnectionScope()) // { // SaveProduct(1, "new name of product 1"); // SaveProduct(2, "new name of product 2"); // } //} //Assert.AreEqual(p1OriginalProductName, new Product(1).ProductName); //Assert.AreEqual(p2OriginalProductName, new Product(2).ProductName); using (TransactionScope ts = new TransactionScope()) { using (SharedDbConnectionScope connScope = new SharedDbConnectionScope()) { SaveProduct(1, "product 1 process " + index.ToString()); SaveProduct(2, "product 2 process " + index.ToString()); } ts.Complete(); } resetEvents[index].Set(); } /// <summary> /// Saves the product. /// </summary> /// <param name="productId">The product id.</param> /// <param name="productName">Name of the product.</param> private static void SaveProduct(int productId, string productName) { Product p1 = UpdateProduct(productId, productName); p1.Save("Unit Test"); } /// <summary> /// Updates the product. /// </summary> /// <param name="productId">The product id.</param> /// <param name="productName">Name of the product.</param> /// <returns></returns> private static Product UpdateProduct(int productId, string productName) { Product p1 = new Product(productId); p1.ProductName = productName; p1.UnitPrice = 50; return p1; } } }
using System; using System.Diagnostics; using GeneticSharp.Infrastructure.Framework.Texts; using GeneticSharp.Infrastructure.Framework.Commons; namespace GeneticSharp.Domain.Chromosomes { /// <summary> /// A base class for chromosomes. /// </summary> [DebuggerDisplay("Fitness:{Fitness}, Genes:{Length}")] [Serializable] public abstract class ChromosomeBase : IChromosome { #region Fields private Gene[] m_genes; private int m_length; #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="ChromosomeBase"/> class. /// </summary> /// <param name="length">The length, in genes, of the chromosome.</param> protected ChromosomeBase(int length) { ValidateLength(length); m_length = length; m_genes = new Gene[length]; } #endregion #region Properties /// <summary> /// Gets or sets the fitness of the chromosome in the current problem. /// </summary> public double? Fitness { get; set; } /// <summary> /// Gets the length, in genes, of the chromosome. /// </summary> public int Length { get { return m_length; } } #endregion #region Methods /// <summary> /// Implements the operator ==. /// </summary> /// <param name="first">The first.</param> /// <param name="second">The second.</param> /// <returns> /// The result of the operator. /// </returns> public static bool operator ==(ChromosomeBase first, ChromosomeBase second) { if (Object.ReferenceEquals(first, second)) { return true; } if (((object)first == null) || ((object)second == null)) { return false; } return first.CompareTo(second) == 0; } /// <summary> /// Implements the operator !=. /// </summary> /// <param name="first">The first.</param> /// <param name="second">The second.</param> /// <returns> /// The result of the operator. /// </returns> public static bool operator !=(ChromosomeBase first, ChromosomeBase second) { return !(first == second); } /// <summary> /// Implements the operator &lt;. /// </summary> /// <param name="first">The first.</param> /// <param name="second">The second.</param> /// <returns> /// The result of the operator. /// </returns> public static bool operator <(ChromosomeBase first, ChromosomeBase second) { if (Object.ReferenceEquals(first, second)) { return false; } if ((object)first == null) { return true; } if ((object)second == null) { return false; } return first.CompareTo(second) < 0; } /// <summary> /// Implements the operator &gt;. /// </summary> /// <param name="first">The first.</param> /// <param name="second">The second.</param> /// <returns> /// The result of the operator. /// </returns> public static bool operator >(ChromosomeBase first, ChromosomeBase second) { return !(first == second) && !(first < second); } /// <summary> /// Generates the gene for the specified index. /// </summary> /// <param name="geneIndex">Gene index.</param> /// <returns>The gene generated at the specified index.</returns> public abstract Gene GenerateGene(int geneIndex); /// <summary> /// Creates a new chromosome using the same structure of this. /// </summary> /// <returns>The new chromosome.</returns> public abstract IChromosome CreateNew(); /// <summary> /// Creates a clone. /// </summary> /// <returns>The chromosome clone.</returns> public virtual IChromosome Clone() { var clone = CreateNew(); clone.ReplaceGenes(0, GetGenes()); clone.Fitness = Fitness; return clone; } /// <summary> /// Replaces the gene in the specified index. /// </summary> /// <param name="index">The gene index to replace.</param> /// <param name="gene">The new gene.</param> /// <exception cref="System.ArgumentOutOfRangeException">index;There is no Gene on index {0} to be replaced..With(index)</exception> public void ReplaceGene(int index, Gene gene) { if (index < 0 || index >= m_length) { throw new ArgumentOutOfRangeException(nameof(index), "There is no Gene on index {0} to be replaced.".With(index)); } m_genes[index] = gene; Fitness = null; } /// <summary> /// Replaces the genes starting in the specified index. /// </summary> /// <param name="startIndex">Start index.</param> /// <param name="genes">The genes.</param> /// <remarks> /// The genes to be replaced can't be greater than the available space between the start index and the end of the chromosome. /// </remarks> public void ReplaceGenes(int startIndex, Gene[] genes) { ExceptionHelper.ThrowIfNull("genes", genes); if (genes.Length > 0) { if (startIndex < 0 || startIndex >= m_length) { throw new ArgumentOutOfRangeException(nameof(startIndex), "There is no Gene on index {0} to be replaced.".With(startIndex)); } var genesToBeReplacedLength = genes.Length; var availableSpaceLength = m_length - startIndex; if (genesToBeReplacedLength > availableSpaceLength) { throw new ArgumentException( nameof(Gene), "The number of genes to be replaced is greater than available space, there is {0} genes between the index {1} and the end of chromosome, but there is {2} genes to be replaced." .With(availableSpaceLength, startIndex, genesToBeReplacedLength)); } Array.Copy(genes, 0, m_genes, startIndex, genes.Length); Fitness = null; } } /// <summary> /// Resizes the chromosome to the new length. /// </summary> /// <param name="newLength">The new length.</param> public void Resize(int newLength) { ValidateLength(newLength); Array.Resize(ref m_genes, newLength); m_length = newLength; } /// <summary> /// Gets the gene in the specified index. /// </summary> /// <param name="index">The gene index.</param> /// <returns> /// The gene. /// </returns> public Gene GetGene(int index) { return m_genes[index]; } /// <summary> /// Gets the genes. /// </summary> /// <returns>The genes.</returns> public Gene[] GetGenes() { return m_genes; } /// <summary> /// Compares the current object with another object of the same type. /// </summary> /// <returns>The to.</returns> /// <param name="other">The other chromosome.</param> public int CompareTo(IChromosome other) { if (other == null) { return -1; } var otherFitness = other.Fitness; if (Fitness == otherFitness) { return 0; } return Fitness > otherFitness ? 1 : -1; } /// <summary> /// Determines whether the specified <see cref="System.Object"/> is equal to the current <see cref="GeneticSharp.Domain.Chromosomes.ChromosomeBase"/>. /// </summary> /// <param name="obj">The <see cref="System.Object"/> to compare with the current <see cref="GeneticSharp.Domain.Chromosomes.ChromosomeBase"/>.</param> /// <returns><c>true</c> if the specified <see cref="System.Object"/> is equal to the current /// <see cref="GeneticSharp.Domain.Chromosomes.ChromosomeBase"/>; otherwise, <c>false</c>.</returns> public override bool Equals(object obj) { var other = obj as IChromosome; if (other == null) { return false; } return CompareTo(other) == 0; } /// <summary> /// Returns a hash code for this instance. /// </summary> /// <returns> /// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table. /// </returns> public override int GetHashCode() { return Fitness.GetHashCode(); } /// <summary> /// Creates the gene on specified index. /// <remarks> /// It's a shortcut to: /// <code> /// ReplaceGene(index, GenerateGene(index)); /// </code> /// </remarks> /// </summary> /// <param name="index">The gene index.</param> protected virtual void CreateGene(int index) { ReplaceGene(index, GenerateGene(index)); } /// <summary> /// Creates all genes /// <remarks> /// It's a shortcut to: /// <code> /// for (int i = 0; i &lt; Length; i++) /// { /// ReplaceGene(i, GenerateGene(i)); /// } /// </code> /// </remarks> /// </summary> protected virtual void CreateGenes() { for (int i = 0; i < Length; i++) { ReplaceGene(i, GenerateGene(i)); } } /// <summary> /// Validates the length. /// </summary> /// <param name="length">The length.</param> /// <exception cref="System.ArgumentException">The minimum length for a chromosome is 2 genes.</exception> private static void ValidateLength(int length) { if (length < 2) { throw new ArgumentException("The minimum length for a chromosome is 2 genes.", nameof(length)); } } #endregion } }
using Microsoft.IdentityModel.S2S.Protocols.OAuth2; using Microsoft.IdentityModel.Tokens; using Microsoft.SharePoint.Client; using System; using System.Net; using System.Security.Principal; using System.Web; using System.Web.Configuration; namespace RemoteEventsDemoWeb { /// <summary> /// Encapsulates all the information from SharePoint. /// </summary> public abstract class SharePointContext { public const string SPHostUrlKey = "SPHostUrl"; public const string SPAppWebUrlKey = "SPAppWebUrl"; public const string SPLanguageKey = "SPLanguage"; public const string SPClientTagKey = "SPClientTag"; public const string SPProductNumberKey = "SPProductNumber"; protected static readonly TimeSpan AccessTokenLifetimeTolerance = TimeSpan.FromMinutes(5.0); private readonly Uri spHostUrl; private readonly Uri spAppWebUrl; private readonly string spLanguage; private readonly string spClientTag; private readonly string spProductNumber; // <AccessTokenString, UtcExpiresOn> protected Tuple<string, DateTime> userAccessTokenForSPHost; protected Tuple<string, DateTime> userAccessTokenForSPAppWeb; protected Tuple<string, DateTime> appOnlyAccessTokenForSPHost; protected Tuple<string, DateTime> appOnlyAccessTokenForSPAppWeb; /// <summary> /// Gets the SharePoint host url from QueryString of the specified HTTP request. /// </summary> /// <param name="httpRequest">The specified HTTP request.</param> /// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns> public static Uri GetSPHostUrl(HttpRequestBase httpRequest) { if (httpRequest == null) { throw new ArgumentNullException("httpRequest"); } string spHostUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SPHostUrlKey]); Uri spHostUrl; if (Uri.TryCreate(spHostUrlString, UriKind.Absolute, out spHostUrl) && (spHostUrl.Scheme == Uri.UriSchemeHttp || spHostUrl.Scheme == Uri.UriSchemeHttps)) { return spHostUrl; } return null; } /// <summary> /// Gets the SharePoint host url from QueryString of the specified HTTP request. /// </summary> /// <param name="httpRequest">The specified HTTP request.</param> /// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns> public static Uri GetSPHostUrl(HttpRequest httpRequest) { return GetSPHostUrl(new HttpRequestWrapper(httpRequest)); } /// <summary> /// The SharePoint host url. /// </summary> public Uri SPHostUrl { get { return this.spHostUrl; } } /// <summary> /// The SharePoint app web url. /// </summary> public Uri SPAppWebUrl { get { return this.spAppWebUrl; } } /// <summary> /// The SharePoint language. /// </summary> public string SPLanguage { get { return this.spLanguage; } } /// <summary> /// The SharePoint client tag. /// </summary> public string SPClientTag { get { return this.spClientTag; } } /// <summary> /// The SharePoint product number. /// </summary> public string SPProductNumber { get { return this.spProductNumber; } } /// <summary> /// The user access token for the SharePoint host. /// </summary> public abstract string UserAccessTokenForSPHost { get; } /// <summary> /// The user access token for the SharePoint app web. /// </summary> public abstract string UserAccessTokenForSPAppWeb { get; } /// <summary> /// The app only access token for the SharePoint host. /// </summary> public abstract string AppOnlyAccessTokenForSPHost { get; } /// <summary> /// The app only access token for the SharePoint app web. /// </summary> public abstract string AppOnlyAccessTokenForSPAppWeb { get; } /// <summary> /// Constructor. /// </summary> /// <param name="spHostUrl">The SharePoint host url.</param> /// <param name="spAppWebUrl">The SharePoint app web url.</param> /// <param name="spLanguage">The SharePoint language.</param> /// <param name="spClientTag">The SharePoint client tag.</param> /// <param name="spProductNumber">The SharePoint product number.</param> protected SharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber) { if (spHostUrl == null) { throw new ArgumentNullException("spHostUrl"); } if (string.IsNullOrEmpty(spLanguage)) { throw new ArgumentNullException("spLanguage"); } if (string.IsNullOrEmpty(spClientTag)) { throw new ArgumentNullException("spClientTag"); } if (string.IsNullOrEmpty(spProductNumber)) { throw new ArgumentNullException("spProductNumber"); } this.spHostUrl = spHostUrl; this.spAppWebUrl = spAppWebUrl; this.spLanguage = spLanguage; this.spClientTag = spClientTag; this.spProductNumber = spProductNumber; } /// <summary> /// Creates a user ClientContext for the SharePoint host. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateUserClientContextForSPHost() { return CreateClientContext(this.SPHostUrl, this.UserAccessTokenForSPHost); } /// <summary> /// Creates a user ClientContext for the SharePoint app web. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateUserClientContextForSPAppWeb() { return CreateClientContext(this.SPAppWebUrl, this.UserAccessTokenForSPAppWeb); } /// <summary> /// Creates app only ClientContext for the SharePoint host. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateAppOnlyClientContextForSPHost() { return CreateClientContext(this.SPHostUrl, this.AppOnlyAccessTokenForSPHost); } /// <summary> /// Creates an app only ClientContext for the SharePoint app web. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateAppOnlyClientContextForSPAppWeb() { return CreateClientContext(this.SPAppWebUrl, this.AppOnlyAccessTokenForSPAppWeb); } /// <summary> /// Gets the database connection string from SharePoint for autohosted add-in. /// This method is deprecated because the autohosted option is no longer available. /// </summary> [ObsoleteAttribute("This method is deprecated because the autohosted option is no longer available.", true)] public string GetDatabaseConnectionString() { throw new NotSupportedException("This method is deprecated because the autohosted option is no longer available."); } /// <summary> /// Determines if the specified access token is valid. /// It considers an access token as not valid if it is null, or it has expired. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <returns>True if the access token is valid.</returns> protected static bool IsAccessTokenValid(Tuple<string, DateTime> accessToken) { return accessToken != null && !string.IsNullOrEmpty(accessToken.Item1) && accessToken.Item2 > DateTime.UtcNow; } /// <summary> /// Creates a ClientContext with the specified SharePoint site url and the access token. /// </summary> /// <param name="spSiteUrl">The site url.</param> /// <param name="accessToken">The access token.</param> /// <returns>A ClientContext instance.</returns> private static ClientContext CreateClientContext(Uri spSiteUrl, string accessToken) { if (spSiteUrl != null && !string.IsNullOrEmpty(accessToken)) { return TokenHelper.GetClientContextWithAccessToken(spSiteUrl.AbsoluteUri, accessToken); } return null; } } /// <summary> /// Redirection status. /// </summary> public enum RedirectionStatus { Ok, ShouldRedirect, CanNotRedirect } /// <summary> /// Provides SharePointContext instances. /// </summary> public abstract class SharePointContextProvider { private static SharePointContextProvider current; /// <summary> /// The current SharePointContextProvider instance. /// </summary> public static SharePointContextProvider Current { get { return SharePointContextProvider.current; } } /// <summary> /// Initializes the default SharePointContextProvider instance. /// </summary> static SharePointContextProvider() { if (!TokenHelper.IsHighTrustApp()) { SharePointContextProvider.current = new SharePointAcsContextProvider(); } else { SharePointContextProvider.current = new SharePointHighTrustContextProvider(); } } /// <summary> /// Registers the specified SharePointContextProvider instance as current. /// It should be called by Application_Start() in Global.asax. /// </summary> /// <param name="provider">The SharePointContextProvider to be set as current.</param> public static void Register(SharePointContextProvider provider) { if (provider == null) { throw new ArgumentNullException("provider"); } SharePointContextProvider.current = provider; } /// <summary> /// Checks if it is necessary to redirect to SharePoint for user to authenticate. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param> /// <returns>Redirection status.</returns> public static RedirectionStatus CheckRedirectionStatus(HttpContextBase httpContext, out Uri redirectUrl) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } redirectUrl = null; bool contextTokenExpired = false; try { if (SharePointContextProvider.Current.GetSharePointContext(httpContext) != null) { return RedirectionStatus.Ok; } } catch (SecurityTokenExpiredException) { contextTokenExpired = true; } const string SPHasRedirectedToSharePointKey = "SPHasRedirectedToSharePoint"; if (!string.IsNullOrEmpty(httpContext.Request.QueryString[SPHasRedirectedToSharePointKey]) && !contextTokenExpired) { return RedirectionStatus.CanNotRedirect; } Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); if (spHostUrl == null) { return RedirectionStatus.CanNotRedirect; } if (StringComparer.OrdinalIgnoreCase.Equals(httpContext.Request.HttpMethod, "POST")) { return RedirectionStatus.CanNotRedirect; } Uri requestUrl = httpContext.Request.Url; var queryNameValueCollection = HttpUtility.ParseQueryString(requestUrl.Query); // Removes the values that are included in {StandardTokens}, as {StandardTokens} will be inserted at the beginning of the query string. queryNameValueCollection.Remove(SharePointContext.SPHostUrlKey); queryNameValueCollection.Remove(SharePointContext.SPAppWebUrlKey); queryNameValueCollection.Remove(SharePointContext.SPLanguageKey); queryNameValueCollection.Remove(SharePointContext.SPClientTagKey); queryNameValueCollection.Remove(SharePointContext.SPProductNumberKey); // Adds SPHasRedirectedToSharePoint=1. queryNameValueCollection.Add(SPHasRedirectedToSharePointKey, "1"); UriBuilder returnUrlBuilder = new UriBuilder(requestUrl); returnUrlBuilder.Query = queryNameValueCollection.ToString(); // Inserts StandardTokens. const string StandardTokens = "{StandardTokens}"; string returnUrlString = returnUrlBuilder.Uri.AbsoluteUri; returnUrlString = returnUrlString.Insert(returnUrlString.IndexOf("?") + 1, StandardTokens + "&"); // Constructs redirect url. string redirectUrlString = TokenHelper.GetAppContextTokenRequestUrl(spHostUrl.AbsoluteUri, Uri.EscapeDataString(returnUrlString)); redirectUrl = new Uri(redirectUrlString, UriKind.Absolute); return RedirectionStatus.ShouldRedirect; } /// <summary> /// Checks if it is necessary to redirect to SharePoint for user to authenticate. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param> /// <returns>Redirection status.</returns> public static RedirectionStatus CheckRedirectionStatus(HttpContext httpContext, out Uri redirectUrl) { return CheckRedirectionStatus(new HttpContextWrapper(httpContext), out redirectUrl); } /// <summary> /// Creates a SharePointContext instance with the specified HTTP request. /// </summary> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> public SharePointContext CreateSharePointContext(HttpRequestBase httpRequest) { if (httpRequest == null) { throw new ArgumentNullException("httpRequest"); } // SPHostUrl Uri spHostUrl = SharePointContext.GetSPHostUrl(httpRequest); if (spHostUrl == null) { return null; } // SPAppWebUrl string spAppWebUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SharePointContext.SPAppWebUrlKey]); Uri spAppWebUrl; if (!Uri.TryCreate(spAppWebUrlString, UriKind.Absolute, out spAppWebUrl) || !(spAppWebUrl.Scheme == Uri.UriSchemeHttp || spAppWebUrl.Scheme == Uri.UriSchemeHttps)) { spAppWebUrl = null; } // SPLanguage string spLanguage = httpRequest.QueryString[SharePointContext.SPLanguageKey]; if (string.IsNullOrEmpty(spLanguage)) { return null; } // SPClientTag string spClientTag = httpRequest.QueryString[SharePointContext.SPClientTagKey]; if (string.IsNullOrEmpty(spClientTag)) { return null; } // SPProductNumber string spProductNumber = httpRequest.QueryString[SharePointContext.SPProductNumberKey]; if (string.IsNullOrEmpty(spProductNumber)) { return null; } return CreateSharePointContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, httpRequest); } /// <summary> /// Creates a SharePointContext instance with the specified HTTP request. /// </summary> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> public SharePointContext CreateSharePointContext(HttpRequest httpRequest) { return CreateSharePointContext(new HttpRequestWrapper(httpRequest)); } /// <summary> /// Gets a SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns> public SharePointContext GetSharePointContext(HttpContextBase httpContext) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); if (spHostUrl == null) { return null; } SharePointContext spContext = LoadSharePointContext(httpContext); if (spContext == null || !ValidateSharePointContext(spContext, httpContext)) { spContext = CreateSharePointContext(httpContext.Request); if (spContext != null) { SaveSharePointContext(spContext, httpContext); } } return spContext; } /// <summary> /// Gets a SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns> public SharePointContext GetSharePointContext(HttpContext httpContext) { return GetSharePointContext(new HttpContextWrapper(httpContext)); } /// <summary> /// Creates a SharePointContext instance. /// </summary> /// <param name="spHostUrl">The SharePoint host url.</param> /// <param name="spAppWebUrl">The SharePoint app web url.</param> /// <param name="spLanguage">The SharePoint language.</param> /// <param name="spClientTag">The SharePoint client tag.</param> /// <param name="spProductNumber">The SharePoint product number.</param> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> protected abstract SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest); /// <summary> /// Validates if the given SharePointContext can be used with the specified HTTP context. /// </summary> /// <param name="spContext">The SharePointContext.</param> /// <param name="httpContext">The HTTP context.</param> /// <returns>True if the given SharePointContext can be used with the specified HTTP context.</returns> protected abstract bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext); /// <summary> /// Loads the SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found.</returns> protected abstract SharePointContext LoadSharePointContext(HttpContextBase httpContext); /// <summary> /// Saves the specified SharePointContext instance associated with the specified HTTP context. /// <c>null</c> is accepted for clearing the SharePointContext instance associated with the HTTP context. /// </summary> /// <param name="spContext">The SharePointContext instance to be saved, or <c>null</c>.</param> /// <param name="httpContext">The HTTP context.</param> protected abstract void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext); } #region ACS /// <summary> /// Encapsulates all the information from SharePoint in ACS mode. /// </summary> public class SharePointAcsContext : SharePointContext { private readonly string contextToken; private readonly SharePointContextToken contextTokenObj; /// <summary> /// The context token. /// </summary> public string ContextToken { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextToken : null; } } /// <summary> /// The context token's "CacheKey" claim. /// </summary> public string CacheKey { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.CacheKey : null; } } /// <summary> /// The context token's "refreshtoken" claim. /// </summary> public string RefreshToken { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.RefreshToken : null; } } public override string UserAccessTokenForSPHost { get { return GetAccessTokenString(ref this.userAccessTokenForSPHost, () => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPHostUrl.Authority)); } } public override string UserAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb, () => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPAppWebUrl.Authority)); } } public override string AppOnlyAccessTokenForSPHost { get { return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost, () => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPHostUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPHostUrl))); } } public override string AppOnlyAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb, () => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPAppWebUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPAppWebUrl))); } } public SharePointAcsContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, string contextToken, SharePointContextToken contextTokenObj) : base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber) { if (string.IsNullOrEmpty(contextToken)) { throw new ArgumentNullException("contextToken"); } if (contextTokenObj == null) { throw new ArgumentNullException("contextTokenObj"); } this.contextToken = contextToken; this.contextTokenObj = contextTokenObj; } /// <summary> /// Ensures the access token is valid and returns it. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> /// <returns>The access token string.</returns> private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler) { RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler); return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null; } /// <summary> /// Renews the access token if it is not valid. /// </summary> /// <param name="accessToken">The access token to renew.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler) { if (IsAccessTokenValid(accessToken)) { return; } try { OAuth2AccessTokenResponse oAuth2AccessTokenResponse = tokenRenewalHandler(); DateTime expiresOn = oAuth2AccessTokenResponse.ExpiresOn; if ((expiresOn - oAuth2AccessTokenResponse.NotBefore) > AccessTokenLifetimeTolerance) { // Make the access token get renewed a bit earlier than the time when it expires // so that the calls to SharePoint with it will have enough time to complete successfully. expiresOn -= AccessTokenLifetimeTolerance; } accessToken = Tuple.Create(oAuth2AccessTokenResponse.AccessToken, expiresOn); } catch (WebException) { } } } /// <summary> /// Default provider for SharePointAcsContext. /// </summary> public class SharePointAcsContextProvider : SharePointContextProvider { private const string SPContextKey = "SPContext"; private const string SPCacheKeyKey = "SPCacheKey"; protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest) { string contextTokenString = TokenHelper.GetContextTokenFromRequest(httpRequest); if (string.IsNullOrEmpty(contextTokenString)) { return null; } SharePointContextToken contextToken = null; try { contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, httpRequest.Url.Authority); } catch (WebException) { return null; } catch (AudienceUriValidationFailedException) { return null; } return new SharePointAcsContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, contextTokenString, contextToken); } protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointAcsContext spAcsContext = spContext as SharePointAcsContext; if (spAcsContext != null) { Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); string contextToken = TokenHelper.GetContextTokenFromRequest(httpContext.Request); HttpCookie spCacheKeyCookie = httpContext.Request.Cookies[SPCacheKeyKey]; string spCacheKey = spCacheKeyCookie != null ? spCacheKeyCookie.Value : null; return spHostUrl == spAcsContext.SPHostUrl && !string.IsNullOrEmpty(spAcsContext.CacheKey) && spCacheKey == spAcsContext.CacheKey && !string.IsNullOrEmpty(spAcsContext.ContextToken) && (string.IsNullOrEmpty(contextToken) || contextToken == spAcsContext.ContextToken); } return false; } protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext) { return httpContext.Session[SPContextKey] as SharePointAcsContext; } protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointAcsContext spAcsContext = spContext as SharePointAcsContext; if (spAcsContext != null) { HttpCookie spCacheKeyCookie = new HttpCookie(SPCacheKeyKey) { Value = spAcsContext.CacheKey, Secure = true, HttpOnly = true }; httpContext.Response.AppendCookie(spCacheKeyCookie); } httpContext.Session[SPContextKey] = spAcsContext; } } #endregion ACS #region HighTrust /// <summary> /// Encapsulates all the information from SharePoint in HighTrust mode. /// </summary> public class SharePointHighTrustContext : SharePointContext { private readonly WindowsIdentity logonUserIdentity; /// <summary> /// The Windows identity for the current user. /// </summary> public WindowsIdentity LogonUserIdentity { get { return this.logonUserIdentity; } } public override string UserAccessTokenForSPHost { get { return GetAccessTokenString(ref this.userAccessTokenForSPHost, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, this.LogonUserIdentity)); } } public override string UserAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, this.LogonUserIdentity)); } } public override string AppOnlyAccessTokenForSPHost { get { return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, null)); } } public override string AppOnlyAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, null)); } } public SharePointHighTrustContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, WindowsIdentity logonUserIdentity) : base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber) { if (logonUserIdentity == null) { throw new ArgumentNullException("logonUserIdentity"); } this.logonUserIdentity = logonUserIdentity; } /// <summary> /// Ensures the access token is valid and returns it. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> /// <returns>The access token string.</returns> private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler) { RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler); return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null; } /// <summary> /// Renews the access token if it is not valid. /// </summary> /// <param name="accessToken">The access token to renew.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler) { if (IsAccessTokenValid(accessToken)) { return; } DateTime expiresOn = DateTime.UtcNow.Add(TokenHelper.HighTrustAccessTokenLifetime); if (TokenHelper.HighTrustAccessTokenLifetime > AccessTokenLifetimeTolerance) { // Make the access token get renewed a bit earlier than the time when it expires // so that the calls to SharePoint with it will have enough time to complete successfully. expiresOn -= AccessTokenLifetimeTolerance; } accessToken = Tuple.Create(tokenRenewalHandler(), expiresOn); } } /// <summary> /// Default provider for SharePointHighTrustContext. /// </summary> public class SharePointHighTrustContextProvider : SharePointContextProvider { private const string SPContextKey = "SPContext"; protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest) { WindowsIdentity logonUserIdentity = httpRequest.LogonUserIdentity; if (logonUserIdentity == null || !logonUserIdentity.IsAuthenticated || logonUserIdentity.IsGuest || logonUserIdentity.User == null) { return null; } return new SharePointHighTrustContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, logonUserIdentity); } protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointHighTrustContext spHighTrustContext = spContext as SharePointHighTrustContext; if (spHighTrustContext != null) { Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); WindowsIdentity logonUserIdentity = httpContext.Request.LogonUserIdentity; return spHostUrl == spHighTrustContext.SPHostUrl && logonUserIdentity != null && logonUserIdentity.IsAuthenticated && !logonUserIdentity.IsGuest && logonUserIdentity.User == spHighTrustContext.LogonUserIdentity.User; } return false; } protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext) { return httpContext.Session[SPContextKey] as SharePointHighTrustContext; } protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { httpContext.Session[SPContextKey] = spContext as SharePointHighTrustContext; } } #endregion HighTrust }
using System; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Text; using Microsoft.Win32.SafeHandles; using IO = System.IO; namespace PWLib.Platform.Windows { #region New file replacements internal class PathInternal { public const UInt32 OurMaxPath = 32767; internal struct DllImport { [StructLayout( LayoutKind.Sequential, CharSet = CharSet.Unicode )] public struct FILETIME { public UInt32 dwLowDateTime; public UInt32 dwHighDateTime; } [StructLayout( LayoutKind.Sequential, CharSet = CharSet.Unicode )] public struct WIN32_FIND_DATA { public UInt32 dwFileAttributes; public FILETIME ftCreationTime; public FILETIME ftLastAccessTime; public FILETIME ftLastWriteTime; public UInt32 nFileSizeHigh; public UInt32 nFileSizeLow; public UInt32 dwReserved0; public UInt32 dwReserved1; [MarshalAs( UnmanagedType.ByValTStr, SizeConst = 260 )] public string cFileName; [MarshalAs( UnmanagedType.ByValTStr, SizeConst = 16 )] public string cAlternateFileName; } [StructLayout( LayoutKind.Sequential, CharSet = CharSet.Unicode )] public struct WIN32_FILE_ATTRIBUTE_DATA { public UInt32 dwFileAttributes; public FILETIME ftCreationTime; public FILETIME ftLastAccessTime; public FILETIME ftLastWriteTime; public UInt32 nFileSizeHigh; public UInt32 nFileSizeLow; } [DllImport( "kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode )] public static extern bool MoveFileW( string lpExistingFileName, string lpNewFileName ); [DllImport( "kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode )] public static extern bool CopyFileW( string lpExistingFileName, string lpNewFileName, bool failIfExists ); [DllImport( "kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode )] public static extern bool DeleteFileW( string lpFileName ); [DllImport( "kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode )] public static extern bool RemoveDirectoryW( string lpPathName ); [DllImport( "kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode )] public static extern bool CreateDirectoryW( string lpPathName, IntPtr lpSecurityAttributes ); [DllImport( "kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode )] public static extern SafeFileHandle CreateFileW( string lpFileName, uint dwDesiredAccess, uint dwShareMode, IntPtr lpSecurityAttributes, uint dwCreationDisposition, uint dwFlagsAndAttributes, IntPtr hTemplateFile ); [DllImport( "kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode )] public static extern uint SetFilePointer( SafeFileHandle hFile, long lDistanceToMove, IntPtr lpDistanceToMoveHigh, uint dwMoveMethod ); [DllImport( "kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode )] public static extern UInt32 GetFileAttributesW( string filename ); [DllImport( "kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode )] public static extern bool SetFileAttributesW( string lpFileName, UInt32 dwFileAttributes ); [DllImport( "kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode )] public static extern bool GetFileAttributesExW( string filename, UInt32 fInfoLevelId, ref WIN32_FILE_ATTRIBUTE_DATA lpFileInformation ); [DllImport( "kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode )] public static unsafe extern bool SetFileTime( SafeFileHandle hFile, FILETIME* lpCreationTime, FILETIME* lpLastAccessTime, FILETIME* lpLastWriteTime ); [DllImport( "kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode )] public static extern bool GetFileSizeEx( SafeHandle hFile, ref ulong lpFileSize ); [DllImport( "kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode )] public static extern IntPtr FindFirstFileExW( string lpFileName, int fInfoLevelId, ref WIN32_FIND_DATA lpFindFileData, int fSearchOp, IntPtr lpSearchFilter, UInt32 swAdditionalFlags ); [DllImport( "kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode )] public static extern bool FindClose( IntPtr hFindFile ); [DllImport( "kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode )] public static extern bool FindNextFile( IntPtr hFindFile, ref WIN32_FIND_DATA lpFindFileData ); [DllImport( "kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode )] public static unsafe extern bool GetFullPathNameW( string lpFileName, UInt32 nBufferLength, char* lpBuffer, IntPtr lpFilePart ); public const uint CREATE_NEW = 1; public const uint CREATE_ALWAYS = 2; public const uint OPEN_EXISTING = 3; public const uint OPEN_ALWAYS = 4; public const uint TRUNCATE_EXISTING = 5; public const uint GENERIC_READ = 0x80000000; public const uint GENERIC_WRITE = 0x40000000; public const uint GENERIC_EXECUTE = 0x20000000; public const uint GENERIC_ALL = 0x10000000; public const uint FILE_SHARE_READ = 0x00000001; public const uint FILE_SHARE_WRITE = 0x00000002; public const uint FILE_SHARE_DELETE = 0x00000004; public const uint FILE_APPEND_DATA = 0x0004; public const uint FILE_ATTRIBUTE_READONLY = 0x00000001; public const uint FILE_ATTRIBUTE_NORMAL = 0x00000080; public const uint ERROR_ALREADY_EXISTS = 183; public const uint FILE_END = 2; public const uint INVALID_FILE_ATTRIBUTES = 0xffffffff; public const uint FILE_ATTRIBUTE_DIRECTORY = 0x0010; } static string RootPathIfNecessary( string path ) { return PWLib.Platform.Windows.Path.GetFullPath( path, false ); } public static string ConvertToUnicodePath( string path ) { // If file path is disk file path then prepend it with \\?\ // if file path is UNC prepend it with \\?\UNC\ and remove \\ prefix in unc path. if ( path.StartsWith( @"\\?\" ) ) return path; else if ( path.StartsWith( @"\\" ) ) return @"\\?\UNC\" + path.Substring( 2, path.Length - 2 ); else return @"\\?\" + RootPathIfNecessary( path ); } public static DateTime FILETIMEToDateTime( DllImport.FILETIME fileTime, bool utc ) { UInt64 high = ( (UInt64)( fileTime.dwHighDateTime ) ); UInt64 shiftedHigh = ( high & 0xFFFFFFFF ) << 32; UInt64 low = (UInt64)( fileTime.dwLowDateTime & ( 0xFFFFFFFF ) ); long final = (long)( low | shiftedHigh ); return utc ? DateTime.FromFileTimeUtc( final ) : DateTime.FromFileTime( final ); } public static UInt32 GetFileAttributes( string filename ) { return PathInternal.DllImport.GetFileAttributesW( PathInternal.ConvertToUnicodePath( filename ) ); } public static bool SetFileAttributes( string filename, UInt32 attribs ) { return PathInternal.DllImport.SetFileAttributesW( PathInternal.ConvertToUnicodePath( filename ), attribs ); } public static void RemoveReadOnlyFlag( string filename ) { UInt32 attribs = PathInternal.GetFileAttributes( filename ); if ( attribs != PathInternal.DllImport.INVALID_FILE_ATTRIBUTES && ( attribs & PathInternal.DllImport.FILE_ATTRIBUTE_READONLY ) > 0 ) { PathInternal.SetFileAttributes( filename, ( attribs & ( ~PathInternal.DllImport.FILE_ATTRIBUTE_READONLY ) ) ); } } } public class File { #region Win32 helper methods private static uint GetMode( IO.FileMode mode ) { uint umode = 0; switch ( mode ) { case IO.FileMode.CreateNew: umode = PathInternal.DllImport.CREATE_NEW; break; case IO.FileMode.Create: umode = PathInternal.DllImport.CREATE_ALWAYS; break; case IO.FileMode.Append: umode = PathInternal.DllImport.OPEN_ALWAYS; break; case IO.FileMode.Open: umode = PathInternal.DllImport.OPEN_EXISTING; break; case IO.FileMode.OpenOrCreate: umode = PathInternal.DllImport.OPEN_ALWAYS; break; case IO.FileMode.Truncate: umode = PathInternal.DllImport.TRUNCATE_EXISTING; break; } return umode; } private static uint GetAccess( IO.FileAccess access ) { uint uaccess = 0; switch ( access ) { case IO.FileAccess.Read: uaccess = PathInternal.DllImport.GENERIC_READ; break; case IO.FileAccess.ReadWrite: uaccess = PathInternal.DllImport.GENERIC_READ | PathInternal.DllImport.GENERIC_WRITE; break; case IO.FileAccess.Write: uaccess = PathInternal.DllImport.GENERIC_WRITE; break; } return uaccess; } private static uint GetShare( IO.FileShare share ) { uint ushare = 0; switch ( share ) { case IO.FileShare.Read: ushare = PathInternal.DllImport.FILE_SHARE_READ; break; case IO.FileShare.ReadWrite: ushare = PathInternal.DllImport.FILE_SHARE_READ | PathInternal.DllImport.FILE_SHARE_WRITE; break; case IO.FileShare.Write: ushare = PathInternal.DllImport.FILE_SHARE_WRITE; break; case IO.FileShare.Delete: ushare = PathInternal.DllImport.FILE_SHARE_DELETE; break; case IO.FileShare.None: ushare = 0; break; } return ushare; } #endregion #region Open file methods public static IO.FileStream Create( string filename ) { return Open( filename, System.IO.FileMode.Create, System.IO.FileAccess.ReadWrite, System.IO.FileShare.ReadWrite ); } public static IO.FileStream OpenRead( string filepath ) { return Open( filepath, IO.FileMode.Open, IO.FileAccess.Read, IO.FileShare.Read ); } public static IO.FileStream OpenWrite( string filepath ) { return Open( filepath, IO.FileMode.OpenOrCreate, IO.FileAccess.Write, IO.FileShare.None ); } public static IO.FileStream Open( string filepath, IO.FileMode mode, IO.FileAccess access ) { return Open( filepath, mode, access, IO.FileShare.ReadWrite ); } public static IO.FileStream Open( string filepath, IO.FileMode mode, IO.FileAccess access, IO.FileShare share ) { //opened in the specified mode , access and share IO.FileStream fs = null; uint umode = GetMode( mode ); uint uaccess = GetAccess( access ); uint ushare = GetShare( share ); if ( mode == IO.FileMode.Append ) uaccess = PathInternal.DllImport.FILE_APPEND_DATA; SafeFileHandle sh = PathInternal.DllImport.CreateFileW( PathInternal.ConvertToUnicodePath( filepath ), uaccess, ushare, IntPtr.Zero, umode, PathInternal.DllImport.FILE_ATTRIBUTE_NORMAL, IntPtr.Zero ); int iError = Marshal.GetLastWin32Error(); if ( ( iError > 0 && !( mode == IO.FileMode.Append && iError != PathInternal.DllImport.ERROR_ALREADY_EXISTS ) ) || sh.IsInvalid ) { throw new Exception( "Error opening file Win32 Error:" + iError ); } else { fs = new IO.FileStream( sh, access ); } // if opened in append mode if ( mode == IO.FileMode.Append ) { if ( !sh.IsInvalid ) { PathInternal.DllImport.SetFilePointer( sh, 0, IntPtr.Zero, PathInternal.DllImport.FILE_END ); } } return fs; } #endregion public static ulong GetFileSize( string path ) { ulong num = 0; try { IO.FileStream fs = OpenRead( path ); if ( !PathInternal.DllImport.GetFileSizeEx( fs.SafeFileHandle, ref num ) ) num = 0; fs.Close(); } catch ( System.Exception ) { } return num; } public static bool Exists(string filename) { UInt32 attribs = PathInternal.GetFileAttributes( filename ); return attribs != PathInternal.DllImport.INVALID_FILE_ATTRIBUTES && ( ( attribs & PathInternal.DllImport.FILE_ATTRIBUTE_DIRECTORY ) == 0 ); } //public static bool CopyFile( string existingFile, string newFile, bool failIfExists ) //{ // return PathInternal.DllImport.CopyFileW( PathInternal.ConvertToUnicodePath( existingFile ), PathInternal.ConvertToUnicodePath( newFile ), failIfExists ); //} public static bool Delete( string filename ) { return Delete( filename, false ); } public static bool Delete( string filename, bool force ) { if ( force ) { PathInternal.RemoveReadOnlyFlag( filename ); } return PathInternal.DllImport.DeleteFileW( PathInternal.ConvertToUnicodePath( filename ) ); } public static bool Move(string source, string dest) { return PathInternal.DllImport.MoveFileW( PathInternal.ConvertToUnicodePath( source ), PathInternal.ConvertToUnicodePath( dest ) ); } private enum DateTimeAttrib { Write, Access, Creation }; private static DateTime GetDateTime( string path, DateTimeAttrib attrib, bool utc ) { PathInternal.DllImport.WIN32_FILE_ATTRIBUTE_DATA fileData = new PathInternal.DllImport.WIN32_FILE_ATTRIBUTE_DATA(); if ( PathInternal.DllImport.GetFileAttributesExW( PathInternal.ConvertToUnicodePath( path ), 0, ref fileData ) ) { switch ( attrib ) { case DateTimeAttrib.Write: return PathInternal.FILETIMEToDateTime( fileData.ftLastWriteTime, utc ); case DateTimeAttrib.Access: return PathInternal.FILETIMEToDateTime( fileData.ftLastAccessTime, utc ); case DateTimeAttrib.Creation: return PathInternal.FILETIMEToDateTime( fileData.ftCreationTime, utc ); default: throw new Exception( "Unknown DateTimeAttrib in File.GetDateTime() function" ); } } else throw new IO.FileNotFoundException( path ); } private static unsafe void SetDateTime( string path, DateTime dateTime, DateTimeAttrib attrib, bool utc ) { long rawFileTime = utc ? dateTime.ToFileTimeUtc() : dateTime.ToFileTime(); PathInternal.DllImport.FILETIME fileTime = new PathInternal.DllImport.FILETIME(); fileTime.dwLowDateTime = (uint)( rawFileTime & 0xFFFFFFFF ); fileTime.dwHighDateTime = (uint)( ( rawFileTime >> 32 ) & 0xFFFFFFFF ); IO.FileStream fs = OpenRead( path ); switch ( attrib ) { case DateTimeAttrib.Access: PathInternal.DllImport.SetFileTime( fs.SafeFileHandle, (PathInternal.DllImport.FILETIME*)0, &fileTime, (PathInternal.DllImport.FILETIME*)0 ); break; case DateTimeAttrib.Creation: PathInternal.DllImport.SetFileTime( fs.SafeFileHandle, &fileTime, (PathInternal.DllImport.FILETIME*)0, (PathInternal.DllImport.FILETIME*)0 ); break; case DateTimeAttrib.Write: PathInternal.DllImport.SetFileTime( fs.SafeFileHandle, (PathInternal.DllImport.FILETIME*)0, (PathInternal.DllImport.FILETIME*)0, &fileTime ); break; default: throw new Exception( "Unknown DateTimeAttrib in File.SetDateTime() function" ); } fs.Close(); } public static void SetLastWriteTime(string filename, DateTime dateTime ) { SetDateTime( filename, dateTime, DateTimeAttrib.Write, false ); } public static void SetLastWriteTimeUtc( string filename, DateTime dateTime ) { SetDateTime( filename, dateTime, DateTimeAttrib.Write, true ); } public static void SetLastAccessTime( string filename, DateTime dateTime ) { SetDateTime( filename, dateTime, DateTimeAttrib.Access, false ); } public static void SetLastAccessTimeUtc( string filename, DateTime dateTime ) { SetDateTime( filename, dateTime, DateTimeAttrib.Access, true ); } public static void SetCreationTime( string filename, DateTime dateTime ) { SetDateTime( filename, dateTime, DateTimeAttrib.Creation, false ); } public static void SetCreationTimeUtc( string filename, DateTime dateTime ) { SetDateTime( filename, dateTime, DateTimeAttrib.Creation, true ); } public static DateTime GetLastWriteTime( string path ) { return GetDateTime( path, DateTimeAttrib.Write, false ); } public static DateTime GetLastWriteTimeUtc( string path ) { return GetDateTime( path, DateTimeAttrib.Write, true ); } public static DateTime GetLastAccessTime( string path ) { return GetDateTime( path, DateTimeAttrib.Access, false ); } public static DateTime GetLastAccessTimeUtc( string path ) { return GetDateTime( path, DateTimeAttrib.Access, true ); } public static DateTime GetCreationTime( string path ) { return GetDateTime( path, DateTimeAttrib.Creation, false ); } public static DateTime GetCreationTimeUtc( string path ) { return GetDateTime( path, DateTimeAttrib.Creation, true ); } } public class Directory { public static bool Exists(string filename) { UInt32 attribs = PathInternal.GetFileAttributes( filename ); return attribs != PathInternal.DllImport.INVALID_FILE_ATTRIBUTES && ( attribs & PathInternal.DllImport.FILE_ATTRIBUTE_DIRECTORY ) > 0; } public static void CreateDirectory(string filename) { // peel back the path until we find a directory that exists string modPath = filename; Stack<string> directoryList = new Stack<string>(); while ( !Exists( modPath ) ) { int index1 = modPath.LastIndexOf( Path.DirectorySeparatorChar ); if ( index1 < 0 ) break; else { string dirName = modPath.Substring( index1 + 1 ); directoryList.Push( dirName ); modPath = modPath.Substring( 0, index1 ); } } while ( directoryList.Count > 0 ) { string dirName = directoryList.Pop(); modPath += Path.DirectorySeparatorChar + dirName; PathInternal.DllImport.CreateDirectoryW( PathInternal.ConvertToUnicodePath( modPath ), IntPtr.Zero ); } } public static string GetCurrentDirectory() { return IO.Directory.GetCurrentDirectory(); // safe } public static bool Move( string existingDir, string newDir ) { // can use same method for moving files return File.Move( existingDir, newDir ); } public static DateTime GetLastWriteTimeUtc( string path ) { return File.GetLastWriteTimeUtc( path ); } public static string[] GetFiles( string path ) { return GetFiles( path, "*" ); } public static string[] GetFiles( string path, string searchPattern ) { List<string> list = new List<string>(); PathInternal.DllImport.WIN32_FIND_DATA findData = new PathInternal.DllImport.WIN32_FIND_DATA(); IntPtr findFileHandle = PathInternal.DllImport.FindFirstFileExW( PathInternal.ConvertToUnicodePath( Path.Combine( path, searchPattern ) ), 0, ref findData, 0, (IntPtr)0, 0 ); if ( findFileHandle.ToInt64() > 0 ) { do { if ( ( findData.dwFileAttributes & PathInternal.DllImport.FILE_ATTRIBUTE_DIRECTORY ) == 0 ) list.Add( Path.Combine( path, findData.cFileName ) ); } while ( PathInternal.DllImport.FindNextFile( findFileHandle, ref findData ) ); PathInternal.DllImport.FindClose( findFileHandle ); } return list.ToArray(); } public static string[] GetDirectories( string path ) { return GetDirectories( path, "*" ); } public static string[] GetDirectories( string path, string searchPattern ) { List<string> list = new List<string>(); PathInternal.DllImport.WIN32_FIND_DATA findData = new PathInternal.DllImport.WIN32_FIND_DATA(); IntPtr findFileHandle = PathInternal.DllImport.FindFirstFileExW( PathInternal.ConvertToUnicodePath( Path.Combine( path, searchPattern ) ), 0, ref findData, 0, (IntPtr)0, 0 ); if ( findFileHandle.ToInt64() > 0 ) { do { if ( ( findData.dwFileAttributes & PathInternal.DllImport.FILE_ATTRIBUTE_DIRECTORY ) > 0 && findData.cFileName != "." && findData.cFileName != ".." ) { list.Add( Path.Combine( path, findData.cFileName ) ); } } while ( PathInternal.DllImport.FindNextFile( findFileHandle, ref findData ) ); PathInternal.DllImport.FindClose( findFileHandle ); } return list.ToArray(); } public static bool Remove( string path, bool force ) { if ( force ) PathInternal.RemoveReadOnlyFlag( path ); return PathInternal.DllImport.RemoveDirectoryW( PathInternal.ConvertToUnicodePath( path ) ); } } public class FileInfo { string mFullPath; public string FullName { get { return mFullPath; } } public string Name { get { return Path.GetFileName( mFullPath ); } } public string Extension { get { return Path.GetExtension( mFullPath ); } } public IO.FileAttributes Attributes { get { return (IO.FileAttributes)PathInternal.GetFileAttributes( mFullPath ); } } public long Length { get { return (long)File.GetFileSize( mFullPath ); } } public DateTime CreationTime { get { return File.GetCreationTime( mFullPath ); } } public DateTime LastAccessTime { get { return File.GetLastAccessTime( mFullPath ); } } public DateTime LastWriteTime { get { return File.GetLastWriteTime( mFullPath ); } } public FileInfo(string filename) { mFullPath = Path.GetFullPath( filename ); } public bool Exists { get { return File.Exists( mFullPath ); } } public IO.FileStream OpenWrite() { return File.OpenWrite( mFullPath ); } } public class DirectoryInfo { string mFullPath; public string FullName { get { return mFullPath; } } // public string Name { get { return Path.GetDirectoryOnlyName( mFullPath ); } } public DirectoryInfo(string name) { mFullPath = Path.GetFullPath( name ); } private FileInfo[] ConvertArray( string[] filenames ) { FileInfo[] array = new FileInfo[ filenames.Length ]; for ( int i = 0; i < filenames.Length; ++i ) { array[ i ] = new FileInfo( filenames[ i ] ); } return array; } public FileInfo[] GetFiles() { return ConvertArray( Directory.GetFiles( mFullPath ) ); } public FileInfo[] GetFiles( string searchPattern ) { return ConvertArray( Directory.GetFiles( mFullPath, searchPattern ) ); } public DirectoryInfo[] GetDirectories() { string[] filenames = Directory.GetDirectories( mFullPath ); DirectoryInfo[] array = new DirectoryInfo[ filenames.Length ]; for ( int i = 0; i < filenames.Length; ++i ) { array[ i ] = new DirectoryInfo( filenames[ i ] ); } return array; } } public class Path { public static readonly char DirectorySeparatorChar = IO.Path.DirectorySeparatorChar; public static readonly char AltDirectorySeperatorChar = IO.Path.AltDirectorySeparatorChar; public static string GetLeafName( string path ) { int index1 = path.LastIndexOf( Path.DirectorySeparatorChar ); if ( index1 < 0 ) return path; else if ( index1 == path.Length - 1 ) { return GetLeafName( path.Substring( 0, index1 ) ); } else return path.Substring( index1+1 ); } public static string GetStemName( string path ) { int index1 = path.LastIndexOf( Path.DirectorySeparatorChar ); if ( index1 < 0 ) return path; else if ( index1 == path.Length - 1 ) { return GetStemName( path.Substring( 0, index1 ) ); } else return path.Substring( 0, index1 ); } //public static string GetDirectoryName( string path ) //{ // if ( path == null ) // return path; // else if ( Directory.Exists( path ) ) // return path; // else // { // int index1 = path.LastIndexOf( Path.DirectorySeparatorChar ); // if (index1 < 0) // return path; // else if(index1 == path.Length-1) // return path; // path.Substring(0, path.Length - 1); // else // return path.Substring( 0, index1 ); // } //} public static char[] GetInvalidFileNameChars() { return IO.Path.GetInvalidFileNameChars(); } public static string GetTempPath() { return IO.Path.GetTempPath(); } // public static string GetDirectoryOnlyName( string path ) //{ // string directoryPath = GetDirectoryName( path ); // int index1 = directoryPath.LastIndexOf( Path.DirectorySeparatorChar ); // if ( index1 < 0 || index1 == directoryPath.Length - 1 ) // { // if ( directoryPath.Length == 0 ) // { // if ( path.StartsWith( Path.DirectorySeparatorChar.ToString() ) || path.StartsWith( Path.AltDirectorySeperatorChar.ToString() ) ) // { // return path.Substring( 1 ); // } // else // return path; // } // else // return directoryPath; // } // return directoryPath.Substring( index1 + 1 ); //} public static string GetExtension(string path) { if ( path == null ) return null; int index1 = path.LastIndexOf( '.' ); if ( index1 < 0 ) return ""; return path.Substring( index1 ); } public static string GetFileNameWithoutExtension( string path ) { if ( path == null ) return null; string modPath = GetFileName( path ); int index1 = modPath.LastIndexOf( '.' ); if ( index1 < 0 ) return modPath; return modPath.Substring( 0, index1 ); } public static string GetFullPath( string path ) { return GetFullPath( path, true ); } public unsafe static string GetFullPath(string path, bool useUnicodePath) { fixed ( char* buffer = new char[ PathInternal.OurMaxPath ] ) { PathInternal.DllImport.GetFullPathNameW( useUnicodePath ? PathInternal.ConvertToUnicodePath( path ) : path, PathInternal.OurMaxPath, buffer, (IntPtr)0 ); return new string( buffer ); } } public static string GetFileName( string filename ) { return IO.Path.GetFileName( filename ); // Will not throw too long exception } public static string Combine( string path1, string path2 ) { return IO.Path.Combine( path1, path2 ); // Will not throw too long exception } private static string GetLastErrorString() { return ( new System.ComponentModel.Win32Exception( Marshal.GetLastWin32Error() ) ).Message; } private static void CallCallback( DeletePathDelegate callback, string path, bool isFile, bool success ) { if ( callback != null ) callback( path, isFile, success, success ? "" : GetLastErrorString() ); } private static void DeletePathRecurse( string directory, bool force, DeletePathDelegate callback ) { foreach ( string file in Directory.GetFiles( directory ) ) { CallCallback( callback, file, true, File.Delete( file, force ) ); } foreach ( string subdir in Directory.GetDirectories( directory ) ) { System.IO.Directory.Delete( subdir, true ); CallCallback( callback, subdir, false, true ); } } public static void DeletePath( string path, bool force ) { DeletePath( path, force, null ); } public delegate void DeletePathDelegate( string path, bool isFile, bool succeeded, string errorMessage ); public static void DeletePath( string path, bool force, DeletePathDelegate callback ) { if ( File.Exists( path ) ) { bool success = File.Delete( path, force ); CallCallback( callback, path, true, success ); } else { DeletePathRecurse( path, force, callback ); CallCallback( callback, path, false, Directory.Remove( path, force ) ); } } static void CountFilesRecurse( string path, ref ulong count ) { count += (ulong)Directory.GetFiles( path ).Length; foreach ( string subdir in Directory.GetDirectories( path ) ) { CountFilesRecurse( subdir, ref count ); } } public static ulong CountFiles( string path ) { if ( File.Exists( path ) ) { return 1; } else { ulong count=0; CountFilesRecurse( path, ref count ); return count; } } } #endregion #region CopyFileEx /// <summary> /// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// </summary> public class FileCopyEx { #region Constants //constants that specify how the file is to be copied private const uint COPY_FILE_ALLOW_DECRYPTED_DESTINATION = 0x00000008; private const uint COPY_FILE_FAIL_IF_EXISTS = 0x00000001; private const uint COPY_FILE_OPEN_SOURCE_FOR_WRITE = 0x00000004; private const uint COPY_FILE_RESTARTABLE = 0x00000002; /// <summary> /// Callback reason passed as dwCallbackReason in CopyProgressRoutine. /// Indicates another part of the data file was copied. /// </summary> private const uint CALLBACK_CHUNK_FINISHED = 0; /// <summary> /// Callback reason passed as dwCallbackReason in CopyProgressRoutine. /// Indicates another stream was created and is about to be copied. This is the callback reason given when the callback routine is first invoked. /// </summary> private const uint CALLBACK_STREAM_SWITCH = 1; /// <summary> /// Return value of the CopyProgressRoutine. /// Indicates continue the copy operation. /// </summary> private const uint PROGRESS_CONTINUE = 0; /// <summary> /// Return value of the CopyProgressRoutine. /// Indicates cancel the copy operation and delete the destination file. /// </summary> private const uint PROGRESS_CANCEL = 1; /// <summary> /// Return value of the CopyProgressRoutine. /// Indicates stop the copy operation. It can be restarted at a later time. /// </summary> private const uint PROGRESS_STOP = 2; /// <summary> /// Return value of the CopyProgressRoutine. /// Indicates continue the copy operation, but stop invoking CopyProgressRoutine to report progress. /// </summary> private const uint PROGRESS_QUIET = 3; #endregion volatile bool mCopyCancelled = false; public void Cancel() { mCopyCancelled = true; } #region Methods /// <summary> /// The CopyProgressRoutine delegate is an application-defined callback function used with the CopyFileEx and MoveFileWithProgress functions. /// It is called when a portion of a copy or move operation is completed. /// </summary> /// <param name="TotalFileSize">Total size of the file, in bytes.</param> /// <param name="TotalBytesTransferred">Total number of bytes transferred from the source file to the destination file since the copy operation began.</param> /// <param name="StreamSize">Total size of the current file stream, in bytes.</param> /// <param name="StreamBytesTransferred">Total number of bytes in the current stream that have been transferred from the source file to the destination file since the copy operation began. </param> /// <param name="dwStreamNumber">Handle to the current stream. The first time CopyProgressRoutine is called, the stream number is 1.</param> /// <param name="dwCallbackReason">Reason that CopyProgressRoutine was called.</param> /// <param name="hSourceFile">Handle to the source file.</param> /// <param name="hDestinationFile">Handle to the destination file.</param> /// <param name="lpData">Argument passed to CopyProgressRoutine by the CopyFileEx or MoveFileWithProgress function.</param> /// <returns>A value indicating how to proceed with the copy operation.</returns> protected uint CopyProgressCallback( long TotalFileSize, long TotalBytesTransferred, long StreamSize, long StreamBytesTransferred, uint dwStreamNumber, uint dwCallbackReason, IntPtr hSourceFile, IntPtr hDestinationFile, IntPtr lpData ) { switch ( dwCallbackReason ) { case CALLBACK_CHUNK_FINISHED: // Another part of the file was copied. CopyProgressEventArgs e = new CopyProgressEventArgs( TotalFileSize, TotalBytesTransferred ); InvokeCopyProgress( e ); return e.Cancel ? PROGRESS_CANCEL : PROGRESS_CONTINUE; case CALLBACK_STREAM_SWITCH: // A new stream was created. We don't care about this one - just continue the move operation. return PROGRESS_CONTINUE; default: return PROGRESS_CONTINUE; } } public unsafe void CopyFile( string sourceFile, string destinationFile ) { mCopyCancelled = false; bool success = false; #pragma warning disable 420 fixed ( bool* cancelPtr = &mCopyCancelled ) { success = CopyFileExW( PathInternal.ConvertToUnicodePath( sourceFile ), PathInternal.ConvertToUnicodePath( destinationFile ), new CopyProgressRoutine( this.CopyProgressCallback ), IntPtr.Zero, cancelPtr, COPY_FILE_ALLOW_DECRYPTED_DESTINATION ); } #pragma warning restore 420 //Throw an exception if the copy failed if ( !success && !mCopyCancelled ) { int error = Marshal.GetLastWin32Error(); throw new System.ComponentModel.Win32Exception( error ); } } #endregion #region Events public event CopyProgressEventHandler CopyProgress; protected void InvokeCopyProgress( CopyProgressEventArgs e ) { if ( CopyProgress != null ) { CopyProgress( this, e ); } } #endregion #region P/Invoke [DllImport( "kernel32.dll", SetLastError = true, CharSet=CharSet.Unicode )] private static unsafe extern bool CopyFileExW( string lpExistingFileName, string lpNewFileName, CopyProgressRoutine lpProgressRoutine, IntPtr lpData, bool* pbCancel, uint dwCopyFlags ); #endregion /// <summary> /// The CopyProgressRoutine delegate is an application-defined callback function used with the CopyFileEx and MoveFileWithProgress functions. /// It is called when a portion of a copy or move operation is completed. /// </summary> private delegate uint CopyProgressRoutine( long TotalFileSize, long TotalBytesTransferred, long StreamSize, long StreamBytesTransferred, uint dwStreamNumber, uint dwCallbackReason, IntPtr hSourceFile, IntPtr hDestinationFile, IntPtr lpData ); } /// <summary> /// Represents the method which handles the CopyProgress event. /// </summary> public delegate void CopyProgressEventHandler( object sender, CopyProgressEventArgs e ); /// <summary> /// Provides data for the CopyProgress event. /// </summary> public class CopyProgressEventArgs : EventArgs { private long _totalFileSize; private long _totalBytesTransferred; private bool _cancel = false; /// <summary> /// Initializes a new instance of the CopyProgressEventArgs class. /// </summary> /// <param name="totalFileSize">The total file size, in bytes.</param> /// <param name="totalBytesTransferred">The total bytes transferred so far.</param> public CopyProgressEventArgs( long totalFileSize, long totalBytesTransferred ) { _totalFileSize = totalFileSize; _totalBytesTransferred = totalBytesTransferred; } /// <summary> /// Gets the total file size, in bytes, of the file being moved. /// </summary> /// <value>The total file size.</value> public long TotalFileSize { get { return _totalFileSize; } } /// <summary> /// Gets the total bytes transferred so far. /// </summary> /// <value>The total bytes transferred.</value> public long TotalBytesTransferred { get { return _totalBytesTransferred; } } /// <summary> /// Gets or sets a value indicating whether the event should be canceled. /// </summary> /// <value>True if the event should be canceled, False otherwise.</value> public bool Cancel { get { return _cancel; } set { _cancel = value; } } } #endregion }
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using EasyNetQ.ChannelDispatcher; using EasyNetQ.Consumer; using EasyNetQ.DI; using EasyNetQ.Events; using EasyNetQ.Interception; using EasyNetQ.Internals; using EasyNetQ.Logging; using EasyNetQ.Producer; using EasyNetQ.Topology; namespace EasyNetQ; /// <inheritdoc /> public class RabbitAdvancedBus : IAdvancedBus { private readonly IChannelDispatcher channelDispatcher; private readonly ConnectionConfiguration configuration; private readonly IPublishConfirmationListener confirmationListener; private readonly ILogger logger; private readonly IProducerConnection producerConnection; private readonly IConsumerConnection consumerConnection; private readonly IConsumerFactory consumerFactory; private readonly IEventBus eventBus; private readonly IDisposable[] eventSubscriptions; private readonly IHandlerCollectionFactory handlerCollectionFactory; private readonly IMessageSerializationStrategy messageSerializationStrategy; private readonly IProduceConsumeInterceptor produceConsumeInterceptor; private readonly IPullingConsumerFactory pullingConsumerFactory; private readonly AdvancedBusEventHandlers advancedBusEventHandlers; private readonly IConsumeScopeProvider consumeScopeProvider; private volatile bool disposed; /// <summary> /// Creates RabbitAdvancedBus /// </summary> public RabbitAdvancedBus( ILogger<RabbitAdvancedBus> logger, IProducerConnection producerConnection, IConsumerConnection consumerConnection, IConsumerFactory consumerFactory, IChannelDispatcher channelDispatcher, IPublishConfirmationListener confirmationListener, IEventBus eventBus, IHandlerCollectionFactory handlerCollectionFactory, IServiceResolver container, ConnectionConfiguration configuration, IProduceConsumeInterceptor produceConsumeInterceptor, IMessageSerializationStrategy messageSerializationStrategy, IConventions conventions, IPullingConsumerFactory pullingConsumerFactory, AdvancedBusEventHandlers advancedBusEventHandlers, IConsumeScopeProvider consumeScopeProvider ) { Preconditions.CheckNotNull(producerConnection, nameof(producerConnection)); Preconditions.CheckNotNull(consumerConnection, nameof(consumerConnection)); Preconditions.CheckNotNull(consumerFactory, nameof(consumerFactory)); Preconditions.CheckNotNull(eventBus, nameof(eventBus)); Preconditions.CheckNotNull(handlerCollectionFactory, nameof(handlerCollectionFactory)); Preconditions.CheckNotNull(container, nameof(container)); Preconditions.CheckNotNull(messageSerializationStrategy, nameof(messageSerializationStrategy)); Preconditions.CheckNotNull(configuration, nameof(configuration)); Preconditions.CheckNotNull(produceConsumeInterceptor, nameof(produceConsumeInterceptor)); Preconditions.CheckNotNull(conventions, nameof(conventions)); Preconditions.CheckNotNull(pullingConsumerFactory, nameof(pullingConsumerFactory)); Preconditions.CheckNotNull(advancedBusEventHandlers, nameof(advancedBusEventHandlers)); this.logger = logger; this.producerConnection = producerConnection; this.consumerConnection = consumerConnection; this.consumerFactory = consumerFactory; this.channelDispatcher = channelDispatcher; this.confirmationListener = confirmationListener; this.eventBus = eventBus; this.handlerCollectionFactory = handlerCollectionFactory; this.Container = container; this.configuration = configuration; this.produceConsumeInterceptor = produceConsumeInterceptor; this.messageSerializationStrategy = messageSerializationStrategy; this.pullingConsumerFactory = pullingConsumerFactory; this.advancedBusEventHandlers = advancedBusEventHandlers; this.Conventions = conventions; this.consumeScopeProvider = consumeScopeProvider; Connected += advancedBusEventHandlers.Connected; Disconnected += advancedBusEventHandlers.Disconnected; Blocked += advancedBusEventHandlers.Blocked; Unblocked += advancedBusEventHandlers.Unblocked; MessageReturned += advancedBusEventHandlers.MessageReturned; eventSubscriptions = new[] { this.eventBus.Subscribe<ConnectionCreatedEvent>(OnConnectionCreated), this.eventBus.Subscribe<ConnectionRecoveredEvent>(OnConnectionRecovered), this.eventBus.Subscribe<ConnectionDisconnectedEvent>(OnConnectionDisconnected), this.eventBus.Subscribe<ConnectionBlockedEvent>(OnConnectionBlocked), this.eventBus.Subscribe<ConnectionUnblockedEvent>(OnConnectionUnblocked), this.eventBus.Subscribe<ReturnedMessageEvent>(OnMessageReturned), }; } /// <inheritdoc /> public bool IsConnected => producerConnection.IsConnected && consumerConnection.IsConnected; /// <inheritdoc /> public Task ConnectAsync(CancellationToken cancellationToken = default) { producerConnection.Connect(); consumerConnection.Connect(); return Task.CompletedTask; } #region Consume /// <inheritdoc /> public IDisposable Consume(Action<IConsumeConfiguration> configure) { Preconditions.CheckNotNull(configure, nameof(configure)); var consumeConfiguration = new ConsumeConfiguration( configuration.PrefetchCount, handlerCollectionFactory ); configure(consumeConfiguration); var consumerConfiguration = new ConsumerConfiguration( consumeConfiguration.PrefetchCount, consumeConfiguration.PerQueueConsumeConfigurations.ToDictionary( x => x.Item1, x => new PerQueueConsumerConfiguration( x.Item3.AutoAck, x.Item3.ConsumerTag, x.Item3.IsExclusive, x.Item3.Arguments, async (body, properties, receivedInfo, cancellationToken) => { var rawMessage = produceConsumeInterceptor.OnConsume( new ConsumedMessage(receivedInfo, properties, body) ); using var scope = consumeScopeProvider.CreateScope(); return await x.Item2( rawMessage.Body, rawMessage.Properties, rawMessage.ReceivedInfo, cancellationToken ).ConfigureAwait(false); } ) ).Union( consumeConfiguration.PerQueueTypedConsumeConfigurations.ToDictionary( x => x.Item1, x => new PerQueueConsumerConfiguration( x.Item3.AutoAck, x.Item3.ConsumerTag, x.Item3.IsExclusive, x.Item3.Arguments, async (body, properties, receivedInfo, cancellationToken) => { var rawMessage = produceConsumeInterceptor.OnConsume( new ConsumedMessage(receivedInfo, properties, body) ); var deserializedMessage = messageSerializationStrategy.DeserializeMessage( rawMessage.Properties, rawMessage.Body ); var handler = x.Item2.GetHandler(deserializedMessage.MessageType); using var scope = consumeScopeProvider.CreateScope(); return await handler(deserializedMessage, receivedInfo, cancellationToken) .ConfigureAwait(false); } ) ) ).ToDictionary(x => x.Key, x => x.Value) ); var consumer = consumerFactory.CreateConsumer(consumerConfiguration); consumer.StartConsuming(); return consumer; } #endregion /// <inheritdoc /> public async Task<QueueStats> GetQueueStatsAsync(Queue queue, CancellationToken cancellationToken) { using var cts = cancellationToken.WithTimeout(configuration.Timeout); var declareResult = await channelDispatcher.InvokeAsync( x => x.QueueDeclarePassive(queue.Name), ChannelDispatchOptions.ConsumerTopology, cts.Token ).ConfigureAwait(false); if (logger.IsDebugEnabled()) { logger.DebugFormat( "{messagesCount} messages, {consumersCount} consumers in queue {queue}", declareResult.MessageCount, declareResult.ConsumerCount, queue.Name ); } return new QueueStats(declareResult.MessageCount, declareResult.ConsumerCount); } /// <inheritdoc /> public IPullingConsumer<PullResult> CreatePullingConsumer(in Queue queue, bool autoAck = true) { var options = new PullingConsumerOptions(autoAck, configuration.Timeout); return pullingConsumerFactory.CreateConsumer(queue, options); } /// <inheritdoc /> public IPullingConsumer<PullResult<T>> CreatePullingConsumer<T>(in Queue queue, bool autoAck = true) { var options = new PullingConsumerOptions(autoAck, configuration.Timeout); return pullingConsumerFactory.CreateConsumer<T>(queue, options); } /// <inheritdoc /> public event EventHandler<ConnectedEventArgs> Connected; /// <inheritdoc /> public event EventHandler<DisconnectedEventArgs> Disconnected; /// <inheritdoc /> public event EventHandler<BlockedEventArgs> Blocked; /// <inheritdoc /> public event EventHandler<UnblockedEventArgs> Unblocked; /// <inheritdoc /> public event EventHandler<MessageReturnedEventArgs> MessageReturned; /// <inheritdoc /> public IServiceResolver Container { get; } /// <inheritdoc /> public IConventions Conventions { get; } /// <inheritdoc /> public virtual void Dispose() { if (disposed) return; disposed = true; foreach (var eventSubscription in eventSubscriptions) eventSubscription.Dispose(); Connected -= advancedBusEventHandlers.Connected; Disconnected -= advancedBusEventHandlers.Disconnected; Blocked -= advancedBusEventHandlers.Blocked; Unblocked -= advancedBusEventHandlers.Unblocked; MessageReturned -= advancedBusEventHandlers.MessageReturned; } #region Publish /// <inheritdoc /> public virtual async Task PublishAsync( Exchange exchange, string routingKey, bool mandatory, IMessage message, CancellationToken cancellationToken ) { Preconditions.CheckNotNull(exchange, nameof(exchange)); Preconditions.CheckShortString(routingKey, nameof(routingKey)); Preconditions.CheckNotNull(message, nameof(message)); using var serializedMessage = messageSerializationStrategy.SerializeMessage(message); await PublishAsync( exchange, routingKey, mandatory, serializedMessage.Properties, serializedMessage.Body, cancellationToken ).ConfigureAwait(false); } /// <inheritdoc /> public virtual async Task PublishAsync<T>( Exchange exchange, string routingKey, bool mandatory, IMessage<T> message, CancellationToken cancellationToken ) { Preconditions.CheckShortString(routingKey, "routingKey"); Preconditions.CheckNotNull(message, nameof(message)); using var serializedMessage = messageSerializationStrategy.SerializeMessage(message); await PublishAsync( exchange, routingKey, mandatory, serializedMessage.Properties, serializedMessage.Body, cancellationToken ).ConfigureAwait(false); } /// <inheritdoc /> public virtual async Task PublishAsync( Exchange exchange, string routingKey, bool mandatory, MessageProperties messageProperties, ReadOnlyMemory<byte> body, CancellationToken cancellationToken ) { Preconditions.CheckShortString(routingKey, nameof(routingKey)); Preconditions.CheckNotNull(messageProperties, nameof(messageProperties)); Preconditions.CheckNotNull(body, nameof(body)); using var cts = cancellationToken.WithTimeout(configuration.Timeout); var rawMessage = produceConsumeInterceptor.OnProduce(new ProducedMessage(messageProperties, body)); if (configuration.PublisherConfirms) { while (true) { var pendingConfirmation = await channelDispatcher.InvokeAsync(model => { var confirmation = confirmationListener.CreatePendingConfirmation(model); rawMessage.Properties.SetConfirmationId(confirmation.Id); var properties = model.CreateBasicProperties(); rawMessage.Properties.CopyTo(properties); try { model.BasicPublish(exchange.Name, routingKey, mandatory, properties, rawMessage.Body); } catch (Exception) { confirmation.Cancel(); throw; } return confirmation; }, ChannelDispatchOptions.ProducerPublishWithConfirms, cts.Token).ConfigureAwait(false); try { await pendingConfirmation.WaitAsync(cts.Token).ConfigureAwait(false); break; } catch (PublishInterruptedException) { } } } else { await channelDispatcher.InvokeAsync(model => { var properties = model.CreateBasicProperties(); rawMessage.Properties.CopyTo(properties); model.BasicPublish(exchange.Name, routingKey, mandatory, properties, rawMessage.Body); }, ChannelDispatchOptions.ProducerPublish, cts.Token).ConfigureAwait(false); } eventBus.Publish( new PublishedMessageEvent(exchange, routingKey, rawMessage.Properties, rawMessage.Body) ); if (logger.IsDebugEnabled()) { logger.DebugFormat( "Published to exchange {exchange} with routingKey={routingKey} and correlationId={correlationId}", exchange.Name, routingKey, messageProperties.CorrelationId ); } } #endregion #region Exchage, Queue, Binding /// <inheritdoc /> public Task<Queue> QueueDeclareAsync(CancellationToken cancellationToken) { return QueueDeclareAsync( string.Empty, c => c.AsDurable(true).AsExclusive(true).AsAutoDelete(true), cancellationToken ); } /// <inheritdoc /> public async Task QueueDeclarePassiveAsync(string name, CancellationToken cancellationToken = default) { Preconditions.CheckNotNull(name, nameof(name)); using var cts = cancellationToken.WithTimeout(configuration.Timeout); await channelDispatcher.InvokeAsync( x => x.QueueDeclarePassive(name), ChannelDispatchOptions.ConsumerTopology, cts.Token ).ConfigureAwait(false); if (logger.IsDebugEnabled()) { logger.DebugFormat("Passive declared queue {queue}", name); } } /// <inheritdoc /> public async Task<Queue> QueueDeclareAsync( string name, Action<IQueueDeclareConfiguration> configure, CancellationToken cancellationToken = default ) { Preconditions.CheckNotNull(name, nameof(name)); Preconditions.CheckNotNull(configure, nameof(configure)); using var cts = cancellationToken.WithTimeout(configuration.Timeout); var queueDeclareConfiguration = new QueueDeclareConfiguration(); configure(queueDeclareConfiguration); var isDurable = queueDeclareConfiguration.IsDurable; var isExclusive = queueDeclareConfiguration.IsExclusive; var isAutoDelete = queueDeclareConfiguration.IsAutoDelete; var arguments = queueDeclareConfiguration.Arguments; var queueDeclareOk = await channelDispatcher.InvokeAsync( x => x.QueueDeclare(name, isDurable, isExclusive, isAutoDelete, arguments), ChannelDispatchOptions.ConsumerTopology, cts.Token ).ConfigureAwait(false); if (logger.IsDebugEnabled()) { logger.DebugFormat( "Declared queue {queue}: durable={durable}, exclusive={exclusive}, autoDelete={autoDelete}, arguments={arguments}", queueDeclareOk.QueueName, isDurable, isExclusive, isAutoDelete, arguments?.Stringify() ); } return new Queue(queueDeclareOk.QueueName, isDurable, isExclusive, isAutoDelete, arguments); } /// <inheritdoc /> public virtual async Task QueueDeleteAsync( Queue queue, bool ifUnused = false, bool ifEmpty = false, CancellationToken cancellationToken = default ) { using var cts = cancellationToken.WithTimeout(configuration.Timeout); await channelDispatcher.InvokeAsync( x => x.QueueDelete(queue.Name, ifUnused, ifEmpty), ChannelDispatchOptions.ConsumerTopology, cts.Token ).ConfigureAwait(false); if (logger.IsDebugEnabled()) { logger.DebugFormat("Deleted queue {queue}", queue.Name); } } /// <inheritdoc /> public virtual async Task QueuePurgeAsync(Queue queue, CancellationToken cancellationToken) { using var cts = cancellationToken.WithTimeout(configuration.Timeout); await channelDispatcher.InvokeAsync( x => x.QueuePurge(queue.Name), ChannelDispatchOptions.ConsumerTopology, cts.Token ).ConfigureAwait(false); if (logger.IsDebugEnabled()) { logger.DebugFormat("Purged queue {queue}", queue.Name); } } /// <inheritdoc /> public async Task ExchangeDeclarePassiveAsync(string name, CancellationToken cancellationToken = default) { Preconditions.CheckShortString(name, "name"); using var cts = cancellationToken.WithTimeout(configuration.Timeout); await channelDispatcher.InvokeAsync( x => x.ExchangeDeclarePassive(name), ChannelDispatchOptions.ProducerTopology, cts.Token ).ConfigureAwait(false); if (logger.IsDebugEnabled()) { logger.DebugFormat("Passive declared exchange {exchange}", name); } } /// <inheritdoc /> public async Task<Exchange> ExchangeDeclareAsync( string name, Action<IExchangeDeclareConfiguration> configure, CancellationToken cancellationToken = default ) { Preconditions.CheckShortString(name, "name"); using var cts = cancellationToken.WithTimeout(configuration.Timeout); var exchangeDeclareConfiguration = new ExchangeDeclareConfiguration(); configure(exchangeDeclareConfiguration); var type = exchangeDeclareConfiguration.Type; var isDurable = exchangeDeclareConfiguration.IsDurable; var isAutoDelete = exchangeDeclareConfiguration.IsAutoDelete; var arguments = exchangeDeclareConfiguration.Arguments; await channelDispatcher.InvokeAsync( x => x.ExchangeDeclare(name, type, isDurable, isAutoDelete, arguments), ChannelDispatchOptions.ProducerTopology, cts.Token ).ConfigureAwait(false); if (logger.IsDebugEnabled()) { logger.DebugFormat( "Declared exchange {exchange}: type={type}, durable={durable}, autoDelete={autoDelete}, arguments={arguments}", name, type, isDurable, isAutoDelete, arguments?.Stringify() ); } return new Exchange(name, type, isDurable, isAutoDelete, arguments); } /// <inheritdoc /> public virtual async Task ExchangeDeleteAsync( Exchange exchange, bool ifUnused = false, CancellationToken cancellationToken = default ) { using var cts = cancellationToken.WithTimeout(configuration.Timeout); await channelDispatcher.InvokeAsync( x => x.ExchangeDelete(exchange.Name, ifUnused), ChannelDispatchOptions.ProducerTopology, cts.Token ).ConfigureAwait(false); if (logger.IsDebugEnabled()) { logger.DebugFormat("Deleted exchange {exchange}", exchange.Name); } } /// <inheritdoc /> public async Task<Binding<Queue>> BindAsync( Exchange exchange, Queue queue, string routingKey, IDictionary<string, object> arguments, CancellationToken cancellationToken ) { Preconditions.CheckShortString(routingKey, "routingKey"); using var cts = cancellationToken.WithTimeout(configuration.Timeout); await channelDispatcher.InvokeAsync( x => x.QueueBind(queue.Name, exchange.Name, routingKey, arguments), ChannelDispatchOptions.ConsumerTopology, cts.Token ).ConfigureAwait(false); if (logger.IsDebugEnabled()) { logger.DebugFormat( "Bound queue {queue} to exchange {exchange} with routingKey={routingKey} and arguments={arguments}", queue.Name, exchange.Name, routingKey, arguments?.Stringify() ); } return new Binding<Queue>(exchange, queue, routingKey, arguments); } /// <inheritdoc /> public async Task<Binding<Exchange>> BindAsync( Exchange source, Exchange destination, string routingKey, IDictionary<string, object> arguments, CancellationToken cancellationToken ) { Preconditions.CheckShortString(routingKey, "routingKey"); using var cts = cancellationToken.WithTimeout(configuration.Timeout); await channelDispatcher.InvokeAsync( x => x.ExchangeBind(destination.Name, source.Name, routingKey, arguments), ChannelDispatchOptions.ProducerTopology, cts.Token ).ConfigureAwait(false); if (logger.IsDebugEnabled()) { logger.DebugFormat( "Bound destination exchange {destinationExchange} to source exchange {sourceExchange} with routingKey={routingKey} and arguments={arguments}", destination.Name, source.Name, routingKey, arguments?.Stringify() ); } return new Binding<Exchange>(source, destination, routingKey, arguments); } /// <inheritdoc /> public virtual async Task UnbindAsync(Binding<Queue> binding, CancellationToken cancellationToken) { using var cts = cancellationToken.WithTimeout(configuration.Timeout); await channelDispatcher.InvokeAsync( x => x.QueueUnbind( binding.Destination.Name, binding.Source.Name, binding.RoutingKey, binding.Arguments ), ChannelDispatchOptions.ConsumerTopology, cts.Token ).ConfigureAwait(false); if (logger.IsDebugEnabled()) { logger.DebugFormat( "Unbound queue {queue} from exchange {exchange} with routing key {routingKey}", binding.Destination.Name, binding.Source.Name, binding.RoutingKey ); } } /// <inheritdoc /> public virtual async Task UnbindAsync(Binding<Exchange> binding, CancellationToken cancellationToken) { using var cts = cancellationToken.WithTimeout(configuration.Timeout); await channelDispatcher.InvokeAsync( x => x.ExchangeUnbind( binding.Destination.Name, binding.Source.Name, binding.RoutingKey, binding.Arguments ), ChannelDispatchOptions.ProducerTopology, cts.Token ).ConfigureAwait(false); if (logger.IsDebugEnabled()) { logger.DebugFormat( "Unbound destination exchange {destinationExchange} from source exchange {sourceExchange} with routing key {routingKey}", binding.Destination.Name, binding.Source.Name, binding.RoutingKey ); } } #endregion private void OnConnectionCreated(in ConnectionCreatedEvent @event) { Connected?.Invoke( this, new ConnectedEventArgs(@event.Type, @event.Endpoint.HostName, @event.Endpoint.Port) ); } private void OnConnectionRecovered(in ConnectionRecoveredEvent @event) { Connected?.Invoke( this, new ConnectedEventArgs(@event.Type, @event.Endpoint.HostName, @event.Endpoint.Port) ); } private void OnConnectionDisconnected(in ConnectionDisconnectedEvent @event) { Disconnected?.Invoke( this, new DisconnectedEventArgs(@event.Type, @event.Endpoint.HostName, @event.Endpoint.Port, @event.Reason) ); } private void OnConnectionBlocked(in ConnectionBlockedEvent @event) { Blocked?.Invoke(this, new BlockedEventArgs(@event.Type, @event.Reason)); } private void OnConnectionUnblocked(in ConnectionUnblockedEvent @event) { Unblocked?.Invoke(this, new UnblockedEventArgs(@event.Type)); } private void OnMessageReturned(in ReturnedMessageEvent @event) { MessageReturned?.Invoke(this, new MessageReturnedEventArgs(@event.Body, @event.Properties, @event.Info)); } }
// * // * Copyright (C) 2008 Roger Alsing : http://www.RogerAlsing.com // * // * This library is free software; you can redistribute it and/or modify it // * under the terms of the GNU Lesser General Public License 2.1 or later, as // * published by the Free Software Foundation. See the included license.txt // * or http://www.gnu.org/copyleft/lesser.html for details. // * // * using System; using System.Collections; using System.ComponentModel; using System.IO; using System.Reflection; using System.Text; using Alsing.SourceCode.SyntaxDocumentParsers; namespace Alsing.SourceCode { /// <summary> /// The SyntaxDocument is a component that is responsible for Parsing , Folding , Undo / Redo actions and various text actions. /// </summary> public class SyntaxDocument : Component, IEnumerable { #region General declarations private readonly RowList rows = new RowList(); /// <summary> /// /// </summary> public RowList KeywordQueue = new RowList(); /// <summary> /// List of rows that should be parsed /// </summary> public RowList ParseQueue = new RowList(); private UndoBlockCollection captureBlock; private bool captureMode; private bool folding = true; /// <summary> /// For public use only /// </summary> private bool isParsed = true; private bool modified; private string mSyntaxFile = ""; /// <summary> /// Gets or Sets if folding needs to be recalculated /// </summary> public bool NeedResetRows; /// <summary> /// The active parser of the document /// </summary> public IParser Parser = new DefaultParser(); /// <summary> /// Tag property , lets the user store custom data in the row. /// </summary> public object Tag; /// <summary> /// Buffer containing undo actions /// </summary> public readonly UndoBuffer UndoBuffer = new UndoBuffer(); /// <summary> /// List of rows that is not hidden by folding /// </summary> public RowList VisibleRows = new RowList(); #region PUBLIC PROPERTY UNDOSTEP private int _UndoStep; public int UndoStep { get { if (_UndoStep > UndoBuffer.Count) _UndoStep = UndoBuffer.Count; return _UndoStep; } set { _UndoStep = value; } } #endregion /// <summary> /// Event that is raised when there is no more rows to parse /// </summary> public event EventHandler ParsingCompleted; public event EventHandler UndoBufferChanged = null; /// <summary> /// Raised when the parser is active /// </summary> public event EventHandler Parsing; /// <summary> /// Raised when the document content is changed /// </summary> public event EventHandler Change; public event RowEventHandler BreakPointAdded; public event RowEventHandler BreakPointRemoved; public event RowEventHandler BookmarkAdded; public event RowEventHandler BookmarkRemoved; protected virtual void OnBreakPointAdded(Row r) { if (BreakPointAdded != null) BreakPointAdded(this, new RowEventArgs(r)); } protected virtual void OnBreakPointRemoved(Row r) { if (BreakPointRemoved != null) BreakPointRemoved(this, new RowEventArgs(r)); } protected virtual void OnBookmarkAdded(Row r) { if (BookmarkAdded != null) BookmarkAdded(this, new RowEventArgs(r)); } protected virtual void OnBookmarkRemoved(Row r) { if (BookmarkRemoved != null) BookmarkRemoved(this, new RowEventArgs(r)); } protected virtual void OnUndoBufferChanged() { if (UndoBufferChanged != null) UndoBufferChanged(this, EventArgs.Empty); } public virtual void InvokeBreakPointAdded(Row r) { OnBreakPointAdded(r); } public virtual void InvokeBreakPointRemoved(Row r) { OnBreakPointRemoved(r); } public virtual void InvokeBookmarkAdded(Row r) { OnBookmarkAdded(r); } public virtual void InvokeBookmarkRemoved(Row r) { OnBookmarkRemoved(r); } //public event System.EventHandler CreateParser; /// <summary> /// Raised when the modified flag has changed /// </summary> public event EventHandler ModifiedChanged; //---------------------------------------------- /// <summary> /// Raised when a row have been parsed /// </summary> public event ParserEventHandler RowParsed; // public event ParserEventHandler RowAdded; /// <summary> /// Raised when a row have been deleted /// </summary> public event ParserEventHandler RowDeleted; #endregion #region PUBLIC PROPERTY MAXUNDOBUFFERSIZE /// <summary> /// Gets or Sets the Maximum number of entries in the undobuffer /// </summary> public int MaxUndoBufferSize { get { return UndoBuffer.MaxSize; } set { UndoBuffer.MaxSize = value; } } #endregion #region PUBLIC PROPERTY VERSION private long _Version = long.MinValue; [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public long Version { get { return _Version; } set { _Version = value; } } #endregion /// <summary> /// /// </summary> /// <param name="container"></param> public SyntaxDocument(IContainer container) : this() { container.Add(this); InitializeComponent(); } /// <summary> /// /// </summary> public SyntaxDocument() { Parser.Document = this; Text = ""; ResetVisibleRows(); Init(); } /// <summary> /// Get or Set the Modified flag /// </summary> public bool Modified { get { return modified; } set { modified = value; OnModifiedChanged(); } } /// <summary> /// Get or Set the Name of the Syntaxfile to use /// </summary> [DefaultValue("")] public string SyntaxFile { get { return mSyntaxFile; } set { mSyntaxFile = value; // this.Parser=new Parser_Default(); Parser.Init(value); Text = Text; } } /// <summary> /// Gets or Sets if the document should use folding or not /// </summary> [DefaultValue(true)] public bool Folding { get { return folding; } set { folding = value; if (!value) { foreach (Row r in this) { r.Expanded = true; } } ResetVisibleRows(); OnChange(); } } /// <summary> /// Gets if the document is fully parsed /// </summary> [Browsable(false)] public bool IsParsed { get { return isParsed; } } /// <summary> /// Returns the row at the specified index /// </summary> public Row this[int index] { get { if (index < 0 || index >= rows.Count) { // System.Diagnostics.Debugger.Break (); return null; } return rows[index]; } set { rows[index] = value; } } /// <summary> /// Gets the row count of the document /// </summary> [Browsable(false)] public int Count { get { return rows.Count; } } /// <summary> /// Gets or Sets the text of the entire document /// </summary> [Browsable(false)] // [RefreshProperties (RefreshProperties.All)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public string Text { get { int i = 0; var sb = new StringBuilder(); ParseAll(true); foreach (Row tr in rows) { if (i > 0) sb.Append(Environment.NewLine); tr.MatchCase(); sb.Append(tr.Text); i++; } return sb.ToString(); } set { clear(); Add(""); InsertText(value, 0, 0); UndoBuffer.Clear(); UndoStep = 0; Modified = false; isParsed = false; //OnChange(); InvokeChange(); } } /// <summary> /// Gets and string array containing the text of all rows. /// </summary> public string[] Lines { get { return Text.Split("\n".ToCharArray()); } set { string s = ""; foreach (string sl in value) s += sl + "\n"; Text = s.Substring(0, s.Length - 1); } } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { new System.ComponentModel.Container(); } #endregion #region IEnumerable Members /// <summary> /// /// </summary> /// <returns></returns> public IEnumerator GetEnumerator() { return rows.GetEnumerator(); } #endregion /// <summary> /// For internal use only /// </summary> public void ChangeVersion() { Version ++; if (Version > long.MaxValue - 10) Version = long.MinValue; } /// <summary> /// Starts an Undo Capture. /// This method can be called if you with to collect multiple text operations into one undo action /// </summary> public void StartUndoCapture() { captureMode = true; captureBlock = new UndoBlockCollection(); } /// <summary> /// Ends an Undo capture and pushes the collected actions onto the undostack /// <seealso cref="StartUndoCapture"/> /// </summary> /// <returns></returns> public UndoBlockCollection EndUndoCapture() { captureMode = false; AddToUndoList(captureBlock); return captureBlock; } /// <summary> /// ReParses the document /// </summary> public void ReParse() { Text = Text; } /// <summary> /// Removes all bookmarks in the document /// </summary> public void ClearBookmarks() { foreach (Row r in this) { r.Bookmarked = false; } InvokeChange(); } /// <summary> /// Removes all breakpoints in the document. /// </summary> public void ClearBreakpoints() { foreach (Row r in this) { r.Breakpoint = false; } InvokeChange(); } /// <summary> /// Call this method to ensure that a specific row is fully parsed /// </summary> /// <param name="Row"></param> public void EnsureParsed(Row Row) { ParseAll(); Parser.ParseRow(Row.Index, true); } private void Init() { var l = new SyntaxDefinition(); l.mainSpanDefinition = new SpanDefinition(l) { MultiLine = true }; Parser.Init(l); } /// <summary> /// Call this method to make the SyntaxDocument raise the Changed event /// </summary> public void InvokeChange() { OnChange(); } /// <summary> /// Performs a span parse on all rows. No Keyword colorizing /// </summary> public void ParseAll() { while (ParseQueue.Count > 0) ParseSome(); ParseQueue.Clear(); } /// <summary> /// Parses all rows , either a span parse or a full parse with keyword colorizing /// </summary> public void ParseAll(bool ParseKeywords) { ParseAll(); if (ParseKeywords) { for (int i = 0; i < Count; i++) { if (this[i].RowState != RowState.AllParsed) Parser.ParseRow(i, true); } ParseQueue.Clear(); KeywordQueue.Clear(); } } /// <summary> /// Folds all foldable rows /// </summary> public void FoldAll() { ParseAll(false); foreach (Row r in this) { r.Expanded = false; } ResetVisibleRows(); OnChange(); } /// <summary> /// UnFolds all foldable rows /// </summary> public void UnFoldAll() { ParseAll(false); foreach (Row r in this) { r.Expanded = true; } ResetVisibleRows(); OnChange(); } /// <summary> /// Parses a chunk of 1000 rows , this is not thread safe /// </summary> public void ParseSome() { ParseSome(1000); } /// <summary> /// Parse a chunk of rows, this is not thread safe /// </summary> /// <param name="RowCount">The number of rows to parse</param> public void ParseSome(int RowCount) { if (ParseQueue.Count > 0) { isParsed = false; int i = 0; while (i < RowCount && ParseQueue.Count > 0) { Row row = ParseQueue[0]; i += ParseRows(row); } if (NeedResetRows) ResetVisibleRows(); if (Parsing != null) Parsing(this, new EventArgs()); } else { if (!isParsed && !Modified) { isParsed = true; foreach (Row r in this) { if (r.expansion_StartSpan != null && r.Expansion_EndRow != null) { if (r.expansion_StartSpan.Scope.DefaultExpanded == false) r.Expanded = false; } } ResetVisibleRows(); if (ParsingCompleted != null) ParsingCompleted(this, new EventArgs()); } } if (ParseQueue.Count == 0 && KeywordQueue.Count > 0) { // Console.WriteLine (this.KeywordQueue.Count.ToString ()); int i = 0; while (i < RowCount/20 && KeywordQueue.Count > 0) { Row row = KeywordQueue[0]; i += ParseRows(row, true); } } } /// <summary> /// Add a new row with the specified text to the bottom of the document /// </summary> /// <param name="text">Text to add</param> /// <returns>The row that was added</returns> public Row Add(string text) { return Add(text, true); } /// <summary> /// Add a new row with the specified text to the bottom of the document /// </summary> /// <param name="text">Text to add</param> /// <param name="StoreUndo">true if and undo action should be added to the undo stack</param> /// <returns>The row that was added</returns> public Row Add(string text, bool StoreUndo) { var xtl = new Row(); rows.Add(xtl); xtl.Document = this; xtl.Text = text; return xtl; } /// <summary> /// Insert a text at the specified row index /// </summary> /// <param name="text">Text to insert</param> /// <param name="index">Row index where the text should be inserted</param> /// <returns>The row that was inserted</returns> public Row Insert(string text, int index) { return Insert(text, index, true); } /// <summary> /// Insert a text at the specified row index /// </summary> /// <param name="text">Text to insert</param> /// <param name="index">Row index where the text should be inserted</param> /// <param name="storeUndo">true if and undo action should be added to the undo stack</param> /// <returns>The row that was inserted</returns> public Row Insert(string text, int index, bool storeUndo) { var xtl = new Row {Document = this}; rows.Insert(index, xtl); xtl.Text = text; if (storeUndo) { var undo = new UndoBlock { Text = text, }; undo.Position.Y = IndexOf(xtl); AddToUndoList(undo); } //this.ResetVisibleRows (); return xtl; } /// <summary> /// Remove a row at specified row index /// </summary> /// <param name="index">index of the row that should be removed</param> public void Remove(int index) { Remove(index, true); } public void Remove(int index, bool StoreUndo) { Remove(index, StoreUndo, true); } /// <summary> /// Remove a row at specified row index /// </summary> /// <param name="index">index of the row that should be removed</param> /// <param name="storeUndo">true if and undo action should be added to the undo stack</param> /// <param name="raiseChanged"></param> public void Remove(int index, bool storeUndo, bool raiseChanged) { Row r = this[index]; if (storeUndo) { var ra = new TextRange(); if (index != Count - 1) { ra.FirstColumn = 0; ra.FirstRow = index; ra.LastRow = index + 1; ra.LastColumn = 0; } else { ra.FirstColumn = r.PrevRow.Text.Length; ra.FirstRow = index - 1; ra.LastRow = index; ra.LastColumn = r.Text.Length; } PushUndoBlock(UndoAction.DeleteRange, GetRange(ra), ra.FirstColumn, ra.FirstRow); } rows.RemoveAt(index); if (r.InKeywordQueue) KeywordQueue.Remove(r); if (r.InQueue) ParseQueue.Remove(r); //this.ResetVisibleRows (); OnRowDeleted(r); if (raiseChanged) OnChange(); } /// <summary> /// Deletes a range of text /// </summary> /// <param name="Range">the range that should be deleted</param> public void DeleteRange(TextRange Range) { DeleteRange(Range, true); } private int ParseRows(Row row) { return ParseRows(row, false); } private int ParseRows(Row row, bool Keywords) { if (!Keywords) { int index = IndexOf(row); int count = 0; try { while (row.InQueue && count < 100) { if (index >= 0) { if (index > 0) if (this[index - 1].InQueue) ParseRow(this[index - 1]); Parser.ParseRow(index, false); } int i = ParseQueue.IndexOf(row); if (i >= 0) ParseQueue.RemoveAt(i); row.InQueue = false; index++; count++; row = this[index]; if (row == null) break; } } catch {} return count; } else { int index = IndexOf(row); if (index == -1 || row.InKeywordQueue == false) { KeywordQueue.Remove(row); return 0; } int count = 0; try { while (row.InKeywordQueue && count < 100) { if (index >= 0) { if (index > 0) if (this[index - 1].InQueue) ParseRow(this[index - 1]); Parser.ParseRow(index, true); } index++; count++; row = this[index]; if (row == null) break; } } catch {} return count; } } /// <summary> /// Forces a row to be parsed /// </summary> /// <param name="r">Row to parse</param> /// <param name="ParseKeywords">true if keywords and operators should be parsed</param> public void ParseRow(Row r, bool ParseKeywords) { int index = IndexOf(r); if (index >= 0) { if (index > 0) if (this[index - 1].InQueue) ParseRow(this[index - 1]); Parser.ParseRow(index, false); if (ParseKeywords) Parser.ParseRow(index, true); } int i = ParseQueue.IndexOf(r); if (i >= 0) ParseQueue.RemoveAt(i); r.InQueue = false; } /// <summary> /// Forces a row to be parsed /// </summary> /// <param name="r">Row to parse</param> public void ParseRow(Row r) { ParseRow(r, false); } /// <summary> /// Gets the row index of the next bookmarked row /// </summary> /// <param name="StartIndex">Start index</param> /// <returns>Index of the next bookmarked row</returns> public int GetNextBookmark(int StartIndex) { for (int i = StartIndex + 1; i < Count; i++) { Row r = this[i]; if (r.Bookmarked) return i; } for (int i = 0; i < StartIndex; i++) { Row r = this[i]; if (r.Bookmarked) return i; } return StartIndex; } /// <summary> /// Gets the row index of the previous bookmarked row /// </summary> /// <param name="StartIndex">Start index</param> /// <returns>Index of the previous bookmarked row</returns> public int GetPreviousBookmark(int StartIndex) { for (int i = StartIndex - 1; i >= 0; i--) { Row r = this[i]; if (r.Bookmarked) return i; } for (int i = Count - 1; i >= StartIndex; i--) { Row r = this[i]; if (r.Bookmarked) return i; } return StartIndex; } /// <summary> /// Deletes a range of text /// </summary> /// <param name="Range">Range to delete</param> /// <param name="StoreUndo">true if the actions should be pushed onto the undo stack</param> public void DeleteRange(TextRange Range, bool StoreUndo) { TextRange r = Range; Modified = true; if (StoreUndo) { string deltext = GetRange(Range); PushUndoBlock(UndoAction.DeleteRange, deltext, r.FirstColumn, r.FirstRow); } if (r.FirstRow == r.LastRow) { Row xtr = this[r.FirstRow]; int max = Math.Min(r.FirstColumn, xtr.Text.Length); string left = xtr.Text.Substring(0, max); string right = ""; if (xtr.Text.Length >= r.LastColumn) right = xtr.Text.Substring(r.LastColumn); xtr.Text = left + right; } else { if (r.LastRow > Count - 1) r.LastRow = Count - 1; Row xtr = this[r.FirstRow]; if (r.FirstColumn > xtr.Text.Length) { int diff = r.FirstColumn - xtr.Text.Length; var ws = new string(' ', diff); InsertText(ws, xtr.Text.Length, r.FirstRow, true); //return; } string row1 = xtr.Text.Substring(0, r.FirstColumn); Row xtr2 = this[r.LastRow]; int Max = Math.Min(xtr2.Text.Length, r.LastColumn); string row2 = xtr2.Text.Substring(Max); string tot = row1 + row2; //bool fold=this[r.LastRow].IsCollapsed | this[r.FirstRow].IsCollapsed ; int start = r.FirstRow; int end = r.LastRow; for (int i = end - 1; i >= start; i--) { Remove(i, false, false); } //todo: DeleteRange error //this.Insert ( tot ,r.FirstRow,false); Row row = this[start]; row.Expanded = true; row.Text = tot; row.startSpans.Clear(); row.endSpans.Clear(); row.startSpan = null; row.endSpan = null; row.Parse(); } ResetVisibleRows(); OnChange(); } /// <summary> /// Get a range of text /// </summary> /// <param name="Range">The range to get</param> /// <returns>string containing the text inside the given range</returns> public string GetRange(TextRange Range) { if (Range.FirstRow >= Count) Range.FirstRow = Count; if (Range.LastRow >= Count) Range.LastRow = Count; if (Range.FirstRow != Range.LastRow) { //note:error has been tracked here Row r1 = this[Range.FirstRow]; int mx = Math.Min(r1.Text.Length, Range.FirstColumn); string s1 = r1.Text.Substring(mx) + Environment.NewLine; //if (Range.LastRow >= this.Count) // Range.LastRow=this.Count -1; Row r2 = this[Range.LastRow]; if (r2 == null) return ""; int Max = Math.Min(r2.Text.Length, Range.LastColumn); string s2 = r2.Text.Substring(0, Max); var sb = new StringBuilder(); for (int i = Range.FirstRow + 1; i <= Range.LastRow - 1; i++) { Row r3 = this[i]; sb.Append(r3.Text + Environment.NewLine); } string s3 = sb.ToString(); return s1 + s3 + s2; } else { Row r = this[Range.FirstRow]; int Max = Math.Min(r.Text.Length, Range.LastColumn); int Length = Max - Range.FirstColumn; if (Length <= 0) return ""; string s = r.Text.Substring(Range.FirstColumn, Max - Range.FirstColumn); return s; } } /// <summary> /// Returns the index of a given row /// </summary> /// <param name="xtr">row to find</param> /// <returns>Index of the given row</returns> public int IndexOf(Row xtr) { return rows.IndexOf(xtr); } /// <summary> /// Clear all content in the document /// </summary> public void clear() { foreach (Row r in rows) { OnRowDeleted(r); } rows.Clear(); // this.FormatRanges.Clear (); ParseQueue.Clear(); KeywordQueue.Clear(); UndoBuffer.Clear(); UndoStep = 0; // this.Add (""); // ResetVisibleRows(); // this.OnChange (); } public void Clear() { Text = ""; } /// <summary> /// Inserts a text into the document at a given column,row. /// </summary> /// <param name="text">Text to insert</param> /// <param name="xPos">Column</param> /// <param name="yPos">Row index</param> /// <returns>TextPoint containing the end of the inserted text</returns> public TextPoint InsertText(string text, int xPos, int yPos) { return InsertText(text, xPos, yPos, true); } /// <summary> /// Inserts a text into the document at a given column,row. /// </summary> /// <param name="text">Text to insert</param> /// <param name="xPos">Column</param> /// <param name="yPos">Row index</param> /// <param name="StoreUndo">true if this action should be pushed onto the undo stack</param> /// <returns>TextPoint containing the end of the inserted text</returns> public TextPoint InsertText(string text, int xPos, int yPos, bool StoreUndo) { Modified = true; Row xtr = this[yPos]; if (xPos > xtr.Text.Length) { //virtualwhitespace fix int Padd = xPos - xtr.Text.Length; var PaddStr = new string(' ', Padd); text = PaddStr + text; xPos -= Padd; } string lft = xtr.Text.Substring(0, xPos); string rgt = xtr.Text.Substring(xPos); string NewText = lft + text + rgt; string t = NewText.Replace(Environment.NewLine, "\n"); string[] lines = t.Split('\n'); xtr.Text = lines[0]; Row lastrow = xtr; //this.Parser.ParsePreviewLine(xtr); xtr.Parse(); if (!xtr.InQueue) ParseQueue.Add(xtr); xtr.InQueue = true; int i = IndexOf(xtr); for (int j = 1; j <= lines.GetUpperBound(0); j++) { lastrow = Insert(lines[j], j + i, false); } if (StoreUndo) PushUndoBlock(UndoAction.InsertRange, text, xPos, yPos); ResetVisibleRows(); OnChange(); return new TextPoint(lastrow.Text.Length - rgt.Length, IndexOf(lastrow)); } private void OnModifiedChanged() { if (ModifiedChanged != null) ModifiedChanged(this, new EventArgs()); } private void OnChange() { if (Change != null) Change(this, new EventArgs()); } private void OnRowParsed(Row r) { if (RowParsed != null) RowParsed(this, new RowEventArgs(r)); OnApplyFormatRanges(r); } // private void OnRowAdded(Row r) // { // if (RowAdded != null) // RowAdded(this,new RowEventArgs(r)); // } private void OnRowDeleted(Row r) { if (RowDeleted != null) RowDeleted(this, new RowEventArgs(r)); } public void PushUndoBlock(UndoAction Action, string text, int x, int y) { var undo = new UndoBlock { Action = Action, Text = text }; undo.Position.Y = y; undo.Position.X = x; //AddToUndoList(undo); if (captureMode) { captureBlock.Add(undo); } else { AddToUndoList(undo); } } /// <summary> /// Gets a Range from a given text /// </summary> /// <param name="text"></param> /// <param name="xPos"></param> /// <param name="yPos"></param> /// <returns></returns> public TextRange GetRangeFromText(string text, int xPos, int yPos) { string t = text.Replace(Environment.NewLine, "\n"); string[] lines = t.Split("\n".ToCharArray()); var r = new TextRange { FirstColumn = xPos, FirstRow = yPos, LastRow = (lines.Length - 1 + yPos), LastColumn = lines[lines.Length - 1].Length }; if (r.FirstRow == r.LastRow) r.LastColumn += r.FirstColumn; return r; } public void AddToUndoList(UndoBlock undo) { //store the undo action in a actiongroup var ActionGroup = new UndoBlockCollection {undo}; AddToUndoList(ActionGroup); } /// <summary> /// Add an action to the undo stack /// </summary> /// <param name="ActionGroup">action to add</param> public void AddToUndoList(UndoBlockCollection ActionGroup) { UndoBuffer.ClearFrom(UndoStep); UndoBuffer.Add(ActionGroup); UndoStep++; OnUndoBufferChanged(); } /// <summary> /// Perform an undo action /// </summary> /// <returns>The position where the caret should be placed</returns> public TextPoint Undo() { if (UndoStep == 0) return new TextPoint(-1, -1); UndoBlockCollection ActionGroup = UndoBuffer[UndoStep - 1]; UndoBlock undo = ActionGroup[0]; for (int i = ActionGroup.Count - 1; i >= 0; i--) { undo = ActionGroup[i]; //TextPoint tp=new TextPoint (undo.Position.X,undo.Position.Y); switch (undo.Action) { case UndoAction.DeleteRange: InsertText(undo.Text, undo.Position.X, undo.Position.Y, false); break; case UndoAction.InsertRange: { TextRange r = GetRangeFromText(undo.Text, undo.Position.X, undo.Position.Y); DeleteRange(r, false); } break; default: break; } } UndoStep--; ResetVisibleRows(); //no undo steps left , the document is not dirty if (UndoStep == 0) Modified = false; var tp = new TextPoint(undo.Position.X, undo.Position.Y); OnUndoBufferChanged(); return tp; } public void AutoIndentSegment(Span span) { if (span == null) span = this[0].startSpan; Row start = span.StartRow; Row end = span.EndRow; if (start == null) start = this[0]; if (end == null) end = this[Count - 1]; for (int i = start.Index; i <= end.Index; i++) { Row r = this[i]; int depth = r.Indent; string text = r.Text.Substring(r.GetLeadingWhitespace().Length); var indent = new string('\t', depth); r.Text = indent + text; } ResetVisibleRows(); } //Returns the span object at the given position /// <summary> /// Gets a span object form a given column , Row index /// (This only applies if the row is fully parsed) /// </summary> /// <param name="p">Column and Rowindex</param> /// <returns>span object at the given position</returns> public Span GetSegmentFromPos(TextPoint p) { Row xtr = this[p.Y]; int CharNo = 0; if (xtr.Count == 0) return xtr.startSpan; Span prev = xtr.startSpan; foreach (Word w in xtr) { if (w.Text.Length + CharNo > p.X) { if (CharNo == p.X) return prev; return w.Span; } CharNo += w.Text.Length; prev = w.Span; } return xtr.endSpan; } //the specific word that contains the char in point p /// <summary> /// Gets a Word object form a given column , Row index /// (this only applies if the row is fully parsed) /// </summary> /// <param name="p">Column and Rowindex</param> /// <returns>Word object at the given position</returns> public Word GetWordFromPos(TextPoint p) { Row xtr = this[p.Y]; int CharNo = 0; Word CorrectWord = null; foreach (Word w in xtr) { if (CorrectWord != null) { if (w.Text == "") return w; return CorrectWord; } if (w.Text.Length + CharNo > p.X || w == xtr[xtr.Count - 1]) { //return w; CorrectWord = w; } else { CharNo += w.Text.Length; } } return CorrectWord; } //the specific word that contains the char in point p /// <summary> /// Gets a Word object form a given column , Row index /// (this only applies if the row is fully parsed) /// </summary> /// <param name="p">Column and Rowindex</param> /// <returns>Word object at the given position</returns> public Word GetFormatWordFromPos(TextPoint p) { Row xtr = this[p.Y]; int CharNo = 0; Word CorrectWord = null; foreach (Word w in xtr.FormattedWords) { if (CorrectWord != null) { if (w.Text == "") return w; return CorrectWord; } if (w.Text.Length + CharNo > p.X || w == xtr[xtr.Count - 1]) { //return w; CorrectWord = w; } else { CharNo += w.Text.Length; } } return CorrectWord; } /// <summary> /// Call this method to make the document raise the RowParsed event /// </summary> /// <param name="row"></param> public void InvokeRowParsed(Row row) { OnRowParsed(row); } /// <summary> /// Call this method to recalculate the visible rows /// </summary> public void ResetVisibleRows() { InternalResetVisibleRows(); } private void InternalResetVisibleRows() { // if (System.DateTime.Now > new DateTime (2002,12,31)) // { // // this.rows = new RowList (); // this.Add ("BETA VERSION EXPIRED"); // VisibleRows = this.rows; // return; // } if (!folding) { VisibleRows = rows; NeedResetRows = false; } else { NeedResetRows = false; VisibleRows = new RowList(); //.Clear (); int RealRow = 0; for (int i = 0; i < Count; i++) { Row r = this[RealRow]; VisibleRows.Add(r); bool collapsed = false; if (r.CanFold) if (r.expansion_StartSpan.Expanded == false) { if (r.expansion_StartSpan.EndWord == null) {} else { r = r.Expansion_EndRow; // .expansion_StartSpan.EndRow; collapsed = true; } } if (!collapsed) RealRow++; else RealRow = IndexOf(r) + 1; if (RealRow >= Count) break; } } } /// <summary> /// Converts a Column/Row index position into a char index /// </summary> /// <param name="pos">TextPoint where x is column and y is row index</param> /// <returns>Char index in the document text</returns> public int PointToIntPos(TextPoint pos) { int y = 0; int p = 0; foreach (Row r in this) { if (y == pos.Y) break; p += r.Text.Length + Environment.NewLine.Length; y++; } // Not sure why but if I paste multiple lines // then this causes a crash because pos.Y is greater // than the number of elements available through the [] // operator. int yToUse = Math.Min(this.Count-1, pos.Y); return p + Math.Min(pos.X, this[yToUse].Text.Length); } /// <summary> /// Converts a char index into a Column/Row index /// </summary> /// <param name="pos">Char index to convert</param> /// <returns>Point where x is column and y is row index</returns> public TextPoint IntPosToPoint(int pos) { int p = 0; int y = 0; foreach (Row r in this) { p += r.Text.Length + Environment.NewLine.Length; if (p > pos) { p -= r.Text.Length + Environment.NewLine.Length; int x = pos - p; return new TextPoint(x, y); } y++; } return new TextPoint(-1, -1); } /// <summary> /// Toggle expansion of a given row /// </summary> /// <param name="r"></param> public void ToggleRow(Row r) { if (!folding) return; if (r.Expansion_EndRow == null || r.Expansion_StartRow == null) return; // if (r.IsCollapsed) // { // r.expansion_StartSpan.Expanded = true; // ExpandRow(r); // } // else // { // r.expansion_StartSpan.Expanded = false; // CollapseRow(r); // } if (r.CanFold) r.Expanded = !r.Expanded; ResetVisibleRows(); OnChange(); } /// <summary> /// Perform an redo action /// </summary> /// <returns>The position where the caret should be placed</returns> public TextPoint Redo() { if (UndoStep >= UndoBuffer.Count) return new TextPoint(-1, -1); UndoBlockCollection ActionGroup = UndoBuffer[UndoStep]; UndoBlock undo = ActionGroup[0]; for (int i = 0; i < ActionGroup.Count; i++) { undo = ActionGroup[i]; switch (undo.Action) { case UndoAction.InsertRange: { InsertText(undo.Text, undo.Position.X, undo.Position.Y, false); } break; case UndoAction.DeleteRange: { TextRange r = GetRangeFromText(undo.Text, undo.Position.X, undo.Position.Y); DeleteRange(r, false); } break; default: break; } } TextRange ran = GetRangeFromText(undo.Text, undo.Position.X, undo.Position.Y); UndoStep++; ResetVisibleRows(); OnUndoBufferChanged(); return new TextPoint(ran.LastColumn, ran.LastRow); } public Word GetStartBracketWord(Word Start, Pattern End, Span FindIn) { if (Start == null || Start.Pattern == null || Start.Span == null) return null; int CurrentRow = Start.Row.Index; int FirstRow = FindIn.StartRow.Index; int x = Start.Index; int count = 0; while (CurrentRow >= FirstRow) { for (int i = x; i >= 0; i--) { Word w = this[CurrentRow][i]; if (w.Span == FindIn && w.Type == WordType.Word) { if (w.Pattern == Start.Pattern) count++; if (w.Pattern == End) count--; if (count == 0) return w; } } if (!Start.Pattern.IsMultiLineBracket) break; CurrentRow--; if (CurrentRow >= 0) x = this[CurrentRow].Count - 1; } return null; } public Word GetEndBracketWord(Word Start, Pattern End, Span FindIn) { if (Start == null || Start.Pattern == null || Start.Span == null) return null; int CurrentRow = Start.Row.Index; int LastRow = Count - 1; if (FindIn.EndRow != null) LastRow = FindIn.EndRow.Index; int x = Start.Index; int count = 0; while (CurrentRow <= LastRow) { for (int i = x; i < this[CurrentRow].Count; i++) { Word w = this[CurrentRow][i]; if (w.Span == FindIn && w.Type == WordType.Word) { if (w.Pattern == Start.Pattern) count++; if (w.Pattern == End) count--; if (count == 0) return w; } } if (!Start.Pattern.IsMultiLineBracket) break; CurrentRow++; x = 0; } return null; } /// <summary> /// Sets a syntax file, from an embedded resource. /// </summary> /// <param name="assembly">The assembly which contains the embedded resource.</param> /// <param name="resourceName">The name of the resource.</param> public void SetSyntaxFromEmbeddedResource(Assembly assembly, String resourceName) { if (assembly == null) throw new ArgumentNullException("assembly"); if (string.IsNullOrEmpty(resourceName)) throw new ArgumentNullException("resourceName"); // // Get the xml from an embedded resource. Load the stream. // Stream stream = assembly.GetManifestResourceStream(resourceName); if (stream != null) { stream.Seek(0, SeekOrigin.Begin); // // Read stream. // var reader = new StreamReader(stream); String xml = reader.ReadToEnd(); // // Clean up stream. // stream.Close(); // // Initialize. // Parser.Init(SyntaxDefinition.FromSyntaxXml(xml)); Text = Text; } } public void OnApplyFormatRanges(Row row) { row.FormattedWords = row.words; } } }
using DevExpress.Mvvm.DataAnnotations; using DevExpress.Mvvm.POCO; using DevExpress.Xpf.DXBinding; using NUnit.Framework; using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows; using System.Windows.Data; using System.Windows.Markup; namespace DevExpress.Mvvm.Tests { [TestFixture] public class DXDataTemplateSelectorTests { #region templates static readonly DataTemplate TextBoxTemplate = (DataTemplate)XamlReader.Parse( @"<DataTemplate xmlns=""http://schemas.microsoft.com/winfx/2006/xaml/presentation"" xmlns:x=""http://schemas.microsoft.com/winfx/2006/xaml""> <TextBox/> </DataTemplate>"); static readonly DataTemplate ButtonTemplate = (DataTemplate)XamlReader.Parse( @"<DataTemplate xmlns=""http://schemas.microsoft.com/winfx/2006/xaml/presentation"" xmlns:x=""http://schemas.microsoft.com/winfx/2006/xaml""> <Button/> </DataTemplate>"); static readonly DataTemplate CheckBoxTemplate = (DataTemplate)XamlReader.Parse( @"<DataTemplate xmlns=""http://schemas.microsoft.com/winfx/2006/xaml/presentation"" xmlns:x=""http://schemas.microsoft.com/winfx/2006/xaml""> <CheckBox/> </DataTemplate>"); #endregion public enum TestEnum { One, Two, Three } public class TestData { bool @bool; public int BoolGetCount; [BindableProperty] public virtual bool Bool { get { BoolGetCount++; return @bool; } set { @bool = value; } } public virtual TestEnum Enum { get; set; } public virtual string String { get; set; } } [Test] public void Priority() { var selector = new DXDataTemplateSelector(); selector.Items.Add(new DXDataTemplateTrigger() { Binding = new Binding("Bool"), Value = "True", Template = TextBoxTemplate, }); selector.Items.Add(new DXDataTemplateTrigger() { Binding = new Binding("Enum"), Value = "Two", Template = ButtonTemplate, }); selector.Items.Add(new DXDataTemplateTrigger() { Template = CheckBoxTemplate, }); Assert.AreEqual(TextBoxTemplate, selector.SelectTemplate(new TestData() { Bool = true }, null)); Assert.AreEqual(ButtonTemplate, selector.SelectTemplate(new TestData() { Bool = true, Enum = TestEnum.Two }, null)); Assert.AreEqual(ButtonTemplate, selector.SelectTemplate(new TestData() { Enum = TestEnum.Two }, null)); Assert.AreEqual(CheckBoxTemplate, selector.SelectTemplate(new TestData(), null)); } [Test(Description = "T593922")] public void ThreadSafety() { DXDataTemplateSelector selector = CreateSimpleSelector(); Action checkSelector = () => { Assert.AreEqual(TextBoxTemplate, selector.SelectTemplate(new TestData() { Bool = true }, null)); Assert.AreEqual(CheckBoxTemplate, selector.SelectTemplate(new TestData(), null)); }; checkSelector(); var thread = new Thread(x => checkSelector()); thread.SetApartmentState(ApartmentState.STA); thread.Start(); thread.Join(); Assert.AreEqual(ThreadState.Stopped, thread.ThreadState); } static DXDataTemplateSelector CreateSimpleSelector() { var selector = new DXDataTemplateSelector(); selector.Items.Add(new DXDataTemplateTrigger() { Binding = new Binding("Bool"), Value = "True", Template = TextBoxTemplate, }); selector.Items.Add(new DXDataTemplateTrigger() { Template = CheckBoxTemplate, }); return selector; } [Test, Explicit] public void Performance() { MeasureTime(() => { var selector = CreateSimpleSelector(); selector.SelectTemplate(new TestData() { Bool = true }, null); selector = CreateSimpleSelector(); selector.SelectTemplate(new TestData() { Bool = true }, null); selector = CreateSimpleSelector(); selector.SelectTemplate(new TestData() { Bool = true }, null); }, "warm up"); MeasureTime(() => { var selector = CreateSimpleSelector(); selector.SelectTemplate(new TestData() { Bool = true }, null); }, "once"); MeasureTime(() => { var selector = CreateSimpleSelector(); selector.SelectTemplate(new TestData() { Bool = true }, null); selector.SelectTemplate(new TestData() { Bool = true }, null); }, "twice"); } static void MeasureTime(Action a, string description) { var sw = new System.Diagnostics.Stopwatch(); sw.Start(); a(); System.Diagnostics.Debug.WriteLine(description + ": " + sw.ElapsedTicks); } [Test] public void UnconvertibleStrings() { var selector = new DXDataTemplateSelector(); selector.Items.Add(new DXDataTemplateTrigger() { Binding = new Binding("Bool"), Value = "foo", Template = TextBoxTemplate, }); selector.Items.Add(new DXDataTemplateTrigger() { Binding = new Binding("Enum"), Value = "bar", Template = ButtonTemplate, }); selector.Items.Add(new DXDataTemplateTrigger() { Template = CheckBoxTemplate, }); Assert.AreEqual(CheckBoxTemplate, selector.SelectTemplate(new TestData() { Bool = true }, null)); Assert.AreEqual(CheckBoxTemplate, selector.SelectTemplate(new TestData() { Bool = true, Enum = TestEnum.Two }, null)); Assert.AreEqual(CheckBoxTemplate, selector.SelectTemplate(new TestData() { Enum = TestEnum.Two }, null)); Assert.AreEqual(CheckBoxTemplate, selector.SelectTemplate(new TestData(), null)); } [Test] public void RealValues() { var selector = new DXDataTemplateSelector(); selector.Items.Add(new DXDataTemplateTrigger() { Binding = new Binding("Bool"), Value = true, Template = TextBoxTemplate, }); selector.Items.Add(new DXDataTemplateTrigger() { Binding = new Binding("Enum"), Value = TestEnum.Two, Template = ButtonTemplate, }); selector.Items.Add(new DXDataTemplateTrigger() { Template = CheckBoxTemplate, }); Assert.AreEqual(TextBoxTemplate, selector.SelectTemplate(new TestData() { Bool = true }, null)); Assert.AreEqual(ButtonTemplate, selector.SelectTemplate(new TestData() { Bool = true, Enum = TestEnum.Two }, null)); Assert.AreEqual(ButtonTemplate, selector.SelectTemplate(new TestData() { Enum = TestEnum.Two }, null)); Assert.AreEqual(CheckBoxTemplate, selector.SelectTemplate(new TestData(), null)); } [Test] public void UseLastTrigger() { var selector = new DXDataTemplateSelector(); selector.Items.Add(new DXDataTemplateTrigger() { Binding = new Binding("Bool"), Value = "True", Template = TextBoxTemplate, }); selector.Items.Add(new DXDataTemplateTrigger() { Binding = new Binding("Bool"), Value = "True", Template = CheckBoxTemplate, }); Assert.AreEqual(CheckBoxTemplate, selector.SelectTemplate(new TestData() { Bool = true }, null)); Assert.AreEqual(null, selector.SelectTemplate(new TestData(), null)); } [Test] public void DefaultTemplateFirst() { var selector = new DXDataTemplateSelector(); selector.Items.Add(new DXDataTemplateTrigger() { Template = CheckBoxTemplate, }); selector.Items.Add(new DXDataTemplateTrigger() { Binding = new Binding("Bool"), Value = "True", Template = TextBoxTemplate, }); Assert.AreEqual(TextBoxTemplate, selector.SelectTemplate(new TestData() { Bool = true }, null)); Assert.AreEqual(CheckBoxTemplate, selector.SelectTemplate(new TestData(), null)); } [Test] public void DefaultTemplateFirst_UseLastDefaultTemplate() { var selector = new DXDataTemplateSelector(); selector.Items.Add(new DXDataTemplateTrigger() { Template = CheckBoxTemplate, }); selector.Items.Add(new DXDataTemplateTrigger() { Template = TextBoxTemplate, }); Assert.AreEqual(TextBoxTemplate, selector.SelectTemplate(new TestData(), null)); } [Test] public void DoNotListenINPCNotifications() { var selector = new DXDataTemplateSelector(); selector.Items.Add(new DXDataTemplateTrigger() { Binding = new Binding("Bool"), Value = "True", Template = TextBoxTemplate, }); var data = ViewModelSource.Create<TestData>(); data.Bool = true; Assert.AreEqual(1, data.BoolGetCount); Assert.AreEqual(TextBoxTemplate, selector.SelectTemplate(data, null)); Assert.AreEqual(2, data.BoolGetCount); data.Bool = false; DispatcherHelper.DoEvents(); Assert.AreEqual(3, data.BoolGetCount); Assert.AreEqual(null, selector.SelectTemplate(data, null)); Assert.AreEqual(4, data.BoolGetCount); } [Test] public void NullValue() { var selector = new DXDataTemplateSelector(); selector.Items.Add(new DXDataTemplateTrigger() { Binding = new Binding("Bool"), Template = TextBoxTemplate, }); selector.Items.Add(new DXDataTemplateTrigger() { Binding = new Binding("String"), Template = CheckBoxTemplate, }); Assert.AreEqual(CheckBoxTemplate, selector.SelectTemplate(new TestData(), null)); Assert.AreEqual(null, selector.SelectTemplate(new TestData() { String = "" }, null)); } [Test] public void NullBinding() { var selector = new DXDataTemplateSelector(); selector.Items.Add(new DXDataTemplateTrigger() { Value = "True", Template = TextBoxTemplate, }); Assert.AreEqual(TextBoxTemplate, selector.SelectTemplate(new TestData() { String = "" }, null)); } [Test] public void Freeze() { var selector = new DXDataTemplateSelector(); selector.Items.Add(new DXDataTemplateTrigger() { Binding = new Binding("Bool"), Value = "True", Template = TextBoxTemplate, }); Assert.AreEqual(TextBoxTemplate, selector.SelectTemplate(new TestData() { Bool = true }, null)); Assert.Throws<InvalidOperationException>(() => selector.Items.Add(new DXDataTemplateTrigger())); Assert.Throws<InvalidOperationException>(() => selector.Items[0].Value = null); Assert.Throws<InvalidOperationException>(() => selector.Items[0].Binding = null); Assert.Throws<InvalidOperationException>(() => selector.Items[0].Template = null); } [Test] public void DontFreezeInDesignTime() { var selector = new DXDataTemplateSelector(); DesignerProperties.SetIsInDesignMode(selector.Items, true); selector.Items.Add(new DXDataTemplateTrigger() { Template = TextBoxTemplate }); Assert.AreEqual(TextBoxTemplate, selector.SelectTemplate(new TestData(), null)); Assert.IsFalse(selector.Items.IsFrozen); selector.Items.Add(new DXDataTemplateTrigger()); } } }
namespace SubSonic.SubStage { partial class SubStageForm { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if(activeServer != null) { activeServer.Stop(); } if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(SubStageForm)); this.pGrid = new PropertyGridEx.PropertyGridEx(); this.pgbTestConnection = new System.Windows.Forms.ToolStripButton(); this.menuStrip1 = new System.Windows.Forms.MenuStrip(); this.fileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.miFileImportProject = new System.Windows.Forms.ToolStripMenuItem(); this.miFileExit = new System.Windows.Forms.ToolStripMenuItem(); this.editToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.helpToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.miHelpAbout = new System.Windows.Forms.ToolStripMenuItem(); this.kryptonManager1 = new ComponentFactory.Krypton.Toolkit.KryptonManager(this.components); this.statusStrip1 = new System.Windows.Forms.StatusStrip(); this.tsStatus = new System.Windows.Forms.ToolStripStatusLabel(); this.toolStrip1 = new System.Windows.Forms.ToolStrip(); this.btnNewProject = new System.Windows.Forms.ToolStripButton(); this.btnNewProvider = new System.Windows.Forms.ToolStripButton(); this.btnAddConnectionString = new System.Windows.Forms.ToolStripButton(); this.btnSplitGenerateCode = new System.Windows.Forms.ToolStripSplitButton(); this.miScriptSchemas = new System.Windows.Forms.ToolStripMenuItem(); this.miScriptData = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator3 = new System.Windows.Forms.ToolStripSeparator(); this.miGenerateCSharp = new System.Windows.Forms.ToolStripMenuItem(); this.miGenerateVB = new System.Windows.Forms.ToolStripMenuItem(); this.btnDDNodeView = new System.Windows.Forms.ToolStripDropDownButton(); this.miUseGeneratedNames = new System.Windows.Forms.ToolStripMenuItem(); this.miUseDatabaseNames = new System.Windows.Forms.ToolStripMenuItem(); this.btnInvokeProviders = new System.Windows.Forms.ToolStripButton(); this.kryptonSplitContainer1 = new ComponentFactory.Krypton.Toolkit.KryptonSplitContainer(); this.treeView1 = new System.Windows.Forms.TreeView(); this.ilNodes = new System.Windows.Forms.ImageList(this.components); this.kryptonSplitContainer2 = new ComponentFactory.Krypton.Toolkit.KryptonSplitContainer(); this.tabMaster = new System.Windows.Forms.TabControl(); this.tabMasterProperties = new System.Windows.Forms.TabPage(); this.tabMasterScaffolds = new System.Windows.Forms.TabPage(); this.webScaffolds = new System.Windows.Forms.WebBrowser(); this.tabMasterAPIReference = new System.Windows.Forms.TabPage(); this.webBrowser1 = new System.Windows.Forms.WebBrowser(); this.tabMasterForums = new System.Windows.Forms.TabPage(); this.webBrowser2 = new System.Windows.Forms.WebBrowser(); this.tabMasterWorkItems = new System.Windows.Forms.TabPage(); this.webBrowser3 = new System.Windows.Forms.WebBrowser(); this.ilTabs = new System.Windows.Forms.ImageList(this.components); this.tabDetail = new System.Windows.Forms.TabControl(); this.tabDetailLog = new System.Windows.Forms.TabPage(); this.tbxLog = new ComponentFactory.Krypton.Toolkit.KryptonRichTextBox(); this.tsEventLog = new System.Windows.Forms.ToolStrip(); this.btnClearLog = new System.Windows.Forms.ToolStripButton(); this.tabDetailConfigOutput = new System.Windows.Forms.TabPage(); this.tbxConfigOutput = new ComponentFactory.Krypton.Toolkit.KryptonRichTextBox(); this.tsConfigFile = new System.Windows.Forms.ToolStrip(); this.btnCopyConfig = new System.Windows.Forms.ToolStripButton(); this.tabDetailFileBrowser = new System.Windows.Forms.TabPage(); this.splitContainer1 = new System.Windows.Forms.SplitContainer(); this.treeFileSystem = new System.Windows.Forms.TreeView(); this.fileBrowser = new System.Windows.Forms.WebBrowser(); this.cmTree = new System.Windows.Forms.ContextMenuStrip(this.components); this.cmiTreeDeleteProject = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator(); this.cmiTreeAddProvider = new System.Windows.Forms.ToolStripMenuItem(); this.cmiTreeDeleteProvider = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator2 = new System.Windows.Forms.ToolStripSeparator(); this.cmiTreeAddConnectionString = new System.Windows.Forms.ToolStripMenuItem(); this.cmiTreeDeleteConnectionString = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem1 = new System.Windows.Forms.ToolStripSeparator(); this.cmiGenerateObjectEnabled = new System.Windows.Forms.ToolStripMenuItem(); this.folderBrowserDialog1 = new System.Windows.Forms.FolderBrowserDialog(); this.menuStrip1.SuspendLayout(); this.statusStrip1.SuspendLayout(); this.toolStrip1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.kryptonSplitContainer1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.kryptonSplitContainer1.Panel1)).BeginInit(); this.kryptonSplitContainer1.Panel1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.kryptonSplitContainer1.Panel2)).BeginInit(); this.kryptonSplitContainer1.Panel2.SuspendLayout(); this.kryptonSplitContainer1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.kryptonSplitContainer2)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.kryptonSplitContainer2.Panel1)).BeginInit(); this.kryptonSplitContainer2.Panel1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.kryptonSplitContainer2.Panel2)).BeginInit(); this.kryptonSplitContainer2.Panel2.SuspendLayout(); this.kryptonSplitContainer2.SuspendLayout(); this.tabMaster.SuspendLayout(); this.tabMasterProperties.SuspendLayout(); this.tabMasterScaffolds.SuspendLayout(); this.tabMasterAPIReference.SuspendLayout(); this.tabMasterForums.SuspendLayout(); this.tabMasterWorkItems.SuspendLayout(); this.tabDetail.SuspendLayout(); this.tabDetailLog.SuspendLayout(); this.tsEventLog.SuspendLayout(); this.tabDetailConfigOutput.SuspendLayout(); this.tsConfigFile.SuspendLayout(); this.tabDetailFileBrowser.SuspendLayout(); this.splitContainer1.Panel1.SuspendLayout(); this.splitContainer1.Panel2.SuspendLayout(); this.splitContainer1.SuspendLayout(); this.cmTree.SuspendLayout(); this.SuspendLayout(); // // pGrid // // // // this.pGrid.DocCommentDescription.AutoEllipsis = true; this.pGrid.DocCommentDescription.Cursor = System.Windows.Forms.Cursors.Default; this.pGrid.DocCommentDescription.Location = new System.Drawing.Point(3, 18); this.pGrid.DocCommentDescription.Name = ""; this.pGrid.DocCommentDescription.Size = new System.Drawing.Size(617, 37); this.pGrid.DocCommentDescription.TabIndex = 1; this.pGrid.DocCommentImage = null; // // // this.pGrid.DocCommentTitle.Cursor = System.Windows.Forms.Cursors.Default; this.pGrid.DocCommentTitle.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold); this.pGrid.DocCommentTitle.Location = new System.Drawing.Point(3, 3); this.pGrid.DocCommentTitle.Name = ""; this.pGrid.DocCommentTitle.Size = new System.Drawing.Size(617, 15); this.pGrid.DocCommentTitle.TabIndex = 0; this.pGrid.DocCommentTitle.UseMnemonic = false; this.pGrid.Dock = System.Windows.Forms.DockStyle.Fill; this.pGrid.Location = new System.Drawing.Point(0, 0); this.pGrid.Margin = new System.Windows.Forms.Padding(0); this.pGrid.Name = "pGrid"; this.pGrid.Size = new System.Drawing.Size(623, 263); this.pGrid.TabIndex = 0; // // // this.pGrid.ToolStrip.AccessibleName = "ToolBar"; this.pGrid.ToolStrip.AccessibleRole = System.Windows.Forms.AccessibleRole.ToolBar; this.pGrid.ToolStrip.AllowMerge = false; this.pGrid.ToolStrip.AutoSize = false; this.pGrid.ToolStrip.CanOverflow = false; this.pGrid.ToolStrip.Dock = System.Windows.Forms.DockStyle.None; this.pGrid.ToolStrip.Font = new System.Drawing.Font("Segoe UI", 9F); this.pGrid.ToolStrip.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden; this.pGrid.ToolStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.pgbTestConnection}); this.pGrid.ToolStrip.Location = new System.Drawing.Point(0, 1); this.pGrid.ToolStrip.Name = ""; this.pGrid.ToolStrip.Padding = new System.Windows.Forms.Padding(2, 0, 1, 0); this.pGrid.ToolStrip.Size = new System.Drawing.Size(623, 25); this.pGrid.ToolStrip.TabIndex = 1; this.pGrid.ToolStrip.TabStop = true; this.pGrid.ToolStrip.Text = "PropertyGridToolBar"; this.pGrid.ToolStrip.ItemClicked += new System.Windows.Forms.ToolStripItemClickedEventHandler(this.pGrid_ToolStrip_ItemClicked); this.pGrid.PropertyValueChanged += new System.Windows.Forms.PropertyValueChangedEventHandler(this.propertyGridEx1_PropertyValueChanged); // // pgbTestConnection // this.pgbTestConnection.Image = ((System.Drawing.Image)(resources.GetObject("pgbTestConnection.Image"))); this.pgbTestConnection.ImageTransparentColor = System.Drawing.Color.Magenta; this.pgbTestConnection.Name = "pgbTestConnection"; this.pgbTestConnection.Size = new System.Drawing.Size(114, 22); this.pgbTestConnection.Text = "Test Connection"; // // menuStrip1 // this.menuStrip1.Font = new System.Drawing.Font("Segoe UI", 9F); this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.fileToolStripMenuItem, this.editToolStripMenuItem, this.helpToolStripMenuItem}); this.menuStrip1.Location = new System.Drawing.Point(0, 0); this.menuStrip1.Name = "menuStrip1"; this.menuStrip1.Size = new System.Drawing.Size(816, 24); this.menuStrip1.TabIndex = 0; this.menuStrip1.Text = "menuStrip1"; // // fileToolStripMenuItem // this.fileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.miFileImportProject, this.miFileExit}); this.fileToolStripMenuItem.Name = "fileToolStripMenuItem"; this.fileToolStripMenuItem.Size = new System.Drawing.Size(37, 20); this.fileToolStripMenuItem.Text = "File"; // // miFileImportProject // this.miFileImportProject.Name = "miFileImportProject"; this.miFileImportProject.Size = new System.Drawing.Size(159, 22); this.miFileImportProject.Text = "Import Project..."; this.miFileImportProject.Click += new System.EventHandler(this.miFileImportProject_Click); // // miFileExit // this.miFileExit.Name = "miFileExit"; this.miFileExit.Size = new System.Drawing.Size(159, 22); this.miFileExit.Text = "E&xit"; this.miFileExit.Click += new System.EventHandler(this.miFileExit_Click); // // editToolStripMenuItem // this.editToolStripMenuItem.Name = "editToolStripMenuItem"; this.editToolStripMenuItem.Size = new System.Drawing.Size(39, 20); this.editToolStripMenuItem.Text = "Edit"; // // helpToolStripMenuItem // this.helpToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.miHelpAbout}); this.helpToolStripMenuItem.Name = "helpToolStripMenuItem"; this.helpToolStripMenuItem.Size = new System.Drawing.Size(44, 20); this.helpToolStripMenuItem.Text = "Help"; // // miHelpAbout // this.miHelpAbout.Name = "miHelpAbout"; this.miHelpAbout.Size = new System.Drawing.Size(159, 22); this.miHelpAbout.Text = "&About SubStage"; this.miHelpAbout.Click += new System.EventHandler(this.miHelpAbout_Click); // // kryptonManager1 // this.kryptonManager1.GlobalPaletteMode = ComponentFactory.Krypton.Toolkit.PaletteModeManager.Office2007Black; // // statusStrip1 // this.statusStrip1.Font = new System.Drawing.Font("Segoe UI", 9F); this.statusStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.tsStatus}); this.statusStrip1.Location = new System.Drawing.Point(0, 513); this.statusStrip1.Name = "statusStrip1"; this.statusStrip1.RenderMode = System.Windows.Forms.ToolStripRenderMode.ManagerRenderMode; this.statusStrip1.Size = new System.Drawing.Size(816, 22); this.statusStrip1.SizingGrip = false; this.statusStrip1.Stretch = false; this.statusStrip1.TabIndex = 1; this.statusStrip1.Text = "statusStrip1"; // // tsStatus // this.tsStatus.Name = "tsStatus"; this.tsStatus.Size = new System.Drawing.Size(801, 17); this.tsStatus.Spring = true; this.tsStatus.Text = "Ready"; this.tsStatus.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // toolStrip1 // this.toolStrip1.Font = new System.Drawing.Font("Segoe UI", 9F); this.toolStrip1.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden; this.toolStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.btnNewProject, this.btnNewProvider, this.btnAddConnectionString, this.btnSplitGenerateCode, this.btnDDNodeView, this.btnInvokeProviders}); this.toolStrip1.Location = new System.Drawing.Point(0, 0); this.toolStrip1.Name = "toolStrip1"; this.toolStrip1.Size = new System.Drawing.Size(180, 25); this.toolStrip1.TabIndex = 2; this.toolStrip1.Text = "toolStrip1"; // // btnNewProject // this.btnNewProject.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.btnNewProject.Image = ((System.Drawing.Image)(resources.GetObject("btnNewProject.Image"))); this.btnNewProject.ImageTransparentColor = System.Drawing.Color.Magenta; this.btnNewProject.Name = "btnNewProject"; this.btnNewProject.Size = new System.Drawing.Size(23, 22); this.btnNewProject.Text = "New Project"; this.btnNewProject.Click += new System.EventHandler(this.btnNewProject_Click); // // btnNewProvider // this.btnNewProvider.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.btnNewProvider.Enabled = false; this.btnNewProvider.Image = ((System.Drawing.Image)(resources.GetObject("btnNewProvider.Image"))); this.btnNewProvider.ImageTransparentColor = System.Drawing.Color.Magenta; this.btnNewProvider.Name = "btnNewProvider"; this.btnNewProvider.Size = new System.Drawing.Size(23, 22); this.btnNewProvider.Text = "New Provider"; this.btnNewProvider.Click += new System.EventHandler(this.btnNewProvider_Click); // // btnAddConnectionString // this.btnAddConnectionString.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.btnAddConnectionString.Enabled = false; this.btnAddConnectionString.Image = ((System.Drawing.Image)(resources.GetObject("btnAddConnectionString.Image"))); this.btnAddConnectionString.ImageTransparentColor = System.Drawing.Color.Magenta; this.btnAddConnectionString.Name = "btnAddConnectionString"; this.btnAddConnectionString.Size = new System.Drawing.Size(23, 22); this.btnAddConnectionString.Text = "New Connection String"; this.btnAddConnectionString.Click += new System.EventHandler(this.btnAddConnectionString_Click); // // btnSplitGenerateCode // this.btnSplitGenerateCode.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.btnSplitGenerateCode.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.miScriptSchemas, this.miScriptData, this.toolStripSeparator3, this.miGenerateCSharp, this.miGenerateVB}); this.btnSplitGenerateCode.Image = ((System.Drawing.Image)(resources.GetObject("btnSplitGenerateCode.Image"))); this.btnSplitGenerateCode.ImageTransparentColor = System.Drawing.Color.Magenta; this.btnSplitGenerateCode.Name = "btnSplitGenerateCode"; this.btnSplitGenerateCode.Size = new System.Drawing.Size(32, 22); this.btnSplitGenerateCode.Text = "Generate Code"; this.btnSplitGenerateCode.Click += new System.EventHandler(this.btnSplitGenerateCode_Click); this.btnSplitGenerateCode.DropDownItemClicked += new System.Windows.Forms.ToolStripItemClickedEventHandler(this.btnSplitGenerateCode_DropDownItemClicked); // // miScriptSchemas // this.miScriptSchemas.CheckOnClick = true; this.miScriptSchemas.Name = "miScriptSchemas"; this.miScriptSchemas.Size = new System.Drawing.Size(191, 22); this.miScriptSchemas.Text = "Script Schemas"; // // miScriptData // this.miScriptData.CheckOnClick = true; this.miScriptData.Name = "miScriptData"; this.miScriptData.Size = new System.Drawing.Size(191, 22); this.miScriptData.Text = "Script Data"; // // toolStripSeparator3 // this.toolStripSeparator3.Name = "toolStripSeparator3"; this.toolStripSeparator3.Size = new System.Drawing.Size(188, 6); // // miGenerateCSharp // this.miGenerateCSharp.Checked = true; this.miGenerateCSharp.CheckState = System.Windows.Forms.CheckState.Checked; this.miGenerateCSharp.Name = "miGenerateCSharp"; this.miGenerateCSharp.Size = new System.Drawing.Size(191, 22); this.miGenerateCSharp.Text = "Generate C# Code"; // // miGenerateVB // this.miGenerateVB.Name = "miGenerateVB"; this.miGenerateVB.Size = new System.Drawing.Size(191, 22); this.miGenerateVB.Text = "Generate VB.Net Code"; // // btnDDNodeView // this.btnDDNodeView.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.btnDDNodeView.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.miUseGeneratedNames, this.miUseDatabaseNames}); this.btnDDNodeView.Image = ((System.Drawing.Image)(resources.GetObject("btnDDNodeView.Image"))); this.btnDDNodeView.ImageTransparentColor = System.Drawing.Color.Magenta; this.btnDDNodeView.Name = "btnDDNodeView"; this.btnDDNodeView.Size = new System.Drawing.Size(29, 22); this.btnDDNodeView.Text = "Node View"; // // miUseGeneratedNames // this.miUseGeneratedNames.Checked = true; this.miUseGeneratedNames.CheckOnClick = true; this.miUseGeneratedNames.CheckState = System.Windows.Forms.CheckState.Checked; this.miUseGeneratedNames.Name = "miUseGeneratedNames"; this.miUseGeneratedNames.Size = new System.Drawing.Size(190, 22); this.miUseGeneratedNames.Text = "Use Generated Names"; this.miUseGeneratedNames.Click += new System.EventHandler(this.miUseGeneratedNames_Click); // // miUseDatabaseNames // this.miUseDatabaseNames.CheckOnClick = true; this.miUseDatabaseNames.Name = "miUseDatabaseNames"; this.miUseDatabaseNames.Size = new System.Drawing.Size(190, 22); this.miUseDatabaseNames.Text = "Use Database Names"; this.miUseDatabaseNames.Click += new System.EventHandler(this.miUseDatabaseNames_Click); // // btnInvokeProviders // this.btnInvokeProviders.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.btnInvokeProviders.Enabled = false; this.btnInvokeProviders.Image = ((System.Drawing.Image)(resources.GetObject("btnInvokeProviders.Image"))); this.btnInvokeProviders.ImageTransparentColor = System.Drawing.Color.Magenta; this.btnInvokeProviders.Name = "btnInvokeProviders"; this.btnInvokeProviders.Size = new System.Drawing.Size(23, 22); this.btnInvokeProviders.Text = "Invoke Providers"; this.btnInvokeProviders.Click += new System.EventHandler(this.btnInvokeProviders_Click); // // kryptonSplitContainer1 // this.kryptonSplitContainer1.Cursor = System.Windows.Forms.Cursors.Default; this.kryptonSplitContainer1.Dock = System.Windows.Forms.DockStyle.Fill; this.kryptonSplitContainer1.Location = new System.Drawing.Point(0, 24); this.kryptonSplitContainer1.Name = "kryptonSplitContainer1"; // // kryptonSplitContainer1.Panel1 // this.kryptonSplitContainer1.Panel1.Controls.Add(this.treeView1); this.kryptonSplitContainer1.Panel1.Controls.Add(this.toolStrip1); // // kryptonSplitContainer1.Panel2 // this.kryptonSplitContainer1.Panel2.Controls.Add(this.kryptonSplitContainer2); this.kryptonSplitContainer1.Size = new System.Drawing.Size(816, 489); this.kryptonSplitContainer1.SplitterDistance = 180; this.kryptonSplitContainer1.TabIndex = 3; // // treeView1 // this.treeView1.BackColor = System.Drawing.SystemColors.Control; this.treeView1.BorderStyle = System.Windows.Forms.BorderStyle.None; this.treeView1.Dock = System.Windows.Forms.DockStyle.Fill; this.treeView1.HideSelection = false; this.treeView1.HotTracking = true; this.treeView1.ImageKey = "box.png"; this.treeView1.ImageList = this.ilNodes; this.treeView1.Indent = 10; this.treeView1.LineColor = System.Drawing.Color.DarkGray; this.treeView1.Location = new System.Drawing.Point(0, 25); this.treeView1.Name = "treeView1"; this.treeView1.SelectedImageIndex = 0; this.treeView1.ShowNodeToolTips = true; this.treeView1.Size = new System.Drawing.Size(180, 464); this.treeView1.StateImageList = this.ilNodes; this.treeView1.TabIndex = 0; this.treeView1.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.treeView1_AfterSelect); this.treeView1.MouseDown += new System.Windows.Forms.MouseEventHandler(this.treeView1_MouseDown); // // ilNodes // this.ilNodes.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("ilNodes.ImageStream"))); this.ilNodes.TransparentColor = System.Drawing.Color.Transparent; this.ilNodes.Images.SetKeyName(0, "package.png"); this.ilNodes.Images.SetKeyName(1, "database.png"); this.ilNodes.Images.SetKeyName(2, "folder.png"); this.ilNodes.Images.SetKeyName(3, "table.png"); this.ilNodes.Images.SetKeyName(4, "database_table.png"); this.ilNodes.Images.SetKeyName(5, "database_gear.png"); this.ilNodes.Images.SetKeyName(6, "folder_link.png"); this.ilNodes.Images.SetKeyName(7, "link.png"); this.ilNodes.Images.SetKeyName(8, "textfield.png"); this.ilNodes.Images.SetKeyName(9, "textfield_key.png"); this.ilNodes.Images.SetKeyName(10, "table_error.png"); this.ilNodes.Images.SetKeyName(11, "script_gear.png"); this.ilNodes.Images.SetKeyName(12, "table_delete.png"); this.ilNodes.Images.SetKeyName(13, "drive.png"); this.ilNodes.Images.SetKeyName(14, "brick.png"); // // kryptonSplitContainer2 // this.kryptonSplitContainer2.Cursor = System.Windows.Forms.Cursors.Default; this.kryptonSplitContainer2.Dock = System.Windows.Forms.DockStyle.Fill; this.kryptonSplitContainer2.Location = new System.Drawing.Point(0, 0); this.kryptonSplitContainer2.Margin = new System.Windows.Forms.Padding(0); this.kryptonSplitContainer2.Name = "kryptonSplitContainer2"; this.kryptonSplitContainer2.Orientation = System.Windows.Forms.Orientation.Horizontal; // // kryptonSplitContainer2.Panel1 // this.kryptonSplitContainer2.Panel1.Controls.Add(this.tabMaster); // // kryptonSplitContainer2.Panel2 // this.kryptonSplitContainer2.Panel2.Controls.Add(this.tabDetail); this.kryptonSplitContainer2.Size = new System.Drawing.Size(631, 489); this.kryptonSplitContainer2.SplitterDistance = 290; this.kryptonSplitContainer2.TabIndex = 0; // // tabMaster // this.tabMaster.Controls.Add(this.tabMasterProperties); this.tabMaster.Controls.Add(this.tabMasterScaffolds); this.tabMaster.Controls.Add(this.tabMasterAPIReference); this.tabMaster.Controls.Add(this.tabMasterForums); this.tabMaster.Controls.Add(this.tabMasterWorkItems); this.tabMaster.Dock = System.Windows.Forms.DockStyle.Fill; this.tabMaster.ImageList = this.ilTabs; this.tabMaster.ItemSize = new System.Drawing.Size(81, 19); this.tabMaster.Location = new System.Drawing.Point(0, 0); this.tabMaster.Margin = new System.Windows.Forms.Padding(0); this.tabMaster.Name = "tabMaster"; this.tabMaster.SelectedIndex = 0; this.tabMaster.Size = new System.Drawing.Size(631, 290); this.tabMaster.TabIndex = 0; this.tabMaster.SelectedIndexChanged += new System.EventHandler(this.tabMaster_SelectedIndexChanged); // // tabMasterProperties // this.tabMasterProperties.Controls.Add(this.pGrid); this.tabMasterProperties.ImageKey = "application_side_list.png"; this.tabMasterProperties.Location = new System.Drawing.Point(4, 23); this.tabMasterProperties.Name = "tabMasterProperties"; this.tabMasterProperties.Size = new System.Drawing.Size(623, 263); this.tabMasterProperties.TabIndex = 0; this.tabMasterProperties.Text = "Properties"; this.tabMasterProperties.UseVisualStyleBackColor = true; // // tabMasterScaffolds // this.tabMasterScaffolds.Controls.Add(this.webScaffolds); this.tabMasterScaffolds.ImageIndex = 8; this.tabMasterScaffolds.Location = new System.Drawing.Point(4, 23); this.tabMasterScaffolds.Name = "tabMasterScaffolds"; this.tabMasterScaffolds.Size = new System.Drawing.Size(623, 263); this.tabMasterScaffolds.TabIndex = 4; this.tabMasterScaffolds.Text = "Scaffolds"; this.tabMasterScaffolds.UseVisualStyleBackColor = true; // // webScaffolds // this.webScaffolds.Dock = System.Windows.Forms.DockStyle.Fill; this.webScaffolds.Location = new System.Drawing.Point(0, 0); this.webScaffolds.MinimumSize = new System.Drawing.Size(20, 20); this.webScaffolds.Name = "webScaffolds"; this.webScaffolds.Size = new System.Drawing.Size(623, 263); this.webScaffolds.TabIndex = 0; // // tabMasterAPIReference // this.tabMasterAPIReference.Controls.Add(this.webBrowser1); this.tabMasterAPIReference.ImageKey = "book_addresses.png"; this.tabMasterAPIReference.Location = new System.Drawing.Point(4, 23); this.tabMasterAPIReference.Name = "tabMasterAPIReference"; this.tabMasterAPIReference.Size = new System.Drawing.Size(623, 263); this.tabMasterAPIReference.TabIndex = 1; this.tabMasterAPIReference.Text = "API Reference"; this.tabMasterAPIReference.UseVisualStyleBackColor = true; // // webBrowser1 // this.webBrowser1.Dock = System.Windows.Forms.DockStyle.Fill; this.webBrowser1.Location = new System.Drawing.Point(0, 0); this.webBrowser1.MinimumSize = new System.Drawing.Size(20, 20); this.webBrowser1.Name = "webBrowser1"; this.webBrowser1.ScriptErrorsSuppressed = true; this.webBrowser1.Size = new System.Drawing.Size(623, 263); this.webBrowser1.TabIndex = 0; this.webBrowser1.Url = new System.Uri("http://subsonichelp.com/", System.UriKind.Absolute); // // tabMasterForums // this.tabMasterForums.Controls.Add(this.webBrowser2); this.tabMasterForums.ImageIndex = 2; this.tabMasterForums.Location = new System.Drawing.Point(4, 23); this.tabMasterForums.Name = "tabMasterForums"; this.tabMasterForums.Size = new System.Drawing.Size(623, 263); this.tabMasterForums.TabIndex = 2; this.tabMasterForums.Text = "Forums"; this.tabMasterForums.UseVisualStyleBackColor = true; // // webBrowser2 // this.webBrowser2.Dock = System.Windows.Forms.DockStyle.Fill; this.webBrowser2.Location = new System.Drawing.Point(0, 0); this.webBrowser2.MinimumSize = new System.Drawing.Size(20, 20); this.webBrowser2.Name = "webBrowser2"; this.webBrowser2.ScriptErrorsSuppressed = true; this.webBrowser2.Size = new System.Drawing.Size(623, 263); this.webBrowser2.TabIndex = 1; this.webBrowser2.Url = new System.Uri("http://forums.subsonicproject.com/forums/TopicsActive.aspx", System.UriKind.Absolute); // // tabMasterWorkItems // this.tabMasterWorkItems.Controls.Add(this.webBrowser3); this.tabMasterWorkItems.ImageIndex = 3; this.tabMasterWorkItems.Location = new System.Drawing.Point(4, 23); this.tabMasterWorkItems.Margin = new System.Windows.Forms.Padding(0); this.tabMasterWorkItems.Name = "tabMasterWorkItems"; this.tabMasterWorkItems.Size = new System.Drawing.Size(623, 263); this.tabMasterWorkItems.TabIndex = 3; this.tabMasterWorkItems.Text = "Work Items"; this.tabMasterWorkItems.UseVisualStyleBackColor = true; // // webBrowser3 // this.webBrowser3.Dock = System.Windows.Forms.DockStyle.Fill; this.webBrowser3.Location = new System.Drawing.Point(0, 0); this.webBrowser3.MinimumSize = new System.Drawing.Size(20, 20); this.webBrowser3.Name = "webBrowser3"; this.webBrowser3.ScriptErrorsSuppressed = true; this.webBrowser3.Size = new System.Drawing.Size(623, 263); this.webBrowser3.TabIndex = 1; this.webBrowser3.Url = new System.Uri("http://www.codeplex.com/subsonic/WorkItem/List.aspx", System.UriKind.Absolute); // // ilTabs // this.ilTabs.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("ilTabs.ImageStream"))); this.ilTabs.TransparentColor = System.Drawing.Color.Transparent; this.ilTabs.Images.SetKeyName(0, "application_side_list.png"); this.ilTabs.Images.SetKeyName(1, "book_addresses.png"); this.ilTabs.Images.SetKeyName(2, "group.png"); this.ilTabs.Images.SetKeyName(3, "bug.png"); this.ilTabs.Images.SetKeyName(4, "script_gear.png"); this.ilTabs.Images.SetKeyName(5, "page_white_visualstudio.png"); this.ilTabs.Images.SetKeyName(6, "page.png"); this.ilTabs.Images.SetKeyName(7, "page_white_delete.png"); this.ilTabs.Images.SetKeyName(8, "application_form_edit.png"); // // tabDetail // this.tabDetail.Alignment = System.Windows.Forms.TabAlignment.Bottom; this.tabDetail.Controls.Add(this.tabDetailLog); this.tabDetail.Controls.Add(this.tabDetailConfigOutput); this.tabDetail.Controls.Add(this.tabDetailFileBrowser); this.tabDetail.Dock = System.Windows.Forms.DockStyle.Fill; this.tabDetail.ImageList = this.ilTabs; this.tabDetail.Location = new System.Drawing.Point(0, 0); this.tabDetail.Margin = new System.Windows.Forms.Padding(0); this.tabDetail.Name = "tabDetail"; this.tabDetail.SelectedIndex = 0; this.tabDetail.Size = new System.Drawing.Size(631, 194); this.tabDetail.TabIndex = 0; // // tabDetailLog // this.tabDetailLog.Controls.Add(this.tbxLog); this.tabDetailLog.Controls.Add(this.tsEventLog); this.tabDetailLog.ImageKey = "page.png"; this.tabDetailLog.Location = new System.Drawing.Point(4, 4); this.tabDetailLog.Name = "tabDetailLog"; this.tabDetailLog.Size = new System.Drawing.Size(623, 167); this.tabDetailLog.TabIndex = 2; this.tabDetailLog.Text = "Event Log"; this.tabDetailLog.UseVisualStyleBackColor = true; // // tbxLog // this.tbxLog.Dock = System.Windows.Forms.DockStyle.Fill; this.tbxLog.Location = new System.Drawing.Point(0, 25); this.tbxLog.Name = "tbxLog"; this.tbxLog.ReadOnly = true; this.tbxLog.ScrollBars = System.Windows.Forms.RichTextBoxScrollBars.Both; this.tbxLog.Size = new System.Drawing.Size(623, 142); this.tbxLog.StateCommon.Border.DrawBorders = ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Left; this.tbxLog.StateCommon.Content.Font = new System.Drawing.Font("Courier New", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.tbxLog.TabIndex = 1; this.tbxLog.WordWrap = false; this.tbxLog.TextChanged += new System.EventHandler(this.tbxLog_TextChanged); // // tsEventLog // this.tsEventLog.BackgroundImageLayout = System.Windows.Forms.ImageLayout.None; this.tsEventLog.Font = new System.Drawing.Font("Segoe UI", 9F); this.tsEventLog.GripMargin = new System.Windows.Forms.Padding(0); this.tsEventLog.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden; this.tsEventLog.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.btnClearLog}); this.tsEventLog.Location = new System.Drawing.Point(0, 0); this.tsEventLog.Name = "tsEventLog"; this.tsEventLog.Padding = new System.Windows.Forms.Padding(0); this.tsEventLog.Size = new System.Drawing.Size(623, 25); this.tsEventLog.Stretch = true; this.tsEventLog.TabIndex = 0; this.tsEventLog.Text = "toolStrip2"; // // btnClearLog // this.btnClearLog.Alignment = System.Windows.Forms.ToolStripItemAlignment.Right; this.btnClearLog.Image = ((System.Drawing.Image)(resources.GetObject("btnClearLog.Image"))); this.btnClearLog.ImageTransparentColor = System.Drawing.Color.Magenta; this.btnClearLog.Name = "btnClearLog"; this.btnClearLog.Size = new System.Drawing.Size(77, 22); this.btnClearLog.Text = "Clear Log"; this.btnClearLog.Click += new System.EventHandler(this.btnClearLog_Click); // // tabDetailConfigOutput // this.tabDetailConfigOutput.Controls.Add(this.tbxConfigOutput); this.tabDetailConfigOutput.Controls.Add(this.tsConfigFile); this.tabDetailConfigOutput.ImageKey = "script_gear.png"; this.tabDetailConfigOutput.Location = new System.Drawing.Point(4, 4); this.tabDetailConfigOutput.Name = "tabDetailConfigOutput"; this.tabDetailConfigOutput.Size = new System.Drawing.Size(623, 167); this.tabDetailConfigOutput.TabIndex = 0; this.tabDetailConfigOutput.Text = "Configuration Output"; this.tabDetailConfigOutput.UseVisualStyleBackColor = true; // // tbxConfigOutput // this.tbxConfigOutput.Dock = System.Windows.Forms.DockStyle.Fill; this.tbxConfigOutput.Location = new System.Drawing.Point(0, 25); this.tbxConfigOutput.Margin = new System.Windows.Forms.Padding(0); this.tbxConfigOutput.Name = "tbxConfigOutput"; this.tbxConfigOutput.ScrollBars = System.Windows.Forms.RichTextBoxScrollBars.Both; this.tbxConfigOutput.Size = new System.Drawing.Size(623, 142); this.tbxConfigOutput.StateCommon.Border.DrawBorders = ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Left; this.tbxConfigOutput.StateCommon.Content.Font = new System.Drawing.Font("Courier New", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.tbxConfigOutput.TabIndex = 2; this.tbxConfigOutput.WordWrap = false; // // tsConfigFile // this.tsConfigFile.Font = new System.Drawing.Font("Segoe UI", 9F); this.tsConfigFile.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden; this.tsConfigFile.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.btnCopyConfig}); this.tsConfigFile.Location = new System.Drawing.Point(0, 0); this.tsConfigFile.Name = "tsConfigFile"; this.tsConfigFile.Padding = new System.Windows.Forms.Padding(0); this.tsConfigFile.Size = new System.Drawing.Size(623, 25); this.tsConfigFile.TabIndex = 1; this.tsConfigFile.Text = "toolStrip2"; // // btnCopyConfig // this.btnCopyConfig.Alignment = System.Windows.Forms.ToolStripItemAlignment.Right; this.btnCopyConfig.Image = ((System.Drawing.Image)(resources.GetObject("btnCopyConfig.Image"))); this.btnCopyConfig.ImageTransparentColor = System.Drawing.Color.Magenta; this.btnCopyConfig.Name = "btnCopyConfig"; this.btnCopyConfig.Size = new System.Drawing.Size(124, 22); this.btnCopyConfig.Text = "Copy to Clipboard"; this.btnCopyConfig.Click += new System.EventHandler(this.btnCopyConfig_Click); // // tabDetailFileBrowser // this.tabDetailFileBrowser.BackColor = System.Drawing.Color.Transparent; this.tabDetailFileBrowser.BackgroundImageLayout = System.Windows.Forms.ImageLayout.None; this.tabDetailFileBrowser.Controls.Add(this.splitContainer1); this.tabDetailFileBrowser.ImageKey = "page_white_visualstudio.png"; this.tabDetailFileBrowser.Location = new System.Drawing.Point(4, 4); this.tabDetailFileBrowser.Margin = new System.Windows.Forms.Padding(0); this.tabDetailFileBrowser.Name = "tabDetailFileBrowser"; this.tabDetailFileBrowser.Size = new System.Drawing.Size(623, 167); this.tabDetailFileBrowser.TabIndex = 1; this.tabDetailFileBrowser.Text = "Generated Files"; this.tabDetailFileBrowser.UseVisualStyleBackColor = true; // // splitContainer1 // this.splitContainer1.BackColor = System.Drawing.Color.DarkGray; this.splitContainer1.Dock = System.Windows.Forms.DockStyle.Fill; this.splitContainer1.Location = new System.Drawing.Point(0, 0); this.splitContainer1.Name = "splitContainer1"; // // splitContainer1.Panel1 // this.splitContainer1.Panel1.Controls.Add(this.treeFileSystem); // // splitContainer1.Panel2 // this.splitContainer1.Panel2.Controls.Add(this.fileBrowser); this.splitContainer1.Size = new System.Drawing.Size(623, 167); this.splitContainer1.SplitterDistance = 121; this.splitContainer1.TabIndex = 1; // // treeFileSystem // this.treeFileSystem.BackColor = System.Drawing.SystemColors.Control; this.treeFileSystem.BorderStyle = System.Windows.Forms.BorderStyle.None; this.treeFileSystem.Dock = System.Windows.Forms.DockStyle.Fill; this.treeFileSystem.HideSelection = false; this.treeFileSystem.HotTracking = true; this.treeFileSystem.ImageKey = "drive.png"; this.treeFileSystem.ImageList = this.ilNodes; this.treeFileSystem.Indent = 10; this.treeFileSystem.LineColor = System.Drawing.Color.LightGray; this.treeFileSystem.Location = new System.Drawing.Point(0, 0); this.treeFileSystem.Margin = new System.Windows.Forms.Padding(0); this.treeFileSystem.Name = "treeFileSystem"; this.treeFileSystem.SelectedImageIndex = 0; this.treeFileSystem.Size = new System.Drawing.Size(121, 167); this.treeFileSystem.TabIndex = 0; this.treeFileSystem.BeforeExpand += new System.Windows.Forms.TreeViewCancelEventHandler(this.treeFileSystem_BeforeExpand); this.treeFileSystem.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.treeFileSystem_AfterSelect); // // fileBrowser // this.fileBrowser.Dock = System.Windows.Forms.DockStyle.Fill; this.fileBrowser.Location = new System.Drawing.Point(0, 0); this.fileBrowser.Margin = new System.Windows.Forms.Padding(0); this.fileBrowser.MinimumSize = new System.Drawing.Size(20, 20); this.fileBrowser.Name = "fileBrowser"; this.fileBrowser.Size = new System.Drawing.Size(498, 167); this.fileBrowser.TabIndex = 0; this.fileBrowser.Navigating += new System.Windows.Forms.WebBrowserNavigatingEventHandler(this.fileBrowser_Navigating); this.fileBrowser.Navigated += new System.Windows.Forms.WebBrowserNavigatedEventHandler(this.fileBrowser_Navigated); // // cmTree // this.cmTree.Font = new System.Drawing.Font("Segoe UI", 8.25F); this.cmTree.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.cmiTreeDeleteProject, this.toolStripSeparator1, this.cmiTreeAddProvider, this.cmiTreeDeleteProvider, this.toolStripSeparator2, this.cmiTreeAddConnectionString, this.cmiTreeDeleteConnectionString, this.toolStripMenuItem1, this.cmiGenerateObjectEnabled}); this.cmTree.Name = "cmTree"; this.cmTree.Size = new System.Drawing.Size(205, 154); this.cmTree.ItemClicked += new System.Windows.Forms.ToolStripItemClickedEventHandler(this.cmTree_ItemClicked); // // cmiTreeDeleteProject // this.cmiTreeDeleteProject.Image = ((System.Drawing.Image)(resources.GetObject("cmiTreeDeleteProject.Image"))); this.cmiTreeDeleteProject.Name = "cmiTreeDeleteProject"; this.cmiTreeDeleteProject.Size = new System.Drawing.Size(204, 22); this.cmiTreeDeleteProject.Text = "Delete Project"; // // toolStripSeparator1 // this.toolStripSeparator1.Name = "toolStripSeparator1"; this.toolStripSeparator1.Size = new System.Drawing.Size(201, 6); // // cmiTreeAddProvider // this.cmiTreeAddProvider.Image = ((System.Drawing.Image)(resources.GetObject("cmiTreeAddProvider.Image"))); this.cmiTreeAddProvider.Name = "cmiTreeAddProvider"; this.cmiTreeAddProvider.Size = new System.Drawing.Size(204, 22); this.cmiTreeAddProvider.Text = "Add Provider"; // // cmiTreeDeleteProvider // this.cmiTreeDeleteProvider.Image = ((System.Drawing.Image)(resources.GetObject("cmiTreeDeleteProvider.Image"))); this.cmiTreeDeleteProvider.Name = "cmiTreeDeleteProvider"; this.cmiTreeDeleteProvider.Size = new System.Drawing.Size(204, 22); this.cmiTreeDeleteProvider.Text = "Delete Provider"; // // toolStripSeparator2 // this.toolStripSeparator2.Name = "toolStripSeparator2"; this.toolStripSeparator2.Size = new System.Drawing.Size(201, 6); // // cmiTreeAddConnectionString // this.cmiTreeAddConnectionString.Image = ((System.Drawing.Image)(resources.GetObject("cmiTreeAddConnectionString.Image"))); this.cmiTreeAddConnectionString.Name = "cmiTreeAddConnectionString"; this.cmiTreeAddConnectionString.Size = new System.Drawing.Size(204, 22); this.cmiTreeAddConnectionString.Text = "Add Connection String"; // // cmiTreeDeleteConnectionString // this.cmiTreeDeleteConnectionString.Image = ((System.Drawing.Image)(resources.GetObject("cmiTreeDeleteConnectionString.Image"))); this.cmiTreeDeleteConnectionString.Name = "cmiTreeDeleteConnectionString"; this.cmiTreeDeleteConnectionString.Size = new System.Drawing.Size(204, 22); this.cmiTreeDeleteConnectionString.Text = "Delete Connection String"; // // toolStripMenuItem1 // this.toolStripMenuItem1.Name = "toolStripMenuItem1"; this.toolStripMenuItem1.Size = new System.Drawing.Size(201, 6); // // cmiGenerateObjectEnabled // this.cmiGenerateObjectEnabled.Name = "cmiGenerateObjectEnabled"; this.cmiGenerateObjectEnabled.Size = new System.Drawing.Size(204, 22); this.cmiGenerateObjectEnabled.Text = "Generate Object?"; // // SubStageForm // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(816, 535); this.Controls.Add(this.kryptonSplitContainer1); this.Controls.Add(this.statusStrip1); this.Controls.Add(this.menuStrip1); this.DoubleBuffered = true; this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.MainMenuStrip = this.menuStrip1; this.Name = "SubStageForm"; this.Text = "SubStage"; this.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.SubStageForm_FormClosed); this.menuStrip1.ResumeLayout(false); this.menuStrip1.PerformLayout(); this.statusStrip1.ResumeLayout(false); this.statusStrip1.PerformLayout(); this.toolStrip1.ResumeLayout(false); this.toolStrip1.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.kryptonSplitContainer1.Panel1)).EndInit(); this.kryptonSplitContainer1.Panel1.ResumeLayout(false); this.kryptonSplitContainer1.Panel1.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.kryptonSplitContainer1.Panel2)).EndInit(); this.kryptonSplitContainer1.Panel2.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.kryptonSplitContainer1)).EndInit(); this.kryptonSplitContainer1.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.kryptonSplitContainer2.Panel1)).EndInit(); this.kryptonSplitContainer2.Panel1.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.kryptonSplitContainer2.Panel2)).EndInit(); this.kryptonSplitContainer2.Panel2.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.kryptonSplitContainer2)).EndInit(); this.kryptonSplitContainer2.ResumeLayout(false); this.tabMaster.ResumeLayout(false); this.tabMasterProperties.ResumeLayout(false); this.tabMasterScaffolds.ResumeLayout(false); this.tabMasterAPIReference.ResumeLayout(false); this.tabMasterForums.ResumeLayout(false); this.tabMasterWorkItems.ResumeLayout(false); this.tabDetail.ResumeLayout(false); this.tabDetailLog.ResumeLayout(false); this.tabDetailLog.PerformLayout(); this.tsEventLog.ResumeLayout(false); this.tsEventLog.PerformLayout(); this.tabDetailConfigOutput.ResumeLayout(false); this.tabDetailConfigOutput.PerformLayout(); this.tsConfigFile.ResumeLayout(false); this.tsConfigFile.PerformLayout(); this.tabDetailFileBrowser.ResumeLayout(false); this.splitContainer1.Panel1.ResumeLayout(false); this.splitContainer1.Panel2.ResumeLayout(false); this.splitContainer1.ResumeLayout(false); this.cmTree.ResumeLayout(false); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.MenuStrip menuStrip1; private System.Windows.Forms.ToolStripMenuItem fileToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem editToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem helpToolStripMenuItem; private ComponentFactory.Krypton.Toolkit.KryptonManager kryptonManager1; private System.Windows.Forms.StatusStrip statusStrip1; private System.Windows.Forms.ToolStrip toolStrip1; private ComponentFactory.Krypton.Toolkit.KryptonSplitContainer kryptonSplitContainer1; private System.Windows.Forms.TreeView treeView1; private ComponentFactory.Krypton.Toolkit.KryptonSplitContainer kryptonSplitContainer2; private System.Windows.Forms.TabControl tabMaster; private System.Windows.Forms.TabPage tabMasterProperties; private System.Windows.Forms.TabControl tabDetail; private System.Windows.Forms.ImageList ilNodes; private System.Windows.Forms.ToolStripMenuItem miFileExit; private System.Windows.Forms.ToolStripMenuItem miHelpAbout; private System.Windows.Forms.ToolStripButton btnNewProject; private System.Windows.Forms.ToolStripButton btnNewProvider; private System.Windows.Forms.TabPage tabMasterAPIReference; private System.Windows.Forms.WebBrowser webBrowser1; private System.Windows.Forms.TabPage tabMasterForums; private System.Windows.Forms.TabPage tabMasterWorkItems; private System.Windows.Forms.WebBrowser webBrowser2; private System.Windows.Forms.WebBrowser webBrowser3; private System.Windows.Forms.ContextMenuStrip cmTree; private System.Windows.Forms.ToolStripMenuItem cmiTreeDeleteProject; private System.Windows.Forms.ToolStripSeparator toolStripSeparator1; private System.Windows.Forms.ToolStripMenuItem cmiTreeAddProvider; private System.Windows.Forms.ToolStripMenuItem cmiTreeDeleteProvider; private System.Windows.Forms.ToolStripButton btnAddConnectionString; private System.Windows.Forms.ToolStripSeparator toolStripSeparator2; private System.Windows.Forms.ToolStripMenuItem cmiTreeAddConnectionString; private System.Windows.Forms.ToolStripMenuItem cmiTreeDeleteConnectionString; private System.Windows.Forms.ToolStripButton btnInvokeProviders; private System.Windows.Forms.ToolStripMenuItem miFileImportProject; private PropertyGridEx.PropertyGridEx pGrid; private System.Windows.Forms.TabPage tabDetailConfigOutput; private System.Windows.Forms.ImageList ilTabs; private System.Windows.Forms.TabPage tabDetailFileBrowser; private System.Windows.Forms.WebBrowser fileBrowser; private System.Windows.Forms.ToolStripStatusLabel tsStatus; private System.Windows.Forms.ToolStripButton pgbTestConnection; private System.Windows.Forms.ToolStripSplitButton btnSplitGenerateCode; private System.Windows.Forms.ToolStripMenuItem miScriptSchemas; private System.Windows.Forms.ToolStripMenuItem miScriptData; private System.Windows.Forms.ToolStripDropDownButton btnDDNodeView; private System.Windows.Forms.ToolStripMenuItem miUseGeneratedNames; private System.Windows.Forms.ToolStripMenuItem miUseDatabaseNames; private System.Windows.Forms.ToolStrip tsConfigFile; private System.Windows.Forms.ToolStripButton btnCopyConfig; private System.Windows.Forms.TabPage tabDetailLog; private System.Windows.Forms.ToolStrip tsEventLog; private System.Windows.Forms.ToolStripButton btnClearLog; private ComponentFactory.Krypton.Toolkit.KryptonRichTextBox tbxLog; private ComponentFactory.Krypton.Toolkit.KryptonRichTextBox tbxConfigOutput; private System.Windows.Forms.ToolStripSeparator toolStripSeparator3; private System.Windows.Forms.ToolStripMenuItem miGenerateCSharp; private System.Windows.Forms.ToolStripMenuItem miGenerateVB; private System.Windows.Forms.TabPage tabMasterScaffolds; private System.Windows.Forms.WebBrowser webScaffolds; private System.Windows.Forms.ToolStripSeparator toolStripMenuItem1; private System.Windows.Forms.ToolStripMenuItem cmiGenerateObjectEnabled; private System.Windows.Forms.FolderBrowserDialog folderBrowserDialog1; private System.Windows.Forms.SplitContainer splitContainer1; private System.Windows.Forms.TreeView treeFileSystem; } }
// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! namespace Google.Cloud.Datastore.V1.Snippets { using Google.Api.Gax; using Google.Api.Gax.Grpc; using apis = Google.Cloud.Datastore.V1; using Google.Protobuf; using Google.Protobuf.WellKnownTypes; using Grpc.Core; using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Threading; using System.Threading.Tasks; /// <summary>Generated snippets</summary> public class GeneratedDatastoreClientSnippets { /// <summary>Snippet for LookupAsync</summary> public async Task LookupAsync() { // Snippet: LookupAsync(string,ReadOptions,IEnumerable<Key>,CallSettings) // Additional: LookupAsync(string,ReadOptions,IEnumerable<Key>,CancellationToken) // Create client DatastoreClient datastoreClient = await DatastoreClient.CreateAsync(); // Initialize request argument(s) string projectId = ""; ReadOptions readOptions = new ReadOptions(); IEnumerable<Key> keys = new List<Key>(); // Make the request LookupResponse response = await datastoreClient.LookupAsync(projectId, readOptions, keys); // End snippet } /// <summary>Snippet for Lookup</summary> public void Lookup() { // Snippet: Lookup(string,ReadOptions,IEnumerable<Key>,CallSettings) // Create client DatastoreClient datastoreClient = DatastoreClient.Create(); // Initialize request argument(s) string projectId = ""; ReadOptions readOptions = new ReadOptions(); IEnumerable<Key> keys = new List<Key>(); // Make the request LookupResponse response = datastoreClient.Lookup(projectId, readOptions, keys); // End snippet } /// <summary>Snippet for LookupAsync</summary> public async Task LookupAsync_RequestObject() { // Snippet: LookupAsync(LookupRequest,CallSettings) // Additional: LookupAsync(LookupRequest,CancellationToken) // Create client DatastoreClient datastoreClient = await DatastoreClient.CreateAsync(); // Initialize request argument(s) LookupRequest request = new LookupRequest { ProjectId = "", Keys = { }, }; // Make the request LookupResponse response = await datastoreClient.LookupAsync(request); // End snippet } /// <summary>Snippet for Lookup</summary> public void Lookup_RequestObject() { // Snippet: Lookup(LookupRequest,CallSettings) // Create client DatastoreClient datastoreClient = DatastoreClient.Create(); // Initialize request argument(s) LookupRequest request = new LookupRequest { ProjectId = "", Keys = { }, }; // Make the request LookupResponse response = datastoreClient.Lookup(request); // End snippet } /// <summary>Snippet for RunQueryAsync</summary> public async Task RunQueryAsync_RequestObject() { // Snippet: RunQueryAsync(RunQueryRequest,CallSettings) // Additional: RunQueryAsync(RunQueryRequest,CancellationToken) // Create client DatastoreClient datastoreClient = await DatastoreClient.CreateAsync(); // Initialize request argument(s) RunQueryRequest request = new RunQueryRequest { ProjectId = "", PartitionId = new PartitionId(), }; // Make the request RunQueryResponse response = await datastoreClient.RunQueryAsync(request); // End snippet } /// <summary>Snippet for RunQuery</summary> public void RunQuery_RequestObject() { // Snippet: RunQuery(RunQueryRequest,CallSettings) // Create client DatastoreClient datastoreClient = DatastoreClient.Create(); // Initialize request argument(s) RunQueryRequest request = new RunQueryRequest { ProjectId = "", PartitionId = new PartitionId(), }; // Make the request RunQueryResponse response = datastoreClient.RunQuery(request); // End snippet } /// <summary>Snippet for BeginTransactionAsync</summary> public async Task BeginTransactionAsync() { // Snippet: BeginTransactionAsync(string,CallSettings) // Additional: BeginTransactionAsync(string,CancellationToken) // Create client DatastoreClient datastoreClient = await DatastoreClient.CreateAsync(); // Initialize request argument(s) string projectId = ""; // Make the request BeginTransactionResponse response = await datastoreClient.BeginTransactionAsync(projectId); // End snippet } /// <summary>Snippet for BeginTransaction</summary> public void BeginTransaction() { // Snippet: BeginTransaction(string,CallSettings) // Create client DatastoreClient datastoreClient = DatastoreClient.Create(); // Initialize request argument(s) string projectId = ""; // Make the request BeginTransactionResponse response = datastoreClient.BeginTransaction(projectId); // End snippet } /// <summary>Snippet for BeginTransactionAsync</summary> public async Task BeginTransactionAsync_RequestObject() { // Snippet: BeginTransactionAsync(BeginTransactionRequest,CallSettings) // Additional: BeginTransactionAsync(BeginTransactionRequest,CancellationToken) // Create client DatastoreClient datastoreClient = await DatastoreClient.CreateAsync(); // Initialize request argument(s) BeginTransactionRequest request = new BeginTransactionRequest { ProjectId = "", }; // Make the request BeginTransactionResponse response = await datastoreClient.BeginTransactionAsync(request); // End snippet } /// <summary>Snippet for BeginTransaction</summary> public void BeginTransaction_RequestObject() { // Snippet: BeginTransaction(BeginTransactionRequest,CallSettings) // Create client DatastoreClient datastoreClient = DatastoreClient.Create(); // Initialize request argument(s) BeginTransactionRequest request = new BeginTransactionRequest { ProjectId = "", }; // Make the request BeginTransactionResponse response = datastoreClient.BeginTransaction(request); // End snippet } /// <summary>Snippet for CommitAsync</summary> public async Task CommitAsync1() { // Snippet: CommitAsync(string,CommitRequest.Types.Mode,ByteString,IEnumerable<Mutation>,CallSettings) // Additional: CommitAsync(string,CommitRequest.Types.Mode,ByteString,IEnumerable<Mutation>,CancellationToken) // Create client DatastoreClient datastoreClient = await DatastoreClient.CreateAsync(); // Initialize request argument(s) string projectId = ""; CommitRequest.Types.Mode mode = CommitRequest.Types.Mode.Unspecified; ByteString transaction = ByteString.Empty; IEnumerable<Mutation> mutations = new List<Mutation>(); // Make the request CommitResponse response = await datastoreClient.CommitAsync(projectId, mode, transaction, mutations); // End snippet } /// <summary>Snippet for Commit</summary> public void Commit1() { // Snippet: Commit(string,CommitRequest.Types.Mode,ByteString,IEnumerable<Mutation>,CallSettings) // Create client DatastoreClient datastoreClient = DatastoreClient.Create(); // Initialize request argument(s) string projectId = ""; CommitRequest.Types.Mode mode = CommitRequest.Types.Mode.Unspecified; ByteString transaction = ByteString.Empty; IEnumerable<Mutation> mutations = new List<Mutation>(); // Make the request CommitResponse response = datastoreClient.Commit(projectId, mode, transaction, mutations); // End snippet } /// <summary>Snippet for CommitAsync</summary> public async Task CommitAsync2() { // Snippet: CommitAsync(string,CommitRequest.Types.Mode,IEnumerable<Mutation>,CallSettings) // Additional: CommitAsync(string,CommitRequest.Types.Mode,IEnumerable<Mutation>,CancellationToken) // Create client DatastoreClient datastoreClient = await DatastoreClient.CreateAsync(); // Initialize request argument(s) string projectId = ""; CommitRequest.Types.Mode mode = CommitRequest.Types.Mode.Unspecified; IEnumerable<Mutation> mutations = new List<Mutation>(); // Make the request CommitResponse response = await datastoreClient.CommitAsync(projectId, mode, mutations); // End snippet } /// <summary>Snippet for Commit</summary> public void Commit2() { // Snippet: Commit(string,CommitRequest.Types.Mode,IEnumerable<Mutation>,CallSettings) // Create client DatastoreClient datastoreClient = DatastoreClient.Create(); // Initialize request argument(s) string projectId = ""; CommitRequest.Types.Mode mode = CommitRequest.Types.Mode.Unspecified; IEnumerable<Mutation> mutations = new List<Mutation>(); // Make the request CommitResponse response = datastoreClient.Commit(projectId, mode, mutations); // End snippet } /// <summary>Snippet for CommitAsync</summary> public async Task CommitAsync_RequestObject() { // Snippet: CommitAsync(CommitRequest,CallSettings) // Additional: CommitAsync(CommitRequest,CancellationToken) // Create client DatastoreClient datastoreClient = await DatastoreClient.CreateAsync(); // Initialize request argument(s) CommitRequest request = new CommitRequest { ProjectId = "", Mode = CommitRequest.Types.Mode.Unspecified, Mutations = { }, }; // Make the request CommitResponse response = await datastoreClient.CommitAsync(request); // End snippet } /// <summary>Snippet for Commit</summary> public void Commit_RequestObject() { // Snippet: Commit(CommitRequest,CallSettings) // Create client DatastoreClient datastoreClient = DatastoreClient.Create(); // Initialize request argument(s) CommitRequest request = new CommitRequest { ProjectId = "", Mode = CommitRequest.Types.Mode.Unspecified, Mutations = { }, }; // Make the request CommitResponse response = datastoreClient.Commit(request); // End snippet } /// <summary>Snippet for RollbackAsync</summary> public async Task RollbackAsync() { // Snippet: RollbackAsync(string,ByteString,CallSettings) // Additional: RollbackAsync(string,ByteString,CancellationToken) // Create client DatastoreClient datastoreClient = await DatastoreClient.CreateAsync(); // Initialize request argument(s) string projectId = ""; ByteString transaction = ByteString.Empty; // Make the request RollbackResponse response = await datastoreClient.RollbackAsync(projectId, transaction); // End snippet } /// <summary>Snippet for Rollback</summary> public void Rollback() { // Snippet: Rollback(string,ByteString,CallSettings) // Create client DatastoreClient datastoreClient = DatastoreClient.Create(); // Initialize request argument(s) string projectId = ""; ByteString transaction = ByteString.Empty; // Make the request RollbackResponse response = datastoreClient.Rollback(projectId, transaction); // End snippet } /// <summary>Snippet for RollbackAsync</summary> public async Task RollbackAsync_RequestObject() { // Snippet: RollbackAsync(RollbackRequest,CallSettings) // Additional: RollbackAsync(RollbackRequest,CancellationToken) // Create client DatastoreClient datastoreClient = await DatastoreClient.CreateAsync(); // Initialize request argument(s) RollbackRequest request = new RollbackRequest { ProjectId = "", Transaction = ByteString.Empty, }; // Make the request RollbackResponse response = await datastoreClient.RollbackAsync(request); // End snippet } /// <summary>Snippet for Rollback</summary> public void Rollback_RequestObject() { // Snippet: Rollback(RollbackRequest,CallSettings) // Create client DatastoreClient datastoreClient = DatastoreClient.Create(); // Initialize request argument(s) RollbackRequest request = new RollbackRequest { ProjectId = "", Transaction = ByteString.Empty, }; // Make the request RollbackResponse response = datastoreClient.Rollback(request); // End snippet } /// <summary>Snippet for AllocateIdsAsync</summary> public async Task AllocateIdsAsync() { // Snippet: AllocateIdsAsync(string,IEnumerable<Key>,CallSettings) // Additional: AllocateIdsAsync(string,IEnumerable<Key>,CancellationToken) // Create client DatastoreClient datastoreClient = await DatastoreClient.CreateAsync(); // Initialize request argument(s) string projectId = ""; IEnumerable<Key> keys = new List<Key>(); // Make the request AllocateIdsResponse response = await datastoreClient.AllocateIdsAsync(projectId, keys); // End snippet } /// <summary>Snippet for AllocateIds</summary> public void AllocateIds() { // Snippet: AllocateIds(string,IEnumerable<Key>,CallSettings) // Create client DatastoreClient datastoreClient = DatastoreClient.Create(); // Initialize request argument(s) string projectId = ""; IEnumerable<Key> keys = new List<Key>(); // Make the request AllocateIdsResponse response = datastoreClient.AllocateIds(projectId, keys); // End snippet } /// <summary>Snippet for AllocateIdsAsync</summary> public async Task AllocateIdsAsync_RequestObject() { // Snippet: AllocateIdsAsync(AllocateIdsRequest,CallSettings) // Additional: AllocateIdsAsync(AllocateIdsRequest,CancellationToken) // Create client DatastoreClient datastoreClient = await DatastoreClient.CreateAsync(); // Initialize request argument(s) AllocateIdsRequest request = new AllocateIdsRequest { ProjectId = "", Keys = { }, }; // Make the request AllocateIdsResponse response = await datastoreClient.AllocateIdsAsync(request); // End snippet } /// <summary>Snippet for AllocateIds</summary> public void AllocateIds_RequestObject() { // Snippet: AllocateIds(AllocateIdsRequest,CallSettings) // Create client DatastoreClient datastoreClient = DatastoreClient.Create(); // Initialize request argument(s) AllocateIdsRequest request = new AllocateIdsRequest { ProjectId = "", Keys = { }, }; // Make the request AllocateIdsResponse response = datastoreClient.AllocateIds(request); // End snippet } /// <summary>Snippet for ReserveIdsAsync</summary> public async Task ReserveIdsAsync() { // Snippet: ReserveIdsAsync(string,IEnumerable<Key>,CallSettings) // Additional: ReserveIdsAsync(string,IEnumerable<Key>,CancellationToken) // Create client DatastoreClient datastoreClient = await DatastoreClient.CreateAsync(); // Initialize request argument(s) string projectId = ""; IEnumerable<Key> keys = new List<Key>(); // Make the request ReserveIdsResponse response = await datastoreClient.ReserveIdsAsync(projectId, keys); // End snippet } /// <summary>Snippet for ReserveIds</summary> public void ReserveIds() { // Snippet: ReserveIds(string,IEnumerable<Key>,CallSettings) // Create client DatastoreClient datastoreClient = DatastoreClient.Create(); // Initialize request argument(s) string projectId = ""; IEnumerable<Key> keys = new List<Key>(); // Make the request ReserveIdsResponse response = datastoreClient.ReserveIds(projectId, keys); // End snippet } /// <summary>Snippet for ReserveIdsAsync</summary> public async Task ReserveIdsAsync_RequestObject() { // Snippet: ReserveIdsAsync(ReserveIdsRequest,CallSettings) // Additional: ReserveIdsAsync(ReserveIdsRequest,CancellationToken) // Create client DatastoreClient datastoreClient = await DatastoreClient.CreateAsync(); // Initialize request argument(s) ReserveIdsRequest request = new ReserveIdsRequest { ProjectId = "", Keys = { }, }; // Make the request ReserveIdsResponse response = await datastoreClient.ReserveIdsAsync(request); // End snippet } /// <summary>Snippet for ReserveIds</summary> public void ReserveIds_RequestObject() { // Snippet: ReserveIds(ReserveIdsRequest,CallSettings) // Create client DatastoreClient datastoreClient = DatastoreClient.Create(); // Initialize request argument(s) ReserveIdsRequest request = new ReserveIdsRequest { ProjectId = "", Keys = { }, }; // Make the request ReserveIdsResponse response = datastoreClient.ReserveIds(request); // End snippet } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Drawing; using System.Reflection; using log4net; using Mono.Addins; using Nini.Config; using OpenMetaverse; using OpenMetaverse.Imaging; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; namespace OpenSim.Region.CoreModules.World.LegacyMap { public enum DrawRoutine { Rectangle, Polygon, Ellipse } public struct face { public Point[] pts; } public struct DrawStruct { public DrawRoutine dr; // public Rectangle rect; public SolidBrush brush; public face[] trns; } [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "MapImageModule")] public class MapImageModule : IMapImageGenerator, INonSharedRegionModule { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private Scene m_scene; private IConfigSource m_config; private IMapTileTerrainRenderer terrainRenderer; private bool m_Enabled = false; #region IMapImageGenerator Members public Bitmap CreateMapTile() { bool drawPrimVolume = true; bool textureTerrain = false; bool generateMaptiles = true; Bitmap mapbmp; string[] configSections = new string[] { "Map", "Startup" }; drawPrimVolume = Util.GetConfigVarFromSections<bool>(m_config, "DrawPrimOnMapTile", configSections, drawPrimVolume); textureTerrain = Util.GetConfigVarFromSections<bool>(m_config, "TextureOnMapTile", configSections, textureTerrain); generateMaptiles = Util.GetConfigVarFromSections<bool>(m_config, "GenerateMaptiles", configSections, generateMaptiles); if (generateMaptiles) { if (String.IsNullOrEmpty(m_scene.RegionInfo.MaptileStaticFile)) { if (textureTerrain) { terrainRenderer = new TexturedMapTileRenderer(); } else { terrainRenderer = new ShadedMapTileRenderer(); } terrainRenderer.Initialise(m_scene, m_config); mapbmp = new Bitmap((int)m_scene.Heightmap.Width, (int)m_scene.Heightmap.Height, System.Drawing.Imaging.PixelFormat.Format24bppRgb); //long t = System.Environment.TickCount; //for (int i = 0; i < 10; ++i) { terrainRenderer.TerrainToBitmap(mapbmp); //} //t = System.Environment.TickCount - t; //m_log.InfoFormat("[MAPTILE] generation of 10 maptiles needed {0} ms", t); if (drawPrimVolume) { DrawObjectVolume(m_scene, mapbmp); } } else { try { mapbmp = new Bitmap(m_scene.RegionInfo.MaptileStaticFile); } catch (Exception) { m_log.ErrorFormat( "[MAPTILE]: Failed to load Static map image texture file: {0} for {1}", m_scene.RegionInfo.MaptileStaticFile, m_scene.Name); //mapbmp = new Bitmap((int)m_scene.Heightmap.Width, (int)m_scene.Heightmap.Height, System.Drawing.Imaging.PixelFormat.Format24bppRgb); mapbmp = null; } if (mapbmp != null) m_log.DebugFormat( "[MAPTILE]: Static map image texture file {0} found for {1}", m_scene.RegionInfo.MaptileStaticFile, m_scene.Name); } } else { mapbmp = FetchTexture(m_scene.RegionInfo.RegionSettings.TerrainImageID); } return mapbmp; } public byte[] WriteJpeg2000Image() { try { using (Bitmap mapbmp = CreateMapTile()) { if (mapbmp != null) return OpenJPEG.EncodeFromImage(mapbmp, true); } } catch (Exception e) // LEGIT: Catching problems caused by OpenJPEG p/invoke { m_log.Error("Failed generating terrain map: " + e); } return null; } #endregion #region Region Module interface public void Initialise(IConfigSource source) { m_config = source; if (Util.GetConfigVarFromSections<string>( m_config, "MapImageModule", new string[] { "Startup", "Map" }, "MapImageModule") != "MapImageModule") return; m_Enabled = true; } public void AddRegion(Scene scene) { if (!m_Enabled) return; m_scene = scene; m_scene.RegisterModuleInterface<IMapImageGenerator>(this); } public void RegionLoaded(Scene scene) { } public void RemoveRegion(Scene scene) { } public void Close() { } public string Name { get { return "MapImageModule"; } } public Type ReplaceableInterface { get { return null; } } #endregion // TODO: unused: // private void ShadeBuildings(Bitmap map) // { // lock (map) // { // lock (m_scene.Entities) // { // foreach (EntityBase entity in m_scene.Entities.Values) // { // if (entity is SceneObjectGroup) // { // SceneObjectGroup sog = (SceneObjectGroup) entity; // // foreach (SceneObjectPart primitive in sog.Children.Values) // { // int x = (int) (primitive.AbsolutePosition.X - (primitive.Scale.X / 2)); // int y = (int) (primitive.AbsolutePosition.Y - (primitive.Scale.Y / 2)); // int w = (int) primitive.Scale.X; // int h = (int) primitive.Scale.Y; // // int dx; // for (dx = x; dx < x + w; dx++) // { // int dy; // for (dy = y; dy < y + h; dy++) // { // if (x < 0 || y < 0) // continue; // if (x >= map.Width || y >= map.Height) // continue; // // map.SetPixel(dx, dy, Color.DarkGray); // } // } // } // } // } // } // } // } private Bitmap FetchTexture(UUID id) { AssetBase asset = m_scene.AssetService.Get(id.ToString()); if (asset != null) { m_log.DebugFormat("[MAPTILE]: Static map image texture {0} found for {1}", id, m_scene.Name); } else { m_log.WarnFormat("[MAPTILE]: Static map image texture {0} not found for {1}", id, m_scene.Name); return null; } ManagedImage managedImage; Image image; try { if (OpenJPEG.DecodeToImage(asset.Data, out managedImage, out image)) return new Bitmap(image); else return null; } catch (DllNotFoundException) { m_log.ErrorFormat("[MAPTILE]: OpenJpeg is not installed correctly on this system. Asset Data is empty for {0}", id); } catch (IndexOutOfRangeException) { m_log.ErrorFormat("[MAPTILE]: OpenJpeg was unable to decode this. Asset Data is empty for {0}", id); } catch (Exception) { m_log.ErrorFormat("[MAPTILE]: OpenJpeg was unable to decode this. Asset Data is empty for {0}", id); } return null; } private Bitmap DrawObjectVolume(Scene whichScene, Bitmap mapbmp) { int tc = 0; ITerrainChannel hm = whichScene.Heightmap; tc = Environment.TickCount; m_log.Debug("[MAPTILE]: Generating Maptile Step 2: Object Volume Profile"); EntityBase[] objs = whichScene.GetEntities(); List<float> z_sortheights = new List<float>(); List<uint> z_localIDs = new List<uint>(); Dictionary<uint, DrawStruct> z_sort = new Dictionary<uint, DrawStruct>(); try { lock (objs) { foreach (EntityBase obj in objs) { // Only draw the contents of SceneObjectGroup if (obj is SceneObjectGroup) { SceneObjectGroup mapdot = (SceneObjectGroup)obj; Color mapdotspot = Color.Gray; // Default color when prim color is white // Loop over prim in group foreach (SceneObjectPart part in mapdot.Parts) { if (part == null) continue; // Draw if the object is at least 1 meter wide in any direction if (part.Scale.X > 1f || part.Scale.Y > 1f || part.Scale.Z > 1f) { // Try to get the RGBA of the default texture entry.. // try { // get the null checks out of the way // skip the ones that break if (part == null) continue; if (part.Shape == null) continue; if (part.Shape.PCode == (byte)PCode.Tree || part.Shape.PCode == (byte)PCode.NewTree || part.Shape.PCode == (byte)PCode.Grass) continue; // eliminates trees from this since we don't really have a good tree representation // if you want tree blocks on the map comment the above line and uncomment the below line //mapdotspot = Color.PaleGreen; Primitive.TextureEntry textureEntry = part.Shape.Textures; if (textureEntry == null || textureEntry.DefaultTexture == null) continue; Color4 texcolor = textureEntry.DefaultTexture.RGBA; // Not sure why some of these are null, oh well. int colorr = 255 - (int)(texcolor.R * 255f); int colorg = 255 - (int)(texcolor.G * 255f); int colorb = 255 - (int)(texcolor.B * 255f); if (!(colorr == 255 && colorg == 255 && colorb == 255)) { //Try to set the map spot color try { // If the color gets goofy somehow, skip it *shakes fist at Color4 mapdotspot = Color.FromArgb(colorr, colorg, colorb); } catch (ArgumentException) { } } } catch (IndexOutOfRangeException) { // Windows Array } catch (ArgumentOutOfRangeException) { // Mono Array } Vector3 pos = part.GetWorldPosition(); // skip prim outside of retion if (!m_scene.PositionIsInCurrentRegion(pos)) continue; // skip prim in non-finite position if (Single.IsNaN(pos.X) || Single.IsNaN(pos.Y) || Single.IsInfinity(pos.X) || Single.IsInfinity(pos.Y)) continue; // Figure out if object is under 256m above the height of the terrain bool isBelow256AboveTerrain = false; try { isBelow256AboveTerrain = (pos.Z < ((float)hm[(int)pos.X, (int)pos.Y] + 256f)); } catch (Exception) { } if (isBelow256AboveTerrain) { // Translate scale by rotation so scale is represented properly when object is rotated Vector3 lscale = new Vector3(part.Shape.Scale.X, part.Shape.Scale.Y, part.Shape.Scale.Z); Vector3 scale = new Vector3(); Vector3 tScale = new Vector3(); Vector3 axPos = new Vector3(pos.X, pos.Y, pos.Z); Quaternion llrot = part.GetWorldRotation(); Quaternion rot = new Quaternion(llrot.W, llrot.X, llrot.Y, llrot.Z); scale = lscale * rot; // negative scales don't work in this situation scale.X = Math.Abs(scale.X); scale.Y = Math.Abs(scale.Y); scale.Z = Math.Abs(scale.Z); // This scaling isn't very accurate and doesn't take into account the face rotation :P int mapdrawstartX = (int)(pos.X - scale.X); int mapdrawstartY = (int)(pos.Y - scale.Y); int mapdrawendX = (int)(pos.X + scale.X); int mapdrawendY = (int)(pos.Y + scale.Y); // If object is beyond the edge of the map, don't draw it to avoid errors if (mapdrawstartX < 0 || mapdrawstartX > (hm.Width - 1) || mapdrawendX < 0 || mapdrawendX > (hm.Width - 1) || mapdrawstartY < 0 || mapdrawstartY > (hm.Height - 1) || mapdrawendY < 0 || mapdrawendY > (hm.Height - 1)) continue; #region obb face reconstruction part duex Vector3[] vertexes = new Vector3[8]; // float[] distance = new float[6]; Vector3[] FaceA = new Vector3[6]; // vertex A for Facei Vector3[] FaceB = new Vector3[6]; // vertex B for Facei Vector3[] FaceC = new Vector3[6]; // vertex C for Facei Vector3[] FaceD = new Vector3[6]; // vertex D for Facei tScale = new Vector3(lscale.X, -lscale.Y, lscale.Z); scale = ((tScale * rot)); vertexes[0] = (new Vector3((pos.X + scale.X), (pos.Y + scale.Y), (pos.Z + scale.Z))); // vertexes[0].x = pos.X + vertexes[0].x; //vertexes[0].y = pos.Y + vertexes[0].y; //vertexes[0].z = pos.Z + vertexes[0].z; FaceA[0] = vertexes[0]; FaceB[3] = vertexes[0]; FaceA[4] = vertexes[0]; tScale = lscale; scale = ((tScale * rot)); vertexes[1] = (new Vector3((pos.X + scale.X), (pos.Y + scale.Y), (pos.Z + scale.Z))); // vertexes[1].x = pos.X + vertexes[1].x; // vertexes[1].y = pos.Y + vertexes[1].y; //vertexes[1].z = pos.Z + vertexes[1].z; FaceB[0] = vertexes[1]; FaceA[1] = vertexes[1]; FaceC[4] = vertexes[1]; tScale = new Vector3(lscale.X, -lscale.Y, -lscale.Z); scale = ((tScale * rot)); vertexes[2] = (new Vector3((pos.X + scale.X), (pos.Y + scale.Y), (pos.Z + scale.Z))); //vertexes[2].x = pos.X + vertexes[2].x; //vertexes[2].y = pos.Y + vertexes[2].y; //vertexes[2].z = pos.Z + vertexes[2].z; FaceC[0] = vertexes[2]; FaceD[3] = vertexes[2]; FaceC[5] = vertexes[2]; tScale = new Vector3(lscale.X, lscale.Y, -lscale.Z); scale = ((tScale * rot)); vertexes[3] = (new Vector3((pos.X + scale.X), (pos.Y + scale.Y), (pos.Z + scale.Z))); //vertexes[3].x = pos.X + vertexes[3].x; // vertexes[3].y = pos.Y + vertexes[3].y; // vertexes[3].z = pos.Z + vertexes[3].z; FaceD[0] = vertexes[3]; FaceC[1] = vertexes[3]; FaceA[5] = vertexes[3]; tScale = new Vector3(-lscale.X, lscale.Y, lscale.Z); scale = ((tScale * rot)); vertexes[4] = (new Vector3((pos.X + scale.X), (pos.Y + scale.Y), (pos.Z + scale.Z))); // vertexes[4].x = pos.X + vertexes[4].x; // vertexes[4].y = pos.Y + vertexes[4].y; // vertexes[4].z = pos.Z + vertexes[4].z; FaceB[1] = vertexes[4]; FaceA[2] = vertexes[4]; FaceD[4] = vertexes[4]; tScale = new Vector3(-lscale.X, lscale.Y, -lscale.Z); scale = ((tScale * rot)); vertexes[5] = (new Vector3((pos.X + scale.X), (pos.Y + scale.Y), (pos.Z + scale.Z))); // vertexes[5].x = pos.X + vertexes[5].x; // vertexes[5].y = pos.Y + vertexes[5].y; // vertexes[5].z = pos.Z + vertexes[5].z; FaceD[1] = vertexes[5]; FaceC[2] = vertexes[5]; FaceB[5] = vertexes[5]; tScale = new Vector3(-lscale.X, -lscale.Y, lscale.Z); scale = ((tScale * rot)); vertexes[6] = (new Vector3((pos.X + scale.X), (pos.Y + scale.Y), (pos.Z + scale.Z))); // vertexes[6].x = pos.X + vertexes[6].x; // vertexes[6].y = pos.Y + vertexes[6].y; // vertexes[6].z = pos.Z + vertexes[6].z; FaceB[2] = vertexes[6]; FaceA[3] = vertexes[6]; FaceB[4] = vertexes[6]; tScale = new Vector3(-lscale.X, -lscale.Y, -lscale.Z); scale = ((tScale * rot)); vertexes[7] = (new Vector3((pos.X + scale.X), (pos.Y + scale.Y), (pos.Z + scale.Z))); // vertexes[7].x = pos.X + vertexes[7].x; // vertexes[7].y = pos.Y + vertexes[7].y; // vertexes[7].z = pos.Z + vertexes[7].z; FaceD[2] = vertexes[7]; FaceC[3] = vertexes[7]; FaceD[5] = vertexes[7]; #endregion //int wy = 0; //bool breakYN = false; // If we run into an error drawing, break out of the // loop so we don't lag to death on error handling DrawStruct ds = new DrawStruct(); ds.brush = new SolidBrush(mapdotspot); //ds.rect = new Rectangle(mapdrawstartX, (255 - mapdrawstartY), mapdrawendX - mapdrawstartX, mapdrawendY - mapdrawstartY); ds.trns = new face[FaceA.Length]; for (int i = 0; i < FaceA.Length; i++) { Point[] working = new Point[5]; working[0] = project(hm, FaceA[i], axPos); working[1] = project(hm, FaceB[i], axPos); working[2] = project(hm, FaceD[i], axPos); working[3] = project(hm, FaceC[i], axPos); working[4] = project(hm, FaceA[i], axPos); face workingface = new face(); workingface.pts = working; ds.trns[i] = workingface; } z_sort.Add(part.LocalId, ds); z_localIDs.Add(part.LocalId); z_sortheights.Add(pos.Z); // for (int wx = mapdrawstartX; wx < mapdrawendX; wx++) // { // for (wy = mapdrawstartY; wy < mapdrawendY; wy++) // { // m_log.InfoFormat("[MAPDEBUG]: {0},{1}({2})", wx, (255 - wy),wy); // try // { // // Remember, flip the y! // mapbmp.SetPixel(wx, (255 - wy), mapdotspot); // } // catch (ArgumentException) // { // breakYN = true; // } // } // if (breakYN) // break; // } // } //} } // Object is within 256m Z of terrain } // object is at least a meter wide } // loop over group children } // entitybase is sceneobject group } // foreach loop over entities float[] sortedZHeights = z_sortheights.ToArray(); uint[] sortedlocalIds = z_localIDs.ToArray(); // Sort prim by Z position Array.Sort(sortedZHeights, sortedlocalIds); using (Graphics g = Graphics.FromImage(mapbmp)) { for (int s = 0; s < sortedZHeights.Length; s++) { if (z_sort.ContainsKey(sortedlocalIds[s])) { DrawStruct rectDrawStruct = z_sort[sortedlocalIds[s]]; for (int r = 0; r < rectDrawStruct.trns.Length; r++) { g.FillPolygon(rectDrawStruct.brush,rectDrawStruct.trns[r].pts); } //g.FillRectangle(rectDrawStruct.brush , rectDrawStruct.rect); } } } } // lock entities objs } finally { foreach (DrawStruct ds in z_sort.Values) ds.brush.Dispose(); } m_log.Debug("[MAPTILE]: Generating Maptile Step 2: Done in " + (Environment.TickCount - tc) + " ms"); return mapbmp; } private Point project(ITerrainChannel hm, Vector3 point3d, Vector3 originpos) { Point returnpt = new Point(); //originpos = point3d; //int d = (int)(256f / 1.5f); //Vector3 topos = new Vector3(0, 0, 0); // float z = -point3d.z - topos.z; returnpt.X = (int)point3d.X;//(int)((topos.x - point3d.x) / z * d); returnpt.Y = (int)((hm.Width - 1) - point3d.Y);//(int)(255 - (((topos.y - point3d.y) / z * d))); return returnpt; } public Bitmap CreateViewImage(Vector3 camPos, Vector3 camDir, float fov, int width, int height, bool useTextures) { return null; } } }
using System; using System.Collections.ObjectModel; using System.Drawing; using System.Windows.Forms; using Free.Controls.TreeView.Tree.NodeControls; namespace Free.Controls.TreeView.Tree { public class Node { #region NodeCollection private class NodeCollection : Collection<Node> { private Node _owner; public NodeCollection(Node owner) { _owner=owner; } protected override void ClearItems() { while(this.Count!=0) this.RemoveAt(this.Count-1); } protected override void InsertItem(int index, Node item) { if(item==null) throw new ArgumentNullException("item"); if(item.Parent!=_owner) { if(item.Parent!=null) item.Parent.Nodes.Remove(item); item._parent=_owner; item._index=index; for(int i=index; i<Count; i++) this[i]._index++; base.InsertItem(index, item); TreeModel model=_owner.FindModel(); if(model!=null) model.OnNodeInserted(_owner, index, item); } } protected override void RemoveItem(int index) { Node item=this[index]; item._parent=null; item._index=-1; for(int i=index+1; i<Count; i++) this[i]._index--; base.RemoveItem(index); TreeModel model=_owner.FindModel(); if(model!=null) model.OnNodeRemoved(_owner, index, item); } protected override void SetItem(int index, Node item) { if(item==null) throw new ArgumentNullException("item"); RemoveAt(index); InsertItem(index, item); } } #endregion #region Properties private TreeModel _model; internal TreeModel Model { get { return _model; } set { _model=value; } } private NodeCollection _nodes; public Collection<Node> Nodes { get { return _nodes; } } private Node _parent; public Node Parent { get { return _parent; } set { if(value!=_parent) { if(_parent!=null) _parent.Nodes.Remove(this); if(value!=null) value.Nodes.Add(this); } } } private int _index=-1; public int Index { get { return _index; } } public Node PreviousNode { get { int index=Index; if(index>0) return _parent.Nodes[index-1]; else return null; } } public Node NextNode { get { int index=Index; if(index>=0&&index<_parent.Nodes.Count-1) return _parent.Nodes[index+1]; else return null; } } private string _text; public virtual string Text { get { return _text; } set { if(_text!=value) { _text=value; NotifyModel(); } } } private CheckState _checkState; public virtual CheckState CheckState { get { return _checkState; } set { if(_checkState!=value) { _checkState=value; NotifyModel(); } } } private Image _image; public Image Image { get { return _image; } set { if(_image!=value) { _image=value; NotifyModel(); } } } private ProgressData _progress; public ProgressData Progress { get { return _progress; } set { if(_progress!=value) { _progress=value; NotifyModel(); } } } private object _tag; public object Tag { get { return _tag; } set { _tag=value; } } public bool IsChecked { get { return CheckState!=CheckState.Unchecked; } set { if(value) CheckState=CheckState.Checked; else CheckState=CheckState.Unchecked; } } public virtual bool IsLeaf { get { return false; } } #endregion public Node() : this(string.Empty) { } public Node(string text) { _text=text; _nodes=new NodeCollection(this); } public override string ToString() { return Text; } private TreeModel FindModel() { Node node=this; while(node!=null) { if(node.Model!=null) return node.Model; node=node.Parent; } return null; } protected void NotifyModel() { TreeModel model=FindModel(); if(model!=null&&Parent!=null) { TreePath path=model.GetPath(Parent); if(path!=null) { TreeModelEventArgs args=new TreeModelEventArgs(path, new int[] { Index }, new object[] { this }); model.OnNodesChanged(args); } } } } }
using System; using System.ComponentModel; namespace xmljr.math { /// <summary> /// Summary description for SquareMatrix. /// </summary> [TypeConverter(typeof(ExpandableObjectConverter))] public class SquareMatrix { protected double [] data; private int len; public void SetData(double [] d, int n) { data = d; len = n; } public double [] Data { get { return data; } } public int Dimension { get { return len; } } public SquareMatrix(int n) { data = new double[n*n]; len = n; } public SquareMatrix(SquareMatrix cpy) { data = new double[cpy.Dimension*cpy.Dimension]; len = cpy.Dimension; CopyFrom(cpy); } public static SquareMatrix operator*(SquareMatrix a, SquareMatrix b) { int n = a.Dimension; if(n != b.Dimension) throw new Exception("Matrix Mismatch"); SquareMatrix res = new SquareMatrix(a.Dimension); for(int row = 0; row < n; row ++) { for(int col = 0; col < n; col ++) { double v = 0; for(int z = 0; z < n; z++) { v += a.Get(row,z) * b.Get(z, col); } res.Set(row,col,v); } } return res; } public void CopyFrom(double [] d) { for(int k = 0; k < len * len; k++) data[k] = d[k]; } public void CopyFrom(SquareMatrix d) { CopyFrom(d.data); } public void MakeIdentity() { for(int k = 0; k < len * len; k++) data[k] = 0.0; for(int k = 0; k < len; k++) data[k * len + k] = 1.0; } public double Get(int row, int col) { return data[row * len + col]; } public void Set(int row, int col, double v) { data[row * len + col] = v; } public void DivideRowBy(int row, double s) { for(int k = 0; k < len; k++) { data[row * len + k] /= s; } } public void MultiplyRowBy(int row, double s) { for(int k = 0; k < len; k++) { data[row * len + k] *= s; } } public void SwapRows(int row0, int row1) { for(int k = 0; k < len; k++) { double temp = data[row0 * len + k]; data[row0 * len + k] = data[row1 * len + k]; data[row1 * len + k] = temp; } } public void AddRow(int dest, int src) { for(int k = 0; k < len; k++) { data[dest * len + k] += data[src * len + k]; } } public void SubtractRow(int from, int row) { for(int k = 0; k < len; k++) { data[from * len + k] -= data[row * len + k]; } } public void SubtractRowBy(int from, int row, double s) { for(int k = 0; k < len; k++) { data[from * len + k] -= data[row * len + k] * s; } } public void Show() { for(int row = 0; row < len; row++) { for(int col = 0; col < len; col++) { double v = System.Math.Round(Get(row,col), 3); Console.Write( ("" + v + " ").Substring(0,8) + " "); } Console.WriteLine(); } Console.WriteLine(); } public SquareMatrix minor(int row, int col) { SquareMatrix Rez = new SquareMatrix(len - 1); // left for(int r = 0; r < row; r++) { // up for(int c = 0; c < col; c++) { Rez.Set(r,c,Get(r,c)); } for(int c = col+1; c < len; c++) { Rez.Set(r,c-1,Get(r,c)); } } for(int r = row+1; r < len; r++) { // up for(int c = 0; c < col; c++) { Rez.Set(r-1,c,Get(r,c)); } for(int c = col+1; c < len; c++) { Rez.Set(r-1,c-1,Get(r,c)); } } return Rez; } public double det() { if(len == 1) return Get(0,0); if(len == 2) { return Get(0,0) * Get(1,1) - Get(0,1) * Get(1,0); } double s = 0; double c = 1; for(int k = 0; k < len; k++) { if(System.Math.Abs(Get(0,k)) > 10E-75) { s += c * Get(0,k) * minor(0,k).det(); } c *= -1; } return s; } public void PerformTranspose() { SquareMatrix Cpy = new SquareMatrix(this); for(int row = 0; row < len; row++) { for(int col = 0; col < len; col++) { Cpy.Set(col,row,this.Get(row,col)); } } CopyFrom(Cpy); } public SquareMatrix Transpose { get { SquareMatrix Cpy = new SquareMatrix(this); Cpy.PerformTranspose(); return Cpy; } } public SquareMatrix Inverse { get { SquareMatrix Cpy = new SquareMatrix(this); Cpy.Invert(); return Cpy; } } public void Invert() { SquareMatrix Inv = new SquareMatrix(len); Inv.MakeIdentity(); for(int col = 0; col < len; col++) { // find a non-zero int NonZeroRow = -1; for(int row = col; row < len; row++) { double v = Get(row,col); if(System.Math.Abs(v) > 0.00001) { DivideRowBy(row,v); Inv.DivideRowBy(row,v); if(NonZeroRow < 0) NonZeroRow = row; } } if(NonZeroRow < 0) throw new Exception("Singular Matrix"); if(NonZeroRow != col) { SwapRows(col,NonZeroRow); Inv.SwapRows(col,NonZeroRow); } for(int row = col + 1; row < len; row++) { if(System.Math.Abs(Get(row,col)) > 0.00001) { SubtractRow(row, col); Inv.SubtractRow(row, col); } } } for(int col = len-1; col >= 1; col--) { for(int row = 0; row < col; row++) { double v = Get(row,col); if(System.Math.Abs(Get(row,col)) > 0.00001) { SubtractRowBy(row, col, v); Inv.SubtractRowBy(row, col, v); } } } this.CopyFrom(Inv); } } }
// // PrintWriter.cs // // Author: // Zachary Gramana <zack@xamarin.com> // // Copyright (c) 2013, 2014 Xamarin Inc (http://www.xamarin.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. // /** * Original iOS version by Jens Alfke * Ported to Android by Marty Schoch, Traun Leyden * * Copyright (c) 2012, 2013, 2014 Couchbase, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ namespace Sharpen { using System; using System.IO; using System.Text; internal class PrintWriter : TextWriter { TextWriter writer; public PrintWriter (FilePath path) { writer = new StreamWriter (path); } public PrintWriter (TextWriter other) { writer = other; } public override Encoding Encoding { get { return writer.Encoding; } } public override void Close () { writer.Close (); } public override void Flush () { writer.Flush (); } public override System.IFormatProvider FormatProvider { get { return writer.FormatProvider; } } public override string NewLine { get { return writer.NewLine; } set { writer.NewLine = value; } } public override void Write (char[] buffer, int index, int count) { writer.Write (buffer, index, count); } public override void Write (char[] buffer) { writer.Write (buffer); } public override void Write (string format, object arg0, object arg1, object arg2) { writer.Write (format, arg0, arg1, arg2); } public override void Write (string format, object arg0, object arg1) { writer.Write (format, arg0, arg1); } public override void Write (string format, object arg0) { writer.Write (format, arg0); } public override void Write (string format, params object[] arg) { writer.Write (format, arg); } public override void WriteLine (char[] buffer, int index, int count) { writer.WriteLine (buffer, index, count); } public override void WriteLine (char[] buffer) { writer.WriteLine (buffer); } public override void WriteLine (string format, object arg0, object arg1, object arg2) { writer.WriteLine (format, arg0, arg1, arg2); } public override void WriteLine (string format, object arg0, object arg1) { writer.WriteLine (format, arg0, arg1); } public override void WriteLine (string format, object arg0) { writer.WriteLine (format, arg0); } public override void WriteLine (string format, params object[] arg) { writer.WriteLine (format, arg); } public override void WriteLine (ulong value) { writer.WriteLine (value); } public override void WriteLine (uint value) { writer.WriteLine (value); } public override void WriteLine (string value) { writer.WriteLine (value); } public override void WriteLine (float value) { writer.WriteLine (value); } public override void WriteLine (object value) { writer.WriteLine (value); } public override void WriteLine (long value) { writer.WriteLine (value); } public override void WriteLine (int value) { writer.WriteLine (value); } public override void WriteLine (double value) { writer.WriteLine (value); } public override void WriteLine (decimal value) { writer.WriteLine (value); } public override void WriteLine (char value) { writer.WriteLine (value); } public override void WriteLine (bool value) { writer.WriteLine (value); } public override void WriteLine () { writer.WriteLine (); } public override void Write (bool value) { writer.Write (value); } public override void Write (char value) { writer.Write (value); } public override void Write (decimal value) { writer.Write (value); } public override void Write (double value) { writer.Write (value); } public override void Write (int value) { writer.Write (value); } public override void Write (long value) { writer.Write (value); } public override void Write (object value) { writer.Write (value); } public override void Write (float value) { writer.Write (value); } public override void Write (string value) { writer.Write (value); } public override void Write (uint value) { writer.Write (value); } public override void Write (ulong value) { writer.Write (value); } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Hyak.Common; 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 activities. (see /// http://aka.ms/azureautomationsdk/activityoperations for more /// information) /// </summary> internal partial class ActivityOperations : IServiceOperations<AutomationManagementClient>, IActivityOperations { /// <summary> /// Initializes a new instance of the ActivityOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal ActivityOperations(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> /// Retrieve the activity in the module identified by module name and /// activity name. (see /// http://aka.ms/azureautomationsdk/activityoperations 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='moduleName'> /// Required. The name of module. /// </param> /// <param name='activityName'> /// Required. The name of activity. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response model for the get activity operation. /// </returns> public async Task<ActivityGetResponse> GetAsync(string resourceGroupName, string automationAccount, string moduleName, string activityName, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (automationAccount == null) { throw new ArgumentNullException("automationAccount"); } if (moduleName == null) { throw new ArgumentNullException("moduleName"); } if (activityName == null) { throw new ArgumentNullException("activityName"); } // 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("moduleName", moduleName); tracingParameters.Add("activityName", activityName); 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 + "/modules/"; url = url + Uri.EscapeDataString(moduleName); url = url + "/activities/"; url = url + Uri.EscapeDataString(activityName); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2017-05-15-preview"); 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 ActivityGetResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ActivityGetResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { Activity activityInstance = new Activity(); result.Activity = activityInstance; JToken idValue = responseDoc["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); activityInstance.Id = idInstance; } JToken nameValue = responseDoc["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); activityInstance.Name = nameInstance; } JToken propertiesValue = responseDoc["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { ActivityProperties propertiesInstance = new ActivityProperties(); activityInstance.Properties = propertiesInstance; JToken definitionValue = propertiesValue["definition"]; if (definitionValue != null && definitionValue.Type != JTokenType.Null) { string definitionInstance = ((string)definitionValue); propertiesInstance.Definition = definitionInstance; } JToken parameterSetsArray = propertiesValue["parameterSets"]; if (parameterSetsArray != null && parameterSetsArray.Type != JTokenType.Null) { foreach (JToken parameterSetsValue in ((JArray)parameterSetsArray)) { ActivityParameterSet activityParameterSetInstance = new ActivityParameterSet(); propertiesInstance.ParameterSets.Add(activityParameterSetInstance); JToken nameValue2 = parameterSetsValue["name"]; if (nameValue2 != null && nameValue2.Type != JTokenType.Null) { string nameInstance2 = ((string)nameValue2); activityParameterSetInstance.Name = nameInstance2; } JToken parametersArray = parameterSetsValue["parameters"]; if (parametersArray != null && parametersArray.Type != JTokenType.Null) { foreach (JToken parametersValue in ((JArray)parametersArray)) { ActivityParameter activityParameterInstance = new ActivityParameter(); activityParameterSetInstance.Parameters.Add(activityParameterInstance); JToken nameValue3 = parametersValue["name"]; if (nameValue3 != null && nameValue3.Type != JTokenType.Null) { string nameInstance3 = ((string)nameValue3); activityParameterInstance.Name = nameInstance3; } JToken typeValue = parametersValue["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); activityParameterInstance.Type = typeInstance; } JToken isMandatoryValue = parametersValue["isMandatory"]; if (isMandatoryValue != null && isMandatoryValue.Type != JTokenType.Null) { bool isMandatoryInstance = ((bool)isMandatoryValue); activityParameterInstance.IsMandatory = isMandatoryInstance; } JToken isDynamicValue = parametersValue["isDynamic"]; if (isDynamicValue != null && isDynamicValue.Type != JTokenType.Null) { bool isDynamicInstance = ((bool)isDynamicValue); activityParameterInstance.IsDynamic = isDynamicInstance; } JToken positionValue = parametersValue["position"]; if (positionValue != null && positionValue.Type != JTokenType.Null) { bool positionInstance = ((bool)positionValue); activityParameterInstance.Position = positionInstance; } JToken valueFromPipelineValue = parametersValue["valueFromPipeline"]; if (valueFromPipelineValue != null && valueFromPipelineValue.Type != JTokenType.Null) { bool valueFromPipelineInstance = ((bool)valueFromPipelineValue); activityParameterInstance.ValueFromPipeline = valueFromPipelineInstance; } JToken valueFromPipelineByPropertyNameValue = parametersValue["valueFromPipelineByPropertyName"]; if (valueFromPipelineByPropertyNameValue != null && valueFromPipelineByPropertyNameValue.Type != JTokenType.Null) { bool valueFromPipelineByPropertyNameInstance = ((bool)valueFromPipelineByPropertyNameValue); activityParameterInstance.ValueFromPipelineByPropertyName = valueFromPipelineByPropertyNameInstance; } JToken valueFromRemainingArgumentsValue = parametersValue["valueFromRemainingArguments"]; if (valueFromRemainingArgumentsValue != null && valueFromRemainingArgumentsValue.Type != JTokenType.Null) { bool valueFromRemainingArgumentsInstance = ((bool)valueFromRemainingArgumentsValue); activityParameterInstance.ValueFromRemainingArguments = valueFromRemainingArgumentsInstance; } } } } } JToken outputTypesArray = propertiesValue["outputTypes"]; if (outputTypesArray != null && outputTypesArray.Type != JTokenType.Null) { foreach (JToken outputTypesValue in ((JArray)outputTypesArray)) { ActivityOutputType activityOutputTypeInstance = new ActivityOutputType(); propertiesInstance.OutputTypes.Add(activityOutputTypeInstance); JToken nameValue4 = outputTypesValue["name"]; if (nameValue4 != null && nameValue4.Type != JTokenType.Null) { string nameInstance4 = ((string)nameValue4); activityOutputTypeInstance.Name = nameInstance4; } JToken typeValue2 = outputTypesValue["type"]; if (typeValue2 != null && typeValue2.Type != JTokenType.Null) { string typeInstance2 = ((string)typeValue2); activityOutputTypeInstance.Type = typeInstance2; } } } JToken typeValue3 = propertiesValue["type"]; if (typeValue3 != null && typeValue3.Type != JTokenType.Null) { string typeInstance3 = ((string)typeValue3); propertiesInstance.Type = typeInstance3; } 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 activities in the module identified by module /// name. (see http://aka.ms/azureautomationsdk/activityoperations /// 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='moduleName'> /// Required. The name of module. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response model for the list activity operation. /// </returns> public async Task<ActivityListResponse> ListAsync(string resourceGroupName, string automationAccount, string moduleName, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (automationAccount == null) { throw new ArgumentNullException("automationAccount"); } if (moduleName == null) { throw new ArgumentNullException("moduleName"); } // 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("moduleName", moduleName); 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 + "/modules/"; url = url + Uri.EscapeDataString(moduleName); url = url + "/activities"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2017-05-15-preview"); 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 ActivityListResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ActivityListResponse(); 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)) { Activity activityInstance = new Activity(); result.Activities.Add(activityInstance); JToken idValue = valueValue["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); activityInstance.Id = idInstance; } JToken nameValue = valueValue["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); activityInstance.Name = nameInstance; } JToken propertiesValue = valueValue["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { ActivityProperties propertiesInstance = new ActivityProperties(); activityInstance.Properties = propertiesInstance; JToken definitionValue = propertiesValue["definition"]; if (definitionValue != null && definitionValue.Type != JTokenType.Null) { string definitionInstance = ((string)definitionValue); propertiesInstance.Definition = definitionInstance; } JToken parameterSetsArray = propertiesValue["parameterSets"]; if (parameterSetsArray != null && parameterSetsArray.Type != JTokenType.Null) { foreach (JToken parameterSetsValue in ((JArray)parameterSetsArray)) { ActivityParameterSet activityParameterSetInstance = new ActivityParameterSet(); propertiesInstance.ParameterSets.Add(activityParameterSetInstance); JToken nameValue2 = parameterSetsValue["name"]; if (nameValue2 != null && nameValue2.Type != JTokenType.Null) { string nameInstance2 = ((string)nameValue2); activityParameterSetInstance.Name = nameInstance2; } JToken parametersArray = parameterSetsValue["parameters"]; if (parametersArray != null && parametersArray.Type != JTokenType.Null) { foreach (JToken parametersValue in ((JArray)parametersArray)) { ActivityParameter activityParameterInstance = new ActivityParameter(); activityParameterSetInstance.Parameters.Add(activityParameterInstance); JToken nameValue3 = parametersValue["name"]; if (nameValue3 != null && nameValue3.Type != JTokenType.Null) { string nameInstance3 = ((string)nameValue3); activityParameterInstance.Name = nameInstance3; } JToken typeValue = parametersValue["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); activityParameterInstance.Type = typeInstance; } JToken isMandatoryValue = parametersValue["isMandatory"]; if (isMandatoryValue != null && isMandatoryValue.Type != JTokenType.Null) { bool isMandatoryInstance = ((bool)isMandatoryValue); activityParameterInstance.IsMandatory = isMandatoryInstance; } JToken isDynamicValue = parametersValue["isDynamic"]; if (isDynamicValue != null && isDynamicValue.Type != JTokenType.Null) { bool isDynamicInstance = ((bool)isDynamicValue); activityParameterInstance.IsDynamic = isDynamicInstance; } JToken positionValue = parametersValue["position"]; if (positionValue != null && positionValue.Type != JTokenType.Null) { bool positionInstance = ((bool)positionValue); activityParameterInstance.Position = positionInstance; } JToken valueFromPipelineValue = parametersValue["valueFromPipeline"]; if (valueFromPipelineValue != null && valueFromPipelineValue.Type != JTokenType.Null) { bool valueFromPipelineInstance = ((bool)valueFromPipelineValue); activityParameterInstance.ValueFromPipeline = valueFromPipelineInstance; } JToken valueFromPipelineByPropertyNameValue = parametersValue["valueFromPipelineByPropertyName"]; if (valueFromPipelineByPropertyNameValue != null && valueFromPipelineByPropertyNameValue.Type != JTokenType.Null) { bool valueFromPipelineByPropertyNameInstance = ((bool)valueFromPipelineByPropertyNameValue); activityParameterInstance.ValueFromPipelineByPropertyName = valueFromPipelineByPropertyNameInstance; } JToken valueFromRemainingArgumentsValue = parametersValue["valueFromRemainingArguments"]; if (valueFromRemainingArgumentsValue != null && valueFromRemainingArgumentsValue.Type != JTokenType.Null) { bool valueFromRemainingArgumentsInstance = ((bool)valueFromRemainingArgumentsValue); activityParameterInstance.ValueFromRemainingArguments = valueFromRemainingArgumentsInstance; } } } } } JToken outputTypesArray = propertiesValue["outputTypes"]; if (outputTypesArray != null && outputTypesArray.Type != JTokenType.Null) { foreach (JToken outputTypesValue in ((JArray)outputTypesArray)) { ActivityOutputType activityOutputTypeInstance = new ActivityOutputType(); propertiesInstance.OutputTypes.Add(activityOutputTypeInstance); JToken nameValue4 = outputTypesValue["name"]; if (nameValue4 != null && nameValue4.Type != JTokenType.Null) { string nameInstance4 = ((string)nameValue4); activityOutputTypeInstance.Name = nameInstance4; } JToken typeValue2 = outputTypesValue["type"]; if (typeValue2 != null && typeValue2.Type != JTokenType.Null) { string typeInstance2 = ((string)typeValue2); activityOutputTypeInstance.Type = typeInstance2; } } } JToken typeValue3 = propertiesValue["type"]; if (typeValue3 != null && typeValue3.Type != JTokenType.Null) { string typeInstance3 = ((string)typeValue3); propertiesInstance.Type = typeInstance3; } 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 activities in the module identified by module /// name. (see http://aka.ms/azureautomationsdk/activityoperations /// 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 activity operation. /// </returns> public async Task<ActivityListResponse> 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 ActivityListResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ActivityListResponse(); 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)) { Activity activityInstance = new Activity(); result.Activities.Add(activityInstance); JToken idValue = valueValue["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); activityInstance.Id = idInstance; } JToken nameValue = valueValue["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); activityInstance.Name = nameInstance; } JToken propertiesValue = valueValue["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { ActivityProperties propertiesInstance = new ActivityProperties(); activityInstance.Properties = propertiesInstance; JToken definitionValue = propertiesValue["definition"]; if (definitionValue != null && definitionValue.Type != JTokenType.Null) { string definitionInstance = ((string)definitionValue); propertiesInstance.Definition = definitionInstance; } JToken parameterSetsArray = propertiesValue["parameterSets"]; if (parameterSetsArray != null && parameterSetsArray.Type != JTokenType.Null) { foreach (JToken parameterSetsValue in ((JArray)parameterSetsArray)) { ActivityParameterSet activityParameterSetInstance = new ActivityParameterSet(); propertiesInstance.ParameterSets.Add(activityParameterSetInstance); JToken nameValue2 = parameterSetsValue["name"]; if (nameValue2 != null && nameValue2.Type != JTokenType.Null) { string nameInstance2 = ((string)nameValue2); activityParameterSetInstance.Name = nameInstance2; } JToken parametersArray = parameterSetsValue["parameters"]; if (parametersArray != null && parametersArray.Type != JTokenType.Null) { foreach (JToken parametersValue in ((JArray)parametersArray)) { ActivityParameter activityParameterInstance = new ActivityParameter(); activityParameterSetInstance.Parameters.Add(activityParameterInstance); JToken nameValue3 = parametersValue["name"]; if (nameValue3 != null && nameValue3.Type != JTokenType.Null) { string nameInstance3 = ((string)nameValue3); activityParameterInstance.Name = nameInstance3; } JToken typeValue = parametersValue["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); activityParameterInstance.Type = typeInstance; } JToken isMandatoryValue = parametersValue["isMandatory"]; if (isMandatoryValue != null && isMandatoryValue.Type != JTokenType.Null) { bool isMandatoryInstance = ((bool)isMandatoryValue); activityParameterInstance.IsMandatory = isMandatoryInstance; } JToken isDynamicValue = parametersValue["isDynamic"]; if (isDynamicValue != null && isDynamicValue.Type != JTokenType.Null) { bool isDynamicInstance = ((bool)isDynamicValue); activityParameterInstance.IsDynamic = isDynamicInstance; } JToken positionValue = parametersValue["position"]; if (positionValue != null && positionValue.Type != JTokenType.Null) { bool positionInstance = ((bool)positionValue); activityParameterInstance.Position = positionInstance; } JToken valueFromPipelineValue = parametersValue["valueFromPipeline"]; if (valueFromPipelineValue != null && valueFromPipelineValue.Type != JTokenType.Null) { bool valueFromPipelineInstance = ((bool)valueFromPipelineValue); activityParameterInstance.ValueFromPipeline = valueFromPipelineInstance; } JToken valueFromPipelineByPropertyNameValue = parametersValue["valueFromPipelineByPropertyName"]; if (valueFromPipelineByPropertyNameValue != null && valueFromPipelineByPropertyNameValue.Type != JTokenType.Null) { bool valueFromPipelineByPropertyNameInstance = ((bool)valueFromPipelineByPropertyNameValue); activityParameterInstance.ValueFromPipelineByPropertyName = valueFromPipelineByPropertyNameInstance; } JToken valueFromRemainingArgumentsValue = parametersValue["valueFromRemainingArguments"]; if (valueFromRemainingArgumentsValue != null && valueFromRemainingArgumentsValue.Type != JTokenType.Null) { bool valueFromRemainingArgumentsInstance = ((bool)valueFromRemainingArgumentsValue); activityParameterInstance.ValueFromRemainingArguments = valueFromRemainingArgumentsInstance; } } } } } JToken outputTypesArray = propertiesValue["outputTypes"]; if (outputTypesArray != null && outputTypesArray.Type != JTokenType.Null) { foreach (JToken outputTypesValue in ((JArray)outputTypesArray)) { ActivityOutputType activityOutputTypeInstance = new ActivityOutputType(); propertiesInstance.OutputTypes.Add(activityOutputTypeInstance); JToken nameValue4 = outputTypesValue["name"]; if (nameValue4 != null && nameValue4.Type != JTokenType.Null) { string nameInstance4 = ((string)nameValue4); activityOutputTypeInstance.Name = nameInstance4; } JToken typeValue2 = outputTypesValue["type"]; if (typeValue2 != null && typeValue2.Type != JTokenType.Null) { string typeInstance2 = ((string)typeValue2); activityOutputTypeInstance.Type = typeInstance2; } } } JToken typeValue3 = propertiesValue["type"]; if (typeValue3 != null && typeValue3.Type != JTokenType.Null) { string typeInstance3 = ((string)typeValue3); propertiesInstance.Type = typeInstance3; } 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(); } } } } }
// Code generated by Microsoft (R) AutoRest Code Generator 1.1.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace ApplicationGateway { using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// ApplicationGatewaysOperations operations. /// </summary> public partial interface IApplicationGatewaysOperations { /// <summary> /// Deletes the specified application gateway. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='applicationGatewayName'> /// The name of the application gateway. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string applicationGatewayName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets the specified application gateway. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='applicationGatewayName'> /// The name of the application gateway. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<ApplicationGateway>> GetWithHttpMessagesAsync(string resourceGroupName, string applicationGatewayName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Creates or updates the specified application gateway. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='applicationGatewayName'> /// The name of the application gateway. /// </param> /// <param name='parameters'> /// Parameters supplied to the create or update application gateway /// operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<ApplicationGateway>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string applicationGatewayName, ApplicationGateway parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Lists all application gateways in a resource group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<ApplicationGateway>>> ListWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets all the application gateways in a subscription. /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<ApplicationGateway>>> ListAllWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Starts the specified application gateway. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='applicationGatewayName'> /// The name of the application gateway. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> StartWithHttpMessagesAsync(string resourceGroupName, string applicationGatewayName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Stops the specified application gateway in a resource group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='applicationGatewayName'> /// The name of the application gateway. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> StopWithHttpMessagesAsync(string resourceGroupName, string applicationGatewayName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets the backend health of the specified application gateway in a /// resource group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='applicationGatewayName'> /// The name of the application gateway. /// </param> /// <param name='expand'> /// Expands BackendAddressPool and BackendHttpSettings referenced in /// backend health. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<ApplicationGatewayBackendHealth>> BackendHealthWithHttpMessagesAsync(string resourceGroupName, string applicationGatewayName, string expand = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Deletes the specified application gateway. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='applicationGatewayName'> /// The name of the application gateway. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string applicationGatewayName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Creates or updates the specified application gateway. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='applicationGatewayName'> /// The name of the application gateway. /// </param> /// <param name='parameters'> /// Parameters supplied to the create or update application gateway /// operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<ApplicationGateway>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string applicationGatewayName, ApplicationGateway parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Starts the specified application gateway. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='applicationGatewayName'> /// The name of the application gateway. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> BeginStartWithHttpMessagesAsync(string resourceGroupName, string applicationGatewayName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Stops the specified application gateway in a resource group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='applicationGatewayName'> /// The name of the application gateway. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> BeginStopWithHttpMessagesAsync(string resourceGroupName, string applicationGatewayName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets the backend health of the specified application gateway in a /// resource group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='applicationGatewayName'> /// The name of the application gateway. /// </param> /// <param name='expand'> /// Expands BackendAddressPool and BackendHttpSettings referenced in /// backend health. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<ApplicationGatewayBackendHealth>> BeginBackendHealthWithHttpMessagesAsync(string resourceGroupName, string applicationGatewayName, string expand = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Lists all application gateways in a resource group. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<ApplicationGateway>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets all the application gateways in a subscription. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<ApplicationGateway>>> ListAllNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
using System; using System.Diagnostics; using System.Globalization; using System.IO; using System.Net; using System.Net.Sockets; using System.Threading; using Microsoft.Win32; namespace OpenQA.Selenium.Chrome { /// <summary> /// Provides a mechanism to find the Chrome Binary /// </summary> internal class ChromeBinary { private static readonly string[] chromePaths = new string[] { "/usr/bin/google-chrome", "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome", string.Concat("/Users/", Environment.UserName, "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome") }; private const int ShutdownWaitInterval = 2000; private const int StartWaitInterval = 2500; private static int linearStartWaitCoefficient = 1; private static string chromeFile = string.Empty; private ChromeProfile profile; private ChromeExtension extension; private Process chromeProcess; private int listeningPort; /// <summary> /// Initializes a new instance of the ChromeBinary class using the given <see cref="ChromeProfile"/> and <see cref="ChromeExtension"/>. /// </summary> /// <param name="profile">The Chrome profile to use.</param> /// <param name="extension">The extension to launch Chrome with.</param> internal ChromeBinary(ChromeProfile profile, ChromeExtension extension) : this(profile, extension, 0) { } /// <summary> /// Initializes a new instance of the ChromeBinary class using the given <see cref="ChromeProfile"/>, <see cref="ChromeExtension"/> and port value. /// </summary> /// <param name="profile">The Chrome profile to use.</param> /// <param name="extension">The extension to launch Chrome with.</param> /// <param name="port">The port on which to listen for commands.</param> internal ChromeBinary(ChromeProfile profile, ChromeExtension extension, int port) { this.profile = profile; this.extension = extension; if (port == 0) { FindFreePort(); } else { this.listeningPort = port; } } /// <summary> /// Gets the port number on which the <see cref="ChromeExtension"/> should listen for commands. /// </summary> public int Port { get { return listeningPort; } } private static string ChromePathFromRegistry { get { return Registry.LocalMachine.OpenSubKey( "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\").GetValue("chrome.exe"). ToString(); } } private string Arguments { get { return string.Concat(" --user-data-dir=\"", profile.ProfileDirectory, "\"", " --load-extension=\"", extension.ExtensionDirectory, "\"", " --activate-on-launch", " --homepage=about:blank", " --no-first-run", " --disable-hang-monitor", " --disable-popup-blocking", " --disable-prompt-on-repost", " --no-default-browser-check "); } } /// <summary> /// Increases the wait time used for starting the Chrome process. /// </summary> /// <param name="diff">Interval by which to increase the wait time.</param> public static void IncrementStartWaitInterval(int diff) { linearStartWaitCoefficient += diff; } /// <summary> /// Starts the Chrome process for WebDriver. Assumes the passed directories exist. /// </summary> /// <exception cref="WebDriverException">When it can't launch will throw an error</exception> public void Start() { try { chromeProcess = Process.Start(new ProcessStartInfo(GetChromeFile(), string.Concat(Arguments, string.Format(CultureInfo.InvariantCulture, "http://localhost:{0}/chromeCommandExecutor", listeningPort))) { UseShellExecute = false }); } catch (IOException e) { // TODO(AndreNogueira): Check exception type thrown when process.start fails throw new WebDriverException("Could not start Chrome process", e); } Thread.Sleep(StartWaitInterval * linearStartWaitCoefficient); } /// <summary> /// Kills off the Browser Instance /// </summary> public void Kill() { if ((chromeProcess != null) && !chromeProcess.HasExited) { // Ask nicely to close. chromeProcess.CloseMainWindow(); chromeProcess.WaitForExit(ShutdownWaitInterval); // If it still hasn't closed, be rude. if (!chromeProcess.HasExited) { chromeProcess.Kill(); } chromeProcess = null; DeleteProfileDirectory(profile.ProfileDirectory); } } /// <summary> /// Locates the Chrome executable on the current platform. First looks in the webdriver.chrome.bin property, then searches /// through the default expected locations. /// </summary> /// <returns>chrome.exe path</returns> private static string GetChromeFile() { if (!IsChromeBinaryLocationKnown()) { string chromeFileSystemProperty = Environment.GetEnvironmentVariable("webdriver.chrome.bin"); if (chromeFileSystemProperty != null) { chromeFile = chromeFileSystemProperty; } else { if (Platform.CurrentPlatform.IsPlatformType(PlatformType.XP) || Platform.CurrentPlatform.IsPlatformType(PlatformType.Vista)) { try { chromeFile = ChromePathFromRegistry; } catch (NullReferenceException) { if (Platform.CurrentPlatform.IsPlatformType(PlatformType.XP)) { chromeFile = Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Google\\Chrome\\Application\\chrome.exe"); } else { chromeFile = Path.Combine(Path.GetTempPath(), "..\\Google\\Chrome\\Application\\chrome.exe"); } } } else if (Platform.CurrentPlatform.IsPlatformType(PlatformType.Unix)) { // Thanks to a bug in Mono Mac and Linux will be treated the same https://bugzilla.novell.com/show_bug.cgi?id=515570 but adding this in case string chromeFileString = string.Empty; bool foundPath = false; foreach (string path in chromePaths) { FileInfo binary = new FileInfo(path); if (binary.Exists) { chromeFileString = binary.FullName; foundPath = true; break; } } if (!foundPath) { throw new WebDriverException("Couldn't locate Chrome. Set webdriver.chrome.bin"); } chromeFile = chromeFileString; } else { throw new WebDriverException( "Unsupported operating system. Could not locate Chrome. Set webdriver.chrome.bin"); } } } return chromeFile; } private static bool IsChromeBinaryLocationKnown() { return !string.IsNullOrEmpty(chromeFile) && File.Exists(chromeFile); } private static void DeleteProfileDirectory(string directoryToDelete) { int numberOfRetries = 0; while (Directory.Exists(directoryToDelete) && numberOfRetries < 10) { try { Directory.Delete(directoryToDelete, true); } catch (IOException) { // If we hit an exception (like file still in use), wait a half second // and try again. If we still hit an exception, go ahead and let it through. System.Threading.Thread.Sleep(500); } catch (UnauthorizedAccessException) { // If we hit an exception (like file still in use), wait a half second // and try again. If we still hit an exception, go ahead and let it through. System.Threading.Thread.Sleep(500); } finally { numberOfRetries++; } if (Directory.Exists(directoryToDelete)) { Console.WriteLine("Unable to delete profile directory '{0}'", directoryToDelete); } } } private void FindFreePort() { // Locate a free port on the local machine by binding a socket to // an IPEndPoint using IPAddress.Any and port 0. The socket will // select a free port. Socket portSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPEndPoint socketEndPoint = new IPEndPoint(IPAddress.Any, 0); portSocket.Bind(socketEndPoint); socketEndPoint = (IPEndPoint)portSocket.LocalEndPoint; listeningPort = socketEndPoint.Port; portSocket.Close(); } } }
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Reflection; using THNETII.Common; using THNETII.Common.Collections.Generic; namespace THNETII.DependencyInjection.Nesting { /// <summary> /// A collection of service descriptors that are nested under a parent /// serice collection. /// </summary> /// <typeparam name="TFamily">The family for which the collection manages nested services.</typeparam> /// <typeparam name="TKey">The type of the key that is used to uniquely distinguish nested sibling containers from each other.</typeparam> public class NestedServiceCollection<TFamily, TKey> : INestedServiceCollection<TFamily, TKey> { private readonly IEnumerable<ServiceDescriptor> inheritedServices; private readonly ServiceDescriptorExceptionCollection rootProxyDescriptors = new ServiceDescriptorExceptionCollection(); private readonly IServiceCollection nestedServices; private int InheritedCount => (InheritedServices?.Count ?? 0) - rootProxyDescriptors.Count; /// <inheritdoc cref="INestedServiceCollection{TKey}.Key" /> public TKey Key { get; } /// <inheritdoc cref="INestedServiceCollection.InheritedServices" /> public IServiceCollection? InheritedServices { get; } /// <inheritdoc cref="INestedServiceCollection.RootServicesAddBehavior" /> public RootServicesAddBehavior RootServicesAddBehavior { get; set; } = RootServicesAddBehavior.Add; /// <summary> /// Creates a new nested service collection with the specified key and /// inherited services. /// </summary> /// <param name="key">The key for the nested services collection. Must not be <see langword="null"/>.</param> /// <param name="inheritedServices"> /// The parent service collection from which parent services should be inherited. /// </param> public NestedServiceCollection(TKey key, IServiceCollection? inheritedServices) { Key = key; InheritedServices = inheritedServices; this.inheritedServices = inheritedServices.EmptyIfNull() .Except(rootProxyDescriptors, ReferenceEqualityComparer.Instance) .Select(desc => GetProxyDescriptorForNested(desc)); nestedServices = new ServiceCollection(); } private static ServiceDescriptor GetProxyDescriptorForNested( ServiceDescriptor rootServiceDescriptor) { var serviceTypeRef = rootServiceDescriptor.ServiceType #if NETSTANDARD1_3 .GetTypeInfo() #endif ; if (serviceTypeRef.IsGenericTypeDefinition) return rootServiceDescriptor; return new ServiceDescriptor(rootServiceDescriptor.ServiceType, nsp => nsp.GetRequiredService<RootServiceProviderAccessor>() .RootServiceProvider.GetService( rootServiceDescriptor.ServiceType), rootServiceDescriptor.Lifetime); } private ServiceDescriptor GetProxyDescriptorForRoot( ServiceDescriptor nestedServiceDescriptor) { var serviceTypeRef = nestedServiceDescriptor.ServiceType #if NETSTANDARD1_3 .GetTypeInfo() #endif ; if (serviceTypeRef.IsGenericTypeDefinition) return nestedServiceDescriptor; return new ServiceDescriptor(nestedServiceDescriptor.ServiceType, rsp => rsp.GetNestedServiceProvider<TFamily, TKey>(Key) .GetService(nestedServiceDescriptor.ServiceType), nestedServiceDescriptor.Lifetime); } #if !NETSTANDARD1_3 private static readonly MethodInfo InternalRemoveAllServicesMethodInfo = typeof(NestedServicesServiceCollectionExtensions) .GetMethod(nameof(InternalRemoveAllServices), BindingFlags.NonPublic | BindingFlags.Static); private static void InternalRemoveAllServices<T>(IServiceCollection services) => services.RemoveAll<T>(); #endif /// <inheritdoc cref="ICollection{T}.Add(T)" /> void ICollection<ServiceDescriptor>.Add( ServiceDescriptor serviceDescriptor) { nestedServices.Add(serviceDescriptor); RegisterDescriptorInInheritedServiceCollection(serviceDescriptor); } private void RegisterDescriptorInInheritedServiceCollection(ServiceDescriptor serviceDescriptor) { if (!(InheritedServices is null)) { int beforeAdd = InheritedServices.Count; bool ensureAddProxy = false; var rootProxyDescriptor = GetProxyDescriptorForRoot(serviceDescriptor); switch (RootServicesAddBehavior) { case RootServicesAddBehavior.Add: InheritedServices.Add(rootProxyDescriptor); ensureAddProxy = true; break; case RootServicesAddBehavior.TryAdd: InheritedServices.TryAdd(rootProxyDescriptor); break; case RootServicesAddBehavior.TryAddEnumerable: InheritedServices.TryAddEnumerable(rootProxyDescriptor); break; case RootServicesAddBehavior.Replace: InheritedServices.Replace(rootProxyDescriptor); ensureAddProxy = true; break; #if !NETSTANDARD1_3 case RootServicesAddBehavior.ReplaceAll: var mi = InternalRemoveAllServicesMethodInfo .MakeGenericMethod(rootProxyDescriptor.ServiceType); mi.Invoke(null, new[] { InheritedServices }); ensureAddProxy = true; goto case RootServicesAddBehavior.Add; #endif } if (InheritedServices.Count != beforeAdd || ensureAddProxy) rootProxyDescriptors.Add(rootProxyDescriptor); } } /// <inheritdoc cref="IEnumerable{T}.GetEnumerator" /> public IEnumerator<ServiceDescriptor> GetEnumerator() { return inheritedServices .Concat(nestedServices) .GetEnumerator(); } /// <inheritdoc cref="Enumerable.ElementAt{TSource}(IEnumerable{TSource}, int)"/> public ServiceDescriptor this[int index] { get => (index < InheritedCount) ? inheritedServices.ElementAt(index) : nestedServices[index - InheritedCount]; set { if (index < InheritedCount) InheritedServices![index] = value; else nestedServices[index - InheritedCount] = value; } } /// <inheritdoc cref="ICollection{T}.Count" /> public int Count => InheritedCount + nestedServices.Count; /// <inheritdoc cref="ICollection{T}.IsReadOnly" /> bool ICollection<ServiceDescriptor>.IsReadOnly => nestedServices.IsReadOnly; /// <inheritdoc cref="IList{T}.IndexOf(T)" /> int IList<ServiceDescriptor>.IndexOf(ServiceDescriptor item) { int result = inheritedServices .Select((d, i) => d == item ? (int?)i : null) .FirstOrDefault(i => !(i is null)) ?? -1; if (result < 0) { result = nestedServices.IndexOf(item); if (result < 0) result += InheritedCount; } return result; } /// <inheritdoc cref="IList{T}.Insert(int, T)" /> void IList<ServiceDescriptor>.Insert(int index, ServiceDescriptor item) { if (index < InheritedCount) throw new InvalidOperationException(); index -= InheritedCount; nestedServices.Insert(index, item); RegisterDescriptorInInheritedServiceCollection(item); } /// <inheritdoc cref="IList{T}.RemoveAt(int)" /> void IList<ServiceDescriptor>.RemoveAt(int index) => RemoveAt(index); private void RemoveAt(int index) { if (index < InheritedCount) throw new InvalidOperationException(); index -= InheritedCount; var nestedDesc = nestedServices[index]; int nestedServiceTypeIdx = nestedServices .Take(index) .Count(d => d.ServiceType == nestedDesc.ServiceType); var rootDesc = rootProxyDescriptors .Where(d => d.ServiceType == nestedDesc.ServiceType) .ElementAt(nestedServiceTypeIdx); InheritedServices?.Remove(rootDesc); rootProxyDescriptors.Remove(rootDesc, ReferenceEqualityComparer.Instance); } /// <inheritdoc cref="ICollection{T}.Clear" /> void ICollection<ServiceDescriptor>.Clear() { nestedServices.Clear(); foreach (var proxyDesc in rootProxyDescriptors) InheritedServices?.Remove(proxyDesc); rootProxyDescriptors.Clear(); } /// <inheritdoc cref="ICollection{T}.Contains(T)"/> bool ICollection<ServiceDescriptor>.Contains(ServiceDescriptor item) => inheritedServices.Contains(item) && nestedServices.Contains(item); /// <inheritdoc cref="ICollection{T}.CopyTo(T[], int)" /> void ICollection<ServiceDescriptor>.CopyTo(ServiceDescriptor[] array, int arrayIndex) { int i = 0; for (var enumerator = inheritedServices.GetEnumerator(); enumerator.MoveNext(); i++) array[arrayIndex + i] = enumerator.Current; nestedServices.CopyTo(array, arrayIndex + i); } /// <inheritdoc cref="ICollection{T}.Remove(T)"/> bool ICollection<ServiceDescriptor>.Remove(ServiceDescriptor item) { int index = nestedServices.IndexOf(item); if (index < 0) return false; RemoveAt(index); return true; } /// <inheritdoc cref="IEnumerable.GetEnumerator"/> IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); } }
/* * [The "BSD licence"] * Copyright (c) 2005-2008 Terence Parr * All rights reserved. * * Conversion to C#: * Copyright (c) 2008-2009 Sam Harwell, Pixel Mine, 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: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. 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. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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. */ // TODO: build indexes for wizard //#define BUILD_INDEXES namespace TypeSql.Antlr.Runtime.Tree { using System.Collections.Generic; using IList = System.Collections.IList; #if BUILD_INDEXES using IDictionary = System.Collections.IDictionary; #endif /** <summary> * Build and navigate trees with this object. Must know about the names * of tokens so you have to pass in a map or array of token names (from which * this class can build the map). I.e., Token DECL means nothing unless the * class can translate it to a token type. * </summary> * * <remarks> * In order to create nodes and navigate, this class needs a TreeAdaptor. * * This class can build a token type -> node index for repeated use or for * iterating over the various nodes with a particular type. * * This class works in conjunction with the TreeAdaptor rather than moving * all this functionality into the adaptor. An adaptor helps build and * navigate trees using methods. This class helps you do it with string * patterns like "(A B C)". You can create a tree from that pattern or * match subtrees against it. * </remarks> */ public class TreeWizard { protected ITreeAdaptor adaptor; protected IDictionary<string, int> tokenNameToTypeMap; public interface IContextVisitor { // TODO: should this be called visit or something else? void Visit( object t, object parent, int childIndex, IDictionary<string, object> labels ); } public abstract class Visitor : IContextVisitor { public virtual void Visit( object t, object parent, int childIndex, IDictionary<string, object> labels ) { Visit( t ); } public abstract void Visit( object t ); } class ActionVisitor : Visitor { System.Action<object> _action; public ActionVisitor( System.Action<object> action ) { _action = action; } public override void Visit( object t ) { _action( t ); } } /** <summary> * When using %label:TOKENNAME in a tree for parse(), we must * track the label. * </summary> */ public class TreePattern : CommonTree { public string label; public bool hasTextArg; public TreePattern( IToken payload ) : base( payload ) { } public override string ToString() { if ( label != null ) { return "%" + label + ":"; //+ base.ToString(); } else { return base.ToString(); } } } public class WildcardTreePattern : TreePattern { public WildcardTreePattern( IToken payload ) : base( payload ) { } } /** <summary>This adaptor creates TreePattern objects for use during scan()</summary> */ public class TreePatternTreeAdaptor : CommonTreeAdaptor { public override object Create( IToken payload ) { return new TreePattern( payload ); } } #if BUILD_INDEXES // TODO: build indexes for the wizard /** <summary> * During fillBuffer(), we can make a reverse index from a set * of token types of interest to the list of indexes into the * node stream. This lets us convert a node pointer to a * stream index semi-efficiently for a list of interesting * nodes such as function definition nodes (you'll want to seek * to their bodies for an interpreter). Also useful for doing * dynamic searches; i.e., go find me all PLUS nodes. * </summary> */ protected IDictionary<int, IList<int>> tokenTypeToStreamIndexesMap; /** <summary> * If tokenTypesToReverseIndex set to INDEX_ALL then indexing * occurs for all token types. * </summary> */ public static readonly HashSet<int> INDEX_ALL = new HashSet<int>(); /** <summary> * A set of token types user would like to index for faster lookup. * If this is INDEX_ALL, then all token types are tracked. If null, * then none are indexed. * </summary> */ protected HashSet<int> tokenTypesToReverseIndex = null; #endif public TreeWizard( ITreeAdaptor adaptor ) { this.adaptor = adaptor; } public TreeWizard( ITreeAdaptor adaptor, IDictionary<string, int> tokenNameToTypeMap ) { this.adaptor = adaptor; this.tokenNameToTypeMap = tokenNameToTypeMap; } public TreeWizard( ITreeAdaptor adaptor, string[] tokenNames ) { this.adaptor = adaptor; this.tokenNameToTypeMap = ComputeTokenTypes( tokenNames ); } public TreeWizard( string[] tokenNames ) : this( new CommonTreeAdaptor(), tokenNames ) { } /** <summary> * Compute a Map&lt;String, Integer&gt; that is an inverted index of * tokenNames (which maps int token types to names). * </summary> */ public virtual IDictionary<string, int> ComputeTokenTypes( string[] tokenNames ) { IDictionary<string, int> m = new Dictionary<string, int>(); if ( tokenNames == null ) { return m; } for ( int ttype = TokenTypes.Min; ttype < tokenNames.Length; ttype++ ) { string name = tokenNames[ttype]; m[name] = ttype; } return m; } /** <summary>Using the map of token names to token types, return the type.</summary> */ public virtual int GetTokenType( string tokenName ) { if ( tokenNameToTypeMap == null ) { return TokenTypes.Invalid; } int value; if ( tokenNameToTypeMap.TryGetValue( tokenName, out value ) ) return value; return TokenTypes.Invalid; } /** <summary> * Walk the entire tree and make a node name to nodes mapping. * For now, use recursion but later nonrecursive version may be * more efficient. Returns Map&lt;Integer, List&gt; where the List is * of your AST node type. The Integer is the token type of the node. * </summary> * * <remarks> * TODO: save this index so that find and visit are faster * </remarks> */ public IDictionary<int, IList> Index( object t ) { IDictionary<int, IList> m = new Dictionary<int, IList>(); IndexCore( t, m ); return m; } /** <summary>Do the work for index</summary> */ protected virtual void IndexCore( object t, IDictionary<int, IList> m ) { if ( t == null ) { return; } int ttype = adaptor.GetType( t ); IList elements; if ( !m.TryGetValue( ttype, out elements ) || elements == null ) { elements = new List<object>(); m[ttype] = elements; } elements.Add( t ); int n = adaptor.GetChildCount( t ); for ( int i = 0; i < n; i++ ) { object child = adaptor.GetChild( t, i ); IndexCore( child, m ); } } class FindTreeWizardVisitor : TreeWizard.Visitor { IList _nodes; public FindTreeWizardVisitor( IList nodes ) { _nodes = nodes; } public override void Visit( object t ) { _nodes.Add( t ); } } class FindTreeWizardContextVisitor : TreeWizard.IContextVisitor { TreeWizard _outer; TreePattern _tpattern; IList _subtrees; public FindTreeWizardContextVisitor( TreeWizard outer, TreePattern tpattern, IList subtrees ) { _outer = outer; _tpattern = tpattern; _subtrees = subtrees; } public void Visit( object t, object parent, int childIndex, IDictionary<string, object> labels ) { if ( _outer.ParseCore( t, _tpattern, null ) ) { _subtrees.Add( t ); } } } /** <summary>Return a List of tree nodes with token type ttype</summary> */ public virtual IList Find( object t, int ttype ) { IList nodes = new List<object>(); Visit( t, ttype, new FindTreeWizardVisitor( nodes ) ); return nodes; } /** <summary>Return a List of subtrees matching pattern.</summary> */ public virtual IList Find( object t, string pattern ) { IList subtrees = new List<object>(); // Create a TreePattern from the pattern TreePatternLexer tokenizer = new TreePatternLexer( pattern ); TreePatternParser parser = new TreePatternParser( tokenizer, this, new TreePatternTreeAdaptor() ); TreePattern tpattern = (TreePattern)parser.Pattern(); // don't allow invalid patterns if ( tpattern == null || tpattern.IsNil || tpattern.GetType() == typeof( WildcardTreePattern ) ) { return null; } int rootTokenType = tpattern.Type; Visit( t, rootTokenType, new FindTreeWizardContextVisitor( this, tpattern, subtrees ) ); return subtrees; } public virtual object FindFirst( object t, int ttype ) { return null; } public virtual object FindFirst( object t, string pattern ) { return null; } /** <summary> * Visit every ttype node in t, invoking the visitor. This is a quicker * version of the general visit(t, pattern) method. The labels arg * of the visitor action method is never set (it's null) since using * a token type rather than a pattern doesn't let us set a label. * </summary> */ public void Visit( object t, int ttype, IContextVisitor visitor ) { VisitCore( t, null, 0, ttype, visitor ); } public void Visit( object t, int ttype, System.Action<object> action ) { Visit( t, ttype, new ActionVisitor( action ) ); } /** <summary>Do the recursive work for visit</summary> */ protected virtual void VisitCore( object t, object parent, int childIndex, int ttype, IContextVisitor visitor ) { if ( t == null ) { return; } if ( adaptor.GetType( t ) == ttype ) { visitor.Visit( t, parent, childIndex, null ); } int n = adaptor.GetChildCount( t ); for ( int i = 0; i < n; i++ ) { object child = adaptor.GetChild( t, i ); VisitCore( child, t, i, ttype, visitor ); } } class VisitTreeWizardContextVisitor : TreeWizard.IContextVisitor { TreeWizard _outer; IContextVisitor _visitor; IDictionary<string, object> _labels; TreePattern _tpattern; public VisitTreeWizardContextVisitor( TreeWizard outer, IContextVisitor visitor, IDictionary<string, object> labels, TreePattern tpattern ) { _outer = outer; _visitor = visitor; _labels = labels; _tpattern = tpattern; } public void Visit( object t, object parent, int childIndex, IDictionary<string, object> unusedlabels ) { // the unusedlabels arg is null as visit on token type doesn't set. _labels.Clear(); if ( _outer.ParseCore( t, _tpattern, _labels ) ) { _visitor.Visit( t, parent, childIndex, _labels ); } } } /** <summary> * For all subtrees that match the pattern, execute the visit action. * The implementation uses the root node of the pattern in combination * with visit(t, ttype, visitor) so nil-rooted patterns are not allowed. * Patterns with wildcard roots are also not allowed. * </summary> */ public void Visit( object t, string pattern, IContextVisitor visitor ) { // Create a TreePattern from the pattern TreePatternLexer tokenizer = new TreePatternLexer( pattern ); TreePatternParser parser = new TreePatternParser( tokenizer, this, new TreePatternTreeAdaptor() ); TreePattern tpattern = (TreePattern)parser.Pattern(); // don't allow invalid patterns if ( tpattern == null || tpattern.IsNil || tpattern.GetType() == typeof( WildcardTreePattern ) ) { return; } IDictionary<string, object> labels = new Dictionary<string, object>(); // reused for each _parse int rootTokenType = tpattern.Type; Visit( t, rootTokenType, new VisitTreeWizardContextVisitor( this, visitor, labels, tpattern ) ); } /** <summary> * Given a pattern like (ASSIGN %lhs:ID %rhs:.) with optional labels * on the various nodes and '.' (dot) as the node/subtree wildcard, * return true if the pattern matches and fill the labels Map with * the labels pointing at the appropriate nodes. Return false if * the pattern is malformed or the tree does not match. * </summary> * * <remarks> * If a node specifies a text arg in pattern, then that must match * for that node in t. * * TODO: what's a better way to indicate bad pattern? Exceptions are a hassle * </remarks> */ public bool Parse( object t, string pattern, IDictionary<string, object> labels ) { TreePatternLexer tokenizer = new TreePatternLexer( pattern ); TreePatternParser parser = new TreePatternParser( tokenizer, this, new TreePatternTreeAdaptor() ); TreePattern tpattern = (TreePattern)parser.Pattern(); /* System.out.println("t="+((Tree)t).toStringTree()); System.out.println("scant="+tpattern.toStringTree()); */ bool matched = ParseCore( t, tpattern, labels ); return matched; } public bool Parse( object t, string pattern ) { return Parse( t, pattern, null ); } /** <summary> * Do the work for parse. Check to see if the t2 pattern fits the * structure and token types in t1. Check text if the pattern has * text arguments on nodes. Fill labels map with pointers to nodes * in tree matched against nodes in pattern with labels. * </summary> */ protected virtual bool ParseCore( object t1, TreePattern tpattern, IDictionary<string, object> labels ) { // make sure both are non-null if ( t1 == null || tpattern == null ) { return false; } // check roots (wildcard matches anything) if ( tpattern.GetType() != typeof( WildcardTreePattern ) ) { if ( adaptor.GetType( t1 ) != tpattern.Type ) { return false; } // if pattern has text, check node text if ( tpattern.hasTextArg && !adaptor.GetText( t1 ).Equals( tpattern.Text ) ) { return false; } } if ( tpattern.label != null && labels != null ) { // map label in pattern to node in t1 labels[tpattern.label] = t1; } // check children int n1 = adaptor.GetChildCount( t1 ); int n2 = tpattern.ChildCount; if ( n1 != n2 ) { return false; } for ( int i = 0; i < n1; i++ ) { object child1 = adaptor.GetChild( t1, i ); TreePattern child2 = (TreePattern)tpattern.GetChild( i ); if ( !ParseCore( child1, child2, labels ) ) { return false; } } return true; } /** <summary> * Create a tree or node from the indicated tree pattern that closely * follows ANTLR tree grammar tree element syntax: * * (root child1 ... child2). * </summary> * * <remarks> * You can also just pass in a node: ID * * Any node can have a text argument: ID[foo] * (notice there are no quotes around foo--it's clear it's a string). * * nil is a special name meaning "give me a nil node". Useful for * making lists: (nil A B C) is a list of A B C. * </remarks> */ public virtual object Create( string pattern ) { TreePatternLexer tokenizer = new TreePatternLexer( pattern ); TreePatternParser parser = new TreePatternParser( tokenizer, this, adaptor ); object t = parser.Pattern(); return t; } /** <summary> * Compare t1 and t2; return true if token types/text, structure match exactly. * The trees are examined in their entirety so that (A B) does not match * (A B C) nor (A (B C)). * </summary> * * <remarks> * TODO: allow them to pass in a comparator * TODO: have a version that is nonstatic so it can use instance adaptor * * I cannot rely on the tree node's equals() implementation as I make * no constraints at all on the node types nor interface etc... * </remarks> */ public static bool Equals( object t1, object t2, ITreeAdaptor adaptor ) { return EqualsCore( t1, t2, adaptor ); } /** <summary> * Compare type, structure, and text of two trees, assuming adaptor in * this instance of a TreeWizard. * </summary> */ public new bool Equals( object t1, object t2 ) { return EqualsCore( t1, t2, adaptor ); } protected static bool EqualsCore( object t1, object t2, ITreeAdaptor adaptor ) { // make sure both are non-null if ( t1 == null || t2 == null ) { return false; } // check roots if ( adaptor.GetType( t1 ) != adaptor.GetType( t2 ) ) { return false; } if ( !adaptor.GetText( t1 ).Equals( adaptor.GetText( t2 ) ) ) { return false; } // check children int n1 = adaptor.GetChildCount( t1 ); int n2 = adaptor.GetChildCount( t2 ); if ( n1 != n2 ) { return false; } for ( int i = 0; i < n1; i++ ) { object child1 = adaptor.GetChild( t1, i ); object child2 = adaptor.GetChild( t2, i ); if ( !EqualsCore( child1, child2, adaptor ) ) { return false; } } return true; } #if BUILD_INDEXES // TODO: next stuff taken from CommonTreeNodeStream /** <summary> * Given a node, add this to the reverse index tokenTypeToStreamIndexesMap. * You can override this method to alter how indexing occurs. The * default is to create a * * Map&lt;Integer token type,ArrayList&lt;Integer stream index&gt;&gt; * </summary> * * <remarks> * This data structure allows you to find all nodes with type INT in order. * * If you really need to find a node of type, say, FUNC quickly then perhaps * * Map&lt;Integertoken type,Map&lt;Object tree node,Integer stream index&gt;&gt; * * would be better for you. The interior maps map a tree node to * the index so you don't have to search linearly for a specific node. * * If you change this method, you will likely need to change * getNodeIndex(), which extracts information. * </remarks> */ protected void fillReverseIndex( object node, int streamIndex ) { //System.out.println("revIndex "+node+"@"+streamIndex); if ( tokenTypesToReverseIndex == null ) { return; // no indexing if this is empty (nothing of interest) } if ( tokenTypeToStreamIndexesMap == null ) { tokenTypeToStreamIndexesMap = new Dictionary<int, IList<int>>(); // first indexing op } int tokenType = adaptor.getType( node ); if ( !( tokenTypesToReverseIndex == INDEX_ALL || tokenTypesToReverseIndex.Contains( tokenType ) ) ) { return; // tokenType not of interest } IList<int> indexes; if ( !tokenTypeToStreamIndexesMap.TryGetValue( tokenType, out indexes ) || indexes == null ) { indexes = new List<int>(); // no list yet for this token type indexes.Add( streamIndex ); // not there yet, add tokenTypeToStreamIndexesMap[tokenType] = indexes; } else { if ( !indexes.Contains( streamIndex ) ) { indexes.Add( streamIndex ); // not there yet, add } } } /** <summary> * Track the indicated token type in the reverse index. Call this * repeatedly for each type or use variant with Set argument to * set all at once. * </summary> * * <param name="tokenType" /> */ public void reverseIndex( int tokenType ) { if ( tokenTypesToReverseIndex == null ) { tokenTypesToReverseIndex = new HashSet<int>(); } else if ( tokenTypesToReverseIndex == INDEX_ALL ) { return; } tokenTypesToReverseIndex.add( tokenType ); } /** <summary> * Track the indicated token types in the reverse index. Set * to INDEX_ALL to track all token types. * </summary> */ public void reverseIndex( HashSet<int> tokenTypes ) { tokenTypesToReverseIndex = tokenTypes; } /** <summary> * Given a node pointer, return its index into the node stream. * This is not its Token stream index. If there is no reverse map * from node to stream index or the map does not contain entries * for node's token type, a linear search of entire stream is used. * </summary> * * <remarks> * Return -1 if exact node pointer not in stream. * </remarks> */ public int getNodeIndex( object node ) { //System.out.println("get "+node); if ( tokenTypeToStreamIndexesMap == null ) { return getNodeIndexLinearly( node ); } int tokenType = adaptor.getType( node ); IList<int> indexes; if ( !tokenTypeToStreamIndexesMap.TryGetValue( tokenType, out indexes ) || indexes == null ) { //System.out.println("found linearly; stream index = "+getNodeIndexLinearly(node)); return getNodeIndexLinearly( node ); } for ( int i = 0; i < indexes.size(); i++ ) { int streamIndex = indexes[i]; object n = get( streamIndex ); if ( n == node ) { //System.out.println("found in index; stream index = "+streamIndexI); return streamIndex; // found it! } } return -1; } #endif } }
//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the MIT License (MIT). // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // //********************************************************* using System; using System.Collections.Generic; using Windows.Storage.Streams; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Navigation; using Windows.Devices.Bluetooth; using Windows.Devices.Bluetooth.Advertisement; using SDKTemplate; namespace BluetoothAdvertisement { /// <summary> /// An empty page that can be used on its own or navigated to within a Frame. /// </summary> public sealed partial class Scenario2_Publisher : Page { // The Bluetooth LE advertisement publisher class is used to control and customize Bluetooth LE advertising. private BluetoothLEAdvertisementPublisher publisher; // A pointer back to the main page is required to display status messages. private MainPage rootPage; /// <summary> /// Initializes the singleton application object. This is the first line of authored code /// executed, and as such is the logical equivalent of main() or WinMain(). /// </summary> public Scenario2_Publisher() { this.InitializeComponent(); // Create and initialize a new publisher instance. publisher = new BluetoothLEAdvertisementPublisher(); // We need to add some payload to the advertisement. A publisher without any payload // or with invalid ones cannot be started. We only need to configure the payload once // for any publisher. // Add a manufacturer-specific section: // First, let create a manufacturer data section var manufacturerData = new BluetoothLEManufacturerData(); // Then, set the company ID for the manufacturer data. Here we picked an unused value: 0xFFFE manufacturerData.CompanyId = 0xFFFE; // Finally set the data payload within the manufacturer-specific section // Here, use a 16-bit UUID: 0x1234 -> {0x34, 0x12} (little-endian) var writer = new DataWriter(); UInt16 uuidData = 0x1234; writer.WriteUInt16(uuidData); // Make sure that the buffer length can fit within an advertisement payload. Otherwise you will get an exception. manufacturerData.Data = writer.DetachBuffer(); // Add the manufacturer data to the advertisement publisher: publisher.Advertisement.ManufacturerData.Add(manufacturerData); // Display the information about the published payload PublisherPayloadBlock.Text = string.Format("Published payload information: CompanyId=0x{0}, ManufacturerData=0x{1}", manufacturerData.CompanyId.ToString("X"), uuidData.ToString("X")); // Display the current status of the publisher PublisherStatusBlock.Text = string.Format("Published Status: {0}, Error: {1}", publisher.Status, BluetoothError.Success); } /// <summary> /// Invoked when this page is about to be displayed in a Frame. /// /// We will enable/disable parts of the UI if the device doesn't support it. /// </summary> /// <param name="eventArgs">Event data that describes how this page was reached. The Parameter /// property is typically used to configure the page.</param> protected override void OnNavigatedTo(NavigationEventArgs e) { rootPage = MainPage.Current; // Attach a event handler to monitor the status of the publisher, which // can tell us whether the advertising has been serviced or is waiting to be serviced // due to lack of resources. It will also inform us of unexpected errors such as the Bluetooth // radio being turned off by the user. publisher.StatusChanged += OnPublisherStatusChanged; // Attach handlers for suspension to stop the publisher when the App is suspended. App.Current.Suspending += App_Suspending; App.Current.Resuming += App_Resuming; rootPage.NotifyUser("Press Run to start publisher.", NotifyType.StatusMessage); } /// <summary> /// Invoked immediately before the Page is unloaded and is no longer the current source of a parent Frame. /// </summary> /// <param name="e"> /// Event data that can be examined by overriding code. The event data is representative /// of the navigation that will unload the current Page unless canceled. The /// navigation can potentially be canceled by setting Cancel. /// </param> protected override void OnNavigatingFrom(NavigatingCancelEventArgs e) { // Remove local suspension handlers from the App since this page is no longer active. App.Current.Suspending -= App_Suspending; App.Current.Resuming -= App_Resuming; // Make sure to stop the publisher when leaving the context. Even if the publisher is not stopped, // advertising will be stopped automatically if the publisher is destroyed. publisher.Stop(); // Always unregister the handlers to release the resources to prevent leaks. publisher.StatusChanged -= OnPublisherStatusChanged; rootPage.NotifyUser("Navigating away. Publisher stopped.", NotifyType.StatusMessage); base.OnNavigatingFrom(e); } /// <summary> /// Invoked when application execution is being suspended. Application state is saved /// without knowing whether the application will be terminated or resumed with the contents /// of memory still intact. /// </summary> /// <param name="sender">The source of the suspend request.</param> /// <param name="e">Details about the suspend request.</param> private void App_Suspending(object sender, Windows.ApplicationModel.SuspendingEventArgs e) { // Make sure to stop the publisher on suspend. publisher.Stop(); // Always unregister the handlers to release the resources to prevent leaks. publisher.StatusChanged -= OnPublisherStatusChanged; rootPage.NotifyUser("App suspending. Publisher stopped.", NotifyType.StatusMessage); } /// <summary> /// Invoked when application execution is being resumed. /// </summary> /// <param name="sender">The source of the resume request.</param> /// <param name="e"></param> private void App_Resuming(object sender, object e) { publisher.StatusChanged += OnPublisherStatusChanged; } /// <summary> /// Invoked as an event handler when the Run button is pressed. /// </summary> /// <param name="sender">Instance that triggered the event.</param> /// <param name="e">Event data describing the conditions that led to the event.</param> private void RunButton_Click(object sender, RoutedEventArgs e) { // Calling publisher start will start the advertising if resources are available to do so publisher.Start(); rootPage.NotifyUser("Publisher started.", NotifyType.StatusMessage); } /// <summary> /// Invoked as an event handler when the Stop button is pressed. /// </summary> /// <param name="sender">Instance that triggered the event.</param> /// <param name="e">Event data describing the conditions that led to the event.</param> private void StopButton_Click(object sender, RoutedEventArgs e) { // Stopping the publisher will stop advertising the published payload publisher.Stop(); rootPage.NotifyUser("Publisher stopped.", NotifyType.StatusMessage); } /// <summary> /// Invoked as an event handler when the status of the publisher changes. /// </summary> /// <param name="publisher">Instance of publisher that triggered the event.</param> /// <param name="eventArgs">Event data containing information about the publisher status change event.</param> private async void OnPublisherStatusChanged( BluetoothLEAdvertisementPublisher publisher, BluetoothLEAdvertisementPublisherStatusChangedEventArgs eventArgs) { // This event handler can be used to monitor the status of the publisher. // We can catch errors if the publisher is aborted by the system BluetoothLEAdvertisementPublisherStatus status = eventArgs.Status; BluetoothError error = eventArgs.Error; // Update the publisher status displayed in the sample // Serialize UI update to the main UI thread await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { PublisherStatusBlock.Text = string.Format("Published Status: {0}, Error: {1}", status.ToString(), error.ToString()); }); } } }
// Copyright 2015 Google Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using UnityEngine; using System.Collections.Generic; using System; /// @cond namespace Gvr.Internal { // Represents a vr device that this plugin interacts with. public abstract class BaseVRDevice { private static BaseVRDevice device = null; protected BaseVRDevice() { Profile = GvrProfile.Default.Clone(); } public GvrProfile Profile { get; protected set; } public abstract void Init(); public abstract void SetVRModeEnabled(bool enabled); public abstract void SetDistortionCorrectionEnabled(bool enabled); public abstract void SetNeckModelScale(float scale); public virtual bool SupportsNativeDistortionCorrection(List<string> diagnostics) { return true; } public virtual bool RequiresNativeDistortionCorrection() { return leftEyeOrientation != 0 || rightEyeOrientation != 0; } public virtual bool SupportsNativeUILayer(List<string> diagnostics) { return true; } public virtual bool ShouldRecreateStereoScreen(int curWidth, int curHeight) { return this.RequiresNativeDistortionCorrection() && (curWidth != (int)recommendedTextureSize[0] || curHeight != (int)recommendedTextureSize[1]); } public virtual RenderTexture CreateStereoScreen() { float scale = GvrViewer.Instance.StereoScreenScale; #if UNITY_5_6_OR_NEWER // Unity halved the render texture size on 5.6, so we compensate here. scale *= 2.0f; #endif // UNITY_5_6_OR_NEWER int width = Mathf.RoundToInt(Screen.width * scale); int height = Mathf.RoundToInt(Screen.height * scale); if (this.RequiresNativeDistortionCorrection()) { width = (int)recommendedTextureSize[0]; height = (int)recommendedTextureSize[1]; } //Debug.Log("Creating new default stereo screen texture " // + width+ "x" + height + "."); var rt = new RenderTexture(width, height, 24, RenderTextureFormat.Default); rt.anisoLevel = 0; rt.antiAliasing = Mathf.Max(QualitySettings.antiAliasing, 1); return rt; } // Returns true if the URI was set as the device profile, else false. A default URI // is only accepted if the user has not scanned a QR code already. public virtual bool SetDefaultDeviceProfile(Uri uri) { return false; } public virtual void ShowSettingsDialog() { // Do nothing. } public Pose3D GetHeadPose() { return this.headPose; } protected MutablePose3D headPose = new MutablePose3D(); public Pose3D GetEyePose(GvrViewer.Eye eye) { switch(eye) { case GvrViewer.Eye.Left: return leftEyePose; case GvrViewer.Eye.Right: return rightEyePose; default: return null; } } protected MutablePose3D leftEyePose = new MutablePose3D(); protected MutablePose3D rightEyePose = new MutablePose3D(); public Matrix4x4 GetProjection(GvrViewer.Eye eye, GvrViewer.Distortion distortion = GvrViewer.Distortion.Distorted) { switch(eye) { case GvrViewer.Eye.Left: return distortion == GvrViewer.Distortion.Distorted ? leftEyeDistortedProjection : leftEyeUndistortedProjection; case GvrViewer.Eye.Right: return distortion == GvrViewer.Distortion.Distorted ? rightEyeDistortedProjection : rightEyeUndistortedProjection; default: return Matrix4x4.identity; } } protected Matrix4x4 leftEyeDistortedProjection; protected Matrix4x4 rightEyeDistortedProjection; protected Matrix4x4 leftEyeUndistortedProjection; protected Matrix4x4 rightEyeUndistortedProjection; public Rect GetViewport(GvrViewer.Eye eye, GvrViewer.Distortion distortion = GvrViewer.Distortion.Distorted) { switch(eye) { case GvrViewer.Eye.Left: return distortion == GvrViewer.Distortion.Distorted ? leftEyeDistortedViewport : leftEyeUndistortedViewport; case GvrViewer.Eye.Right: return distortion == GvrViewer.Distortion.Distorted ? rightEyeDistortedViewport : rightEyeUndistortedViewport; default: return new Rect(); } } protected Rect leftEyeDistortedViewport; protected Rect rightEyeDistortedViewport; protected Rect leftEyeUndistortedViewport; protected Rect rightEyeUndistortedViewport; protected Vector2 recommendedTextureSize; protected int leftEyeOrientation; protected int rightEyeOrientation; public bool tilted; public bool profileChanged; public bool backButtonPressed; public abstract void UpdateState(); public abstract void UpdateScreenData(); public abstract void Recenter(); public abstract void PostRender(RenderTexture stereoScreen); public virtual void OnPause(bool pause) { if (!pause) { UpdateScreenData(); } } public virtual void OnFocus(bool focus) { // Do nothing. } public virtual void OnApplicationQuit() { // Do nothing. } public virtual void Destroy() { if (device == this) { device = null; } } // Helper functions. protected void ComputeEyesFromProfile() { // Compute left eye matrices from screen and device params Matrix4x4 leftEyeView = Matrix4x4.identity; leftEyeView[0, 3] = -Profile.viewer.lenses.separation / 2; leftEyePose.Set(leftEyeView); float[] rect = new float[4]; Profile.GetLeftEyeVisibleTanAngles(rect); leftEyeDistortedProjection = MakeProjection(rect[0], rect[1], rect[2], rect[3], 1, 1000); Profile.GetLeftEyeNoLensTanAngles(rect); leftEyeUndistortedProjection = MakeProjection(rect[0], rect[1], rect[2], rect[3], 1, 1000); leftEyeUndistortedViewport = Profile.GetLeftEyeVisibleScreenRect(rect); leftEyeDistortedViewport = leftEyeUndistortedViewport; // Right eye matrices same as left ones but for some sign flippage. Matrix4x4 rightEyeView = leftEyeView; rightEyeView[0, 3] *= -1; rightEyePose.Set(rightEyeView); rightEyeDistortedProjection = leftEyeDistortedProjection; rightEyeDistortedProjection[0, 2] *= -1; rightEyeUndistortedProjection = leftEyeUndistortedProjection; rightEyeUndistortedProjection[0, 2] *= -1; rightEyeUndistortedViewport = leftEyeUndistortedViewport; rightEyeUndistortedViewport.x = 1 - rightEyeUndistortedViewport.xMax; rightEyeDistortedViewport = rightEyeUndistortedViewport; float width = Screen.width * (leftEyeUndistortedViewport.width+rightEyeDistortedViewport.width); float height = Screen.height * Mathf.Max(leftEyeUndistortedViewport.height, rightEyeUndistortedViewport.height); recommendedTextureSize = new Vector2(width, height); } private static Matrix4x4 MakeProjection(float l, float t, float r, float b, float n, float f) { Matrix4x4 m = Matrix4x4.zero; m[0, 0] = 2 * n / (r - l); m[1, 1] = 2 * n / (t - b); m[0, 2] = (r + l) / (r - l); m[1, 2] = (t + b) / (t - b); m[2, 2] = (n + f) / (n - f); m[2, 3] = 2 * n * f / (n - f); m[3, 2] = -1; return m; } public static BaseVRDevice GetDevice() { if (device == null) { #if UNITY_EDITOR device = new EditorDevice(); #elif UNITY_HAS_GOOGLEVR && (UNITY_ANDROID || UNITY_IPHONE) device = new UnityVRDevice(); #elif UNITY_ANDROID device = new AndroidDevice(); #elif UNITY_IOS device = new iOSDevice(); #else throw new InvalidOperationException("Unsupported device."); #endif // UNITY_EDITOR } return device; } } } /// @endcond
using System; using System.Collections; using System.Collections.Generic; using System.Runtime.InteropServices; using UnityEngine; using LitJson; using Batch; namespace Batch.Internal { public class UnlockModule : ModuleBase { internal UnlockModule (Bridge _bridge) : base(_bridge) { } #region Handlers public event RedeemAutomaticOfferHandler RedeemAutomaticOffer; public event RedeemURLCodeFoundHandler RedeemURLCodeFound; public event RedeemURLSuccessHandler RedeemURLSuccess; public event RedeemURLFailedHandler RedeemURLFailed; public event RedeemCodeSuccessHandler RedeemCodeSuccess; public event RedeemCodeFailedHandler RedeemCodeFailed; public event RestoreSuccessHandler RestoreSuccess; public event RestoreFailedHandler RestoreFailed; #endregion /// <summary> /// Redeems offer using a code. /// </summary> /// <param name="code">Code.</param> public void RedeemCode(string code) { if ( RedeemCodeSuccess == null ) { Logger.Error(false, "RedeemCode", "Cannot redeem a code without anything listening to RedeemCodeSuccess."); return; } if ( RedeemCodeFailed == null ) { Logger.Error(false, "RedeemCode", "Cannot redeem a code without anything listening to RedeemCodeFailed."); return; } try { JsonData data = new JsonData(); data["code"] = code; bridge.Call("redeemCode", JsonMapper.ToJson(data)); } catch(Exception e) { Logger.Error(true, "RedeemCode", e); } } /// <summary> /// Restore previously unlocked features. /// </summary> public void Restore() { if ( RestoreSuccess == null ) { Logger.Error(false, "Restore", "Cannot perform restore without anything listening to RestoreSuccess."); return; } if ( RestoreFailed == null ) { Logger.Error(false, "Restore", "Cannot perform restore without anything listening to RestoreFailed."); return; } bridge.Call("restore", ""); } public void OnRedeemAutomaticOffer(string response) { try { Response answer = new Response(response); // Treat the offer. Offer offer = answer.GetOffer(); if (offer == null) { throw new NullReferenceException("The returned offer is null."); } if (RedeemAutomaticOffer != null) { RedeemAutomaticOffer(offer); } } catch (Exception e) { Logger.Error(true, "onRedeemAutomaticOffer", e); } } public void OnRedeemURLSuccess(string response) { try { Response answer = new Response(response); // Treat the offer. Offer offer = answer.GetOffer(); if (offer == null) { throw new NullReferenceException("The returned offer is null."); } string code = answer.GetCode(); if (code == null) { throw new NullReferenceException("The returned code is null."); } if (RedeemURLSuccess != null) { RedeemURLSuccess(code, offer); } } catch (Exception e) { Logger.Error(true, "onRedeemURLSuccess", e); if (RedeemURLFailed != null) { RedeemURLFailed(null, FailReason.UNEXPECTED_ERROR, null); } } } public void OnRedeemURLFailed(string response) { try { Response answer = new Response(response); FailReason failReason = answer.GetFailReason(); string code = answer.GetFailedCode(); if (code == null) { throw new NullReferenceException("The returned invalid code is null."); } if (RedeemURLFailed != null) { RedeemURLFailed(code, failReason, answer.GetCodeErrorInfos()); } } catch (Exception e) { Logger.Error(true, "onRedeemURLFailed", e); if (RedeemURLFailed != null) { RedeemURLFailed(null, FailReason.UNEXPECTED_ERROR, null); } } } public void OnRedeemURLCodeFound(string response) { try { Response answer = new Response(response); string code = answer.GetCode(); if (code == null) { throw new NullReferenceException("The returned code is null."); } if (RedeemURLCodeFound != null) { RedeemURLCodeFound(code); } } catch (Exception e) { Logger.Error(true, "onRedeemURLCodeFound", e); } } public void OnRedeemCodeSuccess(string response) { try { Response answer = new Response(response); // Treat the offer. Offer offer = answer.GetOffer(); if (offer == null) { throw new NullReferenceException("The returned offer is null."); } string code = answer.GetCode(); if (code == null) { throw new NullReferenceException("The returned code is null."); } if (RedeemCodeSuccess != null) { RedeemCodeSuccess(code, offer); } } catch (Exception e) { Logger.Error(true, "onRedeemCodeSuccess", e); if (RedeemCodeFailed != null) { RedeemCodeFailed(null, FailReason.UNEXPECTED_ERROR, null); } } } public void OnRedeemCodeFailed(string response) { try { Response answer = new Response(response); FailReason failReason = answer.GetFailReason(); string code = answer.GetFailedCode(); if (code == null) { throw new NullReferenceException("The returned invalid code is null."); } if (RedeemCodeFailed != null) { RedeemCodeFailed(code, failReason, answer.GetCodeErrorInfos()); } } catch (Exception e) { Logger.Error(true, "onRedeemCodeFailed", e); if (RedeemCodeFailed != null) { RedeemCodeFailed(null, FailReason.UNEXPECTED_ERROR, null); } } } public void OnRestoreSuccess(string response) { try { Response answer = new Response(response); List<Feature> features = answer.GetFeatures(); if (features == null) { throw new NullReferenceException("The returned features are null."); } if (RestoreSuccess != null) { RestoreSuccess(features); } } catch (Exception e) { Logger.Error(true, "onRestoreSuccess", e); if (RestoreFailed != null) { RestoreFailed(FailReason.UNEXPECTED_ERROR); } } } public void OnRestoreFailed(string response) { try { Response answer = new Response(response); FailReason failReason = answer.GetFailReason(); if (RestoreFailed != null) { RestoreFailed(failReason); } } catch (Exception e) { Logger.Error(true, "onRestoreFailed", e); if (RestoreFailed != null) { RestoreFailed(FailReason.UNEXPECTED_ERROR); } } } public bool HasRedeemAutomaticOffer() { return RedeemAutomaticOffer != null; } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using NuGet.Lucene.IO; using NuGet.Lucene.Web.Util; namespace NuGet.Lucene.Web.Symbols { public class SymbolSource : ISymbolSource { private const string PdbExtension = ".pdb"; private const string ExeExtension = ".exe"; private const string DllExtension = ".dll"; public string SymbolsPath { get; set; } public SymbolTools SymbolTools { get; set; } public bool Enabled { get { return SymbolTools.ToolsAvailable; } } public bool SymbolsAvailable { get { return Directory.Exists(SymbolsPath) && Directory.EnumerateDirectories(SymbolsPath, "*.pdb", SearchOption.TopDirectoryOnly).Any(); } } public bool AreSymbolsPresentFor(IPackageName package) { return File.Exists(GetNupkgPath(package)); } public async Task AddSymbolsAsync(IPackage package, string symbolSourceUri) { try { await CopyNupkgToTargetPathAsync(package); await ProcessSymbolsAsync(package, symbolSourceUri); } finally { var disposablePackage = package as IDisposable; if (disposablePackage != null) { disposablePackage.Dispose(); } } } protected async Task CopyNupkgToTargetPathAsync(IPackage package) { var targetFile = new FileInfo(GetNupkgPath(package)); if (targetFile.Directory != null && !targetFile.Directory.Exists) { targetFile.Directory.Create(); } else if (targetFile.Exists) { targetFile.Delete(); } var fastZipPackage = package as FastZipPackage; if (fastZipPackage != null) { File.Move(fastZipPackage.GetFileLocation(), targetFile.FullName); fastZipPackage.FileLocation = targetFile.FullName; return; } using (var sourceStream = package.GetStream()) { using (var targetStream = targetFile.Open(FileMode.Create, FileAccess.Write)) { await sourceStream.CopyToAsync(targetStream); } } } public Task RemoveSymbolsAsync(IPackageName package) { var nupkgPath = GetNupkgPath(package); if (File.Exists(nupkgPath)) { File.Delete(nupkgPath); } return Task.FromResult(true); } public Stream OpenFile(string relativePath) { var fullPath = Path.Combine(SymbolsPath, relativePath.Replace('/', Path.DirectorySeparatorChar)); if (!File.Exists(fullPath)) { return null; } return File.Open(fullPath, FileMode.Open, FileAccess.Read, FileShare.Read); } public Stream OpenPackageSourceFile(IPackageName package, string relativePath) { relativePath = relativePath.Replace('/', Path.DirectorySeparatorChar); var packagePath = GetNupkgPath(package); if (!File.Exists(packagePath)) return null; var srcPath = Path.Combine("src", relativePath); var packageFile = FastZipPackage.Open(packagePath, new byte[0]); var file = packageFile.GetFiles().SingleOrDefault(f => f.Path.Equals(srcPath, StringComparison.InvariantCultureIgnoreCase)); return file != null ? new PackageDisposingStream(packageFile, file.GetStream()) : null; } public async Task ProcessSymbolsAsync(IPackage package, string symbolSourceUri) { var files = package.GetFiles().Where(IsSymbolSourceFile); using (var tempFolder = CreateTempFolderForPackage(package)) { foreach (var file in files) { var filePath = Path.Combine(tempFolder.Path, file.Path); var fileDir = Path.GetDirectoryName(filePath); if (fileDir != null && !Directory.Exists(fileDir)) { Directory.CreateDirectory(fileDir); } using (var writeStream = File.Open(filePath, FileMode.Create, FileAccess.Write)) { using (var readStream = file.GetStream()) { await readStream.CopyToAsync(writeStream); } } await ProcessSymbolFileAsync(package, filePath, symbolSourceUri); } } } private static bool IsSymbolSourceFile(IPackageFile packageFile) { return IsPathExtensionAnyOf(packageFile.Path, PdbExtension, ExeExtension, DllExtension); } private static bool IsPathExtensionAnyOf(string filePath, params string[] extensions) { var fileExtension = Path.GetExtension(filePath); if (string.IsNullOrEmpty(fileExtension)) { return false; } var extensionComparer = StringComparison.InvariantCultureIgnoreCase; return extensions.Any(extension => extension.Equals(fileExtension, extensionComparer)); } public async Task ProcessSymbolFileAsync(IPackage package, string symbolFilePath, string symbolSourceUri) { if (IsPdbFile(symbolFilePath)) { await MapSourcesAsync(package, symbolFilePath, symbolSourceUri); } await SymbolTools.IndexSymbolFile(package, symbolFilePath); } private async Task MapSourcesAsync(IPackage package, string symbolFilePath, string symbolSourceUri) { var referencedSources = (await SymbolTools.GetSources(symbolFilePath)).ToList(); var sourceFiles = new HashSet<string>(package.GetFiles("src").Select(f => f.Path.Substring(4))); if (referencedSources.Any() && sourceFiles.Any()) { var sourceMapper = new SymbolSourceMapper(); var mappings = sourceMapper.CreateSourceMappingIndex(package, symbolSourceUri, referencedSources, sourceFiles); await SymbolTools.MapSourcesAsync(symbolFilePath, mappings); } } private static bool IsPdbFile(string filePath) { return IsPathExtensionAnyOf(filePath, PdbExtension); } public virtual string GetNupkgPath(IPackageName package) { return Path.Combine(SymbolsPath, package.Id, package.Id + "." + package.Version + ".symbols.nupkg"); } protected virtual string GetTempFolderPathForPackage(IPackageName package) { return Path.Combine(SymbolsPath, package.Id + "-" + package.Version + ".tmp"); } /// <summary> /// Creates a temp directory that gets deleted when the returned object is disposed /// </summary> /// <param name="package"></param> /// <returns>An IDisposable that deletes the folder when disposed</returns> protected TempFolder CreateTempFolderForPackage(IPackageName package) { return new TempFolder(GetTempFolderPathForPackage(package)); } class PackageDisposingStream : ReadStream { private readonly IFastZipPackage package; public PackageDisposingStream(IFastZipPackage package, Stream stream) : base(stream) { this.package = package; } protected override void Dispose(bool disposing) { base.Dispose(disposing); package.Dispose(); } } } }
//----------------------------------------------------------------------- // <copyright file="FlowFlattenMergeSpec.cs" company="Akka.NET Project"> // Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com> // Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading.Tasks; using Akka.Streams.Dsl; using Akka.Streams.TestKit; using Akka.Streams.TestKit.Tests; using Akka.TestKit; using Akka.Util.Internal; using FluentAssertions; using Xunit; using Xunit.Abstractions; namespace Akka.Streams.Tests.Dsl { public class FlowFlattenMergeSpec : AkkaSpec { private ActorMaterializer Materializer { get; } public FlowFlattenMergeSpec(ITestOutputHelper helper) : base(helper) { Materializer = ActorMaterializer.Create(Sys); } private Source<int, NotUsed> Src10(int i) => Source.From(Enumerable.Range(i, 10)); private Source<int, NotUsed> Blocked => Source.FromTask(new TaskCompletionSource<int>().Task); private Sink<int, Task<IEnumerable<int>>> ToSeq => Flow.Create<int>().Grouped(1000).ToMaterialized(Sink.First<IEnumerable<int>>(), Keep.Right); private Sink<int, Task<ImmutableHashSet<int>>> ToSet => Flow.Create<int>() .Grouped(1000) .Select(x => x.ToImmutableHashSet()) .ToMaterialized(Sink.First<ImmutableHashSet<int>>(), Keep.Right); [Fact] public void A_FlattenMerge_must_work_in_the_nominal_case() { var task = Source.From(new[] {Src10(0), Src10(10), Src10(20), Src10(30)}) .MergeMany(4, s => s) .RunWith(ToSet, Materializer); task.Wait(TimeSpan.FromSeconds(1)).Should().BeTrue(); task.Result.ShouldAllBeEquivalentTo(Enumerable.Range(0, 40)); } [Fact] public void A_FlattenMerge_must_not_be_held_back_by_one_slow_stream() { var task = Source.From(new[] { Src10(0), Src10(10), Blocked, Src10(20), Src10(30) }) .MergeMany(3, s => s) .Take(40) .RunWith(ToSet, Materializer); task.Wait(TimeSpan.FromSeconds(1)).Should().BeTrue(); task.Result.ShouldAllBeEquivalentTo(Enumerable.Range(0, 40)); } [Fact] public void A_FlattenMerge_must_respect_breadth() { var task = Source.From(new[] { Src10(0), Src10(10), Src10(20), Blocked, Blocked, Src10(30) }) .MergeMany(3, s => s) .Take(40) .RunWith(ToSeq, Materializer); task.Wait(TimeSpan.FromSeconds(1)).Should().BeTrue(); task.Result.Take(30).ShouldAllBeEquivalentTo(Enumerable.Range(0, 30)); task.Result.Drop(30).ShouldAllBeEquivalentTo(Enumerable.Range(30, 10)); } [Fact] public void A_FlattenMerge_must_propagate_early_failure_from_main_stream() { var ex = new TestException("buh"); var future = Source.Failed<Source<int, NotUsed>>(ex) .MergeMany(1, x => x) .RunWith(Sink.First<int>(), Materializer); future.Invoking(f => f.Wait(TimeSpan.FromSeconds(1))).ShouldThrow<TestException>().And.Should().Be(ex); } [Fact] public void A_FlattenMerge_must_propage_late_failure_from_main_stream() { var ex = new TestException("buh"); var future = Source.Combine(Source.From(new[] {Blocked, Blocked}), Source.Failed<Source<int, NotUsed>>(ex), i => new Merge<Source<int, NotUsed>>(i)) .MergeMany(10, x => x) .RunWith(Sink.First<int>(), Materializer); future.Invoking(f => f.Wait(TimeSpan.FromSeconds(1))).ShouldThrow<TestException>().And.Should().Be(ex); } [Fact] public void A_FlattenMerge_must_propagate_failure_from_map_function() { var ex = new TestException("buh"); var future = Source.From(Enumerable.Range(1, 3)) .MergeMany(10, x => { if (x == 3) throw ex; return Blocked; }) .RunWith(Sink.First<int>(), Materializer); future.Invoking(f => f.Wait(TimeSpan.FromSeconds(1))).ShouldThrow<TestException>().And.Should().Be(ex); } [Fact] public void A_FlattenMerge_must_bubble_up_substream_exceptions() { var ex = new TestException("buh"); var future = Source.From(new[] { Blocked, Blocked, Source.Failed<int>(ex) }) .MergeMany(10, x => x) .RunWith(Sink.First<int>(), Materializer); future.Invoking(f => f.Wait(TimeSpan.FromSeconds(1))).ShouldThrow<TestException>().And.Should().Be(ex); } [Fact] public void A_FlattenMerge_must_cancel_substreams_when_failing_from_main_stream() { var p1 = this.CreatePublisherProbe<int>(); var p2 = this.CreatePublisherProbe<int>(); var ex = new TestException("buh"); var p = new TaskCompletionSource<Source<int, NotUsed>>(); Source.Combine( Source.From(new[] {Source.FromPublisher(p1), Source.FromPublisher(p2)}), Source.FromTask(p.Task), i => new Merge<Source<int, NotUsed>>(i)) .MergeMany(5, x => x) .RunWith(Sink.First<int>(), Materializer); p1.ExpectRequest(); p2.ExpectRequest(); p.SetException(ex); p1.ExpectCancellation(); p2.ExpectCancellation(); } [Fact] public void A_FlattenMerge_must_cancel_substreams_when_failing_from_substream() { var p1 = this.CreatePublisherProbe<int>(); var p2 = this.CreatePublisherProbe<int>(); var ex = new TestException("buh"); var p = new TaskCompletionSource<int>(); Source.From(new[] {Source.FromPublisher(p1), Source.FromPublisher(p2), Source.FromTask(p.Task)}) .MergeMany(5, x => x) .RunWith(Sink.First<int>(), Materializer); p1.ExpectRequest(); p2.ExpectRequest(); p.SetException(ex); p1.ExpectCancellation(); p2.ExpectCancellation(); } [Fact] public void A_FlattenMerge_must_cancel_substreams_when_failing_map_function() { var settings = ActorMaterializerSettings.Create(Sys).WithSyncProcessingLimit(1).WithInputBuffer(1, 1); var materializer = ActorMaterializer.Create(Sys, settings); var p = this.CreatePublisherProbe<int>(); var ex = new TestException("buh"); var latch = new TestLatch(); Source.From(Enumerable.Range(1, 3)).MergeMany(10, i => { if (i == 1) return Source.FromPublisher(p); latch.Ready(TimeSpan.FromSeconds(3)); throw ex; }).RunWith(Sink.First<int>(), materializer); p.ExpectRequest(); latch.CountDown(); p.ExpectCancellation(); } [Fact] public void A_FlattenMerge_must_cancel_substreams_when_being_cancelled() { var p1 = this.CreatePublisherProbe<int>(); var p2 = this.CreatePublisherProbe<int>(); var sink = Source.From(new[] {Source.FromPublisher(p1), Source.FromPublisher(p2)}) .MergeMany(5, x => x) .RunWith(this.SinkProbe<int>(), Materializer); sink.Request(1); p1.ExpectRequest(); p2.ExpectRequest(); sink.Cancel(); p1.ExpectCancellation(); p2.ExpectCancellation(); } [Fact] public void A_FlattenMerge_must_work_with_many_concurrently_queued_events() { const int noOfSources = 100; var p = Source.From(Enumerable.Range(0, noOfSources).Select(i => Src10(10*i))) .MergeMany(int.MaxValue, x => x) .RunWith(this.SinkProbe<int>(), Materializer); p.EnsureSubscription(); p.ExpectNoMsg(TimeSpan.FromSeconds(1)); var elems = p.Within(TimeSpan.FromSeconds(1), () => Enumerable.Range(1, noOfSources * 10).Select(_ => p.RequestNext()).ToArray()); p.ExpectComplete(); elems.ShouldAllBeEquivalentTo(Enumerable.Range(0, noOfSources * 10)); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using EnvDTE; using Microsoft.VisualStudio.Shell.Interop; using NuGet.VisualStudio.Resources; namespace NuGet.VisualStudio { public class VsPackageManager : PackageManager, IVsPackageManager { private readonly ISharedPackageRepository _sharedRepository; private readonly IDictionary<string, IProjectManager> _projects; private readonly ISolutionManager _solutionManager; private readonly IRecentPackageRepository _recentPackagesRepository; private readonly VsPackageInstallerEvents _packageEvents; public VsPackageManager(ISolutionManager solutionManager, IPackageRepository sourceRepository, IFileSystem fileSystem, ISharedPackageRepository sharedRepository, IRecentPackageRepository recentPackagesRepository, VsPackageInstallerEvents packageEvents) : base(sourceRepository, new DefaultPackagePathResolver(fileSystem), fileSystem, sharedRepository) { _solutionManager = solutionManager; _sharedRepository = sharedRepository; _recentPackagesRepository = recentPackagesRepository; _packageEvents = packageEvents; _projects = new Dictionary<string, IProjectManager>(StringComparer.OrdinalIgnoreCase); } internal bool AddToRecent { get; set; } internal void EnsureCached(Project project) { if (_projects.ContainsKey(project.UniqueName)) { return; } _projects[project.UniqueName] = CreateProjectManager(project); } public virtual IProjectManager GetProjectManager(Project project) { EnsureCached(project); IProjectManager projectManager; bool projectExists = _projects.TryGetValue(project.UniqueName, out projectManager); Debug.Assert(projectExists, "Unknown project"); return projectManager; } private IProjectManager CreateProjectManager(Project project) { // Create the project system IProjectSystem projectSystem = VsProjectSystemFactory.CreateProjectSystem(project); var repository = new PackageReferenceRepository(projectSystem, _sharedRepository); // Ensure the logger is null while registering the repository FileSystem.Logger = null; Logger = null; // Ensure that this repository is registered with the shared repository if it needs to be repository.RegisterIfNecessary(); // The source repository of the project is an aggregate since it might need to look for all // available packages to perform updates on dependent packages var sourceRepository = CreateProjectManagerSourceRepository(); var projectManager = new ProjectManager(sourceRepository, PathResolver, projectSystem, repository); // The package reference repository also provides constraints for packages (via the allowedVersions attribute) projectManager.ConstraintProvider = repository; return projectManager; } public void InstallPackage( IEnumerable<Project> projects, IPackage package, IEnumerable<PackageOperation> operations, bool ignoreDependencies, bool allowPrereleaseVersions, ILogger logger, IPackageOperationEventListener packageOperationEventListener) { if (package == null) { throw new ArgumentNullException("package"); } if (operations == null) { throw new ArgumentNullException("operations"); } if (projects == null) { throw new ArgumentNullException("projectManagers"); } ExecuteOperationsWithPackage( projects, package, operations, projectManager => AddPackageReference(projectManager, package.Id, package.Version, ignoreDependencies, allowPrereleaseVersions), logger, packageOperationEventListener); } public virtual void InstallPackage(IProjectManager projectManager, string packageId, SemanticVersion version, bool ignoreDependencies, bool allowPrereleaseVersions, ILogger logger) { InitializeLogger(logger, projectManager); IPackage package = PackageHelper.ResolvePackage(SourceRepository, LocalRepository, packageId, version, allowPrereleaseVersions); RunSolutionAction(() => { InstallPackage(package, ignoreDependencies, allowPrereleaseVersions); AddPackageReference(projectManager, package.Id, package.Version, ignoreDependencies, allowPrereleaseVersions); }); // Add package to recent repository AddPackageToRecentRepository(package); } public void InstallPackage(IProjectManager projectManager, IPackage package, IEnumerable<PackageOperation> operations, bool ignoreDependencies, bool allowPrereleaseVersions, ILogger logger) { if (package == null) { throw new ArgumentNullException("package"); } if (operations == null) { throw new ArgumentNullException("operations"); } ExecuteOperationsWithPackage( projectManager, package, operations, () => AddPackageReference(projectManager, package.Id, package.Version, ignoreDependencies, allowPrereleaseVersions), logger); } public void UninstallPackage(IProjectManager projectManager, string packageId, SemanticVersion version, bool forceRemove, bool removeDependencies) { UninstallPackage(projectManager, packageId, version, forceRemove, removeDependencies, NullLogger.Instance); } public virtual void UninstallPackage(IProjectManager projectManager, string packageId, SemanticVersion version, bool forceRemove, bool removeDependencies, ILogger logger) { EventHandler<PackageOperationEventArgs> uninstallingHandler = (sender, e) => { _packageEvents.NotifyUninstalling(e); }; EventHandler<PackageOperationEventArgs> uninstalledHandler = (sender, e) => { _packageEvents.NotifyUninstalled(e); }; try { InitializeLogger(logger, projectManager); bool appliesToProject; IPackage package = FindLocalPackage(projectManager, packageId, version, CreateAmbiguousUninstallException, out appliesToProject); PackageUninstalling += uninstallingHandler; PackageUninstalled += uninstalledHandler; if (appliesToProject) { RemovePackageReference(projectManager, packageId, forceRemove, removeDependencies); } else { UninstallPackage(package, forceRemove, removeDependencies); } } finally { PackageUninstalling -= uninstallingHandler; PackageUninstalled -= uninstalledHandler; } } public void UpdatePackage( IEnumerable<Project> projects, IPackage package, IEnumerable<PackageOperation> operations, bool updateDependencies, bool allowPrereleaseVersions, ILogger logger, IPackageOperationEventListener packageOperationEventListener) { if (operations == null) { throw new ArgumentNullException("operations"); } if (projects == null) { throw new ArgumentNullException("projects"); } ExecuteOperationsWithPackage( projects, package, operations, projectManager => UpdatePackageReference(projectManager, package.Id, package.Version, updateDependencies, allowPrereleaseVersions), logger, packageOperationEventListener); } public virtual void UpdatePackage(IProjectManager projectManager, string packageId, SemanticVersion version, bool updateDependencies, bool allowPrereleaseVersions, ILogger logger) { UpdatePackage(projectManager, packageId, () => UpdatePackageReference(projectManager, packageId, version, updateDependencies, allowPrereleaseVersions), () => SourceRepository.FindPackage(packageId, version, allowPrereleaseVersions, allowUnlisted: false), updateDependencies, allowPrereleaseVersions, logger); } private void UpdatePackage(IProjectManager projectManager, string packageId, Action projectAction, Func<IPackage> resolvePackage, bool updateDependencies, bool allowPrereleaseVersions, ILogger logger) { try { InitializeLogger(logger, projectManager); bool appliesToProject; IPackage package = FindLocalPackageForUpdate(projectManager, packageId, out appliesToProject); // Find the package we're going to update to IPackage newPackage = resolvePackage(); if (newPackage != null && package.Version != newPackage.Version) { if (appliesToProject) { RunSolutionAction(projectAction); } else { // We might be updating a solution only package UpdatePackage(newPackage, updateDependencies, allowPrereleaseVersions); } // Add package to recent repository AddPackageToRecentRepository(newPackage); } else { Logger.Log(MessageLevel.Info, VsResources.NoUpdatesAvailable, packageId); } } finally { ClearLogger(logger, projectManager); } } public void UpdatePackage(IProjectManager projectManager, IPackage package, IEnumerable<PackageOperation> operations, bool updateDependencies, bool allowPrereleaseVersions, ILogger logger) { if (package == null) { throw new ArgumentNullException("package"); } if (operations == null) { throw new ArgumentNullException("operations"); } ExecuteOperationsWithPackage(projectManager, package, operations, () => UpdatePackageReference(projectManager, package.Id, package.Version, updateDependencies, allowPrereleaseVersions), logger); } public void UpdatePackage(string packageId, IVersionSpec versionSpec, bool updateDependencies, bool allowPrereleaseVersions, ILogger logger, IPackageOperationEventListener eventListener) { UpdatePackage(packageId, projectManager => UpdatePackageReference(projectManager, packageId, versionSpec, updateDependencies, allowPrereleaseVersions), () => SourceRepository.FindPackage(packageId, versionSpec, allowPrereleaseVersions, allowUnlisted: false), updateDependencies, allowPrereleaseVersions, logger, eventListener); } public void UpdatePackage(string packageId, SemanticVersion version, bool updateDependencies, bool allowPrereleaseVersions, ILogger logger, IPackageOperationEventListener eventListener) { UpdatePackage(packageId, projectManager => UpdatePackageReference(projectManager, packageId, version, updateDependencies, allowPrereleaseVersions), () => SourceRepository.FindPackage(packageId, version, allowPrereleaseVersions, allowUnlisted: false), updateDependencies, allowPrereleaseVersions, logger, eventListener); } public void UpdatePackages(bool updateDependencies, bool allowPrereleaseVersions, ILogger logger, IPackageOperationEventListener eventListener) { UpdatePackages(updateDependencies, safeUpdate: false, allowPrereleaseVersions: allowPrereleaseVersions, logger: logger, eventListener: eventListener); } public void UpdatePackages(IProjectManager projectManager, bool updateDependencies, bool allowPrereleaseVersions, ILogger logger) { UpdatePackages(projectManager, updateDependencies, safeUpdate: false, allowPrereleaseVersions: allowPrereleaseVersions, logger: logger); } public void SafeUpdatePackages(IProjectManager projectManager, bool updateDependencies, bool allowPrereleaseVersions, ILogger logger) { UpdatePackages(projectManager, updateDependencies, safeUpdate: true, allowPrereleaseVersions: allowPrereleaseVersions, logger: logger); } public void SafeUpdatePackage(string packageId, bool updateDependencies, bool allowPrereleaseVersions, ILogger logger, IPackageOperationEventListener eventListener) { UpdatePackage(packageId, projectManager => UpdatePackageReference(projectManager, packageId, GetSafeRange(projectManager, packageId), updateDependencies, allowPrereleaseVersions), () => SourceRepository.FindPackage(packageId, GetSafeRange(packageId), allowPrereleaseVersions: false, allowUnlisted: false), updateDependencies, allowPrereleaseVersions, logger, eventListener); } public void SafeUpdatePackage(IProjectManager projectManager, string packageId, bool updateDependencies, bool allowPrereleaseVersions, ILogger logger) { UpdatePackage(projectManager, packageId, () => UpdatePackageReference(projectManager, packageId, GetSafeRange(projectManager, packageId), updateDependencies, allowPrereleaseVersions), () => SourceRepository.FindPackage(packageId, GetSafeRange(packageId), allowPrereleaseVersions: false, allowUnlisted: false), updateDependencies, allowPrereleaseVersions, logger); } public void SafeUpdatePackages(bool updateDependencies, bool allowPrereleaseVersions, ILogger logger, IPackageOperationEventListener eventListener) { UpdatePackages(updateDependencies, safeUpdate: true, allowPrereleaseVersions: allowPrereleaseVersions, logger: logger, eventListener: eventListener); } protected override void ExecuteUninstall(IPackage package) { // Check if the package is in use before removing it if (!_sharedRepository.IsReferenced(package.Id, package.Version)) { base.ExecuteUninstall(package); } } protected override void OnInstalled(PackageOperationEventArgs e) { base.OnInstalled(e); AddPackageToRecentRepository(e.Package, updateOnly: true); } private IPackage FindLocalPackageForUpdate(IProjectManager projectManager, string packageId, out bool appliesToProject) { return FindLocalPackage(projectManager, packageId, null /* version */, CreateAmbiguousUpdateException, out appliesToProject); } private IPackage FindLocalPackage(IProjectManager projectManager, string packageId, SemanticVersion version, Func<IProjectManager, IList<IPackage>, Exception> getAmbiguousMatchException, out bool appliesToProject) { IPackage package = null; bool existsInProject = false; appliesToProject = false; if (projectManager != null) { // Try the project repository first package = projectManager.LocalRepository.FindPackage(packageId, version); existsInProject = package != null; } // Fallback to the solution repository (it might be a solution only package) if (package == null) { if (version != null) { // Get the exact package package = LocalRepository.FindPackage(packageId, version); } else { // Get all packages by this name to see if we find an ambiguous match var packages = LocalRepository.FindPackagesById(packageId).ToList(); if (packages.Count > 1) { throw getAmbiguousMatchException(projectManager, packages); } // Pick the only one of default if none match package = packages.SingleOrDefault(); } } // Can't find the package in the solution or in the project then fail if (package == null) { throw new InvalidOperationException( String.Format(CultureInfo.CurrentCulture, VsResources.UnknownPackage, packageId)); } appliesToProject = IsProjectLevel(package); if (appliesToProject) { if (!existsInProject) { if (_sharedRepository.IsReferenced(package.Id, package.Version)) { // If the package doesn't exist in the project and is referenced by other projects // then fail. if (projectManager != null) { if (version == null) { throw new InvalidOperationException( String.Format(CultureInfo.CurrentCulture, VsResources.UnknownPackageInProject, package.Id, projectManager.Project.ProjectName)); } throw new InvalidOperationException( String.Format(CultureInfo.CurrentCulture, VsResources.UnknownPackageInProject, package.GetFullName(), projectManager.Project.ProjectName)); } } else { // The operation applies to solution level since it's not installed in the current project // but it is installed in some other project appliesToProject = false; } } } // Can't have a project level operation if no project was specified if (appliesToProject && projectManager == null) { throw new InvalidOperationException(VsResources.ProjectNotSpecified); } return package; } private IPackage FindLocalPackage(string packageId, out bool appliesToProject) { // It doesn't matter if there are multiple versions of the package installed at solution level, // we just want to know that one exists. var packages = LocalRepository.FindPackagesById(packageId).ToList(); // Can't find the package in the solution. if (!packages.Any()) { throw new InvalidOperationException( String.Format(CultureInfo.CurrentCulture, VsResources.UnknownPackage, packageId)); } IPackage package = packages.FirstOrDefault(); appliesToProject = IsProjectLevel(package); if (!appliesToProject) { if (packages.Count > 1) { throw CreateAmbiguousUpdateException(projectManager: null, packages: packages); } } else if (!_sharedRepository.IsReferenced(package.Id, package.Version)) { // If this package applies to a project but isn't installed in any project then // it's probably a borked install. throw new InvalidOperationException( String.Format(CultureInfo.CurrentCulture, VsResources.PackageNotInstalledInAnyProject, packageId)); } return package; } /// <summary> /// Check to see if this package applies to a project based on 2 criteria: /// 1. The package has project content (i.e. content that can be applied to a project lib or content files) /// 2. The package is referenced by any other project /// /// This logic will probably fail in one edge case. If there is a meta package that applies to a project /// that ended up not being installed in any of the projects and it only exists at solution level. /// If this happens, then we think that the following operation applies to the solution instead of showing an error. /// To solve that edge case we'd have to walk the graph to find out what the package applies to. /// </summary> public bool IsProjectLevel(IPackage package) { return package.HasProjectContent() || _sharedRepository.IsReferenced(package.Id, package.Version); } private Exception CreateAmbiguousUpdateException(IProjectManager projectManager, IList<IPackage> packages) { if (projectManager != null && packages.Any(IsProjectLevel)) { return new InvalidOperationException( String.Format(CultureInfo.CurrentCulture, VsResources.UnknownPackageInProject, packages[0].Id, projectManager.Project.ProjectName)); } return new InvalidOperationException( String.Format(CultureInfo.CurrentCulture, VsResources.AmbiguousUpdate, packages[0].Id)); } private Exception CreateAmbiguousUninstallException(IProjectManager projectManager, IList<IPackage> packages) { if (projectManager != null && packages.Any(IsProjectLevel)) { return new InvalidOperationException( String.Format(CultureInfo.CurrentCulture, VsResources.AmbiguousProjectLevelUninstal, packages[0].Id, projectManager.Project.ProjectName)); } return new InvalidOperationException( String.Format(CultureInfo.CurrentCulture, VsResources.AmbiguousUninstall, packages[0].Id)); } private void RemovePackageReference(IProjectManager projectManager, string packageId, bool forceRemove, bool removeDependencies) { RunProjectAction(projectManager, () => projectManager.RemovePackageReference(packageId, forceRemove, removeDependencies)); } private void UpdatePackageReference(IProjectManager projectManager, string packageId, SemanticVersion version, bool updateDependencies, bool allowPrereleaseVersions) { RunProjectAction(projectManager, () => projectManager.UpdatePackageReference(packageId, version, updateDependencies, allowPrereleaseVersions)); } private void UpdatePackageReference(IProjectManager projectManager, string packageId, IVersionSpec versionSpec, bool updateDependencies, bool allowPrereleaseVersions) { RunProjectAction(projectManager, () => projectManager.UpdatePackageReference(packageId, versionSpec, updateDependencies, allowPrereleaseVersions)); } private void AddPackageReference(IProjectManager projectManager, string packageId, SemanticVersion version, bool ignoreDependencies, bool allowPrereleaseVersions) { RunProjectAction(projectManager, () => projectManager.AddPackageReference(packageId, version, ignoreDependencies, allowPrereleaseVersions)); } private void ExecuteOperationsWithPackage(IEnumerable<Project> projects, IPackage package, IEnumerable<PackageOperation> operations, Action<IProjectManager> projectAction, ILogger logger, IPackageOperationEventListener eventListener) { if (eventListener == null) { eventListener = NullPackageOperationEventListener.Instance; } ExecuteOperationsWithPackage( null, package, operations, () => { bool success = false; foreach (var project in projects) { try { eventListener.OnBeforeAddPackageReference(project); IProjectManager projectManager = GetProjectManager(project); InitializeLogger(logger, projectManager); projectAction(projectManager); success |= true; } catch (Exception ex) { eventListener.OnAddPackageReferenceError(project, ex); } finally { eventListener.OnAfterAddPackageReference(project); } } // Throw an exception only if all the update failed for all projects // so we rollback any solution level operations that might have happened if (projects.Any() && !success) { throw new InvalidOperationException(VsResources.OperationFailed); } }, logger); } private void ExecuteOperationsWithPackage(IProjectManager projectManager, IPackage package, IEnumerable<PackageOperation> operations, Action action, ILogger logger) { try { InitializeLogger(logger, projectManager); RunSolutionAction(() => { if (operations.Any()) { foreach (var operation in operations) { Execute(operation); } } else if (LocalRepository.Exists(package)) { Logger.Log(MessageLevel.Info, VsResources.Log_PackageAlreadyInstalled, package.GetFullName()); } action(); }); // Add package to recent repository AddPackageToRecentRepository(package); } finally { ClearLogger(logger, projectManager); } } private Project GetProject(IProjectManager projectManager) { // We only support project systems that implement IVsProjectSystem var vsProjectSystem = projectManager.Project as IVsProjectSystem; if (vsProjectSystem == null) { return null; } // Find the project by it's unique name return _solutionManager.GetProject(vsProjectSystem.UniqueName); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "If we failed to add binding redirects we don't want it to stop the install/update.")] private void AddBindingRedirects(IProjectManager projectManager) { // Find the project by it's unique name Project project = GetProject(projectManager); // If we can't find the project or it doesn't support binding redirects then don't add any redirects if (project == null || !project.SupportsBindingRedirects()) { return; } try { RuntimeHelpers.AddBindingRedirects(_solutionManager, project); } catch (Exception e) { // If there was an error adding binding redirects then print a warning and continue Logger.Log(MessageLevel.Warning, String.Format(CultureInfo.CurrentCulture, VsResources.Warning_FailedToAddBindingRedirects, projectManager.Project.ProjectName, e.Message)); } } private void AddPackageToRecentRepository(IPackage package, bool updateOnly = false) { if (!AddToRecent) { return; } // add the installed package to the recent repository if (_recentPackagesRepository != null) { if (updateOnly) { _recentPackagesRepository.UpdatePackage(package); } else { _recentPackagesRepository.AddPackage(package); } } } private void InitializeLogger(ILogger logger, IProjectManager projectManager) { // Setup logging on all of our objects Logger = logger; FileSystem.Logger = logger; if (projectManager != null) { projectManager.Logger = logger; projectManager.Project.Logger = logger; } } private void ClearLogger(ILogger logger, IProjectManager projectManager) { // clear logging on all of our objects Logger = null; FileSystem.Logger = null; if (projectManager != null) { projectManager.Logger = null; projectManager.Project.Logger = null; } } /// <summary> /// Runs the specified action and rolls back any installed packages if on failure. /// </summary> private void RunSolutionAction(Action action) { var packagesAdded = new List<IPackage>(); EventHandler<PackageOperationEventArgs> installHandler = (sender, e) => { // Record packages that we are installing so that if one fails, we can rollback packagesAdded.Add(e.Package); _packageEvents.NotifyInstalling(e); }; EventHandler<PackageOperationEventArgs> installedHandler = (sender, e) => { _packageEvents.NotifyInstalled(e); }; PackageInstalling += installHandler; PackageInstalled += installedHandler; try { // Execute the action action(); } catch { if (packagesAdded.Any()) { // Only print the rollback warning if we have something to rollback Logger.Log(MessageLevel.Warning, VsResources.Warning_RollingBack); } // Don't log anything during the rollback Logger = null; // Rollback the install if it fails Uninstall(packagesAdded); throw; } finally { // Remove the event handler PackageInstalling -= installHandler; PackageInstalled -= installedHandler; } } /// <summary> /// Runs action on the project manager and rollsback any package installs if it fails. /// </summary> private void RunProjectAction(IProjectManager projectManager, Action action) { if (projectManager == null) { return; } // Keep track of what was added and removed var packagesAdded = new Stack<IPackage>(); var packagesRemoved = new List<IPackage>(); EventHandler<PackageOperationEventArgs> removeHandler = (sender, e) => { packagesRemoved.Add(e.Package); }; EventHandler<PackageOperationEventArgs> addingHandler = (sender, e) => { packagesAdded.Push(e.Package); // If this package doesn't exist at solution level (it might not because of leveling) // then we need to install it. if (!LocalRepository.Exists(e.Package)) { ExecuteInstall(e.Package); } }; // Try to get the project for this project manager Project project = GetProject(projectManager); IVsProjectBuildSystem build = null; if (project != null) { build = project.ToVsProjectBuildSystem(); } // Add the handlers projectManager.PackageReferenceRemoved += removeHandler; projectManager.PackageReferenceAdding += addingHandler; try { if (build != null) { // Start a batch edit so there is no background compilation until we're done // processing project actions build.StartBatchEdit(); } action(); // Only add binding redirects if install was successful AddBindingRedirects(projectManager); } catch { // We need to Remove the handlers here since we're going to attempt // a rollback and we don't want modify the collections while rolling back. projectManager.PackageReferenceRemoved -= removeHandler; projectManager.PackageReferenceAdded -= addingHandler; // When things fail attempt a rollback RollbackProjectActions(projectManager, packagesAdded, packagesRemoved); // Rollback solution packages Uninstall(packagesAdded); // Clear removed packages so we don't try to remove them again (small optimization) packagesRemoved.Clear(); throw; } finally { if (build != null) { // End the batch edit when we are done. build.EndBatchEdit(); } // Remove the handlers projectManager.PackageReferenceRemoved -= removeHandler; projectManager.PackageReferenceAdding -= addingHandler; // Remove any packages that would be removed as a result of updating a dependency or the package itself // We can execute the uninstall directly since we don't need to resolve dependencies again. Uninstall(packagesRemoved); } } private static void RollbackProjectActions(IProjectManager projectManager, IEnumerable<IPackage> packagesAdded, IEnumerable<IPackage> packagesRemoved) { // Disable logging when rolling back project operations projectManager.Logger = null; foreach (var package in packagesAdded) { // Remove each package that was added projectManager.RemovePackageReference(package, forceRemove: false, removeDependencies: false); } foreach (var package in packagesRemoved) { // Add each package that was removed projectManager.AddPackageReference(package, ignoreDependencies: true, allowPrereleaseVersions: true); } } private void Uninstall(IEnumerable<IPackage> packages) { foreach (var package in packages) { ExecuteUninstall(package); } } private void UpdatePackage(string packageId, Action<IProjectManager> projectAction, Func<IPackage> resolvePackage, bool updateDependencies, bool allowPrereleaseVersions, ILogger logger, IPackageOperationEventListener eventListener) { bool appliesToProject; IPackage package = FindLocalPackage(packageId, out appliesToProject); if (appliesToProject) { eventListener = eventListener ?? NullPackageOperationEventListener.Instance; IPackage newPackage = null; foreach (var project in _solutionManager.GetProjects()) { IProjectManager projectManager = GetProjectManager(project); try { InitializeLogger(logger, projectManager); if (projectManager.LocalRepository.Exists(packageId)) { eventListener.OnBeforeAddPackageReference(project); try { RunSolutionAction(() => projectAction(projectManager)); if (newPackage == null) { // after the update, get the new version to add to the recent package repository newPackage = projectManager.LocalRepository.FindPackage(packageId); } } catch (Exception e) { logger.Log(MessageLevel.Error, ExceptionUtility.Unwrap(e).Message); eventListener.OnAddPackageReferenceError(project, e); } finally { eventListener.OnAfterAddPackageReference(project); } } } finally { ClearLogger(logger, projectManager); } } if (newPackage != null) { AddPackageToRecentRepository(newPackage); } } else { // Find the package we're going to update to IPackage newPackage = resolvePackage(); if (newPackage != null && package.Version != newPackage.Version) { try { InitializeLogger(logger, projectManager: null); // We might be updating a solution only package UpdatePackage(newPackage, updateDependencies, allowPrereleaseVersions: allowPrereleaseVersions); } finally { ClearLogger(logger, projectManager: null); } // Add package to recent repository AddPackageToRecentRepository(newPackage); } else { logger.Log(MessageLevel.Info, VsResources.NoUpdatesAvailable, packageId); } } } private void UpdatePackages(IProjectManager projectManager, bool updateDependencies, bool safeUpdate, bool allowPrereleaseVersions, ILogger logger) { UpdatePackages(projectManager.LocalRepository, package => { if (safeUpdate) { SafeUpdatePackage(projectManager, package.Id, updateDependencies, allowPrereleaseVersions, logger); } else { UpdatePackage(projectManager, package.Id, version: null, updateDependencies: updateDependencies, allowPrereleaseVersions: allowPrereleaseVersions, logger: logger); } }, logger); } private void UpdatePackages(bool updateDependencies, bool safeUpdate, bool allowPrereleaseVersions, ILogger logger, IPackageOperationEventListener eventListener) { UpdatePackages(LocalRepository, package => { if (safeUpdate) { SafeUpdatePackage(package.Id, updateDependencies, allowPrereleaseVersions: allowPrereleaseVersions, logger: logger, eventListener: eventListener); } else { UpdatePackage(package.Id, version: null, updateDependencies: updateDependencies, allowPrereleaseVersions: allowPrereleaseVersions, logger: logger, eventListener: eventListener); } }, logger); } private void UpdatePackages(IPackageRepository localRepository, Action<IPackage> updateAction, ILogger logger) { var packageSorter = new PackageSorter(); // Get the packages in reverse dependency order then run update on each one i.e. if A -> B run Update(A) then Update(B) var packages = packageSorter.GetPackagesByDependencyOrder(localRepository).Reverse(); foreach (var package in packages) { // While updating we might remove packages that were initially in the list. e.g. // A 1.0 -> B 2.0, A 2.0 -> [], since updating to A 2.0 removes B, we end up skipping it. if (localRepository.Exists(package.Id)) { try { updateAction(package); } catch (Exception e) { logger.Log(MessageLevel.Error, ExceptionUtility.Unwrap(e).Message); } } } } private IPackageRepository CreateProjectManagerSourceRepository() { // The source repo for the project manager is the aggregate of the shared repo and the selected repo. // For dependency resolution, we want VS to look for packages in the selected source and then use the fallback logic var fallbackRepository = SourceRepository as FallbackRepository; if (fallbackRepository != null) { var primaryRepositories = new[] { _sharedRepository, fallbackRepository.SourceRepository.Clone() }; return new FallbackRepository(new AggregateRepository(primaryRepositories), fallbackRepository.DependencyResolver); } return new AggregateRepository(new[] { _sharedRepository, SourceRepository.Clone() }); } private IVersionSpec GetSafeRange(string packageId) { bool appliesToProject; IPackage package = FindLocalPackage(packageId, out appliesToProject); return VersionUtility.GetSafeRange(package.Version); } private IVersionSpec GetSafeRange(IProjectManager projectManager, string packageId) { bool appliesToProject; IPackage package = FindLocalPackageForUpdate(projectManager, packageId, out appliesToProject); return VersionUtility.GetSafeRange(package.Version); } } }
// 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; /// <summary> /// ToInt16(System.Decimal) /// </summary> public class ConvertToInt16_4 { #region Public Methods public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; retVal = PosTest5() && retVal; // // TODO: Add your negative test cases here // // TestLibrary.TestFramework.LogInformation("[Negative]"); retVal = NegTest1() && retVal; retVal = NegTest2() && retVal; return retVal; } #region Positive Test Cases public bool PosTest1() { bool retVal = true; // Add your scenario description here TestLibrary.TestFramework.BeginScenario("PosTest1: Verify method ToInt16(0<decimal<0.5)"); try { double random; do random = TestLibrary.Generator.GetDouble(-55); while (random >= 0.5); decimal d = decimal.Parse(random.ToString()); Int16 actual = Convert.ToInt16(d); Int16 expected = 0; if (actual != expected) { TestLibrary.TestFramework.LogError("001.1", "Method ToInt16 Err."); TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actual = " + actual + ", expected = " + expected); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("001.2", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; // Add your scenario description here TestLibrary.TestFramework.BeginScenario("PosTest2: Verify method ToInt16(1>decimal>=0.5)"); try { double random; do random = TestLibrary.Generator.GetDouble(-55); while (random < 0.5); decimal d = decimal.Parse(random.ToString()); Int16 actual = Convert.ToInt16(d); Int16 expected = 1; if (actual != expected) { TestLibrary.TestFramework.LogError("002.1", "Method ToInt16 Err."); TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actual = " + actual + ", expected = " + expected); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("001.2", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; // Add your scenario description here TestLibrary.TestFramework.BeginScenario("PosTest3: Verify method ToInt16(0)"); try { decimal d = 0m; Int16 actual = Convert.ToInt16(d); Int16 expected = 0; if (actual != expected) { TestLibrary.TestFramework.LogError("003.1", "Method ToInt16 Err."); TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actual = " + actual + ", expected = " + expected); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("003.2", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool PosTest4() { bool retVal = true; // Add your scenario description here TestLibrary.TestFramework.BeginScenario("PosTest4: Verify method ToInt16(int16.max)"); try { decimal d = Int16.MaxValue; Int16 actual = Convert.ToInt16(d); Int16 expected = Int16.MaxValue; if (actual != expected) { TestLibrary.TestFramework.LogError("004.1", "Method ToInt16 Err."); TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actual = " + actual + ", expected = " + expected); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("004.2", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool PosTest5() { bool retVal = true; // Add your scenario description here TestLibrary.TestFramework.BeginScenario("PosTest5: Verify method ToInt16(int16.min)"); try { decimal d = Int16.MinValue; Int16 actual = Convert.ToInt16(d); Int16 expected = Int16.MinValue; if (actual != expected) { TestLibrary.TestFramework.LogError("005.1", "Method ToInt16 Err."); TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actual = " + actual + ", expected = " + expected); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("005.2", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } #endregion #region Nagetive Test Cases public bool NegTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest1: OverflowException is not thrown."); try { decimal d = Int16.MaxValue + 1; Int16 i = Convert.ToInt16(d); TestLibrary.TestFramework.LogError("101.1", "OverflowException is not thrown."); retVal = false; } catch (OverflowException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("101.2", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool NegTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest2: OverflowException is not thrown."); try { decimal d = Int16.MinValue - 1; Int16 i = Convert.ToInt16(d); TestLibrary.TestFramework.LogError("102.1", "OverflowException is not thrown."); retVal = false; } catch (OverflowException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("102.2", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } #endregion #endregion public static int Main() { ConvertToInt16_4 test = new ConvertToInt16_4(); TestLibrary.TestFramework.BeginTestCase("ConvertToInt16_4"); if (test.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using NUnit.Framework; using QuantConnect.Data.Consolidators; using QuantConnect.Data.Market; using QuantConnect.Indicators; using System.Collections.Generic; namespace QuantConnect.Tests.Common.Data { [TestFixture] public class RenkoConsolidatorTests { [Test] public void WickedOutputTypeIsRenkoBar() { var consolidator = new RenkoConsolidator(10.0m); Assert.AreEqual(typeof(RenkoBar), consolidator.OutputType); } [Test] public void WickedNoFallingRenko() { var consolidator = new TestRenkoConsolidator(1.0m); var renkos = new List<RenkoBar>(); consolidator.DataConsolidated += (sender, renko) => renkos.Add(renko); var tickOn1 = new DateTime(2016, 1, 1, 17, 0, 0, 0); var tickOn2 = new DateTime(2016, 1, 1, 17, 0, 0, 1); consolidator.Update(new IndicatorDataPoint(tickOn1, 10.0m)); consolidator.Update(new IndicatorDataPoint(tickOn2, 9.1m)); Assert.AreEqual(renkos.Count, 0); var openRenko = consolidator.OpenRenko(); Assert.AreEqual(openRenko.Open, 10.0m); Assert.AreEqual(openRenko.High, 10.0m); Assert.AreEqual(openRenko.Low, 9.1m); Assert.AreEqual(openRenko.Close, 9.1m); } [Test] public void WickedNoRisingRenko() { var consolidator = new TestRenkoConsolidator(1.0m); var renkos = new List<RenkoBar>(); consolidator.DataConsolidated += (sender, renko) => renkos.Add(renko); var tickOn1 = new DateTime(2016, 1, 1, 17, 0, 0, 0); var tickOn2 = new DateTime(2016, 1, 1, 17, 0, 0, 1); consolidator.Update(new IndicatorDataPoint(tickOn1, 10.0m)); consolidator.Update(new IndicatorDataPoint(tickOn2, 10.9m)); Assert.AreEqual(renkos.Count, 0); var openRenko = consolidator.OpenRenko(); Assert.AreEqual(openRenko.Open, 10.0m); Assert.AreEqual(openRenko.High, 10.9m); Assert.AreEqual(openRenko.Low, 10.0m); Assert.AreEqual(openRenko.Close, 10.9m); } [Test] public void WickedNoFallingRenkoKissLimit() { var consolidator = new TestRenkoConsolidator(1.0m); var renkos = new List<RenkoBar>(); consolidator.DataConsolidated += (sender, renko) => renkos.Add(renko); var tickOn1 = new DateTime(2016, 1, 1, 17, 0, 0, 0); var tickOn2 = new DateTime(2016, 1, 1, 17, 0, 0, 1); consolidator.Update(new IndicatorDataPoint(tickOn1, 10.0m)); consolidator.Update(new IndicatorDataPoint(tickOn2, 9.0m)); Assert.AreEqual(renkos.Count, 0); var openRenko = consolidator.OpenRenko(); Assert.AreEqual(openRenko.Open, 10.0m); Assert.AreEqual(openRenko.High, 10.0m); Assert.AreEqual(openRenko.Low, 9.0m); Assert.AreEqual(openRenko.Close, 9.0m); } [Test] public void WickedNoRisingRenkoKissLimit() { var consolidator = new TestRenkoConsolidator(1.0m); var renkos = new List<RenkoBar>(); consolidator.DataConsolidated += (sender, renko) => renkos.Add(renko); var tickOn1 = new DateTime(2016, 1, 1, 17, 0, 0, 0); var tickOn2 = new DateTime(2016, 1, 1, 17, 0, 0, 1); consolidator.Update(new IndicatorDataPoint(tickOn1, 10.0m)); consolidator.Update(new IndicatorDataPoint(tickOn2, 11.0m)); Assert.AreEqual(renkos.Count, 0); var openRenko = consolidator.OpenRenko(); Assert.AreEqual(openRenko.Open, 10.0m); Assert.AreEqual(openRenko.High, 11.0m); Assert.AreEqual(openRenko.Low, 10.0m); Assert.AreEqual(openRenko.Close, 11.0m); } [Test] public void WickedOneFallingRenko() { var consolidator = new TestRenkoConsolidator(1.0m); var renkos = new List<RenkoBar>(); consolidator.DataConsolidated += (sender, renko) => renkos.Add(renko); var tickOn1 = new DateTime(2016, 1, 1, 17, 0, 0, 0); var tickOn2 = new DateTime(2016, 1, 1, 17, 0, 0, 1); consolidator.Update(new IndicatorDataPoint(tickOn1, 10.0m)); consolidator.Update(new IndicatorDataPoint(tickOn2, 8.9m)); Assert.AreEqual(renkos.Count, 1); Assert.AreEqual(renkos[0].Open, 10.0m); Assert.AreEqual(renkos[0].High, 10.0m); Assert.AreEqual(renkos[0].Low, 9.0m); Assert.AreEqual(renkos[0].Close, 9.0m); Assert.AreEqual(renkos[0].Direction, BarDirection.Falling); Assert.AreEqual(renkos[0].Spread, 1.0m); Assert.AreEqual(renkos[0].Start, tickOn1); Assert.AreEqual(renkos[0].EndTime, tickOn2); var openRenko = consolidator.OpenRenko(); Assert.AreEqual(openRenko.Start, tickOn2); Assert.AreEqual(openRenko.EndTime, tickOn2); Assert.AreEqual(openRenko.Open, 9.0m); Assert.AreEqual(openRenko.High, 9.0m); Assert.AreEqual(openRenko.Low, 8.9m); Assert.AreEqual(openRenko.Close, 8.9m); } [Test] public void WickedOneRisingRenko() { var consolidator = new TestRenkoConsolidator(1.0m); var renkos = new List<RenkoBar>(); consolidator.DataConsolidated += (sender, renko) => renkos.Add(renko); var tickOn1 = new DateTime(2016, 1, 1, 17, 0, 0, 0); var tickOn2 = new DateTime(2016, 1, 1, 17, 0, 0, 1); consolidator.Update(new IndicatorDataPoint(tickOn1, 9.0m)); consolidator.Update(new IndicatorDataPoint(tickOn2, 10.1m)); Assert.AreEqual(renkos.Count, 1); Assert.AreEqual(renkos[0].Open, 9.0m); Assert.AreEqual(renkos[0].High, 10.0m); Assert.AreEqual(renkos[0].Low, 9.0m); Assert.AreEqual(renkos[0].Close, 10.0m); Assert.AreEqual(renkos[0].Direction, BarDirection.Rising); Assert.AreEqual(renkos[0].Spread, 1.0m); Assert.AreEqual(renkos[0].Start, tickOn1); Assert.AreEqual(renkos[0].EndTime, tickOn2); var openRenko = consolidator.OpenRenko(); Assert.AreEqual(openRenko.Start, tickOn2); Assert.AreEqual(openRenko.EndTime, tickOn2); Assert.AreEqual(openRenko.Open, 10.0m); Assert.AreEqual(openRenko.High, 10.1m); Assert.AreEqual(openRenko.Low, 10.0m); Assert.AreEqual(openRenko.Close, 10.1m); } [Test] public void WickedTwoFallingThenOneRisingRenkos() { var consolidator = new TestRenkoConsolidator(1.0m); var renkos = new List<RenkoBar>(); consolidator.DataConsolidated += (sender, renko) => renkos.Add(renko); var tickOn1 = new DateTime(2016, 1, 1, 17, 0, 0, 0); var tickOn2 = new DateTime(2016, 1, 1, 17, 0, 0, 1); consolidator.Update(new IndicatorDataPoint(tickOn1, 10.0m)); consolidator.Update(new IndicatorDataPoint(tickOn1, 10.5m)); consolidator.Update(new IndicatorDataPoint(tickOn1, 9.5m)); consolidator.Update(new IndicatorDataPoint(tickOn1, 8.9m)); consolidator.Update(new IndicatorDataPoint(tickOn1, 9.1m)); consolidator.Update(new IndicatorDataPoint(tickOn1, 9.2m)); consolidator.Update(new IndicatorDataPoint(tickOn1, 8.5m)); consolidator.Update(new IndicatorDataPoint(tickOn1, 7.8m)); consolidator.Update(new IndicatorDataPoint(tickOn1, 7.6m)); consolidator.Update(new IndicatorDataPoint(tickOn1, 8.5m)); consolidator.Update(new IndicatorDataPoint(tickOn1, 9.2m)); consolidator.Update(new IndicatorDataPoint(tickOn1, 10.1m)); Assert.AreEqual(renkos.Count, 3); Assert.AreEqual(renkos[0].Open, 10.0m); Assert.AreEqual(renkos[0].High, 10.5m); Assert.AreEqual(renkos[0].Low, 9.0m); Assert.AreEqual(renkos[0].Close, 9.0m); Assert.AreEqual(renkos[0].Direction, BarDirection.Falling); Assert.AreEqual(renkos[0].Spread, 1.0m); Assert.AreEqual(renkos[1].Open, 9.0m); Assert.AreEqual(renkos[1].High, 9.2m); Assert.AreEqual(renkos[1].Low, 8.0m); Assert.AreEqual(renkos[1].Close, 8.0m); Assert.AreEqual(renkos[1].Direction, BarDirection.Falling); Assert.AreEqual(renkos[1].Spread, 1.0m); Assert.AreEqual(renkos[2].Open, 9.0m); Assert.AreEqual(renkos[2].High, 10.0m); Assert.AreEqual(renkos[2].Low, 7.6m); Assert.AreEqual(renkos[2].Close, 10.0m); Assert.AreEqual(renkos[2].Direction, BarDirection.Rising); Assert.AreEqual(renkos[2].Spread, 1.0m); var openRenko = consolidator.OpenRenko(); Assert.AreEqual(openRenko.Open, 10.0m); Assert.AreEqual(openRenko.High, 10.1m); Assert.AreEqual(openRenko.Low, 10.0m); Assert.AreEqual(openRenko.Close, 10.1m); } [Test] public void WickedTwoRisingThenOneFallingRenkos() { var consolidator = new TestRenkoConsolidator(1.0m); var renkos = new List<RenkoBar>(); consolidator.DataConsolidated += (sender, renko) => renkos.Add(renko); var tickOn1 = new DateTime(2016, 1, 1, 17, 0, 0, 0); var tickOn2 = new DateTime(2016, 1, 1, 17, 0, 0, 1); consolidator.Update(new IndicatorDataPoint(tickOn1, 10.0m)); consolidator.Update(new IndicatorDataPoint(tickOn1, 9.6m)); consolidator.Update(new IndicatorDataPoint(tickOn1, 10.5m)); consolidator.Update(new IndicatorDataPoint(tickOn1, 11.1m)); consolidator.Update(new IndicatorDataPoint(tickOn1, 11.0m)); consolidator.Update(new IndicatorDataPoint(tickOn1, 10.7m)); consolidator.Update(new IndicatorDataPoint(tickOn1, 11.6m)); consolidator.Update(new IndicatorDataPoint(tickOn1, 12.3m)); consolidator.Update(new IndicatorDataPoint(tickOn1, 12.3m)); consolidator.Update(new IndicatorDataPoint(tickOn1, 12.4m)); consolidator.Update(new IndicatorDataPoint(tickOn1, 11.5m)); consolidator.Update(new IndicatorDataPoint(tickOn1, 9.9m)); Assert.AreEqual(renkos.Count, 3); Assert.AreEqual(renkos[0].Open, 10.0m); Assert.AreEqual(renkos[0].High, 11.0m); Assert.AreEqual(renkos[0].Low, 9.6m); Assert.AreEqual(renkos[0].Close, 11.0m); Assert.AreEqual(renkos[0].Direction, BarDirection.Rising); Assert.AreEqual(renkos[0].Spread, 1.0m); Assert.AreEqual(renkos[1].Open, 11.0m); Assert.AreEqual(renkos[1].High, 12.0m); Assert.AreEqual(renkos[1].Low, 10.7m); Assert.AreEqual(renkos[1].Close, 12.0m); Assert.AreEqual(renkos[1].Direction, BarDirection.Rising); Assert.AreEqual(renkos[1].Spread, 1.0m); Assert.AreEqual(renkos[2].Open, 11.0m); Assert.AreEqual(renkos[2].High, 12.4m); Assert.AreEqual(renkos[2].Low, 10.0m); Assert.AreEqual(renkos[2].Close, 10.0m); Assert.AreEqual(renkos[2].Direction, BarDirection.Falling); Assert.AreEqual(renkos[2].Spread, 1.0m); var openRenko = consolidator.OpenRenko(); Assert.AreEqual(openRenko.Open, 10.0m); Assert.AreEqual(openRenko.High, 10.0m); Assert.AreEqual(openRenko.Low, 9.9m); Assert.AreEqual(openRenko.Close, 9.9m); } [Test] public void WickedThreeRisingGapRenkos() { var consolidator = new TestRenkoConsolidator(1.0m); var renkos = new List<RenkoBar>(); consolidator.DataConsolidated += (sender, renko) => renkos.Add(renko); var tickOn1 = new DateTime(2016, 1, 1, 17, 0, 0, 0); var tickOn2 = new DateTime(2016, 1, 1, 17, 0, 0, 1); consolidator.Update(new IndicatorDataPoint(tickOn1, 10.0m)); consolidator.Update(new IndicatorDataPoint(tickOn2, 14.0m)); Assert.AreEqual(renkos.Count, 3); Assert.AreEqual(renkos[0].Start, tickOn1); Assert.AreEqual(renkos[0].EndTime, tickOn2); Assert.AreEqual(renkos[0].Open, 10.0m); Assert.AreEqual(renkos[0].High, 11.0m); Assert.AreEqual(renkos[0].Low, 10.0m); Assert.AreEqual(renkos[0].Close, 11.0m); Assert.AreEqual(renkos[0].Direction, BarDirection.Rising); Assert.AreEqual(renkos[0].Spread, 1.0m); Assert.AreEqual(renkos[1].Start, tickOn2); Assert.AreEqual(renkos[1].EndTime, tickOn2); Assert.AreEqual(renkos[1].Open, 11.0m); Assert.AreEqual(renkos[1].High, 12.0m); Assert.AreEqual(renkos[1].Low, 11.0m); Assert.AreEqual(renkos[1].Close, 12.0m); Assert.AreEqual(renkos[1].Direction, BarDirection.Rising); Assert.AreEqual(renkos[1].Spread, 1.0m); Assert.AreEqual(renkos[2].Start, tickOn2); Assert.AreEqual(renkos[2].EndTime, tickOn2); Assert.AreEqual(renkos[2].Open, 12.0m); Assert.AreEqual(renkos[2].High, 13.0m); Assert.AreEqual(renkos[2].Low, 12.0m); Assert.AreEqual(renkos[2].Close, 13.0m); Assert.AreEqual(renkos[2].Direction, BarDirection.Rising); Assert.AreEqual(renkos[2].Spread, 1.0m); var openRenko = consolidator.OpenRenko(); Assert.AreEqual(openRenko.Start, tickOn2); Assert.AreEqual(openRenko.EndTime, tickOn2); Assert.AreEqual(openRenko.Open, 13.0m); Assert.AreEqual(openRenko.High, 14.0m); Assert.AreEqual(openRenko.Low, 13.0m); Assert.AreEqual(openRenko.Close, 14.0m); } [Test] public void WickedThreeFallingGapRenkos() { var consolidator = new TestRenkoConsolidator(1.0m); var renkos = new List<RenkoBar>(); consolidator.DataConsolidated += (sender, renko) => renkos.Add(renko); var tickOn1 = new DateTime(2016, 1, 1, 17, 0, 0, 0); var tickOn2 = new DateTime(2016, 1, 1, 17, 0, 0, 1); consolidator.Update(new IndicatorDataPoint(tickOn1, 14.0m)); consolidator.Update(new IndicatorDataPoint(tickOn2, 10.0m)); Assert.AreEqual(renkos.Count, 3); Assert.AreEqual(renkos[0].Start, tickOn1); Assert.AreEqual(renkos[0].EndTime, tickOn2); Assert.AreEqual(renkos[0].Open, 14.0m); Assert.AreEqual(renkos[0].High, 14.0m); Assert.AreEqual(renkos[0].Low, 13.0m); Assert.AreEqual(renkos[0].Close, 13.0m); Assert.AreEqual(renkos[0].Direction, BarDirection.Falling); Assert.AreEqual(renkos[0].Spread, 1.0m); Assert.AreEqual(renkos[1].Start, tickOn2); Assert.AreEqual(renkos[1].EndTime, tickOn2); Assert.AreEqual(renkos[1].Open, 13.0m); Assert.AreEqual(renkos[1].High, 13.0m); Assert.AreEqual(renkos[1].Low, 12.0m); Assert.AreEqual(renkos[1].Close, 12.0m); Assert.AreEqual(renkos[1].Direction, BarDirection.Falling); Assert.AreEqual(renkos[1].Spread, 1.0); Assert.AreEqual(renkos[2].Start, tickOn2); Assert.AreEqual(renkos[2].EndTime, tickOn2); Assert.AreEqual(renkos[2].Open, 12.0m); Assert.AreEqual(renkos[2].High, 12.0m); Assert.AreEqual(renkos[2].Low, 11.0m); Assert.AreEqual(renkos[2].Close, 11.0m); Assert.AreEqual(renkos[2].Direction, BarDirection.Falling); Assert.AreEqual(renkos[2].Spread, 1.0m); var openRenko = consolidator.OpenRenko(); Assert.AreEqual(openRenko.Open, 11.0m); Assert.AreEqual(openRenko.High, 11.0m); Assert.AreEqual(openRenko.Low, 10.0m); Assert.AreEqual(openRenko.Close, 10.0m); } [Test] public void WickedTwoFallingThenThreeRisingGapRenkos() { var consolidator = new TestRenkoConsolidator(1.0m); var renkos = new List<RenkoBar>(); consolidator.DataConsolidated += (sender, renko) => renkos.Add(renko); var tickOn1 = new DateTime(2016, 1, 1, 17, 0, 0, 0); var tickOn2 = new DateTime(2016, 1, 1, 17, 0, 0, 1); consolidator.Update(new IndicatorDataPoint(tickOn1, 10.0m)); consolidator.Update(new IndicatorDataPoint(tickOn1, 10.5m)); consolidator.Update(new IndicatorDataPoint(tickOn1, 9.5m)); consolidator.Update(new IndicatorDataPoint(tickOn1, 8.9m)); consolidator.Update(new IndicatorDataPoint(tickOn1, 9.1m)); consolidator.Update(new IndicatorDataPoint(tickOn1, 9.2m)); consolidator.Update(new IndicatorDataPoint(tickOn1, 8.5m)); consolidator.Update(new IndicatorDataPoint(tickOn1, 7.8m)); consolidator.Update(new IndicatorDataPoint(tickOn1, 7.6m)); consolidator.Update(new IndicatorDataPoint(tickOn1, 8.5m)); consolidator.Update(new IndicatorDataPoint(tickOn1, 9.2m)); consolidator.Update(new IndicatorDataPoint(tickOn1, 12.1m)); Assert.AreEqual(renkos.Count, 5); Assert.AreEqual(renkos[0].Open, 10.0m); Assert.AreEqual(renkos[0].High, 10.5m); Assert.AreEqual(renkos[0].Low, 9.0m); Assert.AreEqual(renkos[0].Close, 9.0m); Assert.AreEqual(renkos[0].Direction, BarDirection.Falling); Assert.AreEqual(renkos[0].Spread, 1.0m); Assert.AreEqual(renkos[1].Open, 9.0m); Assert.AreEqual(renkos[1].High, 9.2m); Assert.AreEqual(renkos[1].Low, 8.0m); Assert.AreEqual(renkos[1].Close, 8.0m); Assert.AreEqual(renkos[1].Direction, BarDirection.Falling); Assert.AreEqual(renkos[1].Spread, 1.0m); Assert.AreEqual(renkos[2].Open, 9.0m); Assert.AreEqual(renkos[2].High, 10.0m); Assert.AreEqual(renkos[2].Low, 7.6m); Assert.AreEqual(renkos[2].Close, 10.0m); Assert.AreEqual(renkos[2].Direction, BarDirection.Rising); Assert.AreEqual(renkos[2].Spread, 1.0m); Assert.AreEqual(renkos[3].Open, 10.0m); Assert.AreEqual(renkos[3].High, 11.0m); Assert.AreEqual(renkos[3].Low, 10.0m); Assert.AreEqual(renkos[3].Close, 11.0m); Assert.AreEqual(renkos[3].Direction, BarDirection.Rising); Assert.AreEqual(renkos[3].Spread, 1.0m); Assert.AreEqual(renkos[4].Open, 11.0m); Assert.AreEqual(renkos[4].High, 12.0m); Assert.AreEqual(renkos[4].Low, 11.0m); Assert.AreEqual(renkos[4].Close, 12.0m); Assert.AreEqual(renkos[4].Direction, BarDirection.Rising); Assert.AreEqual(renkos[4].Spread, 1.0m); var openRenko = consolidator.OpenRenko(); Assert.AreEqual(openRenko.Open, 12.0m); Assert.AreEqual(openRenko.High, 12.1m); Assert.AreEqual(openRenko.Low, 12.0m); Assert.AreEqual(openRenko.Close, 12.1m); } [Test] public void WickedTwoRisingThenThreeFallingGapRenkos() { var consolidator = new TestRenkoConsolidator(1.0m); var renkos = new List<RenkoBar>(); consolidator.DataConsolidated += (sender, renko) => renkos.Add(renko); var tickOn1 = new DateTime(2016, 1, 1, 17, 0, 0, 0); var tickOn2 = new DateTime(2016, 1, 1, 17, 0, 0, 1); consolidator.Update(new IndicatorDataPoint(tickOn1, 10.0m)); consolidator.Update(new IndicatorDataPoint(tickOn1, 9.6m)); consolidator.Update(new IndicatorDataPoint(tickOn1, 10.5m)); consolidator.Update(new IndicatorDataPoint(tickOn1, 11.1m)); consolidator.Update(new IndicatorDataPoint(tickOn1, 11.0m)); consolidator.Update(new IndicatorDataPoint(tickOn1, 10.7m)); consolidator.Update(new IndicatorDataPoint(tickOn1, 11.6m)); consolidator.Update(new IndicatorDataPoint(tickOn1, 12.3m)); consolidator.Update(new IndicatorDataPoint(tickOn1, 12.3m)); consolidator.Update(new IndicatorDataPoint(tickOn1, 12.4m)); consolidator.Update(new IndicatorDataPoint(tickOn1, 11.5m)); consolidator.Update(new IndicatorDataPoint(tickOn1, 7.9m)); Assert.AreEqual(renkos.Count, 5); Assert.AreEqual(renkos[0].Open, 10.0); Assert.AreEqual(renkos[0].High, 11.0); Assert.AreEqual(renkos[0].Low, 9.6); Assert.AreEqual(renkos[0].Close, 11.0); Assert.AreEqual(renkos[0].Direction, BarDirection.Rising); Assert.AreEqual(renkos[0].Spread, 1.0); Assert.AreEqual(renkos[1].Open, 11.0); Assert.AreEqual(renkos[1].High, 12.0); Assert.AreEqual(renkos[1].Low, 10.7); Assert.AreEqual(renkos[1].Close, 12.0); Assert.AreEqual(renkos[1].Direction, BarDirection.Rising); Assert.AreEqual(renkos[1].Spread, 1.0); Assert.AreEqual(renkos[2].Open, 11.0); Assert.AreEqual(renkos[2].High, 12.4); Assert.AreEqual(renkos[2].Low, 10.0); Assert.AreEqual(renkos[2].Close, 10.0); Assert.AreEqual(renkos[2].Direction, BarDirection.Falling); Assert.AreEqual(renkos[2].Spread, 1.0); Assert.AreEqual(renkos[3].Open, 10.0); Assert.AreEqual(renkos[3].High, 10.0); Assert.AreEqual(renkos[3].Low, 9.0); Assert.AreEqual(renkos[3].Close, 9.0); Assert.AreEqual(renkos[3].Direction, BarDirection.Falling); Assert.AreEqual(renkos[3].Spread, 1.0); Assert.AreEqual(renkos[4].Open, 9.0); Assert.AreEqual(renkos[4].High, 9.0); Assert.AreEqual(renkos[4].Low, 8.0); Assert.AreEqual(renkos[4].Close, 8.0); Assert.AreEqual(renkos[4].Direction, BarDirection.Falling); Assert.AreEqual(renkos[4].Spread, 1.0); var openRenko = consolidator.OpenRenko(); Assert.AreEqual(openRenko.Open, 8.0); Assert.AreEqual(openRenko.High, 8.0); Assert.AreEqual(openRenko.Low, 7.9); Assert.AreEqual(openRenko.Close, 7.9); } [Test] public void ConsistentRenkos() { // Reproduce issue #5479 // Test Renko bar consistency amongst three consolidators starting at different times var time = new DateTime(2016, 1, 1); var testValues = new List<decimal> { 1.38687m, 1.38688m, 1.38687m, 1.38686m, 1.38685m, 1.38683m, 1.38682m, 1.38682m, 1.38684m, 1.38682m, 1.38682m, 1.38680m, 1.38681m, 1.38686m, 1.38688m, 1.38688m, 1.38690m, 1.38690m, 1.38691m, 1.38692m, 1.38694m, 1.38695m, 1.38697m, 1.38697m, 1.38700m, 1.38699m, 1.38699m, 1.38699m, 1.38698m, 1.38699m, 1.38697m, 1.38698m, 1.38698m, 1.38697m, 1.38698m, 1.38698m, 1.38697m, 1.38697m, 1.38700m, 1.38702m, 1.38701m, 1.38699m, 1.38697m, 1.38698m, 1.38696m, 1.38698m, 1.38697m, 1.38695m, 1.38695m, 1.38696m, 1.38693m, 1.38692m, 1.38693m, 1.38693m, 1.38692m, 1.38693m, 1.38692m, 1.38690m, 1.38686m, 1.38685m, 1.38687m, 1.38686m, 1.38686m, 1.38686m, 1.38686m, 1.38685m, 1.38684m, 1.38678m, 1.38679m, 1.38680m, 1.38680m, 1.38681m, 1.38685m, 1.38685m, 1.38683m, 1.38682m, 1.38682m, 1.38683m, 1.38682m, 1.38683m, 1.38682m, 1.38681m, 1.38680m, 1.38681m, 1.38681m, 1.38681m, 1.38682m, 1.38680m, 1.38679m, 1.38678m, 1.38675m, 1.38678m, 1.38678m, 1.38678m, 1.38682m, 1.38681m, 1.38682m, 1.38680m, 1.38682m, 1.38683m, 1.38685m, 1.38683m, 1.38683m, 1.38684m, 1.38683m, 1.38683m, 1.38684m, 1.38685m, 1.38684m, 1.38683m, 1.38686m, 1.38685m, 1.38685m, 1.38684m, 1.38685m, 1.38682m, 1.38684m, 1.38683m, 1.38682m, 1.38683m, 1.38685m, 1.38685m, 1.38685m, 1.38683m, 1.38685m, 1.38684m, 1.38686m, 1.38693m, 1.38695m, 1.38693m, 1.38694m, 1.38693m, 1.38692m, 1.38693m, 1.38695m, 1.38697m, 1.38698m, 1.38695m, 1.38696m }; var consolidator1 = new RenkoConsolidator(0.0001m); var consolidator2 = new RenkoConsolidator(0.0001m); var consolidator3 = new RenkoConsolidator(0.0001m); // Update each of our consolidators starting at different indexes of test values for (int i = 0; i < testValues.Count; i++) { var data = new IndicatorDataPoint(time.AddSeconds(i), testValues[i]); consolidator1.Update(data); if (i > 10) { consolidator2.Update(data); } if (i > 20) { consolidator3.Update(data); } } // Assert that consolidator 2 and 3 price is the same as 1. Even though they started at different // indexes they should be the same var bar1 = consolidator1.Consolidated as RenkoBar; var bar2 = consolidator2.Consolidated as RenkoBar; var bar3 = consolidator3.Consolidated as RenkoBar; Assert.AreEqual(bar1.Close, bar2.Close); Assert.AreEqual(bar1.Close, bar3.Close); consolidator1.Dispose(); consolidator2.Dispose(); consolidator3.Dispose(); } private class TestRenkoConsolidator : RenkoConsolidator { public TestRenkoConsolidator(decimal barSize) : base(barSize) { } public RenkoBar OpenRenko() { return new RenkoBar(null, OpenOn, CloseOn, BarSize, OpenRate, HighRate, LowRate, CloseRate); } } } }
using System; using System.Linq.Expressions; using System.Reflection; using System.Reflection.Emit; namespace BTDB.IL; public static class ILGenExtensions { public static IILGen Do(this IILGen il, Action<IILGen> action) { action(il); return il; } public static IILGen LdcI4(this IILGen il, int value) { switch (value) { case 0: il.Emit(OpCodes.Ldc_I4_0); break; case 1: il.Emit(OpCodes.Ldc_I4_1); break; case 2: il.Emit(OpCodes.Ldc_I4_2); break; case 3: il.Emit(OpCodes.Ldc_I4_3); break; case 4: il.Emit(OpCodes.Ldc_I4_4); break; case 5: il.Emit(OpCodes.Ldc_I4_5); break; case 6: il.Emit(OpCodes.Ldc_I4_6); break; case 7: il.Emit(OpCodes.Ldc_I4_7); break; case 8: il.Emit(OpCodes.Ldc_I4_8); break; case -1: il.Emit(OpCodes.Ldc_I4_M1); break; default: if (value >= -128 && value <= 127) il.Emit(OpCodes.Ldc_I4_S, (sbyte)value); else il.Emit(OpCodes.Ldc_I4, value); break; } return il; } public static IILGen LdcI8(this IILGen il, long value) { il.Emit(OpCodes.Ldc_I8, value); return il; } public static IILGen LdcR4(this IILGen il, float value) { il.Emit(OpCodes.Ldc_R4, value); return il; } public static IILGen LdcR8(this IILGen il, double value) { il.Emit(OpCodes.Ldc_R8, value); return il; } public static IILGen Ldarg(this IILGen il, ushort parameterIndex) { switch (parameterIndex) { case 0: il.Emit(OpCodes.Ldarg_0); break; case 1: il.Emit(OpCodes.Ldarg_1); break; case 2: il.Emit(OpCodes.Ldarg_2); break; case 3: il.Emit(OpCodes.Ldarg_3); break; default: if (parameterIndex <= 255) il.Emit(OpCodes.Ldarg_S, (byte)parameterIndex); else il.Emit(OpCodes.Ldarg, parameterIndex); break; } return il; } public static IILGen Starg(this IILGen il, ushort parameterIndex) { if (parameterIndex <= 255) il.Emit(OpCodes.Starg_S, (byte)parameterIndex); else il.Emit(OpCodes.Starg, parameterIndex); return il; } public static IILGen Ldfld(this IILGen il, FieldInfo fieldInfo) { il.Emit(OpCodes.Ldfld, fieldInfo); return il; } public static IILGen Ldfld(this IILGen il, IILField fieldInfo) { il.Emit(OpCodes.Ldfld, fieldInfo); return il; } public static IILGen Ldflda(this IILGen il, FieldInfo fieldInfo) { il.Emit(OpCodes.Ldflda, fieldInfo); return il; } public static IILGen Ldflda(this IILGen il, IILField fieldInfo) { il.Emit(OpCodes.Ldflda, fieldInfo); return il; } public static IILGen Ldsfld(this IILGen il, FieldInfo fieldInfo) { il.Emit(OpCodes.Ldsfld, fieldInfo); return il; } public static IILGen Ldsfld(this IILGen il, IILField fieldInfo) { il.Emit(OpCodes.Ldsfld, fieldInfo); return il; } public static IILGen Stfld(this IILGen il, FieldInfo fieldInfo) { il.Emit(OpCodes.Stfld, fieldInfo); return il; } public static IILGen Stfld(this IILGen il, IILField fieldInfo) { il.Emit(OpCodes.Stfld, fieldInfo); return il; } public static IILGen Stsfld(this IILGen il, FieldInfo fieldInfo) { il.Emit(OpCodes.Stsfld, fieldInfo); return il; } public static IILGen Stsfld(this IILGen il, IILField fieldInfo) { il.Emit(OpCodes.Stsfld, fieldInfo); return il; } public static IILGen Stloc(this IILGen il, ushort localVariableIndex) { switch (localVariableIndex) { case 0: il.Emit(OpCodes.Stloc_0); break; case 1: il.Emit(OpCodes.Stloc_1); break; case 2: il.Emit(OpCodes.Stloc_2); break; case 3: il.Emit(OpCodes.Stloc_3); break; case 65535: throw new ArgumentOutOfRangeException(nameof(localVariableIndex)); default: if (localVariableIndex <= 255) il.Emit(OpCodes.Stloc_S, (byte)localVariableIndex); else il.Emit(OpCodes.Stloc, localVariableIndex); break; } return il; } public static IILGen Stloc(this IILGen il, IILLocal localBuilder) { il.Emit(OpCodes.Stloc, localBuilder); return il; } public static IILGen Ldloc(this IILGen il, ushort localVariableIndex) { switch (localVariableIndex) { case 0: il.Emit(OpCodes.Ldloc_0); break; case 1: il.Emit(OpCodes.Ldloc_1); break; case 2: il.Emit(OpCodes.Ldloc_2); break; case 3: il.Emit(OpCodes.Ldloc_3); break; case 65535: throw new ArgumentOutOfRangeException(nameof(localVariableIndex)); default: if (localVariableIndex <= 255) il.Emit(OpCodes.Ldloc_S, (byte)localVariableIndex); else il.Emit(OpCodes.Ldloc, localVariableIndex); break; } return il; } public static IILGen Ldloc(this IILGen il, IILLocal localBuilder) { il.Emit(OpCodes.Ldloc, localBuilder); return il; } public static IILGen Ldloca(this IILGen il, IILLocal localBuilder) { il.Emit(OpCodes.Ldloca, localBuilder); return il; } public static IILGen Constrained(this IILGen il, Type type) { il.Emit(OpCodes.Constrained, type); return il; } public static IILGen BleUnS(this IILGen il, IILLabel targetLabel) { il.Emit(OpCodes.Ble_Un_S, targetLabel); return il; } public static IILGen Blt(this IILGen il, IILLabel targetLabel) { il.Emit(OpCodes.Blt, targetLabel); return il; } public static IILGen Bgt(this IILGen il, IILLabel targetLabel) { il.Emit(OpCodes.Bgt, targetLabel); return il; } public static IILGen Brfalse(this IILGen il, IILLabel targetLabel) { il.Emit(OpCodes.Brfalse, targetLabel); return il; } public static IILGen BrfalseS(this IILGen il, IILLabel targetLabel) { il.Emit(OpCodes.Brfalse_S, targetLabel); return il; } public static IILGen Brtrue(this IILGen il, IILLabel targetLabel) { il.Emit(OpCodes.Brtrue, targetLabel); return il; } public static IILGen BrtrueS(this IILGen il, IILLabel targetLabel) { il.Emit(OpCodes.Brtrue_S, targetLabel); return il; } public static IILGen Br(this IILGen il, IILLabel targetLabel) { il.Emit(OpCodes.Br, targetLabel); return il; } public static IILGen BrS(this IILGen il, IILLabel targetLabel) { il.Emit(OpCodes.Br_S, targetLabel); return il; } public static IILGen BneUnS(this IILGen il, IILLabel targetLabel) { il.Emit(OpCodes.Bne_Un_S, targetLabel); return il; } public static IILGen BeqS(this IILGen il, IILLabel targetLabel) { il.Emit(OpCodes.Beq_S, targetLabel); return il; } public static IILGen Beq(this IILGen il, IILLabel targetLabel) { il.Emit(OpCodes.Beq, targetLabel); return il; } public static IILGen BgeUnS(this IILGen il, IILLabel targetLabel) { il.Emit(OpCodes.Bge_Un_S, targetLabel); return il; } public static IILGen BgeUn(this IILGen il, IILLabel targetLabel) { il.Emit(OpCodes.Bge_Un, targetLabel); return il; } public static IILGen Newobj(this IILGen il, ConstructorInfo constructorInfo) { il.Emit(OpCodes.Newobj, constructorInfo); return il; } public static IILGen InitObj(this IILGen il, Type type) { il.Emit(OpCodes.Initobj, type); return il; } public static IILGen Callvirt(this IILGen il, MethodInfo methodInfo) { if (methodInfo.IsStatic) throw new ArgumentException("Method in Callvirt cannot be static"); il.Emit(OpCodes.Callvirt, methodInfo); return il; } public static IILGen Call(this IILGen il, MethodInfo methodInfo) { il.Emit(OpCodes.Call, methodInfo); return il; } public static IILGen Call(this IILGen il, ConstructorInfo constructorInfo) { il.Emit(OpCodes.Call, constructorInfo); return il; } public static IILGen Ldftn(this IILGen il, MethodInfo methodInfo) { il.Emit(OpCodes.Ldftn, methodInfo); return il; } public static IILGen Ldnull(this IILGen il) { il.Emit(OpCodes.Ldnull); return il; } public static IILGen Throw(this IILGen il) { il.Emit(OpCodes.Throw); return il; } public static IILGen Ret(this IILGen il) { il.Emit(OpCodes.Ret); return il; } public static IILGen Pop(this IILGen il) { il.Emit(OpCodes.Pop); return il; } public static IILGen Castclass(this IILGen il, Type toType) { il.Emit(OpCodes.Castclass, toType); return il; } public static IILGen Isinst(this IILGen il, Type asType) { il.Emit(OpCodes.Isinst, asType); return il; } public static IILGen ConvU1(this IILGen il) { il.Emit(OpCodes.Conv_U1); return il; } public static IILGen ConvU2(this IILGen il) { il.Emit(OpCodes.Conv_U2); return il; } public static IILGen ConvU4(this IILGen il) { il.Emit(OpCodes.Conv_U4); return il; } public static IILGen ConvU8(this IILGen il) { il.Emit(OpCodes.Conv_U8); return il; } public static IILGen ConvI1(this IILGen il) { il.Emit(OpCodes.Conv_I1); return il; } public static IILGen ConvI2(this IILGen il) { il.Emit(OpCodes.Conv_I2); return il; } public static IILGen ConvI4(this IILGen il) { il.Emit(OpCodes.Conv_I4); return il; } public static IILGen ConvI8(this IILGen il) { il.Emit(OpCodes.Conv_I8); return il; } public static IILGen ConvR4(this IILGen il) { il.Emit(OpCodes.Conv_R4); return il; } public static IILGen ConvR8(this IILGen il) { il.Emit(OpCodes.Conv_R8); return il; } public static IILGen Tail(this IILGen il) { il.Emit(OpCodes.Tailcall); return il; } public static IILGen LdelemRef(this IILGen il) { il.Emit(OpCodes.Ldelem_Ref); return il; } public static IILGen Ldelema(this IILGen il, Type itemType) { il.Emit(OpCodes.Ldelema, itemType); return il; } public static IILGen StelemRef(this IILGen il) { il.Emit(OpCodes.Stelem_Ref); return il; } public static IILGen Ldelem(this IILGen il, Type itemType) { if (itemType == typeof(int)) il.Emit(OpCodes.Ldelem_I4); else if (itemType == typeof(short)) il.Emit(OpCodes.Ldelem_I2); else if (itemType == typeof(sbyte)) il.Emit(OpCodes.Ldelem_I1); else if (itemType == typeof(long)) il.Emit(OpCodes.Ldelem_I8); else if (itemType == typeof(ushort)) il.Emit(OpCodes.Ldelem_U2); else if (itemType == typeof(byte)) il.Emit(OpCodes.Ldelem_U1); else if (itemType == typeof(uint)) il.Emit(OpCodes.Ldelem_U4); else if (itemType == typeof(float)) il.Emit(OpCodes.Ldelem_R4); else if (itemType == typeof(double)) il.Emit(OpCodes.Ldelem_R8); else if (!itemType.IsValueType) il.Emit(OpCodes.Ldelem_Ref); else il.Emit(OpCodes.Ldelem, itemType); return il; } public static IILGen Stelem(this IILGen il, Type itemType) { if (itemType == typeof(int)) il.Emit(OpCodes.Stelem_I4); else if (itemType == typeof(short)) il.Emit(OpCodes.Stelem_I2); else if (itemType == typeof(sbyte)) il.Emit(OpCodes.Stelem_I1); else if (itemType == typeof(long)) il.Emit(OpCodes.Stelem_I8); else if (itemType == typeof(float)) il.Emit(OpCodes.Stelem_R4); else if (itemType == typeof(double)) il.Emit(OpCodes.Stelem_R8); else if (!itemType.IsValueType) il.Emit(OpCodes.Stelem_Ref); else il.Emit(OpCodes.Stelem, itemType); return il; } public static IILGen Ldind(this IILGen il, Type itemType) { if (itemType == typeof(int)) il.Emit(OpCodes.Ldind_I4); else if (itemType == typeof(short)) il.Emit(OpCodes.Ldind_I2); else if (itemType == typeof(sbyte)) il.Emit(OpCodes.Ldind_I1); else if (itemType == typeof(long)) il.Emit(OpCodes.Ldind_I8); else if (itemType == typeof(ushort)) il.Emit(OpCodes.Ldind_U2); else if (itemType == typeof(byte)) il.Emit(OpCodes.Ldind_U1); else if (itemType == typeof(uint)) il.Emit(OpCodes.Ldind_U4); else if (itemType == typeof(float)) il.Emit(OpCodes.Ldind_R4); else if (itemType == typeof(double)) il.Emit(OpCodes.Ldind_R8); else if (!itemType.IsValueType) il.Emit(OpCodes.Ldind_Ref); else throw new ArgumentOutOfRangeException(nameof(itemType)); return il; } public static IILGen Add(this IILGen il) { il.Emit(OpCodes.Add); return il; } public static IILGen Sub(this IILGen il) { il.Emit(OpCodes.Sub); return il; } public static IILGen Mul(this IILGen il) { il.Emit(OpCodes.Mul); return il; } public static IILGen Div(this IILGen il) { il.Emit(OpCodes.Div); return il; } public static IILGen Dup(this IILGen il) { il.Emit(OpCodes.Dup); return il; } public static IILGen Ldtoken(this IILGen il, Type type) { il.Emit(OpCodes.Ldtoken, type); return il; } public static IILGen Callvirt(this IILGen il, Expression<Action> expression) { var methodInfo = ((MethodCallExpression)expression.Body).Method; return il.Callvirt(methodInfo); } public static IILGen Callvirt<T>(this IILGen il, Expression<Func<T>> expression) { if (expression.Body is MemberExpression newExpression) { return il.Callvirt(((PropertyInfo)newExpression.Member).GetAnyGetMethod()!); } var methodInfo = ((MethodCallExpression)expression.Body).Method; return il.Callvirt(methodInfo); } public static IILGen Call(this IILGen il, Expression<Action> expression) { if (expression.Body is NewExpression newExpression) { return il.Call(newExpression.Constructor); } var methodInfo = ((MethodCallExpression)expression.Body).Method; return il.Call(methodInfo); } public static IILGen Call<T>(this IILGen il, Expression<Func<T>> expression) { if (expression.Body is MemberExpression memberExpression) { return il.Call(((PropertyInfo)memberExpression.Member).GetAnyGetMethod()!); } if (expression.Body is NewExpression newExpression) { return il.Call(newExpression.Constructor); } var methodInfo = ((MethodCallExpression)expression.Body).Method; return il.Call(methodInfo); } public static IILGen Newobj<T>(this IILGen il, Expression<Func<T>> expression) { var constructorInfo = ((NewExpression)expression.Body).Constructor; return il.Newobj(constructorInfo); } public static IILGen Ldfld<T>(this IILGen il, Expression<Func<T>> expression) { return il.Ldfld((FieldInfo)((MemberExpression)expression.Body).Member); } public static IILGen Newarr(this IILGen il, Type arrayMemberType) { il.Emit(OpCodes.Newarr, arrayMemberType); return il; } public static IILGen Box(this IILGen il, Type boxedType) { il.Emit(OpCodes.Box, boxedType); return il; } public static IILGen Unbox(this IILGen il, Type valueType) { if (!valueType.IsValueType) throw new ArgumentException("Unboxed could be only valuetype"); il.Emit(OpCodes.Unbox, valueType); return il; } public static IILGen UnboxAny(this IILGen il, Type anyType) { il.Emit(OpCodes.Unbox_Any, anyType); return il; } public static IILGen Break(this IILGen il) { il.Emit(OpCodes.Break); return il; } public static IILGen Localloc(this IILGen il) { il.Emit(OpCodes.Localloc); return il; } public static IILGen Localloc(this IILGen il, uint length) { il .LdcI4((int)length) .Emit(OpCodes.Conv_U); il .Emit(OpCodes.Localloc); return il; } public static IILGen Ld(this IILGen il, object? value) { switch (value) { case null: il.Ldnull(); break; case bool b when !b: il.LdcI4(0); break; case bool b when b: il.LdcI4(1); break; case short i16: il.LdcI4(i16); // there is no instruction for 16b int break; case int i32: il.LdcI4(i32); break; case long i64: il.LdcI8(i64); break; case float f: il.LdcR4(f); break; case double d: il.LdcR8(d); break; case string s: il.Ldstr(s); break; default: throw new ArgumentException($"{value} is not supported.", nameof(value)); } return il; } public static IILGen Ceq(this IILGen il) { il.Emit(OpCodes.Ceq); return il; } public static IILGen Cgt(this IILGen il) { il.Emit(OpCodes.Cgt); return il; } public static IILGen CgtUn(this IILGen il) { il.Emit(OpCodes.Cgt_Un); return il; } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using ComplexTestSupport; using Xunit; namespace System.Numerics.Tests { public class arithmaticOperation_BinaryDivide_DivideTest { // Verification is done with Abs and Conjugate methods private static void VerifyBinaryDivideResult(double realFirst, double imgFirst, double realSecond, double imgSecond) { // Create complex numbers Complex cFirst = new Complex(realFirst, imgFirst); Complex cSecond = new Complex(realSecond, imgSecond); Complex cExpectedResult = (cFirst * Complex.Conjugate(cSecond)); double cExpectedReal = cExpectedResult.Real; double cExpectedImaginary = cExpectedResult.Imaginary; if (!double.IsInfinity(cExpectedReal)) { cExpectedReal = cExpectedReal / (cSecond.Magnitude * cSecond.Magnitude); } if (!double.IsInfinity(cExpectedImaginary)) { cExpectedImaginary = cExpectedImaginary / (cSecond.Magnitude * cSecond.Magnitude); } // local variables Complex cResult; // arithmetic binary divide operation cResult = cFirst / cSecond; // verify the result Support.VerifyRealImaginaryProperties(cResult, cExpectedReal, cExpectedImaginary, string.Format("Binary Divide test = ({0}, {1}) / ({2}, {3})", realFirst, imgFirst, realSecond, imgSecond)); // arithmetic divide (static) operation cResult = Complex.Divide(cFirst, cSecond); // verify the result Support.VerifyRealImaginaryProperties(cResult, cExpectedReal, cExpectedImaginary, string.Format("Divide (Static) test = ({0}, {1}) / ({2}, {3})", realFirst, imgFirst, realSecond, imgSecond)); } [Fact] public static void RunTests_ZeroOneImaginaryOne() { double real = 10; double imaginary = 50; // Test with Zero VerifyBinaryDivideResult(0.0, 0.0, real, imaginary); // Verify 0/x=0 VerifyBinaryDivideResult(real, imaginary, 0.0, 0.0); // Verify x0=0 // Test with One VerifyBinaryDivideResult(1.0, 0.0, real, imaginary); // Verify 1/x=x VerifyBinaryDivideResult(real, imaginary, 1.0, 0.0); // Verify x/1=x // Test with ImaginaryOne VerifyBinaryDivideResult(0.0, 1.0, real, imaginary); // Verify -i/x VerifyBinaryDivideResult(real, imaginary, 0.0, 1.0); // Verify x/-i } [Fact] public static void RunTests_BoundaryValues() { double real = Support.GetSmallRandomDoubleValue(false); double img = Support.GetSmallRandomDoubleValue(false); // test with 'Max' VerifyBinaryDivideResult(double.MaxValue, double.MaxValue, real, img); // test with 'Min' VerifyBinaryDivideResult(double.MinValue, double.MinValue, real, img); } [Fact] public static void RunTests_RandomValidValues() { // Verify test results with ComplexInFirstQuad / ComplexInFirstQuad double realFirst = Support.GetSmallRandomDoubleValue(false); double imgFirst = Support.GetSmallRandomDoubleValue(false); double realSecond = Support.GetSmallRandomDoubleValue(false); double imgSecond = Support.GetSmallRandomDoubleValue(false); VerifyBinaryDivideResult(realFirst, imgFirst, realSecond, imgSecond); // Verify test results with ComplexInFirstQuad / ComplexInSecondQuad realFirst = Support.GetSmallRandomDoubleValue(false); imgFirst = Support.GetSmallRandomDoubleValue(false); realSecond = Support.GetSmallRandomDoubleValue(true); imgSecond = Support.GetSmallRandomDoubleValue(false); VerifyBinaryDivideResult(realFirst, imgFirst, realSecond, imgSecond); // Verify test results with ComplexInFirstQuad / ComplexInThirdQuad realFirst = Support.GetSmallRandomDoubleValue(false); imgFirst = Support.GetSmallRandomDoubleValue(false); realSecond = Support.GetSmallRandomDoubleValue(true); imgSecond = Support.GetSmallRandomDoubleValue(true); VerifyBinaryDivideResult(realFirst, imgFirst, realSecond, imgSecond); // Verify test results with ComplexInFirstQuad / ComplexInFourthQuad realFirst = Support.GetSmallRandomDoubleValue(false); imgFirst = Support.GetSmallRandomDoubleValue(false); realSecond = Support.GetSmallRandomDoubleValue(false); imgSecond = Support.GetSmallRandomDoubleValue(true); VerifyBinaryDivideResult(realFirst, imgFirst, realSecond, imgSecond); // Verify test results with ComplexInSecondQuad / ComplexInSecondQuad realFirst = Support.GetSmallRandomDoubleValue(true); imgFirst = Support.GetSmallRandomDoubleValue(false); realSecond = Support.GetSmallRandomDoubleValue(true); imgSecond = Support.GetSmallRandomDoubleValue(false); VerifyBinaryDivideResult(realFirst, imgFirst, realSecond, imgSecond); // Verify test results with ComplexInSecondQuad / ComplexInThirdQuad realFirst = Support.GetSmallRandomDoubleValue(true); imgFirst = Support.GetSmallRandomDoubleValue(false); realSecond = Support.GetSmallRandomDoubleValue(true); imgSecond = Support.GetSmallRandomDoubleValue(true); VerifyBinaryDivideResult(realFirst, imgFirst, realSecond, imgSecond); // Verify test results with ComplexInSecondQuad / ComplexInFourthQuad realFirst = Support.GetSmallRandomDoubleValue(true); imgFirst = Support.GetSmallRandomDoubleValue(false); realSecond = Support.GetSmallRandomDoubleValue(false); imgSecond = Support.GetSmallRandomDoubleValue(true); VerifyBinaryDivideResult(realFirst, imgFirst, realSecond, imgSecond); // Verify test results with ComplexInThirdQuad / ComplexInThirdQuad realFirst = Support.GetSmallRandomDoubleValue(true); imgFirst = Support.GetSmallRandomDoubleValue(true); realSecond = Support.GetSmallRandomDoubleValue(true); imgSecond = Support.GetSmallRandomDoubleValue(true); VerifyBinaryDivideResult(realFirst, imgFirst, realSecond, imgSecond); // Verify test results with ComplexInThirdQuad / ComplexInFourthQuad realFirst = Support.GetSmallRandomDoubleValue(true); imgFirst = Support.GetSmallRandomDoubleValue(true); realSecond = Support.GetSmallRandomDoubleValue(false); imgSecond = Support.GetSmallRandomDoubleValue(true); VerifyBinaryDivideResult(realFirst, imgFirst, realSecond, imgSecond); // Verify test results with ComplexInFourthQuad / ComplexInFourthQuad realFirst = Support.GetSmallRandomDoubleValue(true); imgFirst = Support.GetSmallRandomDoubleValue(false); realSecond = Support.GetSmallRandomDoubleValue(true); imgSecond = Support.GetSmallRandomDoubleValue(false); VerifyBinaryDivideResult(realFirst, imgFirst, realSecond, imgSecond); } [Fact] public static void RunTests_InvalidImaginaryValues() { double realFirst; double imgFirst; double realSecond; double imgSecond; // Verify with (valid, PositiveInfinity) / (valid, PositiveValid) realFirst = Support.GetSmallRandomDoubleValue(false); imgFirst = double.PositiveInfinity; realSecond = Support.GetSmallRandomDoubleValue(false); imgSecond = Support.GetSmallRandomDoubleValue(false); VerifyBinaryDivideResult(realFirst, imgFirst, realSecond, imgSecond); // Verify with (valid, PositiveInfinity) / (valid, NegativeValid) realFirst = Support.GetSmallRandomDoubleValue(false); imgFirst = double.PositiveInfinity; realSecond = Support.GetSmallRandomDoubleValue(false); imgSecond = Support.GetSmallRandomDoubleValue(true); VerifyBinaryDivideResult(realFirst, imgFirst, realSecond, imgSecond); // Verify with (valid, NegativeInfinity) / (valid, PositiveValid) realFirst = Support.GetSmallRandomDoubleValue(false); imgFirst = double.NegativeInfinity; realSecond = Support.GetSmallRandomDoubleValue(false); imgSecond = Support.GetSmallRandomDoubleValue(false); VerifyBinaryDivideResult(realFirst, imgFirst, realSecond, imgSecond); // Verify with (valid, NegativeInfinity) / (valid, NegativeValid) realFirst = Support.GetSmallRandomDoubleValue(false); imgFirst = double.NegativeInfinity; realSecond = Support.GetSmallRandomDoubleValue(false); imgSecond = Support.GetSmallRandomDoubleValue(true); VerifyBinaryDivideResult(realFirst, imgFirst, realSecond, imgSecond); // Verify with (valid, NaN) / (valid, Valid) realFirst = Support.GetSmallRandomDoubleValue(false); imgFirst = double.NaN; realSecond = Support.GetSmallRandomDoubleValue(false); imgSecond = Support.GetSmallRandomDoubleValue(false); VerifyBinaryDivideResult(realFirst, imgFirst, realSecond, imgSecond); } [Fact] public static void RunTests_InvalidRealValues() { double realFirst; double imgFirst; double realSecond; double imgSecond; // Verify with (PositiveInfinity, valid) / (PositiveValid, valid) realFirst = double.PositiveInfinity; imgFirst = Support.GetSmallRandomDoubleValue(false); realSecond = Support.GetSmallRandomDoubleValue(false); imgSecond = Support.GetSmallRandomDoubleValue(false); VerifyBinaryDivideResult(realFirst, imgFirst, realSecond, imgSecond); // Verify with (PositiveInfinity, valid) / (NegativeValid, valid) realFirst = double.PositiveInfinity; imgFirst = Support.GetSmallRandomDoubleValue(false); realSecond = Support.GetSmallRandomDoubleValue(true); imgSecond = Support.GetSmallRandomDoubleValue(false); VerifyBinaryDivideResult(realFirst, imgFirst, realSecond, imgSecond); // Verify with (NegativeInfinity, valid) / (PositiveValid, valid) realFirst = double.NegativeInfinity; imgFirst = Support.GetSmallRandomDoubleValue(false); realSecond = Support.GetSmallRandomDoubleValue(false); imgSecond = Support.GetSmallRandomDoubleValue(false); VerifyBinaryDivideResult(realFirst, imgFirst, realSecond, imgSecond); // Verify with (NegativeInfinity, valid) / (NegativeValid, valid) realFirst = double.NegativeInfinity; imgFirst = Support.GetSmallRandomDoubleValue(false); realSecond = Support.GetSmallRandomDoubleValue(true); imgSecond = Support.GetSmallRandomDoubleValue(false); VerifyBinaryDivideResult(realFirst, imgFirst, realSecond, imgSecond); // Verify with (NaN, valid) / (valid, valid) realFirst = double.NaN; imgFirst = Support.GetSmallRandomDoubleValue(false); realSecond = Support.GetSmallRandomDoubleValue(false); imgSecond = Support.GetSmallRandomDoubleValue(false); VerifyBinaryDivideResult(realFirst, imgFirst, realSecond, imgSecond); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.Implementation.Outlining; using Microsoft.CodeAnalysis.Editor.Shared.Options; using Microsoft.CodeAnalysis.Editor.Shared.Tagging; using Microsoft.CodeAnalysis.Editor.Tagging; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Projection; using Microsoft.VisualStudio.Text.Tagging; using Moq; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Tagging { public class AsynchronousTaggerTests : TestBase { /// <summary> /// This hits a special codepath in the product that is optimized for more than 100 spans. /// I'm leaving this test here because it covers that code path (as shown by code coverage) /// </summary> [WpfFact] [WorkItem(530368)] public async Task LargeNumberOfSpans() { using (var workspace = await CSharpWorkspaceFactory.CreateWorkspaceFromFileAsync(@"class Program { void M() { int z = 0; z = z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z; } }")) { Callback tagProducer = (span, cancellationToken) => { return new List<ITagSpan<TestTag>>() { new TagSpan<TestTag>(span, new TestTag()) }; }; var asyncListener = new TaggerOperationListener(); var notificationService = workspace.GetService<IForegroundNotificationService>(); var eventSource = CreateEventSource(); var taggerProvider = new TestTaggerProvider( tagProducer, eventSource, workspace, asyncListener, notificationService); var document = workspace.Documents.First(); var textBuffer = document.TextBuffer; var snapshot = textBuffer.CurrentSnapshot; var tagger = taggerProvider.CreateTagger<TestTag>(textBuffer); using (IDisposable disposable = (IDisposable)tagger) { var spans = Enumerable.Range(0, 101).Select(i => new Span(i * 4, 1)); var snapshotSpans = new NormalizedSnapshotSpanCollection(snapshot, spans); eventSource.SendUpdateEvent(); await asyncListener.CreateWaitTask(); var tags = tagger.GetTags(snapshotSpans); Assert.Equal(1, tags.Count()); } } } [WpfFact] public async Task TestSynchronousOutlining() { using (var workspace = await CSharpWorkspaceFactory.CreateWorkspaceFromFileAsync("class Program {\r\n\r\n}")) { var tagProvider = new OutliningTaggerProvider( workspace.GetService<IForegroundNotificationService>(), workspace.GetService<ITextEditorFactoryService>(), workspace.GetService<IEditorOptionsFactoryService>(), workspace.GetService<IProjectionBufferFactoryService>(), workspace.ExportProvider.GetExports<IAsynchronousOperationListener, FeatureMetadata>()); var document = workspace.Documents.First(); var textBuffer = document.TextBuffer; var tagger = tagProvider.CreateTagger<IOutliningRegionTag>(textBuffer); using (var disposable = (IDisposable)tagger) { // The very first all to get tags should return the single outlining span. var tags = tagger.GetAllTags(new NormalizedSnapshotSpanCollection(textBuffer.CurrentSnapshot.GetFullSpan()), CancellationToken.None); Assert.Equal(1, tags.Count()); } } } private static TestTaggerEventSource CreateEventSource() { return new TestTaggerEventSource(); } private static Mock<IOptionService> CreateFeatureOptionsMock() { var featureOptions = new Mock<IOptionService>(MockBehavior.Strict); featureOptions.Setup(s => s.GetOption(EditorComponentOnOffOptions.Tagger)).Returns(true); return featureOptions; } private sealed class TaggerOperationListener : AsynchronousOperationListener { } private sealed class TestTag : TextMarkerTag { public TestTag() : base("Test") { } } private delegate List<ITagSpan<TestTag>> Callback(SnapshotSpan span, CancellationToken cancellationToken); private sealed class TestTaggerProvider : AsynchronousTaggerProvider<TestTag> { private readonly Callback _callback; private readonly ITaggerEventSource _eventSource; private readonly Workspace _workspace; private readonly bool _disableCancellation; public TestTaggerProvider( Callback callback, ITaggerEventSource eventSource, Workspace workspace, IAsynchronousOperationListener asyncListener, IForegroundNotificationService notificationService, bool disableCancellation = false) : base(asyncListener, notificationService) { _callback = callback; _eventSource = eventSource; _workspace = workspace; _disableCancellation = disableCancellation; } protected override ITaggerEventSource CreateEventSource(ITextView textViewOpt, ITextBuffer subjectBuffer) { return _eventSource; } protected override Task ProduceTagsAsync(TaggerContext<TestTag> context, DocumentSnapshotSpan snapshotSpan, int? caretPosition) { var tags = _callback(snapshotSpan.SnapshotSpan, context.CancellationToken); if (tags != null) { foreach (var tag in tags) { context.AddTag(tag); } } return SpecializedTasks.EmptyTask; } } private sealed class TestTaggerEventSource : AbstractTaggerEventSource { public TestTaggerEventSource() : base(delay: TaggerDelay.NearImmediate) { } public void SendUpdateEvent() { this.RaiseChanged(); } public override void Connect() { } public override void Disconnect() { } } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.IO; using System.IO.Compression; using System.Reflection; using System.Net; using System.Text; using System.Web; using OpenSim.Server.Base; using OpenSim.Server.Handlers.Base; using OpenSim.Services.Interfaces; using GridRegion = OpenSim.Services.Interfaces.GridRegion; using OpenSim.Framework; using OpenSim.Framework.Servers.HttpServer; using OpenMetaverse; using OpenMetaverse.StructuredData; using Nini.Config; using log4net; namespace OpenSim.Server.Handlers.Simulation { public class AgentHandler { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private ISimulationService m_SimulationService; public AgentHandler() { } public AgentHandler(ISimulationService sim) { m_SimulationService = sim; } public Hashtable Handler(Hashtable request) { // m_log.Debug("[CONNECTION DEBUGGING]: AgentHandler Called"); // // m_log.Debug("---------------------------"); // m_log.Debug(" >> uri=" + request["uri"]); // m_log.Debug(" >> content-type=" + request["content-type"]); // m_log.Debug(" >> http-method=" + request["http-method"]); // m_log.Debug("---------------------------\n"); Hashtable responsedata = new Hashtable(); responsedata["content_type"] = "text/html"; responsedata["keepalive"] = false; UUID agentID; UUID regionID; string action; if (!Utils.GetParams((string)request["uri"], out agentID, out regionID, out action)) { m_log.InfoFormat("[AGENT HANDLER]: Invalid parameters for agent message {0}", request["uri"]); responsedata["int_response_code"] = 404; responsedata["str_response_string"] = "false"; return responsedata; } // Next, let's parse the verb string method = (string)request["http-method"]; if (method.Equals("DELETE")) { string auth_token = string.Empty; if (request.ContainsKey("auth")) auth_token = request["auth"].ToString(); DoAgentDelete(request, responsedata, agentID, action, regionID, auth_token); return responsedata; } else if (method.Equals("QUERYACCESS")) { DoQueryAccess(request, responsedata, agentID, regionID); return responsedata; } else { m_log.ErrorFormat("[AGENT HANDLER]: method {0} not supported in agent message {1} (caller is {2})", method, (string)request["uri"], Util.GetCallerIP(request)); responsedata["int_response_code"] = HttpStatusCode.MethodNotAllowed; responsedata["str_response_string"] = "Method not allowed"; return responsedata; } } protected virtual void DoQueryAccess(Hashtable request, Hashtable responsedata, UUID agentID, UUID regionID) { Culture.SetCurrentCulture(); EntityTransferContext ctx = new EntityTransferContext(); if (m_SimulationService == null) { m_log.Debug("[AGENT HANDLER]: Agent QUERY called. Harmless but useless."); responsedata["content_type"] = "application/json"; responsedata["int_response_code"] = HttpStatusCode.NotImplemented; responsedata["str_response_string"] = string.Empty; return; } // m_log.DebugFormat("[AGENT HANDLER]: Received QUERYACCESS with {0}", (string)request["body"]); OSDMap args = Utils.GetOSDMap((string)request["body"]); bool viaTeleport = true; if (args.ContainsKey("viaTeleport")) viaTeleport = args["viaTeleport"].AsBoolean(); Vector3 position = Vector3.Zero; if (args.ContainsKey("position")) position = Vector3.Parse(args["position"].AsString()); string agentHomeURI = null; if (args.ContainsKey("agent_home_uri")) agentHomeURI = args["agent_home_uri"].AsString(); // Decode the legacy (string) version and extract the number float theirVersion = 0f; if (args.ContainsKey("my_version")) { string theirVersionStr = args["my_version"].AsString(); string[] parts = theirVersionStr.Split(new char[] {'/'}); if (parts.Length > 1) theirVersion = float.Parse(parts[1]); } if (args.ContainsKey("context")) ctx.Unpack((OSDMap)args["context"]); // Decode the new versioning data float minVersionRequired = 0f; float maxVersionRequired = 0f; float minVersionProvided = 0f; float maxVersionProvided = 0f; if (args.ContainsKey("simulation_service_supported_min")) minVersionProvided = (float)args["simulation_service_supported_min"].AsReal(); if (args.ContainsKey("simulation_service_supported_max")) maxVersionProvided = (float)args["simulation_service_supported_max"].AsReal(); if (args.ContainsKey("simulation_service_accepted_min")) minVersionRequired = (float)args["simulation_service_accepted_min"].AsReal(); if (args.ContainsKey("simulation_service_accepted_max")) maxVersionRequired = (float)args["simulation_service_accepted_max"].AsReal(); responsedata["int_response_code"] = HttpStatusCode.OK; OSDMap resp = new OSDMap(3); float version = 0f; float outboundVersion = 0f; float inboundVersion = 0f; if (minVersionProvided == 0f) // string version or older { // If there is no version in the packet at all we're looking at 0.6 or // even more ancient. Refuse it. if(theirVersion == 0f) { resp["success"] = OSD.FromBoolean(false); resp["reason"] = OSD.FromString("Your region is running a old version of opensim no longer supported. Consider updating it"); responsedata["str_response_string"] = OSDParser.SerializeJsonString(resp, true); return; } version = theirVersion; if (version < VersionInfo.SimulationServiceVersionAcceptedMin || version > VersionInfo.SimulationServiceVersionAcceptedMax ) { resp["success"] = OSD.FromBoolean(false); resp["reason"] = OSD.FromString(String.Format("Your region protocol version is {0} and we accept only {1} - {2}. No version overlap.", theirVersion, VersionInfo.SimulationServiceVersionAcceptedMin, VersionInfo.SimulationServiceVersionAcceptedMax)); responsedata["str_response_string"] = OSDParser.SerializeJsonString(resp, true); return; } } else { // Test for no overlap if (minVersionProvided > VersionInfo.SimulationServiceVersionAcceptedMax || maxVersionProvided < VersionInfo.SimulationServiceVersionAcceptedMin) { resp["success"] = OSD.FromBoolean(false); resp["reason"] = OSD.FromString(String.Format("Your region provide protocol versions {0} - {1} and we accept only {2} - {3}. No version overlap.", minVersionProvided, maxVersionProvided, VersionInfo.SimulationServiceVersionAcceptedMin, VersionInfo.SimulationServiceVersionAcceptedMax)); responsedata["str_response_string"] = OSDParser.SerializeJsonString(resp, true); return; } if (minVersionRequired > VersionInfo.SimulationServiceVersionSupportedMax || maxVersionRequired < VersionInfo.SimulationServiceVersionSupportedMin) { resp["success"] = OSD.FromBoolean(false); resp["reason"] = OSD.FromString(String.Format("You require region protocol versions {0} - {1} and we provide only {2} - {3}. No version overlap.", minVersionRequired, maxVersionRequired, VersionInfo.SimulationServiceVersionSupportedMin, VersionInfo.SimulationServiceVersionSupportedMax)); responsedata["str_response_string"] = OSDParser.SerializeJsonString(resp, true); return; } // Determine versions to use // This is intentionally inverted. Inbound and Outbound refer to the direction of the transfer. // Therefore outbound means from the sender to the receier and inbound means from the receiver to the sender. // So outbound is what we will accept and inbound is what we will send. Confused yet? outboundVersion = Math.Min(maxVersionProvided, VersionInfo.SimulationServiceVersionAcceptedMax); inboundVersion = Math.Min(maxVersionRequired, VersionInfo.SimulationServiceVersionSupportedMax); } List<UUID> features = new List<UUID>(); if (args.ContainsKey("features")) { OSDArray array = (OSDArray)args["features"]; foreach (OSD o in array) features.Add(new UUID(o.AsString())); } GridRegion destination = new GridRegion(); destination.RegionID = regionID; string reason; // We're sending the version numbers down to the local connector to do the varregion check. ctx.InboundVersion = inboundVersion; ctx.OutboundVersion = outboundVersion; if (minVersionProvided == 0f) { ctx.InboundVersion = version; ctx.OutboundVersion = version; } bool result = m_SimulationService.QueryAccess(destination, agentID, agentHomeURI, viaTeleport, position, features, ctx, out reason); m_log.DebugFormat("[AGENT HANDLER]: QueryAccess returned {0} ({1}). Version={2}, {3}/{4}", result, reason, version, inboundVersion, outboundVersion); resp["success"] = OSD.FromBoolean(result); resp["reason"] = OSD.FromString(reason); string legacyVersion = String.Format("SIMULATION/{0}", version); resp["version"] = OSD.FromString(legacyVersion); resp["negotiated_inbound_version"] = OSD.FromReal(inboundVersion); resp["negotiated_outbound_version"] = OSD.FromReal(outboundVersion); OSDArray featuresWanted = new OSDArray(); foreach (UUID feature in features) featuresWanted.Add(OSD.FromString(feature.ToString())); resp["features"] = featuresWanted; // We must preserve defaults here, otherwise a false "success" will not be put into the JSON map! responsedata["str_response_string"] = OSDParser.SerializeJsonString(resp, true); // Console.WriteLine("str_response_string [{0}]", responsedata["str_response_string"]); } protected void DoAgentDelete(Hashtable request, Hashtable responsedata, UUID id, string action, UUID regionID, string auth_token) { if (string.IsNullOrEmpty(action)) m_log.DebugFormat("[AGENT HANDLER]: >>> DELETE <<< RegionID: {0}; from: {1}; auth_code: {2}", regionID, Util.GetCallerIP(request), auth_token); else m_log.DebugFormat("[AGENT HANDLER]: Release {0} to RegionID: {1}", id, regionID); GridRegion destination = new GridRegion(); destination.RegionID = regionID; if (action.Equals("release")) ReleaseAgent(regionID, id); else Util.FireAndForget( o => m_SimulationService.CloseAgent(destination, id, auth_token), null, "AgentHandler.DoAgentDelete"); responsedata["int_response_code"] = HttpStatusCode.OK; responsedata["str_response_string"] = "OpenSim agent " + id.ToString(); //m_log.DebugFormat("[AGENT HANDLER]: Agent {0} Released/Deleted from region {1}", id, regionID); } protected virtual void ReleaseAgent(UUID regionID, UUID id) { m_SimulationService.ReleaseAgent(regionID, id, ""); } } public class AgentPostHandler : BaseStreamHandler { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private ISimulationService m_SimulationService; protected bool m_Proxy = false; public AgentPostHandler(ISimulationService service) : base("POST", "/agent") { m_SimulationService = service; } public AgentPostHandler(string path) : base("POST", path) { m_SimulationService = null; } protected override byte[] ProcessRequest(string path, Stream request, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { // m_log.DebugFormat("[SIMULATION]: Stream handler called"); Hashtable keysvals = new Hashtable(); Hashtable headervals = new Hashtable(); string[] querystringkeys = httpRequest.QueryString.AllKeys; string[] rHeaders = httpRequest.Headers.AllKeys; keysvals.Add("uri", httpRequest.RawUrl); keysvals.Add("content-type", httpRequest.ContentType); keysvals.Add("http-method", httpRequest.HttpMethod); foreach (string queryname in querystringkeys) keysvals.Add(queryname, httpRequest.QueryString[queryname]); foreach (string headername in rHeaders) headervals[headername] = httpRequest.Headers[headername]; keysvals.Add("headers", headervals); keysvals.Add("querystringkeys", querystringkeys); httpResponse.StatusCode = 200; httpResponse.ContentType = "text/html"; httpResponse.KeepAlive = false; Encoding encoding = Encoding.UTF8; if (httpRequest.ContentType != "application/json") { httpResponse.StatusCode = 406; return encoding.GetBytes("false"); } string requestBody; Stream inputStream = request; Stream innerStream = null; try { if ((httpRequest.ContentType == "application/x-gzip" || httpRequest.Headers["Content-Encoding"] == "gzip") || (httpRequest.Headers["X-Content-Encoding"] == "gzip")) { innerStream = inputStream; inputStream = new GZipStream(innerStream, CompressionMode.Decompress); } using (StreamReader reader = new StreamReader(inputStream, encoding)) { requestBody = reader.ReadToEnd(); } } finally { if (innerStream != null) innerStream.Dispose(); inputStream.Dispose(); } keysvals.Add("body", requestBody); Hashtable responsedata = new Hashtable(); UUID agentID; UUID regionID; string action; if (!Utils.GetParams((string)keysvals["uri"], out agentID, out regionID, out action)) { m_log.InfoFormat("[AGENT HANDLER]: Invalid parameters for agent message {0}", keysvals["uri"]); httpResponse.StatusCode = 404; return encoding.GetBytes("false"); } DoAgentPost(keysvals, responsedata, agentID); httpResponse.StatusCode = (int)responsedata["int_response_code"]; return encoding.GetBytes((string)responsedata["str_response_string"]); } protected void DoAgentPost(Hashtable request, Hashtable responsedata, UUID id) { EntityTransferContext ctx = new EntityTransferContext(); OSDMap args = Utils.GetOSDMap((string)request["body"]); if (args == null) { responsedata["int_response_code"] = HttpStatusCode.BadRequest; responsedata["str_response_string"] = "Bad request"; return; } if (args.ContainsKey("context")) ctx.Unpack((OSDMap)args["context"]); AgentDestinationData data = CreateAgentDestinationData(); UnpackData(args, data, request); GridRegion destination = new GridRegion(); destination.RegionID = data.uuid; destination.RegionLocX = data.x; destination.RegionLocY = data.y; destination.RegionName = data.name; GridRegion gatekeeper = ExtractGatekeeper(data); AgentCircuitData aCircuit = new AgentCircuitData(); try { aCircuit.UnpackAgentCircuitData(args); } catch (Exception ex) { m_log.InfoFormat("[AGENT HANDLER]: exception on unpacking ChildCreate message {0}", ex.Message); responsedata["int_response_code"] = HttpStatusCode.BadRequest; responsedata["str_response_string"] = "Bad request"; return; } GridRegion source = null; if (args.ContainsKey("source_uuid")) { source = new GridRegion(); source.RegionLocX = Int32.Parse(args["source_x"].AsString()); source.RegionLocY = Int32.Parse(args["source_y"].AsString()); source.RegionName = args["source_name"].AsString(); source.RegionID = UUID.Parse(args["source_uuid"].AsString()); if (args.ContainsKey("source_server_uri")) source.RawServerURI = args["source_server_uri"].AsString(); else source.RawServerURI = null; } OSDMap resp = new OSDMap(2); string reason = String.Empty; // This is the meaning of POST agent //m_regionClient.AdjustUserInformation(aCircuit); //bool result = m_SimulationService.CreateAgent(destination, aCircuit, teleportFlags, out reason); bool result = CreateAgent(source, gatekeeper, destination, aCircuit, data.flags, data.fromLogin, ctx, out reason); resp["reason"] = OSD.FromString(reason); resp["success"] = OSD.FromBoolean(result); // Let's also send out the IP address of the caller back to the caller (HG 1.5) resp["your_ip"] = OSD.FromString(GetCallerIP(request)); // TODO: add reason if not String.Empty? responsedata["int_response_code"] = HttpStatusCode.OK; responsedata["str_response_string"] = OSDParser.SerializeJsonString(resp); } protected virtual AgentDestinationData CreateAgentDestinationData() { return new AgentDestinationData(); } protected virtual void UnpackData(OSDMap args, AgentDestinationData data, Hashtable request) { // retrieve the input arguments if (args.ContainsKey("destination_x") && args["destination_x"] != null) Int32.TryParse(args["destination_x"].AsString(), out data.x); else m_log.WarnFormat(" -- request didn't have destination_x"); if (args.ContainsKey("destination_y") && args["destination_y"] != null) Int32.TryParse(args["destination_y"].AsString(), out data.y); else m_log.WarnFormat(" -- request didn't have destination_y"); if (args.ContainsKey("destination_uuid") && args["destination_uuid"] != null) UUID.TryParse(args["destination_uuid"].AsString(), out data.uuid); if (args.ContainsKey("destination_name") && args["destination_name"] != null) data.name = args["destination_name"].ToString(); if (args.ContainsKey("teleport_flags") && args["teleport_flags"] != null) data.flags = args["teleport_flags"].AsUInteger(); } protected virtual GridRegion ExtractGatekeeper(AgentDestinationData data) { return null; } protected string GetCallerIP(Hashtable request) { if (request.ContainsKey("headers")) { Hashtable headers = (Hashtable)request["headers"]; //// DEBUG //foreach (object o in headers.Keys) // m_log.DebugFormat("XXX {0} = {1}", o.ToString(), (headers[o] == null? "null" : headers[o].ToString())); string xff = "X-Forwarded-For"; if (!headers.ContainsKey(xff)) xff = xff.ToLower(); if (!headers.ContainsKey(xff) || headers[xff] == null) { // m_log.WarnFormat("[AGENT HANDLER]: No XFF header"); return Util.GetCallerIP(request); } // m_log.DebugFormat("[AGENT HANDLER]: XFF is {0}", headers[xff]); IPEndPoint ep = Util.GetClientIPFromXFF((string)headers[xff]); if (ep != null) return ep.Address.ToString(); } // Oops return Util.GetCallerIP(request); } // subclasses can override this protected virtual bool CreateAgent(GridRegion source, GridRegion gatekeeper, GridRegion destination, AgentCircuitData aCircuit, uint teleportFlags, bool fromLogin, EntityTransferContext ctx, out string reason) { reason = String.Empty; // The data and protocols are already defined so this is just a dummy to satisfy the interface // TODO: make this end-to-end /* this needs to be sync if ((teleportFlags & (uint)TeleportFlags.ViaLogin) == 0) { Util.FireAndForget(x => { string r; m_SimulationService.CreateAgent(source, destination, aCircuit, teleportFlags, ctx, out r); m_log.DebugFormat("[AGENT HANDLER]: ASYNC CreateAgent {0}", r); }); return true; } else { */ bool ret = m_SimulationService.CreateAgent(source, destination, aCircuit, teleportFlags, ctx, out reason); // m_log.DebugFormat("[AGENT HANDLER]: SYNC CreateAgent {0} {1}", ret.ToString(), reason); return ret; // } } } public class AgentPutHandler : BaseStreamHandler { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private ISimulationService m_SimulationService; protected bool m_Proxy = false; public AgentPutHandler(ISimulationService service) : base("PUT", "/agent") { m_SimulationService = service; } public AgentPutHandler(string path) : base("PUT", path) { m_SimulationService = null; } protected override byte[] ProcessRequest(string path, Stream request, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { // m_log.DebugFormat("[SIMULATION]: Stream handler called"); Hashtable keysvals = new Hashtable(); Hashtable headervals = new Hashtable(); string[] querystringkeys = httpRequest.QueryString.AllKeys; string[] rHeaders = httpRequest.Headers.AllKeys; keysvals.Add("uri", httpRequest.RawUrl); keysvals.Add("content-type", httpRequest.ContentType); keysvals.Add("http-method", httpRequest.HttpMethod); foreach (string queryname in querystringkeys) keysvals.Add(queryname, httpRequest.QueryString[queryname]); foreach (string headername in rHeaders) headervals[headername] = httpRequest.Headers[headername]; keysvals.Add("headers", headervals); keysvals.Add("querystringkeys", querystringkeys); String requestBody; Encoding encoding = Encoding.UTF8; Stream inputStream = request; Stream innerStream = null; try { if ((httpRequest.ContentType == "application/x-gzip" || httpRequest.Headers["Content-Encoding"] == "gzip") || (httpRequest.Headers["X-Content-Encoding"] == "gzip")) { innerStream = inputStream; inputStream = new GZipStream(innerStream, CompressionMode.Decompress); } using (StreamReader reader = new StreamReader(inputStream, encoding)) { requestBody = reader.ReadToEnd(); } } finally { if (innerStream != null) innerStream.Dispose(); inputStream.Dispose(); } keysvals.Add("body", requestBody); httpResponse.StatusCode = 200; httpResponse.ContentType = "text/html"; httpResponse.KeepAlive = false; Hashtable responsedata = new Hashtable(); UUID agentID; UUID regionID; string action; if (!Utils.GetParams((string)keysvals["uri"], out agentID, out regionID, out action)) { m_log.InfoFormat("[AGENT HANDLER]: Invalid parameters for agent message {0}", keysvals["uri"]); httpResponse.StatusCode = 404; return encoding.GetBytes("false"); } DoAgentPut(keysvals, responsedata); httpResponse.StatusCode = (int)responsedata["int_response_code"]; return encoding.GetBytes((string)responsedata["str_response_string"]); } protected void DoAgentPut(Hashtable request, Hashtable responsedata) { // TODO: Encode the ENtityTransferContext EntityTransferContext ctx = new EntityTransferContext(); OSDMap args = Utils.GetOSDMap((string)request["body"]); if (args == null) { responsedata["int_response_code"] = HttpStatusCode.BadRequest; responsedata["str_response_string"] = "Bad request"; return; } // retrieve the input arguments int x = 0, y = 0; UUID uuid = UUID.Zero; string regionname = string.Empty; if (args.ContainsKey("destination_x") && args["destination_x"] != null) Int32.TryParse(args["destination_x"].AsString(), out x); if (args.ContainsKey("destination_y") && args["destination_y"] != null) Int32.TryParse(args["destination_y"].AsString(), out y); if (args.ContainsKey("destination_uuid") && args["destination_uuid"] != null) UUID.TryParse(args["destination_uuid"].AsString(), out uuid); if (args.ContainsKey("destination_name") && args["destination_name"] != null) regionname = args["destination_name"].ToString(); if (args.ContainsKey("context")) ctx.Unpack((OSDMap)args["context"]); GridRegion destination = new GridRegion(); destination.RegionID = uuid; destination.RegionLocX = x; destination.RegionLocY = y; destination.RegionName = regionname; string messageType; if (args["message_type"] != null) messageType = args["message_type"].AsString(); else { m_log.Warn("[AGENT HANDLER]: Agent Put Message Type not found. "); messageType = "AgentData"; } bool result = true; if ("AgentData".Equals(messageType)) { AgentData agent = new AgentData(); try { agent.Unpack(args, m_SimulationService.GetScene(destination.RegionID), ctx); } catch (Exception ex) { m_log.InfoFormat("[AGENT HANDLER]: exception on unpacking ChildAgentUpdate message {0}", ex.Message); responsedata["int_response_code"] = HttpStatusCode.BadRequest; responsedata["str_response_string"] = "Bad request"; return; } //agent.Dump(); // This is one of the meanings of PUT agent result = UpdateAgent(destination, agent); } else if ("AgentPosition".Equals(messageType)) { AgentPosition agent = new AgentPosition(); try { agent.Unpack(args, m_SimulationService.GetScene(destination.RegionID), ctx); } catch (Exception ex) { m_log.InfoFormat("[AGENT HANDLER]: exception on unpacking ChildAgentUpdate message {0}", ex.Message); return; } //agent.Dump(); // This is one of the meanings of PUT agent result = m_SimulationService.UpdateAgent(destination, agent); } responsedata["int_response_code"] = HttpStatusCode.OK; responsedata["str_response_string"] = result.ToString(); //responsedata["str_response_string"] = OSDParser.SerializeJsonString(resp); ??? instead } // subclasses can override this protected virtual bool UpdateAgent(GridRegion destination, AgentData agent) { // The data and protocols are already defined so this is just a dummy to satisfy the interface // TODO: make this end-to-end EntityTransferContext ctx = new EntityTransferContext(); return m_SimulationService.UpdateAgent(destination, agent, ctx); } } public class AgentDestinationData { public int x; public int y; public string name; public UUID uuid; public uint flags; public bool fromLogin; } }
using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Drawing; using System.Web; using System.Web.SessionState; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; using ClientDependency.Core; using System.Linq; using ClientDependency.Core.Controls; using umbraco.IO; namespace umbraco.uicontrols { [ClientDependency(ClientDependencyType.Javascript, "CodeArea/javascript.js", "UmbracoClient")] [ClientDependency(ClientDependencyType.Javascript, "CodeArea/UmbracoEditor.js", "UmbracoClient")] [ClientDependency(ClientDependencyType.Css, "CodeArea/styles.css", "UmbracoClient")] [ClientDependency(ClientDependencyType.Javascript, "Application/jQuery/jquery-fieldselection.js", "UmbracoClient")] public class CodeArea : WebControl { public CodeArea() { //set the default to Css CodeBase = EditorType.Css; } protected TextBox CodeTextBox; public bool AutoResize { get; set; } public bool AutoSuggest { get; set; } public string EditorMimeType { get; set; } public ScrollingMenu Menu = new ScrollingMenu(); public int OffSetX { get; set; } public int OffSetY { get; set; } public string Text { get { EnsureChildControls(); return CodeTextBox.Text; } set { EnsureChildControls(); CodeTextBox.Text = value; } } public bool CodeMirrorEnabled { get { return UmbracoSettings.ScriptDisableEditor == false; } } public EditorType CodeBase { get; set; } public string ClientSaveMethod { get; set; } public enum EditorType { JavaScript, Css, Python, XML, HTML, Razor, HtmlMixed } protected override void OnInit(EventArgs e) { base.OnInit(e); EnsureChildControls(); if (CodeMirrorEnabled) { ClientDependencyLoader.Instance.RegisterDependency(0, "CodeMirror/js/lib/codemirror.js", "UmbracoClient", ClientDependencyType.Javascript); ClientDependencyLoader.Instance.RegisterDependency(2, "CodeMirror/js/mode/" + CodeBase.ToString().ToLower() + "/" + CodeBase.ToString().ToLower() + ".js", "UmbracoClient", ClientDependencyType.Javascript); if (CodeBase == EditorType.HtmlMixed) { ClientDependencyLoader.Instance.RegisterDependency(1, "CodeMirror/js/mode/xml/xml.js", "UmbracoClient", ClientDependencyType.Javascript); ClientDependencyLoader.Instance.RegisterDependency(1, "CodeMirror/js/mode/javascript/javascript.js", "UmbracoClient", ClientDependencyType.Javascript); ClientDependencyLoader.Instance.RegisterDependency(1, "CodeMirror/js/mode/css/css.js", "UmbracoClient", ClientDependencyType.Javascript); } ClientDependencyLoader.Instance.RegisterDependency(2, "CodeMirror/js/lib/codemirror.css", "UmbracoClient", ClientDependencyType.Css); ClientDependencyLoader.Instance.RegisterDependency(3, "CodeMirror/css/umbracoCustom.css", "UmbracoClient", ClientDependencyType.Css); ClientDependencyLoader.Instance.RegisterDependency(4, "CodeArea/styles.css", "UmbracoClient", ClientDependencyType.Css); } } protected override void CreateChildControls() { base.CreateChildControls(); CodeTextBox = new TextBox(); CodeTextBox.ID = "CodeTextBox"; if (CodeMirrorEnabled == false) { CodeTextBox.Attributes.Add("class", "codepress"); CodeTextBox.Attributes.Add("wrap", "off"); } CodeTextBox.TextMode = TextBoxMode.MultiLine; this.Controls.Add(Menu); this.Controls.Add(CodeTextBox); } /// <summary> /// Client ID is different if the code editor is turned on/off /// </summary> public override string ClientID { get { if (CodeMirrorEnabled == false) return CodeTextBox.ClientID; else return base.ClientID; } } protected override void Render(HtmlTextWriter writer) { EnsureChildControls(); var jsEventCode = ""; if (CodeMirrorEnabled == false) { CodeTextBox.RenderControl(writer); jsEventCode = RenderBasicEditor(); } else { writer.WriteBeginTag("div"); writer.WriteAttribute("id", this.ClientID); writer.WriteAttribute("class", "umb-editor umb-codeeditor " + this.CssClass); this.ControlStyle.AddAttributesToRender(writer); writer.Write(HtmlTextWriter.TagRightChar); Menu.RenderControl(writer); CodeTextBox.RenderControl(writer); writer.WriteEndTag("div"); jsEventCode = RenderCodeEditor(); } if (this.AutoResize) { if (CodeMirrorEnabled) { //reduce the width if using code mirror because of the line numbers OffSetX += 20; OffSetY += 50; } jsEventCode += @" //TODO: for now this is a global var, need to refactor all this so that is using proper js standards //with correct objects, and proper accessors to these objects. var UmbEditor; $(document).ready(function () { //create the editor UmbEditor = new Umbraco.Controls.CodeEditor.UmbracoEditor(" + (CodeMirrorEnabled == false).ToString().ToLower() + @", '" + this.ClientID + @"'); var m_textEditor = jQuery('#" + this.ClientID + @"'); //with codemirror adding divs for line numbers, we need to target a different element m_textEditor = m_textEditor.find('iframe').length > 0 ? m_textEditor.children('div').get(0) : m_textEditor.get(0); jQuery(window).resize(function(){ resizeTextArea(m_textEditor, " + OffSetX.ToString() + "," + OffSetY.ToString() + @"); }); jQuery(document).ready(function(){ resizeTextArea(m_textEditor, " + OffSetX.ToString() + "," + OffSetY.ToString() + @"); }); });"; } jsEventCode = string.Format(@"<script type=""text/javascript"">{0}</script>", jsEventCode); writer.WriteLine(jsEventCode); } protected string RenderBasicEditor() { string jsEventCode = @" var m_textEditor = document.getElementById('" + this.ClientID + @"'); tab.watch('" + this.ClientID + @"'); "; return jsEventCode; } protected string RenderCodeEditor() { var extraKeys = ""; var editorMimetype = ""; if (string.IsNullOrEmpty(EditorMimeType) == false) editorMimetype = @", mode: """ + EditorMimeType + "\""; var jsEventCode = @" var textarea = document.getElementById('" + CodeTextBox.ClientID + @"'); var codeEditor = CodeMirror.fromTextArea(textarea, { width: ""100%"", height: ""100%"", tabMode: ""shift"", matchBrackets: true, indentUnit: 4, indentWithTabs: true, enterMode: ""keep"", onCursorActivity: updateLineInfo, lineWrapping: false" + editorMimetype + @", lineNumbers: true" + extraKeys + @" }); //resizeTextArea(m_textEditor, " + OffSetX.ToString() + "," + OffSetY.ToString() + @"); updateLineInfo(codeEditor); "; return jsEventCode; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // // This is where we group together all the internal calls. // using System.Runtime.InteropServices; using System.Runtime.CompilerServices; namespace System.Runtime { internal static class InternalCalls { // // internalcalls for System.GC. // // Force a garbage collection. [RuntimeImport(Redhawk.BaseName, "RhCollect")] [MethodImpl(MethodImplOptions.InternalCall)] [ManuallyManaged(GcPollPolicy.Always)] internal static extern void RhCollect(int generation, InternalGCCollectionMode mode); // // internalcalls for System.Runtime.__Finalizer. // // Fetch next object which needs finalization or return null if we've reached the end of the list. [RuntimeImport(Redhawk.BaseName, "RhpGetNextFinalizableObject")] [MethodImpl(MethodImplOptions.InternalCall)] [ManuallyManaged(GcPollPolicy.Never)] internal static extern Object RhpGetNextFinalizableObject(); // // internalcalls for System.Runtime.InteropServices.GCHandle. // // Allocate handle. [RuntimeImport(Redhawk.BaseName, "RhpHandleAlloc")] [MethodImpl(MethodImplOptions.InternalCall)] [ManuallyManaged(GcPollPolicy.Never)] internal static extern IntPtr RhpHandleAlloc(Object value, GCHandleType type); // Allocate dependent handle. [RuntimeImport(Redhawk.BaseName, "RhpHandleAllocDependent")] [MethodImpl(MethodImplOptions.InternalCall)] [ManuallyManaged(GcPollPolicy.Never)] internal static extern IntPtr RhpHandleAllocDependent(Object primary, Object secondary); // Allocate variable handle. [RuntimeImport(Redhawk.BaseName, "RhpHandleAllocVariable")] [MethodImpl(MethodImplOptions.InternalCall)] [ManuallyManaged(GcPollPolicy.Never)] internal static extern IntPtr RhpHandleAllocVariable(Object value, uint type); // // internal calls for allocation // [RuntimeImport(Redhawk.BaseName, "RhpNewFast")] [MethodImpl(MethodImplOptions.InternalCall)] [ManuallyManaged(GcPollPolicy.Sometimes)] internal unsafe extern static object RhpNewFast(EEType* pEEType); // BEWARE: not for finalizable objects! [RuntimeImport(Redhawk.BaseName, "RhpNewFinalizable")] [MethodImpl(MethodImplOptions.InternalCall)] [ManuallyManaged(GcPollPolicy.Sometimes)] internal unsafe extern static object RhpNewFinalizable(EEType* pEEType); [RuntimeImport(Redhawk.BaseName, "RhpNewArray")] [MethodImpl(MethodImplOptions.InternalCall)] [ManuallyManaged(GcPollPolicy.Sometimes)] internal unsafe extern static object RhpNewArray(EEType* pEEType, int length); #if FEATURE_64BIT_ALIGNMENT [RuntimeImport(Redhawk.BaseName, "RhpNewFastAlign8")] [MethodImpl(MethodImplOptions.InternalCall)] [ManuallyManaged(GcPollPolicy.Sometimes)] internal unsafe extern static object RhpNewFastAlign8(EEType * pEEType); // BEWARE: not for finalizable objects! [RuntimeImport(Redhawk.BaseName, "RhpNewFinalizableAlign8")] [MethodImpl(MethodImplOptions.InternalCall)] [ManuallyManaged(GcPollPolicy.Sometimes)] internal unsafe extern static object RhpNewFinalizableAlign8(EEType* pEEType); [RuntimeImport(Redhawk.BaseName, "RhpNewArrayAlign8")] [MethodImpl(MethodImplOptions.InternalCall)] [ManuallyManaged(GcPollPolicy.Sometimes)] internal unsafe extern static object RhpNewArrayAlign8(EEType* pEEType, int length); [RuntimeImport(Redhawk.BaseName, "RhpNewFastMisalign")] [MethodImpl(MethodImplOptions.InternalCall)] [ManuallyManaged(GcPollPolicy.Sometimes)] internal unsafe extern static object RhpNewFastMisalign(EEType * pEEType); #endif // FEATURE_64BIT_ALIGNMENT [RuntimeImport(Redhawk.BaseName, "RhpBox")] [MethodImpl(MethodImplOptions.InternalCall)] [ManuallyManaged(GcPollPolicy.Sometimes)] internal unsafe extern static void RhpBox(object obj, void* pData); // NOTE: returns null on allocation failure [RuntimeImport(Redhawk.BaseName, "RhUnbox")] [MethodImpl(MethodImplOptions.InternalCall)] [ManuallyManaged(GcPollPolicy.Sometimes)] internal unsafe extern static void RhUnbox(object obj, void* pData, EEType* pUnboxToEEType); [RuntimeImport(Redhawk.BaseName, "RhpCopyObjectContents")] [MethodImpl(MethodImplOptions.InternalCall)] [ManuallyManaged(GcPollPolicy.Never)] internal unsafe extern static void RhpCopyObjectContents(object objDest, object objSrc); #if FEATURE_GC_STRESS // // internal calls for GC stress // [RuntimeImport(Redhawk.BaseName, "RhpInitializeGcStress")] [MethodImpl(MethodImplOptions.InternalCall)] [ManuallyManaged(GcPollPolicy.Never)] internal unsafe extern static void RhpInitializeGcStress(); #endif // FEATURE_GC_STRESS [RuntimeImport(Redhawk.BaseName, "RhpEHEnumInitFromStackFrameIterator")] [MethodImpl(MethodImplOptions.InternalCall)] [ManuallyManaged(GcPollPolicy.Never)] internal unsafe extern static bool RhpEHEnumInitFromStackFrameIterator(ref StackFrameIterator pFrameIter, byte** pMethodStartAddress, void* pEHEnum); [RuntimeImport(Redhawk.BaseName, "RhpEHEnumNext")] [MethodImpl(MethodImplOptions.InternalCall)] [ManuallyManaged(GcPollPolicy.Never)] internal unsafe extern static bool RhpEHEnumNext(void* pEHEnum, void* pEHClause); [RuntimeImport(Redhawk.BaseName, "RhpGetArrayBaseType")] [MethodImpl(MethodImplOptions.InternalCall)] [ManuallyManaged(GcPollPolicy.Never)] internal unsafe extern static EEType* RhpGetArrayBaseType(EEType* pEEType); [RuntimeImport(Redhawk.BaseName, "RhpHasDispatchMap")] [MethodImpl(MethodImplOptions.InternalCall)] [ManuallyManaged(GcPollPolicy.Never)] internal unsafe extern static bool RhpHasDispatchMap(EEType* pEETypen); [RuntimeImport(Redhawk.BaseName, "RhpGetDispatchMap")] [MethodImpl(MethodImplOptions.InternalCall)] [ManuallyManaged(GcPollPolicy.Never)] internal unsafe extern static DispatchResolve.DispatchMap* RhpGetDispatchMap(EEType* pEEType); [RuntimeImport(Redhawk.BaseName, "RhpGetSealedVirtualSlot")] [MethodImpl(MethodImplOptions.InternalCall)] [ManuallyManaged(GcPollPolicy.Never)] internal unsafe extern static IntPtr RhpGetSealedVirtualSlot(EEType* pEEType, ushort slot); [RuntimeImport(Redhawk.BaseName, "RhpGetDispatchCellInfo")] [MethodImpl(MethodImplOptions.InternalCall)] [ManuallyManaged(GcPollPolicy.Never)] internal unsafe extern static void RhpGetDispatchCellInfo(IntPtr pCell, EEType** pInterfaceType, ushort* slot); [RuntimeImport(Redhawk.BaseName, "RhpSearchDispatchCellCache")] [MethodImpl(MethodImplOptions.InternalCall)] [ManuallyManaged(GcPollPolicy.Never)] internal unsafe extern static IntPtr RhpSearchDispatchCellCache(IntPtr pCell, EEType* pInstanceType); [RuntimeImport(Redhawk.BaseName, "RhpUpdateDispatchCellCache")] [MethodImpl(MethodImplOptions.InternalCall)] [ManuallyManaged(GcPollPolicy.Never)] internal unsafe extern static IntPtr RhpUpdateDispatchCellCache(IntPtr pCell, IntPtr pTargetCode, EEType* pInstanceType); [RuntimeImport(Redhawk.BaseName, "RhpGetClasslibFunction")] [MethodImpl(MethodImplOptions.InternalCall)] [ManuallyManaged(GcPollPolicy.Never)] internal unsafe extern static void* RhpGetClasslibFunction(IntPtr address, EH.ClassLibFunctionId id); // Given the EEType* for a generic type, retrieve instantiation information (generic type definition // EEType, arity, type arguments and variance info for each type parameter). If the EEType is not // generic, null will be returned. [RuntimeImport(Redhawk.BaseName, "RhGetGenericInstantiation")] [MethodImpl(MethodImplOptions.InternalCall)] [ManuallyManaged(GcPollPolicy.Never)] internal extern static unsafe EEType* RhGetGenericInstantiation(EEType* pEEType, int* pArity, EETypeRef** ppInstantiation, GenericVariance** ppVarianceInfo); // // StackFrameIterator // [RuntimeImport(Redhawk.BaseName, "RhpSfiInit")] [MethodImpl(MethodImplOptions.InternalCall)] [ManuallyManaged(GcPollPolicy.Never)] internal static extern unsafe bool RhpSfiInit(ref StackFrameIterator pThis, void* pStackwalkCtx); [RuntimeImport(Redhawk.BaseName, "RhpSfiNext")] [MethodImpl(MethodImplOptions.InternalCall)] [ManuallyManaged(GcPollPolicy.Never)] internal static extern bool RhpSfiNext(ref StackFrameIterator pThis, out uint uExCollideClauseIdx, out bool fUnwoundReversePInvoke); // // DebugEventSource // [RuntimeImport(Redhawk.BaseName, "RhpGetRequestedExceptionEvents")] [MethodImpl(MethodImplOptions.InternalCall)] [ManuallyManaged(GcPollPolicy.Never)] internal static extern ExceptionEventKind RhpGetRequestedExceptionEvents(); [DllImport(Redhawk.BaseName)] internal static extern unsafe void RhpSendExceptionEventToDebugger(ExceptionEventKind eventKind, byte* ip, UIntPtr sp); // // Miscellaneous helpers. // // Get the rarely used (optional) flags of an EEType. If they're not present 0 will be returned. [RuntimeImport(Redhawk.BaseName, "RhpGetEETypeRareFlags")] [MethodImpl(MethodImplOptions.InternalCall)] [ManuallyManaged(GcPollPolicy.Never)] internal extern static unsafe UInt32 RhpGetEETypeRareFlags(EEType* pEEType); // Retrieve the offset of the value embedded in a Nullable<T>. [RuntimeImport(Redhawk.BaseName, "RhpGetNullableEETypeValueOffset")] [MethodImpl(MethodImplOptions.InternalCall)] [ManuallyManaged(GcPollPolicy.Never)] internal extern static unsafe byte RhpGetNullableEETypeValueOffset(EEType* pEEType); // Retrieve the target type T in a Nullable<T>. [RuntimeImport(Redhawk.BaseName, "RhpGetNullableEEType")] [MethodImpl(MethodImplOptions.InternalCall)] [ManuallyManaged(GcPollPolicy.Never)] internal extern static unsafe EEType* RhpGetNullableEEType(EEType* pEEType); // For an ICastable type return a pointer to code that implements ICastable.IsInstanceOfInterface. [RuntimeImport(Redhawk.BaseName, "RhpGetICastableIsInstanceOfInterfaceMethod")] [MethodImpl(MethodImplOptions.InternalCall)] [ManuallyManaged(GcPollPolicy.Never)] internal extern static unsafe IntPtr RhpGetICastableIsInstanceOfInterfaceMethod(EEType* pEEType); // For an ICastable type return a pointer to code that implements ICastable.GetImplType. [RuntimeImport(Redhawk.BaseName, "RhpGetICastableGetImplTypeMethod")] [MethodImpl(MethodImplOptions.InternalCall)] [ManuallyManaged(GcPollPolicy.Never)] internal extern static unsafe IntPtr RhpGetICastableGetImplTypeMethod(EEType* pEEType); [RuntimeImport(Redhawk.BaseName, "RhpGetNextFinalizerInitCallback")] [MethodImpl(MethodImplOptions.InternalCall)] [ManuallyManaged(GcPollPolicy.Never)] internal extern static unsafe IntPtr RhpGetNextFinalizerInitCallback(); [RuntimeImport(Redhawk.BaseName, "RhpCallCatchFunclet")] [MethodImpl(MethodImplOptions.InternalCall)] [ManuallyManaged(GcPollPolicy.Never)] internal extern static unsafe IntPtr RhpCallCatchFunclet( object exceptionObj, byte* pHandlerIP, void* pvRegDisplay, ref EH.ExInfo exInfo); [RuntimeImport(Redhawk.BaseName, "RhpCallFinallyFunclet")] [MethodImpl(MethodImplOptions.InternalCall)] [ManuallyManaged(GcPollPolicy.Never)] internal extern static unsafe void RhpCallFinallyFunclet(byte* pHandlerIP, void* pvRegDisplay); [RuntimeImport(Redhawk.BaseName, "RhpCallFilterFunclet")] [MethodImpl(MethodImplOptions.InternalCall)] [ManuallyManaged(GcPollPolicy.Never)] internal extern static unsafe bool RhpCallFilterFunclet( object exceptionObj, byte* pFilterIP, void* pvRegDisplay); [RuntimeImport(Redhawk.BaseName, "RhpFallbackFailFast")] [MethodImpl(MethodImplOptions.InternalCall)] [ManuallyManaged(GcPollPolicy.Never)] internal extern static unsafe void RhpFallbackFailFast(); [RuntimeImport(Redhawk.BaseName, "RhpSetThreadDoNotTriggerGC")] [MethodImpl(MethodImplOptions.InternalCall)] [ManuallyManaged(GcPollPolicy.Never)] internal extern static void RhpSetThreadDoNotTriggerGC(); [System.Diagnostics.Conditional("DEBUG")] [RuntimeImport(Redhawk.BaseName, "RhpValidateExInfoStack")] [MethodImpl(MethodImplOptions.InternalCall)] [ManuallyManaged(GcPollPolicy.Never)] internal extern static void RhpValidateExInfoStack(); [RuntimeImport(Redhawk.BaseName, "RhpCopyContextFromExInfo")] [MethodImpl(MethodImplOptions.InternalCall)] [ManuallyManaged(GcPollPolicy.Never)] internal extern static unsafe void RhpCopyContextFromExInfo(void* pOSContext, int cbOSContext, EH.PAL_LIMITED_CONTEXT* pPalContext); //------------------------------------------------------------------------------------------------------------ // PInvoke-based internal calls // // These either do not need to be called in cooperative mode or, in some cases, MUST be called in preemptive // mode. Note that they must use the Cdecl calling convention due to a limitation in our .obj file linking // support. //------------------------------------------------------------------------------------------------------------ // Block the current thread until at least one object needs to be finalized (returns true) or // memory is low (returns false and the finalizer thread should initiate a garbage collection). [DllImport(Redhawk.BaseName, CallingConvention = CallingConvention.Cdecl)] internal static extern UInt32 RhpWaitForFinalizerRequest(); // Indicate that the current round of finalizations is complete. [DllImport(Redhawk.BaseName, CallingConvention = CallingConvention.Cdecl)] internal static extern void RhpSignalFinalizationComplete(); } // Keep this synchronized with GenericVarianceType in rhbinder.h. public enum GenericVariance : byte { NonVariant = 0, Covariant = 1, Contravariant = 2, ArrayCovariant = 0x20, } }
using System; using System.Collections.Generic; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; namespace TeachMePianoPlz { public class GraphicsManager { public int Width { get; private set; } public int Height { get; private set; } public int Zoom { get; private set; } public void Resize(int width, int height, int zoom) { Width = width; Height = height; Zoom = zoom; _graphics.PreferredBackBufferWidth = Width * Zoom; _graphics.PreferredBackBufferHeight = Height * Zoom; _graphics.ApplyChanges(); // (0, 0) in upper-left _projection_matrix = Matrix.CreateOrthographicOffCenter(0, Width, -Height, 0, 0, 1); _line_drawing_effect = new BasicEffect(_graphics_device) { Alpha = 1f, VertexColorEnabled = true, TextureEnabled = false, World = Matrix.Identity, View = _view_matrix, Projection = _projection_matrix, }; _render_target = new RenderTarget2D(_graphics_device, Width, Height); // gotta' update all the sprite sheet effects' projections! foreach(SpriteSheet s in _sprite_sheets.Values) s.Effect.Projection = _projection_matrix; } public GraphicsManager(GraphicsDeviceManager graphicsDeviceManager, ContentManager contentManager, GraphicsDevice graphicsDevice, int width, int height, int zoom) { _graphics = graphicsDeviceManager; _content_manager = contentManager; _graphics_device = graphicsDevice; _view_matrix = new Matrix( 1f, 0, 0, 0, 0, -1f, 0, 0, 0, 0, -1f, 0, 0, 0, 0, 1f ); _sprite_batch = new SpriteBatch(_graphics_device); Resize(width, height, zoom); } public volatile static int LoadProgress = 0; public int LoadTotal() { return Enum.GetValues(typeof(GraphicsID)).Length; } public void Load(Dictionary<GraphicsID, GraphicsMeta> loadList) { foreach (GraphicsID spriteSheet in loadList.Keys) { LoadSprite(spriteSheet, loadList[spriteSheet]); } } private void LoadSprite(GraphicsID spriteSheetID, GraphicsMeta meta) { _sprite_sheets.Add( spriteSheetID, new SpriteSheet( _content_manager.Load<Texture2D>("Graphics/" + spriteSheetID.ToString().Replace('_', '/')), meta.SpriteWidth, meta.SpriteHeight, new BasicEffect(_graphics_device) { World = Matrix.Identity, View = _view_matrix, Projection = _projection_matrix, } ) ); LoadProgress++; } public void DrawSprite(Point center, Point size, GraphicsID spriteSheet, int spriteIndex) { DrawSprite( (center.X - size.X / 2), (center.Y - size.Y / 2), size.X, size.Y, spriteSheet, spriteIndex ); } public void DrawSprite(Point center, Point size, Point camera, GraphicsID spriteSheet, int spriteIndex) { DrawSprite( (center.X - size.X / 2) - (int)camera.X, (center.Y - size.Y / 2) - (int)camera.Y, size.X, size.Y, spriteSheet, spriteIndex ); } public void DrawSprite(double centerX, double centerY, Point size, Point camera, GraphicsID spriteSheet, int spriteIndex) { DrawSprite( (int)(centerX - size.X / 2) - camera.X, (int)(centerY - size.Y / 2) - camera.Y, size.X, size.Y, spriteSheet, spriteIndex ); } public void DrawSprite(int x, int y, GraphicsID spriteSheet, int spriteIndex) { DrawSprite( x, y, _sprite_sheets[spriteSheet].SpriteWidth, _sprite_sheets[spriteSheet].SpriteHeight, spriteSheet, spriteIndex ); } public void DrawSprite(int x, int y, int width, int height, GraphicsID spriteSheet, int spriteIndex) { int spriteX = spriteIndex % _sprite_sheets[spriteSheet].Columns; int spriteY = spriteIndex / _sprite_sheets[spriteSheet].Columns; float spriteXWidth = 1 / (float)_sprite_sheets[spriteSheet].Columns; float spriteYHeight = 1 / (float)_sprite_sheets[spriteSheet].Rows; float spriteXOffset = spriteX * spriteXWidth; float spriteYOffset = spriteY * spriteYHeight; foreach (EffectPass pass in _sprite_sheets[spriteSheet].Effect.CurrentTechnique.Passes) { pass.Apply(); _graphics_device.DrawUserPrimitives(PrimitiveType.TriangleStrip, new VertexPositionTexture[] { new VertexPositionTexture(new Vector3(x, y, 0), new Vector2(spriteXOffset, spriteYOffset)), new VertexPositionTexture(new Vector3(x + width, y, 0), new Vector2(spriteXOffset + spriteXWidth, spriteYOffset)), new VertexPositionTexture(new Vector3(x, y + height, 0), new Vector2(spriteXOffset, spriteYOffset + spriteYHeight)), new VertexPositionTexture(new Vector3(x + width, y + height, 0), new Vector2(spriteXOffset + spriteXWidth, spriteYOffset + spriteYHeight)), }, 0, 2, VertexPositionTexture.VertexDeclaration); } } public void DrawTiledSprite(int x, int y, int width, int height, GraphicsID spriteSheet, float offsetX, float offsetY) { int spriteWidth = _sprite_sheets[spriteSheet].SpriteWidth; int spriteHeight = _sprite_sheets[spriteSheet].SpriteHeight; foreach (EffectPass pass in _sprite_sheets[spriteSheet].Effect.CurrentTechnique.Passes) { pass.Apply(); _graphics_device.DrawUserPrimitives(PrimitiveType.TriangleStrip, new VertexPositionTexture[] { new VertexPositionTexture(new Vector3(x, y, 0), new Vector2(offsetX, offsetY)), new VertexPositionTexture(new Vector3(x + width, y, 0), new Vector2(offsetX + (float)width / spriteWidth, offsetY)), new VertexPositionTexture(new Vector3(x, y + height, 0), new Vector2(offsetX, offsetY + (float)height / spriteHeight)), new VertexPositionTexture(new Vector3(x + width, y + height, 0), new Vector2(offsetX + (float)width / spriteWidth, offsetY + (float)height / spriteHeight)), }, 0, 2, VertexPositionTexture.VertexDeclaration); } } public void DrawLine(int x1, int y1, int x2, int y2, Color color) { foreach (EffectPass pass in _line_drawing_effect.CurrentTechnique.Passes) { pass.Apply(); _graphics_device.DrawUserPrimitives(PrimitiveType.LineList, new VertexPositionColor[] { new VertexPositionColor(new Vector3(x1, y1, 0), color), new VertexPositionColor(new Vector3(x2, y2, 0), color), }, 0, 1); } } public Point SpriteSize(GraphicsID spriteSheet) { return new Point(_sprite_sheets[spriteSheet].SpriteWidth, _sprite_sheets[spriteSheet].SpriteHeight); } public int SpriteCount(GraphicsID spriteSheet) { return _sprite_sheets[spriteSheet].Columns * _sprite_sheets[spriteSheet].Rows; } public void DrawScene(GraphicsID backgroundTile, Point backgroundOffset, Action drawScene) { // render scene _graphics_device.SetRenderTarget(_render_target); _graphics_device.RasterizerState = new RasterizerState() { CullMode = CullMode.None }; DrawTiledSprite(0, 0, Width, Height, backgroundTile, backgroundOffset.X, backgroundOffset.Y); drawScene(); DrawBufferToScreen(); } public void DrawScene(Color backgroundColor, Action drawScene) { // render scene _graphics_device.SetRenderTarget(_render_target); _graphics_device.Clear(backgroundColor); _graphics_device.RasterizerState = new RasterizerState() { CullMode = CullMode.None }; drawScene(); DrawBufferToScreen(); } private void DrawBufferToScreen() { _graphics_device.SetRenderTarget(null); _sprite_batch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, SamplerState.PointWrap); _sprite_batch.Draw(_render_target, new Rectangle(0, 0, Width * Zoom, Height * Zoom), Color.White); _sprite_batch.End(); } private Matrix _projection_matrix; private Matrix _view_matrix; private GraphicsDeviceManager _graphics; private SpriteBatch _sprite_batch; private ContentManager _content_manager; private GraphicsDevice _graphics_device; private RenderTarget2D _render_target; private BasicEffect _line_drawing_effect; private Dictionary<GraphicsID, SpriteSheet> _sprite_sheets = new Dictionary<GraphicsID, SpriteSheet>(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using Signum.Engine.Linq; using Signum.Engine.Maps; using Signum.Entities; using Signum.Utilities; using Signum.Utilities.ExpressionTrees; using Signum.Utilities.Reflection; using Signum.Entities.Internal; namespace Signum.Engine.Cache { internal class CachedTableConstructor { public CachedTableBase cachedTable; public ITable table; public ParameterExpression origin; public AliasGenerator? aliasGenerator; public Alias? currentAlias; public Type tupleType; public string? remainingJoins; public CachedTableConstructor(CachedTableBase cachedTable, AliasGenerator? aliasGenerator) { this.cachedTable = cachedTable; this.table = cachedTable.Table; if (aliasGenerator != null) { this.aliasGenerator = aliasGenerator; this.currentAlias = aliasGenerator.NextTableAlias(table.Name.Name); } this.tupleType = TupleReflection.TupleChainType(table.Columns.Values.Select(GetColumnType)); this.origin = Expression.Parameter(tupleType, "origin"); } public Expression GetTupleProperty(IColumn column) { return TupleReflection.TupleChainProperty(origin, table.Columns.Values.IndexOf(column)); } internal string CreatePartialInnerJoin(IColumn column) { return "INNER JOIN {0} {1} ON {1}.{2}=".FormatWith(table.Name.ToString(), currentAlias, column.Name.SqlEscape(Schema.Current.Settings.IsPostgres)); } internal Type GetColumnType(IColumn column) { return column.Type; } internal Func<FieldReader, object> GetRowReader() { ParameterExpression reader = Expression.Parameter(typeof(FieldReader)); var tupleConstructor = TupleReflection.TupleChainConstructor( table.Columns.Values.Select((c, i) => FieldReader.GetExpression(reader, i, GetColumnType(c))) ); return Expression.Lambda<Func<FieldReader, object>>(tupleConstructor, reader).Compile(); } internal Func<object, PrimaryKey> GetPrimaryKeyGetter(IColumn column) { var access = TupleReflection.TupleChainProperty(Expression.Convert(originObject, tupleType), table.Columns.Values.IndexOf(column)); var primaryKey = NewPrimaryKey(access); return Expression.Lambda<Func<object, PrimaryKey>>(primaryKey, originObject).Compile(); } internal Func<object, PrimaryKey?> GetPrimaryKeyNullableGetter(IColumn column) { var access = TupleReflection.TupleChainProperty(Expression.Convert(originObject, tupleType), table.Columns.Values.IndexOf(column)); var primaryKey = WrapPrimaryKey(access); return Expression.Lambda<Func<object, PrimaryKey?>>(primaryKey, originObject).Compile(); } static ConstructorInfo ciPrimaryKey = ReflectionTools.GetConstuctorInfo(() => new PrimaryKey(1)); internal static Expression NewPrimaryKey(Expression expression) { return Expression.New(ciPrimaryKey, Expression.Convert(expression, typeof(IComparable))); } static GenericInvoker<Func<ICacheLogicController, AliasGenerator?, string, string?, CachedTableBase>> ciCachedTable = new GenericInvoker<Func<ICacheLogicController, AliasGenerator?, string, string?, CachedTableBase>>((controller, aliasGenerator, lastPartialJoin, remainingJoins) => new CachedTable<Entity>(controller, aliasGenerator, lastPartialJoin, remainingJoins)); static GenericInvoker<Func<ICacheLogicController, AliasGenerator, string, string?, CachedTableBase>> ciCachedSemiTable = new GenericInvoker<Func<ICacheLogicController, AliasGenerator, string, string?, CachedTableBase>>((controller, aliasGenerator, lastPartialJoin, remainingJoins) => new CachedLiteTable<Entity>(controller, aliasGenerator, lastPartialJoin, remainingJoins)); static GenericInvoker<Func<ICacheLogicController, TableMList, AliasGenerator?, string, string?, CachedTableBase>> ciCachedTableMList = new GenericInvoker<Func<ICacheLogicController, TableMList, AliasGenerator?, string, string?, CachedTableBase>>((controller, relationalTable, aliasGenerator, lastPartialJoin, remainingJoins) => new CachedTableMList<Entity>(controller, relationalTable, aliasGenerator, lastPartialJoin, remainingJoins)); static Expression NullId = Expression.Constant(null, typeof(PrimaryKey?)); public Expression MaterializeField(Field field) { if (field is FieldValue) { var value = GetTupleProperty((IColumn)field); return value.Type == field.FieldType ? value : Expression.Convert(value, field.FieldType); } if (field is FieldEnum) return Expression.Convert(GetTupleProperty((IColumn)field), field.FieldType); if (field is IFieldReference) { var nullRef = Expression.Constant(null, field.FieldType); bool isLite = ((IFieldReference)field).IsLite; if (field is FieldReference) { IColumn column = (IColumn)field; return GetEntity(isLite, column, field.FieldType.CleanType()); } if (field is FieldImplementedBy ib) { var call = ib.ImplementationColumns.Aggregate((Expression)nullRef, (acum, kvp) => { IColumn column = (IColumn)kvp.Value; Expression entity = GetEntity(isLite, column, kvp.Key); return Expression.Condition(Expression.NotEqual(WrapPrimaryKey(GetTupleProperty(column)), NullId), Expression.Convert(entity, field.FieldType), acum); }); return call; } if (field is FieldImplementedByAll iba) { Expression id = GetTupleProperty(iba.Column); Expression typeId = GetTupleProperty(iba.ColumnType); if (isLite) { var liteCreate = Expression.Call(miGetIBALite.MakeGenericMethod(field.FieldType.CleanType()), Expression.Constant(Schema.Current), NewPrimaryKey(typeId.UnNullify()), id.UnNullify()); var liteRequest = Expression.Call(retriever, miRequestLite.MakeGenericMethod(Lite.Extract(field.FieldType)!), liteCreate); return Expression.Condition(Expression.NotEqual(WrapPrimaryKey(id), NullId), liteRequest, nullRef); } else { return Expression.Call(retriever, miRequestIBA.MakeGenericMethod(field.FieldType), typeId, id); } } } if (field is FieldEmbedded fe) { var bindings = new List<Expression>(); var embParam = Expression.Parameter(fe.FieldType); bindings.Add(Expression.Assign(embParam, Expression.New(fe.FieldType))); bindings.Add(Expression.Call(retriever, miModifiablePostRetrieving.MakeGenericMethod(embParam.Type), embParam)); foreach (var f in fe.EmbeddedFields.Values) { Expression value = MaterializeField(f.Field); var assigment = Expression.Assign(Expression.Field(embParam, f.FieldInfo), value); bindings.Add(assigment); } bindings.Add(embParam); Expression block = Expression.Block(new[] { embParam }, bindings); if (fe.HasValue == null) return block; return Expression.Condition( Expression.Equal(GetTupleProperty(fe.HasValue), Expression.Constant(true)), block, Expression.Constant(null, field.FieldType)); } if (field is FieldMList mListField) { var idColumn = table.Columns.Values.OfType<FieldPrimaryKey>().First(); string lastPartialJoin = CreatePartialInnerJoin(idColumn); Type elementType = field.FieldType.ElementType()!; CachedTableBase ctb = ciCachedTableMList.GetInvoker(elementType)(cachedTable.controller, mListField.TableMList, aliasGenerator, lastPartialJoin, remainingJoins); if (cachedTable.subTables == null) cachedTable.subTables = new List<CachedTableBase>(); cachedTable.subTables.Add(ctb); return Expression.Call(Expression.Constant(ctb), ctb.GetType().GetMethod(nameof(CachedTableMList<int>.GetMList)), NewPrimaryKey(GetTupleProperty(idColumn)), retriever); } throw new InvalidOperationException("Unexpected {0}".FormatWith(field.GetType().Name)); } private Expression GetEntity(bool isLite, IColumn column, Type type) { Expression id = GetTupleProperty(column); if (isLite) { Expression lite; switch (CacheLogic.GetCacheType(type)) { case CacheType.Cached: { lite = Expression.Call(retriever, miRequestLite.MakeGenericMethod(type), Lite.NewExpression(type, NewPrimaryKey(id.UnNullify()), Expression.Constant(null, typeof(string)))); lite = Expression.Call(retriever, miModifiablePostRetrieving.MakeGenericMethod(typeof(LiteImp)), lite.TryConvert(typeof(LiteImp))).TryConvert(lite.Type); break; } case CacheType.Semi: { string lastPartialJoin = CreatePartialInnerJoin(column); CachedTableBase ctb = ciCachedSemiTable.GetInvoker(type)(cachedTable.controller, aliasGenerator!, lastPartialJoin, remainingJoins); if (cachedTable.subTables == null) cachedTable.subTables = new List<CachedTableBase>(); cachedTable.subTables.Add(ctb); ctb.ParentColumn = column; lite = Expression.Call(Expression.Constant(ctb), ctb.GetType().GetMethod("GetLite"), NewPrimaryKey(id.UnNullify()), retriever); break; } default: throw new InvalidOperationException("{0} should be cached at this stage".FormatWith(type)); } if (!id.Type.IsNullable()) return lite; return Expression.Condition(Expression.Equal(id, NullId), Expression.Constant(null, Lite.Generate(type)), lite); } else { switch (CacheLogic.GetCacheType(type)) { case CacheType.Cached: return Expression.Call(retriever, miRequest.MakeGenericMethod(type), WrapPrimaryKey(id.Nullify())); case CacheType.Semi: { string lastPartialJoin = CreatePartialInnerJoin(column); CachedTableBase ctb = ciCachedTable.GetInvoker(type)(cachedTable.controller, aliasGenerator, lastPartialJoin, remainingJoins); if (cachedTable.subTables == null) cachedTable.subTables = new List<CachedTableBase>(); cachedTable.subTables.Add(ctb); ctb.ParentColumn = column; var entity = Expression.Parameter(type); LambdaExpression lambda = Expression.Lambda(typeof(Action<>).MakeGenericType(type), Expression.Call(Expression.Constant(ctb), ctb.GetType().GetMethod("Complete"), entity, retriever), entity); return Expression.Call(retriever, miComplete.MakeGenericMethod(type), WrapPrimaryKey(id.Nullify()), lambda); } default: throw new InvalidOperationException("{0} should be cached at this stage".FormatWith(type)); } } } static readonly MethodInfo miWrap = ReflectionTools.GetMethodInfo(() => PrimaryKey.Wrap(1)); internal static Expression WrapPrimaryKey(Expression expression) { return Expression.Call(miWrap, Expression.Convert(expression, typeof(IComparable))); } static MethodInfo miRequestLite = ReflectionTools.GetMethodInfo((IRetriever r) => r.RequestLite<Entity>(null)).GetGenericMethodDefinition(); static MethodInfo miRequestIBA = ReflectionTools.GetMethodInfo((IRetriever r) => r.RequestIBA<Entity>(null, null)).GetGenericMethodDefinition(); static MethodInfo miRequest = ReflectionTools.GetMethodInfo((IRetriever r) => r.Request<Entity>(null)).GetGenericMethodDefinition(); static MethodInfo miComplete = ReflectionTools.GetMethodInfo((IRetriever r) => r.Complete<Entity>(0, null!)).GetGenericMethodDefinition(); static MethodInfo miModifiablePostRetrieving = ReflectionTools.GetMethodInfo((IRetriever r) => r.ModifiablePostRetrieving<EmbeddedEntity>(null)).GetGenericMethodDefinition(); internal static ParameterExpression originObject = Expression.Parameter(typeof(object), "originObject"); internal static ParameterExpression retriever = Expression.Parameter(typeof(IRetriever), "retriever"); static MethodInfo miGetIBALite = ReflectionTools.GetMethodInfo((Schema s) => GetIBALite<Entity>(null!, 1, "")).GetGenericMethodDefinition(); public static Lite<T> GetIBALite<T>(Schema schema, PrimaryKey typeId, string id) where T : Entity { Type type = schema.GetType(typeId); return (Lite<T>)Lite.Create(type, PrimaryKey.Parse(id, type)); } public static MemberExpression peModified = Expression.Property(retriever, ReflectionTools.GetPropertyInfo((IRetriever me) => me.ModifiedState)); public static ConstructorInfo ciKVPIntString = ReflectionTools.GetConstuctorInfo(() => new KeyValuePair<PrimaryKey, string>(1, "")); public static Action<IRetriever, Modifiable> resetModifiedAction; static CachedTableConstructor() { ParameterExpression modif = Expression.Parameter(typeof(Modifiable)); resetModifiedAction = Expression.Lambda<Action<IRetriever, Modifiable>>(Expression.Assign( Expression.Property(modif, ReflectionTools.GetPropertyInfo((Modifiable me) => me.Modified)), CachedTableConstructor.peModified), CachedTableConstructor.retriever, modif).Compile(); } static readonly MethodInfo miMixin = ReflectionTools.GetMethodInfo((Entity i) => i.Mixin<CorruptMixin>()).GetGenericMethodDefinition(); Expression GetMixin(ParameterExpression me, Type mixinType) { return Expression.Call(me, miMixin.MakeGenericMethod(mixinType)); } internal BlockExpression MaterializeEntity(ParameterExpression me, Table table) { List<Expression> instructions = new List<Expression>(); instructions.Add(Expression.Assign(origin, Expression.Convert(CachedTableConstructor.originObject, tupleType))); foreach (var f in table.Fields.Values.Where(f => !(f.Field is FieldPrimaryKey))) { Expression value = MaterializeField(f.Field); var assigment = Expression.Assign(Expression.Field(me, f.FieldInfo), value); instructions.Add(assigment); } if (table.Mixins != null) { foreach (var mixin in table.Mixins.Values) { ParameterExpression mixParam = Expression.Parameter(mixin.FieldType); var mixBlock = MaterializeMixin(me, mixin, mixParam); instructions.Add(mixBlock); } } var block = Expression.Block(new[] { origin }, instructions); return block; } private BlockExpression MaterializeMixin(ParameterExpression me, FieldMixin mixin, ParameterExpression mixParam) { List<Expression> mixBindings = new List<Expression>(); mixBindings.Add(Expression.Assign(mixParam, GetMixin(me, mixin.FieldType))); mixBindings.Add(Expression.Call(retriever, miModifiablePostRetrieving.MakeGenericMethod(mixin.FieldType), mixParam)); foreach (var f in mixin.Fields.Values) { Expression value = MaterializeField(f.Field); var assigment = Expression.Assign(Expression.Field(mixParam, f.FieldInfo), value); mixBindings.Add(assigment); } var mixBlock = Expression.Block(new[] { mixParam }, mixBindings); return mixBlock; } } }
// // Encog(tm) Core v3.3 - .Net Version // http://www.heatonresearch.com/encog/ // // Copyright 2008-2014 Heaton Research, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // For more information on Heaton Research copyrights, licenses // and trademarks visit: // http://www.heatonresearch.com/copyright // using System; using System.Collections.Generic; using System.IO; using System.Text; using Encog.App.Analyst.CSV.Basic; using Encog.Util.CSV; using Encog.Util.Time; namespace Encog.App.Quant.Ninja { /// <summary> /// Can be used from within NinjaTrader to export data. This class is usually placed /// inside of a NinjaTrader indicator to export NinjaTrader indicators and data. /// </summary> public class NinjaStreamWriter { /// <summary> /// The columns to use. /// </summary> private readonly IList<String> columns = new List<String>(); /// <summary> /// True, if columns were defined. /// </summary> private bool columnsDefined; /// <summary> /// The format of the CSV file. /// </summary> private CSVFormat format; /// <summary> /// True, if headers are present. /// </summary> private bool headers; /// <summary> /// The output line, as it is built. /// </summary> private StringBuilder line; /// <summary> /// The output file. /// </summary> private TextWriter tw; /// <summary> /// Construct the object, and set the defaults. /// </summary> public NinjaStreamWriter() { Percision = 10; columnsDefined = false; } /// <summary> /// The percision to use. /// </summary> public int Percision { get; set; } /// <summary> /// Open the file for output. /// </summary> /// <param name="filename">The filename.</param> /// <param name="headers">True, if headers are present.</param> /// <param name="format">The CSV format.</param> public void Open(String filename, bool headers, CSVFormat format) { tw = new StreamWriter(filename); this.format = format; this.headers = headers; } /// <summary> /// Write the headers. /// </summary> private void WriteHeaders() { if (tw == null) throw new EncogError("Must open file first."); var line = new StringBuilder(); line.Append(FileData.Date); line.Append(format.Separator); line.Append(FileData.Time); foreach (String str in columns) { if (line.Length > 0) line.Append(format.Separator); line.Append("\""); line.Append(str); line.Append("\""); } tw.WriteLine(line.ToString()); } /// <summary> /// Close the file. /// </summary> public void Close() { if (tw == null) throw new EncogError("Must open file first."); tw.Close(); } /// <summary> /// Begin a bar, for the specified date/time. /// </summary> /// <param name="dt">The date/time where the bar begins.</param> public void BeginBar(DateTime dt) { if (tw == null) { throw new EncogError("Must open file first."); } if (line != null) { throw new EncogError("Must call end bar"); } line = new StringBuilder(); line.Append(NumericDateUtil.DateTime2Long(dt)); line.Append(format.Separator); line.Append(NumericDateUtil.Time2Int(dt)); } /// <summary> /// End the current bar. /// </summary> public void EndBar() { if (tw == null) { throw new EncogError("Must open file first."); } if (line == null) { throw new EncogError("Must call BeginBar first."); } if (headers && !columnsDefined) { WriteHeaders(); } tw.WriteLine(line.ToString()); line = null; columnsDefined = true; } /// <summary> /// Store a column. /// </summary> /// <param name="name">The name of the column.</param> /// <param name="d">The value to store.</param> public void StoreColumn(String name, double d) { if (line == null) { throw new EncogError("Must call BeginBar first."); } if (line.Length > 0) { line.Append(format.Separator); } line.Append(format.Format(d, Percision)); if (!columnsDefined) { columns.Add(name); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.DirectoryServices.ActiveDirectory { using System; using System.Text; using System.Diagnostics; using System.Globalization; using System.ComponentModel; using System.Runtime.InteropServices; using System.Security.Permissions; internal enum SearchFlags : int { None = 0, IsIndexed = 1, IsIndexedOverContainer = 2, IsInAnr = 4, IsOnTombstonedObject = 8, IsTupleIndexed = 32 } public class ActiveDirectorySchemaProperty : IDisposable { // private variables private DirectoryEntry _schemaEntry = null; private DirectoryEntry _propertyEntry = null; private DirectoryEntry _abstractPropertyEntry = null; private NativeComInterfaces.IAdsProperty _iadsProperty = null; private DirectoryContext _context = null; internal bool isBound = false; private bool _disposed = false; private ActiveDirectorySchema _schema = null; private bool _propertiesFromSchemaContainerInitialized = false; private bool _isDefunctOnServer = false; private SearchResult _propertyValuesFromServer = null; // private variables for caching properties private string _ldapDisplayName = null; private string _commonName = null; private string _oid = null; private ActiveDirectorySyntax _syntax = (ActiveDirectorySyntax)(-1); private bool _syntaxInitialized = false; private string _description = null; private bool _descriptionInitialized = false; private bool _isSingleValued = false; private bool _isSingleValuedInitialized = false; private bool _isInGlobalCatalog = false; private bool _isInGlobalCatalogInitialized = false; private Nullable<Int32> _rangeLower = null; private bool _rangeLowerInitialized = false; private Nullable<Int32> _rangeUpper = null; private bool _rangeUpperInitialized = false; private bool _isDefunct = false; private SearchFlags _searchFlags = SearchFlags.None; private bool _searchFlagsInitialized = false; private ActiveDirectorySchemaProperty _linkedProperty = null; private bool _linkedPropertyInitialized = false; private Nullable<Int32> _linkId = null; private bool _linkIdInitialized = false; private byte[] _schemaGuidBinaryForm = null; // OMObjectClass values for the syntax //0x2B0C0287731C00854A private static OMObjectClass s_dnOMObjectClass = new OMObjectClass(new byte[] { 0x2B, 0x0C, 0x02, 0x87, 0x73, 0x1C, 0x00, 0x85, 0x4A }); //0x2A864886F7140101010C private static OMObjectClass s_dNWithStringOMObjectClass = new OMObjectClass(new byte[] { 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x14, 0x01, 0x01, 0x01, 0x0C }); //0x2A864886F7140101010B private static OMObjectClass s_dNWithBinaryOMObjectClass = new OMObjectClass(new byte[] { 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x14, 0x01, 0x01, 0x01, 0x0B }); //0x2A864886F71401010106 private static OMObjectClass s_replicaLinkOMObjectClass = new OMObjectClass(new byte[] { 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x14, 0x01, 0x01, 0x01, 0x06 }); //0x2B0C0287731C00855C private static OMObjectClass s_presentationAddressOMObjectClass = new OMObjectClass(new byte[] { 0x2B, 0x0C, 0x02, 0x87, 0x73, 0x1C, 0x00, 0x85, 0x5C }); //0x2B0C0287731C00853E private static OMObjectClass s_accessPointDnOMObjectClass = new OMObjectClass(new byte[] { 0x2B, 0x0C, 0x02, 0x87, 0x73, 0x1C, 0x00, 0x85, 0x3E }); //0x56060102050B1D private static OMObjectClass s_oRNameOMObjectClass = new OMObjectClass(new byte[] { 0x56, 0x06, 0x01, 0x02, 0x05, 0x0B, 0x1D }); // syntaxes private static int s_syntaxesCount = 23; private static Syntax[] s_syntaxes = {/* CaseExactString */ new Syntax("2.5.5.3", 27, null), /* CaseIgnoreString */ new Syntax("2.5.5.4", 20, null), /* NumericString */ new Syntax("2.5.5.6", 18, null), /* DirectoryString */ new Syntax("2.5.5.12", 64, null), /* OctetString */ new Syntax("2.5.5.10", 4, null), /* SecurityDescriptor */ new Syntax("2.5.5.15", 66, null), /* Int */ new Syntax("2.5.5.9", 2, null), /* Int64 */ new Syntax("2.5.5.16", 65, null), /* Bool */ new Syntax("2.5.5.8", 1, null), /* Oid */ new Syntax("2.5.5.2", 6, null), /* GeneralizedTime */ new Syntax("2.5.5.11", 24, null), /* UtcTime */ new Syntax("2.5.5.11", 23, null), /* DN */ new Syntax("2.5.5.1", 127, s_dnOMObjectClass), /* DNWithBinary */ new Syntax("2.5.5.7", 127, s_dNWithBinaryOMObjectClass), /* DNWithString */ new Syntax("2.5.5.14", 127, s_dNWithStringOMObjectClass), /* Enumeration */ new Syntax("2.5.5.9", 10, null), /* IA5String */ new Syntax("2.5.5.5", 22, null), /* PrintableString */ new Syntax("2.5.5.5", 19, null), /* Sid */ new Syntax("2.5.5.17", 4, null), /* AccessPointDN */ new Syntax("2.5.5.14", 127, s_accessPointDnOMObjectClass), /* ORName */ new Syntax("2.5.5.7", 127, s_oRNameOMObjectClass), /* PresentationAddress */ new Syntax("2.5.5.13", 127, s_presentationAddressOMObjectClass), /* ReplicaLink */ new Syntax("2.5.5.10", 127, s_replicaLinkOMObjectClass)}; #region constructors public ActiveDirectorySchemaProperty(DirectoryContext context, string ldapDisplayName) { if (context == null) { throw new ArgumentNullException("context"); } if ((context.Name == null) && (!context.isRootDomain())) { throw new ArgumentException(SR.ContextNotAssociatedWithDomain, "context"); } if (context.Name != null) { // the target should be a valid forest name or a server if (!((context.isRootDomain()) || (context.isADAMConfigSet()) || (context.isServer()))) { throw new ArgumentException(SR.NotADOrADAM, "context"); } } if (ldapDisplayName == null) { throw new ArgumentNullException("ldapDisplayName"); } if (ldapDisplayName.Length == 0) { throw new ArgumentException(SR.EmptyStringParameter, "ldapDisplayName"); } _context = new DirectoryContext(context); // validate the context _schemaEntry = DirectoryEntryManager.GetDirectoryEntry(context, WellKnownDN.SchemaNamingContext); _schemaEntry.Bind(true); _ldapDisplayName = ldapDisplayName; // common name of the property defaults to the ldap display name _commonName = ldapDisplayName; // set the bind flag this.isBound = false; } // internal constructor internal ActiveDirectorySchemaProperty(DirectoryContext context, string ldapDisplayName, DirectoryEntry propertyEntry, DirectoryEntry schemaEntry) { _context = context; _ldapDisplayName = ldapDisplayName; // common name of the property defaults to the ldap display name _propertyEntry = propertyEntry; _isDefunctOnServer = false; _isDefunct = _isDefunctOnServer; try { // initialize the directory entry for the abstract schema class _abstractPropertyEntry = DirectoryEntryManager.GetDirectoryEntryInternal(context, "LDAP://" + context.GetServerName() + "/schema/" + ldapDisplayName); _iadsProperty = (NativeComInterfaces.IAdsProperty)_abstractPropertyEntry.NativeObject; } catch (COMException e) { if (e.ErrorCode == unchecked((int)0x80005000)) { throw new ActiveDirectoryObjectNotFoundException(SR.DSNotFound, typeof(ActiveDirectorySchemaProperty), ldapDisplayName); } else { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } } catch (InvalidCastException) { // this means that we found an object but it is not a schema class throw new ActiveDirectoryObjectNotFoundException(SR.DSNotFound, typeof(ActiveDirectorySchemaProperty), ldapDisplayName); } catch (ActiveDirectoryObjectNotFoundException) { // this is the case where the context is a config set and we could not find an ADAM instance in that config set throw new ActiveDirectoryOperationException(String.Format(CultureInfo.CurrentCulture, SR.ADAMInstanceNotFoundInConfigSet , context.Name)); } // set the bind flag this.isBound = true; } internal ActiveDirectorySchemaProperty(DirectoryContext context, string commonName, SearchResult propertyValuesFromServer, DirectoryEntry schemaEntry) { _context = context; _schemaEntry = schemaEntry; // all relevant properties have already been retrieved from the server _propertyValuesFromServer = propertyValuesFromServer; Debug.Assert(_propertyValuesFromServer != null); _propertiesFromSchemaContainerInitialized = true; _propertyEntry = GetSchemaPropertyDirectoryEntry(); // names _commonName = commonName; _ldapDisplayName = (string)GetValueFromCache(PropertyManager.LdapDisplayName, true); // this constructor is only called for defunct classes _isDefunctOnServer = true; _isDefunct = _isDefunctOnServer; // set the bind flag this.isBound = true; } internal ActiveDirectorySchemaProperty(DirectoryContext context, string commonName, string ldapDisplayName, DirectoryEntry propertyEntry, DirectoryEntry schemaEntry) { _context = context; _schemaEntry = schemaEntry; _propertyEntry = propertyEntry; // names _commonName = commonName; _ldapDisplayName = ldapDisplayName; // this constructor is only called for defunct properties _isDefunctOnServer = true; _isDefunct = _isDefunctOnServer; // set the bind flag this.isBound = true; } #endregion constructors #region IDisposable public void Dispose() { Dispose(true); } // private Dispose method protected virtual void Dispose(bool disposing) { if (!_disposed) { // check if this is an explicit Dispose // only then clean up the directory entries if (disposing) { // dispose schema entry if (_schemaEntry != null) { _schemaEntry.Dispose(); _schemaEntry = null; } // dispose property entry if (_propertyEntry != null) { _propertyEntry.Dispose(); _propertyEntry = null; } // dispose abstract class entry if (_abstractPropertyEntry != null) { _abstractPropertyEntry.Dispose(); _abstractPropertyEntry = null; } // dispose the schema object if (_schema != null) { _schema.Dispose(); } } _disposed = true; } } #endregion IDisposable #region public methods public static ActiveDirectorySchemaProperty FindByName(DirectoryContext context, string ldapDisplayName) { ActiveDirectorySchemaProperty schemaProperty = null; if (context == null) { throw new ArgumentNullException("context"); } if ((context.Name == null) && (!context.isRootDomain())) { throw new ArgumentException(SR.ContextNotAssociatedWithDomain, "context"); } if (context.Name != null) { // the target should be a valid forest name or a server if (!((context.isRootDomain()) || (context.isADAMConfigSet()) || (context.isServer()))) { throw new ArgumentException(SR.NotADOrADAM, "context"); } } if (ldapDisplayName == null) { throw new ArgumentNullException("ldapDisplayName"); } if (ldapDisplayName.Length == 0) { throw new ArgumentException(SR.EmptyStringParameter, "ldapDisplayName"); } // work with copy of the context context = new DirectoryContext(context); // create a schema property schemaProperty = new ActiveDirectorySchemaProperty(context, ldapDisplayName, (DirectoryEntry)null, null); return schemaProperty; } public void Save() { CheckIfDisposed(); if (!isBound) { try { // create a new directory entry for this class if (_schemaEntry == null) { _schemaEntry = DirectoryEntryManager.GetDirectoryEntry(_context, WellKnownDN.SchemaNamingContext); } // this will create the class and set the CN value string rdn = "CN=" + _commonName; rdn = Utils.GetEscapedPath(rdn); _propertyEntry = _schemaEntry.Children.Add(rdn, "attributeSchema"); } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(_context, e); } catch (ActiveDirectoryObjectNotFoundException) { // this is the case where the context is a config set and we could not find an ADAM instance in that config set throw new ActiveDirectoryOperationException(String.Format(CultureInfo.CurrentCulture, SR.ADAMInstanceNotFoundInConfigSet , _context.Name)); } // set the ldap display name property SetProperty(PropertyManager.LdapDisplayName, _ldapDisplayName); // set the oid value SetProperty(PropertyManager.AttributeID, _oid); // set the syntax if (_syntax != (ActiveDirectorySyntax)(-1)) { SetSyntax(_syntax); } // set the description SetProperty(PropertyManager.Description, _description); // set the isSingleValued attribute _propertyEntry.Properties[PropertyManager.IsSingleValued].Value = _isSingleValued; // set the isGlobalCatalogReplicated attribute _propertyEntry.Properties[PropertyManager.IsMemberOfPartialAttributeSet].Value = _isInGlobalCatalog; // set the isDefunct attribute _propertyEntry.Properties[PropertyManager.IsDefunct].Value = _isDefunct; // set the range lower attribute if (_rangeLower != null) { _propertyEntry.Properties[PropertyManager.RangeLower].Value = (int)_rangeLower.Value; } // set the range upper attribute if (_rangeUpper != null) { _propertyEntry.Properties[PropertyManager.RangeUpper].Value = (int)_rangeUpper.Value; } // set the searchFlags attribute if (_searchFlags != SearchFlags.None) { _propertyEntry.Properties[PropertyManager.SearchFlags].Value = (int)_searchFlags; } // set the link id if (_linkId != null) { _propertyEntry.Properties[PropertyManager.LinkID].Value = (int)_linkId.Value; } // set the schemaIDGuid property if (_schemaGuidBinaryForm != null) { SetProperty(PropertyManager.SchemaIDGuid, _schemaGuidBinaryForm); } } try { // commit the classEntry to server _propertyEntry.CommitChanges(); // Refresh the schema cache on the schema role owner if (_schema == null) { ActiveDirectorySchema schemaObject = ActiveDirectorySchema.GetSchema(_context); bool alreadyUsingSchemaRoleOwnerContext = false; DirectoryServer schemaRoleOwner = null; try { // // if we are not already talking to the schema role owner, change the context // schemaRoleOwner = schemaObject.SchemaRoleOwner; if (Utils.Compare(schemaRoleOwner.Name, _context.GetServerName()) != 0) { DirectoryContext schemaRoleOwnerContext = Utils.GetNewDirectoryContext(schemaRoleOwner.Name, DirectoryContextType.DirectoryServer, _context); _schema = ActiveDirectorySchema.GetSchema(schemaRoleOwnerContext); } else { alreadyUsingSchemaRoleOwnerContext = true; _schema = schemaObject; } } finally { if (schemaRoleOwner != null) { schemaRoleOwner.Dispose(); } if (!alreadyUsingSchemaRoleOwnerContext) { schemaObject.Dispose(); } } } _schema.RefreshSchema(); } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(_context, e); } // now that the changes are committed to the server // update the defunct/non-defunct status of the class on the server _isDefunctOnServer = _isDefunct; // invalidate all properties _commonName = null; _oid = null; _syntaxInitialized = false; _descriptionInitialized = false; _isSingleValuedInitialized = false; _isInGlobalCatalogInitialized = false; _rangeLowerInitialized = false; _rangeUpperInitialized = false; _searchFlagsInitialized = false; _linkedPropertyInitialized = false; _linkIdInitialized = false; _schemaGuidBinaryForm = null; _propertiesFromSchemaContainerInitialized = false; // set bind flag isBound = true; } public override string ToString() { return Name; } public DirectoryEntry GetDirectoryEntry() { CheckIfDisposed(); if (!isBound) { throw new InvalidOperationException(SR.CannotGetObject); } GetSchemaPropertyDirectoryEntry(); Debug.Assert(_propertyEntry != null); return DirectoryEntryManager.GetDirectoryEntryInternal(_context, _propertyEntry.Path); } #endregion public methods #region public properties public string Name { get { CheckIfDisposed(); return _ldapDisplayName; } } public string CommonName { get { CheckIfDisposed(); if (isBound) { if (_commonName == null) { // get the property from the server _commonName = (string)GetValueFromCache(PropertyManager.Cn, true); } } return _commonName; } set { CheckIfDisposed(); if (value != null && value.Length == 0) throw new ArgumentException(SR.EmptyStringParameter, "value"); if (isBound) { // set the value on the directory entry SetProperty(PropertyManager.Cn, value); } _commonName = value; } } public string Oid { get { CheckIfDisposed(); if (isBound) { if (_oid == null) { // get the property from the abstract schema/ schema container // (for non-defunt classes this property is available in the abstract schema) if (!_isDefunctOnServer) { try { _oid = _iadsProperty.OID; } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(_context, e); } } else { _oid = (string)GetValueFromCache(PropertyManager.AttributeID, true); } } } return _oid; } set { CheckIfDisposed(); if (value != null && value.Length == 0) throw new ArgumentException(SR.EmptyStringParameter, "value"); if (isBound) { // set the value on the directory entry SetProperty(PropertyManager.AttributeID, value); } _oid = value; } } public ActiveDirectorySyntax Syntax { get { CheckIfDisposed(); if (isBound) { if (!_syntaxInitialized) { byte[] omObjectClassBinaryForm = (byte[])GetValueFromCache(PropertyManager.OMObjectClass, false); OMObjectClass omObjectClass = (omObjectClassBinaryForm != null) ? new OMObjectClass(omObjectClassBinaryForm) : null; _syntax = MapSyntax((string)GetValueFromCache(PropertyManager.AttributeSyntax, true), (int)GetValueFromCache(PropertyManager.OMSyntax, true), omObjectClass); _syntaxInitialized = true; } } return _syntax; } set { CheckIfDisposed(); if (value < ActiveDirectorySyntax.CaseExactString || value > ActiveDirectorySyntax.ReplicaLink) { throw new InvalidEnumArgumentException("value", (int)value, typeof(ActiveDirectorySyntax)); } if (isBound) { // set the value on the directory entry SetSyntax(value); } _syntax = value; } } public string Description { get { CheckIfDisposed(); if (isBound) { if (!_descriptionInitialized) { // get the property from the server _description = (string)GetValueFromCache(PropertyManager.Description, false); _descriptionInitialized = true; } } return _description; } set { CheckIfDisposed(); if (value != null && value.Length == 0) throw new ArgumentException(SR.EmptyStringParameter, "value"); if (isBound) { // set the value on the directory entry SetProperty(PropertyManager.Description, value); } _description = value; } } public bool IsSingleValued { get { CheckIfDisposed(); if (isBound) { if (!_isSingleValuedInitialized) { // get the property from the abstract schema/ schema container // (for non-defunt classes this property is available in the abstract schema) if (!_isDefunctOnServer) { try { _isSingleValued = !_iadsProperty.MultiValued; } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(_context, e); } } else { _isSingleValued = (bool)GetValueFromCache(PropertyManager.IsSingleValued, true); } _isSingleValuedInitialized = true; } } return _isSingleValued; } set { CheckIfDisposed(); if (isBound) { // get the distinguished name to construct the directory entry GetSchemaPropertyDirectoryEntry(); Debug.Assert(_propertyEntry != null); // set the value on the directory entry _propertyEntry.Properties[PropertyManager.IsSingleValued].Value = value; } _isSingleValued = value; } } public bool IsIndexed { get { CheckIfDisposed(); return IsSetInSearchFlags(SearchFlags.IsIndexed); } set { CheckIfDisposed(); if (value) { SetBitInSearchFlags(SearchFlags.IsIndexed); } else { ResetBitInSearchFlags(SearchFlags.IsIndexed); } } } public bool IsIndexedOverContainer { get { CheckIfDisposed(); return IsSetInSearchFlags(SearchFlags.IsIndexedOverContainer); } set { CheckIfDisposed(); if (value) { SetBitInSearchFlags(SearchFlags.IsIndexedOverContainer); } else { ResetBitInSearchFlags(SearchFlags.IsIndexedOverContainer); } } } public bool IsInAnr { get { CheckIfDisposed(); return IsSetInSearchFlags(SearchFlags.IsInAnr); } set { CheckIfDisposed(); if (value) { SetBitInSearchFlags(SearchFlags.IsInAnr); } else { ResetBitInSearchFlags(SearchFlags.IsInAnr); } } } public bool IsOnTombstonedObject { get { CheckIfDisposed(); return IsSetInSearchFlags(SearchFlags.IsOnTombstonedObject); } set { CheckIfDisposed(); if (value) { SetBitInSearchFlags(SearchFlags.IsOnTombstonedObject); } else { ResetBitInSearchFlags(SearchFlags.IsOnTombstonedObject); } } } public bool IsTupleIndexed { get { CheckIfDisposed(); return IsSetInSearchFlags(SearchFlags.IsTupleIndexed); } set { CheckIfDisposed(); if (value) { SetBitInSearchFlags(SearchFlags.IsTupleIndexed); } else { ResetBitInSearchFlags(SearchFlags.IsTupleIndexed); } } } public bool IsInGlobalCatalog { get { CheckIfDisposed(); if (isBound) { if (!_isInGlobalCatalogInitialized) { // get the property from the server object value = GetValueFromCache(PropertyManager.IsMemberOfPartialAttributeSet, false); _isInGlobalCatalog = (value != null) ? (bool)value : false; _isInGlobalCatalogInitialized = true; } } return _isInGlobalCatalog; } set { CheckIfDisposed(); if (isBound) { // get the distinguished name to construct the directory entry GetSchemaPropertyDirectoryEntry(); Debug.Assert(_propertyEntry != null); // set the value on the directory entry _propertyEntry.Properties[PropertyManager.IsMemberOfPartialAttributeSet].Value = value; } _isInGlobalCatalog = value; } } public Nullable<Int32> RangeLower { get { CheckIfDisposed(); if (isBound) { if (!_rangeLowerInitialized) { // get the property from the server // if the property is not set then we will return null object value = GetValueFromCache(PropertyManager.RangeLower, false); if (value == null) { _rangeLower = null; } else { _rangeLower = (int)value; } _rangeLowerInitialized = true; } } return _rangeLower; } set { CheckIfDisposed(); if (isBound) { // get the distinguished name to construct the directory entry GetSchemaPropertyDirectoryEntry(); Debug.Assert(_propertyEntry != null); // set the value on the directory entry if (value == null) { if (_propertyEntry.Properties.Contains(PropertyManager.RangeLower)) { _propertyEntry.Properties[PropertyManager.RangeLower].Clear(); } } else { _propertyEntry.Properties[PropertyManager.RangeLower].Value = (int)value.Value; } } _rangeLower = value; } } public Nullable<Int32> RangeUpper { get { CheckIfDisposed(); if (isBound) { if (!_rangeUpperInitialized) { // get the property from the server // if the property is not set then we will return null object value = GetValueFromCache(PropertyManager.RangeUpper, false); if (value == null) { _rangeUpper = null; } else { _rangeUpper = (int)value; } _rangeUpperInitialized = true; } } return _rangeUpper; } set { CheckIfDisposed(); if (isBound) { // get the distinguished name to construct the directory entry GetSchemaPropertyDirectoryEntry(); Debug.Assert(_propertyEntry != null); // set the value on the directory entry if (value == null) { if (_propertyEntry.Properties.Contains(PropertyManager.RangeUpper)) { _propertyEntry.Properties[PropertyManager.RangeUpper].Clear(); } } else { _propertyEntry.Properties[PropertyManager.RangeUpper].Value = (int)value.Value; } } _rangeUpper = value; } } public bool IsDefunct { get { CheckIfDisposed(); // this is initialized for bound properties in the constructor return _isDefunct; } set { CheckIfDisposed(); if (isBound) { // set the value on the directory entry SetProperty(PropertyManager.IsDefunct, value); } _isDefunct = value; } } public ActiveDirectorySchemaProperty Link { get { CheckIfDisposed(); if (isBound) { if (!_linkedPropertyInitialized) { object value = GetValueFromCache(PropertyManager.LinkID, false); int tempLinkId = (value != null) ? (int)value : -1; if (tempLinkId != -1) { int linkIdToSearch = tempLinkId - 2 * (tempLinkId % 2) + 1; try { if (_schemaEntry == null) { _schemaEntry = DirectoryEntryManager.GetDirectoryEntry(_context, WellKnownDN.SchemaNamingContext); } string filter = "(&(" + PropertyManager.ObjectCategory + "=attributeSchema)" + "(" + PropertyManager.LinkID + "=" + linkIdToSearch + "))"; ReadOnlyActiveDirectorySchemaPropertyCollection linkedProperties = ActiveDirectorySchema.GetAllProperties(_context, _schemaEntry, filter); if (linkedProperties.Count != 1) { throw new ActiveDirectoryObjectNotFoundException(String.Format(CultureInfo.CurrentCulture, SR.LinkedPropertyNotFound , linkIdToSearch), typeof(ActiveDirectorySchemaProperty), null); } _linkedProperty = linkedProperties[0]; } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(_context, e); } } _linkedPropertyInitialized = true; } } return _linkedProperty; } } public Nullable<Int32> LinkId { get { CheckIfDisposed(); if (isBound) { if (!_linkIdInitialized) { object value = GetValueFromCache(PropertyManager.LinkID, false); // if the property was not set we will return null if (value == null) { _linkId = null; } else { _linkId = (int)value; } _linkIdInitialized = true; } } return _linkId; } set { CheckIfDisposed(); if (isBound) { // get the distinguished name to construct the directory entry GetSchemaPropertyDirectoryEntry(); Debug.Assert(_propertyEntry != null); // set the value on the directory entry if (value == null) { if (_propertyEntry.Properties.Contains(PropertyManager.LinkID)) { _propertyEntry.Properties[PropertyManager.LinkID].Clear(); } } else { _propertyEntry.Properties[PropertyManager.LinkID].Value = (int)value.Value; } } _linkId = value; } } public Guid SchemaGuid { get { CheckIfDisposed(); Guid schemaGuid = Guid.Empty; if (isBound) { if (_schemaGuidBinaryForm == null) { // get the property from the server _schemaGuidBinaryForm = (byte[])GetValueFromCache(PropertyManager.SchemaIDGuid, true); } } // we cache the byte array and create a new guid each time return new Guid(_schemaGuidBinaryForm); } set { CheckIfDisposed(); if (isBound) { // set the value on the directory entry SetProperty(PropertyManager.SchemaIDGuid, (value.Equals(Guid.Empty)) ? null : value.ToByteArray()); } _schemaGuidBinaryForm = (value.Equals(Guid.Empty)) ? null : value.ToByteArray(); } } #endregion public properties #region private methods private void CheckIfDisposed() { if (_disposed) { throw new ObjectDisposedException(GetType().Name); } } // // This method retrieves the value of a property (single valued) from the values // that were retrieved from the server. The "mustExist" parameter controls whether or // not an exception should be thrown if a value does not exist. If mustExist is true, this // will throw an exception is value does not exist. // private object GetValueFromCache(string propertyName, bool mustExist) { object value = null; // retrieve the properties from the server if necessary InitializePropertiesFromSchemaContainer(); Debug.Assert(_propertyValuesFromServer != null); ResultPropertyValueCollection propertyValues = null; try { propertyValues = _propertyValuesFromServer.Properties[propertyName]; if ((propertyValues == null) || (propertyValues.Count < 1)) { if (mustExist) { throw new ActiveDirectoryOperationException(String.Format(CultureInfo.CurrentCulture, SR.PropertyNotFound , propertyName)); } } else { value = propertyValues[0]; } } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(_context, e); } return value; } // // Just calls the static method GetPropertiesFromSchemaContainer with the correct context // private void InitializePropertiesFromSchemaContainer() { if (!_propertiesFromSchemaContainerInitialized) { if (_schemaEntry == null) { _schemaEntry = DirectoryEntryManager.GetDirectoryEntry(_context, WellKnownDN.SchemaNamingContext); } _propertyValuesFromServer = GetPropertiesFromSchemaContainer(_context, _schemaEntry, (_isDefunctOnServer) ? _commonName : _ldapDisplayName, _isDefunctOnServer); _propertiesFromSchemaContainerInitialized = true; } } // // This method retrieves properties for this schema class from the schema container // on the server. For non-defunct classes only properties that are not available in the abstract // schema are retrieved. For defunct classes, all the properties are retrieved. // The retrieved values are stored in a class variable "propertyValuesFromServer" which is a // hashtable indexed on the property name. // internal static SearchResult GetPropertiesFromSchemaContainer(DirectoryContext context, DirectoryEntry schemaEntry, string name, bool isDefunctOnServer) { SearchResult propertyValuesFromServer = null; // // The properties that are loaded from the schemaContainer for non-defunct classes: // DistinguishedName // CommonName // Syntax - AttributeSyntax, OMSyntax, OMObjectClass // Description // IsIndexed, IsIndexedOverContainer, IsInAnr, IsOnTombstonedObject, IsTupleIndexed - SearchFlags // IsInGlobalCatalog - IsMemberOfPartialAttributeSet // LinkId (Link) // SchemaGuid - SchemaIdGuid // RangeLower // RangeUpper // // For defunct class we also load teh remaining properties // LdapDisplayName // Oid // IsSingleValued // // build the filter StringBuilder str = new StringBuilder(15); str.Append("(&("); str.Append(PropertyManager.ObjectCategory); str.Append("=attributeSchema)"); str.Append("("); if (!isDefunctOnServer) { str.Append(PropertyManager.LdapDisplayName); } else { str.Append(PropertyManager.Cn); } str.Append("="); str.Append(Utils.GetEscapedFilterValue(name)); str.Append(")"); if (!isDefunctOnServer) { str.Append("(!("); } else { str.Append("("); } str.Append(PropertyManager.IsDefunct); if (!isDefunctOnServer) { str.Append("=TRUE)))"); } else { str.Append("=TRUE))"); } string[] propertiesToLoad = null; if (!isDefunctOnServer) { propertiesToLoad = new string[12]; propertiesToLoad[0] = PropertyManager.DistinguishedName; propertiesToLoad[1] = PropertyManager.Cn; propertiesToLoad[2] = PropertyManager.AttributeSyntax; propertiesToLoad[3] = PropertyManager.OMSyntax; propertiesToLoad[4] = PropertyManager.OMObjectClass; propertiesToLoad[5] = PropertyManager.Description; propertiesToLoad[6] = PropertyManager.SearchFlags; propertiesToLoad[7] = PropertyManager.IsMemberOfPartialAttributeSet; propertiesToLoad[8] = PropertyManager.LinkID; propertiesToLoad[9] = PropertyManager.SchemaIDGuid; propertiesToLoad[10] = PropertyManager.RangeLower; propertiesToLoad[11] = PropertyManager.RangeUpper; } else { propertiesToLoad = new string[15]; propertiesToLoad[0] = PropertyManager.DistinguishedName; propertiesToLoad[1] = PropertyManager.Cn; propertiesToLoad[2] = PropertyManager.AttributeSyntax; propertiesToLoad[3] = PropertyManager.OMSyntax; propertiesToLoad[4] = PropertyManager.OMObjectClass; propertiesToLoad[5] = PropertyManager.Description; propertiesToLoad[6] = PropertyManager.SearchFlags; propertiesToLoad[7] = PropertyManager.IsMemberOfPartialAttributeSet; propertiesToLoad[8] = PropertyManager.LinkID; propertiesToLoad[9] = PropertyManager.SchemaIDGuid; propertiesToLoad[10] = PropertyManager.AttributeID; propertiesToLoad[11] = PropertyManager.IsSingleValued; propertiesToLoad[12] = PropertyManager.RangeLower; propertiesToLoad[13] = PropertyManager.RangeUpper; propertiesToLoad[14] = PropertyManager.LdapDisplayName; } // // Get all the values (don't need to use range retrieval as there are no multivalued attributes) // ADSearcher searcher = new ADSearcher(schemaEntry, str.ToString(), propertiesToLoad, SearchScope.OneLevel, false /* paged search */, false /* cache results */); try { propertyValuesFromServer = searcher.FindOne(); } catch (COMException e) { if (e.ErrorCode == unchecked((int)0x80072030)) { // object is not found since we cannot even find the container in which to search throw new ActiveDirectoryObjectNotFoundException(SR.DSNotFound, typeof(ActiveDirectorySchemaProperty), name); } else { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } } if (propertyValuesFromServer == null) { throw new ActiveDirectoryObjectNotFoundException(SR.DSNotFound, typeof(ActiveDirectorySchemaProperty), name); } return propertyValuesFromServer; } internal DirectoryEntry GetSchemaPropertyDirectoryEntry() { if (_propertyEntry == null) { InitializePropertiesFromSchemaContainer(); _propertyEntry = DirectoryEntryManager.GetDirectoryEntry(_context, (string)GetValueFromCache(PropertyManager.DistinguishedName, true)); } return _propertyEntry; } /// /// <summary> /// Initializes the search flags attribute value i.e. fetches it from /// the directory, if this object is bound. /// </summary> /// private void InitializeSearchFlags() { if (isBound) { if (!_searchFlagsInitialized) { object value = GetValueFromCache(PropertyManager.SearchFlags, false); if (value != null) { _searchFlags = (SearchFlags)((int)value); } _searchFlagsInitialized = true; } } } private bool IsSetInSearchFlags(SearchFlags searchFlagBit) { InitializeSearchFlags(); return (((int)_searchFlags & (int)searchFlagBit) != 0); } private void SetBitInSearchFlags(SearchFlags searchFlagBit) { InitializeSearchFlags(); _searchFlags = (SearchFlags)((int)_searchFlags | (int)searchFlagBit); if (isBound) { // get the distinguished name to construct the directory entry GetSchemaPropertyDirectoryEntry(); Debug.Assert(_propertyEntry != null); // set the value on the directory entry _propertyEntry.Properties[PropertyManager.SearchFlags].Value = (int)_searchFlags; } } private void ResetBitInSearchFlags(SearchFlags searchFlagBit) { InitializeSearchFlags(); _searchFlags = (SearchFlags)((int)_searchFlags & ~((int)searchFlagBit)); if (isBound) { // get the distinguished name to construct the directory entry GetSchemaPropertyDirectoryEntry(); Debug.Assert(_propertyEntry != null); // set the value on the directory entry _propertyEntry.Properties[PropertyManager.SearchFlags].Value = (int)_searchFlags; } } private void SetProperty(string propertyName, object value) { // get the distinguished name to construct the directory entry GetSchemaPropertyDirectoryEntry(); Debug.Assert(_propertyEntry != null); if (value == null) { if (_propertyEntry.Properties.Contains(propertyName)) { _propertyEntry.Properties[propertyName].Clear(); } } else { _propertyEntry.Properties[propertyName].Value = value; } } private ActiveDirectorySyntax MapSyntax(string syntaxId, int oMID, OMObjectClass oMObjectClass) { for (int i = 0; i < s_syntaxesCount; i++) { if (s_syntaxes[i].Equals(new Syntax(syntaxId, oMID, oMObjectClass))) { return (ActiveDirectorySyntax)i; } } throw new ActiveDirectoryOperationException(String.Format(CultureInfo.CurrentCulture, SR.UnknownSyntax , _ldapDisplayName)); } private void SetSyntax(ActiveDirectorySyntax syntax) { if ((((int)syntax) < 0) || (((int)syntax) > (s_syntaxesCount - 1))) { throw new InvalidEnumArgumentException("syntax", (int)syntax, typeof(ActiveDirectorySyntax)); } // get the distinguished name to construct the directory entry GetSchemaPropertyDirectoryEntry(); Debug.Assert(_propertyEntry != null); _propertyEntry.Properties[PropertyManager.AttributeSyntax].Value = s_syntaxes[(int)syntax].attributeSyntax; _propertyEntry.Properties[PropertyManager.OMSyntax].Value = s_syntaxes[(int)syntax].oMSyntax; OMObjectClass oMObjectClass = s_syntaxes[(int)syntax].oMObjectClass; if (oMObjectClass != null) { _propertyEntry.Properties[PropertyManager.OMObjectClass].Value = oMObjectClass.Data; } } #endregion private methods } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Reflection; #if BUILD_PEANUTBUTTER_INTERNAL namespace Imported.PeanutButter.Utils.Dictionaries #else namespace PeanutButter.Utils.Dictionaries #endif { /// <summary> /// Provides a mechanism to merge multiple dictionaries into one /// Source dictionaries /// </summary> /// <typeparam name="TKey"></typeparam> /// <typeparam name="TValue"></typeparam> #if BUILD_PEANUTBUTTER_INTERNAL internal #else public #endif class MergeDictionary<TKey, TValue> : IDictionary<TKey, TValue> { // ReSharper disable once StaticMemberInGenericType private static readonly InvalidOperationException ReadonlyException = new InvalidOperationException($"{typeof(MergeDictionary<,>)} is ALWAYS read-only"); private readonly IDictionary<TKey, TValue>[] _layers; /// <summary> /// Expose the first (or least-restrictive, for strings) key comparer /// </summary> // ReSharper disable once UnusedMember.Global public IEqualityComparer<TKey> Comparer => GetComparer(); private IEqualityComparer<TKey> GetComparer() { if (typeof(TKey) == typeof(string)) { return FindLeastRestrictiveStringComparer() as IEqualityComparer<TKey>; } return _layers .Select(l => GetPropertyValue(l, "Comparer") as IEqualityComparer<TKey>) .FirstOrDefault(); } private IEqualityComparer<string> FindLeastRestrictiveStringComparer() { return _layers .Select(l => GetPropertyValue(l, "Comparer") as IEqualityComparer<string>) .Where(c => c != null) .Select(c => new { Comparer = c, Rank = StringComparerRankings.TryGetValue(c, out var rank) ? rank : 99 }) .OrderBy(o => o.Rank) .FirstOrDefault() ?.Comparer; } private static object GetPropertyValue(object src, string propertyPath) { var parts = propertyPath.Split('.'); return parts.Aggregate(src, GetImmediatePropertyValue); } private static object GetImmediatePropertyValue(object src, string propertyName) { var type = src.GetType(); var propInfo = type.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance) .FirstOrDefault(pi => pi.Name == propertyName); if (propInfo == null) throw new Exception($"Member \"${propertyName}\" not found on type \"${type}\""); return propInfo.GetValue(src, null); } // ReSharper disable once StaticMemberInGenericType private static readonly Dictionary<IEqualityComparer<string>, int> StringComparerRankings = new Dictionary<IEqualityComparer<string>, int>() { [StringComparer.OrdinalIgnoreCase] = 1, #if NETSTANDARD #else [StringComparer.InvariantCultureIgnoreCase] = 2, #endif [StringComparer.CurrentCultureIgnoreCase] = 3, #if NETSTANDARD #else [StringComparer.InvariantCulture] = 4, #endif [StringComparer.CurrentCulture] = 5, [StringComparer.Ordinal] = 6 }; /// <summary> /// Construct MergeDictionary over other dictionaries /// </summary> /// <param name="layers"></param> public MergeDictionary(params IDictionary<TKey, TValue>[] layers) { // TODO: test that we have any layers _layers = layers.Where(l => l != null).ToArray(); if (_layers.IsEmpty()) throw new InvalidOperationException("No non-null layers provided"); } /// <summary> /// Gets an Enumerator for the KeyValuePairs in this merged /// dictionary, prioritised by the order of provided layers /// </summary> /// <returns></returns> public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator() { return new GenericDictionaryEnumerator<TKey, TValue>(_layers); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } /// <summary> /// Will throw - MergeDictionary is read-only /// </summary> /// <param name="item"></param> /// <exception cref="InvalidOperationException"></exception> public void Add(KeyValuePair<TKey, TValue> item) { throw ReadonlyException; } /// <summary> /// Will throw - MergeDictionary is read-only /// </summary> /// <exception cref="InvalidOperationException"></exception> public void Clear() { throw ReadonlyException; } /// <summary> /// Returns true if any layer contains the provided item /// </summary> /// <param name="item">Item to search for</param> /// <returns>True if found, False if not</returns> public bool Contains(KeyValuePair<TKey, TValue> item) { return _layers.Aggregate(false, (acc, cur) => acc || cur.Contains(item) ); } /// <summary> /// Copies the prioritised items to the provided array from the given arrayIndex /// </summary> /// <param name="array">Target array to copy to</param> /// <param name="arrayIndex">Index to start copying at</param> public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex) { using (var enumerator = GetEnumerator()) { while (enumerator.MoveNext() && arrayIndex < array.Length) { array[arrayIndex++] = enumerator.Current; } } } /// <summary> /// Will throw an exception - MergeDictionary is read-only /// </summary> /// <param name="item">Item to remove</param> /// <returns></returns> /// <exception cref="InvalidOperationException"></exception> public bool Remove(KeyValuePair<TKey, TValue> item) { throw ReadonlyException; } /// <summary> /// Returns the count of distinct keys /// </summary> public int Count => _layers.SelectMany(kvp => kvp.Keys).Distinct().Count(); /// <summary> /// Will return true: MergeDictionaries are read-only /// </summary> public bool IsReadOnly => true; /// <summary> /// Searches for the given key across all layers /// </summary> /// <param name="key">Key to search for</param> /// <returns>True if found, False otherwise</returns> public bool ContainsKey(TKey key) { return _layers.Aggregate(false, (acc, cur) => acc || cur.ContainsKey(key)); } /// <summary> /// Will throw - MergeDictionaries are read-only /// </summary> /// <param name="key"></param> /// <param name="value"></param> /// <exception cref="InvalidOperationException"></exception> public void Add(TKey key, TValue value) { throw ReadonlyException; } /// <summary> /// Will throw - MergeDictionaries are read-only /// </summary> /// <param name="key"></param> /// <returns></returns> /// <exception cref="InvalidOperationException"></exception> public bool Remove(TKey key) { throw ReadonlyException; } /// <summary> /// Tries to get a value by key from the underlying layers /// </summary> /// <param name="key">Key to search for</param> /// <param name="value">Value to search for</param> /// <returns>True if found, False otherwise</returns> public bool TryGetValue(TKey key, out TValue value) { foreach (var layer in _layers) { if (layer.TryGetValue(key, out value)) { return true; } } value = default(TValue); return false; } /// <summary> /// Index into the layers to find the highest-priority match for the /// provided key /// </summary> /// <param name="key">Key to look up</param> public TValue this[TKey key] { get => TryGetValue(key, out var value) ? value : throw new KeyNotFoundException(key.ToString()); set => throw ReadonlyException; } /// <summary> /// Returns a collection of the distinct keys in all layers /// </summary> public ICollection<TKey> Keys => _layers.SelectMany(l => l).Select(i => i.Key).Distinct().ToArray(); /// <summary> /// Returns a collection of ALL values in all layers /// </summary> public ICollection<TValue> Values => Keys.Select(k => this[k]).ToArray(); } }
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using ICSharpCode.NRefactory.TypeSystem; using Saltarelle.Compiler; using Saltarelle.Compiler.Compiler; using Saltarelle.Compiler.JSModel.Expressions; using Saltarelle.Compiler.JSModel.ExtensionMethods; using Saltarelle.Compiler.ScriptSemantics; namespace CoreLib.Plugin { public class MetadataImporter : IMetadataImporter { private static readonly ReadOnlySet<string> _unusableStaticFieldNames = new ReadOnlySet<string>(new HashSet<string>(new[] { "__defineGetter__", "__defineSetter__", "apply", "arguments", "bind", "call", "caller", "constructor", "hasOwnProperty", "isPrototypeOf", "length", "name", "propertyIsEnumerable", "prototype", "toLocaleString", "valueOf" }.Concat(Saltarelle.Compiler.JSModel.Utils.AllKeywords))); private static readonly ReadOnlySet<string> _unusableInstanceFieldNames = new ReadOnlySet<string>(new HashSet<string>(new[] { "__defineGetter__", "__defineSetter__", "constructor", "hasOwnProperty", "isPrototypeOf", "propertyIsEnumerable", "toLocaleString", "valueOf" }.Concat(Saltarelle.Compiler.JSModel.Utils.AllKeywords))); private class TypeSemantics { public TypeScriptSemantics Semantics { get; private set; } public bool IsSerializable { get; private set; } public bool IsNamedValues { get; private set; } public bool IsImported { get; private set; } public TypeSemantics(TypeScriptSemantics semantics, bool isSerializable, bool isNamedValues, bool isImported) { Semantics = semantics; IsSerializable = isSerializable; IsNamedValues = isNamedValues; IsImported = isImported; } } private Dictionary<ITypeDefinition, TypeSemantics> _typeSemantics; private Dictionary<ITypeDefinition, DelegateScriptSemantics> _delegateSemantics; private Dictionary<ITypeDefinition, HashSet<string>> _instanceMemberNamesByType; private Dictionary<ITypeDefinition, HashSet<string>> _staticMemberNamesByType; private Dictionary<IMethod, MethodScriptSemantics> _methodSemantics; private Dictionary<IProperty, PropertyScriptSemantics> _propertySemantics; private Dictionary<IField, FieldScriptSemantics> _fieldSemantics; private Dictionary<IEvent, EventScriptSemantics> _eventSemantics; private Dictionary<IMethod, ConstructorScriptSemantics> _constructorSemantics; private Dictionary<IProperty, string> _propertyBackingFieldNames; private Dictionary<IEvent, string> _eventBackingFieldNames; private Dictionary<ITypeDefinition, int> _backingFieldCountPerType; private Dictionary<Tuple<IAssembly, string>, int> _internalTypeCountPerAssemblyAndNamespace; private HashSet<IMember> _ignoredMembers; private IErrorReporter _errorReporter; private IType _systemObject; private ICompilation _compilation; private bool _minimizeNames; public MetadataImporter(IErrorReporter errorReporter, ICompilation compilation, CompilerOptions options) { _errorReporter = errorReporter; _compilation = compilation; _minimizeNames = options.MinimizeScript; _systemObject = compilation.MainAssembly.Compilation.FindType(KnownTypeCode.Object); _typeSemantics = new Dictionary<ITypeDefinition, TypeSemantics>(); _delegateSemantics = new Dictionary<ITypeDefinition, DelegateScriptSemantics>(); _instanceMemberNamesByType = new Dictionary<ITypeDefinition, HashSet<string>>(); _staticMemberNamesByType = new Dictionary<ITypeDefinition, HashSet<string>>(); _methodSemantics = new Dictionary<IMethod, MethodScriptSemantics>(); _propertySemantics = new Dictionary<IProperty, PropertyScriptSemantics>(); _fieldSemantics = new Dictionary<IField, FieldScriptSemantics>(); _eventSemantics = new Dictionary<IEvent, EventScriptSemantics>(); _constructorSemantics = new Dictionary<IMethod, ConstructorScriptSemantics>(); _propertyBackingFieldNames = new Dictionary<IProperty, string>(); _eventBackingFieldNames = new Dictionary<IEvent, string>(); _backingFieldCountPerType = new Dictionary<ITypeDefinition, int>(); _internalTypeCountPerAssemblyAndNamespace = new Dictionary<Tuple<IAssembly, string>, int>(); _ignoredMembers = new HashSet<IMember>(); var sna = compilation.MainAssembly.AssemblyAttributes.SingleOrDefault(a => a.AttributeType.FullName == typeof(ScriptNamespaceAttribute).FullName); if (sna != null) { var data = AttributeReader.ReadAttribute<ScriptNamespaceAttribute>(sna); if (data.Name == null || (data.Name != "" && !data.Name.IsValidNestedJavaScriptIdentifier())) { Message(Messages._7002, sna.Region, "assembly"); } } } private void Message(Tuple<int, MessageSeverity, string> message, DomRegion r, params object[] additionalArgs) { _errorReporter.Region = r; _errorReporter.Message(message, additionalArgs); } private void Message(Tuple<int, MessageSeverity, string> message, IEntity e, params object[] additionalArgs) { var name = (e is IMethod && ((IMethod)e).IsConstructor ? e.DeclaringType.FullName : e.FullName); _errorReporter.Region = e.Region; _errorReporter.Message(message, new object[] { name }.Concat(additionalArgs).ToArray()); } private string GetDefaultTypeName(ITypeDefinition def, bool ignoreGenericArguments) { if (ignoreGenericArguments) { return def.Name; } else { int outerCount = (def.DeclaringTypeDefinition != null ? def.DeclaringTypeDefinition.TypeParameters.Count : 0); return def.Name + (def.TypeParameterCount != outerCount ? "$" + (def.TypeParameterCount - outerCount).ToString(CultureInfo.InvariantCulture) : ""); } } private bool? IsAutoProperty(IProperty property) { if (property.Region == default(DomRegion)) return null; return property.Getter != null && property.Setter != null && property.Getter.BodyRegion == default(DomRegion) && property.Setter.BodyRegion == default(DomRegion); } private string DetermineNamespace(ITypeDefinition typeDefinition) { while (typeDefinition.DeclaringTypeDefinition != null) { typeDefinition = typeDefinition.DeclaringTypeDefinition; } var ina = AttributeReader.ReadAttribute<IgnoreNamespaceAttribute>(typeDefinition); var sna = AttributeReader.ReadAttribute<ScriptNamespaceAttribute>(typeDefinition); if (ina != null) { if (sna != null) { Message(Messages._7001, typeDefinition); return typeDefinition.FullName; } else { return ""; } } else { if (sna != null) { if (sna.Name == null || (sna.Name != "" && !sna.Name.IsValidNestedJavaScriptIdentifier())) Message(Messages._7002, typeDefinition); return sna.Name; } else { var asna = AttributeReader.ReadAttribute<ScriptNamespaceAttribute>(typeDefinition.ParentAssembly.AssemblyAttributes); if (asna != null) { if (asna.Name != null && (asna.Name == "" || asna.Name.IsValidNestedJavaScriptIdentifier())) return asna.Name; } return typeDefinition.Namespace; } } } private Tuple<string, string> SplitNamespacedName(string fullName) { string nmspace; string name; int dot = fullName.IndexOf('.'); if (dot >= 0) { nmspace = fullName.Substring(0, dot); name = fullName.Substring(dot + 1 ); } else { nmspace = ""; name = fullName; } return Tuple.Create(nmspace, name); } private void ProcessDelegate(ITypeDefinition delegateDefinition) { bool bindThisToFirstParameter = AttributeReader.HasAttribute<BindThisToFirstParameterAttribute>(delegateDefinition); bool expandParams = AttributeReader.HasAttribute<ExpandParamsAttribute>(delegateDefinition); if (bindThisToFirstParameter && delegateDefinition.GetDelegateInvokeMethod().Parameters.Count == 0) { Message(Messages._7147, delegateDefinition, delegateDefinition.FullName); bindThisToFirstParameter = false; } if (expandParams && !delegateDefinition.GetDelegateInvokeMethod().Parameters.Any(p => p.IsParams)) { Message(Messages._7148, delegateDefinition, delegateDefinition.FullName); expandParams = false; } _delegateSemantics[delegateDefinition] = new DelegateScriptSemantics(expandParams: expandParams, bindThisToFirstParameter: bindThisToFirstParameter); } private void ProcessType(ITypeDefinition typeDefinition) { if (typeDefinition.Kind == TypeKind.Delegate) { ProcessDelegate(typeDefinition); return; } if (AttributeReader.HasAttribute<NonScriptableAttribute>(typeDefinition) || typeDefinition.DeclaringTypeDefinition != null && GetTypeSemantics(typeDefinition.DeclaringTypeDefinition).Type == TypeScriptSemantics.ImplType.NotUsableFromScript) { _typeSemantics[typeDefinition] = new TypeSemantics(TypeScriptSemantics.NotUsableFromScript(), false, false, false); return; } var scriptNameAttr = AttributeReader.ReadAttribute<ScriptNameAttribute>(typeDefinition); var importedAttr = AttributeReader.ReadAttribute<ImportedAttribute>(typeDefinition.Attributes); bool preserveName = importedAttr != null || AttributeReader.HasAttribute<PreserveNameAttribute>(typeDefinition); bool? includeGenericArguments = typeDefinition.TypeParameterCount > 0 ? MetadataUtils.ShouldGenericArgumentsBeIncluded(typeDefinition) : false; if (includeGenericArguments == null) { _errorReporter.Region = typeDefinition.Region; Message(Messages._7026, typeDefinition); includeGenericArguments = true; } if (AttributeReader.HasAttribute<ResourcesAttribute>(typeDefinition)) { if (!typeDefinition.IsStatic) { Message(Messages._7003, typeDefinition); } else if (typeDefinition.TypeParameterCount > 0) { Message(Messages._7004, typeDefinition); } else if (typeDefinition.Members.Any(m => !(m is IField && ((IField)m).IsConst))) { Message(Messages._7005, typeDefinition); } } string typeName, nmspace; if (scriptNameAttr != null && scriptNameAttr.Name != null && scriptNameAttr.Name.IsValidJavaScriptIdentifier()) { typeName = scriptNameAttr.Name; nmspace = DetermineNamespace(typeDefinition); } else { if (scriptNameAttr != null) { Message(Messages._7006, typeDefinition); } if (_minimizeNames && MetadataUtils.CanBeMinimized(typeDefinition) && !preserveName) { nmspace = DetermineNamespace(typeDefinition); var key = Tuple.Create(typeDefinition.ParentAssembly, nmspace); int index; _internalTypeCountPerAssemblyAndNamespace.TryGetValue(key, out index); _internalTypeCountPerAssemblyAndNamespace[key] = index + 1; typeName = "$" + index.ToString(CultureInfo.InvariantCulture); } else { typeName = GetDefaultTypeName(typeDefinition, !includeGenericArguments.Value); if (typeDefinition.DeclaringTypeDefinition != null) { if (AttributeReader.HasAttribute<IgnoreNamespaceAttribute>(typeDefinition) || AttributeReader.HasAttribute<ScriptNamespaceAttribute>(typeDefinition)) { Message(Messages._7007, typeDefinition); } var declaringName = SplitNamespacedName(GetTypeSemantics(typeDefinition.DeclaringTypeDefinition).Name); nmspace = declaringName.Item1; typeName = declaringName.Item2 + "$" + typeName; } else { nmspace = DetermineNamespace(typeDefinition); } if (MetadataUtils.CanBeMinimized(typeDefinition) && !preserveName && !typeName.StartsWith("$")) { typeName = "$" + typeName; } } } bool isSerializable = MetadataUtils.IsSerializable(typeDefinition); if (isSerializable) { var baseClass = typeDefinition.DirectBaseTypes.Single(c => c.Kind == TypeKind.Class).GetDefinition(); if (!baseClass.Equals(_systemObject) && baseClass.FullName != "System.Record" && !GetTypeSemanticsInternal(baseClass).IsSerializable) { Message(Messages._7009, typeDefinition); } foreach (var i in typeDefinition.DirectBaseTypes.Where(b => b.Kind == TypeKind.Interface && !GetTypeSemanticsInternal(b.GetDefinition()).IsSerializable)) { Message(Messages._7010, typeDefinition, i); } if (typeDefinition.Events.Any(evt => !evt.IsStatic)) { Message(Messages._7011, typeDefinition); } foreach (var m in typeDefinition.Members.Where(m => m.IsVirtual)) { Message(Messages._7023, typeDefinition, m.Name); } foreach (var m in typeDefinition.Members.Where(m => m.IsOverride)) { Message(Messages._7024, typeDefinition, m.Name); } if (typeDefinition.Kind == TypeKind.Interface && typeDefinition.Methods.Any()) { Message(Messages._7155, typeDefinition); } } else { var globalMethodsAttr = AttributeReader.ReadAttribute<GlobalMethodsAttribute>(typeDefinition); var mixinAttr = AttributeReader.ReadAttribute<MixinAttribute>(typeDefinition); if (mixinAttr != null) { if (!typeDefinition.IsStatic) { Message(Messages._7012, typeDefinition); } else if (typeDefinition.Members.Any(m => !(m is IMethod) || ((IMethod)m).IsConstructor)) { Message(Messages._7013, typeDefinition); } else if (typeDefinition.TypeParameterCount > 0) { Message(Messages._7014, typeDefinition); } else if (string.IsNullOrEmpty(mixinAttr.Expression)) { Message(Messages._7025, typeDefinition); } else { var split = SplitNamespacedName(mixinAttr.Expression); nmspace = split.Item1; typeName = split.Item2; } } else if (globalMethodsAttr != null) { if (!typeDefinition.IsStatic) { Message(Messages._7015, typeDefinition); } else if (typeDefinition.TypeParameterCount > 0) { Message(Messages._7017, typeDefinition); } else { nmspace = ""; typeName = ""; } } } if (importedAttr != null) { if (!string.IsNullOrEmpty(importedAttr.TypeCheckCode)) { if (importedAttr.ObeysTypeSystem) { Message(Messages._7158, typeDefinition); } ValidateInlineCode(MetadataUtils.CreateTypeCheckMethod(typeDefinition, _compilation), typeDefinition, importedAttr.TypeCheckCode, Messages._7157); } if (!string.IsNullOrEmpty(MetadataUtils.GetSerializableTypeCheckCode(typeDefinition))) { Message(Messages._7159, typeDefinition); } } _typeSemantics[typeDefinition] = new TypeSemantics(TypeScriptSemantics.NormalType(!string.IsNullOrEmpty(nmspace) ? nmspace + "." + typeName : typeName, ignoreGenericArguments: !includeGenericArguments.Value, generateCode: importedAttr == null), isSerializable: isSerializable, isNamedValues: MetadataUtils.IsNamedValues(typeDefinition), isImported: importedAttr != null); } private HashSet<string> GetInstanceMemberNames(ITypeDefinition typeDefinition) { HashSet<string> result; if (!_instanceMemberNamesByType.TryGetValue(typeDefinition, out result)) throw new ArgumentException("Error getting instance member names: type " + typeDefinition.FullName + " has not yet been processed."); return result; } private Tuple<string, bool> DeterminePreferredMemberName(IMember member) { var asa = AttributeReader.ReadAttribute<AlternateSignatureAttribute>(member); if (asa != null) { var otherMembers = member.DeclaringTypeDefinition.Methods.Where(m => m.Name == member.Name && !AttributeReader.HasAttribute<AlternateSignatureAttribute>(m) && !AttributeReader.HasAttribute<NonScriptableAttribute>(m) && !AttributeReader.HasAttribute<InlineCodeAttribute>(m)).ToList(); if (otherMembers.Count != 1) { Message(Messages._7100, member); return Tuple.Create(member.Name, false); } } return MetadataUtils.DeterminePreferredMemberName(member, _minimizeNames); } private void ProcessTypeMembers(ITypeDefinition typeDefinition) { if (typeDefinition.Kind == TypeKind.Delegate) return; var baseMembersByType = typeDefinition.GetAllBaseTypeDefinitions().Where(x => x != typeDefinition).Select(t => new { Type = t, MemberNames = GetInstanceMemberNames(t) }).ToList(); for (int i = 0; i < baseMembersByType.Count; i++) { var b = baseMembersByType[i]; for (int j = i + 1; j < baseMembersByType.Count; j++) { var b2 = baseMembersByType[j]; if (!b.Type.GetAllBaseTypeDefinitions().Contains(b2.Type) && !b2.Type.GetAllBaseTypeDefinitions().Contains(b.Type)) { foreach (var dup in b.MemberNames.Where(x => b2.MemberNames.Contains(x))) { Message(Messages._7018, typeDefinition, b.Type.FullName, b2.Type.FullName, dup); } } } } var instanceMembers = baseMembersByType.SelectMany(m => m.MemberNames).Distinct().ToDictionary(m => m, m => false); if (_instanceMemberNamesByType.ContainsKey(typeDefinition)) _instanceMemberNamesByType[typeDefinition].ForEach(s => instanceMembers[s] = true); _unusableInstanceFieldNames.ForEach(n => instanceMembers[n] = false); var staticMembers = _unusableStaticFieldNames.ToDictionary(n => n, n => false); if (_staticMemberNamesByType.ContainsKey(typeDefinition)) _staticMemberNamesByType[typeDefinition].ForEach(s => staticMembers[s] = true); var membersByName = from m in typeDefinition.GetMembers(options: GetMemberOptions.IgnoreInheritedMembers) where !_ignoredMembers.Contains(m) let name = DeterminePreferredMemberName(m) group new { m, name } by name.Item1 into g select new { Name = g.Key, Members = g.Select(x => new { Member = x.m, NameSpecified = x.name.Item2 }).ToList() }; bool isSerializable = GetTypeSemanticsInternal(typeDefinition).IsSerializable; foreach (var current in membersByName) { foreach (var m in current.Members.OrderByDescending(x => x.NameSpecified).ThenBy(x => x.Member, MemberOrderer.Instance)) { if (m.Member is IMethod) { var method = (IMethod)m.Member; if (method.IsConstructor) { ProcessConstructor(method, current.Name, m.NameSpecified, staticMembers); } else { ProcessMethod(method, current.Name, m.NameSpecified, m.Member.IsStatic || isSerializable ? staticMembers : instanceMembers); } } else if (m.Member is IProperty) { var p = (IProperty)m.Member; ProcessProperty(p, current.Name, m.NameSpecified, m.Member.IsStatic ? staticMembers : instanceMembers); var ps = GetPropertySemantics(p); if (p.CanGet) _methodSemantics[p.Getter] = ps.Type == PropertyScriptSemantics.ImplType.GetAndSetMethods ? ps.GetMethod : MethodScriptSemantics.NotUsableFromScript(); if (p.CanSet) _methodSemantics[p.Setter] = ps.Type == PropertyScriptSemantics.ImplType.GetAndSetMethods ? ps.SetMethod : MethodScriptSemantics.NotUsableFromScript(); } else if (m.Member is IField) { ProcessField((IField)m.Member, current.Name, m.NameSpecified, m.Member.IsStatic ? staticMembers : instanceMembers); } else if (m.Member is IEvent) { var e = (IEvent)m.Member; ProcessEvent((IEvent)m.Member, current.Name, m.NameSpecified, m.Member.IsStatic ? staticMembers : instanceMembers); var es = GetEventSemantics(e); _methodSemantics[e.AddAccessor] = es.Type == EventScriptSemantics.ImplType.AddAndRemoveMethods ? es.AddMethod : MethodScriptSemantics.NotUsableFromScript(); _methodSemantics[e.RemoveAccessor] = es.Type == EventScriptSemantics.ImplType.AddAndRemoveMethods ? es.RemoveMethod : MethodScriptSemantics.NotUsableFromScript(); } } } _instanceMemberNamesByType[typeDefinition] = new HashSet<string>(instanceMembers.Where(kvp => kvp.Value).Select(kvp => kvp.Key)); _staticMemberNamesByType[typeDefinition] = new HashSet<string>(staticMembers.Where(kvp => kvp.Value).Select(kvp => kvp.Key)); } private string GetUniqueName(string preferredName, Dictionary<string, bool> usedNames) { return MetadataUtils.GetUniqueName(preferredName, n => !usedNames.ContainsKey(n)); } private bool ValidateInlineCode(IMethod method, IEntity errorEntity, string code, Tuple<int, MessageSeverity, string> errorTemplate) { var typeErrors = new List<string>(); var errors = InlineCodeMethodCompiler.ValidateLiteralCode(method, code, n => { var type = ReflectionHelper.ParseReflectionName(n).Resolve(_compilation); if (type.Kind == TypeKind.Unknown) { typeErrors.Add("Unknown type '" + n + "' specified in inline implementation"); } return JsExpression.Null; }, t => JsExpression.Null); if (errors.Count > 0 || typeErrors.Count > 0) { Message(errorTemplate, errorEntity, string.Join(", ", errors.Concat(typeErrors))); return false; } return true; } private void ProcessConstructor(IMethod constructor, string preferredName, bool nameSpecified, Dictionary<string, bool> usedNames) { if (constructor.Parameters.Count == 1 && constructor.Parameters[0].Type.FullName == typeof(DummyTypeUsedToAddAttributeToDefaultValueTypeConstructor).FullName) { _constructorSemantics[constructor] = ConstructorScriptSemantics.NotUsableFromScript(); return; } var source = (IMethod)MetadataUtils.UnwrapValueTypeConstructor(constructor); var nsa = AttributeReader.ReadAttribute<NonScriptableAttribute>(source); var asa = AttributeReader.ReadAttribute<AlternateSignatureAttribute>(source); var epa = AttributeReader.ReadAttribute<ExpandParamsAttribute>(source); var ola = AttributeReader.ReadAttribute<ObjectLiteralAttribute>(source); if (nsa != null || GetTypeSemanticsInternal(source.DeclaringTypeDefinition).Semantics.Type == TypeScriptSemantics.ImplType.NotUsableFromScript) { _constructorSemantics[constructor] = ConstructorScriptSemantics.NotUsableFromScript(); return; } if (source.IsStatic) { _constructorSemantics[constructor] = ConstructorScriptSemantics.Unnamed(); // Whatever, it is not really used. return; } if (epa != null && !source.Parameters.Any(p => p.IsParams)) { Message(Messages._7102, constructor); } bool isSerializable = GetTypeSemanticsInternal(source.DeclaringTypeDefinition).IsSerializable; bool isImported = GetTypeSemanticsInternal(source.DeclaringTypeDefinition).IsImported; bool skipInInitializer = AttributeReader.HasAttribute<ScriptSkipAttribute>(constructor); var ica = AttributeReader.ReadAttribute<InlineCodeAttribute>(source); if (ica != null) { if (!ValidateInlineCode(source, source, ica.Code, Messages._7103)) { _constructorSemantics[constructor] = ConstructorScriptSemantics.Unnamed(); return; } _constructorSemantics[constructor] = ConstructorScriptSemantics.InlineCode(ica.Code, skipInInitializer: skipInInitializer); return; } else if (asa != null) { _constructorSemantics[constructor] = preferredName == "$ctor" ? ConstructorScriptSemantics.Unnamed(generateCode: false, expandParams: epa != null, skipInInitializer: skipInInitializer) : ConstructorScriptSemantics.Named(preferredName, generateCode: false, expandParams: epa != null, skipInInitializer: skipInInitializer); return; } else if (ola != null || (isSerializable && GetTypeSemanticsInternal(source.DeclaringTypeDefinition).IsImported)) { if (isSerializable) { bool hasError = false; var members = source.DeclaringTypeDefinition.Members.Where(m => m.EntityType == EntityType.Property || m.EntityType == EntityType.Field).ToDictionary(m => m.Name.ToLowerInvariant()); var parameterToMemberMap = new List<IMember>(); foreach (var p in source.Parameters) { IMember member; if (p.IsOut || p.IsRef) { Message(Messages._7145, p.Region, p.Name); hasError = true; } else if (members.TryGetValue(p.Name.ToLowerInvariant(), out member)) { if (p.Type.GetAllBaseTypes().Any(b => b.Equals(member.ReturnType)) || (member.ReturnType.IsKnownType(KnownTypeCode.NullableOfT) && member.ReturnType.TypeArguments[0].Equals(p.Type))) { parameterToMemberMap.Add(member); } else { Message(Messages._7144, p.Region, p.Name, p.Type.FullName, member.ReturnType.FullName); hasError = true; } } else { Message(Messages._7143, p.Region, source.DeclaringTypeDefinition.FullName, p.Name); hasError = true; } } _constructorSemantics[constructor] = hasError ? ConstructorScriptSemantics.Unnamed() : ConstructorScriptSemantics.Json(parameterToMemberMap, skipInInitializer: skipInInitializer || constructor.Parameters.Count == 0); } else { Message(Messages._7146, constructor.Region, source.DeclaringTypeDefinition.FullName); _constructorSemantics[constructor] = ConstructorScriptSemantics.Unnamed(); } return; } else if (source.Parameters.Count == 1 && source.Parameters[0].Type is ArrayType && ((ArrayType)source.Parameters[0].Type).ElementType.IsKnownType(KnownTypeCode.Object) && source.Parameters[0].IsParams && isImported) { _constructorSemantics[constructor] = ConstructorScriptSemantics.InlineCode("ss.mkdict({" + source.Parameters[0].Name + "})", skipInInitializer: skipInInitializer); return; } else if (nameSpecified) { if (isSerializable) _constructorSemantics[constructor] = ConstructorScriptSemantics.StaticMethod(preferredName, expandParams: epa != null, skipInInitializer: skipInInitializer); else _constructorSemantics[constructor] = preferredName == "$ctor" ? ConstructorScriptSemantics.Unnamed(expandParams: epa != null, skipInInitializer: skipInInitializer) : ConstructorScriptSemantics.Named(preferredName, expandParams: epa != null, skipInInitializer: skipInInitializer); usedNames[preferredName] = true; return; } else { if (!usedNames.ContainsKey("$ctor") && !(isSerializable && _minimizeNames && MetadataUtils.CanBeMinimized(source))) { // The last part ensures that the first constructor of a serializable type can have its name minimized. _constructorSemantics[constructor] = isSerializable ? ConstructorScriptSemantics.StaticMethod("$ctor", expandParams: epa != null, skipInInitializer: skipInInitializer) : ConstructorScriptSemantics.Unnamed(expandParams: epa != null, skipInInitializer: skipInInitializer); usedNames["$ctor"] = true; return; } else { string name; if (_minimizeNames && MetadataUtils.CanBeMinimized(source)) { name = GetUniqueName(null, usedNames); } else { int i = 1; do { name = "$ctor" + MetadataUtils.EncodeNumber(i, false); i++; } while (usedNames.ContainsKey(name)); } _constructorSemantics[constructor] = isSerializable ? ConstructorScriptSemantics.StaticMethod(name, expandParams: epa != null, skipInInitializer: skipInInitializer) : ConstructorScriptSemantics.Named(name, expandParams: epa != null, skipInInitializer: skipInInitializer); usedNames[name] = true; return; } } } private void ProcessProperty(IProperty property, string preferredName, bool nameSpecified, Dictionary<string, bool> usedNames) { if (GetTypeSemanticsInternal(property.DeclaringTypeDefinition).Semantics.Type == TypeScriptSemantics.ImplType.NotUsableFromScript || AttributeReader.HasAttribute<NonScriptableAttribute>(property)) { _propertySemantics[property] = PropertyScriptSemantics.NotUsableFromScript(); return; } else if (preferredName == "") { if (property.IsIndexer) { Message(Messages._7104, property); } else { Message(Messages._7105, property); } _propertySemantics[property] = PropertyScriptSemantics.GetAndSetMethods(property.CanGet ? MethodScriptSemantics.NormalMethod("get") : null, property.CanSet ? MethodScriptSemantics.NormalMethod("set") : null); return; } else if (GetTypeSemanticsInternal(property.DeclaringTypeDefinition).IsSerializable && !property.IsStatic) { var getica = property.Getter != null ? AttributeReader.ReadAttribute<InlineCodeAttribute>(property.Getter) : null; var setica = property.Setter != null ? AttributeReader.ReadAttribute<InlineCodeAttribute>(property.Setter) : null; if (property.Getter != null && property.Setter != null && (getica != null) != (setica != null)) { Message(Messages._7028, property); } else if (getica != null || setica != null) { bool hasError = false; if (property.Getter != null && !ValidateInlineCode(property.Getter, property.Getter, getica.Code, Messages._7130)) { hasError = true; } if (property.Setter != null && !ValidateInlineCode(property.Setter, property.Setter, setica.Code, Messages._7130)) { hasError = true; } if (!hasError) { _propertySemantics[property] = PropertyScriptSemantics.GetAndSetMethods(getica != null ? MethodScriptSemantics.InlineCode(getica.Code) : null, setica != null ? MethodScriptSemantics.InlineCode(setica.Code) : null); return; } } usedNames[preferredName] = true; _propertySemantics[property] = PropertyScriptSemantics.Field(preferredName); return; } var saa = AttributeReader.ReadAttribute<ScriptAliasAttribute>(property); if (saa != null) { if (property.IsIndexer) { Message(Messages._7106, property.Region); } else if (!property.IsStatic) { Message(Messages._7107, property); } else { _propertySemantics[property] = PropertyScriptSemantics.GetAndSetMethods(property.CanGet ? MethodScriptSemantics.InlineCode(saa.Alias) : null, property.CanSet ? MethodScriptSemantics.InlineCode(saa.Alias + " = {value}") : null); return; } } if (AttributeReader.HasAttribute<IntrinsicPropertyAttribute>(property)) { if (property.DeclaringType.Kind == TypeKind.Interface) { if (property.IsIndexer) Message(Messages._7108, property.Region); else Message(Messages._7109, property); } else if (property.IsOverride && GetPropertySemantics((IProperty)InheritanceHelper.GetBaseMember(property).MemberDefinition).Type != PropertyScriptSemantics.ImplType.NotUsableFromScript) { if (property.IsIndexer) Message(Messages._7110, property.Region); else Message(Messages._7111, property); } else if (property.IsOverridable) { if (property.IsIndexer) Message(Messages._7112, property.Region); else Message(Messages._7113, property); } else if (property.IsExplicitInterfaceImplementation || property.ImplementedInterfaceMembers.Any(m => GetPropertySemantics((IProperty)m.MemberDefinition).Type != PropertyScriptSemantics.ImplType.NotUsableFromScript)) { if (property.IsIndexer) Message(Messages._7114, property.Region); else Message(Messages._7115, property); } else if (property.IsIndexer) { if (property.Parameters.Count == 1) { _propertySemantics[property] = PropertyScriptSemantics.GetAndSetMethods(property.CanGet ? MethodScriptSemantics.NativeIndexer() : null, property.CanSet ? MethodScriptSemantics.NativeIndexer() : null); return; } else { Message(Messages._7116, property.Region); } } else { usedNames[preferredName] = true; _propertySemantics[property] = PropertyScriptSemantics.Field(preferredName); return; } } if (property.IsExplicitInterfaceImplementation && property.ImplementedInterfaceMembers.Any(m => GetPropertySemantics((IProperty)m.MemberDefinition).Type == PropertyScriptSemantics.ImplType.NotUsableFromScript)) { // Inherit [NonScriptable] for explicit interface implementations. _propertySemantics[property] = PropertyScriptSemantics.NotUsableFromScript(); return; } if (property.ImplementedInterfaceMembers.Count > 0) { var bases = property.ImplementedInterfaceMembers.Where(b => GetPropertySemantics((IProperty)b).Type != PropertyScriptSemantics.ImplType.NotUsableFromScript).ToList(); var firstField = bases.FirstOrDefault(b => GetPropertySemantics((IProperty)b).Type == PropertyScriptSemantics.ImplType.Field); if (firstField != null) { var firstFieldSemantics = GetPropertySemantics((IProperty)firstField); if (property.IsOverride) { Message(Messages._7154, property, firstField.FullName); } else if (property.IsOverridable) { Message(Messages._7153, property, firstField.FullName); } if (IsAutoProperty(property) == false) { Message(Messages._7156, property, firstField.FullName); } _propertySemantics[property] = firstFieldSemantics; return; } } MethodScriptSemantics getter, setter; if (property.CanGet) { var getterName = DeterminePreferredMemberName(property.Getter); if (!getterName.Item2) getterName = Tuple.Create(!nameSpecified && _minimizeNames && property.DeclaringType.Kind != TypeKind.Interface && MetadataUtils.CanBeMinimized(property) ? null : (nameSpecified ? "get_" + preferredName : GetUniqueName("get_" + preferredName, usedNames)), false); // If the name was not specified, generate one. ProcessMethod(property.Getter, getterName.Item1, getterName.Item2, usedNames); getter = GetMethodSemantics(property.Getter); } else { getter = null; } if (property.CanSet) { var setterName = DeterminePreferredMemberName(property.Setter); if (!setterName.Item2) setterName = Tuple.Create(!nameSpecified && _minimizeNames && property.DeclaringType.Kind != TypeKind.Interface && MetadataUtils.CanBeMinimized(property) ? null : (nameSpecified ? "set_" + preferredName : GetUniqueName("set_" + preferredName, usedNames)), false); // If the name was not specified, generate one. ProcessMethod(property.Setter, setterName.Item1, setterName.Item2, usedNames); setter = GetMethodSemantics(property.Setter); } else { setter = null; } _propertySemantics[property] = PropertyScriptSemantics.GetAndSetMethods(getter, setter); } private void ProcessMethod(IMethod method, string preferredName, bool nameSpecified, Dictionary<string, bool> usedNames) { var eaa = AttributeReader.ReadAttribute<EnumerateAsArrayAttribute>(method); var ssa = AttributeReader.ReadAttribute<ScriptSkipAttribute>(method); var saa = AttributeReader.ReadAttribute<ScriptAliasAttribute>(method); var ica = AttributeReader.ReadAttribute<InlineCodeAttribute>(method); var ifa = AttributeReader.ReadAttribute<InstanceMethodOnFirstArgumentAttribute>(method); var nsa = AttributeReader.ReadAttribute<NonScriptableAttribute>(method); var ioa = AttributeReader.ReadAttribute<IntrinsicOperatorAttribute>(method); var epa = AttributeReader.ReadAttribute<ExpandParamsAttribute>(method); var asa = AttributeReader.ReadAttribute<AlternateSignatureAttribute>(method); bool? includeGenericArguments = method.TypeParameters.Count > 0 ? MetadataUtils.ShouldGenericArgumentsBeIncluded(method) : false; if (eaa != null && (method.Name != "GetEnumerator" || method.IsStatic || method.TypeParameters.Count > 0 || method.Parameters.Count > 0)) { Message(Messages._7151, method); eaa = null; } if (nsa != null || GetTypeSemanticsInternal(method.DeclaringTypeDefinition).Semantics.Type == TypeScriptSemantics.ImplType.NotUsableFromScript) { _methodSemantics[method] = MethodScriptSemantics.NotUsableFromScript(); return; } if (ioa != null) { if (!method.IsOperator) { Message(Messages._7117, method); _methodSemantics[method] = MethodScriptSemantics.NormalMethod(method.Name); } if (method.Name == "op_Implicit" || method.Name == "op_Explicit") { Message(Messages._7118, method); _methodSemantics[method] = MethodScriptSemantics.NormalMethod(method.Name); } else { _methodSemantics[method] = MethodScriptSemantics.NativeOperator(); } return; } else { var interfaceImplementations = method.ImplementedInterfaceMembers.Where(m => method.IsExplicitInterfaceImplementation || _methodSemantics[(IMethod)m.MemberDefinition].Type != MethodScriptSemantics.ImplType.NotUsableFromScript).ToList(); if (ssa != null) { // [ScriptSkip] - Skip invocation of the method entirely. if (method.DeclaringTypeDefinition.Kind == TypeKind.Interface) { Message(Messages._7119, method); _methodSemantics[method] = MethodScriptSemantics.NormalMethod(method.Name); return; } else if (method.IsOverride && GetMethodSemantics((IMethod)InheritanceHelper.GetBaseMember(method).MemberDefinition).Type != MethodScriptSemantics.ImplType.NotUsableFromScript) { Message(Messages._7120, method); _methodSemantics[method] = MethodScriptSemantics.NormalMethod(method.Name); return; } else if (method.IsOverridable) { Message(Messages._7121, method); _methodSemantics[method] = MethodScriptSemantics.NormalMethod(method.Name); return; } else if (interfaceImplementations.Count > 0) { Message(Messages._7122, method); _methodSemantics[method] = MethodScriptSemantics.NormalMethod(method.Name); return; } else { if (method.IsStatic) { if (method.Parameters.Count != 1) { Message(Messages._7123, method); _methodSemantics[method] = MethodScriptSemantics.NormalMethod(method.Name); return; } _methodSemantics[method] = MethodScriptSemantics.InlineCode("{" + method.Parameters[0].Name + "}", enumerateAsArray: eaa != null); return; } else { if (method.Parameters.Count != 0) Message(Messages._7124, method); _methodSemantics[method] = MethodScriptSemantics.InlineCode("{this}", enumerateAsArray: eaa != null); return; } } } else if (saa != null) { if (method.IsStatic) { _methodSemantics[method] = MethodScriptSemantics.InlineCode(saa.Alias + "(" + string.Join(", ", method.Parameters.Select(p => "{" + p.Name + "}")) + ")"); return; } else { Message(Messages._7125, method); _methodSemantics[method] = MethodScriptSemantics.NormalMethod(method.Name); return; } } else if (ica != null) { string code = ica.Code ?? "", nonVirtualCode = ica.NonVirtualCode ?? ica.Code ?? ""; if (method.DeclaringTypeDefinition.Kind == TypeKind.Interface && string.IsNullOrEmpty(ica.GeneratedMethodName)) { Message(Messages._7126, method); _methodSemantics[method] = MethodScriptSemantics.NormalMethod(method.Name); return; } else if (method.IsOverride && GetMethodSemantics((IMethod)InheritanceHelper.GetBaseMember(method).MemberDefinition).Type != MethodScriptSemantics.ImplType.NotUsableFromScript) { Message(Messages._7127, method); _methodSemantics[method] = MethodScriptSemantics.NormalMethod(method.Name); return; } else if (method.IsOverridable && string.IsNullOrEmpty(ica.GeneratedMethodName)) { Message(Messages._7128, method); _methodSemantics[method] = MethodScriptSemantics.NormalMethod(method.Name); return; } else { if (!ValidateInlineCode(method, method, code, Messages._7130)) { code = nonVirtualCode = "X"; } if (!string.IsNullOrEmpty(ica.NonVirtualCode) && !ValidateInlineCode(method, method, ica.NonVirtualCode, Messages._7130)) { code = nonVirtualCode = "X"; } _methodSemantics[method] = MethodScriptSemantics.InlineCode(code, enumerateAsArray: eaa != null, generatedMethodName: !string.IsNullOrEmpty(ica.GeneratedMethodName) ? ica.GeneratedMethodName : null, nonVirtualInvocationLiteralCode: nonVirtualCode); if (!string.IsNullOrEmpty(ica.GeneratedMethodName)) usedNames[ica.GeneratedMethodName] = true; return; } } else if (ifa != null) { if (method.IsStatic) { if (epa != null && !method.Parameters.Any(p => p.IsParams)) { Message(Messages._7137, method); } if (method.Parameters.Count == 0) { Message(Messages._7149, method); _methodSemantics[method] = MethodScriptSemantics.NormalMethod(method.Name); return; } else if (method.Parameters[0].IsParams) { Message(Messages._7150, method); _methodSemantics[method] = MethodScriptSemantics.NormalMethod(method.Name); return; } else { var sb = new StringBuilder(); sb.Append("{" + method.Parameters[0].Name + "}." + preferredName + "("); for (int i = 1; i < method.Parameters.Count; i++) { var p = method.Parameters[i]; if (i > 1) sb.Append(", "); sb.Append((epa != null && p.IsParams ? "{*" : "{") + p.Name + "}"); } sb.Append(")"); _methodSemantics[method] = MethodScriptSemantics.InlineCode(sb.ToString()); return; } } else { Message(Messages._7131, method); _methodSemantics[method] = MethodScriptSemantics.NormalMethod(method.Name); return; } } else { if (method.IsOverride && GetMethodSemantics((IMethod)InheritanceHelper.GetBaseMember(method).MemberDefinition).Type != MethodScriptSemantics.ImplType.NotUsableFromScript) { if (nameSpecified) { Message(Messages._7132, method); } if (AttributeReader.HasAttribute<IncludeGenericArgumentsAttribute>(method)) { Message(Messages._7133, method); } var semantics = GetMethodSemantics((IMethod)InheritanceHelper.GetBaseMember(method).MemberDefinition); if (semantics.Type == MethodScriptSemantics.ImplType.InlineCode && semantics.GeneratedMethodName != null) semantics = MethodScriptSemantics.NormalMethod(semantics.GeneratedMethodName, ignoreGenericArguments: semantics.IgnoreGenericArguments, expandParams: semantics.ExpandParams); // Methods derived from methods with [InlineCode(..., GeneratedMethodName = "Something")] are treated as normal methods. if (eaa != null) semantics = semantics.WithEnumerateAsArray(); if (semantics.Type == MethodScriptSemantics.ImplType.NormalMethod) { var errorMethod = method.ImplementedInterfaceMembers.FirstOrDefault(im => GetMethodSemantics((IMethod)im.MemberDefinition).Name != semantics.Name); if (errorMethod != null) { Message(Messages._7134, method, errorMethod.FullName); } } _methodSemantics[method] = semantics; return; } else if (interfaceImplementations.Count > 0) { if (nameSpecified) { Message(Messages._7135, method); } var candidateNames = method.ImplementedInterfaceMembers .Select(im => GetMethodSemantics((IMethod)im.MemberDefinition)) .Select(s => s.Type == MethodScriptSemantics.ImplType.NormalMethod ? s.Name : (s.Type == MethodScriptSemantics.ImplType.InlineCode ? s.GeneratedMethodName : null)) .Where(name => name != null) .Distinct(); if (candidateNames.Count() > 1) { Message(Messages._7136, method); } // If the method implements more than one interface member, prefer to take the implementation from one that is not unusable. var sem = method.ImplementedInterfaceMembers.Select(im => GetMethodSemantics((IMethod)im.MemberDefinition)).FirstOrDefault(x => x.Type != MethodScriptSemantics.ImplType.NotUsableFromScript) ?? MethodScriptSemantics.NotUsableFromScript(); if (sem.Type == MethodScriptSemantics.ImplType.InlineCode && sem.GeneratedMethodName != null) sem = MethodScriptSemantics.NormalMethod(sem.GeneratedMethodName, ignoreGenericArguments: sem.IgnoreGenericArguments, expandParams: sem.ExpandParams); // Methods implementing methods with [InlineCode(..., GeneratedMethodName = "Something")] are treated as normal methods. if (eaa != null) sem = sem.WithEnumerateAsArray(); _methodSemantics[method] = sem; return; } else { if (includeGenericArguments == null) { _errorReporter.Region = method.Region; Message(Messages._7027, method); includeGenericArguments = true; } if (epa != null) { if (!method.Parameters.Any(p => p.IsParams)) { Message(Messages._7137, method); } } if (preferredName == "") { // Special case - Script# supports setting the name of a method to an empty string, which means that it simply removes the name (eg. "x.M(a)" becomes "x(a)"). We model this with literal code. if (method.DeclaringTypeDefinition.Kind == TypeKind.Interface) { Message(Messages._7138, method); _methodSemantics[method] = MethodScriptSemantics.NormalMethod(method.Name); return; } else if (method.IsOverridable) { Message(Messages._7139, method); _methodSemantics[method] = MethodScriptSemantics.NormalMethod(method.Name); return; } else if (method.IsStatic) { Message(Messages._7140, method); _methodSemantics[method] = MethodScriptSemantics.NormalMethod(method.Name); return; } else { _methodSemantics[method] = MethodScriptSemantics.InlineCode("{this}(" + string.Join(", ", method.Parameters.Select(p => "{" + p.Name + "}")) + ")", enumerateAsArray: eaa != null); return; } } else { string name = nameSpecified ? preferredName : GetUniqueName(preferredName, usedNames); if (asa == null) usedNames[name] = true; if (GetTypeSemanticsInternal(method.DeclaringTypeDefinition).IsSerializable && !method.IsStatic) { _methodSemantics[method] = MethodScriptSemantics.StaticMethodWithThisAsFirstArgument(name, generateCode: !AttributeReader.HasAttribute<AlternateSignatureAttribute>(method), ignoreGenericArguments: !includeGenericArguments.Value, expandParams: epa != null, enumerateAsArray: eaa != null); } else { _methodSemantics[method] = MethodScriptSemantics.NormalMethod(name, generateCode: !AttributeReader.HasAttribute<AlternateSignatureAttribute>(method), ignoreGenericArguments: !includeGenericArguments.Value, expandParams: epa != null, enumerateAsArray: eaa != null); } } } } } } private void ProcessEvent(IEvent evt, string preferredName, bool nameSpecified, Dictionary<string, bool> usedNames) { if (GetTypeSemanticsInternal(evt.DeclaringTypeDefinition).Semantics.Type == TypeScriptSemantics.ImplType.NotUsableFromScript || AttributeReader.HasAttribute<NonScriptableAttribute>(evt)) { _eventSemantics[evt] = EventScriptSemantics.NotUsableFromScript(); return; } else if (preferredName == "") { Message(Messages._7141, evt); _eventSemantics[evt] = EventScriptSemantics.AddAndRemoveMethods(MethodScriptSemantics.NormalMethod("add"), MethodScriptSemantics.NormalMethod("remove")); return; } MethodScriptSemantics adder, remover; if (evt.CanAdd) { var getterName = DeterminePreferredMemberName(evt.AddAccessor); if (!getterName.Item2) getterName = Tuple.Create(!nameSpecified && _minimizeNames && evt.DeclaringType.Kind != TypeKind.Interface && MetadataUtils.CanBeMinimized(evt) ? null : (nameSpecified ? "add_" + preferredName : GetUniqueName("add_" + preferredName, usedNames)), false); // If the name was not specified, generate one. ProcessMethod(evt.AddAccessor, getterName.Item1, getterName.Item2, usedNames); adder = GetMethodSemantics(evt.AddAccessor); } else { adder = null; } if (evt.CanRemove) { var setterName = DeterminePreferredMemberName(evt.RemoveAccessor); if (!setterName.Item2) setterName = Tuple.Create(!nameSpecified && _minimizeNames && evt.DeclaringType.Kind != TypeKind.Interface && MetadataUtils.CanBeMinimized(evt) ? null : (nameSpecified ? "remove_" + preferredName : GetUniqueName("remove_" + preferredName, usedNames)), false); // If the name was not specified, generate one. ProcessMethod(evt.RemoveAccessor, setterName.Item1, setterName.Item2, usedNames); remover = GetMethodSemantics(evt.RemoveAccessor); } else { remover = null; } _eventSemantics[evt] = EventScriptSemantics.AddAndRemoveMethods(adder, remover); } private void ProcessField(IField field, string preferredName, bool nameSpecified, Dictionary<string, bool> usedNames) { if (GetTypeSemanticsInternal(field.DeclaringTypeDefinition).Semantics.Type == TypeScriptSemantics.ImplType.NotUsableFromScript || AttributeReader.HasAttribute<NonScriptableAttribute>(field)) { _fieldSemantics[field] = FieldScriptSemantics.NotUsableFromScript(); } else if (preferredName == "") { Message(Messages._7142, field); _fieldSemantics[field] = FieldScriptSemantics.Field("X"); } else { string name = (nameSpecified ? preferredName : GetUniqueName(preferredName, usedNames)); if (AttributeReader.HasAttribute<InlineConstantAttribute>(field)) { if (field.IsConst) { name = null; } else { Message(Messages._7152, field); } } else { usedNames[name] = true; } if (GetTypeSemanticsInternal(field.DeclaringTypeDefinition).IsNamedValues) { string value = preferredName; if (!nameSpecified) { // This code handles the feature that it is possible to specify an invalid ScriptName for a member of a NamedValues enum, in which case that value has to be use as the constant value. var sna = AttributeReader.ReadAttribute<ScriptNameAttribute>(field); if (sna != null) value = sna.Name; } _fieldSemantics[field] = FieldScriptSemantics.StringConstant(value, name); } else if (field.DeclaringType.Kind == TypeKind.Enum && AttributeReader.HasAttribute<ImportedAttribute>(field.DeclaringTypeDefinition) && AttributeReader.HasAttribute<ScriptNameAttribute>(field.DeclaringTypeDefinition)) { // Fields of enums that are imported and have an explicit [ScriptName] are treated as normal fields. _fieldSemantics[field] = FieldScriptSemantics.Field(name); } else if (name == null || (field.IsConst && (field.DeclaringType.Kind == TypeKind.Enum || _minimizeNames))) { object value = Saltarelle.Compiler.JSModel.Utils.ConvertToDoubleOrStringOrBoolean(field.ConstantValue); if (value is bool) _fieldSemantics[field] = FieldScriptSemantics.BooleanConstant((bool)value, name); else if (value is double) _fieldSemantics[field] = FieldScriptSemantics.NumericConstant((double)value, name); else if (value is string) _fieldSemantics[field] = FieldScriptSemantics.StringConstant((string)value, name); else _fieldSemantics[field] = FieldScriptSemantics.NullConstant(name); } else { _fieldSemantics[field] = FieldScriptSemantics.Field(name); } } } public void Prepare(ITypeDefinition type) { try { ProcessType(type); ProcessTypeMembers(type); } catch (Exception ex) { _errorReporter.Region = type.Region; _errorReporter.InternalError(ex, "Error importing type " + type.FullName); } } public void ReserveMemberName(ITypeDefinition type, string name, bool isStatic) { HashSet<string> names; if (!isStatic) { if (!_instanceMemberNamesByType.TryGetValue(type, out names)) _instanceMemberNamesByType[type] = names = new HashSet<string>(); } else { if (!_staticMemberNamesByType.TryGetValue(type, out names)) _staticMemberNamesByType[type] = names = new HashSet<string>(); } names.Add(name); } public bool IsMemberNameAvailable(ITypeDefinition type, string name, bool isStatic) { if (isStatic) { if (_unusableStaticFieldNames.Contains(name)) return false; HashSet<string> names; if (!_staticMemberNamesByType.TryGetValue(type, out names)) return true; return !names.Contains(name); } else { if (_unusableInstanceFieldNames.Contains(name)) return false; if (type.DirectBaseTypes.Select(d => d.GetDefinition()).Any(t => !IsMemberNameAvailable(t, name, false))) return false; HashSet<string> names; if (!_instanceMemberNamesByType.TryGetValue(type, out names)) return true; return !names.Contains(name); } } public virtual void SetMethodSemantics(IMethod method, MethodScriptSemantics semantics) { _methodSemantics[method] = semantics; _ignoredMembers.Add(method); } public virtual void SetConstructorSemantics(IMethod method, ConstructorScriptSemantics semantics) { _constructorSemantics[method] = semantics; _ignoredMembers.Add(method); } public virtual void SetPropertySemantics(IProperty property, PropertyScriptSemantics semantics) { _propertySemantics[property] = semantics; _ignoredMembers.Add(property); } public virtual void SetFieldSemantics(IField field, FieldScriptSemantics semantics) { _fieldSemantics[field] = semantics; _ignoredMembers.Add(field); } public virtual void SetEventSemantics(IEvent evt,EventScriptSemantics semantics) { _eventSemantics[evt] = semantics; _ignoredMembers.Add(evt); } private TypeSemantics GetTypeSemanticsInternal(ITypeDefinition typeDefinition) { TypeSemantics ts; if (_typeSemantics.TryGetValue(typeDefinition, out ts)) return ts; throw new ArgumentException(string.Format("Type semantics for type {0} were not correctly imported", typeDefinition.FullName)); } public TypeScriptSemantics GetTypeSemantics(ITypeDefinition typeDefinition) { if (typeDefinition.Kind == TypeKind.Delegate) return TypeScriptSemantics.NormalType("Function"); else if (typeDefinition.Kind == TypeKind.Array) return TypeScriptSemantics.NormalType("Array"); return GetTypeSemanticsInternal(typeDefinition).Semantics; } public MethodScriptSemantics GetMethodSemantics(IMethod method) { switch (method.DeclaringType.Kind) { case TypeKind.Delegate: return MethodScriptSemantics.NotUsableFromScript(); default: MethodScriptSemantics result; if (!_methodSemantics.TryGetValue((IMethod)method.MemberDefinition, out result)) throw new ArgumentException(string.Format("Semantics for method " + method + " were not imported")); return result; } } public ConstructorScriptSemantics GetConstructorSemantics(IMethod method) { switch (method.DeclaringType.Kind) { case TypeKind.Anonymous: return ConstructorScriptSemantics.Json(new IMember[0]); case TypeKind.Delegate: return ConstructorScriptSemantics.NotUsableFromScript(); default: ConstructorScriptSemantics result; if (!_constructorSemantics.TryGetValue((IMethod)method.MemberDefinition, out result)) throw new ArgumentException(string.Format("Semantics for constructor " + method + " were not imported")); return result; } } public PropertyScriptSemantics GetPropertySemantics(IProperty property) { switch (property.DeclaringType.Kind) { case TypeKind.Anonymous: return PropertyScriptSemantics.Field(property.Name.Replace("<>", "$")); case TypeKind.Delegate: return PropertyScriptSemantics.NotUsableFromScript(); default: PropertyScriptSemantics result; if (!_propertySemantics.TryGetValue((IProperty)property.MemberDefinition, out result)) throw new ArgumentException(string.Format("Semantics for property " + property + " were not imported")); return result; } } public DelegateScriptSemantics GetDelegateSemantics(ITypeDefinition delegateType) { DelegateScriptSemantics result; if (!_delegateSemantics.TryGetValue(delegateType, out result)) throw new ArgumentException(string.Format("Semantics for delegate " + delegateType + " were not imported")); return result; } private string GetBackingFieldName(ITypeDefinition declaringTypeDefinition, string memberName) { int inheritanceDepth = declaringTypeDefinition.GetAllBaseTypes().Count(b => b.Kind != TypeKind.Interface) - 1; if (_minimizeNames) { int count; _backingFieldCountPerType.TryGetValue(declaringTypeDefinition, out count); count++; _backingFieldCountPerType[declaringTypeDefinition] = count; return string.Format(CultureInfo.InvariantCulture, "${0}${1}", inheritanceDepth, count); } else { return string.Format(CultureInfo.InvariantCulture, "${0}${1}Field", inheritanceDepth, memberName); } } public string GetAutoPropertyBackingFieldName(IProperty property) { property = (IProperty)property.MemberDefinition; string result; if (_propertyBackingFieldNames.TryGetValue(property, out result)) return result; result = GetBackingFieldName(property.DeclaringTypeDefinition, property.Name); _propertyBackingFieldNames[property] = result; return result; } public FieldScriptSemantics GetFieldSemantics(IField field) { switch (field.DeclaringType.Kind) { case TypeKind.Delegate: return FieldScriptSemantics.NotUsableFromScript(); default: FieldScriptSemantics result; if (!_fieldSemantics.TryGetValue((IField)field.MemberDefinition, out result)) throw new ArgumentException(string.Format("Semantics for field " + field + " were not imported")); return result; } } public EventScriptSemantics GetEventSemantics(IEvent evt) { switch (evt.DeclaringType.Kind) { case TypeKind.Delegate: return EventScriptSemantics.NotUsableFromScript(); default: EventScriptSemantics result; if (!_eventSemantics.TryGetValue((IEvent)evt.MemberDefinition, out result)) throw new ArgumentException(string.Format("Semantics for field " + evt + " were not imported")); return result; } } public string GetAutoEventBackingFieldName(IEvent evt) { evt = (IEvent)evt.MemberDefinition; string result; if (_eventBackingFieldNames.TryGetValue(evt, out result)) return result; result = GetBackingFieldName(evt.DeclaringTypeDefinition, evt.Name); _eventBackingFieldNames[evt] = result; return result; } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using System.Diagnostics; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Caching; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Primitives; using osu.Framework.Graphics.Shaders; using osu.Framework.Graphics.Textures; using osu.Framework.Graphics.UserInterface; using osu.Framework.IO.Stores; using osu.Framework.Localisation; using osu.Framework.MathUtils; using osuTK; using osuTK.Graphics; namespace osu.Framework.Graphics.Sprites { /// <summary> /// A container for simple text rendering purposes. If more complex text rendering is required, use <see cref="TextFlowContainer"/> instead. /// </summary> public partial class SpriteText : Drawable, IHasLineBaseHeight, IHasText, IHasFilterTerms, IFillFlowContainer, IHasCurrentValue<string> { private const float default_text_size = 20; private static readonly Vector2 shadow_offset = new Vector2(0, 0.06f); [Resolved] private FontStore store { get; set; } [Resolved] private LocalisationManager localisation { get; set; } private ILocalisedBindableString localisedText; private float spaceWidth; private IShader textureShader; private IShader roundedTextureShader; public SpriteText() { current.BindValueChanged(text => Text = text.NewValue); } [BackgroundDependencyLoader] private void load(ShaderManager shaders) { localisedText = localisation.GetLocalisedString(text); localisedText.BindValueChanged(str => { if (string.IsNullOrEmpty(str.NewValue)) { // We'll become not present and won't update the characters to set the size to 0, so do it manually if (requiresAutoSizedWidth) base.Width = Padding.TotalHorizontal; if (requiresAutoSizedHeight) base.Height = Padding.TotalVertical; } invalidate(true); }, true); spaceWidth = getTextureForCharacter('.')?.DisplayWidth * 2 ?? 1; textureShader = shaders.Load(VertexShaderDescriptor.TEXTURE_2, FragmentShaderDescriptor.TEXTURE); roundedTextureShader = shaders.Load(VertexShaderDescriptor.TEXTURE_2, FragmentShaderDescriptor.TEXTURE_ROUNDED); // Pre-cache the characters in the texture store foreach (var character in displayedText) getTextureForCharacter(character); } private LocalisedString text = string.Empty; /// <summary> /// Gets or sets the text to be displayed. /// </summary> public LocalisedString Text { get => text; set { if (text == value) return; text = value; current.Value = text; if (localisedText != null) localisedText.Text = value; } } private readonly Bindable<string> current = new Bindable<string>(string.Empty); public Bindable<string> Current { get => current; set { if (value == null) throw new ArgumentNullException(nameof(value)); current.UnbindBindings(); current.BindTo(value); } } private string displayedText => localisedText?.Value ?? text.Text.Original; string IHasText.Text { get => Text; set => Text = value; } private FontUsage font = FontUsage.Default; /// <summary> /// Contains information on the font used to display the text. /// </summary> public FontUsage Font { get => font; set { // The implicit operator can be used to convert strings to fonts, which discards size + fixedwidth in doing so // For the time being, we'll forward those members from the original value // Todo: Remove this along with all other obsolete members if (value.Legacy) value = new FontUsage(value.Family, font.Size, value.Weight, value.Italics, font.FixedWidth); font = value; invalidate(true); shadowOffsetCache.Invalidate(); } } /// <summary> /// The size of the text in local space. This means that if TextSize is set to 16, a single line will have a height of 16. /// </summary> [Obsolete("Setting TextSize directly is deprecated. Use `Font = text.Font.With(size: value)` (see: https://github.com/ppy/osu-framework/pull/2043)")] public float TextSize { get => Font.Size; set => Font = Font.With(size: value); } /// <summary> /// True if all characters should be spaced apart the same distance. /// </summary> [Obsolete("Setting FixedWidth directly is deprecated. Use `Font = text.Font.With(fixedWidth: value)` (see: https://github.com/ppy/osu-framework/pull/2043)")] public bool FixedWidth { get => Font.FixedWidth; set => Font = Font.With(fixedWidth: value); } private bool allowMultiline = true; /// <summary> /// True if the text should be wrapped if it gets too wide. Note that \n does NOT cause a line break. If you need explicit line breaks, use <see cref="TextFlowContainer"/> instead. /// </summary> public bool AllowMultiline { get => allowMultiline; set { if (allowMultiline == value) return; allowMultiline = value; invalidate(true); } } private bool shadow; /// <summary> /// True if a shadow should be displayed around the text. /// </summary> public bool Shadow { get => shadow; set { if (shadow == value) return; shadow = value; Invalidate(Invalidation.DrawNode); } } private Color4 shadowColour = new Color4(0, 0, 0, 0.2f); /// <summary> /// The colour of the shadow displayed around the text. A shadow will only be displayed if the <see cref="Shadow"/> property is set to true. /// </summary> public Color4 ShadowColour { get => shadowColour; set { if (shadowColour == value) return; shadowColour = value; Invalidate(Invalidation.DrawNode); } } private bool useFullGlyphHeight = true; /// <summary> /// True if the <see cref="SpriteText"/>'s vertical size should be equal to <see cref="FontUsage.Size"/> (the full height) or precisely the size of used characters. /// Set to false to allow better centering of individual characters/numerals/etc. /// </summary> public bool UseFullGlyphHeight { get => useFullGlyphHeight; set { if (useFullGlyphHeight == value) return; useFullGlyphHeight = value; invalidate(true); } } private bool requiresAutoSizedWidth => explicitWidth == null && (RelativeSizeAxes & Axes.X) == 0; private bool requiresAutoSizedHeight => explicitHeight == null && (RelativeSizeAxes & Axes.Y) == 0; private float? explicitWidth; /// <summary> /// Gets or sets the width of this <see cref="SpriteText"/>. The <see cref="SpriteText"/> will maintain this width when set. /// </summary> public override float Width { get { if (requiresAutoSizedWidth) computeCharacters(); return base.Width; } set { if (explicitWidth == value) return; base.Width = value; explicitWidth = value; invalidate(true); } } private float? explicitHeight; /// <summary> /// Gets or sets the height of this <see cref="SpriteText"/>. The <see cref="SpriteText"/> will maintain this height when set. /// </summary> public override float Height { get { if (requiresAutoSizedHeight) computeCharacters(); return base.Height; } set { if (explicitHeight == value) return; base.Height = value; explicitHeight = value; invalidate(true); } } /// <summary> /// Gets or sets the size of this <see cref="SpriteText"/>. The <see cref="SpriteText"/> will maintain this size when set. /// </summary> public override Vector2 Size { get { if (requiresAutoSizedWidth || requiresAutoSizedHeight) computeCharacters(); return base.Size; } set { Width = value.X; Height = value.Y; } } private Vector2 spacing; /// <summary> /// Gets or sets the spacing between characters of this <see cref="SpriteText"/>. /// </summary> public Vector2 Spacing { get => spacing; set { if (spacing == value) return; spacing = value; invalidate(true); } } private MarginPadding padding; /// <summary> /// Shrinks the space which may be occupied by characters of this <see cref="SpriteText"/> by the specified amount on each side. /// </summary> public MarginPadding Padding { get => padding; set { if (padding.Equals(value)) return; if (!Validation.IsFinite(value)) throw new ArgumentException($@"{nameof(Padding)} must be finite, but is {value}."); padding = value; invalidate(true); } } public override bool IsPresent => base.IsPresent && (AlwaysPresent || !string.IsNullOrEmpty(displayedText)); #region Characters private Cached charactersCache = new Cached(); private readonly List<CharacterPart> charactersBacking = new List<CharacterPart>(); /// <summary> /// The characters in local space. /// </summary> private List<CharacterPart> characters { get { computeCharacters(); return charactersBacking; } } private bool isComputingCharacters; private void computeCharacters() { if (store == null) return; if (charactersCache.IsValid) return; charactersBacking.Clear(); Debug.Assert(!isComputingCharacters, "Cyclic invocation of computeCharacters()!"); isComputingCharacters = true; Vector2 currentPos = new Vector2(Padding.Left, Padding.Top); try { if (string.IsNullOrEmpty(displayedText)) return; float maxWidth = float.PositiveInfinity; if (!requiresAutoSizedWidth) maxWidth = ApplyRelativeAxes(RelativeSizeAxes, new Vector2(base.Width, base.Height), FillMode).X - Padding.Right; float currentRowHeight = 0; foreach (var character in displayedText) { bool useFixedWidth = Font.FixedWidth && UseFixedWidthForCharacter(character); // Unscaled size (i.e. not multiplied by Font.Size) Vector2 textureSize; Texture texture = null; // Retrieve the texture + size if (char.IsWhiteSpace(character)) { float size = useFixedWidth ? constantWidth : spaceWidth; if (character == 0x3000) { // Double-width space size *= 2; } textureSize = new Vector2(size); } else { texture = getTextureForCharacter(character); textureSize = texture == null ? new Vector2(useFixedWidth ? constantWidth : spaceWidth) : new Vector2(texture.DisplayWidth, texture.DisplayHeight); } // Scaled glyph size to be used for positioning Vector2 glyphSize = new Vector2(useFixedWidth ? constantWidth : textureSize.X, UseFullGlyphHeight ? 1 : textureSize.Y) * Font.Size; // Texture size scaled by Font.Size Vector2 scaledTextureSize = textureSize * Font.Size; // Check if we need to go onto the next line if (AllowMultiline && currentPos.X + glyphSize.X >= maxWidth) { currentPos.X = Padding.Left; currentPos.Y += currentRowHeight + spacing.Y; currentRowHeight = 0; } // The height of the row depends on whether we want to use the full glyph height or not currentRowHeight = Math.Max(currentRowHeight, glyphSize.Y); if (!char.IsWhiteSpace(character) && texture != null) { // If we have fixed width, we'll need to centre the texture to the glyph size float offset = (glyphSize.X - scaledTextureSize.X) / 2; charactersBacking.Add(new CharacterPart { Texture = texture, DrawRectangle = new RectangleF(new Vector2(currentPos.X + offset, currentPos.Y), scaledTextureSize), }); } currentPos.X += glyphSize.X + spacing.X; } // When we added the last character, we also added the spacing, but we should remove it to get the correct size currentPos.X -= spacing.X; // The last row needs to be included in the height currentPos.Y += currentRowHeight; } finally { if (requiresAutoSizedWidth) base.Width = currentPos.X + Padding.Right; if (requiresAutoSizedHeight) base.Height = currentPos.Y + Padding.Bottom; isComputingCharacters = false; charactersCache.Validate(); } } private Cached screenSpaceCharactersCache = new Cached(); private readonly List<ScreenSpaceCharacterPart> screenSpaceCharactersBacking = new List<ScreenSpaceCharacterPart>(); /// <summary> /// The characters in screen space. These are ready to be drawn. /// </summary> private List<ScreenSpaceCharacterPart> screenSpaceCharacters { get { computeScreenSpaceCharacters(); return screenSpaceCharactersBacking; } } private void computeScreenSpaceCharacters() { if (screenSpaceCharactersCache.IsValid) return; screenSpaceCharactersBacking.Clear(); foreach (var character in characters) { screenSpaceCharactersBacking.Add(new ScreenSpaceCharacterPart { DrawQuad = ToScreenSpace(character.DrawRectangle), Texture = character.Texture }); } screenSpaceCharactersCache.Validate(); } private Cached<float> constantWidthCache; private float constantWidth => constantWidthCache.IsValid ? constantWidthCache.Value : constantWidthCache.Value = getTextureForCharacter('D')?.DisplayWidth ?? 0; private Cached<Vector2> shadowOffsetCache; private Vector2 shadowOffset => shadowOffsetCache.IsValid ? shadowOffsetCache.Value : shadowOffsetCache.Value = ToScreenSpace(shadow_offset * Font.Size) - ToScreenSpace(Vector2.Zero); #endregion #region Invalidation private void invalidate(bool layout = false) { if (layout) charactersCache.Invalidate(); screenSpaceCharactersCache.Invalidate(); Invalidate(Invalidation.DrawNode, shallPropagate: false); } public override bool Invalidate(Invalidation invalidation = Invalidation.All, Drawable source = null, bool shallPropagate = true) { base.Invalidate(invalidation, source, shallPropagate); if (source == Parent) { // Colour captures presence changes if ((invalidation & (Invalidation.DrawSize | Invalidation.Presence)) > 0) invalidate(true); if ((invalidation & Invalidation.DrawInfo) > 0) { invalidate(); shadowOffsetCache.Invalidate(); } } else if ((invalidation & Invalidation.MiscGeometry) > 0) invalidate(); return true; } #endregion #region DrawNode protected override DrawNode CreateDrawNode() => new SpriteTextDrawNode(); protected override void ApplyDrawNode(DrawNode node) { base.ApplyDrawNode(node); var n = (SpriteTextDrawNode)node; n.Parts.Clear(); n.Parts.AddRange(screenSpaceCharacters); n.Shadow = Shadow; n.TextureShader = textureShader; n.RoundedTextureShader = roundedTextureShader; if (Shadow) { n.ShadowColour = ShadowColour; n.ShadowOffset = shadowOffset; } } #endregion private Texture getTextureForCharacter(char c) => GetTextureForCharacter(c) ?? GetFallbackTextureForCharacter(c); /// <summary> /// Gets the texture for the given character. /// </summary> /// <param name="c">The character to get the texture for.</param> /// <returns>The texture for the given character.</returns> protected virtual Texture GetTextureForCharacter(char c) { if (store == null) return null; return store.GetCharacter(Font.FontName, c) ?? store.GetCharacter(null, c); } /// <summary> /// Gets a <see cref="Texture"/> that represents a character which doesn't exist in the current font. /// </summary> /// <param name="c">The character which doesn't exist in the current font.</param> /// <returns>The texture for the given character.</returns> protected virtual Texture GetFallbackTextureForCharacter(char c) => GetTextureForCharacter('?'); /// <summary> /// Whether the visual representation of a character should use fixed width when <see cref="FontUsage.FixedWidth"/> is true. /// By default, this includes the following characters, commonly used in numerical formatting: '.' ',' ':' and ' ' /// </summary> /// <param name="c">The character.</param> /// <returns>Whether the visual representation of <paramref name="c"/> should use a fixed width.</returns> protected virtual bool UseFixedWidthForCharacter(char c) { switch (c) { case '.': case ',': case ':': case ' ': return false; } return true; } public override string ToString() { return $@"""{displayedText}"" " + base.ToString(); } /// <summary> /// Gets the base height of the font used by this text. If the font of this text is invalid, 0 is returned. /// </summary> public float LineBaseHeight { get { var baseHeight = store.GetBaseHeight(Font.FontName); if (baseHeight.HasValue) return baseHeight.Value * Font.Size; if (string.IsNullOrEmpty(displayedText)) return 0; return store.GetBaseHeight(displayedText[0]).GetValueOrDefault() * Font.Size; } } public IEnumerable<string> FilterTerms { get { yield return displayedText; } } } }
using System; using System.Collections.Generic; using System.Linq; using DotLiquid; using DotLiquid.Exceptions; using ArgumentException = System.ArgumentException; namespace jstp { public class JstpGenType : Drop { #region static static JstpGenType() { NullType = new JstpGenTypeNull("NULL", new JstpDescType {Type = JstpDescMetaType.Null}); BoolType = new JstpGenTypeBool("Bool", new JstpDescType { Type = JstpDescMetaType.Bool }); IntegerType = new JstpGenTypeInteger("Integer", new JstpDescType { Type = JstpDescMetaType.Integer, Min = long.MinValue, Max = long.MaxValue }); RealType = new JstpGenTypeReal("Real", new JstpDescType { Type = JstpDescMetaType.Real, Min = decimal.MinValue, Max = decimal.MaxValue }); StringType = new JstpGenTypeString("String", new JstpDescType { Type = JstpDescMetaType.String }); } public static JstpGenTypeNull NullType { get; private set; } public static JstpGenTypeBool BoolType { get; set; } public static JstpGenTypeInteger IntegerType { get; set; } public static JstpGenTypeReal RealType { get; set; } public static JstpGenTypeString StringType { get; set; } #endregion protected readonly JstpDescType JstpDescType; public JstpGenType(string name, JstpDescType jstpDescType) { JstpDescType = jstpDescType; Name = name; Title = jstpDescType.Title; Desc = jstpDescType.Desc; } internal virtual void Initialize(IDictionary<string, JstpGenType> types) { } public string Name { get; set; } public string Title { get; set; } public string Desc { get; set; } public JstpDescMetaType Type { get; set; } } public class JstpGenTypeInteger : JstpGenType { public JstpGenTypeInteger(string name, JstpDescType jstpDescType):base(name,jstpDescType) { Type = JstpDescMetaType.Integer; Min = long.MinValue; Max = long.MaxValue; } public long Max { get; set; } public long Min { get; set; } } public class JstpGenTypeReal : JstpGenType { public JstpGenTypeReal(string name, JstpDescType jstpDescType) : base(name, jstpDescType) { Type = JstpDescMetaType.Real; Min = double.MinValue; Max = double.MaxValue; } public double Max { get; set; } public double Min { get; set; } } public class JstpGenTypeString : JstpGenType { public JstpGenTypeString(string name, JstpDescType jstpDescType) : base(name, jstpDescType) { Type = JstpDescMetaType.String; MaxLength = int.MaxValue; } public int MaxLength { get; set; } } public class JstpGenTypeNull : JstpGenType { public JstpGenTypeNull(string name, JstpDescType jstpDescType) : base(name, jstpDescType) { Type = JstpDescMetaType.Null; } } public class JstpGenTypeBool : JstpGenType { public JstpGenTypeBool(string name, JstpDescType jstpDescType) : base(name, jstpDescType) { Type = JstpDescMetaType.Bool; } } public class JstpGenTypeObject : JstpGenType { public JstpGenTypeObject(string name, JstpDescType jstpDescType) : base(name, jstpDescType) { Type = JstpDescMetaType.Object; Properties = new List<JstpGenTypeProperty>(); } internal override void Initialize(IDictionary<string, JstpGenType> types) { base.Initialize(types); Properties = JstpDescType.Properties.Select(_ => new JstpGenTypeProperty(_.Key, _.Value,types)).ToList(); } public List<JstpGenTypeProperty> Properties { get; private set; } } public class JstpGenTypeProperty : Drop { private readonly JstpDescObjectItem _desc; private readonly IDictionary<string, JstpGenType> _types; private JstpGenType _type; public JstpGenTypeProperty(string name, JstpDescObjectItem desc, IDictionary<string, JstpGenType> types) { _desc = desc; _types = types; Name = name; if (!types.TryGetValue(desc.Type,out _type)) { throw new ArgumentException(string.Format("Type '{0}' not found", desc.Type)); } } public string Name { get; set; } public string Title { get { return _desc.Title; } } public string Desc { get { return _desc.Desc; } } public JstpGenType Type { get { return _type; } set { _type = value; } } } public class JstpGenTypeArray : JstpGenType { public JstpGenTypeArray(string name, JstpDescType jstpDescType) : base(name, jstpDescType) { Type = JstpDescMetaType.Array; } internal override void Initialize(IDictionary<string, JstpGenType> types) { Item = types[JstpDescType.Item]; } public JstpGenType Item { get; set; } } public class JstpGenTypeEnum : JstpGenType { public JstpGenTypeEnum(string name, JstpDescType jstpDescType) : base(name, jstpDescType) { Type = JstpDescMetaType.Enum; Items = jstpDescType.Items.Select(_ => new JstpGenTypeEnumItem(_.Key, _.Value)).ToList(); } public List<JstpGenTypeEnumItem> Items { get; private set; } } public class JstpGenTypeEnumItem:Drop { public JstpGenTypeEnumItem(string name, JstpDescEnumItem jstpDescEnumItem) { Name = name; Title = jstpDescEnumItem.Title; Desc = jstpDescEnumItem.Desc; } public string Name { get; set; } public string Title { get; set; } public string Desc { get; set; } } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using HBYW.Utils; namespace HBYW.Data { public class AngES2DataSource : IAngDataSource { ES2Data es2Data; ES2Settings settings; string fileDSN; string dSN; bool use_resources = false; public string DSN { get { return dSN; } set { dSN = value; } } public AngES2DataSource(string path, string table, bool create) { ////this is so we can load a file for editing that normally has .bytes appended to the end so it can be loaded from resources. Otherwise the filename comes out "filename.bytes.es2" or the like. //if (!table.Contains(AngDataSource.STR_DOT_BYTES)) //{ // table = table + "." + myDataSourceType.ToString(); //} DSN = table; settings = new ES2Settings(); use_resources = path.Contains(AngDS.TOKEN_RESOURCES); if (use_resources) { settings.saveLocation = ES2Settings.SaveLocation.Resources; fileDSN = table; } else { fileDSN = LocalPath.CombinePathsPrettily(path, table); } if (CheckDataSource()) { ImportDataSource(); } else { Debug.Log("AngES2DataSource: dsn path does not exist - " + fileDSN); } } public bool CheckDataSource() { if (ES2.Exists(fileDSN, settings)) return true; else AngLog.Severe("ES2 datasource not found: " + fileDSN); return false; } public string[] GetProperties() { string[] props = es2Data.GetTags(); return props; } public bool PropertyExists(string property) { return es2Data.TagExists(property); } public void CommitDS() { AngLog.ImplementMessage("AngES2DataSource", "Commit", "Should use ES2Writer to do all writes at once?"); } public void DeleteDataSource() { ES2.Delete(fileDSN); } public bool ImportDataSource() { es2Data = ES2.LoadAll(fileDSN, settings); if (es2Data.loadedData.Count > 0) return true; return false; } public void Save(string property, Vector3 value) { string path = fileDSN + "?tag=" + property; ES2.Save<Vector3>(value, path, settings); } public void Save(string property, Vector2 value) { string path = fileDSN + "?tag=" + property; ES2.Save<Vector2>(value, path, settings); } public void Save(string property, bool value) { string path = fileDSN + "?tag=" + property; ES2.Save<bool>(value, path, settings); } public void Save(string property, float value) { string path = fileDSN + "?tag=" + property; ES2.Save<float>(value, path, settings); } public void Save(string property, int value) { string path = fileDSN + "?tag=" + property; ES2.Save<int>(value, path, settings); } public void Save(string property, string value) { string path = fileDSN + "?tag=" + property; ES2.Save<string>(value, path, settings); } public void Save(string property, Transform value) { string path = fileDSN + "?tag=" + property; ES2.Save<Transform>(value, path, settings); } public void Save(string property, string[] value) { string path = fileDSN + "?tag=" + property; ES2.Save<string>(value, path, settings); } public void Save(string property, Color value) { string path = fileDSN + "?tag=" + property; ES2.Save<Color>(value, path, settings); } public void Save (string property, LayerMask value) { string path = fileDSN + "?tag=" + property; ES2.Save<LayerMask>(value, path, settings); } public void Save(string property, Dictionary<string, string> value) { string path = fileDSN + "?tag=" + property; ES2.Save<Dictionary<string, string>>(value, path, settings); } public int LoadInt(string property) { return Load<int>(property); } public float LoadFloat(string property) { return Load<float>(property); } public bool LoadBool(string property) { return Load<bool>(property); } public string LoadString(string property) { return Load<string>(property); } public string[] LoadStringArr(string property) { return LoadArray<string>(property); } public Vector3 LoadVector3(string property) { return Load<Vector3>(property); } public Vector2 LoadVector2(string property) { return Load<Vector2>(property); } public void LoadTransform(string property, Transform t) { t = Load<Transform>(property); } public Color LoadColor(string property) { return Load<Color>(property); } public LayerMask LoadLayerMask(string property) { return Load<LayerMask>(property); } public T Load<T>(string property) { if (es2Data.TagExists(property)) return es2Data.Load<T>(property); return default(T); } public T[] LoadArray<T>(string property) { //string path = fullDSN + "?tag=" + property; if (es2Data.TagExists(property)) return es2Data.LoadArray<T>(property); return default(T[]); } public void LoadDictionary(string property, out Dictionary<string, string> dict) { if (es2Data.TagExists(property)) dict = ES2.LoadDictionary<string, string>(property); else { dict = null; AngLog.Severe("ES2 could not find property: " + property); } } public HashSet<T> LoadHashSet<T>(string property) { if (es2Data.TagExists(property)) return es2Data.LoadHashSet<T>(property); else AngLog.Severe("ES2 could not find property: " + property); return null; } //this might be a problem according to the docs. said you can't self-assign components and we have to keep them in a diff file...not sure why the diff file. public void Load(string property, UnityEngine.Component component) { string path = fileDSN + "?tag=" + property; if (ES2.Exists(path, settings)) ES2.Load<UnityEngine.Component>(path, component, settings); else AngLog.Severe("ES2 could not find path: " + path); } } }
//----------------------------------------------------------------------- // <copyright file="InstantPreviewInput.cs" company="Google LLC"> // // Copyright 2017 Google LLC. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // </copyright> //----------------------------------------------------------------------- namespace GoogleARCore { using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; using GoogleARCoreInternal; using UnityEngine; /// <summary> /// Helper class that provides touch input in lieu of Input.GetTouch when /// running the Unity Editor. /// </summary> public static class InstantPreviewInput { private static Touch[] s_Touches = new Touch[0]; private static List<Touch> s_TouchList = new List<Touch>(); /// <summary> /// Gets the inputString from Instant Preview since the last update. /// </summary> [SuppressMessage("UnityRules.UnityStyleRules", "US1000:FieldsMustBeUpperCamelCase", Justification = "Overridden field.")] public static string inputString { get { return Input.inputString; } } /// <summary> /// Gets the available touch inputs from Instant Preview since the last /// update. /// </summary> [SuppressMessage("UnityRules.UnityStyleRules", "US1000:FieldsMustBeUpperCamelCase", Justification = "Overridden field.")] public static Touch[] touches { get { NativeApi.UnityGotTouches(); return s_Touches; } } /// <summary> /// Gets the number of touches available from Instant preview since the /// last update. /// </summary> [SuppressMessage("UnityRules.UnityStyleRules", "US1000:FieldsMustBeUpperCamelCase", Justification = "Overridden field.")] public static int touchCount { get { return touches.Length; } } /// <summary> /// Gets return value of Input.mousePosition. /// </summary> [SuppressMessage("UnityRules.UnityStyleRules", "US1000:FieldsMustBeUpperCamelCase", Justification = "Overridden field.")] public static Vector3 mousePosition { get { return Input.mousePosition; } } /// <summary> /// Gets a value indicating whether a mouse device is detected. /// </summary> [SuppressMessage("UnityRules.UnityStyleRules", "US1000:FieldsMustBeUpperCamelCase", Justification = "Overridden field.")] public static bool mousePresent { get { return Input.mousePresent; } } /// <summary> /// Gets a specific touch input from Instant Preview by index. /// </summary> /// <param name="index">Index of touch input to get.</param> /// <returns>Touch data.</returns> public static Touch GetTouch(int index) { return touches[index]; } /// <summary> /// Passthrough function to Input.GetKey. /// </summary> /// <param name="keyCode">Key parameter to pass to Input.GetKey.</param> /// <returns>Key state returned from Input.GetKey.</returns> public static bool GetKey(KeyCode keyCode) { return Input.GetKey(keyCode); } /// <summary> /// Passthrough function to Input.GetMouseButton. /// </summary> /// <param name="button">Button index.</param> /// <returns>Return value of Input.GetMouseButton.</returns> public static bool GetMouseButton(int button) { return Input.GetMouseButton(button); } /// <summary> /// Passthrough function to Input.GetMouseButtonDown. /// </summary> /// <param name="button">Button index.</param> /// <returns>Return value of Input.GetMouseButtonDown.</returns> public static bool GetMouseButtonDown(int button) { return Input.GetMouseButtonDown(button); } /// <summary> /// Passthrough function to Input.GetMouseButtonUp. /// </summary> /// <param name="button">Button index.</param> /// <returns>Return value of Input.GetMouseButtonUp.</returns> public static bool GetMouseButtonUp(int button) { return Input.GetMouseButtonUp(button); } /// <summary> /// Refreshes touch inputs from Instant Preview to reflect the state /// since the last time Update was called. /// </summary> public static void Update() { if (!InstantPreviewManager.IsProvidingPlatform) { return; } // Removes ended touches, and converts moves to stationary. for (int i = 0; i < s_TouchList.Count; ++i) { if (s_TouchList[i].phase == TouchPhase.Ended) { s_TouchList.RemoveAt(i); --i; continue; } var curTouch = s_TouchList[i]; curTouch.phase = TouchPhase.Stationary; curTouch.deltaPosition = Vector2.zero; s_TouchList[i] = curTouch; } // Updates touches. IntPtr nativeTouchesPtr; int nativeTouchCount; NativeApi.GetTouches(out nativeTouchesPtr, out nativeTouchCount); var structSize = Marshal.SizeOf(typeof(NativeTouch)); for (var i = 0; i < nativeTouchCount; ++i) { var source = new IntPtr(nativeTouchesPtr.ToInt64() + (i * structSize)); NativeTouch nativeTouch = (NativeTouch)Marshal.PtrToStructure(source, typeof(NativeTouch)); var newTouch = new Touch() { fingerId = nativeTouch.Id, phase = nativeTouch.Phase, pressure = nativeTouch.Pressure, // NativeTouch values are normalized and must be converted to screen // coordinates. // Note that the Unity's screen coordinate (0, 0) starts from bottom left. position = new Vector2( Screen.width * nativeTouch.X, Screen.height * (1f - nativeTouch.Y)), }; var index = s_TouchList.FindIndex(touch => touch.fingerId == newTouch.fingerId); // Adds touch if not found, otherwise updates it. if (index < 0) { s_TouchList.Add(newTouch); } else { var prevTouch = s_TouchList[index]; newTouch.deltaPosition += newTouch.position - prevTouch.position; s_TouchList[index] = newTouch; } } s_Touches = s_TouchList.ToArray(); } private struct NativeTouch { #pragma warning disable 649 public TouchPhase Phase; public float X; public float Y; public float Pressure; public int Id; #pragma warning restore 649 } private struct NativeApi { [DllImport(InstantPreviewManager.InstantPreviewNativeApi)] public static extern void GetTouches(out IntPtr touches, out int count); [DllImport(InstantPreviewManager.InstantPreviewNativeApi)] public static extern void UnityGotTouches(); } } }
// // <copyright file="Configuration.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Globalization; using System.Configuration; using System.Collections.Specialized; using System.Runtime.InteropServices; using Microsoft.WindowsAzure.ServiceRuntime; using Microsoft.WindowsAzure.StorageClient; using Microsoft.WindowsAzure; [assembly: CLSCompliant(true)] namespace Microsoft.Samples.ServiceHosting.AspProviders { internal static class Configuration { internal const string CSConfigStringPrefix = "CSConfigName"; internal const string DefaultMembershipTableNameConfigurationString = "DefaultMembershipTableName"; internal const string DefaultRoleTableNameConfigurationString = "DefaultRoleTableName"; internal const string DefaultSessionTableNameConfigurationString = "DefaultSessionTableName"; internal const string DefaultSessionContainerNameConfigurationString = "DefaultSessionContainerName"; internal const string DefaultProfileContainerNameConfigurationString = "DefaultProfileContainerName"; internal const string DefaultProviderApplicationNameConfigurationString = "DefaultProviderApplicationName"; internal const string DefaultMembershipTableName = "Membership"; internal const string DefaultRoleTableName = "Roles"; internal const string DefaultSessionTableName = "Sessions"; internal const string DefaultSessionContainerName = "sessionprovidercontainer"; internal const string DefaultProfileContainerName = "profileprovidercontainer"; internal const string DefaultProviderApplicationName = "appname"; //internal static readonly string DefaultTableStorageEndpointConfigurationString = "TableStorageEndpoint"; //internal static readonly string DefaultAccountNameConfigurationString = "AccountName"; //internal static readonly string DefaultAccountSharedKeyConfigurationString = "AccountSharedKey"; //internal static readonly string DefaultBlobStorageEndpointConfigurationString = "BlobStorageEndpoint"; internal static readonly string DefaultStorageConfigurationString = "DataConnectionString"; internal static readonly DateTime MinSupportedDateTime = DateTime.FromFileTime(0).ToUniversalTime().AddYears(200); internal static readonly int MaxStringPropertySizeInBytes = 64 * 1024; internal static readonly int MaxStringPropertySizeInChars = MaxStringPropertySizeInBytes / 2; internal static CloudStorageAccount GetStorageAccount(string settingName) { try { var rdr = new System.Configuration.AppSettingsReader(); var accountName = (string)rdr.GetValue("MetadataStorageAccountName", typeof(string)); var key = (string)rdr.GetValue("MetadataStorageKey", typeof(string)); //return new CloudStorageAccount(new StorageCredentialsAccountAndKey("storageaismediaservice3", "kATzafnzs0bG3CzAw0FnYv6Cgs4uV4qjXMuT88OmLq5C2FZ2t5G9J57MvhPwAfQI+e0U+hVK+xx7XTut1gGgbQ=="), true); return new CloudStorageAccount(new StorageCredentialsAccountAndKey(accountName, key), true); //return CloudStorageAccount.FromConfigurationSetting(settingName); } catch (InvalidOperationException) { //CloudStorageAccount.SetConfigurationSettingPublisher((configName, configSetter) => //{ // string value = ConfigurationManager.AppSettings[configName]; // if (RoleEnvironment.IsAvailable) // { // value = RoleEnvironment.GetConfigurationSettingValue(configName); // } // configSetter(value); //}); //return CloudStorageAccount.FromConfigurationSetting(settingName); return null; } } internal static string GetConfigurationSetting(string configurationString, string defaultValue) { return GetConfigurationSetting(configurationString, defaultValue, false); } /// <summary> /// Gets a configuration setting from application settings in the Web.config or App.config file. /// When running in a hosted environment, configuration settings are read from the settings specified in /// .cscfg files (i.e., the settings are read from the fabrics configuration system). /// </summary> internal static string GetConfigurationSetting(string configurationString, string defaultValue, bool throwIfNull) { if (string.IsNullOrEmpty(configurationString)) { throw new ArgumentException("The parameter configurationString cannot be null or empty."); } string ret = null; // first, try to read from appsettings ret = TryGetAppSetting(configurationString); // settings in the csc file overload settings in Web.config //if (RoleEnvironment.IsAvailable) { string cscRet = TryGetConfigurationSetting(configurationString); if (!string.IsNullOrEmpty(cscRet)) { ret = cscRet; } // if there is a csc config name in the app settings, this config name even overloads the // setting we have right now string refWebRet = TryGetAppSetting(CSConfigStringPrefix + configurationString); if (!string.IsNullOrEmpty(refWebRet)) { cscRet = TryGetConfigurationSetting(refWebRet); if (!string.IsNullOrEmpty(cscRet)) { ret = cscRet; } } } // if we could not retrieve any configuration string set return value to the default value if (string.IsNullOrEmpty(ret) && defaultValue != null) { ret = defaultValue; } if (string.IsNullOrEmpty(ret) && throwIfNull) { throw new ConfigurationErrorsException(string.Format(CultureInfo.InstalledUICulture, "Cannot find configuration string {0}.", configurationString)); } return ret; } internal static string GetConfigurationSettingFromNameValueCollection(NameValueCollection config, string valueName) { if (config == null) { throw new ArgumentNullException("config"); } if (valueName == null) { throw new ArgumentNullException("valueName"); } string sValue = config[valueName]; //if (RoleEnvironment.IsAvailable) { // settings in the hosting configuration are stronger than settings in app config string cscRet = TryGetConfigurationSetting(valueName); if (!string.IsNullOrEmpty(cscRet)) { sValue = cscRet; } // if there is a csc config name in the app settings, this config name even overloads the // setting we have right now string refWebRet = config[CSConfigStringPrefix + valueName]; if (!string.IsNullOrEmpty(refWebRet)) { cscRet = TryGetConfigurationSetting(refWebRet); if (!string.IsNullOrEmpty(cscRet)) { sValue = cscRet; } } } return sValue; } internal static bool GetBooleanValue(NameValueCollection config, string valueName, bool defaultValue) { string sValue = GetConfigurationSettingFromNameValueCollection(config, valueName); if (string.IsNullOrEmpty(sValue)) { return defaultValue; } bool result; if (bool.TryParse(sValue, out result)) { return result; } else { throw new ConfigurationErrorsException(string.Format(CultureInfo.InstalledUICulture, "The value must be boolean (true or false) for property '{0}'.", valueName)); } } internal static int GetIntValue(NameValueCollection config, string valueName, int defaultValue, bool zeroAllowed, int maxValueAllowed) { string sValue = GetConfigurationSettingFromNameValueCollection(config, valueName); if (string.IsNullOrEmpty(sValue)) { return defaultValue; } int iValue; if (!Int32.TryParse(sValue, out iValue)) { if (zeroAllowed) { throw new ConfigurationErrorsException(string.Format(CultureInfo.InstalledUICulture, "The value must be a non-negative 32-bit integer for property '{0}'.", valueName)); } throw new ConfigurationErrorsException(string.Format(CultureInfo.InstalledUICulture, "The value must be a positive 32-bit integer for property '{0}'.", valueName)); } if (zeroAllowed && iValue < 0) { throw new ConfigurationErrorsException(string.Format(CultureInfo.InstalledUICulture, "The value must be a non-negative 32-bit integer for property '{0}'.", valueName)); } if (!zeroAllowed && iValue <= 0) { throw new ConfigurationErrorsException(string.Format(CultureInfo.InstalledUICulture, "The value must be a positive 32-bit integer for property '{0}'.", valueName)); } if (maxValueAllowed > 0 && iValue > maxValueAllowed) { throw new ConfigurationErrorsException(string.Format(CultureInfo.InstalledUICulture, "The value '{0}' can not be greater than '{1}'.", valueName, maxValueAllowed.ToString(CultureInfo.InstalledUICulture))); } return iValue; } internal static string GetStringValue(NameValueCollection config, string valueName, string defaultValue, bool nullAllowed) { string sValue = GetConfigurationSettingFromNameValueCollection(config, valueName); if (string.IsNullOrEmpty(sValue) && nullAllowed) { return null; } else if (string.IsNullOrEmpty(sValue) && defaultValue != null) { return defaultValue; } else if (string.IsNullOrEmpty(sValue)) { throw new ConfigurationErrorsException(string.Format(CultureInfo.InstalledUICulture, "The parameter '{0}' must not be empty.", valueName)); } return sValue; } internal static string GetStringValueWithGlobalDefault(NameValueCollection config, string valueName, string defaultConfigString, string defaultValue, bool nullAllowed) { string sValue = GetConfigurationSettingFromNameValueCollection(config, valueName); if (string.IsNullOrEmpty(sValue)) { sValue = GetConfigurationSetting(defaultConfigString, null); } if (string.IsNullOrEmpty(sValue) && nullAllowed) { return null; } else if (string.IsNullOrEmpty(sValue) && defaultValue != null) { return defaultValue; } else if (string.IsNullOrEmpty(sValue)) { throw new ConfigurationErrorsException(string.Format(CultureInfo.InstalledUICulture, "The parameter '{0}' must not be empty.", valueName)); } return sValue; } internal static string GetInitExceptionDescription(StorageCredentials credentials, Uri tableBaseUri, Uri blobBaseUri) { StringBuilder builder = new StringBuilder(); builder.Append(GetInitExceptionDescription(credentials, tableBaseUri, "table storage configuration")); builder.Append(GetInitExceptionDescription(credentials, blobBaseUri, "blob storage configuration")); return builder.ToString(); } internal static string GetInitExceptionDescription(StorageCredentials info, Uri baseUri, string desc) { StringBuilder builder = new StringBuilder(); builder.Append("The reason for this exception is typically that the endpoints are not correctly configured. " + Environment.NewLine); if (info == null) { builder.Append("The current " + desc + " is null. Please specify a table endpoint!" + Environment.NewLine); } else { builder.Append("The current " + desc + " is: " + baseUri + Environment.NewLine); builder.Append("Please also make sure that the account name and the shared key are specified correctly. This information cannot be shown here because of security reasons."); } return builder.ToString(); } private static string TryGetConfigurationSetting(string configName) { string ret = null; try { //ret = RoleEnvironment.GetConfigurationSettingValue(configName); } //catch (RoleEnvironmentException) catch (Exception) { return null; } return ret; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Make sure that no error condition prevents environment from reading service configuration.")] internal static string TryGetAppSetting(string configName) { string ret = null; try { ret = ConfigurationManager.AppSettings[configName]; } // some exception happened when accessing the app settings section // most likely this is because there is no app setting file // this is not an error because configuration settings can also be located in the cscfg file, and explicitly // all exceptions are captured here catch (Exception) { return null; } return ret; } } }
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved. // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. using IdentityServer4.Models; using IdentityServer4.Stores; using Microsoft.Extensions.Logging; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace IdentityServer4.Validation { /// <summary> /// Validates scopes /// </summary> public class ScopeValidator { private readonly ILogger _logger; private readonly IResourceStore _store; /// <summary> /// Gets a value indicating whether this instance contains identity scopes /// </summary> /// <value> /// <c>true</c> if it contains identity scopes; otherwise, <c>false</c>. /// </value> public bool ContainsOpenIdScopes => GrantedResources.IdentityResources.Any(); /// <summary> /// Gets a value indicating whether this instance contains API scopes. /// </summary> /// <value> /// <c>true</c> if it contains API scopes; otherwise, <c>false</c>. /// </value> public bool ContainsApiResourceScopes => GrantedResources.ApiResources.Any(); /// <summary> /// Gets a value indicating whether this instance contains the offline access scope. /// </summary> /// <value> /// <c>true</c> if it contains the offline access scope; otherwise, <c>false</c>. /// </value> public bool ContainsOfflineAccessScope => GrantedResources.OfflineAccess; /// <summary> /// Gets the requested resources. /// </summary> /// <value> /// The requested resources. /// </value> public Resources RequestedResources { get; internal set; } = new Resources(); /// <summary> /// Gets the granted resources. /// </summary> /// <value> /// The granted resources. /// </value> public Resources GrantedResources { get; internal set; } = new Resources(); /// <summary> /// Initializes a new instance of the <see cref="ScopeValidator"/> class. /// </summary> /// <param name="store">The store.</param> /// <param name="logger">The logger.</param> public ScopeValidator(IResourceStore store, ILogger<ScopeValidator> logger) { _logger = logger; _store = store; } /// <summary> /// Validates the required scopes. /// </summary> /// <param name="consentedScopes">The consented scopes.</param> /// <returns></returns> public bool ValidateRequiredScopes(IEnumerable<string> consentedScopes) { var identity = RequestedResources.IdentityResources.Where(x => x.Required).Select(x=>x.Name); var apiQuery = from api in RequestedResources.ApiResources where api.Scopes != null from scope in api.Scopes where scope.Required select scope.Name; var requiredScopes = identity.Union(apiQuery); return requiredScopes.All(x => consentedScopes.Contains(x)); } /// <summary> /// Sets the consented scopes. /// </summary> /// <param name="consentedScopes">The consented scopes.</param> public void SetConsentedScopes(IEnumerable<string> consentedScopes) { consentedScopes = consentedScopes ?? Enumerable.Empty<string>(); var offline = consentedScopes.Contains(IdentityServerConstants.StandardScopes.OfflineAccess); if (offline) { consentedScopes = consentedScopes.Where(x => x != IdentityServerConstants.StandardScopes.OfflineAccess); } var identityToKeep = GrantedResources.IdentityResources.Where(x => x.Required || consentedScopes.Contains(x.Name)); var apisToKeep = from api in GrantedResources.ApiResources where api.Scopes != null let scopesToKeep = (from scope in api.Scopes where scope.Required == true || consentedScopes.Contains(scope.Name) select scope) where scopesToKeep.Any() select api.CloneWithScopes(scopesToKeep); GrantedResources = new Resources(identityToKeep, apisToKeep) { OfflineAccess = offline }; } /// <summary> /// Valides given scopes /// </summary> /// <param name="requestedScopes">The requested scopes.</param> /// <param name="filterIdentityScopes">if set to <c>true</c> [filter identity scopes].</param> /// <returns></returns> public async Task<bool> AreScopesValidAsync(IEnumerable<string> requestedScopes, bool filterIdentityScopes = false) { if (requestedScopes.Contains(IdentityServerConstants.StandardScopes.OfflineAccess)) { GrantedResources.OfflineAccess = true; requestedScopes = requestedScopes.Where(x => x != IdentityServerConstants.StandardScopes.OfflineAccess).ToArray(); if (!requestedScopes.Any()) { _logger.LogError("No identity or API scopes requested"); return false; } } var resources = await _store.FindResourcesByScopeAsync(requestedScopes); foreach (var requestedScope in requestedScopes) { var identity = resources.IdentityResources.FirstOrDefault(x => x.Name == requestedScope); if (identity != null) { if (identity.Enabled == false) { _logger.LogError("Scope disabled: {requestedScope}", requestedScope); return false; } if (!filterIdentityScopes) { GrantedResources.IdentityResources.Add(identity); } } else { var api = resources.FindApiResourceByScope(requestedScope); if (api == null) { _logger.LogError("Invalid scope: {requestedScope}", requestedScope); return false; } if (api.Enabled == false) { _logger.LogError("API {api} that contains scope is disabled: {requestedScope}", api.Name, requestedScope); return false; } var scope = api.FindApiScope(requestedScope); if (scope == null) { _logger.LogError("Invalid scope: {requestedScope}", requestedScope); return false; } // see if we already have this API in our list var existingApi = GrantedResources.ApiResources.FirstOrDefault(x => x.Name == api.Name); if (existingApi != null) { existingApi.Scopes.Add(scope); } else { GrantedResources.ApiResources.Add(api.CloneWithScopes(new[] { scope })); } } } RequestedResources = new Resources(GrantedResources.IdentityResources, GrantedResources.ApiResources) { OfflineAccess = GrantedResources.OfflineAccess }; return true; } /// <summary> /// Checks is scopes are allowed. /// </summary> /// <param name="client">The client.</param> /// <param name="requestedScopes">The requested scopes.</param> /// <returns></returns> public async Task<bool> AreScopesAllowedAsync(Client client, IEnumerable<string> requestedScopes) { if (requestedScopes.Contains(IdentityServerConstants.StandardScopes.OfflineAccess)) { if (client.AllowOfflineAccess == false) { _logger.LogError("offline_access is not allowed for this client: {client}", client.ClientId); return false; } requestedScopes = requestedScopes.Where(x => x != IdentityServerConstants.StandardScopes.OfflineAccess).ToArray(); } var resources = await _store.FindEnabledResourcesByScopeAsync(requestedScopes); foreach (var scope in requestedScopes) { var identity = resources.IdentityResources.FirstOrDefault(x => x.Name == scope); if (identity != null) { if (!client.AllowedScopes.Contains(scope)) { _logger.LogError("Requested scope not allowed: {scope}", scope); return false; } } else { var api = resources.FindApiScope(scope); if (api == null || !client.AllowedScopes.Contains(scope)) { _logger.LogError("Requested scope not allowed: {scope}", scope); return false; } } } return true; } /// <summary> /// Determines whether the response type is valid. /// </summary> /// <param name="responseType">Type of the response.</param> /// <returns> /// <c>true</c> if the response type is valid; otherwise, <c>false</c>. /// </returns> public bool IsResponseTypeValid(string responseType) { var requirement = Constants.ResponseTypeToScopeRequirement[responseType]; switch (requirement) { case Constants.ScopeRequirement.Identity: if (!ContainsOpenIdScopes) { _logger.LogError("Requests for id_token response type must include identity scopes"); return false; } break; case Constants.ScopeRequirement.IdentityOnly: if (!ContainsOpenIdScopes || ContainsApiResourceScopes) { _logger.LogError("Requests for id_token response type only must not include resource scopes"); return false; } break; case Constants.ScopeRequirement.ResourceOnly: if (ContainsOpenIdScopes || !ContainsApiResourceScopes) { _logger.LogError("Requests for token response type only must include resource scopes, but no identity scopes."); return false; } break; } return true; } } }
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ using System; using NUnit.Framework; using NPOI.HSSF.Extractor; using TestCases.HSSF; using System.Text.RegularExpressions; using NPOI.XSSF.Extractor; using NPOI.XSSF; using NPOI; namespace TestCases.XSSF.Extractor { /** * Tests for {@link XSSFExcelExtractor} */ [TestFixture] public class TestXSSFExcelExtractor { protected XSSFExcelExtractor GetExtractor(String sampleName) { return new XSSFExcelExtractor(XSSFTestDataSamples.OpenSampleWorkbook(sampleName)); } /** * Get text out of the simple file */ [Test] public void TestGetSimpleText() { // a very simple file XSSFExcelExtractor extractor = GetExtractor("sample.xlsx"); String text = extractor.Text; Assert.IsTrue(text.Length > 0); // Check sheet names Assert.IsTrue(text.StartsWith("Sheet1")); Assert.IsTrue(text.EndsWith("Sheet3\n")); // Now without, will have text extractor.SetIncludeSheetNames(false); text = extractor.Text; String CHUNK1 = "Lorem\t111\n" + "ipsum\t222\n" + "dolor\t333\n" + "sit\t444\n" + "amet\t555\n" + "consectetuer\t666\n" + "adipiscing\t777\n" + "elit\t888\n" + "Nunc\t999\n"; String CHUNK2 = "The quick brown fox jumps over the lazy dog\n" + "hello, xssf hello, xssf\n" + "hello, xssf hello, xssf\n" + "hello, xssf hello, xssf\n" + "hello, xssf hello, xssf\n"; Assert.AreEqual( CHUNK1 + "at\t4995\n" + CHUNK2 , text); // Now Get formulas not their values extractor.SetFormulasNotResults(true); text = extractor.Text; Assert.AreEqual( CHUNK1 + "at\tSUM(B1:B9)\n" + CHUNK2, text); // With sheet names too extractor.SetIncludeSheetNames(true); text = extractor.Text; Assert.AreEqual( "Sheet1\n" + CHUNK1 + "at\tSUM(B1:B9)\n" + "rich test\n" + CHUNK2 + "Sheet3\n" , text); extractor.Close(); } [Test] public void TestGetComplexText() { // A fairly complex file XSSFExcelExtractor extractor = GetExtractor("AverageTaxRates.xlsx"); String text = extractor.Text; Assert.IsTrue(text.Length > 0); // Might not have all formatting it should do! // TODO decide if we should really have the "null" in there Assert.IsTrue(text.StartsWith( "Avgtxfull\n" + "\t(iii) AVERAGE TAX RATES ON ANNUAL" )); extractor.Close(); } /** * Test that we return pretty much the same as * ExcelExtractor does, when we're both passed * the same file, just saved as xls and xlsx */ [Test] public void TestComparedToOLE2() { // A fairly simple file - ooxml XSSFExcelExtractor ooxmlExtractor = GetExtractor("SampleSS.xlsx"); ExcelExtractor ole2Extractor = new ExcelExtractor(HSSFTestDataSamples.OpenSampleWorkbook("SampleSS.xls")); POITextExtractor[] extractors = new POITextExtractor[] { ooxmlExtractor, ole2Extractor }; for (int i = 0; i < extractors.Length; i++) { POITextExtractor extractor = extractors[i]; String text = Regex.Replace(extractor.Text,"[\r\t]", ""); Assert.IsTrue(text.StartsWith("First Sheet\nTest spreadsheet\n2nd row2nd row 2nd column\n")); Regex pattern = new Regex(".*13(\\.0+)?\\s+Sheet3.*",RegexOptions.Compiled); Assert.IsTrue(pattern.IsMatch(text)); } ole2Extractor.Close(); ooxmlExtractor.Close(); } /** * From bug #45540 */ [Test] public void TestHeaderFooter() { String[] files = new String[] { "45540_classic_Header.xlsx", "45540_form_Header.xlsx", "45540_classic_Footer.xlsx", "45540_form_Footer.xlsx", }; foreach (String sampleName in files) { XSSFExcelExtractor extractor = GetExtractor(sampleName); String text = extractor.Text; Assert.IsTrue(text.Contains("testdoc"), "Unable to find expected word in text from " + sampleName + "\n" + text); Assert.IsTrue(text.Contains("test phrase"), "Unable to find expected word in text\n" + text); extractor.Close(); } } /** * From bug #45544 */ [Test] public void TestComments() { XSSFExcelExtractor extractor = GetExtractor("45544.xlsx"); String text = extractor.Text; // No comments there yet Assert.IsFalse(text.Contains("testdoc"), "Unable to find expected word in text\n" + text); Assert.IsFalse(text.Contains("test phrase"), "Unable to find expected word in text\n" + text); // Turn on comment extraction, will then be extractor.SetIncludeCellComments(true); text = extractor.Text; Assert.IsTrue(text.Contains("testdoc"), "Unable to find expected word in text\n" + text); Assert.IsTrue(text.Contains("test phrase"), "Unable to find expected word in text\n" + text); extractor.Close(); } [Test] public void TestInlineStrings() { XSSFExcelExtractor extractor = GetExtractor("InlineStrings.xlsx"); extractor.SetFormulasNotResults(true); String text = extractor.Text; // Numbers Assert.IsTrue(text.Contains("43"), "Unable to find expected word in text\n" + text); Assert.IsTrue(text.Contains("22"), "Unable to find expected word in text\n" + text); // Strings Assert.IsTrue(text.Contains("ABCDE"), "Unable to find expected word in text\n" + text); Assert.IsTrue(text.Contains("Long Text"), "Unable to find expected word in text\n" + text); // Inline Strings Assert.IsTrue(text.Contains("1st Inline String"), "Unable to find expected word in text\n" + text); Assert.IsTrue(text.Contains("And More"), "Unable to find expected word in text\n" + text); // Formulas Assert.IsTrue(text.Contains("A2"), "Unable to find expected word in text\n" + text); Assert.IsTrue(text.Contains("A5-A$2"), "Unable to find expected word in text\n" + text); extractor.Close(); } [Test] public void TestEmptyCells() { XSSFExcelExtractor extractor = GetExtractor("SimpleNormal.xlsx"); String text = extractor.Text; Assert.IsTrue(text.Length > 0); // This sheet demonstrates the preservation of empty cells, as // signified by sequential \t characters. Assert.AreEqual( // Sheet 1 "Sheet1\n" + "test\t\t1\n" + "test 2\t\t2\n" + "\t\t3\n" + "\t\t4\n" + "\t\t5\n" + "\t\t6\n" + // Sheet 2 "Sheet Number 2\n" + "This is sheet 2\n" + "Stuff\n" + "1\t2\t3\t4\t5\t6\n" + "1/1/90\n" + "10\t\t3\n", text); extractor.Close(); } /** * Simple test for text box text * @throws IOException */ [Test] public void TestTextBoxes() { XSSFExcelExtractor extractor = GetExtractor("WithTextBox.xlsx"); try { extractor.SetFormulasNotResults(true); String text = extractor.Text; Assert.IsTrue(text.IndexOf("Line 1") > -1); Assert.IsTrue(text.IndexOf("Line 2") > -1); Assert.IsTrue(text.IndexOf("Line 3") > -1); } finally { extractor.Close(); } } } }
using System; using System.Collections.Generic; using Microsoft.Data.Entity.Migrations; namespace WebApp.Migrations { public partial class AddedHousingTime : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.DropForeignKey(name: "FK_IdentityRoleClaim<string>_IdentityRole_RoleId", table: "AspNetRoleClaims"); migrationBuilder.DropForeignKey(name: "FK_IdentityUserClaim<string>_ApplicationUser_UserId", table: "AspNetUserClaims"); migrationBuilder.DropForeignKey(name: "FK_IdentityUserLogin<string>_ApplicationUser_UserId", table: "AspNetUserLogins"); migrationBuilder.DropForeignKey(name: "FK_IdentityUserRole<string>_IdentityRole_RoleId", table: "AspNetUserRoles"); migrationBuilder.DropForeignKey(name: "FK_IdentityUserRole<string>_ApplicationUser_UserId", table: "AspNetUserRoles"); migrationBuilder.DropForeignKey(name: "FK_Customer_City_CityId", table: "Customer"); migrationBuilder.DropForeignKey(name: "FK_Customer_Sms_SmsId", table: "Customer"); migrationBuilder.DropForeignKey(name: "FK_Housing_City_CityId", table: "Housing"); migrationBuilder.DropForeignKey(name: "FK_Housing_District_DistrictId", table: "Housing"); migrationBuilder.DropForeignKey(name: "FK_Housing_Street_StreetId", table: "Housing"); migrationBuilder.DropForeignKey(name: "FK_Housing_TypesHousing_TypesHousingId", table: "Housing"); migrationBuilder.DropForeignKey(name: "FK_HousingCall_Housing_HousingId", table: "Call"); migrationBuilder.AddColumn<DateTime>( name: "CreatedAt", table: "Housing", nullable: false, defaultValueSql: "GETUTCDATE()"); migrationBuilder.AddColumn<DateTime>( name: "LastEditedAt", table: "Housing", nullable: true); migrationBuilder.AddForeignKey( name: "FK_IdentityRoleClaim<string>_IdentityRole_RoleId", table: "AspNetRoleClaims", column: "RoleId", principalTable: "AspNetRoles", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_IdentityUserClaim<string>_ApplicationUser_UserId", table: "AspNetUserClaims", column: "UserId", principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_IdentityUserLogin<string>_ApplicationUser_UserId", table: "AspNetUserLogins", column: "UserId", principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_IdentityUserRole<string>_IdentityRole_RoleId", table: "AspNetUserRoles", column: "RoleId", principalTable: "AspNetRoles", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_IdentityUserRole<string>_ApplicationUser_UserId", table: "AspNetUserRoles", column: "UserId", principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_Customer_City_CityId", table: "Customer", column: "CityId", principalTable: "City", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_Customer_Sms_SmsId", table: "Customer", column: "SmsId", principalTable: "Sms", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_Housing_City_CityId", table: "Housing", column: "CityId", principalTable: "City", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_Housing_District_DistrictId", table: "Housing", column: "DistrictId", principalTable: "District", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_Housing_Street_StreetId", table: "Housing", column: "StreetId", principalTable: "Street", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_Housing_TypesHousing_TypesHousingId", table: "Housing", column: "TypesHousingId", principalTable: "TypesHousing", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_HousingCall_Housing_HousingId", table: "Call", column: "HousingId", principalTable: "Housing", principalColumn: "Id", onDelete: ReferentialAction.Cascade); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropForeignKey(name: "FK_IdentityRoleClaim<string>_IdentityRole_RoleId", table: "AspNetRoleClaims"); migrationBuilder.DropForeignKey(name: "FK_IdentityUserClaim<string>_ApplicationUser_UserId", table: "AspNetUserClaims"); migrationBuilder.DropForeignKey(name: "FK_IdentityUserLogin<string>_ApplicationUser_UserId", table: "AspNetUserLogins"); migrationBuilder.DropForeignKey(name: "FK_IdentityUserRole<string>_IdentityRole_RoleId", table: "AspNetUserRoles"); migrationBuilder.DropForeignKey(name: "FK_IdentityUserRole<string>_ApplicationUser_UserId", table: "AspNetUserRoles"); migrationBuilder.DropForeignKey(name: "FK_Customer_City_CityId", table: "Customer"); migrationBuilder.DropForeignKey(name: "FK_Customer_Sms_SmsId", table: "Customer"); migrationBuilder.DropForeignKey(name: "FK_Housing_City_CityId", table: "Housing"); migrationBuilder.DropForeignKey(name: "FK_Housing_District_DistrictId", table: "Housing"); migrationBuilder.DropForeignKey(name: "FK_Housing_Street_StreetId", table: "Housing"); migrationBuilder.DropForeignKey(name: "FK_Housing_TypesHousing_TypesHousingId", table: "Housing"); migrationBuilder.DropForeignKey(name: "FK_HousingCall_Housing_HousingId", table: "Call"); migrationBuilder.DropColumn(name: "CreatedAt", table: "Housing"); migrationBuilder.DropColumn(name: "LastEditedAt", table: "Housing"); migrationBuilder.AddForeignKey( name: "FK_IdentityRoleClaim<string>_IdentityRole_RoleId", table: "AspNetRoleClaims", column: "RoleId", principalTable: "AspNetRoles", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_IdentityUserClaim<string>_ApplicationUser_UserId", table: "AspNetUserClaims", column: "UserId", principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_IdentityUserLogin<string>_ApplicationUser_UserId", table: "AspNetUserLogins", column: "UserId", principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_IdentityUserRole<string>_IdentityRole_RoleId", table: "AspNetUserRoles", column: "RoleId", principalTable: "AspNetRoles", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_IdentityUserRole<string>_ApplicationUser_UserId", table: "AspNetUserRoles", column: "UserId", principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_Customer_City_CityId", table: "Customer", column: "CityId", principalTable: "City", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_Customer_Sms_SmsId", table: "Customer", column: "SmsId", principalTable: "Sms", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_Housing_City_CityId", table: "Housing", column: "CityId", principalTable: "City", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_Housing_District_DistrictId", table: "Housing", column: "DistrictId", principalTable: "District", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_Housing_Street_StreetId", table: "Housing", column: "StreetId", principalTable: "Street", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_Housing_TypesHousing_TypesHousingId", table: "Housing", column: "TypesHousingId", principalTable: "TypesHousing", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_HousingCall_Housing_HousingId", table: "Call", column: "HousingId", principalTable: "Housing", principalColumn: "Id", onDelete: ReferentialAction.Restrict); } } }
#region Copyright and license information // Copyright 2001-2009 Stephen Colebourne // Copyright 2009-2011 Jon Skeet // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion using System; using NUnit.Framework; using NodaTime.Testing.TimeZones; using NodaTime.TimeZones; namespace NodaTime.Test.TimeZones { [TestFixture] public class PrecalculatedDateTimeZoneTest { private static readonly ZoneInterval FirstInterval = new ZoneInterval("First", Instant.MinValue, Instant.FromUtc(2000, 3, 10, 10, 0), Offset.FromHours(3), Offset.Zero); // Note that this is effectively UTC +3 + 1 hour DST. private static readonly ZoneInterval SecondInterval = new ZoneInterval("Second", FirstInterval.End, Instant.FromUtc(2000, 9, 15, 5, 0), Offset.FromHours(4), Offset.FromHours(1)); private static readonly ZoneInterval ThirdInterval = new ZoneInterval("Third", SecondInterval.End, Instant.FromUtc(2005, 6, 20, 8, 0), Offset.FromHours(-5), Offset.Zero); private static readonly FixedDateTimeZone TailZone = new FixedDateTimeZone("TestFixed", Offset.FromHours(-6)); // We don't actually want an interval from the beginning of time when we ask our composite time zone for an interval // - because that could give the wrong idea. So we clamp it at the end of the precalculated interval. private static readonly ZoneInterval ClampedTailZoneInterval = TailZone.GetZoneInterval(Instant.UnixEpoch).WithStart(ThirdInterval.End); private static readonly PrecalculatedDateTimeZone TestZone = new PrecalculatedDateTimeZone("Test", new[] { FirstInterval, SecondInterval, ThirdInterval }, TailZone); [Test] public void MinMaxOffsets() { Assert.AreEqual(Offset.FromHours(-6), TestZone.MinOffset); Assert.AreEqual(Offset.FromHours(4), TestZone.MaxOffset); } [Test] public void MinMaxOffsetsWithOtherTailZone() { var tailZone = new FixedDateTimeZone("TestFixed", Offset.FromHours(8)); var testZone = new PrecalculatedDateTimeZone("Test", new[] { FirstInterval, SecondInterval, ThirdInterval }, tailZone); Assert.AreEqual(Offset.FromHours(-5), testZone.MinOffset); Assert.AreEqual(Offset.FromHours(8), testZone.MaxOffset); } [Test] public void MinMaxOffsetsWithNullTailZone() { var testZone = new PrecalculatedDateTimeZone("Test", new[] { FirstInterval, SecondInterval, ThirdInterval, new ZoneInterval("Last", ThirdInterval.End, Instant.MaxValue, Offset.Zero, Offset.Zero) }, null); Assert.AreEqual(Offset.FromHours(-5), testZone.MinOffset); Assert.AreEqual(Offset.FromHours(4), testZone.MaxOffset); } [Test] public void GetZoneIntervalInstant_End() { Assert.AreEqual(SecondInterval, TestZone.GetZoneInterval(SecondInterval.End - Duration.One)); } [Test] public void GetZoneIntervalInstant_Start() { Assert.AreEqual(SecondInterval, TestZone.GetZoneInterval(SecondInterval.Start)); } [Test] public void GetZoneIntervalInstant_TailZone() { Assert.AreEqual(ClampedTailZoneInterval, TestZone.GetZoneInterval(ThirdInterval.End)); } [Test] public void GetZoneIntervals_UnambiguousInPrecalculated() { var pair = TestZone.GetZoneIntervals(new LocalInstant(2000, 6, 1, 0, 0)); Assert.AreEqual(SecondInterval, pair.EarlyInterval); Assert.IsNull(pair.LateInterval); } [Test] public void GetZoneIntervals_UnambiguousInTailZone() { var pair = TestZone.GetZoneIntervals(new LocalInstant(2015, 1, 1, 0, 0)); Assert.AreEqual(ClampedTailZoneInterval, pair.EarlyInterval); Assert.IsNull(pair.LateInterval); } [Test] public void GetZoneIntervals_AmbiguousWithinPrecalculated() { // Transition from +4 to -5 has a 9 hour ambiguity var pair = TestZone.GetZoneIntervals(ThirdInterval.LocalStart); Assert.AreEqual(SecondInterval, pair.EarlyInterval); Assert.AreEqual(ThirdInterval, pair.LateInterval); } [Test] public void GetZoneIntervals_AmbiguousAroundTailZoneTransition() { // Transition from -5 to -6 has a 1 hour ambiguity var pair = TestZone.GetZoneIntervals(ThirdInterval.LocalEnd - Duration.One); Assert.AreEqual(ThirdInterval, pair.EarlyInterval); Assert.AreEqual(ClampedTailZoneInterval, pair.LateInterval); } [Test] public void GetZoneIntervals_AmbiguousButTooEarlyInTailZoneTransition() { // Tail zone is +10 / +8, with the transition occurring just after // the transition *to* the tail zone from the precalculated zone. // A local instant of one hour before after the transition from the precalculated zone (which is -5) // will therefore be ambiguous, but the resulting instants from the ambiguity occur // before our transition into the tail zone, so are ignored. var tailZone = new SingleTransitionZone(ThirdInterval.End + Duration.FromHours(1), 10, 8); var gapZone = new PrecalculatedDateTimeZone("Test", new[] { FirstInterval, SecondInterval, ThirdInterval }, tailZone); var pair = gapZone.GetZoneIntervals(ThirdInterval.LocalEnd - Duration.FromHours(1)); Assert.AreEqual(ThirdInterval, pair.EarlyInterval); Assert.IsNull(pair.LateInterval); } [Test] public void GetZoneIntervals_GapWithinPrecalculated() { // Transition from +3 to +4 has a 1 hour gap Assert.IsTrue(FirstInterval.LocalEnd < SecondInterval.LocalStart); var pair = TestZone.GetZoneIntervals(FirstInterval.LocalEnd); Assert.IsNull(pair.EarlyInterval); Assert.IsNull(pair.LateInterval); } [Test] public void GetZoneIntervals_SingleIntervalAroundTailZoneTransition() { // Tail zone is fixed at +5. A local instant of one hour before the transition // from the precalculated zone (which is -5) will therefore give an instant from // the tail zone which occurs before the precalculated-to-tail transition, // and can therefore be ignored, resulting in an overall unambiguous time. var tailZone = new FixedDateTimeZone(Offset.FromHours(5)); var gapZone = new PrecalculatedDateTimeZone("Test", new[] { FirstInterval, SecondInterval, ThirdInterval }, tailZone); var pair = gapZone.GetZoneIntervals(ThirdInterval.LocalEnd - Duration.FromHours(1)); Assert.AreEqual(ThirdInterval, pair.EarlyInterval); Assert.IsNull(pair.LateInterval); } [Test] public void GetZoneIntervals_GapAroundTailZoneTransition() { // Tail zone is fixed at +5. A local instant of one hour after the transition // from the precalculated zone (which is -5) will therefore give an instant from // the tail zone which occurs before the precalculated-to-tail transition, // and can therefore be ignored, resulting in an overall gap. var tailZone = new FixedDateTimeZone(Offset.FromHours(5)); var gapZone = new PrecalculatedDateTimeZone("Test", new[] { FirstInterval, SecondInterval, ThirdInterval }, tailZone); var actual = gapZone.GetZoneIntervals(ThirdInterval.LocalEnd); var expected = ZoneIntervalPair.NoMatch; Assert.AreEqual(expected, actual); } [Test] public void GetZoneIntervals_GapAroundAndInTailZoneTransition() { // Tail zone is -10 / +5, with the transition occurring just after // the transition *to* the tail zone from the precalculated zone. // A local instant of one hour after the transition from the precalculated zone (which is -5) // will therefore be in the gap. No zone interval matches, so the result is // an empty pair. var tailZone = new SingleTransitionZone(ThirdInterval.End + Duration.FromHours(1), -10, +5); var gapZone = new PrecalculatedDateTimeZone("Test", new[] { FirstInterval, SecondInterval, ThirdInterval }, tailZone); var pair = gapZone.GetZoneIntervals(ThirdInterval.LocalEnd + Duration.FromHours(1)); Assert.IsNull(pair.EarlyInterval); Assert.IsNull(pair.LateInterval); } [Test] public void Validation_EmptyPeriodArray() { Assert.Throws<ArgumentException>(() => PrecalculatedDateTimeZone.ValidatePeriods(new ZoneInterval[0], DateTimeZone.Utc)); } [Test] public void Validation_BadFirstStartingPoint() { ZoneInterval[] intervals = { new ZoneInterval("foo", new Instant(10), new Instant(20), Offset.Zero, Offset.Zero), new ZoneInterval("foo", new Instant(20), new Instant(30), Offset.Zero, Offset.Zero), }; Assert.Throws<ArgumentException>(() => PrecalculatedDateTimeZone.ValidatePeriods(intervals, DateTimeZone.Utc)); } [Test] public void Validation_NonAdjoiningIntervals() { ZoneInterval[] intervals = { new ZoneInterval("foo", Instant.MinValue, new Instant(20), Offset.Zero, Offset.Zero), new ZoneInterval("foo", new Instant(25), new Instant(30), Offset.Zero, Offset.Zero), }; Assert.Throws<ArgumentException>(() => PrecalculatedDateTimeZone.ValidatePeriods(intervals, DateTimeZone.Utc)); } [Test] public void Validation_Success() { ZoneInterval[] intervals = { new ZoneInterval("foo", Instant.MinValue, new Instant(20), Offset.Zero, Offset.Zero), new ZoneInterval("foo", new Instant(20), new Instant(30), Offset.Zero, Offset.Zero), new ZoneInterval("foo", new Instant(30), new Instant(100), Offset.Zero, Offset.Zero), new ZoneInterval("foo", new Instant(100), new Instant(200), Offset.Zero, Offset.Zero), }; PrecalculatedDateTimeZone.ValidatePeriods(intervals, DateTimeZone.Utc); } [Test] public void Validation_NullTailZoneWithMiddleOfTimeFinalPeriod() { ZoneInterval[] intervals = { new ZoneInterval("foo", Instant.MinValue, new Instant(20), Offset.Zero, Offset.Zero), new ZoneInterval("foo", new Instant(20), new Instant(30), Offset.Zero, Offset.Zero) }; Assert.Throws<ArgumentException>(() => PrecalculatedDateTimeZone.ValidatePeriods(intervals, null)); } [Test] public void Validation_NullTailZoneWithEotPeriodEnd() { ZoneInterval[] intervals = { new ZoneInterval("foo", Instant.MinValue, new Instant(20), Offset.Zero, Offset.Zero), new ZoneInterval("foo", new Instant(20), Instant.MaxValue, Offset.Zero, Offset.Zero), }; PrecalculatedDateTimeZone.ValidatePeriods(intervals, null); } } }
using Lucene.Net.Documents; using Lucene.Net.Index.Extensions; using NUnit.Framework; using System; using System.Collections.Generic; using System.IO; using Assert = Lucene.Net.TestFramework.Assert; namespace Lucene.Net.Index { /* * 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 BaseDirectory = Lucene.Net.Store.BaseDirectory; using BufferedIndexInput = Lucene.Net.Store.BufferedIndexInput; using Directory = Lucene.Net.Store.Directory; using Document = Documents.Document; using DocumentStoredFieldVisitor = DocumentStoredFieldVisitor; using Field = Field; using IndexInput = Lucene.Net.Store.IndexInput; using IndexOutput = Lucene.Net.Store.IndexOutput; using IOContext = Lucene.Net.Store.IOContext; using LuceneTestCase = Lucene.Net.Util.LuceneTestCase; using MockAnalyzer = Lucene.Net.Analysis.MockAnalyzer; [TestFixture] public class TestFieldsReader : LuceneTestCase { private static Directory dir; private static Document testDoc; private static FieldInfos.Builder fieldInfos = null; /// <summary> /// LUCENENET specific /// Is non-static because NewIndexWriterConfig is no longer static. /// </summary> [OneTimeSetUp] public override void BeforeClass() { base.BeforeClass(); testDoc = new Document(); fieldInfos = new FieldInfos.Builder(); DocHelper.SetupDoc(testDoc); foreach (IIndexableField field in testDoc) { fieldInfos.AddOrUpdate(field.Name, field.IndexableFieldType); } dir = NewDirectory(); IndexWriterConfig conf = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random)).SetMergePolicy(NewLogMergePolicy()); conf.MergePolicy.NoCFSRatio = 0.0; IndexWriter writer = new IndexWriter(dir, conf); writer.AddDocument(testDoc); writer.Dispose(); FaultyIndexInput.doFail = false; } [OneTimeTearDown] public override void AfterClass() { dir.Dispose(); dir = null; fieldInfos = null; testDoc = null; base.AfterClass(); } [Test] public virtual void Test() { Assert.IsTrue(dir != null); Assert.IsTrue(fieldInfos != null); IndexReader reader = DirectoryReader.Open(dir); Document doc = reader.Document(0); Assert.IsTrue(doc != null); Assert.IsTrue(doc.GetField(DocHelper.TEXT_FIELD_1_KEY) != null); Field field = (Field)doc.GetField(DocHelper.TEXT_FIELD_2_KEY); Assert.IsTrue(field != null); Assert.IsTrue(field.IndexableFieldType.StoreTermVectors); Assert.IsFalse(field.IndexableFieldType.OmitNorms); Assert.IsTrue(field.IndexableFieldType.IndexOptions == IndexOptions.DOCS_AND_FREQS_AND_POSITIONS); field = (Field)doc.GetField(DocHelper.TEXT_FIELD_3_KEY); Assert.IsTrue(field != null); Assert.IsFalse(field.IndexableFieldType.StoreTermVectors); Assert.IsTrue(field.IndexableFieldType.OmitNorms); Assert.IsTrue(field.IndexableFieldType.IndexOptions == IndexOptions.DOCS_AND_FREQS_AND_POSITIONS); field = (Field)doc.GetField(DocHelper.NO_TF_KEY); Assert.IsTrue(field != null); Assert.IsFalse(field.IndexableFieldType.StoreTermVectors); Assert.IsFalse(field.IndexableFieldType.OmitNorms); Assert.IsTrue(field.IndexableFieldType.IndexOptions == IndexOptions.DOCS_ONLY); DocumentStoredFieldVisitor visitor = new DocumentStoredFieldVisitor(DocHelper.TEXT_FIELD_3_KEY); reader.Document(0, visitor); IList<IIndexableField> fields = visitor.Document.Fields; Assert.AreEqual(1, fields.Count); Assert.AreEqual(DocHelper.TEXT_FIELD_3_KEY, fields[0].Name); reader.Dispose(); } public class FaultyFSDirectory : BaseDirectory { internal Directory fsDir; public FaultyFSDirectory(DirectoryInfo dir) { fsDir = NewFSDirectory(dir); m_lockFactory = fsDir.LockFactory; } public override IndexInput OpenInput(string name, IOContext context) { return new FaultyIndexInput(fsDir.OpenInput(name, context)); } public override string[] ListAll() { return fsDir.ListAll(); } [Obsolete("this method will be removed in 5.0")] public override bool FileExists(string name) { return fsDir.FileExists(name); } public override void DeleteFile(string name) { fsDir.DeleteFile(name); } public override long FileLength(string name) { return fsDir.FileLength(name); } public override IndexOutput CreateOutput(string name, IOContext context) { return fsDir.CreateOutput(name, context); } public override void Sync(ICollection<string> names) { fsDir.Sync(names); } protected override void Dispose(bool disposing) { if (disposing) { fsDir.Dispose(); } } } private class FaultyIndexInput : BufferedIndexInput { internal IndexInput @delegate; internal static bool doFail; internal int count; internal FaultyIndexInput(IndexInput @delegate) : base("FaultyIndexInput(" + @delegate + ")", BufferedIndexInput.BUFFER_SIZE) { this.@delegate = @delegate; } internal virtual void SimOutage() { if (doFail && count++ % 2 == 1) { throw new IOException("Simulated network outage"); } } protected override void ReadInternal(byte[] b, int offset, int length) { SimOutage(); @delegate.Seek(GetFilePointer()); @delegate.ReadBytes(b, offset, length); } protected override void SeekInternal(long pos) { } public override long Length => @delegate.Length; protected override void Dispose(bool disposing) { if (disposing) { @delegate.Dispose(); } } public override object Clone() { FaultyIndexInput i = new FaultyIndexInput((IndexInput)@delegate.Clone()); // seek the clone to our current position try { i.Seek(GetFilePointer()); } #pragma warning disable 168 catch (IOException e) #pragma warning restore 168 { throw new Exception(); } return i; } } // LUCENE-1262 [Test] public virtual void TestExceptions() { DirectoryInfo indexDir = CreateTempDir("testfieldswriterexceptions"); try { Directory dir = new FaultyFSDirectory(indexDir); IndexWriterConfig iwc = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random)).SetOpenMode(OpenMode.CREATE); IndexWriter writer = new IndexWriter(dir, iwc); for (int i = 0; i < 2; i++) { writer.AddDocument(testDoc); } writer.ForceMerge(1); writer.Dispose(); IndexReader reader = DirectoryReader.Open(dir); FaultyIndexInput.doFail = true; bool exc = false; for (int i = 0; i < 2; i++) { try { reader.Document(i); } #pragma warning disable 168 catch (IOException ioe) #pragma warning restore 168 { // expected exc = true; } try { reader.Document(i); } #pragma warning disable 168 catch (IOException ioe) #pragma warning restore 168 { // expected exc = true; } } Assert.IsTrue(exc); reader.Dispose(); dir.Dispose(); } finally { System.IO.Directory.Delete(indexDir.FullName, true); } } } }
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace applicationGateway.Models { using Microsoft.Rest; using Microsoft.Rest.Serialization; using Newtonsoft.Json; using System.Linq; /// <summary> /// Peering in an ExpressRouteCircuit resource. /// </summary> [JsonTransformation] public partial class ExpressRouteCircuitPeering : SubResource { /// <summary> /// Initializes a new instance of the ExpressRouteCircuitPeering class. /// </summary> public ExpressRouteCircuitPeering() { CustomInit(); } /// <summary> /// Initializes a new instance of the ExpressRouteCircuitPeering class. /// </summary> /// <param name="id">Resource ID.</param> /// <param name="peeringType">The PeeringType. Possible values are: /// 'AzurePublicPeering', 'AzurePrivatePeering', and /// 'MicrosoftPeering'. Possible values include: 'AzurePublicPeering', /// 'AzurePrivatePeering', 'MicrosoftPeering'</param> /// <param name="state">The state of peering. Possible values are: /// 'Disabled' and 'Enabled'. Possible values include: 'Disabled', /// 'Enabled'</param> /// <param name="azureASN">The Azure ASN.</param> /// <param name="peerASN">The peer ASN.</param> /// <param name="primaryPeerAddressPrefix">The primary address /// prefix.</param> /// <param name="secondaryPeerAddressPrefix">The secondary address /// prefix.</param> /// <param name="primaryAzurePort">The primary port.</param> /// <param name="secondaryAzurePort">The secondary port.</param> /// <param name="sharedKey">The shared key.</param> /// <param name="vlanId">The VLAN ID.</param> /// <param name="microsoftPeeringConfig">The Microsoft peering /// configuration.</param> /// <param name="stats">Gets peering stats.</param> /// <param name="provisioningState">Gets the provisioning state of the /// public IP resource. Possible values are: 'Updating', 'Deleting', /// and 'Failed'.</param> /// <param name="gatewayManagerEtag">The GatewayManager Etag.</param> /// <param name="lastModifiedBy">Gets whether the provider or the /// customer last modified the peering.</param> /// <param name="routeFilter">The reference of the RouteFilter /// resource.</param> /// <param name="name">Gets name of the resource that is unique within /// a resource group. This name can be used to access the /// resource.</param> /// <param name="etag">A unique read-only string that changes whenever /// the resource is updated.</param> public ExpressRouteCircuitPeering(string id = default(string), string peeringType = default(string), string state = default(string), int? azureASN = default(int?), int? peerASN = default(int?), string primaryPeerAddressPrefix = default(string), string secondaryPeerAddressPrefix = default(string), string primaryAzurePort = default(string), string secondaryAzurePort = default(string), string sharedKey = default(string), int? vlanId = default(int?), ExpressRouteCircuitPeeringConfig microsoftPeeringConfig = default(ExpressRouteCircuitPeeringConfig), ExpressRouteCircuitStats stats = default(ExpressRouteCircuitStats), string provisioningState = default(string), string gatewayManagerEtag = default(string), string lastModifiedBy = default(string), RouteFilter routeFilter = default(RouteFilter), string name = default(string), string etag = default(string)) : base(id) { PeeringType = peeringType; State = state; AzureASN = azureASN; PeerASN = peerASN; PrimaryPeerAddressPrefix = primaryPeerAddressPrefix; SecondaryPeerAddressPrefix = secondaryPeerAddressPrefix; PrimaryAzurePort = primaryAzurePort; SecondaryAzurePort = secondaryAzurePort; SharedKey = sharedKey; VlanId = vlanId; MicrosoftPeeringConfig = microsoftPeeringConfig; Stats = stats; ProvisioningState = provisioningState; GatewayManagerEtag = gatewayManagerEtag; LastModifiedBy = lastModifiedBy; RouteFilter = routeFilter; Name = name; Etag = etag; CustomInit(); } /// <summary> /// An initialization method that performs custom operations like setting defaults /// </summary> partial void CustomInit(); /// <summary> /// Gets or sets the PeeringType. Possible values are: /// 'AzurePublicPeering', 'AzurePrivatePeering', and /// 'MicrosoftPeering'. Possible values include: 'AzurePublicPeering', /// 'AzurePrivatePeering', 'MicrosoftPeering' /// </summary> [JsonProperty(PropertyName = "properties.peeringType")] public string PeeringType { get; set; } /// <summary> /// Gets or sets the state of peering. Possible values are: 'Disabled' /// and 'Enabled'. Possible values include: 'Disabled', 'Enabled' /// </summary> [JsonProperty(PropertyName = "properties.state")] public string State { get; set; } /// <summary> /// Gets or sets the Azure ASN. /// </summary> [JsonProperty(PropertyName = "properties.azureASN")] public int? AzureASN { get; set; } /// <summary> /// Gets or sets the peer ASN. /// </summary> [JsonProperty(PropertyName = "properties.peerASN")] public int? PeerASN { get; set; } /// <summary> /// Gets or sets the primary address prefix. /// </summary> [JsonProperty(PropertyName = "properties.primaryPeerAddressPrefix")] public string PrimaryPeerAddressPrefix { get; set; } /// <summary> /// Gets or sets the secondary address prefix. /// </summary> [JsonProperty(PropertyName = "properties.secondaryPeerAddressPrefix")] public string SecondaryPeerAddressPrefix { get; set; } /// <summary> /// Gets or sets the primary port. /// </summary> [JsonProperty(PropertyName = "properties.primaryAzurePort")] public string PrimaryAzurePort { get; set; } /// <summary> /// Gets or sets the secondary port. /// </summary> [JsonProperty(PropertyName = "properties.secondaryAzurePort")] public string SecondaryAzurePort { get; set; } /// <summary> /// Gets or sets the shared key. /// </summary> [JsonProperty(PropertyName = "properties.sharedKey")] public string SharedKey { get; set; } /// <summary> /// Gets or sets the VLAN ID. /// </summary> [JsonProperty(PropertyName = "properties.vlanId")] public int? VlanId { get; set; } /// <summary> /// Gets or sets the Microsoft peering configuration. /// </summary> [JsonProperty(PropertyName = "properties.microsoftPeeringConfig")] public ExpressRouteCircuitPeeringConfig MicrosoftPeeringConfig { get; set; } /// <summary> /// Gets peering stats. /// </summary> [JsonProperty(PropertyName = "properties.stats")] public ExpressRouteCircuitStats Stats { get; set; } /// <summary> /// Gets the provisioning state of the public IP resource. Possible /// values are: 'Updating', 'Deleting', and 'Failed'. /// </summary> [JsonProperty(PropertyName = "properties.provisioningState")] public string ProvisioningState { get; set; } /// <summary> /// Gets or sets the GatewayManager Etag. /// </summary> [JsonProperty(PropertyName = "properties.gatewayManagerEtag")] public string GatewayManagerEtag { get; set; } /// <summary> /// Gets whether the provider or the customer last modified the /// peering. /// </summary> [JsonProperty(PropertyName = "properties.lastModifiedBy")] public string LastModifiedBy { get; set; } /// <summary> /// Gets or sets the reference of the RouteFilter resource. /// </summary> [JsonProperty(PropertyName = "properties.routeFilter")] public RouteFilter RouteFilter { get; set; } /// <summary> /// Gets name of the resource that is unique within a resource group. /// This name can be used to access the resource. /// </summary> [JsonProperty(PropertyName = "name")] public string Name { get; set; } /// <summary> /// Gets a unique read-only string that changes whenever the resource /// is updated. /// </summary> [JsonProperty(PropertyName = "etag")] public string Etag { get; private set; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.Drawing { [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct Color { private object _dummy; public static readonly System.Drawing.Color Empty; public byte A { get { throw null; } } public static System.Drawing.Color AliceBlue { get { throw null; } } public static System.Drawing.Color AntiqueWhite { get { throw null; } } public static System.Drawing.Color Aqua { get { throw null; } } public static System.Drawing.Color Aquamarine { get { throw null; } } public static System.Drawing.Color Azure { get { throw null; } } public byte B { get { throw null; } } public static System.Drawing.Color Beige { get { throw null; } } public static System.Drawing.Color Bisque { get { throw null; } } public static System.Drawing.Color Black { get { throw null; } } public static System.Drawing.Color BlanchedAlmond { get { throw null; } } public static System.Drawing.Color Blue { get { throw null; } } public static System.Drawing.Color BlueViolet { get { throw null; } } public static System.Drawing.Color Brown { get { throw null; } } public static System.Drawing.Color BurlyWood { get { throw null; } } public static System.Drawing.Color CadetBlue { get { throw null; } } public static System.Drawing.Color Chartreuse { get { throw null; } } public static System.Drawing.Color Chocolate { get { throw null; } } public static System.Drawing.Color Coral { get { throw null; } } public static System.Drawing.Color CornflowerBlue { get { throw null; } } public static System.Drawing.Color Cornsilk { get { throw null; } } public static System.Drawing.Color Crimson { get { throw null; } } public static System.Drawing.Color Cyan { get { throw null; } } public static System.Drawing.Color DarkBlue { get { throw null; } } public static System.Drawing.Color DarkCyan { get { throw null; } } public static System.Drawing.Color DarkGoldenrod { get { throw null; } } public static System.Drawing.Color DarkGray { get { throw null; } } public static System.Drawing.Color DarkGreen { get { throw null; } } public static System.Drawing.Color DarkKhaki { get { throw null; } } public static System.Drawing.Color DarkMagenta { get { throw null; } } public static System.Drawing.Color DarkOliveGreen { get { throw null; } } public static System.Drawing.Color DarkOrange { get { throw null; } } public static System.Drawing.Color DarkOrchid { get { throw null; } } public static System.Drawing.Color DarkRed { get { throw null; } } public static System.Drawing.Color DarkSalmon { get { throw null; } } public static System.Drawing.Color DarkSeaGreen { get { throw null; } } public static System.Drawing.Color DarkSlateBlue { get { throw null; } } public static System.Drawing.Color DarkSlateGray { get { throw null; } } public static System.Drawing.Color DarkTurquoise { get { throw null; } } public static System.Drawing.Color DarkViolet { get { throw null; } } public static System.Drawing.Color DeepPink { get { throw null; } } public static System.Drawing.Color DeepSkyBlue { get { throw null; } } public static System.Drawing.Color DimGray { get { throw null; } } public static System.Drawing.Color DodgerBlue { get { throw null; } } public static System.Drawing.Color Firebrick { get { throw null; } } public static System.Drawing.Color FloralWhite { get { throw null; } } public static System.Drawing.Color ForestGreen { get { throw null; } } public static System.Drawing.Color Fuchsia { get { throw null; } } public byte G { get { throw null; } } public static System.Drawing.Color Gainsboro { get { throw null; } } public static System.Drawing.Color GhostWhite { get { throw null; } } public static System.Drawing.Color Gold { get { throw null; } } public static System.Drawing.Color Goldenrod { get { throw null; } } public static System.Drawing.Color Gray { get { throw null; } } public static System.Drawing.Color Green { get { throw null; } } public static System.Drawing.Color GreenYellow { get { throw null; } } public static System.Drawing.Color Honeydew { get { throw null; } } public static System.Drawing.Color HotPink { get { throw null; } } public static System.Drawing.Color IndianRed { get { throw null; } } public static System.Drawing.Color Indigo { get { throw null; } } public bool IsEmpty { get { throw null; } } public bool IsKnownColor { get { throw null; } } public bool IsNamedColor { get { throw null; } } public bool IsSystemColor { get { throw null; } } public static System.Drawing.Color Ivory { get { throw null; } } public static System.Drawing.Color Khaki { get { throw null; } } public static System.Drawing.Color Lavender { get { throw null; } } public static System.Drawing.Color LavenderBlush { get { throw null; } } public static System.Drawing.Color LawnGreen { get { throw null; } } public static System.Drawing.Color LemonChiffon { get { throw null; } } public static System.Drawing.Color LightBlue { get { throw null; } } public static System.Drawing.Color LightCoral { get { throw null; } } public static System.Drawing.Color LightCyan { get { throw null; } } public static System.Drawing.Color LightGoldenrodYellow { get { throw null; } } public static System.Drawing.Color LightGray { get { throw null; } } public static System.Drawing.Color LightGreen { get { throw null; } } public static System.Drawing.Color LightPink { get { throw null; } } public static System.Drawing.Color LightSalmon { get { throw null; } } public static System.Drawing.Color LightSeaGreen { get { throw null; } } public static System.Drawing.Color LightSkyBlue { get { throw null; } } public static System.Drawing.Color LightSlateGray { get { throw null; } } public static System.Drawing.Color LightSteelBlue { get { throw null; } } public static System.Drawing.Color LightYellow { get { throw null; } } public static System.Drawing.Color Lime { get { throw null; } } public static System.Drawing.Color LimeGreen { get { throw null; } } public static System.Drawing.Color Linen { get { throw null; } } public static System.Drawing.Color Magenta { get { throw null; } } public static System.Drawing.Color Maroon { get { throw null; } } public static System.Drawing.Color MediumAquamarine { get { throw null; } } public static System.Drawing.Color MediumBlue { get { throw null; } } public static System.Drawing.Color MediumOrchid { get { throw null; } } public static System.Drawing.Color MediumPurple { get { throw null; } } public static System.Drawing.Color MediumSeaGreen { get { throw null; } } public static System.Drawing.Color MediumSlateBlue { get { throw null; } } public static System.Drawing.Color MediumSpringGreen { get { throw null; } } public static System.Drawing.Color MediumTurquoise { get { throw null; } } public static System.Drawing.Color MediumVioletRed { get { throw null; } } public static System.Drawing.Color MidnightBlue { get { throw null; } } public static System.Drawing.Color MintCream { get { throw null; } } public static System.Drawing.Color MistyRose { get { throw null; } } public static System.Drawing.Color Moccasin { get { throw null; } } public string Name { get { throw null; } } public static System.Drawing.Color NavajoWhite { get { throw null; } } public static System.Drawing.Color Navy { get { throw null; } } public static System.Drawing.Color OldLace { get { throw null; } } public static System.Drawing.Color Olive { get { throw null; } } public static System.Drawing.Color OliveDrab { get { throw null; } } public static System.Drawing.Color Orange { get { throw null; } } public static System.Drawing.Color OrangeRed { get { throw null; } } public static System.Drawing.Color Orchid { get { throw null; } } public static System.Drawing.Color PaleGoldenrod { get { throw null; } } public static System.Drawing.Color PaleGreen { get { throw null; } } public static System.Drawing.Color PaleTurquoise { get { throw null; } } public static System.Drawing.Color PaleVioletRed { get { throw null; } } public static System.Drawing.Color PapayaWhip { get { throw null; } } public static System.Drawing.Color PeachPuff { get { throw null; } } public static System.Drawing.Color Peru { get { throw null; } } public static System.Drawing.Color Pink { get { throw null; } } public static System.Drawing.Color Plum { get { throw null; } } public static System.Drawing.Color PowderBlue { get { throw null; } } public static System.Drawing.Color Purple { get { throw null; } } public byte R { get { throw null; } } public static System.Drawing.Color Red { get { throw null; } } public static System.Drawing.Color RosyBrown { get { throw null; } } public static System.Drawing.Color RoyalBlue { get { throw null; } } public static System.Drawing.Color SaddleBrown { get { throw null; } } public static System.Drawing.Color Salmon { get { throw null; } } public static System.Drawing.Color SandyBrown { get { throw null; } } public static System.Drawing.Color SeaGreen { get { throw null; } } public static System.Drawing.Color SeaShell { get { throw null; } } public static System.Drawing.Color Sienna { get { throw null; } } public static System.Drawing.Color Silver { get { throw null; } } public static System.Drawing.Color SkyBlue { get { throw null; } } public static System.Drawing.Color SlateBlue { get { throw null; } } public static System.Drawing.Color SlateGray { get { throw null; } } public static System.Drawing.Color Snow { get { throw null; } } public static System.Drawing.Color SpringGreen { get { throw null; } } public static System.Drawing.Color SteelBlue { get { throw null; } } public static System.Drawing.Color Tan { get { throw null; } } public static System.Drawing.Color Teal { get { throw null; } } public static System.Drawing.Color Thistle { get { throw null; } } public static System.Drawing.Color Tomato { get { throw null; } } public static System.Drawing.Color Transparent { get { throw null; } } public static System.Drawing.Color Turquoise { get { throw null; } } public static System.Drawing.Color Violet { get { throw null; } } public static System.Drawing.Color Wheat { get { throw null; } } public static System.Drawing.Color White { get { throw null; } } public static System.Drawing.Color WhiteSmoke { get { throw null; } } public static System.Drawing.Color Yellow { get { throw null; } } public static System.Drawing.Color YellowGreen { get { throw null; } } public override bool Equals(object obj) { throw null; } public static System.Drawing.Color FromArgb(int argb) { throw null; } public static System.Drawing.Color FromArgb(int alpha, System.Drawing.Color baseColor) { throw null; } public static System.Drawing.Color FromArgb(int red, int green, int blue) { throw null; } public static System.Drawing.Color FromArgb(int alpha, int red, int green, int blue) { throw null; } public static System.Drawing.Color FromKnownColor(System.Drawing.KnownColor color) { throw null; } public static System.Drawing.Color FromName(string name) { throw null; } public float GetBrightness() { throw null; } public override int GetHashCode() { throw null; } public float GetHue() { throw null; } public float GetSaturation() { throw null; } public static bool operator ==(System.Drawing.Color left, System.Drawing.Color right) { throw null; } public static bool operator !=(System.Drawing.Color left, System.Drawing.Color right) { throw null; } public int ToArgb() { throw null; } public System.Drawing.KnownColor ToKnownColor() { throw null; } public override string ToString() { throw null; } } public enum KnownColor { ActiveBorder = 1, ActiveCaption = 2, ActiveCaptionText = 3, AliceBlue = 28, AntiqueWhite = 29, AppWorkspace = 4, Aqua = 30, Aquamarine = 31, Azure = 32, Beige = 33, Bisque = 34, Black = 35, BlanchedAlmond = 36, Blue = 37, BlueViolet = 38, Brown = 39, BurlyWood = 40, ButtonFace = 168, ButtonHighlight = 169, ButtonShadow = 170, CadetBlue = 41, Chartreuse = 42, Chocolate = 43, Control = 5, ControlDark = 6, ControlDarkDark = 7, ControlLight = 8, ControlLightLight = 9, ControlText = 10, Coral = 44, CornflowerBlue = 45, Cornsilk = 46, Crimson = 47, Cyan = 48, DarkBlue = 49, DarkCyan = 50, DarkGoldenrod = 51, DarkGray = 52, DarkGreen = 53, DarkKhaki = 54, DarkMagenta = 55, DarkOliveGreen = 56, DarkOrange = 57, DarkOrchid = 58, DarkRed = 59, DarkSalmon = 60, DarkSeaGreen = 61, DarkSlateBlue = 62, DarkSlateGray = 63, DarkTurquoise = 64, DarkViolet = 65, DeepPink = 66, DeepSkyBlue = 67, Desktop = 11, DimGray = 68, DodgerBlue = 69, Firebrick = 70, FloralWhite = 71, ForestGreen = 72, Fuchsia = 73, Gainsboro = 74, GhostWhite = 75, Gold = 76, Goldenrod = 77, GradientActiveCaption = 171, GradientInactiveCaption = 172, Gray = 78, GrayText = 12, Green = 79, GreenYellow = 80, Highlight = 13, HighlightText = 14, Honeydew = 81, HotPink = 82, HotTrack = 15, InactiveBorder = 16, InactiveCaption = 17, InactiveCaptionText = 18, IndianRed = 83, Indigo = 84, Info = 19, InfoText = 20, Ivory = 85, Khaki = 86, Lavender = 87, LavenderBlush = 88, LawnGreen = 89, LemonChiffon = 90, LightBlue = 91, LightCoral = 92, LightCyan = 93, LightGoldenrodYellow = 94, LightGray = 95, LightGreen = 96, LightPink = 97, LightSalmon = 98, LightSeaGreen = 99, LightSkyBlue = 100, LightSlateGray = 101, LightSteelBlue = 102, LightYellow = 103, Lime = 104, LimeGreen = 105, Linen = 106, Magenta = 107, Maroon = 108, MediumAquamarine = 109, MediumBlue = 110, MediumOrchid = 111, MediumPurple = 112, MediumSeaGreen = 113, MediumSlateBlue = 114, MediumSpringGreen = 115, MediumTurquoise = 116, MediumVioletRed = 117, Menu = 21, MenuBar = 173, MenuHighlight = 174, MenuText = 22, MidnightBlue = 118, MintCream = 119, MistyRose = 120, Moccasin = 121, NavajoWhite = 122, Navy = 123, OldLace = 124, Olive = 125, OliveDrab = 126, Orange = 127, OrangeRed = 128, Orchid = 129, PaleGoldenrod = 130, PaleGreen = 131, PaleTurquoise = 132, PaleVioletRed = 133, PapayaWhip = 134, PeachPuff = 135, Peru = 136, Pink = 137, Plum = 138, PowderBlue = 139, Purple = 140, Red = 141, RosyBrown = 142, RoyalBlue = 143, SaddleBrown = 144, Salmon = 145, SandyBrown = 146, ScrollBar = 23, SeaGreen = 147, SeaShell = 148, Sienna = 149, Silver = 150, SkyBlue = 151, SlateBlue = 152, SlateGray = 153, Snow = 154, SpringGreen = 155, SteelBlue = 156, Tan = 157, Teal = 158, Thistle = 159, Tomato = 160, Transparent = 27, Turquoise = 161, Violet = 162, Wheat = 163, White = 164, WhiteSmoke = 165, Window = 24, WindowFrame = 25, WindowText = 26, Yellow = 166, YellowGreen = 167, } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct Point { private int _dummy; public static readonly System.Drawing.Point Empty; public Point(System.Drawing.Size sz) { throw null; } public Point(int dw) { throw null; } public Point(int x, int y) { throw null; } [System.ComponentModel.BrowsableAttribute(false)] public bool IsEmpty { get { throw null; } } public int X { get { throw null; } set { } } public int Y { get { throw null; } set { } } public static System.Drawing.Point Add(System.Drawing.Point pt, System.Drawing.Size sz) { throw null; } public static System.Drawing.Point Ceiling(System.Drawing.PointF value) { throw null; } public override bool Equals(object obj) { throw null; } public override int GetHashCode() { throw null; } public void Offset(System.Drawing.Point p) { } public void Offset(int dx, int dy) { } public static System.Drawing.Point operator +(System.Drawing.Point pt, System.Drawing.Size sz) { throw null; } public static bool operator ==(System.Drawing.Point left, System.Drawing.Point right) { throw null; } public static explicit operator System.Drawing.Size (System.Drawing.Point p) { throw null; } public static implicit operator System.Drawing.PointF (System.Drawing.Point p) { throw null; } public static bool operator !=(System.Drawing.Point left, System.Drawing.Point right) { throw null; } public static System.Drawing.Point operator -(System.Drawing.Point pt, System.Drawing.Size sz) { throw null; } public static System.Drawing.Point Round(System.Drawing.PointF value) { throw null; } public static System.Drawing.Point Subtract(System.Drawing.Point pt, System.Drawing.Size sz) { throw null; } public override string ToString() { throw null; } public static System.Drawing.Point Truncate(System.Drawing.PointF value) { throw null; } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct PointF { private int _dummy; public static readonly System.Drawing.PointF Empty; public PointF(float x, float y) { throw null; } [System.ComponentModel.BrowsableAttribute(false)] public bool IsEmpty { get { throw null; } } public float X { get { throw null; } set { } } public float Y { get { throw null; } set { } } public static System.Drawing.PointF Add(System.Drawing.PointF pt, System.Drawing.Size sz) { throw null; } public static System.Drawing.PointF Add(System.Drawing.PointF pt, System.Drawing.SizeF sz) { throw null; } public override bool Equals(object obj) { throw null; } public override int GetHashCode() { throw null; } public static System.Drawing.PointF operator +(System.Drawing.PointF pt, System.Drawing.Size sz) { throw null; } public static System.Drawing.PointF operator +(System.Drawing.PointF pt, System.Drawing.SizeF sz) { throw null; } public static bool operator ==(System.Drawing.PointF left, System.Drawing.PointF right) { throw null; } public static bool operator !=(System.Drawing.PointF left, System.Drawing.PointF right) { throw null; } public static System.Drawing.PointF operator -(System.Drawing.PointF pt, System.Drawing.Size sz) { throw null; } public static System.Drawing.PointF operator -(System.Drawing.PointF pt, System.Drawing.SizeF sz) { throw null; } public static System.Drawing.PointF Subtract(System.Drawing.PointF pt, System.Drawing.Size sz) { throw null; } public static System.Drawing.PointF Subtract(System.Drawing.PointF pt, System.Drawing.SizeF sz) { throw null; } public override string ToString() { throw null; } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct Rectangle { private int _dummy; public static readonly System.Drawing.Rectangle Empty; public Rectangle(System.Drawing.Point location, System.Drawing.Size size) { throw null; } public Rectangle(int x, int y, int width, int height) { throw null; } [System.ComponentModel.BrowsableAttribute(false)] public int Bottom { get { throw null; } } public int Height { get { throw null; } set { } } [System.ComponentModel.BrowsableAttribute(false)] public bool IsEmpty { get { throw null; } } [System.ComponentModel.BrowsableAttribute(false)] public int Left { get { throw null; } } [System.ComponentModel.BrowsableAttribute(false)] public System.Drawing.Point Location { get { throw null; } set { } } [System.ComponentModel.BrowsableAttribute(false)] public int Right { get { throw null; } } [System.ComponentModel.BrowsableAttribute(false)] public System.Drawing.Size Size { get { throw null; } set { } } [System.ComponentModel.BrowsableAttribute(false)] public int Top { get { throw null; } } public int Width { get { throw null; } set { } } public int X { get { throw null; } set { } } public int Y { get { throw null; } set { } } public static System.Drawing.Rectangle Ceiling(System.Drawing.RectangleF value) { throw null; } public bool Contains(System.Drawing.Point pt) { throw null; } public bool Contains(System.Drawing.Rectangle rect) { throw null; } public bool Contains(int x, int y) { throw null; } public override bool Equals(object obj) { throw null; } public static System.Drawing.Rectangle FromLTRB(int left, int top, int right, int bottom) { throw null; } public override int GetHashCode() { throw null; } public static System.Drawing.Rectangle Inflate(System.Drawing.Rectangle rect, int x, int y) { throw null; } public void Inflate(System.Drawing.Size size) { } public void Inflate(int width, int height) { } public void Intersect(System.Drawing.Rectangle rect) { } public static System.Drawing.Rectangle Intersect(System.Drawing.Rectangle a, System.Drawing.Rectangle b) { throw null; } public bool IntersectsWith(System.Drawing.Rectangle rect) { throw null; } public void Offset(System.Drawing.Point pos) { } public void Offset(int x, int y) { } public static bool operator ==(System.Drawing.Rectangle left, System.Drawing.Rectangle right) { throw null; } public static bool operator !=(System.Drawing.Rectangle left, System.Drawing.Rectangle right) { throw null; } public static System.Drawing.Rectangle Round(System.Drawing.RectangleF value) { throw null; } public override string ToString() { throw null; } public static System.Drawing.Rectangle Truncate(System.Drawing.RectangleF value) { throw null; } public static System.Drawing.Rectangle Union(System.Drawing.Rectangle a, System.Drawing.Rectangle b) { throw null; } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct RectangleF { private int _dummy; public static readonly System.Drawing.RectangleF Empty; public RectangleF(System.Drawing.PointF location, System.Drawing.SizeF size) { throw null; } public RectangleF(float x, float y, float width, float height) { throw null; } [System.ComponentModel.BrowsableAttribute(false)] public float Bottom { get { throw null; } } public float Height { get { throw null; } set { } } [System.ComponentModel.BrowsableAttribute(false)] public bool IsEmpty { get { throw null; } } [System.ComponentModel.BrowsableAttribute(false)] public float Left { get { throw null; } } [System.ComponentModel.BrowsableAttribute(false)] public System.Drawing.PointF Location { get { throw null; } set { } } [System.ComponentModel.BrowsableAttribute(false)] public float Right { get { throw null; } } [System.ComponentModel.BrowsableAttribute(false)] public System.Drawing.SizeF Size { get { throw null; } set { } } [System.ComponentModel.BrowsableAttribute(false)] public float Top { get { throw null; } } public float Width { get { throw null; } set { } } public float X { get { throw null; } set { } } public float Y { get { throw null; } set { } } public bool Contains(System.Drawing.PointF pt) { throw null; } public bool Contains(System.Drawing.RectangleF rect) { throw null; } public bool Contains(float x, float y) { throw null; } public override bool Equals(object obj) { throw null; } public static System.Drawing.RectangleF FromLTRB(float left, float top, float right, float bottom) { throw null; } public override int GetHashCode() { throw null; } public static System.Drawing.RectangleF Inflate(System.Drawing.RectangleF rect, float x, float y) { throw null; } public void Inflate(System.Drawing.SizeF size) { } public void Inflate(float x, float y) { } public void Intersect(System.Drawing.RectangleF rect) { } public static System.Drawing.RectangleF Intersect(System.Drawing.RectangleF a, System.Drawing.RectangleF b) { throw null; } public bool IntersectsWith(System.Drawing.RectangleF rect) { throw null; } public void Offset(System.Drawing.PointF pos) { } public void Offset(float x, float y) { } public static bool operator ==(System.Drawing.RectangleF left, System.Drawing.RectangleF right) { throw null; } public static implicit operator System.Drawing.RectangleF (System.Drawing.Rectangle r) { throw null; } public static bool operator !=(System.Drawing.RectangleF left, System.Drawing.RectangleF right) { throw null; } public override string ToString() { throw null; } public static System.Drawing.RectangleF Union(System.Drawing.RectangleF a, System.Drawing.RectangleF b) { throw null; } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct Size { private int _dummy; public static readonly System.Drawing.Size Empty; public Size(System.Drawing.Point pt) { throw null; } public Size(int width, int height) { throw null; } public int Height { get { throw null; } set { } } [System.ComponentModel.BrowsableAttribute(false)] public bool IsEmpty { get { throw null; } } public int Width { get { throw null; } set { } } public static System.Drawing.Size Add(System.Drawing.Size sz1, System.Drawing.Size sz2) { throw null; } public static System.Drawing.Size Ceiling(System.Drawing.SizeF value) { throw null; } public override bool Equals(object obj) { throw null; } public override int GetHashCode() { throw null; } public static System.Drawing.Size operator +(System.Drawing.Size sz1, System.Drawing.Size sz2) { throw null; } public static bool operator ==(System.Drawing.Size sz1, System.Drawing.Size sz2) { throw null; } public static explicit operator System.Drawing.Point (System.Drawing.Size size) { throw null; } public static implicit operator System.Drawing.SizeF (System.Drawing.Size p) { throw null; } public static bool operator !=(System.Drawing.Size sz1, System.Drawing.Size sz2) { throw null; } public static System.Drawing.Size operator -(System.Drawing.Size sz1, System.Drawing.Size sz2) { throw null; } public static System.Drawing.Size Round(System.Drawing.SizeF value) { throw null; } public static System.Drawing.Size Subtract(System.Drawing.Size sz1, System.Drawing.Size sz2) { throw null; } public override string ToString() { throw null; } public static System.Drawing.Size Truncate(System.Drawing.SizeF value) { throw null; } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct SizeF { private int _dummy; public static readonly System.Drawing.SizeF Empty; public SizeF(System.Drawing.PointF pt) { throw null; } public SizeF(System.Drawing.SizeF size) { throw null; } public SizeF(float width, float height) { throw null; } public float Height { get { throw null; } set { } } [System.ComponentModel.BrowsableAttribute(false)] public bool IsEmpty { get { throw null; } } public float Width { get { throw null; } set { } } public static System.Drawing.SizeF Add(System.Drawing.SizeF sz1, System.Drawing.SizeF sz2) { throw null; } public override bool Equals(object obj) { throw null; } public override int GetHashCode() { throw null; } public static System.Drawing.SizeF operator +(System.Drawing.SizeF sz1, System.Drawing.SizeF sz2) { throw null; } public static bool operator ==(System.Drawing.SizeF sz1, System.Drawing.SizeF sz2) { throw null; } public static explicit operator System.Drawing.PointF (System.Drawing.SizeF size) { throw null; } public static bool operator !=(System.Drawing.SizeF sz1, System.Drawing.SizeF sz2) { throw null; } public static System.Drawing.SizeF operator -(System.Drawing.SizeF sz1, System.Drawing.SizeF sz2) { throw null; } public static System.Drawing.SizeF Subtract(System.Drawing.SizeF sz1, System.Drawing.SizeF sz2) { throw null; } public System.Drawing.PointF ToPointF() { throw null; } public System.Drawing.Size ToSize() { throw null; } public override string ToString() { throw null; } } }
/* * Copyright (C) 2010 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Text; namespace ZXing.Common { /// <summary> /// Common string-related functions. /// </summary> /// <author>Sean Owen</author> /// <author>Alex Dupre</author> public static class StringUtils { #if (WINDOWS_PHONE || SILVERLIGHT4 || SILVERLIGHT5 || NETFX_CORE || PORTABLE || NETSTANDARD) private const String PLATFORM_DEFAULT_ENCODING = "UTF-8"; #else private static String PLATFORM_DEFAULT_ENCODING = Encoding.Default.WebName; #endif /// <summary> /// SJIS /// </summary> public static String SHIFT_JIS = "SJIS"; /// <summary> /// GB2312 /// </summary> public static String GB2312 = "GB2312"; private const String EUC_JP = "EUC-JP"; private const String UTF8 = "UTF-8"; private const String ISO88591 = "ISO-8859-1"; private static readonly bool ASSUME_SHIFT_JIS = String.Compare(SHIFT_JIS, PLATFORM_DEFAULT_ENCODING, StringComparison.OrdinalIgnoreCase) == 0 || String.Compare(EUC_JP, PLATFORM_DEFAULT_ENCODING, StringComparison.OrdinalIgnoreCase) == 0; /// <summary> /// Guesses the encoding. /// </summary> /// <param name="bytes">bytes encoding a string, whose encoding should be guessed</param> /// <param name="hints">decode hints if applicable</param> /// <returns>name of guessed encoding; at the moment will only guess one of: /// {@link #SHIFT_JIS}, {@link #UTF8}, {@link #ISO88591}, or the platform /// default encoding if none of these can possibly be correct</returns> public static String guessEncoding(byte[] bytes, IDictionary<DecodeHintType, object> hints) { if (hints != null && hints.ContainsKey(DecodeHintType.CHARACTER_SET)) { String characterSet = (String)hints[DecodeHintType.CHARACTER_SET]; if (characterSet != null) { return characterSet; } } // For now, merely tries to distinguish ISO-8859-1, UTF-8 and Shift_JIS, // which should be by far the most common encodings. int length = bytes.Length; bool canBeISO88591 = true; bool canBeShiftJIS = true; bool canBeUTF8 = true; int utf8BytesLeft = 0; //int utf8LowChars = 0; int utf2BytesChars = 0; int utf3BytesChars = 0; int utf4BytesChars = 0; int sjisBytesLeft = 0; //int sjisLowChars = 0; int sjisKatakanaChars = 0; //int sjisDoubleBytesChars = 0; int sjisCurKatakanaWordLength = 0; int sjisCurDoubleBytesWordLength = 0; int sjisMaxKatakanaWordLength = 0; int sjisMaxDoubleBytesWordLength = 0; //int isoLowChars = 0; //int isoHighChars = 0; int isoHighOther = 0; bool utf8bom = bytes.Length > 3 && bytes[0] == 0xEF && bytes[1] == 0xBB && bytes[2] == 0xBF; for (int i = 0; i < length && (canBeISO88591 || canBeShiftJIS || canBeUTF8); i++) { int value = bytes[i] & 0xFF; // UTF-8 stuff if (canBeUTF8) { if (utf8BytesLeft > 0) { if ((value & 0x80) == 0) { canBeUTF8 = false; } else { utf8BytesLeft--; } } else if ((value & 0x80) != 0) { if ((value & 0x40) == 0) { canBeUTF8 = false; } else { utf8BytesLeft++; if ((value & 0x20) == 0) { utf2BytesChars++; } else { utf8BytesLeft++; if ((value & 0x10) == 0) { utf3BytesChars++; } else { utf8BytesLeft++; if ((value & 0x08) == 0) { utf4BytesChars++; } else { canBeUTF8 = false; } } } } } //else { //utf8LowChars++; //} } // ISO-8859-1 stuff if (canBeISO88591) { if (value > 0x7F && value < 0xA0) { canBeISO88591 = false; } else if (value > 0x9F) { if (value < 0xC0 || value == 0xD7 || value == 0xF7) { isoHighOther++; } //else { //isoHighChars++; //} } //else { //isoLowChars++; //} } // Shift_JIS stuff if (canBeShiftJIS) { if (sjisBytesLeft > 0) { if (value < 0x40 || value == 0x7F || value > 0xFC) { canBeShiftJIS = false; } else { sjisBytesLeft--; } } else if (value == 0x80 || value == 0xA0 || value > 0xEF) { canBeShiftJIS = false; } else if (value > 0xA0 && value < 0xE0) { sjisKatakanaChars++; sjisCurDoubleBytesWordLength = 0; sjisCurKatakanaWordLength++; if (sjisCurKatakanaWordLength > sjisMaxKatakanaWordLength) { sjisMaxKatakanaWordLength = sjisCurKatakanaWordLength; } } else if (value > 0x7F) { sjisBytesLeft++; //sjisDoubleBytesChars++; sjisCurKatakanaWordLength = 0; sjisCurDoubleBytesWordLength++; if (sjisCurDoubleBytesWordLength > sjisMaxDoubleBytesWordLength) { sjisMaxDoubleBytesWordLength = sjisCurDoubleBytesWordLength; } } else { //sjisLowChars++; sjisCurKatakanaWordLength = 0; sjisCurDoubleBytesWordLength = 0; } } } if (canBeUTF8 && utf8BytesLeft > 0) { canBeUTF8 = false; } if (canBeShiftJIS && sjisBytesLeft > 0) { canBeShiftJIS = false; } // Easy -- if there is BOM or at least 1 valid not-single byte character (and no evidence it can't be UTF-8), done if (canBeUTF8 && (utf8bom || utf2BytesChars + utf3BytesChars + utf4BytesChars > 0)) { return UTF8; } // Easy -- if assuming Shift_JIS or at least 3 valid consecutive not-ascii characters (and no evidence it can't be), done if (canBeShiftJIS && (ASSUME_SHIFT_JIS || sjisMaxKatakanaWordLength >= 3 || sjisMaxDoubleBytesWordLength >= 3)) { return SHIFT_JIS; } // Distinguishing Shift_JIS and ISO-8859-1 can be a little tough for short words. The crude heuristic is: // - If we saw // - only two consecutive katakana chars in the whole text, or // - at least 10% of bytes that could be "upper" not-alphanumeric Latin1, // - then we conclude Shift_JIS, else ISO-8859-1 if (canBeISO88591 && canBeShiftJIS) { return (sjisMaxKatakanaWordLength == 2 && sjisKatakanaChars == 2) || isoHighOther * 10 >= length ? SHIFT_JIS : ISO88591; } // Otherwise, try in order ISO-8859-1, Shift JIS, UTF-8 and fall back to default platform encoding if (canBeISO88591) { return ISO88591; } if (canBeShiftJIS) { return SHIFT_JIS; } if (canBeUTF8) { return UTF8; } // Otherwise, we take a wild guess with platform encoding return PLATFORM_DEFAULT_ENCODING; } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="WorldEntered.cs" company="Exit Games GmbH"> // Copyright (c) Exit Games GmbH. All rights reserved. // </copyright> // <summary> // The dispatcher world entered. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace Photon.MmoDemo.Client.GameStateStrategies { using System; using System.Collections; using System.Collections.Generic; using ExitGames.Client.Photon; using Photon.MmoDemo.Common; /// <summary> /// The dispatcher world entered. /// </summary> [CLSCompliant(false)] public class WorldEntered : IGameLogicStrategy { /// <summary> /// The instance. /// </summary> public static readonly IGameLogicStrategy Instance = new WorldEntered(); /// <summary> /// Gets State. /// </summary> public GameState State { get { return GameState.WorldEntered; } } #region Implemented Interfaces #region IGameLogicStrategy /// <summary> /// The on event receive. /// </summary> /// <param name="game"> /// The mmo game. /// </param> /// <param name="eventData"> /// The event data. /// </param> public void OnEventReceive(Game game, EventData eventData) { switch ((EventCode)eventData.Code) { case EventCode.RadarUpdate: { HandleEventRadarUpdate(eventData.Parameters, game); return; } case EventCode.ItemMoved: { HandleEventItemMoved(game, eventData.Parameters); return; } case EventCode.ItemDestroyed: { HandleEventItemDestroyed(game, eventData.Parameters); return; } case EventCode.ItemProperties: { HandleEventItemProperties(game, eventData.Parameters); return; } case EventCode.ItemPropertiesSet: { HandleEventItemPropertiesSet(game, eventData.Parameters); return; } case EventCode.ItemSubscribed: { HandleEventItemSubscribed(game, eventData.Parameters); return; } case EventCode.ItemUnsubscribed: { HandleEventItemUnsubscribed(game, eventData.Parameters); return; } case EventCode.WorldExited: { game.SetConnected(); return; } } game.OnUnexpectedEventReceive(eventData); } /// <summary> /// The on operation return. /// </summary> /// <param name="game"> /// The mmo game. /// </param> /// <param name="response"> /// The operation response. /// </param> public void OnOperationReturn(Game game, OperationResponse response) { if (response.ReturnCode == 0) { switch ((OperationCode)response.OperationCode) { case OperationCode.RemoveInterestArea: case OperationCode.AddInterestArea: { return; } case OperationCode.AttachInterestArea: { HandleEventInterestAreaAttached(game, response.Parameters); return; } case OperationCode.DetachInterestArea: { HandleEventInterestAreaDetached(game); return; } case OperationCode.SpawnItem: { HandleEventItemSpawned(game, response.Parameters); return; } case OperationCode.RadarSubscribe: { return; } } } game.OnUnexpectedOperationError(response); } /// <summary> /// The on peer status callback. /// </summary> /// <param name="game"> /// The mmo game. /// </param> /// <param name="returnCode"> /// The return code. /// </param> public void OnPeerStatusCallback(Game game, StatusCode returnCode) { switch (returnCode) { case StatusCode.Disconnect: case StatusCode.DisconnectByServer: case StatusCode.DisconnectByServerLogic: case StatusCode.DisconnectByServerUserLimit: case StatusCode.TimeoutDisconnect: { game.SetDisconnected(returnCode); break; } default: { game.DebugReturn(DebugLevel.ERROR, returnCode.ToString()); break; } } } /// <summary> /// The on update. /// </summary> /// <param name="game"> /// The game logic. /// </param> public void OnUpdate(Game game) { game.Peer.Service(); } /// <summary> /// The send operation. /// </summary> /// <param name="game"> /// The mmo game. /// </param> /// <param name="operationCode"> /// The operation code. /// </param> /// <param name="parameter"> /// The parameter. /// </param> /// <param name="sendReliable"> /// The send reliable. /// </param> /// <param name="channelId"> /// The channel Id. /// </param> public void SendOperation(Game game, OperationCode operationCode, Dictionary<byte, object> parameter, bool sendReliable, byte channelId) { game.Peer.OpCustom((byte)operationCode, parameter, sendReliable, channelId); } #endregion #endregion /// <summary> /// The handle event interest area attached. /// </summary> /// <param name="game"> /// The mmo game. /// </param> /// <param name="eventData"> /// The event data. /// </param> private static void HandleEventInterestAreaAttached(Game game, IDictionary eventData) { var itemType = (byte)eventData[(byte)ParameterCode.ItemType]; var itemId = (string)eventData[(byte)ParameterCode.ItemId]; game.OnCameraAttached(itemId, itemType); } /// <summary> /// The handle event interest area detached. /// </summary> /// <param name="game"> /// The mmo game. /// </param> private static void HandleEventInterestAreaDetached(Game game) { game.OnCameraDetached(); } /// <summary> /// The handle event item destroyed. /// </summary> /// <param name="game"> /// The mmo game. /// </param> /// <param name="eventData"> /// The event data. /// </param> private static void HandleEventItemDestroyed(Game game, IDictionary eventData) { var itemType = (byte)eventData[(byte)ParameterCode.ItemType]; var itemId = (string)eventData[(byte)ParameterCode.ItemId]; Item item; if (game.TryGetItem(itemType, itemId, out item)) { item.IsDestroyed = game.RemoveItem(item); } } /// <summary> /// The handle event item moved. /// </summary> /// <param name="game"> /// The mmo game. /// </param> /// <param name="eventData"> /// The event data. /// </param> private static void HandleEventItemMoved(Game game, IDictionary eventData) { var itemType = (byte)eventData[(byte)ParameterCode.ItemType]; var itemId = (string)eventData[(byte)ParameterCode.ItemId]; Item item; if (game.TryGetItem(itemType, itemId, out item)) { if (item.IsMine == false) { var position = (float[])eventData[(byte)ParameterCode.Position]; var oldPosition = (float[])eventData[(byte)ParameterCode.OldPosition]; float[] rotation = eventData.Contains((byte)ParameterCode.Rotation) ? (float[])eventData[(byte)ParameterCode.Rotation] : null; float[] oldRotation = eventData.Contains((byte)ParameterCode.OldRotation) ? (float[])eventData[(byte)ParameterCode.OldRotation] : null; item.SetPositions(position, oldPosition, rotation, oldRotation); } } } /// <summary> /// The handle event item properties. /// </summary> /// <param name="game"> /// The mmo game. /// </param> /// <param name="eventData"> /// The event data. /// </param> private static void HandleEventItemProperties(Game game, IDictionary eventData) { var itemType = (byte)eventData[(byte)ParameterCode.ItemType]; var itemId = (string)eventData[(byte)ParameterCode.ItemId]; Item item; if (game.TryGetItem(itemType, itemId, out item)) { item.PropertyRevision = (int)eventData[(byte)ParameterCode.PropertiesRevision]; if (item.IsMine == false) { var propertiesSet = (Hashtable)eventData[(byte)ParameterCode.PropertiesSet]; item.SetColor((int)propertiesSet[Item.PropertyKeyColor]); item.SetText((string)propertiesSet[Item.PropertyKeyText]); item.SetInterestAreaAttached((bool)propertiesSet[Item.PropertyKeyInterestAreaAttached]); item.SetInterestAreaViewDistance( (float[])propertiesSet[Item.PropertyKeyViewDistanceEnter], (float[])propertiesSet[Item.PropertyKeyViewDistanceExit]); item.MakeVisibleToSubscribedInterestAreas(); } } } /// <summary> /// The handle event item properties set. /// </summary> /// <param name="game"> /// The mmo game. /// </param> /// <param name="eventData"> /// The event data. /// </param> private static void HandleEventItemPropertiesSet(Game game, IDictionary eventData) { var itemType = (byte)eventData[(byte)ParameterCode.ItemType]; var itemId = (string)eventData[(byte)ParameterCode.ItemId]; Item item; if (game.TryGetItem(itemType, itemId, out item)) { item.PropertyRevision = (int)eventData[(byte)ParameterCode.PropertiesRevision]; if (item.IsMine == false) { var propertiesSet = (Hashtable)eventData[(byte)ParameterCode.PropertiesSet]; if (propertiesSet.ContainsKey(Item.PropertyKeyColor)) { item.SetColor((int)propertiesSet[Item.PropertyKeyColor]); } if (propertiesSet.ContainsKey(Item.PropertyKeyText)) { item.SetText((string)propertiesSet[Item.PropertyKeyText]); } if (propertiesSet.ContainsKey(Item.PropertyKeyViewDistanceEnter)) { var viewDistanceEnter = (float[])propertiesSet[Item.PropertyKeyViewDistanceEnter]; item.SetInterestAreaViewDistance(viewDistanceEnter, (float[])propertiesSet[Item.PropertyKeyViewDistanceExit]); } if (propertiesSet.ContainsKey(Item.PropertyKeyInterestAreaAttached)) { item.SetInterestAreaAttached((bool)propertiesSet[Item.PropertyKeyInterestAreaAttached]); } } } } /// <summary> /// The handle event item spawned. /// </summary> /// <param name="game"> /// The mmo game. /// </param> /// <param name="eventData"> /// The event data. /// </param> private static void HandleEventItemSpawned(Game game, IDictionary eventData) { var itemType = (byte)eventData[(byte)ParameterCode.ItemType]; var itemId = (string)eventData[(byte)ParameterCode.ItemId]; game.OnItemSpawned(itemType, itemId); } /// <summary> /// The handle event item subscribed. /// </summary> /// <param name="game"> /// The mmo game. /// </param> /// <param name="eventData"> /// The event data. /// </param> private static void HandleEventItemSubscribed(Game game, IDictionary eventData) { var itemType = (byte)eventData[(byte)ParameterCode.ItemType]; var itemId = (string)eventData[(byte)ParameterCode.ItemId]; var position = (float[])eventData[(byte)ParameterCode.Position]; var cameraId = (byte)eventData[(byte)ParameterCode.InterestAreaId]; float[] rotation = eventData.Contains((byte)ParameterCode.Rotation) ? (float[])eventData[(byte)ParameterCode.Rotation] : null; Item item; if (game.TryGetItem(itemType, itemId, out item)) { if (item.IsMine) { item.AddSubscribedInterestArea(cameraId); item.AddVisibleInterestArea(cameraId); } else { var revision = (int)eventData[(byte)ParameterCode.PropertiesRevision]; if (revision == item.PropertyRevision) { item.AddSubscribedInterestArea(cameraId); item.AddVisibleInterestArea(cameraId); } else { item.AddSubscribedInterestArea(cameraId); item.GetProperties(); } item.SetPositions(position, position, rotation, rotation); } } else { item = new ForeignItem(itemId, itemType, game); item.SetPositions(position, position, rotation, rotation); game.AddItem(item); item.AddSubscribedInterestArea(cameraId); item.GetProperties(); } } /// <summary> /// The handle event item unsubscribed. /// </summary> /// <param name="game"> /// The mmo game. /// </param> /// <param name="eventData"> /// The event data. /// </param> private static void HandleEventItemUnsubscribed(Game game, IDictionary eventData) { var itemType = (byte)eventData[(byte)ParameterCode.ItemType]; var itemId = (string)eventData[(byte)ParameterCode.ItemId]; var cameraId = (byte)eventData[(byte)ParameterCode.InterestAreaId]; Item item; if (game.TryGetItem(itemType, itemId, out item)) { if (item.RemoveSubscribedInterestArea(cameraId)) { item.RemoveVisibleInterestArea(cameraId); } } } /// <summary> /// The handle event radar update. /// </summary> /// <param name="eventData"> /// The event data. /// </param> /// <param name="game"> /// The mmo game. /// </param> private static void HandleEventRadarUpdate(IDictionary eventData, Game game) { var itemId = (string)eventData[(byte)ParameterCode.ItemId]; var itemType = (byte)eventData[(byte)ParameterCode.ItemType]; var position = (float[])eventData[(byte)ParameterCode.Position]; game.Listener.OnRadarUpdate(itemId, itemType, position); } } }
/* * Infoplus API * * Infoplus API. * * OpenAPI spec version: v1.0 * Contact: api@infopluscommerce.com * Generated by: https://github.com/swagger-api/swagger-codegen.git * * 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.Collections.ObjectModel; using System.Linq; using RestSharp; using Infoplus.Client; using Infoplus.Model; namespace Infoplus.Api { /// <summary> /// Represents a collection of functions to interact with the API endpoints /// </summary> public interface IFulfillmentPlanApi : IApiAccessor { #region Synchronous Operations /// <summary> /// Create a fulfillmentPlan /// </summary> /// <remarks> /// Inserts a new fulfillmentPlan using the specified data. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body">FulfillmentPlan to be inserted.</param> /// <returns>FulfillmentPlan</returns> FulfillmentPlan AddFulfillmentPlan (FulfillmentPlan body); /// <summary> /// Create a fulfillmentPlan /// </summary> /// <remarks> /// Inserts a new fulfillmentPlan using the specified data. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body">FulfillmentPlan to be inserted.</param> /// <returns>ApiResponse of FulfillmentPlan</returns> ApiResponse<FulfillmentPlan> AddFulfillmentPlanWithHttpInfo (FulfillmentPlan body); /// <summary> /// Delete a fulfillmentPlan /// </summary> /// <remarks> /// Deletes the fulfillmentPlan identified by the specified id. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="fulfillmentPlanId">Id of the fulfillmentPlan to be deleted.</param> /// <returns></returns> void DeleteFulfillmentPlan (int? fulfillmentPlanId); /// <summary> /// Delete a fulfillmentPlan /// </summary> /// <remarks> /// Deletes the fulfillmentPlan identified by the specified id. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="fulfillmentPlanId">Id of the fulfillmentPlan to be deleted.</param> /// <returns>ApiResponse of Object(void)</returns> ApiResponse<Object> DeleteFulfillmentPlanWithHttpInfo (int? fulfillmentPlanId); /// <summary> /// Search fulfillmentPlans by filter /// </summary> /// <remarks> /// Returns the list of fulfillmentPlans that match the given filter. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="filter">Query string, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <param name="sort">Sort results by specified field. (optional)</param> /// <returns>List&lt;FulfillmentPlan&gt;</returns> List<FulfillmentPlan> GetFulfillmentPlanByFilter (string filter = null, int? page = null, int? limit = null, string sort = null); /// <summary> /// Search fulfillmentPlans by filter /// </summary> /// <remarks> /// Returns the list of fulfillmentPlans that match the given filter. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="filter">Query string, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <param name="sort">Sort results by specified field. (optional)</param> /// <returns>ApiResponse of List&lt;FulfillmentPlan&gt;</returns> ApiResponse<List<FulfillmentPlan>> GetFulfillmentPlanByFilterWithHttpInfo (string filter = null, int? page = null, int? limit = null, string sort = null); /// <summary> /// Get a fulfillmentPlan by id /// </summary> /// <remarks> /// Returns the fulfillmentPlan identified by the specified id. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="fulfillmentPlanId">Id of the fulfillmentPlan to be returned.</param> /// <returns>FulfillmentPlan</returns> FulfillmentPlan GetFulfillmentPlanById (int? fulfillmentPlanId); /// <summary> /// Get a fulfillmentPlan by id /// </summary> /// <remarks> /// Returns the fulfillmentPlan identified by the specified id. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="fulfillmentPlanId">Id of the fulfillmentPlan to be returned.</param> /// <returns>ApiResponse of FulfillmentPlan</returns> ApiResponse<FulfillmentPlan> GetFulfillmentPlanByIdWithHttpInfo (int? fulfillmentPlanId); /// <summary> /// Update a fulfillmentPlan /// </summary> /// <remarks> /// Updates an existing fulfillmentPlan using the specified data. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body">FulfillmentPlan to be updated.</param> /// <returns></returns> void UpdateFulfillmentPlan (FulfillmentPlan body); /// <summary> /// Update a fulfillmentPlan /// </summary> /// <remarks> /// Updates an existing fulfillmentPlan using the specified data. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body">FulfillmentPlan to be updated.</param> /// <returns>ApiResponse of Object(void)</returns> ApiResponse<Object> UpdateFulfillmentPlanWithHttpInfo (FulfillmentPlan body); #endregion Synchronous Operations #region Asynchronous Operations /// <summary> /// Create a fulfillmentPlan /// </summary> /// <remarks> /// Inserts a new fulfillmentPlan using the specified data. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body">FulfillmentPlan to be inserted.</param> /// <returns>Task of FulfillmentPlan</returns> System.Threading.Tasks.Task<FulfillmentPlan> AddFulfillmentPlanAsync (FulfillmentPlan body); /// <summary> /// Create a fulfillmentPlan /// </summary> /// <remarks> /// Inserts a new fulfillmentPlan using the specified data. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body">FulfillmentPlan to be inserted.</param> /// <returns>Task of ApiResponse (FulfillmentPlan)</returns> System.Threading.Tasks.Task<ApiResponse<FulfillmentPlan>> AddFulfillmentPlanAsyncWithHttpInfo (FulfillmentPlan body); /// <summary> /// Delete a fulfillmentPlan /// </summary> /// <remarks> /// Deletes the fulfillmentPlan identified by the specified id. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="fulfillmentPlanId">Id of the fulfillmentPlan to be deleted.</param> /// <returns>Task of void</returns> System.Threading.Tasks.Task DeleteFulfillmentPlanAsync (int? fulfillmentPlanId); /// <summary> /// Delete a fulfillmentPlan /// </summary> /// <remarks> /// Deletes the fulfillmentPlan identified by the specified id. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="fulfillmentPlanId">Id of the fulfillmentPlan to be deleted.</param> /// <returns>Task of ApiResponse</returns> System.Threading.Tasks.Task<ApiResponse<Object>> DeleteFulfillmentPlanAsyncWithHttpInfo (int? fulfillmentPlanId); /// <summary> /// Search fulfillmentPlans by filter /// </summary> /// <remarks> /// Returns the list of fulfillmentPlans that match the given filter. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="filter">Query string, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <param name="sort">Sort results by specified field. (optional)</param> /// <returns>Task of List&lt;FulfillmentPlan&gt;</returns> System.Threading.Tasks.Task<List<FulfillmentPlan>> GetFulfillmentPlanByFilterAsync (string filter = null, int? page = null, int? limit = null, string sort = null); /// <summary> /// Search fulfillmentPlans by filter /// </summary> /// <remarks> /// Returns the list of fulfillmentPlans that match the given filter. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="filter">Query string, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <param name="sort">Sort results by specified field. (optional)</param> /// <returns>Task of ApiResponse (List&lt;FulfillmentPlan&gt;)</returns> System.Threading.Tasks.Task<ApiResponse<List<FulfillmentPlan>>> GetFulfillmentPlanByFilterAsyncWithHttpInfo (string filter = null, int? page = null, int? limit = null, string sort = null); /// <summary> /// Get a fulfillmentPlan by id /// </summary> /// <remarks> /// Returns the fulfillmentPlan identified by the specified id. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="fulfillmentPlanId">Id of the fulfillmentPlan to be returned.</param> /// <returns>Task of FulfillmentPlan</returns> System.Threading.Tasks.Task<FulfillmentPlan> GetFulfillmentPlanByIdAsync (int? fulfillmentPlanId); /// <summary> /// Get a fulfillmentPlan by id /// </summary> /// <remarks> /// Returns the fulfillmentPlan identified by the specified id. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="fulfillmentPlanId">Id of the fulfillmentPlan to be returned.</param> /// <returns>Task of ApiResponse (FulfillmentPlan)</returns> System.Threading.Tasks.Task<ApiResponse<FulfillmentPlan>> GetFulfillmentPlanByIdAsyncWithHttpInfo (int? fulfillmentPlanId); /// <summary> /// Update a fulfillmentPlan /// </summary> /// <remarks> /// Updates an existing fulfillmentPlan using the specified data. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body">FulfillmentPlan to be updated.</param> /// <returns>Task of void</returns> System.Threading.Tasks.Task UpdateFulfillmentPlanAsync (FulfillmentPlan body); /// <summary> /// Update a fulfillmentPlan /// </summary> /// <remarks> /// Updates an existing fulfillmentPlan using the specified data. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body">FulfillmentPlan to be updated.</param> /// <returns>Task of ApiResponse</returns> System.Threading.Tasks.Task<ApiResponse<Object>> UpdateFulfillmentPlanAsyncWithHttpInfo (FulfillmentPlan body); #endregion Asynchronous Operations } /// <summary> /// Represents a collection of functions to interact with the API endpoints /// </summary> public partial class FulfillmentPlanApi : IFulfillmentPlanApi { private Infoplus.Client.ExceptionFactory _exceptionFactory = (name, response) => null; /// <summary> /// Initializes a new instance of the <see cref="FulfillmentPlanApi"/> class. /// </summary> /// <returns></returns> public FulfillmentPlanApi(String basePath) { this.Configuration = new Configuration(new ApiClient(basePath)); ExceptionFactory = Infoplus.Client.Configuration.DefaultExceptionFactory; // ensure API client has configuration ready if (Configuration.ApiClient.Configuration == null) { this.Configuration.ApiClient.Configuration = this.Configuration; } } /// <summary> /// Initializes a new instance of the <see cref="FulfillmentPlanApi"/> class /// using Configuration object /// </summary> /// <param name="configuration">An instance of Configuration</param> /// <returns></returns> public FulfillmentPlanApi(Configuration configuration = null) { if (configuration == null) // use the default one in Configuration this.Configuration = Configuration.Default; else this.Configuration = configuration; ExceptionFactory = Infoplus.Client.Configuration.DefaultExceptionFactory; // ensure API client has configuration ready if (Configuration.ApiClient.Configuration == null) { this.Configuration.ApiClient.Configuration = this.Configuration; } } /// <summary> /// Gets the base path of the API client. /// </summary> /// <value>The base path</value> public String GetBasePath() { return this.Configuration.ApiClient.RestClient.BaseUrl.ToString(); } /// <summary> /// Sets the base path of the API client. /// </summary> /// <value>The base path</value> [Obsolete("SetBasePath is deprecated, please do 'Configuration.ApiClient = new ApiClient(\"http://new-path\")' instead.")] public void SetBasePath(String basePath) { // do nothing } /// <summary> /// Gets or sets the configuration object /// </summary> /// <value>An instance of the Configuration</value> public Configuration Configuration {get; set;} /// <summary> /// Provides a factory method hook for the creation of exceptions. /// </summary> public Infoplus.Client.ExceptionFactory ExceptionFactory { get { if (_exceptionFactory != null && _exceptionFactory.GetInvocationList().Length > 1) { throw new InvalidOperationException("Multicast delegate for ExceptionFactory is unsupported."); } return _exceptionFactory; } set { _exceptionFactory = value; } } /// <summary> /// Gets the default header. /// </summary> /// <returns>Dictionary of HTTP header</returns> [Obsolete("DefaultHeader is deprecated, please use Configuration.DefaultHeader instead.")] public Dictionary<String, String> DefaultHeader() { return this.Configuration.DefaultHeader; } /// <summary> /// Add default header. /// </summary> /// <param name="key">Header field name.</param> /// <param name="value">Header field value.</param> /// <returns></returns> [Obsolete("AddDefaultHeader is deprecated, please use Configuration.AddDefaultHeader instead.")] public void AddDefaultHeader(string key, string value) { this.Configuration.AddDefaultHeader(key, value); } /// <summary> /// Create a fulfillmentPlan Inserts a new fulfillmentPlan using the specified data. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body">FulfillmentPlan to be inserted.</param> /// <returns>FulfillmentPlan</returns> public FulfillmentPlan AddFulfillmentPlan (FulfillmentPlan body) { ApiResponse<FulfillmentPlan> localVarResponse = AddFulfillmentPlanWithHttpInfo(body); return localVarResponse.Data; } /// <summary> /// Create a fulfillmentPlan Inserts a new fulfillmentPlan using the specified data. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body">FulfillmentPlan to be inserted.</param> /// <returns>ApiResponse of FulfillmentPlan</returns> public ApiResponse< FulfillmentPlan > AddFulfillmentPlanWithHttpInfo (FulfillmentPlan body) { // verify the required parameter 'body' is set if (body == null) throw new ApiException(400, "Missing required parameter 'body' when calling FulfillmentPlanApi->AddFulfillmentPlan"); var localVarPath = "/v1.0/fulfillmentPlan"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { "application/json" }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (body != null && body.GetType() != typeof(byte[])) { localVarPostBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter } else { localVarPostBody = body; // byte array } // authentication (api_key) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key"))) { localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("AddFulfillmentPlan", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<FulfillmentPlan>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (FulfillmentPlan) Configuration.ApiClient.Deserialize(localVarResponse, typeof(FulfillmentPlan))); } /// <summary> /// Create a fulfillmentPlan Inserts a new fulfillmentPlan using the specified data. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body">FulfillmentPlan to be inserted.</param> /// <returns>Task of FulfillmentPlan</returns> public async System.Threading.Tasks.Task<FulfillmentPlan> AddFulfillmentPlanAsync (FulfillmentPlan body) { ApiResponse<FulfillmentPlan> localVarResponse = await AddFulfillmentPlanAsyncWithHttpInfo(body); return localVarResponse.Data; } /// <summary> /// Create a fulfillmentPlan Inserts a new fulfillmentPlan using the specified data. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body">FulfillmentPlan to be inserted.</param> /// <returns>Task of ApiResponse (FulfillmentPlan)</returns> public async System.Threading.Tasks.Task<ApiResponse<FulfillmentPlan>> AddFulfillmentPlanAsyncWithHttpInfo (FulfillmentPlan body) { // verify the required parameter 'body' is set if (body == null) throw new ApiException(400, "Missing required parameter 'body' when calling FulfillmentPlanApi->AddFulfillmentPlan"); var localVarPath = "/v1.0/fulfillmentPlan"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { "application/json" }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (body != null && body.GetType() != typeof(byte[])) { localVarPostBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter } else { localVarPostBody = body; // byte array } // authentication (api_key) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key"))) { localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath, Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("AddFulfillmentPlan", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<FulfillmentPlan>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (FulfillmentPlan) Configuration.ApiClient.Deserialize(localVarResponse, typeof(FulfillmentPlan))); } /// <summary> /// Delete a fulfillmentPlan Deletes the fulfillmentPlan identified by the specified id. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="fulfillmentPlanId">Id of the fulfillmentPlan to be deleted.</param> /// <returns></returns> public void DeleteFulfillmentPlan (int? fulfillmentPlanId) { DeleteFulfillmentPlanWithHttpInfo(fulfillmentPlanId); } /// <summary> /// Delete a fulfillmentPlan Deletes the fulfillmentPlan identified by the specified id. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="fulfillmentPlanId">Id of the fulfillmentPlan to be deleted.</param> /// <returns>ApiResponse of Object(void)</returns> public ApiResponse<Object> DeleteFulfillmentPlanWithHttpInfo (int? fulfillmentPlanId) { // verify the required parameter 'fulfillmentPlanId' is set if (fulfillmentPlanId == null) throw new ApiException(400, "Missing required parameter 'fulfillmentPlanId' when calling FulfillmentPlanApi->DeleteFulfillmentPlan"); var localVarPath = "/v1.0/fulfillmentPlan/{fulfillmentPlanId}"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (fulfillmentPlanId != null) localVarPathParams.Add("fulfillmentPlanId", Configuration.ApiClient.ParameterToString(fulfillmentPlanId)); // path parameter // authentication (api_key) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key"))) { localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, Method.DELETE, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("DeleteFulfillmentPlan", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<Object>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), null); } /// <summary> /// Delete a fulfillmentPlan Deletes the fulfillmentPlan identified by the specified id. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="fulfillmentPlanId">Id of the fulfillmentPlan to be deleted.</param> /// <returns>Task of void</returns> public async System.Threading.Tasks.Task DeleteFulfillmentPlanAsync (int? fulfillmentPlanId) { await DeleteFulfillmentPlanAsyncWithHttpInfo(fulfillmentPlanId); } /// <summary> /// Delete a fulfillmentPlan Deletes the fulfillmentPlan identified by the specified id. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="fulfillmentPlanId">Id of the fulfillmentPlan to be deleted.</param> /// <returns>Task of ApiResponse</returns> public async System.Threading.Tasks.Task<ApiResponse<Object>> DeleteFulfillmentPlanAsyncWithHttpInfo (int? fulfillmentPlanId) { // verify the required parameter 'fulfillmentPlanId' is set if (fulfillmentPlanId == null) throw new ApiException(400, "Missing required parameter 'fulfillmentPlanId' when calling FulfillmentPlanApi->DeleteFulfillmentPlan"); var localVarPath = "/v1.0/fulfillmentPlan/{fulfillmentPlanId}"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (fulfillmentPlanId != null) localVarPathParams.Add("fulfillmentPlanId", Configuration.ApiClient.ParameterToString(fulfillmentPlanId)); // path parameter // authentication (api_key) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key"))) { localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath, Method.DELETE, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("DeleteFulfillmentPlan", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<Object>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), null); } /// <summary> /// Search fulfillmentPlans by filter Returns the list of fulfillmentPlans that match the given filter. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="filter">Query string, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <param name="sort">Sort results by specified field. (optional)</param> /// <returns>List&lt;FulfillmentPlan&gt;</returns> public List<FulfillmentPlan> GetFulfillmentPlanByFilter (string filter = null, int? page = null, int? limit = null, string sort = null) { ApiResponse<List<FulfillmentPlan>> localVarResponse = GetFulfillmentPlanByFilterWithHttpInfo(filter, page, limit, sort); return localVarResponse.Data; } /// <summary> /// Search fulfillmentPlans by filter Returns the list of fulfillmentPlans that match the given filter. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="filter">Query string, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <param name="sort">Sort results by specified field. (optional)</param> /// <returns>ApiResponse of List&lt;FulfillmentPlan&gt;</returns> public ApiResponse< List<FulfillmentPlan> > GetFulfillmentPlanByFilterWithHttpInfo (string filter = null, int? page = null, int? limit = null, string sort = null) { var localVarPath = "/v1.0/fulfillmentPlan/search"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (filter != null) localVarQueryParams.Add("filter", Configuration.ApiClient.ParameterToString(filter)); // query parameter if (page != null) localVarQueryParams.Add("page", Configuration.ApiClient.ParameterToString(page)); // query parameter if (limit != null) localVarQueryParams.Add("limit", Configuration.ApiClient.ParameterToString(limit)); // query parameter if (sort != null) localVarQueryParams.Add("sort", Configuration.ApiClient.ParameterToString(sort)); // query parameter // authentication (api_key) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key"))) { localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("GetFulfillmentPlanByFilter", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<List<FulfillmentPlan>>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (List<FulfillmentPlan>) Configuration.ApiClient.Deserialize(localVarResponse, typeof(List<FulfillmentPlan>))); } /// <summary> /// Search fulfillmentPlans by filter Returns the list of fulfillmentPlans that match the given filter. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="filter">Query string, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <param name="sort">Sort results by specified field. (optional)</param> /// <returns>Task of List&lt;FulfillmentPlan&gt;</returns> public async System.Threading.Tasks.Task<List<FulfillmentPlan>> GetFulfillmentPlanByFilterAsync (string filter = null, int? page = null, int? limit = null, string sort = null) { ApiResponse<List<FulfillmentPlan>> localVarResponse = await GetFulfillmentPlanByFilterAsyncWithHttpInfo(filter, page, limit, sort); return localVarResponse.Data; } /// <summary> /// Search fulfillmentPlans by filter Returns the list of fulfillmentPlans that match the given filter. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="filter">Query string, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <param name="sort">Sort results by specified field. (optional)</param> /// <returns>Task of ApiResponse (List&lt;FulfillmentPlan&gt;)</returns> public async System.Threading.Tasks.Task<ApiResponse<List<FulfillmentPlan>>> GetFulfillmentPlanByFilterAsyncWithHttpInfo (string filter = null, int? page = null, int? limit = null, string sort = null) { var localVarPath = "/v1.0/fulfillmentPlan/search"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (filter != null) localVarQueryParams.Add("filter", Configuration.ApiClient.ParameterToString(filter)); // query parameter if (page != null) localVarQueryParams.Add("page", Configuration.ApiClient.ParameterToString(page)); // query parameter if (limit != null) localVarQueryParams.Add("limit", Configuration.ApiClient.ParameterToString(limit)); // query parameter if (sort != null) localVarQueryParams.Add("sort", Configuration.ApiClient.ParameterToString(sort)); // query parameter // authentication (api_key) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key"))) { localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath, Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("GetFulfillmentPlanByFilter", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<List<FulfillmentPlan>>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (List<FulfillmentPlan>) Configuration.ApiClient.Deserialize(localVarResponse, typeof(List<FulfillmentPlan>))); } /// <summary> /// Get a fulfillmentPlan by id Returns the fulfillmentPlan identified by the specified id. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="fulfillmentPlanId">Id of the fulfillmentPlan to be returned.</param> /// <returns>FulfillmentPlan</returns> public FulfillmentPlan GetFulfillmentPlanById (int? fulfillmentPlanId) { ApiResponse<FulfillmentPlan> localVarResponse = GetFulfillmentPlanByIdWithHttpInfo(fulfillmentPlanId); return localVarResponse.Data; } /// <summary> /// Get a fulfillmentPlan by id Returns the fulfillmentPlan identified by the specified id. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="fulfillmentPlanId">Id of the fulfillmentPlan to be returned.</param> /// <returns>ApiResponse of FulfillmentPlan</returns> public ApiResponse< FulfillmentPlan > GetFulfillmentPlanByIdWithHttpInfo (int? fulfillmentPlanId) { // verify the required parameter 'fulfillmentPlanId' is set if (fulfillmentPlanId == null) throw new ApiException(400, "Missing required parameter 'fulfillmentPlanId' when calling FulfillmentPlanApi->GetFulfillmentPlanById"); var localVarPath = "/v1.0/fulfillmentPlan/{fulfillmentPlanId}"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (fulfillmentPlanId != null) localVarPathParams.Add("fulfillmentPlanId", Configuration.ApiClient.ParameterToString(fulfillmentPlanId)); // path parameter // authentication (api_key) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key"))) { localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("GetFulfillmentPlanById", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<FulfillmentPlan>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (FulfillmentPlan) Configuration.ApiClient.Deserialize(localVarResponse, typeof(FulfillmentPlan))); } /// <summary> /// Get a fulfillmentPlan by id Returns the fulfillmentPlan identified by the specified id. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="fulfillmentPlanId">Id of the fulfillmentPlan to be returned.</param> /// <returns>Task of FulfillmentPlan</returns> public async System.Threading.Tasks.Task<FulfillmentPlan> GetFulfillmentPlanByIdAsync (int? fulfillmentPlanId) { ApiResponse<FulfillmentPlan> localVarResponse = await GetFulfillmentPlanByIdAsyncWithHttpInfo(fulfillmentPlanId); return localVarResponse.Data; } /// <summary> /// Get a fulfillmentPlan by id Returns the fulfillmentPlan identified by the specified id. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="fulfillmentPlanId">Id of the fulfillmentPlan to be returned.</param> /// <returns>Task of ApiResponse (FulfillmentPlan)</returns> public async System.Threading.Tasks.Task<ApiResponse<FulfillmentPlan>> GetFulfillmentPlanByIdAsyncWithHttpInfo (int? fulfillmentPlanId) { // verify the required parameter 'fulfillmentPlanId' is set if (fulfillmentPlanId == null) throw new ApiException(400, "Missing required parameter 'fulfillmentPlanId' when calling FulfillmentPlanApi->GetFulfillmentPlanById"); var localVarPath = "/v1.0/fulfillmentPlan/{fulfillmentPlanId}"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (fulfillmentPlanId != null) localVarPathParams.Add("fulfillmentPlanId", Configuration.ApiClient.ParameterToString(fulfillmentPlanId)); // path parameter // authentication (api_key) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key"))) { localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath, Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("GetFulfillmentPlanById", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<FulfillmentPlan>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (FulfillmentPlan) Configuration.ApiClient.Deserialize(localVarResponse, typeof(FulfillmentPlan))); } /// <summary> /// Update a fulfillmentPlan Updates an existing fulfillmentPlan using the specified data. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body">FulfillmentPlan to be updated.</param> /// <returns></returns> public void UpdateFulfillmentPlan (FulfillmentPlan body) { UpdateFulfillmentPlanWithHttpInfo(body); } /// <summary> /// Update a fulfillmentPlan Updates an existing fulfillmentPlan using the specified data. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body">FulfillmentPlan to be updated.</param> /// <returns>ApiResponse of Object(void)</returns> public ApiResponse<Object> UpdateFulfillmentPlanWithHttpInfo (FulfillmentPlan body) { // verify the required parameter 'body' is set if (body == null) throw new ApiException(400, "Missing required parameter 'body' when calling FulfillmentPlanApi->UpdateFulfillmentPlan"); var localVarPath = "/v1.0/fulfillmentPlan"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { "application/json" }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (body != null && body.GetType() != typeof(byte[])) { localVarPostBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter } else { localVarPostBody = body; // byte array } // authentication (api_key) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key"))) { localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, Method.PUT, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("UpdateFulfillmentPlan", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<Object>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), null); } /// <summary> /// Update a fulfillmentPlan Updates an existing fulfillmentPlan using the specified data. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body">FulfillmentPlan to be updated.</param> /// <returns>Task of void</returns> public async System.Threading.Tasks.Task UpdateFulfillmentPlanAsync (FulfillmentPlan body) { await UpdateFulfillmentPlanAsyncWithHttpInfo(body); } /// <summary> /// Update a fulfillmentPlan Updates an existing fulfillmentPlan using the specified data. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body">FulfillmentPlan to be updated.</param> /// <returns>Task of ApiResponse</returns> public async System.Threading.Tasks.Task<ApiResponse<Object>> UpdateFulfillmentPlanAsyncWithHttpInfo (FulfillmentPlan body) { // verify the required parameter 'body' is set if (body == null) throw new ApiException(400, "Missing required parameter 'body' when calling FulfillmentPlanApi->UpdateFulfillmentPlan"); var localVarPath = "/v1.0/fulfillmentPlan"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { "application/json" }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (body != null && body.GetType() != typeof(byte[])) { localVarPostBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter } else { localVarPostBody = body; // byte array } // authentication (api_key) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key"))) { localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath, Method.PUT, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("UpdateFulfillmentPlan", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<Object>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), null); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Linq; using Xunit; namespace System.Collections.Immutable.Tests { public abstract class ImmutableDictionaryBuilderTestBase : ImmutablesTestBase { [Fact] public void Add() { var builder = this.GetBuilder<string, int>(); builder.Add("five", 5); builder.Add(new KeyValuePair<string, int>("six", 6)); Assert.Equal(5, builder["five"]); Assert.Equal(6, builder["six"]); Assert.False(builder.ContainsKey("four")); } /// <summary> /// Verifies that "adding" an entry to the dictionary that already exists /// with exactly the same key and value will *not* throw an exception. /// </summary> /// <remarks> /// The BCL Dictionary type would throw in this circumstance. /// But in an immutable world, not only do we not care so much since the result is the same. /// </remarks> [Fact] public void AddExactDuplicate() { var builder = this.GetBuilder<string, int>(); builder.Add("five", 5); builder.Add("five", 5); Assert.Equal(1, builder.Count); } [Fact] public void AddExistingKeyWithDifferentValue() { var builder = this.GetBuilder<string, int>(); builder.Add("five", 5); Assert.Throws<ArgumentException>(null, () => builder.Add("five", 6)); } [Fact] public void Indexer() { var builder = this.GetBuilder<string, int>(); // Set and set again. builder["five"] = 5; Assert.Equal(5, builder["five"]); builder["five"] = 5; Assert.Equal(5, builder["five"]); // Set to a new value. builder["five"] = 50; Assert.Equal(50, builder["five"]); // Retrieve an invalid value. Assert.Throws<KeyNotFoundException>(() => builder["foo"]); } [Fact] public void ContainsPair() { var map = this.GetEmptyImmutableDictionary<string, int>().Add("five", 5); var builder = this.GetBuilder(map); Assert.True(builder.Contains(new KeyValuePair<string, int>("five", 5))); } [Fact] public void RemovePair() { var map = this.GetEmptyImmutableDictionary<string, int>().Add("five", 5).Add("six", 6); var builder = this.GetBuilder(map); Assert.True(builder.Remove(new KeyValuePair<string, int>("five", 5))); Assert.False(builder.Remove(new KeyValuePair<string, int>("foo", 1))); Assert.Equal(1, builder.Count); Assert.Equal(6, builder["six"]); } [Fact] public void RemoveKey() { var map = this.GetEmptyImmutableDictionary<string, int>().Add("five", 5).Add("six", 6); var builder = this.GetBuilder(map); builder.Remove("five"); Assert.Equal(1, builder.Count); Assert.Equal(6, builder["six"]); } [Fact] public void CopyTo() { var map = this.GetEmptyImmutableDictionary<string, int>().Add("five", 5); var builder = this.GetBuilder(map); var array = new KeyValuePair<string, int>[2]; // intentionally larger than source. builder.CopyTo(array, 1); Assert.Equal(new KeyValuePair<string, int>(), array[0]); Assert.Equal(new KeyValuePair<string, int>("five", 5), array[1]); Assert.Throws<ArgumentNullException>("array", () => builder.CopyTo(null, 0)); } [Fact] public void IsReadOnly() { var builder = this.GetBuilder<string, int>(); Assert.False(builder.IsReadOnly); } [Fact] public void Keys() { var map = this.GetEmptyImmutableDictionary<string, int>().Add("five", 5).Add("six", 6); var builder = this.GetBuilder(map); CollectionAssertAreEquivalent(new[] { "five", "six" }, builder.Keys); CollectionAssertAreEquivalent(new[] { "five", "six" }, ((IReadOnlyDictionary<string, int>)builder).Keys.ToArray()); } [Fact] public void Values() { var map = this.GetEmptyImmutableDictionary<string, int>().Add("five", 5).Add("six", 6); var builder = this.GetBuilder(map); CollectionAssertAreEquivalent(new[] { 5, 6 }, builder.Values); CollectionAssertAreEquivalent(new[] { 5, 6 }, ((IReadOnlyDictionary<string, int>)builder).Values.ToArray()); } [Fact] public void TryGetValue() { var map = this.GetEmptyImmutableDictionary<string, int>().Add("five", 5).Add("six", 6); var builder = this.GetBuilder(map); int value; Assert.True(builder.TryGetValue("five", out value) && value == 5); Assert.True(builder.TryGetValue("six", out value) && value == 6); Assert.False(builder.TryGetValue("four", out value)); Assert.Equal(0, value); } [Fact] public void TryGetKey() { var builder = Empty<int>(StringComparer.OrdinalIgnoreCase) .Add("a", 1).ToBuilder(); string actualKey; Assert.True(TryGetKeyHelper(builder, "a", out actualKey)); Assert.Equal("a", actualKey); Assert.True(TryGetKeyHelper(builder, "A", out actualKey)); Assert.Equal("a", actualKey); Assert.False(TryGetKeyHelper(builder, "b", out actualKey)); Assert.Equal("b", actualKey); } [Fact] public void EnumerateTest() { var map = this.GetEmptyImmutableDictionary<string, int>().Add("five", 5).Add("six", 6); var builder = this.GetBuilder(map); using (var enumerator = builder.GetEnumerator()) { Assert.True(enumerator.MoveNext()); Assert.True(enumerator.MoveNext()); Assert.False(enumerator.MoveNext()); } var manualEnum = builder.GetEnumerator(); Assert.Throws<InvalidOperationException>(() => manualEnum.Current); while (manualEnum.MoveNext()) { } Assert.False(manualEnum.MoveNext()); Assert.Throws<InvalidOperationException>(() => manualEnum.Current); } [Fact] public void IDictionaryMembers() { var builder = this.GetBuilder<string, int>(); var dictionary = (IDictionary)builder; dictionary.Add("a", 1); Assert.True(dictionary.Contains("a")); Assert.Equal(1, dictionary["a"]); Assert.Equal(new[] { "a" }, dictionary.Keys.Cast<string>().ToArray()); Assert.Equal(new[] { 1 }, dictionary.Values.Cast<int>().ToArray()); dictionary["a"] = 2; Assert.Equal(2, dictionary["a"]); dictionary.Remove("a"); Assert.False(dictionary.Contains("a")); Assert.False(dictionary.IsFixedSize); Assert.False(dictionary.IsReadOnly); } [Fact] public void IDictionaryEnumerator() { var builder = this.GetBuilder<string, int>(); var dictionary = (IDictionary)builder; dictionary.Add("a", 1); var enumerator = dictionary.GetEnumerator(); Assert.Throws<InvalidOperationException>(() => enumerator.Current); Assert.Throws<InvalidOperationException>(() => enumerator.Key); Assert.Throws<InvalidOperationException>(() => enumerator.Value); Assert.Throws<InvalidOperationException>(() => enumerator.Entry); Assert.True(enumerator.MoveNext()); Assert.Equal(enumerator.Entry, enumerator.Current); Assert.Equal(enumerator.Key, enumerator.Entry.Key); Assert.Equal(enumerator.Value, enumerator.Entry.Value); Assert.Equal("a", enumerator.Key); Assert.Equal(1, enumerator.Value); Assert.False(enumerator.MoveNext()); Assert.Throws<InvalidOperationException>(() => enumerator.Current); Assert.Throws<InvalidOperationException>(() => enumerator.Key); Assert.Throws<InvalidOperationException>(() => enumerator.Value); Assert.Throws<InvalidOperationException>(() => enumerator.Entry); Assert.False(enumerator.MoveNext()); enumerator.Reset(); Assert.Throws<InvalidOperationException>(() => enumerator.Current); Assert.Throws<InvalidOperationException>(() => enumerator.Key); Assert.Throws<InvalidOperationException>(() => enumerator.Value); Assert.Throws<InvalidOperationException>(() => enumerator.Entry); Assert.True(enumerator.MoveNext()); Assert.Equal(enumerator.Key, ((DictionaryEntry)enumerator.Current).Key); Assert.Equal(enumerator.Value, ((DictionaryEntry)enumerator.Current).Value); Assert.Equal("a", enumerator.Key); Assert.Equal(1, enumerator.Value); Assert.False(enumerator.MoveNext()); Assert.Throws<InvalidOperationException>(() => enumerator.Current); Assert.Throws<InvalidOperationException>(() => enumerator.Key); Assert.Throws<InvalidOperationException>(() => enumerator.Value); Assert.Throws<InvalidOperationException>(() => enumerator.Entry); Assert.False(enumerator.MoveNext()); } [Fact] public void ICollectionMembers() { var builder = this.GetBuilder<string, int>(); var collection = (ICollection)builder; collection.CopyTo(new object[0], 0); builder.Add("b", 2); Assert.True(builder.ContainsKey("b")); var array = new object[builder.Count + 1]; collection.CopyTo(array, 1); Assert.Null(array[0]); Assert.Equal(new object[] { null, new DictionaryEntry("b", 2), }, array); Assert.False(collection.IsSynchronized); Assert.NotNull(collection.SyncRoot); Assert.Same(collection.SyncRoot, collection.SyncRoot); } protected abstract bool TryGetKeyHelper<TKey, TValue>(IDictionary<TKey, TValue> dictionary, TKey equalKey, out TKey actualKey); /// <summary> /// Gets the Builder for a given dictionary instance. /// </summary> /// <typeparam name="TKey">The type of key.</typeparam> /// <typeparam name="TValue">The type of value.</typeparam> /// <returns>The builder.</returns> protected abstract IDictionary<TKey, TValue> GetBuilder<TKey, TValue>(IImmutableDictionary<TKey, TValue> basis = null); /// <summary> /// Gets an empty immutable dictionary. /// </summary> /// <typeparam name="TKey">The type of key.</typeparam> /// <typeparam name="TValue">The type of value.</typeparam> /// <returns>The immutable dictionary.</returns> protected abstract IImmutableDictionary<TKey, TValue> GetEmptyImmutableDictionary<TKey, TValue>(); protected abstract IImmutableDictionary<string, TValue> Empty<TValue>(StringComparer comparer); } }
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; using Avalonia.Input; using Avalonia.Input.Platform; using static Avalonia.X11.XLib; namespace Avalonia.X11 { class X11Clipboard : IClipboard { private readonly X11Info _x11; private IDataObject _storedDataObject; private IntPtr _handle; private TaskCompletionSource<IntPtr[]> _requestedFormatsTcs; private TaskCompletionSource<object> _requestedDataTcs; private readonly IntPtr[] _textAtoms; private readonly IntPtr _avaloniaSaveTargetsAtom; private readonly Dictionary<string, IntPtr> _formatAtoms = new Dictionary<string, IntPtr>(); private readonly Dictionary<IntPtr, string> _atomFormats = new Dictionary<IntPtr, string>(); public X11Clipboard(AvaloniaX11Platform platform) { _x11 = platform.Info; _handle = CreateEventWindow(platform, OnEvent); _avaloniaSaveTargetsAtom = XInternAtom(_x11.Display, "AVALONIA_SAVE_TARGETS_PROPERTY_ATOM", false); _textAtoms = new[] { _x11.Atoms.XA_STRING, _x11.Atoms.OEMTEXT, _x11.Atoms.UTF8_STRING, _x11.Atoms.UTF16_STRING }.Where(a => a != IntPtr.Zero).ToArray(); } bool IsStringAtom(IntPtr atom) { return _textAtoms.Contains(atom); } Encoding GetStringEncoding(IntPtr atom) { return (atom == _x11.Atoms.XA_STRING || atom == _x11.Atoms.OEMTEXT) ? Encoding.ASCII : atom == _x11.Atoms.UTF8_STRING ? Encoding.UTF8 : atom == _x11.Atoms.UTF16_STRING ? Encoding.Unicode : null; } private unsafe void OnEvent(XEvent ev) { if (ev.type == XEventName.SelectionRequest) { var sel = ev.SelectionRequestEvent; var resp = new XEvent { SelectionEvent = { type = XEventName.SelectionNotify, send_event = true, display = _x11.Display, selection = sel.selection, target = sel.target, requestor = sel.requestor, time = sel.time, property = IntPtr.Zero } }; if (sel.selection == _x11.Atoms.CLIPBOARD) { resp.SelectionEvent.property = WriteTargetToProperty(sel.target, sel.requestor, sel.property); } XSendEvent(_x11.Display, sel.requestor, false, new IntPtr((int)EventMask.NoEventMask), ref resp); } IntPtr WriteTargetToProperty(IntPtr target, IntPtr window, IntPtr property) { Encoding textEnc; if (target == _x11.Atoms.TARGETS) { var atoms = new HashSet<IntPtr> { _x11.Atoms.TARGETS, _x11.Atoms.MULTIPLE }; foreach (var fmt in _storedDataObject.GetDataFormats()) { if (fmt == DataFormats.Text) foreach (var ta in _textAtoms) atoms.Add(ta); else atoms.Add(_x11.Atoms.GetAtom(fmt)); } XChangeProperty(_x11.Display, window, property, _x11.Atoms.XA_ATOM, 32, PropertyMode.Replace, atoms.ToArray(), atoms.Count); return property; } else if(target == _x11.Atoms.SAVE_TARGETS && _x11.Atoms.SAVE_TARGETS != IntPtr.Zero) { return property; } else if ((textEnc = GetStringEncoding(target)) != null && _storedDataObject?.Contains(DataFormats.Text) == true) { var text = _storedDataObject.GetText(); if(text == null) return IntPtr.Zero; var data = textEnc.GetBytes(text); fixed (void* pdata = data) XChangeProperty(_x11.Display, window, property, target, 8, PropertyMode.Replace, pdata, data.Length); return property; } else if (target == _x11.Atoms.MULTIPLE && _x11.Atoms.MULTIPLE != IntPtr.Zero) { XGetWindowProperty(_x11.Display, window, property, IntPtr.Zero, new IntPtr(0x7fffffff), false, _x11.Atoms.ATOM_PAIR, out _, out var actualFormat, out var nitems, out _, out var prop); if (nitems == IntPtr.Zero) return IntPtr.Zero; if (actualFormat == 32) { var data = (IntPtr*)prop.ToPointer(); for (var c = 0; c < nitems.ToInt32(); c += 2) { var subTarget = data[c]; var subProp = data[c + 1]; var converted = WriteTargetToProperty(subTarget, window, subProp); data[c + 1] = converted; } XChangeProperty(_x11.Display, window, property, _x11.Atoms.ATOM_PAIR, 32, PropertyMode.Replace, prop.ToPointer(), nitems.ToInt32()); } XFree(prop); return property; } else if(_storedDataObject?.Contains(_x11.Atoms.GetAtomName(target)) == true) { var objValue = _storedDataObject.Get(_x11.Atoms.GetAtomName(target)); if(!(objValue is byte[] bytes)) { if (objValue is string s) bytes = Encoding.UTF8.GetBytes(s); else return IntPtr.Zero; } XChangeProperty(_x11.Display, window, property, target, 8, PropertyMode.Replace, bytes, bytes.Length); return property; } else return IntPtr.Zero; } if (ev.type == XEventName.SelectionNotify && ev.SelectionEvent.selection == _x11.Atoms.CLIPBOARD) { var sel = ev.SelectionEvent; if (sel.property == IntPtr.Zero) { _requestedFormatsTcs?.TrySetResult(null); _requestedDataTcs?.TrySetResult(null); } XGetWindowProperty(_x11.Display, _handle, sel.property, IntPtr.Zero, new IntPtr (0x7fffffff), true, (IntPtr)Atom.AnyPropertyType, out var actualTypeAtom, out var actualFormat, out var nitems, out var bytes_after, out var prop); Encoding textEnc = null; if (nitems == IntPtr.Zero) { _requestedFormatsTcs?.TrySetResult(null); _requestedDataTcs?.TrySetResult(null); } else { if (sel.property == _x11.Atoms.TARGETS) { if (actualFormat != 32) _requestedFormatsTcs?.TrySetResult(null); else { var formats = new IntPtr[nitems.ToInt32()]; Marshal.Copy(prop, formats, 0, formats.Length); _requestedFormatsTcs?.TrySetResult(formats); } } else if ((textEnc = GetStringEncoding(actualTypeAtom)) != null) { var text = textEnc.GetString((byte*)prop.ToPointer(), nitems.ToInt32()); _requestedDataTcs?.TrySetResult(text); } else { if (actualTypeAtom == _x11.Atoms.INCR) { // TODO: Actually implement that monstrosity _requestedDataTcs.TrySetResult(null); } else { var data = new byte[(int)nitems * (actualFormat / 8)]; Marshal.Copy(prop, data, 0, data.Length); _requestedDataTcs?.TrySetResult(data); } } } XFree(prop); } } Task<IntPtr[]> SendFormatRequest() { if (_requestedFormatsTcs == null || _requestedFormatsTcs.Task.IsCompleted) _requestedFormatsTcs = new TaskCompletionSource<IntPtr[]>(); XConvertSelection(_x11.Display, _x11.Atoms.CLIPBOARD, _x11.Atoms.TARGETS, _x11.Atoms.TARGETS, _handle, IntPtr.Zero); return _requestedFormatsTcs.Task; } Task<object> SendDataRequest(IntPtr format) { if (_requestedDataTcs == null || _requestedFormatsTcs.Task.IsCompleted) _requestedDataTcs = new TaskCompletionSource<object>(); XConvertSelection(_x11.Display, _x11.Atoms.CLIPBOARD, format, format, _handle, IntPtr.Zero); return _requestedDataTcs.Task; } bool HasOwner => XGetSelectionOwner(_x11.Display, _x11.Atoms.CLIPBOARD) != IntPtr.Zero; public async Task<string> GetTextAsync() { if (!HasOwner) return null; var res = await SendFormatRequest(); var target = _x11.Atoms.UTF8_STRING; if (res != null) { var preferredFormats = new[] {_x11.Atoms.UTF16_STRING, _x11.Atoms.UTF8_STRING, _x11.Atoms.XA_STRING}; foreach (var pf in preferredFormats) if (res.Contains(pf)) { target = pf; break; } } return (string)await SendDataRequest(target); } void StoreAtomsInClipboardManager(IntPtr[] atoms) { if (_x11.Atoms.CLIPBOARD_MANAGER != IntPtr.Zero && _x11.Atoms.SAVE_TARGETS != IntPtr.Zero) { var clipboardManager = XGetSelectionOwner(_x11.Display, _x11.Atoms.CLIPBOARD_MANAGER); if (clipboardManager != IntPtr.Zero) { XChangeProperty(_x11.Display, _handle, _avaloniaSaveTargetsAtom, _x11.Atoms.XA_ATOM, 32, PropertyMode.Replace, atoms, atoms.Length); XConvertSelection(_x11.Display, _x11.Atoms.CLIPBOARD_MANAGER, _x11.Atoms.SAVE_TARGETS, _avaloniaSaveTargetsAtom, _handle, IntPtr.Zero); } } } public Task SetTextAsync(string text) { var data = new DataObject(); data.Set(DataFormats.Text, text); return SetDataObjectAsync(data); } public Task ClearAsync() { return SetTextAsync(null); } public Task SetDataObjectAsync(IDataObject data) { _storedDataObject = data; XSetSelectionOwner(_x11.Display, _x11.Atoms.CLIPBOARD, _handle, IntPtr.Zero); StoreAtomsInClipboardManager(_textAtoms); return Task.CompletedTask; } public async Task<string[]> GetFormatsAsync() { if (!HasOwner) return null; var res = await SendFormatRequest(); if (res == null) return null; var rv = new List<string>(); if (_textAtoms.Any(res.Contains)) rv.Add(DataFormats.Text); foreach (var t in res) rv.Add(_x11.Atoms.GetAtomName(t)); return rv.ToArray(); } public async Task<object> GetDataAsync(string format) { if (!HasOwner) return null; if (format == DataFormats.Text) return await GetTextAsync(); var formatAtom = _x11.Atoms.GetAtom(format); var res = await SendFormatRequest(); if (!res.Contains(formatAtom)) return null; return await SendDataRequest(formatAtom); } } }
// // Copyright (c) 2004-2020 Jaroslaw Kowalski <jaak@jkowalski.net>, 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. // using System; using System.Linq; using System.Collections.Generic; using NLog.Internal; using Xunit; namespace NLog.UnitTests.Internal { public class SortHelpersTests { [Fact] public void SingleBucketDictionary_NoBucketTest() { SortHelpers.ReadOnlySingleBucketDictionary<string, IList<string>> dict = new SortHelpers.ReadOnlySingleBucketDictionary<string, IList<string>>(); Assert.Empty(dict); Assert.Empty(dict); Assert.Equal(0, dict.Count(val => val.Key == "Bucket1")); foreach (var _ in dict) Assert.False(true); Assert.Equal(0, dict.Keys.Count); foreach (var _ in dict.Keys) Assert.False(true); Assert.Equal(0, dict.Values.Count); foreach (var _ in dict.Values) Assert.False(true); IList<string> bucket; Assert.False(dict.TryGetValue("Bucket1", out bucket) || bucket != null); Assert.False(dict.TryGetValue(string.Empty, out bucket) || bucket != null); Assert.False(dict.TryGetValue(null, out bucket) || bucket != null); Assert.Throws<NotSupportedException>(() => dict[string.Empty] = new string[0]); } [Fact] public void SingleBucketDictionary_OneBucketEmptyTest() { IList<string> bucket = new string[0]; SortHelpers.ReadOnlySingleBucketDictionary<string, IList<string>> dict = new SortHelpers.ReadOnlySingleBucketDictionary<string, IList<string>>(new KeyValuePair<string, IList<string>>("Bucket1", bucket)); Assert.Single(dict); Assert.Contains(new KeyValuePair<string, IList<string>>("Bucket1", bucket), dict); Assert.DoesNotContain(new KeyValuePair<string, IList<string>>("Bucket1", null), dict); Assert.DoesNotContain(new KeyValuePair<string, IList<string>>(string.Empty, bucket), dict); Assert.True(dict.ContainsKey("Bucket1")); Assert.False(dict.ContainsKey(string.Empty)); KeyValuePair<string, IList<string>>[] copyToResult = new KeyValuePair<string, IList<string>>[10]; dict.CopyTo(copyToResult, 0); Assert.Equal("Bucket1", copyToResult[0].Key); Assert.Equal(0, copyToResult[0].Value.Count); Assert.Single(dict); Assert.Equal(1, dict.Count(val => val.Key == "Bucket1")); foreach (var item in dict) { Assert.Equal("Bucket1", item.Key); Assert.Equal(0, item.Value.Count); } Assert.Equal(1, dict.Keys.Count); foreach (var key in dict.Keys) { Assert.Equal("Bucket1", key); } Assert.Equal(1, dict.Values.Count); foreach (var val in dict.Values) { Assert.Equal(0, val.Count); } Assert.Equal(0, dict["Bucket1"].Count); Assert.True(dict.TryGetValue("Bucket1", out bucket) && bucket.Count == 0); Assert.False(dict.TryGetValue(string.Empty, out bucket) || bucket != null); Assert.False(dict.TryGetValue(null, out bucket) || bucket != null); Assert.Throws<NotSupportedException>(() => dict[string.Empty] = new string[0]); } [Fact] public void SingleBucketDictionary_OneBucketOneItem() { IList<string> bucket = new string[] { "Bucket1Item1" }; SortHelpers.ReadOnlySingleBucketDictionary<string, IList<string>> dict = new SortHelpers.ReadOnlySingleBucketDictionary<string, IList<string>>(new KeyValuePair<string, IList<string>>("Bucket1", bucket)); Assert.Single(dict); Assert.Contains(new KeyValuePair<string, IList<string>>("Bucket1", bucket), dict); Assert.DoesNotContain(new KeyValuePair<string, IList<string>>("Bucket1", null), dict); Assert.DoesNotContain(new KeyValuePair<string, IList<string>>(string.Empty, bucket), dict); Assert.True(dict.ContainsKey("Bucket1")); Assert.False(dict.ContainsKey(string.Empty)); KeyValuePair<string, IList<string>>[] copyToResult = new KeyValuePair<string, IList<string>>[10]; dict.CopyTo(copyToResult, 0); Assert.Equal("Bucket1", copyToResult[0].Key); Assert.Equal(1, copyToResult[0].Value.Count); Assert.Equal("Bucket1Item1", copyToResult[0].Value[0]); Assert.Single(dict); Assert.Equal(1, dict.Count(val => val.Key == "Bucket1")); foreach (var item in dict) { Assert.Equal("Bucket1", item.Key); Assert.Equal(1, item.Value.Count); Assert.Equal("Bucket1Item1", item.Value[0]); } Assert.Equal(1, dict.Keys.Count); foreach (var key in dict.Keys) { Assert.Equal("Bucket1", key); } Assert.Equal(1, dict.Values.Count); foreach (var val in dict.Values) { Assert.Equal(1, val.Count); Assert.Equal("Bucket1Item1", val[0]); } Assert.Equal(1, dict["Bucket1"].Count); Assert.True(dict.TryGetValue("Bucket1", out bucket) && bucket.Count == 1); Assert.False(dict.TryGetValue(string.Empty, out bucket) || bucket != null); Assert.False(dict.TryGetValue(null, out bucket) || bucket != null); Assert.Throws<NotSupportedException>(() => dict[string.Empty] = new string[0]); } [Fact] public void SingleBucketDictionary_OneBucketTwoItemsTest() { IList<string> bucket = new string[] { "Bucket1Item1", "Bucket1Item2" }; SortHelpers.ReadOnlySingleBucketDictionary<string, IList<string>> dict = new SortHelpers.ReadOnlySingleBucketDictionary<string, IList<string>>(new KeyValuePair<string, IList<string>>("Bucket1", bucket)); Assert.Single(dict); Assert.Contains(new KeyValuePair<string, IList<string>>("Bucket1", bucket), dict); Assert.DoesNotContain(new KeyValuePair<string, IList<string>>("Bucket1", null), dict); Assert.DoesNotContain(new KeyValuePair<string, IList<string>>(string.Empty, bucket), dict); Assert.True(dict.ContainsKey("Bucket1")); Assert.False(dict.ContainsKey(string.Empty)); KeyValuePair<string, IList<string>>[] copyToResult = new KeyValuePair<string, IList<string>>[10]; dict.CopyTo(copyToResult, 0); Assert.Equal("Bucket1", copyToResult[0].Key); Assert.Equal(2, copyToResult[0].Value.Count); Assert.Equal("Bucket1Item1", copyToResult[0].Value[0]); Assert.Equal("Bucket1Item2", copyToResult[0].Value[1]); Assert.Single(dict); Assert.Equal(1, dict.Count(val => val.Key == "Bucket1")); foreach (var item in dict) { Assert.Equal("Bucket1", item.Key); Assert.Equal(2, item.Value.Count); Assert.Equal("Bucket1Item1", item.Value[0]); Assert.Equal("Bucket1Item2", item.Value[1]); } Assert.Equal(1, dict.Keys.Count); foreach (var key in dict.Keys) { Assert.Equal("Bucket1", key); } Assert.Equal(1, dict.Values.Count); foreach (var val in dict.Values) { Assert.Equal(2, val.Count); Assert.Equal("Bucket1Item1", val[0]); Assert.Equal("Bucket1Item2", val[1]); } Assert.Equal(2, dict["Bucket1"].Count); Assert.True(dict.TryGetValue("Bucket1", out bucket) && bucket.Count == 2); Assert.False(dict.TryGetValue(string.Empty, out bucket) || bucket != null); Assert.False(dict.TryGetValue(null, out bucket) || bucket != null); Assert.Throws<NotSupportedException>(() => dict[string.Empty] = new string[0]); } [Fact] public void SingleBucketDictionary_TwoBucketEmptyTest() { IList<string> bucket1 = new string[0]; IList<string> bucket2 = new string[0]; Dictionary<string, IList<string>> buckets = new Dictionary<string, IList<string>>(); buckets["Bucket1"] = bucket1; buckets["Bucket2"] = bucket2; SortHelpers.ReadOnlySingleBucketDictionary<string, IList<string>> dict = new SortHelpers.ReadOnlySingleBucketDictionary<string, IList<string>>(buckets); Assert.Equal(2, dict.Count); Assert.Contains(new KeyValuePair<string, IList<string>>("Bucket1", bucket1), dict); Assert.DoesNotContain(new KeyValuePair<string, IList<string>>("Bucket1", null), dict); Assert.DoesNotContain(new KeyValuePair<string, IList<string>>(string.Empty, bucket1), dict); Assert.Contains(new KeyValuePair<string, IList<string>>("Bucket2", bucket2), dict); Assert.DoesNotContain(new KeyValuePair<string, IList<string>>("Bucket2", null), dict); Assert.DoesNotContain(new KeyValuePair<string, IList<string>>(string.Empty, bucket2), dict); Assert.True(dict.ContainsKey("Bucket1")); Assert.True(dict.ContainsKey("Bucket2")); Assert.False(dict.ContainsKey(string.Empty)); KeyValuePair<string, IList<string>>[] copyToResult = new KeyValuePair<string, IList<string>>[10]; dict.CopyTo(copyToResult, 0); Assert.Equal("Bucket1", copyToResult[0].Key); Assert.Equal("Bucket2", copyToResult[1].Key); Assert.Equal(0, copyToResult[0].Value.Count); Assert.Equal(0, copyToResult[1].Value.Count); Assert.Equal(2, dict.Count()); Assert.Equal(1, dict.Count(val => val.Key == "Bucket1")); Assert.Equal(1, dict.Count(val => val.Key == "Bucket2")); foreach (var item in dict) { Assert.True(item.Key == "Bucket1" || item.Key == "Bucket2"); Assert.Equal(0, item.Value.Count); } Assert.Equal(2, dict.Keys.Count); foreach (var key in dict.Keys) { Assert.True(key == "Bucket1" || key == "Bucket2"); } Assert.Equal(2, dict.Values.Count); foreach (var val in dict.Values) { Assert.Equal(0, val.Count); } Assert.Equal(0, dict["Bucket1"].Count); Assert.Equal(0, dict["Bucket2"].Count); Assert.True(dict.TryGetValue("Bucket1", out bucket1) && bucket1.Count == 0); Assert.True(dict.TryGetValue("Bucket2", out bucket2) && bucket2.Count == 0); Assert.Throws<NotSupportedException>(() => dict[string.Empty] = new string[0]); } [Fact] public void SingleBucketDictionary_TwoBuckettOneItemTest() { IList<string> bucket1 = new string[] { "Bucket1Item1" }; IList<string> bucket2 = new string[] { "Bucket1Item1" }; Dictionary<string, IList<string>> buckets = new Dictionary<string, IList<string>>(); buckets["Bucket1"] = bucket1; buckets["Bucket2"] = bucket2; SortHelpers.ReadOnlySingleBucketDictionary<string, IList<string>> dict = new SortHelpers.ReadOnlySingleBucketDictionary<string, IList<string>>(buckets); Assert.Equal(2, dict.Count); Assert.Contains(new KeyValuePair<string, IList<string>>("Bucket1", bucket1), dict); Assert.DoesNotContain(new KeyValuePair<string, IList<string>>("Bucket1", null), dict); Assert.DoesNotContain(new KeyValuePair<string, IList<string>>(string.Empty, bucket1), dict); Assert.Contains(new KeyValuePair<string, IList<string>>("Bucket2", bucket2), dict); Assert.DoesNotContain(new KeyValuePair<string, IList<string>>("Bucket2", null), dict); Assert.DoesNotContain(new KeyValuePair<string, IList<string>>(string.Empty, bucket2), dict); Assert.True(dict.ContainsKey("Bucket1")); Assert.True(dict.ContainsKey("Bucket2")); Assert.False(dict.ContainsKey(string.Empty)); KeyValuePair<string, IList<string>>[] copyToResult = new KeyValuePair<string, IList<string>>[10]; dict.CopyTo(copyToResult, 0); Assert.Equal("Bucket1", copyToResult[0].Key); Assert.Equal("Bucket2", copyToResult[1].Key); Assert.Equal(1, copyToResult[0].Value.Count); Assert.Equal(1, copyToResult[1].Value.Count); Assert.Equal(2, dict.Count()); Assert.Equal(1, dict.Count(val => val.Key == "Bucket1")); Assert.Equal(1, dict.Count(val => val.Key == "Bucket2")); foreach (var item in dict) { Assert.True(item.Key == "Bucket1" || item.Key == "Bucket2"); Assert.Equal(1, item.Value.Count); Assert.Equal("Bucket1Item1", item.Value[0]); } Assert.Equal(2, dict.Keys.Count); foreach (var key in dict.Keys) { Assert.True(key == "Bucket1" || key == "Bucket2"); } Assert.Equal(2, dict.Values.Count); foreach (var val in dict.Values) { Assert.Equal(1, val.Count); Assert.Equal("Bucket1Item1", val[0]); } Assert.Equal(1, dict["Bucket1"].Count); Assert.Equal(1, dict["Bucket2"].Count); Assert.True(dict.TryGetValue("Bucket1", out bucket1) && bucket1.Count == 1); Assert.True(dict.TryGetValue("Bucket2", out bucket2) && bucket2.Count == 1); Assert.Throws<NotSupportedException>(() => dict[string.Empty] = new string[0]); } } }
using System; using System.Collections.Generic; using System.Threading.Tasks; using FluentAssertions; using FluentAssertions.Equivalency; using Orleans.Runtime; using Orleans.Transactions.Abstractions; namespace Orleans.Transactions.TestKit { public abstract class TransactionalStateStorageTestRunner<TState> : TransactionTestRunnerBase where TState : class, new() { protected Func<Task<ITransactionalStateStorage<TState>>> stateStorageFactory; protected Func<int, TState> stateFactory; protected Func<EquivalencyAssertionOptions<TState>, EquivalencyAssertionOptions<TState>> assertConfig; /// <summary> /// Constructor /// </summary> /// <param name="stateStorageFactory">factory to create ITransactionalStateStorage, the test runner are assuming the state /// in storage is empty when ITransactionalStateStorage was created </param> /// <param name="stateFactory">factory to create TState for test</param> /// <param name="grainFactory">grain Factory needed for test runner</param> /// <param name="testOutput">test output to helpful messages</param> /// <param name="assertConfig">A reference to the FluentAssertions.Equivalency.EquivalencyAssertionOptions`1 /// configuration object that can be used to influence the way the object graphs /// are compared</param> protected TransactionalStateStorageTestRunner(Func<Task<ITransactionalStateStorage<TState>>> stateStorageFactory, Func<int, TState> stateFactory, IGrainFactory grainFactory, Action<string> testOutput, Func<EquivalencyAssertionOptions<TState>, EquivalencyAssertionOptions<TState>> assertConfig = null) :base(grainFactory, testOutput) { this.stateStorageFactory = stateStorageFactory; this.stateFactory = stateFactory; this.assertConfig = assertConfig; } public virtual async Task FirstTime_Load_ShouldReturnEmptyLoadResponse() { var stateStorage = await this.stateStorageFactory(); var response = await stateStorage.Load(); var defaultStateValue = new TState(); //Assertion response.Should().NotBeNull(); response.ETag.Should().BeNull(); response.CommittedSequenceId.Should().Be(0); AssertTState(response.CommittedState, defaultStateValue); response.PendingStates.Should().BeEmpty(); } private static List<PendingTransactionState<TState>> emptyPendingStates = new List<PendingTransactionState<TState>>(); public virtual async Task StoreWithoutChanges() { var stateStorage = await this.stateStorageFactory(); // load first time var loadresponse = await stateStorage.Load(); // store without any changes var etag1 = await stateStorage.Store(loadresponse.ETag, loadresponse.Metadata, emptyPendingStates, null, null); // load again loadresponse = await stateStorage.Load(); loadresponse.Should().NotBeNull(); loadresponse.Metadata.Should().NotBeNull(); loadresponse.Metadata.TimeStamp.Should().Be(default(DateTime)); loadresponse.Metadata.CommitRecords.Should().BeEmpty(); loadresponse.ETag.Should().Be(etag1); loadresponse.CommittedSequenceId.Should().Be(0); loadresponse.PendingStates.Should().BeEmpty(); // update metadata, then write back var now = DateTime.UtcNow; var cr = MakeCommitRecords(2, 2); var metadata = new TransactionalStateMetaData() { TimeStamp = now, CommitRecords = cr }; var etag2 = await stateStorage.Store(etag1, metadata, emptyPendingStates, null, null); // load again, check content loadresponse = await stateStorage.Load(); loadresponse.Should().NotBeNull(); loadresponse.Metadata.Should().NotBeNull(); loadresponse.Metadata.TimeStamp.Should().Be(now); loadresponse.Metadata.CommitRecords.Count.Should().Be(cr.Count); loadresponse.ETag.Should().Be(etag2); loadresponse.CommittedSequenceId.Should().Be(0); loadresponse.PendingStates.Should().BeEmpty(); } public virtual async Task WrongEtags() { var stateStorage = await this.stateStorageFactory(); // load first time var loadresponse = await stateStorage.Load(); // store with wrong e-tag, must fail try { var etag1 = await stateStorage.Store("wrong-etag", loadresponse.Metadata, emptyPendingStates, null, null); throw new Exception("storage did not catch e-tag mismatch"); } catch (Exception) { } // load again loadresponse = await stateStorage.Load(); loadresponse.Should().NotBeNull(); loadresponse.Metadata.TimeStamp.Should().Be(default(DateTime)); loadresponse.Metadata.CommitRecords.Should().BeEmpty(); loadresponse.ETag.Should().BeNull(); loadresponse.CommittedSequenceId.Should().Be(0); loadresponse.PendingStates.Should().BeEmpty(); // update timestamp in metadata, then write back with correct e-tag var now = DateTime.UtcNow; var cr = MakeCommitRecords(2,2); var metadata = new TransactionalStateMetaData() { TimeStamp = now, CommitRecords = cr }; var etag2 = await stateStorage.Store(null, metadata, emptyPendingStates, null, null); // update timestamp in metadata, then write back with wrong e-tag, must fail try { var now2 = DateTime.UtcNow; var metadata2 = new TransactionalStateMetaData() { TimeStamp = now2, CommitRecords = MakeCommitRecords(3,3) }; await stateStorage.Store(null, metadata, emptyPendingStates, null, null); throw new Exception("storage did not catch e-tag mismatch"); } catch (Exception) { } // load again, check content loadresponse = await stateStorage.Load(); loadresponse.Should().NotBeNull(); loadresponse.Metadata.Should().NotBeNull(); loadresponse.Metadata.TimeStamp.Should().Be(now); loadresponse.Metadata.CommitRecords.Count.Should().Be(cr.Count); loadresponse.ETag.Should().Be(etag2); loadresponse.CommittedSequenceId.Should().Be(0); loadresponse.PendingStates.Should().BeEmpty(); } private void AssertTState(TState actual, TState expected) { if(assertConfig == null) actual.ShouldBeEquivalentTo(expected); else actual.ShouldBeEquivalentTo(expected, assertConfig); } private PendingTransactionState<TState> MakePendingState(long seqno, TState val, bool tm) { var result = new PendingTransactionState<TState>() { SequenceId = seqno, TimeStamp = DateTime.UtcNow, TransactionId = Guid.NewGuid().ToString(), TransactionManager = tm ? default(ParticipantId) : MakeParticipantId(), State = new TState() }; result.State = val; return result; } private ParticipantId MakeParticipantId() { return new ParticipantId( "tm", null, // (GrainReference) grainFactory.GetGrain<ITransactionTestGrain>(Guid.NewGuid(), TransactionTestConstants.SingleStateTransactionalGrain), ParticipantId.Role.Resource | ParticipantId.Role.Manager); } private Dictionary<Guid, CommitRecord> MakeCommitRecords(int count, int size) { var result = new Dictionary<Guid, CommitRecord>(); for (int j = 0; j < size; j++) { var r = new CommitRecord() { Timestamp = DateTime.UtcNow, WriteParticipants = new List<ParticipantId>(), }; for (int i = 0; i < size; i++) { r.WriteParticipants.Add(MakeParticipantId()); } result.Add(Guid.NewGuid(), r); } return result; } private async Task PrepareOne() { var stateStorage = await this.stateStorageFactory(); var loadresponse = await stateStorage.Load(); var etag = loadresponse.ETag; var metadata = loadresponse.Metadata; var initialstate = loadresponse.CommittedState; var expectedState = this.stateFactory(123); var pendingstate = MakePendingState(1, expectedState, false); etag = await stateStorage.Store(etag, metadata, new List<PendingTransactionState<TState>>() { pendingstate }, null, null); loadresponse = await stateStorage.Load(); etag = loadresponse.ETag; metadata = loadresponse.Metadata; loadresponse.Should().NotBeNull(); loadresponse.Metadata.Should().NotBeNull(); loadresponse.CommittedSequenceId.Should().Be(0); loadresponse.PendingStates.Count.Should().Be(1); loadresponse.PendingStates[0].SequenceId.Should().Be(1); loadresponse.PendingStates[0].TimeStamp.Should().Be(pendingstate.TimeStamp); loadresponse.PendingStates[0].TransactionManager.Should().Be(pendingstate.TransactionManager); loadresponse.PendingStates[0].TransactionId.Should().Be(pendingstate.TransactionId); AssertTState(loadresponse.PendingStates[0].State, expectedState); } public virtual async Task ConfirmOne(bool useTwoSteps) { var stateStorage = await this.stateStorageFactory(); var loadresponse = await stateStorage.Load(); var etag = loadresponse.ETag; var metadata = loadresponse.Metadata; var initialstate = loadresponse.CommittedState; var expectedState = this.stateFactory(123); var pendingstate = MakePendingState(1, expectedState, false); if (useTwoSteps) { etag = await stateStorage.Store(etag, metadata, new List<PendingTransactionState<TState>>() { pendingstate }, null, null); etag = await stateStorage.Store(etag, metadata, emptyPendingStates, 1, null); } else { etag = await stateStorage.Store(etag, metadata, new List<PendingTransactionState<TState>>() { pendingstate }, 1, null); } loadresponse = await stateStorage.Load(); etag = loadresponse.ETag; metadata = loadresponse.Metadata; loadresponse.Should().NotBeNull(); loadresponse.Metadata.Should().NotBeNull(); loadresponse.CommittedSequenceId.Should().Be(1); loadresponse.PendingStates.Count.Should().Be(0); AssertTState(loadresponse.CommittedState, expectedState); loadresponse.Metadata.TimeStamp.Should().Be(default(DateTime)); loadresponse.Metadata.CommitRecords.Count.Should().Be(0); } public virtual async Task CancelOne() { var stateStorage = await this.stateStorageFactory(); var loadresponse = await stateStorage.Load(); var etag = loadresponse.ETag; var metadata = loadresponse.Metadata; var initialstate = loadresponse.CommittedState; var pendingstate = MakePendingState(1, this.stateFactory(123), false); etag = await stateStorage.Store(etag, metadata, new List<PendingTransactionState<TState>>() { pendingstate }, null, null); etag = await stateStorage.Store(etag, metadata, emptyPendingStates, null, 0); loadresponse = await stateStorage.Load(); etag = loadresponse.ETag; metadata = loadresponse.Metadata; loadresponse.Should().NotBeNull(); loadresponse.Metadata.Should().NotBeNull(); loadresponse.CommittedSequenceId.Should().Be(0); loadresponse.PendingStates.Count.Should().Be(0); AssertTState(loadresponse.CommittedState,initialstate); loadresponse.Metadata.TimeStamp.Should().Be(default(DateTime)); loadresponse.Metadata.CommitRecords.Count.Should().Be(0); } public virtual async Task ReplaceOne() { var stateStorage = await this.stateStorageFactory(); var loadresponse = await stateStorage.Load(); var etag = loadresponse.ETag; var metadata = loadresponse.Metadata; var initialstate = loadresponse.CommittedState; var expectedState1 = this.stateFactory(123); var expectedState2 = this.stateFactory(456); var pendingstate1 = MakePendingState(1, expectedState1, false); var pendingstate2 = MakePendingState(1, expectedState2, false); etag = await stateStorage.Store(etag, metadata, new List<PendingTransactionState<TState>>() { pendingstate1 }, null, null); etag = await stateStorage.Store(etag, metadata, new List<PendingTransactionState<TState>>() { pendingstate2 }, null, null); loadresponse = await stateStorage.Load(); etag = loadresponse.ETag; metadata = loadresponse.Metadata; loadresponse.Should().NotBeNull(); loadresponse.Metadata.Should().NotBeNull(); loadresponse.CommittedSequenceId.Should().Be(0); loadresponse.PendingStates.Count.Should().Be(1); loadresponse.PendingStates[0].SequenceId.Should().Be(1); loadresponse.PendingStates[0].TimeStamp.Should().Be(pendingstate2.TimeStamp); loadresponse.PendingStates[0].TransactionManager.Should().Be(pendingstate2.TransactionManager); loadresponse.PendingStates[0].TransactionId.Should().Be(pendingstate2.TransactionId); AssertTState(loadresponse.PendingStates[0].State,expectedState2); } public virtual async Task ConfirmOneAndCancelOne(bool useTwoSteps = false, bool reverseOrder = false) { var stateStorage = await this.stateStorageFactory(); var loadresponse = await stateStorage.Load(); var etag = loadresponse.ETag; var metadata = loadresponse.Metadata; var initialstate = loadresponse.CommittedState; var expectedState = this.stateFactory(123); var pendingstate1 = MakePendingState(1, expectedState, false); var pendingstate2 = MakePendingState(2, this.stateFactory(456), false); etag = await stateStorage.Store(etag, metadata, new List<PendingTransactionState<TState>>() { pendingstate1, pendingstate2 }, null, null); if (useTwoSteps) { if (reverseOrder) { etag = await stateStorage.Store(etag, metadata, emptyPendingStates, 1, null); etag = await stateStorage.Store(etag, metadata, emptyPendingStates, null, 1); } else { etag = await stateStorage.Store(etag, metadata, emptyPendingStates, 1, null); etag = await stateStorage.Store(etag, metadata, emptyPendingStates, null, 1); } } else { etag = await stateStorage.Store(etag, metadata, emptyPendingStates, 1, 1); } loadresponse = await stateStorage.Load(); etag = loadresponse.ETag; metadata = loadresponse.Metadata; loadresponse.Should().NotBeNull(); loadresponse.Metadata.Should().NotBeNull(); loadresponse.CommittedSequenceId.Should().Be(1); loadresponse.PendingStates.Count.Should().Be(0); AssertTState(loadresponse.CommittedState,expectedState); loadresponse.Metadata.TimeStamp.Should().Be(default(DateTime)); loadresponse.Metadata.CommitRecords.Count.Should().Be(0); } public virtual async Task PrepareMany(int count) { var stateStorage = await this.stateStorageFactory(); var loadresponse = await stateStorage.Load(); var etag = loadresponse.ETag; var metadata = loadresponse.Metadata; var initialstate = loadresponse.CommittedState; var pendingstates = new List<PendingTransactionState<TState>>(); var expectedStates = new List<TState>(); for (int i = 0; i < count; i++) { expectedStates.Add(this.stateFactory(i * 1000)); } for (int i = 0; i < count; i++) { pendingstates.Add(MakePendingState(i + 1, expectedStates[i], false)); } etag = await stateStorage.Store(etag, metadata, pendingstates, null, null); loadresponse = await stateStorage.Load(); etag = loadresponse.ETag; metadata = loadresponse.Metadata; loadresponse.Should().NotBeNull(); loadresponse.Metadata.Should().NotBeNull(); loadresponse.CommittedSequenceId.Should().Be(0); loadresponse.PendingStates.Count.Should().Be(count); for (int i = 0; i < count; i++) { loadresponse.PendingStates[i].SequenceId.Should().Be(i+1); loadresponse.PendingStates[i].TimeStamp.Should().Be(pendingstates[i].TimeStamp); loadresponse.PendingStates[i].TransactionManager.Should().Be(pendingstates[i].TransactionManager); loadresponse.PendingStates[i].TransactionId.Should().Be(pendingstates[i].TransactionId); AssertTState(loadresponse.PendingStates[i].State,expectedStates[i]); } } public virtual async Task ConfirmMany(int count, bool useTwoSteps) { var stateStorage = await this.stateStorageFactory(); var loadresponse = await stateStorage.Load(); var etag = loadresponse.ETag; var metadata = loadresponse.Metadata; var initialstate = loadresponse.CommittedState; var expectedStates = new List<TState>(); for (int i = 0; i < count; i++) { expectedStates.Add(this.stateFactory(i * 1000)); } var pendingstates = new List<PendingTransactionState<TState>>(); for (int i = 0; i < count; i++) { pendingstates.Add(MakePendingState(i + 1, expectedStates[i], false)); } if (useTwoSteps) { etag = await stateStorage.Store(etag, metadata, pendingstates, null, null); etag = await stateStorage.Store(etag, metadata, emptyPendingStates, count, null); } else { etag = await stateStorage.Store(etag, metadata, pendingstates, count, null); } loadresponse = await stateStorage.Load(); etag = loadresponse.ETag; metadata = loadresponse.Metadata; loadresponse.Should().NotBeNull(); loadresponse.Metadata.Should().NotBeNull(); loadresponse.CommittedSequenceId.Should().Be(count); loadresponse.PendingStates.Count.Should().Be(0); AssertTState(loadresponse.CommittedState,expectedStates[count - 1]); loadresponse.Metadata.TimeStamp.Should().Be(default(DateTime)); loadresponse.Metadata.CommitRecords.Count.Should().Be(0); } public virtual async Task CancelMany(int count) { var stateStorage = await this.stateStorageFactory(); var loadresponse = await stateStorage.Load(); var etag = loadresponse.ETag; var metadata = loadresponse.Metadata; var initialstate = loadresponse.CommittedState; var expectedStates = new List<TState>(); for (int i = 0; i < count; i++) { expectedStates.Add(this.stateFactory(i * 1000)); } var pendingstates = new List<PendingTransactionState<TState>>(); for (int i = 0; i < count; i++) { pendingstates.Add(MakePendingState(i + 1, expectedStates[i], false)); } etag = await stateStorage.Store(etag, metadata, pendingstates, null, null); etag = await stateStorage.Store(etag, metadata, emptyPendingStates, null, 0); loadresponse = await stateStorage.Load(); etag = loadresponse.ETag; metadata = loadresponse.Metadata; loadresponse.Should().NotBeNull(); loadresponse.Metadata.Should().NotBeNull(); loadresponse.CommittedSequenceId.Should().Be(0); loadresponse.PendingStates.Count.Should().Be(0); AssertTState(loadresponse.CommittedState,initialstate); loadresponse.Metadata.TimeStamp.Should().Be(default(DateTime)); loadresponse.Metadata.CommitRecords.Count.Should().Be(0); } public virtual async Task ReplaceMany(int count) { var stateStorage = await this.stateStorageFactory(); var loadresponse = await stateStorage.Load(); var etag = loadresponse.ETag; var metadata = loadresponse.Metadata; var initialstate = loadresponse.CommittedState; var expectedStates1 = new List<TState>(); for (int i = 0; i < count; i++) { expectedStates1.Add(this.stateFactory(i * 1000 + 1)); } var expectedStates2 = new List<TState>(); for (int i = 0; i < count; i++) { expectedStates2.Add(this.stateFactory(i * 1000)); } var pendingstates1 = new List<PendingTransactionState<TState>>(); for (int i = 0; i < count; i++) { pendingstates1.Add(MakePendingState(i + 1, expectedStates1[i], false)); } var pendingstates2 = new List<PendingTransactionState<TState>>(); for (int i = 0; i < count; i++) { pendingstates2.Add(MakePendingState(i + 1, expectedStates2[i], false)); } etag = await stateStorage.Store(etag, metadata, pendingstates1, null, null); etag = await stateStorage.Store(etag, metadata, pendingstates2, null, null); loadresponse = await stateStorage.Load(); etag = loadresponse.ETag; metadata = loadresponse.Metadata; loadresponse.Should().NotBeNull(); loadresponse.Metadata.Should().NotBeNull(); loadresponse.CommittedSequenceId.Should().Be(0); loadresponse.PendingStates.Count.Should().Be(count); for (int i = 0; i < count; i++) { loadresponse.PendingStates[i].SequenceId.Should().Be(i + 1); loadresponse.PendingStates[i].TimeStamp.Should().Be(pendingstates2[i].TimeStamp); loadresponse.PendingStates[i].TransactionManager.Should().Be(pendingstates2[i].TransactionManager); loadresponse.PendingStates[i].TransactionId.Should().Be(pendingstates2[i].TransactionId); AssertTState(loadresponse.PendingStates[i].State, expectedStates2[i]); } } public virtual async Task GrowingBatch() { var stateStorage = await this.stateStorageFactory(); var loadresponse = await stateStorage.Load(); var etag = loadresponse.ETag; var metadata = loadresponse.Metadata; var initialstate = loadresponse.CommittedState; var pendingstate1 = MakePendingState(1, this.stateFactory(11), false); var pendingstate2 = MakePendingState(2, this.stateFactory(22), false); var pendingstate3a = MakePendingState(3, this.stateFactory(333), false); var pendingstate4a = MakePendingState(4, this.stateFactory(444), false); var pendingstate3b = MakePendingState(3, this.stateFactory(33), false); var pendingstate4b = MakePendingState(4, this.stateFactory(44), false); var pendingstate5 = MakePendingState(5, this.stateFactory(55), false); var expectedState6 = this.stateFactory(66); var pendingstate6 = MakePendingState(6, expectedState6, false); var expectedState7 = this.stateFactory(77); var pendingstate7 = MakePendingState(7, expectedState7, false); var expectedState8 = this.stateFactory(88); var pendingstate8 = MakePendingState(8, expectedState8, false); // prepare 1,2,3a,4a etag = await stateStorage.Store(etag, metadata, new List<PendingTransactionState<TState>>() { pendingstate1, pendingstate2, pendingstate3a, pendingstate4a}, null, null); // replace 3b,4b, prepare 5, 6, 7, 8 confirm 1, 2, 3b, 4b, 5, 6 etag = await stateStorage.Store(etag, metadata, new List<PendingTransactionState<TState>>() { pendingstate3b, pendingstate4b, pendingstate5, pendingstate6, pendingstate7, pendingstate8 }, 6, null); loadresponse = await stateStorage.Load(); etag = loadresponse.ETag; metadata = loadresponse.Metadata; loadresponse.Should().NotBeNull(); loadresponse.Metadata.Should().NotBeNull(); loadresponse.CommittedSequenceId.Should().Be(6); AssertTState(loadresponse.CommittedState, expectedState6); loadresponse.Metadata.TimeStamp.Should().Be(default(DateTime)); loadresponse.Metadata.CommitRecords.Count.Should().Be(0); loadresponse.PendingStates.Count.Should().Be(2); loadresponse.PendingStates[0].SequenceId.Should().Be(7); loadresponse.PendingStates[0].TimeStamp.Should().Be(pendingstate7.TimeStamp); loadresponse.PendingStates[0].TransactionManager.Should().Be(pendingstate7.TransactionManager); loadresponse.PendingStates[0].TransactionId.Should().Be(pendingstate7.TransactionId); AssertTState(loadresponse.PendingStates[0].State, expectedState7); loadresponse.PendingStates[1].SequenceId.Should().Be(8); loadresponse.PendingStates[1].TimeStamp.Should().Be(pendingstate8.TimeStamp); loadresponse.PendingStates[1].TransactionManager.Should().Be(pendingstate8.TransactionManager); loadresponse.PendingStates[1].TransactionId.Should().Be(pendingstate8.TransactionId); AssertTState(loadresponse.PendingStates[1].State, expectedState8); } public virtual async Task ShrinkingBatch() { var stateStorage = await this.stateStorageFactory(); var loadresponse = await stateStorage.Load(); var etag = loadresponse.ETag; var metadata = loadresponse.Metadata; var initialstate = loadresponse.CommittedState; var pendingstate1 = MakePendingState(1, this.stateFactory(11), false); var pendingstate2 = MakePendingState(2, this.stateFactory(22), false); var pendingstate3a = MakePendingState(3, this.stateFactory(333), false); var pendingstate4a = MakePendingState(4, this.stateFactory(444), false); var pendingstate5 = MakePendingState(5, this.stateFactory(55), false); var pendingstate6 = MakePendingState(6, this.stateFactory(66), false); var pendingstate7 = MakePendingState(7, this.stateFactory(77), false); var pendingstate8 = MakePendingState(8, this.stateFactory(88), false); var expectedState3b = this.stateFactory(33); var pendingstate3b = MakePendingState(3, expectedState3b, false); var expectedState4b = this.stateFactory(44); var pendingstate4b = MakePendingState(4, expectedState4b, false); // prepare 1,2,3a,4a, 5, 6, 7, 8 etag = await stateStorage.Store(etag, metadata, new List<PendingTransactionState<TState>>() { pendingstate1, pendingstate2, pendingstate3a, pendingstate4a, pendingstate5, pendingstate6, pendingstate7, pendingstate8 }, null, null); // replace 3b,4b, confirm 1, 2, 3b, cancel 5, 6, 7, 8 etag = await stateStorage.Store(etag, metadata, new List<PendingTransactionState<TState>>() { pendingstate3b, pendingstate4b }, 3, 4); loadresponse = await stateStorage.Load(); etag = loadresponse.ETag; metadata = loadresponse.Metadata; loadresponse.Should().NotBeNull(); loadresponse.Metadata.Should().NotBeNull(); loadresponse.CommittedSequenceId.Should().Be(3); AssertTState(loadresponse.CommittedState, expectedState3b); loadresponse.Metadata.TimeStamp.Should().Be(default(DateTime)); loadresponse.Metadata.CommitRecords.Count.Should().Be(0); loadresponse.PendingStates.Count.Should().Be(1); loadresponse.PendingStates[0].SequenceId.Should().Be(4); loadresponse.PendingStates[0].TimeStamp.Should().Be(pendingstate4b.TimeStamp); loadresponse.PendingStates[0].TransactionManager.Should().Be(pendingstate4b.TransactionManager); loadresponse.PendingStates[0].TransactionId.Should().Be(pendingstate4b.TransactionId); AssertTState(loadresponse.PendingStates[0].State, expectedState4b); } } }
// ------------------------------------------------------------------------------ // Copyright (c) 2014 Microsoft Corporation // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // ------------------------------------------------------------------------------ namespace Microsoft.Live { using System; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using System.Diagnostics; using System.Net; using System.Text; using System.Threading; using Microsoft.Live.Operations; /// <summary> /// This is the class that applications use to authenticate the user and obtain access token after user /// grants consent to the application. /// </summary> // TODO: consider making this class a helper class. There is really not much that can be shared between // Win8 & WP for this class anymore. public sealed partial class LiveAuthClient : INotifyPropertyChanged { #region Constants /// <summary> /// Defines local storage keys. /// </summary> internal static class StorageConstants { public const string RefreshToken = "Microsoft.Live.LiveAuthClient.RefreshToken"; public const string SigningOut = "Microsoft.Live.LiveAuthClient.SigningOut"; } /// <summary> /// Default redirect url for desktop apps. /// </summary> internal static readonly string DefaultRedirectPath = "/oauth20_desktop.srf"; /// <summary> /// Default consent endpoint. /// </summary> internal static readonly string DefaultConsentEndpoint = "https://login.live.com"; /// <summary> /// Authorize endpoint. /// </summary> internal static readonly string AuthorizeEndpoint = "/oauth20_authorize.srf"; /// <summary> /// Token endpoint. /// </summary> internal static readonly string TokenEndpoint = "/oauth20_token.srf"; /// <summary> /// Logout endpoint. /// </summary> internal static readonly string LogoutUrl = "https://login.live.com/oauth20_logout.srf"; #endregion #region Private Member Fields private static readonly char[] ScopeSeparators = new char[] { ' ', ',' }; private const string AuthorizeUrlTemplate = @"{0}{1}?" + AuthConstants.ClientId + "={2}&" + AuthConstants.Callback + "={3}&" + AuthConstants.Scope + "={4}&" + AuthConstants.ResponseType + "={5}&" + "locale={6}&display={7}{8}"; private string clientId; private string redirectUri; private LiveConnectSession session; private List<string> scopes; /// <summary> /// Used for locking Initialize and Login operations. /// </summary> private int asyncInProgress; private SynchronizationContextWrapper syncContext; #endregion #region Properties #if DEBUG /// <summary> /// Allows the application to override the default consent endpoint. /// </summary> public static string AuthEndpointOverride { get; set; } /// <summary> /// Allows the application to override the default logout endpoint. /// </summary> public static string LogoutEndpointOverride { get; set; } #endif /// <summary> /// Gets the current session object. /// </summary> public LiveConnectSession Session { get { return this.session; } internal set { this.session = value; this.NotifyPropertyChanged("Session"); } } /// <summary> /// Gets and sets the response type used for the consent request. /// </summary> internal ResponseType ResponseType { get; set; } /// <summary> /// Gets and sets the display type used for the consent request. /// </summary> internal DisplayType Display { get; set; } /// <summary> /// Gets the root consent endpoint. /// </summary> internal string ConsentEndpoint { get; private set; } /// <summary> /// Gets and sets the IAuthClient instance. /// </summary> internal IAuthClient AuthClient { get; set; } /// <summary> /// Gets the redirect url. /// </summary> internal string RedirectUrl { get { return this.redirectUri; } } #endregion #region Public Events /// <summary> /// An event that fires when the Session property is changed. /// </summary> public event PropertyChangedEventHandler PropertyChanged; #endregion #region Private & internal Methods /// <summary> /// Constructs the consent url. /// </summary> internal string BuildLoginUrl(string scopes, bool silent) { string consentUrl = String.Format( LiveAuthClient.AuthorizeUrlTemplate, this.ConsentEndpoint, AuthorizeEndpoint, HttpUtility.UrlEncode(this.clientId), HttpUtility.UrlEncode(this.redirectUri), HttpUtility.UrlEncode(scopes), HttpUtility.UrlEncode(this.ResponseType.ToString().ToLowerInvariant()), HttpUtility.UrlEncode(Platform.GetCurrentUICultureString()), silent ? "none" : HttpUtility.UrlEncode(this.Display.ToString().ToLowerInvariant()), silent ? string.Empty : "&theme=" + HttpUtility.UrlEncode(this.Theme.ToString().ToLowerInvariant())); return consentUrl; } /// <summary> /// Converts a list of offers into one single offer string with space as separator. /// </summary> internal static string BuildScopeString(IEnumerable<string> scopes) { var sb = new StringBuilder(); if (scopes != null) { foreach (string s in scopes) { sb.Append(s).Append(LiveAuthClient.ScopeSeparators[0]); } } return sb.ToString().TrimEnd(LiveAuthClient.ScopeSeparators); } /// <summary> /// Calculates when the access token will be expired. /// </summary> internal static DateTimeOffset CalculateExpiration(string expiresIn) { DateTimeOffset expires = DateTimeOffset.UtcNow; long seconds; if (long.TryParse(expiresIn, out seconds)) { expires = expires.AddSeconds(seconds); } return expires; } /// <summary> /// Converts a single offer string into a list of offers. /// </summary> internal static IEnumerable<string> ParseScopeString(string scopesString) { return new List<string>( scopesString.Split(LiveAuthClient.ScopeSeparators, StringSplitOptions.RemoveEmptyEntries)); } /// <summary> /// Creates a error LoginResult object. /// </summary> private static LiveLoginResult GetErrorResult(IDictionary<string, object> result) { Debug.Assert(result.ContainsKey(AuthConstants.Error)); var errorCode = result[AuthConstants.Error] as string; if (errorCode.Equals(AuthErrorCodes.AccessDenied, StringComparison.Ordinal)) { return new LiveLoginResult(LiveConnectSessionStatus.NotConnected, null); } if (errorCode.Equals(AuthErrorCodes.UnknownUser, StringComparison.Ordinal)) { return new LiveLoginResult(LiveConnectSessionStatus.Unknown, null); } string errorDescription = string.Empty; if (result.ContainsKey(AuthConstants.ErrorDescription)) { errorDescription = result[AuthConstants.ErrorDescription] as string; } return new LiveLoginResult(new LiveAuthException(errorCode, errorDescription)); } /// <summary> /// Initializes the member variables. /// </summary> private void InitializeMembers(string clientId, string redirectUri) { this.clientId = clientId; #if DEBUG this.ConsentEndpoint = string.IsNullOrEmpty(LiveAuthClient.AuthEndpointOverride) ? LiveAuthClient.DefaultConsentEndpoint : LiveAuthClient.AuthEndpointOverride.TrimEnd('/'); #else this.ConsentEndpoint = LiveAuthClient.DefaultConsentEndpoint; #endif if (!string.IsNullOrEmpty(redirectUri)) { this.redirectUri = redirectUri; } else { this.redirectUri = string.Format( CultureInfo.InvariantCulture, "{0}{1}", new Uri(this.ConsentEndpoint).GetComponents(UriComponents.SchemeAndServer, UriFormat.SafeUnescaped), LiveAuthClient.DefaultRedirectPath); } this.ResponseType = Platform.GetResponseType(); this.Display = Platform.GetDisplayType(); } /// <summary> /// Fires the property changed event. /// </summary> private void NotifyPropertyChanged(String propertyName) { PropertyChangedEventHandler handler = this.PropertyChanged; if (handler != null) { Debug.Assert(this.syncContext != null); this.syncContext.Post(() => handler(this, new PropertyChangedEventArgs(propertyName))); } } /// <summary> /// Parses the query string into key-value pairs. /// </summary> private static IDictionary<string, object> ParseQueryString(string query) { var values = new Dictionary<string, object>(); if (!string.IsNullOrEmpty(query)) { query = query.TrimStart(new char[] { '?', '#' }); if (!String.IsNullOrEmpty(query)) { string[] parameters = query.Split(new char[] { '&' }); foreach (string parameter in parameters) { string[] pair = parameter.Split(new char[] { '=' }); if (pair.Length == 2) { values.Add(pair[0], pair[1]); } } } } return values; } /// <summary> /// Parse the response data. /// </summary> private LiveLoginResult ParseResponseFragment(string fragment) { Debug.Assert(!string.IsNullOrEmpty(fragment)); LiveLoginResult loginResult = null; IDictionary<string, object> result = LiveAuthClient.ParseQueryString(fragment); if (result.ContainsKey(AuthConstants.AccessToken)) { LiveConnectSession sessionData = CreateSession(this, result); loginResult = new LiveLoginResult(LiveConnectSessionStatus.Connected, sessionData); } else if (result.ContainsKey(AuthConstants.Error)) { loginResult = GetErrorResult(result); } return loginResult; } /// <summary> /// Ensures that only one async operation is active at any time. /// </summary> private void PrepareForAsync() { Debug.Assert( this.asyncInProgress == 0 || this.asyncInProgress == 1, "Unexpected value for 'asyncInProgress' field."); if (this.asyncInProgress > 0) { throw new LiveAuthException( AuthErrorCodes.ClientError, ResourceHelper.GetString("AsyncOperationInProgress")); } Interlocked.Increment(ref this.asyncInProgress); this.syncContext = SynchronizationContextWrapper.Current; } /// <summary> /// Processes authentication result from the server. /// Method could return synchronously or asynchronously. /// </summary> private void ProcessAuthResponse(string responseData, Action<LiveLoginResult> callback) { if (string.IsNullOrEmpty(responseData)) { // non-connected user scenario. return status unknown. callback(new LiveLoginResult(LiveConnectSessionStatus.Unknown, null)); return; } Uri responseUrl; try { responseUrl = new Uri(responseData, UriKind.Absolute); } catch (FormatException) { callback(new LiveLoginResult( new LiveAuthException(AuthErrorCodes.ServerError, ResourceHelper.GetString("ServerError")))); return; } if (!string.IsNullOrEmpty(responseUrl.Fragment)) { callback(this.ParseResponseFragment(responseUrl.Fragment)); return; } if (!string.IsNullOrEmpty(responseUrl.Query)) { IDictionary<string, object> parameters = LiveAuthClient.ParseQueryString(responseUrl.Query); if (parameters.ContainsKey(AuthConstants.Code)) { var authCode = parameters[AuthConstants.Code] as string; if (!string.IsNullOrEmpty(authCode)) { var refreshOp = new RefreshTokenOperation( this, this.clientId, authCode, this.redirectUri, this.syncContext); refreshOp.OperationCompletedCallback = callback; refreshOp.Execute(); return; } } else if (parameters.ContainsKey(AuthConstants.Error)) { callback(GetErrorResult(parameters)); return; } } callback( new LiveLoginResult( new LiveAuthException(AuthErrorCodes.ServerError, ResourceHelper.GetString("ServerError")))); } #endregion } }
using System; using System.Collections.Generic; using System.Reactive.Linq; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Layout; using Xunit; namespace Avalonia.Controls.UnitTests.Presenters { public class ScrollContentPresenterTests { [Theory] [InlineData(HorizontalAlignment.Stretch, VerticalAlignment.Stretch, 10, 10, 80, 80)] [InlineData(HorizontalAlignment.Left, VerticalAlignment.Stretch, 10, 10, 16, 80)] [InlineData(HorizontalAlignment.Right, VerticalAlignment.Stretch, 74, 10, 16, 80)] [InlineData(HorizontalAlignment.Center, VerticalAlignment.Stretch, 42, 10, 16, 80)] [InlineData(HorizontalAlignment.Stretch, VerticalAlignment.Top, 10, 10, 80, 16)] [InlineData(HorizontalAlignment.Stretch, VerticalAlignment.Bottom, 10, 74, 80, 16)] [InlineData(HorizontalAlignment.Stretch, VerticalAlignment.Center, 10, 42, 80, 16)] public void Alignment_And_Padding_Are_Applied_To_Child_Bounds( HorizontalAlignment h, VerticalAlignment v, double expectedX, double expectedY, double expectedWidth, double expectedHeight) { Border content; var target = new ScrollContentPresenter { Padding = new Thickness(10), Content = content = new Border { MinWidth = 16, MinHeight = 16, HorizontalAlignment = h, VerticalAlignment = v, }, }; target.UpdateChild(); target.Measure(new Size(100, 100)); target.Arrange(new Rect(0, 0, 100, 100)); Assert.Equal(new Rect(expectedX, expectedY, expectedWidth, expectedHeight), content.Bounds); } [Fact] public void DesiredSize_Is_Content_Size_When_Smaller_Than_AvailableSize() { var target = new ScrollContentPresenter { Padding = new Thickness(10), Content = new Border { MinWidth = 16, MinHeight = 16, }, }; target.UpdateChild(); target.Measure(new Size(100, 100)); target.Arrange(new Rect(0, 0, 100, 100)); Assert.Equal(new Size(16, 16), target.DesiredSize); } [Fact] public void DesiredSize_Is_AvailableSize_When_Content_Larger_Than_AvailableSize() { var target = new ScrollContentPresenter { Padding = new Thickness(10), Content = new Border { MinWidth = 160, MinHeight = 160, }, }; target.UpdateChild(); target.Measure(new Size(100, 100)); target.Arrange(new Rect(0, 0, 100, 100)); Assert.Equal(new Size(100, 100), target.DesiredSize); } [Fact] public void Content_Can_Be_Larger_Than_Viewport() { TestControl content; var target = new ScrollContentPresenter { CanHorizontallyScroll = true, CanVerticallyScroll = true, Content = content = new TestControl(), }; target.UpdateChild(); target.Measure(new Size(100, 100)); target.Arrange(new Rect(0, 0, 100, 100)); Assert.Equal(new Rect(0, 0, 150, 150), content.Bounds); } [Fact] public void Content_Can_Be_Offset() { Border content; var target = new ScrollContentPresenter { CanHorizontallyScroll = true, CanVerticallyScroll = true, Content = content = new Border { Width = 150, Height = 150, }, }; target.UpdateChild(); target.Measure(new Size(100, 100)); target.Arrange(new Rect(0, 0, 100, 100)); target.Offset = new Vector(25, 25); target.Measure(new Size(100, 100)); target.Arrange(new Rect(0, 0, 100, 100)); Assert.Equal(new Rect(-25, -25, 150, 150), content.Bounds); } [Fact] public void Measure_Should_Pass_Bounded_X_If_CannotScrollHorizontally() { var child = new TestControl(); var target = new ScrollContentPresenter { CanVerticallyScroll = true, Content = child, }; target.UpdateChild(); target.Measure(new Size(100, 100)); Assert.Equal(new Size(100, double.PositiveInfinity), child.AvailableSize); } [Fact] public void Measure_Should_Pass_Unbounded_X_If_CanScrollHorizontally() { var child = new TestControl(); var target = new ScrollContentPresenter { CanHorizontallyScroll = true, CanVerticallyScroll = true, Content = child, }; target.UpdateChild(); target.Measure(new Size(100, 100)); Assert.Equal(Size.Infinity, child.AvailableSize); } [Fact] public void Arrange_Should_Set_Viewport_And_Extent_In_That_Order() { var target = new ScrollContentPresenter { Content = new Border { Width = 40, Height = 50 } }; var set = new List<string>(); target.UpdateChild(); target.Measure(new Size(100, 100)); target.GetObservable(ScrollViewer.ViewportProperty).Skip(1).Subscribe(_ => set.Add("Viewport")); target.GetObservable(ScrollViewer.ExtentProperty).Skip(1).Subscribe(_ => set.Add("Extent")); target.Arrange(new Rect(0, 0, 100, 100)); Assert.Equal(new[] { "Viewport", "Extent" }, set); } [Fact] public void Should_Correctly_Arrange_Child_Larger_Than_Viewport() { var child = new Canvas { MinWidth = 150, MinHeight = 150 }; var target = new ScrollContentPresenter { Content = child, }; target.UpdateChild(); target.Measure(Size.Infinity); target.Arrange(new Rect(0, 0, 100, 100)); Assert.Equal(new Size(150, 150), child.Bounds.Size); } [Fact] public void Arrange_Should_Constrain_Child_Width_When_CanHorizontallyScroll_False() { var child = new WrapPanel { Children = { new Border { Width = 40, Height = 50 }, new Border { Width = 40, Height = 50 }, new Border { Width = 40, Height = 50 }, } }; var target = new ScrollContentPresenter { Content = child, CanHorizontallyScroll = false, }; target.UpdateChild(); target.Measure(Size.Infinity); target.Arrange(new Rect(0, 0, 100, 100)); Assert.Equal(100, child.Bounds.Width); } [Fact] public void Extent_Should_Include_Content_Margin() { var target = new ScrollContentPresenter { Content = new Border { Width = 100, Height = 100, Margin = new Thickness(5), } }; target.UpdateChild(); target.Measure(new Size(50, 50)); target.Arrange(new Rect(0, 0, 50, 50)); Assert.Equal(new Size(110, 110), target.Extent); } [Fact] public void Extent_Width_Should_Be_Arrange_Width_When_CanScrollHorizontally_False() { var child = new WrapPanel { Children = { new Border { Width = 40, Height = 50 }, new Border { Width = 40, Height = 50 }, new Border { Width = 40, Height = 50 }, } }; var target = new ScrollContentPresenter { Content = child, CanHorizontallyScroll = false, }; target.UpdateChild(); target.Measure(Size.Infinity); target.Arrange(new Rect(0, 0, 100, 100)); Assert.Equal(new Size(100, 100), target.Extent); } [Fact] public void Setting_Offset_Should_Invalidate_Arrange() { var target = new ScrollContentPresenter { Content = new Border { Width = 140, Height = 150 } }; target.UpdateChild(); target.Measure(new Size(100, 100)); target.Arrange(new Rect(0, 0, 100, 100)); target.Offset = new Vector(10, 100); Assert.True(target.IsMeasureValid); Assert.False(target.IsArrangeValid); } [Fact] public void BringDescendantIntoView_Should_Update_Offset() { var target = new ScrollContentPresenter { Width = 100, Height = 100, Content = new Border { Width = 200, Height = 200, } }; target.UpdateChild(); target.Measure(Size.Infinity); target.Arrange(new Rect(0, 0, 100, 100)); target.BringDescendantIntoView(target.Child, new Rect(200, 200, 0, 0)); Assert.Equal(new Vector(100, 100), target.Offset); } [Fact] public void BringDescendantIntoView_Should_Handle_Child_Margin() { Border border; var target = new ScrollContentPresenter { CanHorizontallyScroll = true, CanVerticallyScroll = true, Width = 100, Height = 100, Content = new Decorator { Margin = new Thickness(50), Child = border = new Border { Width = 200, Height = 200, } } }; target.UpdateChild(); target.Measure(Size.Infinity); target.Arrange(new Rect(0, 0, 100, 100)); target.BringDescendantIntoView(border, new Rect(200, 200, 0, 0)); Assert.Equal(new Vector(150, 150), target.Offset); } private class TestControl : Control { public Size AvailableSize { get; private set; } protected override Size MeasureOverride(Size availableSize) { AvailableSize = availableSize; return new Size(150, 150); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*============================================================ ** ** ** ** Purpose: This class will encapsulate a byte and provide an ** Object representation of it. ** ** ===========================================================*/ using System.Diagnostics.Contracts; using System.Globalization; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; namespace System { [Serializable] [StructLayout(LayoutKind.Sequential)] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public struct Byte : IComparable, IConvertible, IFormattable, IComparable<Byte>, IEquatable<Byte> { private byte m_value; // Do not rename (binary serialization) // The maximum value that a Byte may represent: 255. public const byte MaxValue = (byte)0xFF; // The minimum value that a Byte may represent: 0. public const byte MinValue = 0; // Compares this object to another object, returning an integer that // indicates the relationship. // Returns a value less than zero if this object // null is considered to be less than any instance. // If object is not of type byte, this method throws an ArgumentException. // public int CompareTo(Object value) { if (value == null) { return 1; } if (!(value is Byte)) { throw new ArgumentException(SR.Arg_MustBeByte); } return m_value - (((Byte)value).m_value); } public int CompareTo(Byte value) { return m_value - value; } // Determines whether two Byte objects are equal. public override bool Equals(Object obj) { if (!(obj is Byte)) { return false; } return m_value == ((Byte)obj).m_value; } [NonVersionable] public bool Equals(Byte obj) { return m_value == obj; } // Gets a hash code for this instance. public override int GetHashCode() { return m_value; } [Pure] public static byte Parse(String s) { if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Parse(s.AsSpan(), NumberStyles.Integer, NumberFormatInfo.CurrentInfo); } [Pure] public static byte Parse(String s, NumberStyles style) { NumberFormatInfo.ValidateParseStyleInteger(style); if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Parse(s.AsSpan(), style, NumberFormatInfo.CurrentInfo); } [Pure] public static byte Parse(String s, IFormatProvider provider) { if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Parse(s.AsSpan(), NumberStyles.Integer, NumberFormatInfo.GetInstance(provider)); } // Parses an unsigned byte from a String in the given style. If // a NumberFormatInfo isn't specified, the current culture's // NumberFormatInfo is assumed. [Pure] public static byte Parse(String s, NumberStyles style, IFormatProvider provider) { NumberFormatInfo.ValidateParseStyleInteger(style); if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Parse(s.AsSpan(), style, NumberFormatInfo.GetInstance(provider)); } public static byte Parse(ReadOnlySpan<char> s, NumberStyles style = NumberStyles.Integer, IFormatProvider provider = null) { NumberFormatInfo.ValidateParseStyleInteger(style); return Parse(s, style, NumberFormatInfo.GetInstance(provider)); } private static byte Parse(ReadOnlySpan<char> s, NumberStyles style, NumberFormatInfo info) { int i = 0; try { i = Number.ParseInt32(s, style, info); } catch (OverflowException e) { throw new OverflowException(SR.Overflow_Byte, e); } if (i < MinValue || i > MaxValue) throw new OverflowException(SR.Overflow_Byte); return (byte)i; } public static bool TryParse(String s, out Byte result) { if (s == null) { result = 0; return false; } return TryParse(s.AsSpan(), NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result); } public static bool TryParse(String s, NumberStyles style, IFormatProvider provider, out Byte result) { NumberFormatInfo.ValidateParseStyleInteger(style); if (s == null) { result = 0; return false; } return TryParse(s.AsSpan(), style, NumberFormatInfo.GetInstance(provider), out result); } public static bool TryParse(ReadOnlySpan<char> s, out byte result, NumberStyles style = NumberStyles.Integer, IFormatProvider provider = null) { NumberFormatInfo.ValidateParseStyleInteger(style); return TryParse(s, style, NumberFormatInfo.GetInstance(provider), out result); } private static bool TryParse(ReadOnlySpan<char> s, NumberStyles style, NumberFormatInfo info, out Byte result) { result = 0; int i; if (!Number.TryParseInt32(s, style, info, out i)) { return false; } if (i < MinValue || i > MaxValue) { return false; } result = (byte)i; return true; } [Pure] public override String ToString() { Contract.Ensures(Contract.Result<String>() != null); return Number.FormatInt32(m_value, null, NumberFormatInfo.CurrentInfo); } [Pure] public String ToString(String format) { Contract.Ensures(Contract.Result<String>() != null); return Number.FormatInt32(m_value, format, NumberFormatInfo.CurrentInfo); } [Pure] public String ToString(IFormatProvider provider) { Contract.Ensures(Contract.Result<String>() != null); return Number.FormatInt32(m_value, null, NumberFormatInfo.GetInstance(provider)); } [Pure] public String ToString(String format, IFormatProvider provider) { Contract.Ensures(Contract.Result<String>() != null); return Number.FormatInt32(m_value, format, NumberFormatInfo.GetInstance(provider)); } // // IConvertible implementation // [Pure] public TypeCode GetTypeCode() { return TypeCode.Byte; } bool IConvertible.ToBoolean(IFormatProvider provider) { return Convert.ToBoolean(m_value); } char IConvertible.ToChar(IFormatProvider provider) { return Convert.ToChar(m_value); } sbyte IConvertible.ToSByte(IFormatProvider provider) { return Convert.ToSByte(m_value); } byte IConvertible.ToByte(IFormatProvider provider) { return m_value; } short IConvertible.ToInt16(IFormatProvider provider) { return Convert.ToInt16(m_value); } ushort IConvertible.ToUInt16(IFormatProvider provider) { return Convert.ToUInt16(m_value); } int IConvertible.ToInt32(IFormatProvider provider) { return Convert.ToInt32(m_value); } uint IConvertible.ToUInt32(IFormatProvider provider) { return Convert.ToUInt32(m_value); } long IConvertible.ToInt64(IFormatProvider provider) { return Convert.ToInt64(m_value); } ulong IConvertible.ToUInt64(IFormatProvider provider) { return Convert.ToUInt64(m_value); } float IConvertible.ToSingle(IFormatProvider provider) { return Convert.ToSingle(m_value); } double IConvertible.ToDouble(IFormatProvider provider) { return Convert.ToDouble(m_value); } Decimal IConvertible.ToDecimal(IFormatProvider provider) { return Convert.ToDecimal(m_value); } DateTime IConvertible.ToDateTime(IFormatProvider provider) { throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Byte", "DateTime")); } Object IConvertible.ToType(Type type, IFormatProvider provider) { return Convert.DefaultToType((IConvertible)this, type, provider); } } }
//--------------------------------------------------------------------- // <copyright file="ResourceSetExpression.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // <summary> // Respresents a resource set in resource bound expression tree. // </summary> // // @owner [....] //--------------------------------------------------------------------- namespace System.Data.Services.Client { #region Namespaces. using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Linq.Expressions; using System.Reflection; #endregion Namespaces. /// <summary>ResourceSet Expression</summary> [DebuggerDisplay("ResourceSetExpression {Source}.{MemberExpression}")] internal class ResourceSetExpression : ResourceExpression { #region Private fields. /// <summary> /// The (static) type of the resources in this resource set. /// The resource type can differ from this.Type if this expression represents a transparent scope. /// For example, in TransparentScope{Category, Product}, the true element type is Product. /// </summary> private readonly Type resourceType; /// <summary>property member name</summary> private readonly Expression member; /// <summary>key predicate</summary> private Dictionary<PropertyInfo, ConstantExpression> keyFilter; /// <summary>sequence query options</summary> private List<QueryOptionExpression> sequenceQueryOptions; /// <summary>enclosing transparent scope</summary> private TransparentAccessors transparentScope; #endregion Private fields. /// <summary> /// Creates a ResourceSet expression /// </summary> /// <param name="type">the return type of the expression</param> /// <param name="source">the source expression</param> /// <param name="memberExpression">property member name</param> /// <param name="resourceType">the element type of the resource set</param> /// <param name="expandPaths">expand paths for resource set</param> /// <param name="countOption">count query option for the resource set</param> /// <param name="customQueryOptions">custom query options for resourcse set</param> internal ResourceSetExpression(Type type, Expression source, Expression memberExpression, Type resourceType, List<string> expandPaths, CountOption countOption, Dictionary<ConstantExpression, ConstantExpression> customQueryOptions, ProjectionQueryOptionExpression projection) : base(source, source != null ? (ExpressionType)ResourceExpressionType.ResourceNavigationProperty : (ExpressionType)ResourceExpressionType.RootResourceSet, type, expandPaths, countOption, customQueryOptions, projection) { Debug.Assert(type != null, "type != null"); Debug.Assert(memberExpression != null, "memberExpression != null"); Debug.Assert(resourceType != null, "resourceType != null"); Debug.Assert( (source == null && memberExpression is ConstantExpression) || (source != null && memberExpression is MemberExpression), "source is null with constant entity set name, or not null with member expression"); this.member = memberExpression; this.resourceType = resourceType; this.sequenceQueryOptions = new List<QueryOptionExpression>(); } #region Internal properties. /// <summary> /// Member for ResourceSet /// </summary> internal Expression MemberExpression { get { return this.member; } } /// <summary> /// Type of resources contained in this ResourceSet - it's element type. /// </summary> internal override Type ResourceType { get { return this.resourceType; } } /// <summary> /// Is this ResourceSet enclosed in an anonymously-typed transparent scope produced by a SelectMany operation? /// Applies to navigation ResourceSets. /// </summary> internal bool HasTransparentScope { get { return this.transparentScope != null; } } /// <summary> /// The property accesses required to reference this ResourceSet and its source ResourceSet if a transparent scope is present. /// May be null. Use <see cref="HasTransparentScope"/> to test for the presence of a value. /// </summary> internal TransparentAccessors TransparentScope { get { return this.transparentScope; } set { this.transparentScope = value; } } /// <summary> /// Has a key predicate restriction been applied to this ResourceSet? /// </summary> internal bool HasKeyPredicate { get { return this.keyFilter != null; } } /// <summary> /// The property name/required value pairs that comprise the key predicate (if any) applied to this ResourceSet. /// May be null. Use <see cref="HasKeyPredicate"/> to test for the presence of a value. /// </summary> internal Dictionary<PropertyInfo, ConstantExpression> KeyPredicate { get { return this.keyFilter; } set { this.keyFilter = value; } } /// <summary> /// A resource set produces at most 1 result if constrained by a key predicate /// </summary> internal override bool IsSingleton { get { return this.HasKeyPredicate; } } /// <summary> /// Have sequence query options (filter, orderby, skip, take), expand paths, projection /// or custom query options been applied to this resource set? /// </summary> internal override bool HasQueryOptions { get { return this.sequenceQueryOptions.Count > 0 || this.ExpandPaths.Count > 0 || this.CountOption == CountOption.InlineAll || // value only count is not an option this.CustomQueryOptions.Count > 0 || this.Projection != null; } } /// <summary> /// Filter query option for ResourceSet /// </summary> internal FilterQueryOptionExpression Filter { get { return this.sequenceQueryOptions.OfType<FilterQueryOptionExpression>().SingleOrDefault(); } } /// <summary> /// OrderBy query option for ResourceSet /// </summary> internal OrderByQueryOptionExpression OrderBy { get { return this.sequenceQueryOptions.OfType<OrderByQueryOptionExpression>().SingleOrDefault(); } } /// <summary> /// Skip query option for ResourceSet /// </summary> internal SkipQueryOptionExpression Skip { get { return this.sequenceQueryOptions.OfType<SkipQueryOptionExpression>().SingleOrDefault(); } } /// <summary> /// Take query option for ResourceSet /// </summary> internal TakeQueryOptionExpression Take { get { return this.sequenceQueryOptions.OfType<TakeQueryOptionExpression>().SingleOrDefault(); } } /// <summary> /// Gets sequence query options for ResourcSet /// </summary> internal IEnumerable<QueryOptionExpression> SequenceQueryOptions { get { return this.sequenceQueryOptions.ToList(); } } /// <summary>Whether there are any query options for the sequence.</summary> internal bool HasSequenceQueryOptions { get { return this.sequenceQueryOptions.Count > 0; } } #endregion Internal properties. #region Internal methods. /// <summary> /// Cast ResourceSetExpression to new type /// </summary> internal override ResourceExpression CreateCloneWithNewType(Type type) { ResourceSetExpression rse = new ResourceSetExpression( type, this.source, this.MemberExpression, TypeSystem.GetElementType(type), this.ExpandPaths.ToList(), this.CountOption, this.CustomQueryOptions.ToDictionary(kvp => kvp.Key, kvp => kvp.Value), this.Projection); rse.keyFilter = this.keyFilter; rse.sequenceQueryOptions = this.sequenceQueryOptions; rse.transparentScope = this.transparentScope; return rse; } /// <summary> /// Add query option to resource expression /// </summary> internal void AddSequenceQueryOption(QueryOptionExpression qoe) { Debug.Assert(qoe != null, "qoe != null"); QueryOptionExpression old = this.sequenceQueryOptions.Where(o => o.GetType() == qoe.GetType()).FirstOrDefault(); if (old != null) { qoe = qoe.ComposeMultipleSpecification(old); this.sequenceQueryOptions.Remove(old); } this.sequenceQueryOptions.Add(qoe); } /// <summary> /// Instructs this resource set expression to use the input reference expression from <paramref name="newInput"/> as it's /// own input reference, and to retarget the input reference from <paramref name="newInput"/> to this resource set expression. /// </summary> /// <param name="newInput">The resource set expression from which to take the input reference.</param> /// <remarks>Used exclusively by <see cref="ResourceBinder.RemoveTransparentScope"/>.</remarks> internal void OverrideInputReference(ResourceSetExpression newInput) { Debug.Assert(newInput != null, "Original resource set cannot be null"); Debug.Assert(this.inputRef == null, "OverrideInputReference cannot be called if the target has already been referenced"); InputReferenceExpression inputRef = newInput.inputRef; if (inputRef != null) { this.inputRef = inputRef; inputRef.OverrideTarget(this); } } #endregion Internal methods. /// <summary> /// Represents the property accesses required to access both /// this resource set and its source resource/set (for navigations). /// /// These accesses are required to reference resource sets enclosed /// in transparent scopes introduced by use of SelectMany. /// </summary> /// <remarks> /// For example, this query: /// from c in Custs where c.id == 1 /// from o in c.Orders from od in o.OrderDetails select od /// /// Translates to: /// c.Where(c => c.id == 1) /// .SelectMany(c => o, (c, o) => new $(c=c, o=o)) /// .SelectMany($ => $.o, ($, od) => od) /// /// PatternRules.MatchPropertyProjectionSet identifies Orders as the target of the collector. /// PatternRules.MatchTransparentScopeSelector identifies the introduction of a transparent identifer. /// /// A transparent accessor is associated with Orders, with 'c' being the source accesor, /// and 'o' being the (introduced) accessor. /// </remarks> [DebuggerDisplay("{ToString()}")] internal class TransparentAccessors { #region Internal fields. /// <summary> /// The property reference that must be applied to reference this resource set /// </summary> internal readonly string Accessor; /// <summary> /// The property reference that must be applied to reference the source resource set. /// Note that this set's Accessor is NOT required to access the source set, but the /// source set MAY impose it's own Transparent Accessors /// </summary> internal readonly Dictionary<string, Expression> SourceAccessors; #endregion Internal fields. /// <summary> /// Constructs a new transparent scope with the specified set and source set accessors /// </summary> /// <param name="acc">The name of the property required to access the resource set</param> /// <param name="sourceAccesors">The names of the property required to access the resource set's sources.</param> internal TransparentAccessors(string acc, Dictionary<string, Expression> sourceAccesors) { Debug.Assert(!string.IsNullOrEmpty(acc), "Set accessor cannot be null or empty"); Debug.Assert(sourceAccesors != null, "sourceAccesors != null"); this.Accessor = acc; this.SourceAccessors = sourceAccesors; } /// <summary>Provides a string representation of this accessor.</summary> /// <returns>The text represntation of this accessor.</returns> public override string ToString() { string result = "SourceAccessors=[" + string.Join(",", this.SourceAccessors.Keys.ToArray()); result += "] ->* Accessor=" + this.Accessor; return result; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text.Json; using System.Text.RegularExpressions; using System.Threading.Tasks; using Microsoft.AspNetCore.BrowserTesting; using Microsoft.AspNetCore.Internal; using Microsoft.AspNetCore.Testing; using Microsoft.Extensions.CommandLineUtils; using Newtonsoft.Json.Linq; using PlaywrightSharp; using Templates.Test.Helpers; using Xunit; using Xunit.Abstractions; namespace BlazorTemplates.Tests { public class BlazorWasmTemplateTest : BlazorTemplateTest { public BlazorWasmTemplateTest(ProjectFactoryFixture projectFactory) : base(projectFactory) { } public override string ProjectType { get; } = "blazorwasm"; [Theory] [InlineData(BrowserKind.Chromium)] [QuarantinedTest("https://github.com/dotnet/aspnetcore/issues/30882")] public async Task BlazorWasmStandaloneTemplate_Works(BrowserKind browserKind) { var project = await CreateBuildPublishAsync("blazorstandalone" + browserKind); // The service worker assets manifest isn't generated for non-PWA projects var publishDir = Path.Combine(project.TemplatePublishDir, "wwwroot"); Assert.False(File.Exists(Path.Combine(publishDir, "service-worker-assets.js")), "Non-PWA templates should not produce service-worker-assets.js"); await BuildAndRunTest(project.ProjectName, project, browserKind); var (serveProcess, listeningUri) = RunPublishedStandaloneBlazorProject(project); using (serveProcess) { Output.WriteLine($"Opening browser at {listeningUri}..."); if (BrowserManager.IsAvailable(browserKind)) { await using var browser = await BrowserManager.GetBrowserInstance(browserKind, BrowserContextInfo); var page = await NavigateToPage(browser, listeningUri); await TestBasicNavigation(project.ProjectName, page); } else { EnsureBrowserAvailable(browserKind); } } } private async Task<IPage> NavigateToPage(IBrowserContext browser, string listeningUri) { var page = await browser.NewPageAsync(); await page.GoToAsync(listeningUri, LifecycleEvent.Networkidle); return page; } [Theory] [InlineData(BrowserKind.Chromium)] [QuarantinedTest("https://github.com/dotnet/aspnetcore/issues/30882")] public async Task BlazorWasmHostedTemplate_Works(BrowserKind browserKind) { var project = await CreateBuildPublishAsync("blazorhosted" + BrowserKind.Chromium, args: new[] { "--hosted" }, serverProject: true); var serverProject = GetSubProject(project, "Server", $"{project.ProjectName}.Server"); await BuildAndRunTest(project.ProjectName, serverProject, browserKind); using var aspNetProcess = serverProject.StartPublishedProjectAsync(); Assert.False( aspNetProcess.Process.HasExited, ErrorMessages.GetFailedProcessMessageOrEmpty("Run published project", serverProject, aspNetProcess.Process)); await aspNetProcess.AssertStatusCode("/", HttpStatusCode.OK, "text/html"); await AssertCompressionFormat(aspNetProcess, "br"); if (BrowserManager.IsAvailable(browserKind)) { await using var browser = await BrowserManager.GetBrowserInstance(browserKind, BrowserContextInfo); var page = await browser.NewPageAsync(); await aspNetProcess.VisitInBrowserAsync(page); await TestBasicNavigation(project.ProjectName, page); } else { EnsureBrowserAvailable(browserKind); } } private static async Task AssertCompressionFormat(AspNetProcess aspNetProcess, string expectedEncoding) { var response = await aspNetProcess.SendRequest(() => { var request = new HttpRequestMessage(HttpMethod.Get, new Uri(aspNetProcess.ListeningUri, "/_framework/blazor.boot.json")); // These are the same as chrome request.Headers.AcceptEncoding.Clear(); request.Headers.AcceptEncoding.Add(StringWithQualityHeaderValue.Parse("gzip")); request.Headers.AcceptEncoding.Add(StringWithQualityHeaderValue.Parse("deflate")); request.Headers.AcceptEncoding.Add(StringWithQualityHeaderValue.Parse("br")); return request; }); Assert.Equal(expectedEncoding, response.Content.Headers.ContentEncoding.Single()); } [Theory] [InlineData(BrowserKind.Chromium)] [QuarantinedTest("https://github.com/dotnet/aspnetcore/issues/30882")] public async Task BlazorWasmStandalonePwaTemplate_Works(BrowserKind browserKind) { var project = await CreateBuildPublishAsync("blazorstandalonepwa", args: new[] { "--pwa" }); await BuildAndRunTest(project.ProjectName, project, browserKind); ValidatePublishedServiceWorker(project); if (BrowserManager.IsAvailable(browserKind)) { var (serveProcess, listeningUri) = RunPublishedStandaloneBlazorProject(project); await using var browser = await BrowserManager.GetBrowserInstance(browserKind, BrowserContextInfo); Output.WriteLine($"Opening browser at {listeningUri}..."); var page = await NavigateToPage(browser, listeningUri); using (serveProcess) { await TestBasicNavigation(project.ProjectName, page); } // The PWA template supports offline use. By now, the browser should have cached everything it needs, // so we can continue working even without the server. await page.GoToAsync("about:blank"); await browser.SetOfflineAsync(true); await page.GoToAsync(listeningUri); await TestBasicNavigation(project.ProjectName, page, skipFetchData: true); await page.CloseAsync(); } else { EnsureBrowserAvailable(browserKind); } } [Theory] [InlineData(BrowserKind.Chromium)] [QuarantinedTest("https://github.com/dotnet/aspnetcore/issues/30882")] public async Task BlazorWasmHostedPwaTemplate_Works(BrowserKind browserKind) { var project = await CreateBuildPublishAsync("blazorhostedpwa", args: new[] { "--hosted", "--pwa" }, serverProject: true); var serverProject = GetSubProject(project, "Server", $"{project.ProjectName}.Server"); await BuildAndRunTest(project.ProjectName, serverProject, browserKind); ValidatePublishedServiceWorker(serverProject); string listeningUri = null; if (BrowserManager.IsAvailable(browserKind)) { await using var browser = await BrowserManager.GetBrowserInstance(browserKind, BrowserContextInfo); IPage page = null; using (var aspNetProcess = serverProject.StartPublishedProjectAsync()) { Assert.False( aspNetProcess.Process.HasExited, ErrorMessages.GetFailedProcessMessageOrEmpty("Run published project", serverProject, aspNetProcess.Process)); await aspNetProcess.AssertStatusCode("/", HttpStatusCode.OK, "text/html"); page = await browser.NewPageAsync(); await aspNetProcess.VisitInBrowserAsync(page); await TestBasicNavigation(project.ProjectName, page); // Note: we don't want to use aspNetProcess.ListeningUri because that isn't necessarily the HTTPS URI listeningUri = new Uri(page.Url).GetLeftPart(UriPartial.Authority); } // The PWA template supports offline use. By now, the browser should have cached everything it needs, // so we can continue working even without the server. // Since this is the hosted project, backend APIs won't work offline, so we need to skip "fetchdata" await page.GoToAsync("about:blank"); await browser.SetOfflineAsync(true); await page.GoToAsync(listeningUri); await TestBasicNavigation(project.ProjectName, page, skipFetchData: true); await page.CloseAsync(); } else { EnsureBrowserAvailable(browserKind); } } private void ValidatePublishedServiceWorker(Project project) { var publishDir = Path.Combine(project.TemplatePublishDir, "wwwroot"); // When publishing the PWA template, we generate an assets manifest // and move service-worker.published.js to overwrite service-worker.js Assert.False(File.Exists(Path.Combine(publishDir, "service-worker.published.js")), "service-worker.published.js should not be published"); Assert.True(File.Exists(Path.Combine(publishDir, "service-worker.js")), "service-worker.js should be published"); Assert.True(File.Exists(Path.Combine(publishDir, "service-worker-assets.js")), "service-worker-assets.js should be published"); // We automatically append the SWAM version as a comment in the published service worker file var serviceWorkerAssetsManifestContents = ReadFile(publishDir, "service-worker-assets.js"); var serviceWorkerContents = ReadFile(publishDir, "service-worker.js"); // Parse the "version": "..." value from the SWAM, and check it's in the service worker var serviceWorkerAssetsManifestVersionMatch = new Regex(@"^\s*\""version\"":\s*(\""[^\""]+\"")", RegexOptions.Multiline) .Match(serviceWorkerAssetsManifestContents); Assert.True(serviceWorkerAssetsManifestVersionMatch.Success); var serviceWorkerAssetsManifestVersionJson = serviceWorkerAssetsManifestVersionMatch.Groups[1].Captures[0].Value; var serviceWorkerAssetsManifestVersion = JsonSerializer.Deserialize<string>(serviceWorkerAssetsManifestVersionJson); Assert.True(serviceWorkerContents.Contains($"/* Manifest version: {serviceWorkerAssetsManifestVersion} */", StringComparison.Ordinal)); } [ConditionalTheory] [InlineData(BrowserKind.Chromium)] // LocalDB doesn't work on non Windows platforms [OSSkipCondition(OperatingSystems.Linux | OperatingSystems.MacOSX)] [QuarantinedTest("https://github.com/dotnet/aspnetcore/issues/30882")] public Task BlazorWasmHostedTemplate_IndividualAuth_Works_WithLocalDB(BrowserKind browserKind) => BlazorWasmHostedTemplate_IndividualAuth_Works(browserKind, true); // This test depends on BlazorWasmTemplate_CreateBuildPublish_IndividualAuthNoLocalDb running first [Theory] [InlineData(BrowserKind.Chromium)] [QuarantinedTest("https://github.com/dotnet/aspnetcore/issues/30882")] [SkipOnHelix("https://github.com/dotnet/aspnetcore/issues/30825", Queues = "All.OSX")] public Task BlazorWasmHostedTemplate_IndividualAuth_Works_WithOutLocalDB(BrowserKind browserKind) => BlazorWasmHostedTemplate_IndividualAuth_Works(browserKind, false); private async Task<Project> CreateBuildPublishIndividualAuthProject(BrowserKind browserKind, bool useLocalDb) { // Additional arguments are needed. See: https://github.com/dotnet/aspnetcore/issues/24278 Environment.SetEnvironmentVariable("EnableDefaultScopedCssItems", "true"); var project = await CreateBuildPublishAsync("blazorhostedindividual" + browserKind + (useLocalDb ? "uld" : ""), args: new[] { "--hosted", "-au", "Individual", useLocalDb ? "-uld" : "" }); var serverProject = GetSubProject(project, "Server", $"{project.ProjectName}.Server"); var serverProjectFileContents = ReadFile(serverProject.TemplateOutputDir, $"{serverProject.ProjectName}.csproj"); if (!useLocalDb) { Assert.Contains(".db", serverProjectFileContents); } var appSettings = ReadFile(serverProject.TemplateOutputDir, "appsettings.json"); var element = JsonSerializer.Deserialize<JsonElement>(appSettings); var clientsProperty = element.GetProperty("IdentityServer").EnumerateObject().Single().Value.EnumerateObject().Single(); var replacedSection = element.GetRawText().Replace(clientsProperty.Name, serverProject.ProjectName.Replace(".Server", ".Client")); var appSettingsPath = Path.Combine(serverProject.TemplateOutputDir, "appsettings.json"); File.WriteAllText(appSettingsPath, replacedSection); var publishResult = await serverProject.RunDotNetPublishAsync(); Assert.True(0 == publishResult.ExitCode, ErrorMessages.GetFailedProcessMessage("publish", serverProject, publishResult)); // Run dotnet build after publish. The reason is that one uses Config = Debug and the other uses Config = Release // The output from publish will go into bin/Release/netcoreappX.Y/publish and won't be affected by calling build // later, while the opposite is not true. var buildResult = await serverProject.RunDotNetBuildAsync(); Assert.True(0 == buildResult.ExitCode, ErrorMessages.GetFailedProcessMessage("build", serverProject, buildResult)); var migrationsResult = await serverProject.RunDotNetEfCreateMigrationAsync("blazorwasm"); Assert.True(0 == migrationsResult.ExitCode, ErrorMessages.GetFailedProcessMessage("run EF migrations", serverProject, migrationsResult)); serverProject.AssertEmptyMigration("blazorwasm"); if (useLocalDb) { var dbUpdateResult = await serverProject.RunDotNetEfUpdateDatabaseAsync(); Assert.True(0 == dbUpdateResult.ExitCode, ErrorMessages.GetFailedProcessMessage("update database", serverProject, dbUpdateResult)); } return project; } private async Task BlazorWasmHostedTemplate_IndividualAuth_Works(BrowserKind browserKind, bool useLocalDb) { var project = await CreateBuildPublishIndividualAuthProject(browserKind, useLocalDb: useLocalDb); var serverProject = GetSubProject(project, "Server", $"{project.ProjectName}.Server"); await BuildAndRunTest(project.ProjectName, serverProject, browserKind, usesAuth: true); UpdatePublishedSettings(serverProject); if (BrowserManager.IsAvailable(browserKind)) { using var aspNetProcess = serverProject.StartPublishedProjectAsync(); Assert.False( aspNetProcess.Process.HasExited, ErrorMessages.GetFailedProcessMessageOrEmpty("Run published project", serverProject, aspNetProcess.Process)); await aspNetProcess.AssertStatusCode("/", HttpStatusCode.OK, "text/html"); await using var browser = await BrowserManager.GetBrowserInstance(browserKind, BrowserContextInfo); var page = await browser.NewPageAsync(); await aspNetProcess.VisitInBrowserAsync(page); await TestBasicNavigation(project.ProjectName, page, usesAuth: true); await page.CloseAsync(); } else { EnsureBrowserAvailable(browserKind); } } public static TheoryData<TemplateInstance> TemplateData => new TheoryData<TemplateInstance> { new TemplateInstance( "blazorwasmhostedaadb2c", "-ho", "-au", "IndividualB2C", "--aad-b2c-instance", "example.b2clogin.com", "-ssp", "b2c_1_siupin", "--client-id", "clientId", "--domain", "my-domain", "--default-scope", "full", "--app-id-uri", "ApiUri", "--api-client-id", "1234123413241324"), new TemplateInstance( "blazorwasmhostedaad", "-ho", "-au", "SingleOrg", "--domain", "my-domain", "--tenant-id", "tenantId", "--client-id", "clientId", "--default-scope", "full", "--app-id-uri", "ApiUri", "--api-client-id", "1234123413241324"), new TemplateInstance( "blazorwasmhostedaadgraph", "-ho", "-au", "SingleOrg", "--calls-graph", "--domain", "my-domain", "--tenant-id", "tenantId", "--client-id", "clientId", "--default-scope", "full", "--app-id-uri", "ApiUri", "--api-client-id", "1234123413241324"), new TemplateInstance( "blazorwasmhostedaadapi", "-ho", "-au", "SingleOrg", "--called-api-url", "\"https://graph.microsoft.com\"", "--called-api-scopes", "user.readwrite", "--domain", "my-domain", "--tenant-id", "tenantId", "--client-id", "clientId", "--default-scope", "full", "--app-id-uri", "ApiUri", "--api-client-id", "1234123413241324"), new TemplateInstance( "blazorwasmstandaloneaadb2c", "-au", "IndividualB2C", "--aad-b2c-instance", "example.b2clogin.com", "-ssp", "b2c_1_siupin", "--client-id", "clientId", "--domain", "my-domain"), new TemplateInstance( "blazorwasmstandaloneaad", "-au", "SingleOrg", "--domain", "my-domain", "--tenant-id", "tenantId", "--client-id", "clientId"), }; public class TemplateInstance { public TemplateInstance(string name, params string[] arguments) { Name = name; Arguments = arguments; } public string Name { get; } public string[] Arguments { get; } } [Theory] [MemberData(nameof(TemplateData))] [QuarantinedTest("https://github.com/dotnet/aspnetcore/issues/37782")] public Task BlazorWasmHostedTemplate_AzureActiveDirectoryTemplate_Works(TemplateInstance instance) => CreateBuildPublishAsync(instance.Name, args: instance.Arguments, targetFramework: "netstandard2.1"); protected async Task BuildAndRunTest(string appName, Project project, BrowserKind browserKind, bool usesAuth = false) { using var aspNetProcess = project.StartBuiltProjectAsync(); Assert.False( aspNetProcess.Process.HasExited, ErrorMessages.GetFailedProcessMessageOrEmpty("Run built project", project, aspNetProcess.Process)); await aspNetProcess.AssertStatusCode("/", HttpStatusCode.OK, "text/html"); if (BrowserManager.IsAvailable(browserKind)) { await using var browser = await BrowserManager.GetBrowserInstance(browserKind, BrowserContextInfo); var page = await browser.NewPageAsync(); await aspNetProcess.VisitInBrowserAsync(page); await TestBasicNavigation(appName, page, usesAuth); await page.CloseAsync(); } else { EnsureBrowserAvailable(browserKind); } } private async Task TestBasicNavigation(string appName, IPage page, bool usesAuth = false, bool skipFetchData = false) { await page.WaitForSelectorAsync("nav"); // Initially displays the home page await page.WaitForSelectorAsync("h1 >> text=Hello, world!"); Assert.Equal("Index", (await page.GetTitleAsync()).Trim()); // Can navigate to the counter page await Task.WhenAll( page.WaitForNavigationAsync("**/counter"), page.WaitForSelectorAsync("h1 >> text=Counter"), page.WaitForSelectorAsync("p >> text=Current count: 0"), page.ClickAsync("a[href=counter]")); // Clicking the counter button works await Task.WhenAll( page.WaitForSelectorAsync("p >> text=Current count: 1"), page.ClickAsync("p+button >> text=Click me")); if (usesAuth) { await Task.WhenAll( page.WaitForNavigationAsync("**/Identity/Account/Login**", LifecycleEvent.Networkidle), page.ClickAsync("text=Log in")); await Task.WhenAll( page.WaitForSelectorAsync("[name=\"Input.Email\"]"), page.WaitForNavigationAsync("**/Identity/Account/Register**", LifecycleEvent.Networkidle), page.ClickAsync("text=Register as a new user")); var userName = $"{Guid.NewGuid()}@example.com"; var password = $"!Test.Password1$"; await page.TypeAsync("[name=\"Input.Email\"]", userName); await page.TypeAsync("[name=\"Input.Password\"]", password); await page.TypeAsync("[name=\"Input.ConfirmPassword\"]", password); // We will be redirected to the RegisterConfirmation await Task.WhenAll( page.WaitForNavigationAsync("**/Identity/Account/RegisterConfirmation**", LifecycleEvent.Networkidle), page.ClickAsync("#registerSubmit")); // We will be redirected to the ConfirmEmail await Task.WhenAll( page.WaitForNavigationAsync("**/Identity/Account/ConfirmEmail**", LifecycleEvent.Networkidle), page.ClickAsync("text=Click here to confirm your account")); // Now we can login await page.ClickAsync("text=Login"); await page.WaitForSelectorAsync("[name=\"Input.Email\"]"); await page.TypeAsync("[name=\"Input.Email\"]", userName); await page.TypeAsync("[name=\"Input.Password\"]", password); await page.ClickAsync("#login-submit"); // Need to navigate to fetch page await page.GoToAsync(new Uri(page.Url).GetLeftPart(UriPartial.Authority)); Assert.Equal(appName.Trim(), (await page.GetTitleAsync()).Trim()); } if (!skipFetchData) { // Can navigate to the 'fetch data' page await Task.WhenAll( page.WaitForNavigationAsync("**/fetchdata"), page.WaitForSelectorAsync("h1 >> text=Weather forecast"), page.ClickAsync("text=Fetch data")); // Asynchronously loads and displays the table of weather forecasts await page.WaitForSelectorAsync("table>tbody>tr"); Assert.Equal(5, (await page.QuerySelectorAllAsync("p+table>tbody>tr")).Count()); } } private string ReadFile(string basePath, string path) { var fullPath = Path.Combine(basePath, path); var doesExist = File.Exists(fullPath); Assert.True(doesExist, $"Expected file to exist, but it doesn't: {path}"); return File.ReadAllText(Path.Combine(basePath, path)); } private void UpdatePublishedSettings(Project serverProject) { // Hijack here the config file to use the development key during publish. var appSettings = JObject.Parse(File.ReadAllText(Path.Combine(serverProject.TemplateOutputDir, "appsettings.json"))); var appSettingsDevelopment = JObject.Parse(File.ReadAllText(Path.Combine(serverProject.TemplateOutputDir, "appsettings.Development.json"))); ((JObject)appSettings["IdentityServer"]).Merge(appSettingsDevelopment["IdentityServer"]); ((JObject)appSettings["IdentityServer"]).Merge(new { IdentityServer = new { Key = new { FilePath = "./tempkey.json" } } }); var testAppSettings = appSettings.ToString(); File.WriteAllText(Path.Combine(serverProject.TemplatePublishDir, "appsettings.json"), testAppSettings); } private (ProcessEx, string url) RunPublishedStandaloneBlazorProject(Project project) { var publishDir = Path.Combine(project.TemplatePublishDir, "wwwroot"); Output.WriteLine("Running dotnet serve on published output..."); var developmentCertificate = DevelopmentCertificate.Create(project.TemplateOutputDir); var args = $"-S --pfx \"{developmentCertificate.CertificatePath}\" --pfx-pwd \"{developmentCertificate.CertificatePassword}\" --port 0"; var command = DotNetMuxer.MuxerPathOrDefault(); if (string.IsNullOrEmpty(Environment.GetEnvironmentVariable("HELIX_DIR"))) { args = $"serve " + args; } else { command = "dotnet-serve"; args = "--roll-forward LatestMajor " + args; // dotnet-serve targets net5.0 by default } var serveProcess = ProcessEx.Run(TestOutputHelper, publishDir, command, args); var listeningUri = ResolveListeningUrl(serveProcess); return (serveProcess, listeningUri); } private static string ResolveListeningUrl(ProcessEx process) { var buffer = new List<string>(); try { foreach (var line in process.OutputLinesAsEnumerable) { if (line != null) { buffer.Add(line); if (line.Trim().Contains("https://", StringComparison.Ordinal) || line.Trim().Contains("http://", StringComparison.Ordinal)) { return line.Trim(); } } } } catch (OperationCanceledException) { } throw new InvalidOperationException(@$"Couldn't find listening url: {string.Join(Environment.NewLine, buffer.Append(process.Error))}"); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Globalization; namespace System.Collections.Immutable { /// <summary> /// A node in the AVL tree storing key/value pairs with Int32 keys. /// </summary> /// <remarks> /// This is a trimmed down version of <see cref="ImmutableSortedDictionary{TKey, TValue}.Node"/> /// with <c>TKey</c> fixed to be <see cref="int"/>. This avoids multiple interface-based dispatches while examining /// each node in the tree during a lookup: an interface call to the comparer's <see cref="IComparer{T}.Compare"/> method, /// and then an interface call to <see cref="int"/>'s <see cref="IComparable{T}.CompareTo"/> method as part of /// the <see cref="T:System.Collections.Generic.GenericComparer`1"/>'s <see cref="IComparer{T}.Compare"/> implementation. /// </remarks> [DebuggerDisplay("{_key} = {_value}")] internal sealed class SortedInt32KeyNode<TValue> : IBinaryTree { /// <summary> /// The default empty node. /// </summary> internal static readonly SortedInt32KeyNode<TValue> EmptyNode = new SortedInt32KeyNode<TValue>(); /// <summary> /// The Int32 key associated with this node. /// </summary> private readonly int _key; /// <summary> /// The value associated with this node. /// </summary> /// <remarks> /// Sadly, this field could be readonly but doing so breaks serialization due to bug: /// http://connect.microsoft.com/VisualStudio/feedback/details/312970/weird-argumentexception-when-deserializing-field-in-typedreferences-cannot-be-static-or-init-only /// </remarks> private TValue _value; /// <summary> /// A value indicating whether this node has been frozen (made immutable). /// </summary> /// <remarks> /// Nodes must be frozen before ever being observed by a wrapping collection type /// to protect collections from further mutations. /// </remarks> private bool _frozen; /// <summary> /// The depth of the tree beneath this node. /// </summary> private byte _height; // AVL tree height <= ~1.44 * log2(numNodes + 2) /// <summary> /// The left tree. /// </summary> private SortedInt32KeyNode<TValue> _left; /// <summary> /// The right tree. /// </summary> private SortedInt32KeyNode<TValue> _right; /// <summary> /// Initializes a new instance of the <see cref="SortedInt32KeyNode{TValue}"/> class that is pre-frozen. /// </summary> private SortedInt32KeyNode() { _frozen = true; // the empty node is *always* frozen. } /// <summary> /// Initializes a new instance of the <see cref="SortedInt32KeyNode{TValue}"/> class that is not yet frozen. /// </summary> /// <param name="key">The key.</param> /// <param name="value">The value.</param> /// <param name="left">The left.</param> /// <param name="right">The right.</param> /// <param name="frozen">Whether this node is prefrozen.</param> private SortedInt32KeyNode(int key, TValue value, SortedInt32KeyNode<TValue> left, SortedInt32KeyNode<TValue> right, bool frozen = false) { Requires.NotNull(left, "left"); Requires.NotNull(right, "right"); Debug.Assert(!frozen || (left._frozen && right._frozen)); _key = key; _value = value; _left = left; _right = right; _frozen = frozen; _height = checked((byte)(1 + Math.Max(left._height, right._height))); } /// <summary> /// Gets a value indicating whether this instance is empty. /// </summary> /// <value> /// <c>true</c> if this instance is empty; otherwise, <c>false</c>. /// </value> public bool IsEmpty { get { return _left == null; } } /// <summary> /// Gets the height of the tree beneath this node. /// </summary> public int Height { get { return _height; } } /// <summary> /// Gets the left branch of this node. /// </summary> public SortedInt32KeyNode<TValue> Left { get { return _left; } } /// <summary> /// Gets the right branch of this node. /// </summary> public SortedInt32KeyNode<TValue> Right { get { return _right; } } /// <summary> /// Gets the left branch of this node. /// </summary> IBinaryTree IBinaryTree.Left { get { return _left; } } /// <summary> /// Gets the right branch of this node. /// </summary> IBinaryTree IBinaryTree.Right { get { return _right; } } /// <summary> /// Gets the number of elements contained by this node and below. /// </summary> int IBinaryTree.Count { get { throw new NotSupportedException(); } } /// <summary> /// Gets the value represented by the current node. /// </summary> public KeyValuePair<int, TValue> Value { get { return new KeyValuePair<int, TValue>(_key, _value); } } /// <summary> /// Gets the values. /// </summary> internal IEnumerable<TValue> Values { get { foreach (var pair in this) { yield return pair.Value; } } } /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns> /// A <see cref="IEnumerator{T}"/> that can be used to iterate through the collection. /// </returns> public Enumerator GetEnumerator() { return new Enumerator(this); } /// <summary> /// Adds the specified key. /// </summary> /// <param name="key">The key.</param> /// <param name="value">The value.</param> /// <param name="valueComparer">The value comparer.</param> /// <param name="replacedExistingValue">Receives a value indicating whether an existing value was replaced.</param> /// <param name="mutated">Receives a value indicating whether this node tree has mutated because of this operation.</param> internal SortedInt32KeyNode<TValue> SetItem(int key, TValue value, IEqualityComparer<TValue> valueComparer, out bool replacedExistingValue, out bool mutated) { Requires.NotNull(valueComparer, "valueComparer"); return this.SetOrAdd(key, value, valueComparer, true, out replacedExistingValue, out mutated); } /// <summary> /// Removes the specified key. /// </summary> /// <param name="key">The key.</param> /// <param name="mutated">Receives a value indicating whether this node tree has mutated because of this operation.</param> /// <returns>The new AVL tree.</returns> internal SortedInt32KeyNode<TValue> Remove(int key, out bool mutated) { return this.RemoveRecursive(key, out mutated); } /// <summary> /// Gets the value or default. /// </summary> /// <param name="key">The key.</param> /// <returns>The value.</returns> [Pure] internal TValue GetValueOrDefault(int key) { var match = this.Search(key); return match.IsEmpty ? default(TValue) : match._value; } /// <summary> /// Tries to get the value. /// </summary> /// <param name="key">The key.</param> /// <param name="value">The value.</param> /// <returns>True if the key was found.</returns> [Pure] internal bool TryGetValue(int key, out TValue value) { var match = this.Search(key); if (match.IsEmpty) { value = default(TValue); return false; } else { value = match._value; return true; } } /// <summary> /// Freezes this node and all descendant nodes so that any mutations require a new instance of the nodes. /// </summary> internal void Freeze(Action<KeyValuePair<int, TValue>> freezeAction = null) { // If this node is frozen, all its descendants must already be frozen. if (!_frozen) { if (freezeAction != null) { freezeAction(new KeyValuePair<int, TValue>(_key, _value)); } _left.Freeze(freezeAction); _right.Freeze(freezeAction); _frozen = true; } } /// <summary> /// AVL rotate left operation. /// </summary> /// <param name="tree">The tree.</param> /// <returns>The rotated tree.</returns> private static SortedInt32KeyNode<TValue> RotateLeft(SortedInt32KeyNode<TValue> tree) { Requires.NotNull(tree, "tree"); Debug.Assert(!tree.IsEmpty); if (tree._right.IsEmpty) { return tree; } var right = tree._right; return right.Mutate(left: tree.Mutate(right: right._left)); } /// <summary> /// AVL rotate right operation. /// </summary> /// <param name="tree">The tree.</param> /// <returns>The rotated tree.</returns> private static SortedInt32KeyNode<TValue> RotateRight(SortedInt32KeyNode<TValue> tree) { Requires.NotNull(tree, "tree"); Debug.Assert(!tree.IsEmpty); if (tree._left.IsEmpty) { return tree; } var left = tree._left; return left.Mutate(right: tree.Mutate(left: left._right)); } /// <summary> /// AVL rotate double-left operation. /// </summary> /// <param name="tree">The tree.</param> /// <returns>The rotated tree.</returns> private static SortedInt32KeyNode<TValue> DoubleLeft(SortedInt32KeyNode<TValue> tree) { Requires.NotNull(tree, "tree"); Debug.Assert(!tree.IsEmpty); if (tree._right.IsEmpty) { return tree; } SortedInt32KeyNode<TValue> rotatedRightChild = tree.Mutate(right: RotateRight(tree._right)); return RotateLeft(rotatedRightChild); } /// <summary> /// AVL rotate double-right operation. /// </summary> /// <param name="tree">The tree.</param> /// <returns>The rotated tree.</returns> private static SortedInt32KeyNode<TValue> DoubleRight(SortedInt32KeyNode<TValue> tree) { Requires.NotNull(tree, "tree"); Debug.Assert(!tree.IsEmpty); if (tree._left.IsEmpty) { return tree; } SortedInt32KeyNode<TValue> rotatedLeftChild = tree.Mutate(left: RotateLeft(tree._left)); return RotateRight(rotatedLeftChild); } /// <summary> /// Returns a value indicating whether the tree is in balance. /// </summary> /// <param name="tree">The tree.</param> /// <returns>0 if the tree is in balance, a positive integer if the right side is heavy, or a negative integer if the left side is heavy.</returns> [Pure] private static int Balance(SortedInt32KeyNode<TValue> tree) { Requires.NotNull(tree, "tree"); Debug.Assert(!tree.IsEmpty); return tree._right._height - tree._left._height; } /// <summary> /// Determines whether the specified tree is right heavy. /// </summary> /// <param name="tree">The tree.</param> /// <returns> /// <c>true</c> if [is right heavy] [the specified tree]; otherwise, <c>false</c>. /// </returns> [Pure] private static bool IsRightHeavy(SortedInt32KeyNode<TValue> tree) { Requires.NotNull(tree, "tree"); Debug.Assert(!tree.IsEmpty); return Balance(tree) >= 2; } /// <summary> /// Determines whether the specified tree is left heavy. /// </summary> [Pure] private static bool IsLeftHeavy(SortedInt32KeyNode<TValue> tree) { Requires.NotNull(tree, "tree"); Debug.Assert(!tree.IsEmpty); return Balance(tree) <= -2; } /// <summary> /// Balances the specified tree. /// </summary> /// <param name="tree">The tree.</param> /// <returns>A balanced tree.</returns> [Pure] private static SortedInt32KeyNode<TValue> MakeBalanced(SortedInt32KeyNode<TValue> tree) { Requires.NotNull(tree, "tree"); Debug.Assert(!tree.IsEmpty); if (IsRightHeavy(tree)) { return Balance(tree._right) < 0 ? DoubleLeft(tree) : RotateLeft(tree); } if (IsLeftHeavy(tree)) { return Balance(tree._left) > 0 ? DoubleRight(tree) : RotateRight(tree); } return tree; } /// <summary> /// Creates a node tree that contains the contents of a list. /// </summary> /// <param name="items">An indexable list with the contents that the new node tree should contain.</param> /// <param name="start">The starting index within <paramref name="items"/> that should be captured by the node tree.</param> /// <param name="length">The number of elements from <paramref name="items"/> that should be captured by the node tree.</param> /// <returns>The root of the created node tree.</returns> [Pure] private static SortedInt32KeyNode<TValue> NodeTreeFromList(IOrderedCollection<KeyValuePair<int, TValue>> items, int start, int length) { Requires.NotNull(items, "items"); Requires.Range(start >= 0, "start"); Requires.Range(length >= 0, "length"); if (length == 0) { return EmptyNode; } int rightCount = (length - 1) / 2; int leftCount = (length - 1) - rightCount; SortedInt32KeyNode<TValue> left = NodeTreeFromList(items, start, leftCount); SortedInt32KeyNode<TValue> right = NodeTreeFromList(items, start + leftCount + 1, rightCount); var item = items[start + leftCount]; return new SortedInt32KeyNode<TValue>(item.Key, item.Value, left, right, true); } /// <summary> /// Adds the specified key. Callers are expected to have validated arguments. /// </summary> /// <param name="key">The key.</param> /// <param name="value">The value.</param> /// <param name="valueComparer">The value comparer.</param> /// <param name="overwriteExistingValue">if <c>true</c>, an existing key=value pair will be overwritten with the new one.</param> /// <param name="replacedExistingValue">Receives a value indicating whether an existing value was replaced.</param> /// <param name="mutated">Receives a value indicating whether this node tree has mutated because of this operation.</param> /// <returns>The new AVL tree.</returns> private SortedInt32KeyNode<TValue> SetOrAdd(int key, TValue value, IEqualityComparer<TValue> valueComparer, bool overwriteExistingValue, out bool replacedExistingValue, out bool mutated) { // Arg validation skipped in this private method because it's recursive and the tax // of revalidating arguments on each recursive call is significant. // All our callers are therefore required to have done input validation. replacedExistingValue = false; if (this.IsEmpty) { mutated = true; return new SortedInt32KeyNode<TValue>(key, value, this, this); } else { SortedInt32KeyNode<TValue> result = this; if (key > _key) { var newRight = _right.SetOrAdd(key, value, valueComparer, overwriteExistingValue, out replacedExistingValue, out mutated); if (mutated) { result = this.Mutate(right: newRight); } } else if (key < _key) { var newLeft = _left.SetOrAdd(key, value, valueComparer, overwriteExistingValue, out replacedExistingValue, out mutated); if (mutated) { result = this.Mutate(left: newLeft); } } else { if (valueComparer.Equals(_value, value)) { mutated = false; return this; } else if (overwriteExistingValue) { mutated = true; replacedExistingValue = true; result = new SortedInt32KeyNode<TValue>(key, value, _left, _right); } else { throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.DuplicateKey, key)); } } return mutated ? MakeBalanced(result) : result; } } /// <summary> /// Removes the specified key. Callers are expected to validate arguments. /// </summary> /// <param name="key">The key.</param> /// <param name="mutated">Receives a value indicating whether this node tree has mutated because of this operation.</param> /// <returns>The new AVL tree.</returns> private SortedInt32KeyNode<TValue> RemoveRecursive(int key, out bool mutated) { if (this.IsEmpty) { mutated = false; return this; } else { SortedInt32KeyNode<TValue> result = this; if (key == _key) { // We have a match. mutated = true; // If this is a leaf, just remove it // by returning Empty. If we have only one child, // replace the node with the child. if (_right.IsEmpty && _left.IsEmpty) { result = EmptyNode; } else if (_right.IsEmpty && !_left.IsEmpty) { result = _left; } else if (!_right.IsEmpty && _left.IsEmpty) { result = _right; } else { // We have two children. Remove the next-highest node and replace // this node with it. var successor = _right; while (!successor._left.IsEmpty) { successor = successor._left; } bool dummyMutated; var newRight = _right.Remove(successor._key, out dummyMutated); result = successor.Mutate(left: _left, right: newRight); } } else if (key < _key) { var newLeft = _left.Remove(key, out mutated); if (mutated) { result = this.Mutate(left: newLeft); } } else { var newRight = _right.Remove(key, out mutated); if (mutated) { result = this.Mutate(right: newRight); } } return result.IsEmpty ? result : MakeBalanced(result); } } /// <summary> /// Creates a node mutation, either by mutating this node (if not yet frozen) or by creating a clone of this node /// with the described changes. /// </summary> /// <param name="left">The left branch of the mutated node.</param> /// <param name="right">The right branch of the mutated node.</param> /// <returns>The mutated (or created) node.</returns> private SortedInt32KeyNode<TValue> Mutate(SortedInt32KeyNode<TValue> left = null, SortedInt32KeyNode<TValue> right = null) { if (_frozen) { return new SortedInt32KeyNode<TValue>(_key, _value, left ?? _left, right ?? _right); } else { if (left != null) { _left = left; } if (right != null) { _right = right; } _height = checked((byte)(1 + Math.Max(_left._height, _right._height))); return this; } } /// <summary> /// Searches the specified key. Callers are expected to validate arguments. /// </summary> /// <param name="key">The key.</param> [Pure] private SortedInt32KeyNode<TValue> Search(int key) { if (this.IsEmpty || key == _key) { return this; } if (key > _key) { return _right.Search(key); } return _left.Search(key); } /// <summary> /// Enumerates the contents of a binary tree. /// </summary> /// <remarks> /// This struct can and should be kept in exact sync with the other binary tree enumerators: /// <see cref="ImmutableList{T}.Enumerator"/>, <see cref="ImmutableSortedDictionary{TKey, TValue}.Enumerator"/>, and <see cref="ImmutableSortedSet{T}.Enumerator"/>. /// /// CAUTION: when this enumerator is actually used as a valuetype (not boxed) do NOT copy it by assigning to a second variable /// or by passing it to another method. When this enumerator is disposed of it returns a mutable reference type stack to a resource pool, /// and if the value type enumerator is copied (which can easily happen unintentionally if you pass the value around) there is a risk /// that a stack that has already been returned to the resource pool may still be in use by one of the enumerator copies, leading to data /// corruption and/or exceptions. /// </remarks> [EditorBrowsable(EditorBrowsableState.Advanced)] public struct Enumerator : IEnumerator<KeyValuePair<int, TValue>>, ISecurePooledObjectUser { /// <summary> /// The resource pool of reusable mutable stacks for purposes of enumeration. /// </summary> /// <remarks> /// We utilize this resource pool to make "allocation free" enumeration achievable. /// </remarks> private static readonly SecureObjectPool<Stack<RefAsValueType<SortedInt32KeyNode<TValue>>>, Enumerator> s_enumeratingStacks = new SecureObjectPool<Stack<RefAsValueType<SortedInt32KeyNode<TValue>>>, Enumerator>(); /// <summary> /// A unique ID for this instance of this enumerator. /// Used to protect pooled objects from use after they are recycled. /// </summary> private readonly int _poolUserId; /// <summary> /// The set being enumerated. /// </summary> private SortedInt32KeyNode<TValue> _root; /// <summary> /// The stack to use for enumerating the binary tree. /// </summary> private SecurePooledObject<Stack<RefAsValueType<SortedInt32KeyNode<TValue>>>> _stack; /// <summary> /// The node currently selected. /// </summary> private SortedInt32KeyNode<TValue> _current; /// <summary> /// Initializes an <see cref="Enumerator"/> structure. /// </summary> /// <param name="root">The root of the set to be enumerated.</param> internal Enumerator(SortedInt32KeyNode<TValue> root) { Requires.NotNull(root, "root"); _root = root; _current = null; _poolUserId = SecureObjectPool.NewId(); _stack = null; if (!_root.IsEmpty) { if (!s_enumeratingStacks.TryTake(this, out _stack)) { _stack = s_enumeratingStacks.PrepNew(this, new Stack<RefAsValueType<SortedInt32KeyNode<TValue>>>(root.Height)); } this.PushLeft(_root); } } /// <summary> /// The current element. /// </summary> public KeyValuePair<int, TValue> Current { get { this.ThrowIfDisposed(); if (_current != null) { return _current.Value; } throw new InvalidOperationException(); } } /// <inheritdoc/> int ISecurePooledObjectUser.PoolUserId { get { return _poolUserId; } } /// <summary> /// The current element. /// </summary> object IEnumerator.Current { get { return this.Current; } } /// <summary> /// Disposes of this enumerator and returns the stack reference to the resource pool. /// </summary> public void Dispose() { _root = null; _current = null; Stack<RefAsValueType<SortedInt32KeyNode<TValue>>> stack; if (_stack != null && _stack.TryUse(ref this, out stack)) { stack.ClearFastWhenEmpty(); s_enumeratingStacks.TryAdd(this, _stack); } _stack = null; } /// <summary> /// Advances enumeration to the next element. /// </summary> /// <returns>A value indicating whether there is another element in the enumeration.</returns> public bool MoveNext() { this.ThrowIfDisposed(); if (_stack != null) { var stack = _stack.Use(ref this); if (stack.Count > 0) { SortedInt32KeyNode<TValue> n = stack.Pop().Value; _current = n; this.PushLeft(n.Right); return true; } } _current = null; return false; } /// <summary> /// Restarts enumeration. /// </summary> public void Reset() { this.ThrowIfDisposed(); _current = null; if (_stack != null) { var stack = _stack.Use(ref this); stack.ClearFastWhenEmpty(); this.PushLeft(_root); } } /// <summary> /// Throws an <see cref="ObjectDisposedException"/> if this enumerator has been disposed. /// </summary> internal void ThrowIfDisposed() { // Since this is a struct, copies might not have been marked as disposed. // But the stack we share across those copies would know. // This trick only works when we have a non-null stack. // For enumerators of empty collections, there isn't any natural // way to know when a copy of the struct has been disposed of. if (_root == null || (_stack != null && !_stack.IsOwned(ref this))) { Requires.FailObjectDisposed(this); } } /// <summary> /// Pushes this node and all its Left descendants onto the stack. /// </summary> /// <param name="node">The starting node to push onto the stack.</param> private void PushLeft(SortedInt32KeyNode<TValue> node) { Requires.NotNull(node, "node"); var stack = _stack.Use(ref this); while (!node.IsEmpty) { stack.Push(new RefAsValueType<SortedInt32KeyNode<TValue>>(node)); node = node.Left; } } } } }
//////////////////////////////////////////////////////////////////////////// // // Copyright 2016 Realm Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////// using System; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using Nito.AsyncEx; using NUnit.Framework; using Realms; using Realms.Exceptions; namespace Tests.Database { [TestFixture, Preserve(AllMembers = true)] public class InstanceTests : RealmTest { private const string SpecialRealmName = "EnterTheMagic.realm"; protected override void CustomTearDown() { base.CustomTearDown(); Realm.DeleteRealm(RealmConfiguration.DefaultConfiguration); var uniqueConfig = new RealmConfiguration(SpecialRealmName); // for when need 2 realms or want to not use default Realm.DeleteRealm(uniqueConfig); } [Test] public void GetInstanceTest() { // Arrange, act and "assert" that no exception is thrown, using default location Realm.GetInstance().Dispose(); } [Test] public void InstanceIsClosedByDispose() { Realm temp; using (temp = Realm.GetInstance()) { Assert.That(!temp.IsClosed); } Assert.That(temp.IsClosed); } [Test] public void GetInstanceWithJustFilenameTest() { // Arrange, act and "assert" that no exception is thrown, using default location + unique name Realm.GetInstance(SpecialRealmName).Dispose(); } [Test] public void DeleteRealmWorksIfClosed() { // Arrange var config = RealmConfiguration.DefaultConfiguration; var openRealm = Realm.GetInstance(config); // Act openRealm.Dispose(); // Assert Assert.That(File.Exists(config.DatabasePath)); Assert.DoesNotThrow(() => Realm.DeleteRealm(config)); Assert.That(File.Exists(config.DatabasePath), Is.False); } [Test] public void GetUniqueInstancesDifferentThreads() { AsyncContext.Run(async () => { Realm realm1 = null; Realm realm2 = null; try { // Arrange realm1 = Realm.GetInstance(); // Act await Task.Run(() => { realm2 = Realm.GetInstance(); }); // Assert Assert.That(ReferenceEquals(realm1, realm2), Is.False, "ReferenceEquals"); Assert.That(realm1.IsSameInstance(realm2), Is.False, "IsSameInstance"); Assert.That(realm1, Is.EqualTo(realm2), "IsEqualTo"); // equal and same Realm but not same instance } finally { realm1.Dispose(); realm2.Dispose(); } }); } [Test] public void GetCachedInstancesSameThread() { // Arrange using (var realm1 = Realm.GetInstance()) using (var realm2 = Realm.GetInstance()) { // Assert Assert.That(ReferenceEquals(realm1, realm2), Is.False); Assert.That(realm1, Is.EqualTo(realm1)); // check equality with self Assert.That(realm1.IsSameInstance(realm2)); Assert.That(realm1, Is.EqualTo(realm2)); } } [Test] public void InstancesHaveDifferentHashes() { // Arrange using (var realm1 = Realm.GetInstance()) using (var realm2 = Realm.GetInstance()) { // Assert Assert.That(ReferenceEquals(realm1, realm2), Is.False); Assert.That(realm1.GetHashCode(), Is.Not.EqualTo(0)); Assert.That(realm1.GetHashCode(), Is.Not.EqualTo(realm2.GetHashCode())); } } [Test, Ignore("Currently doesn't work. Ref #308")] public void DeleteRealmFailsIfOpenSameThread() { // Arrange var config = new RealmConfiguration(); var openRealm = Realm.GetInstance(config); // Assert Assert.Throws<RealmPermissionDeniedException>(() => Realm.DeleteRealm(config)); } [Test, Ignore("Currently doesn't work. Ref #199")] public void GetInstanceShouldThrowIfFileIsLocked() { // Arrange var databasePath = Path.GetTempFileName(); using (File.Open(databasePath, FileMode.Open, FileAccess.Read, FileShare.None)) // Lock the file { // Act and assert Assert.Throws<RealmPermissionDeniedException>(() => Realm.GetInstance(databasePath)); } } [Test, Ignore("Currently doesn't work. Ref #338")] public void GetInstanceShouldThrowWithBadPath() { // Arrange Assert.Throws<RealmPermissionDeniedException>(() => Realm.GetInstance("/")); } private class LoneClass : RealmObject { public string Name { get; set; } } [Test] public void RealmWithOneClassWritesDesiredClass() { // Arrange var config = new RealmConfiguration("RealmWithOneClass.realm"); Realm.DeleteRealm(config); config.ObjectClasses = new Type[] { typeof(LoneClass) }; // Act using (var lonelyRealm = Realm.GetInstance(config)) { lonelyRealm.Write(() => { lonelyRealm.Add(new LoneClass { Name = "The Singular" }); }); // Assert Assert.That(lonelyRealm.All<LoneClass>().Count(), Is.EqualTo(1)); } } [Test] public void RealmWithOneClassThrowsIfUseOther() { // Arrange var config = new RealmConfiguration("RealmWithOneClass.realm"); Realm.DeleteRealm(config); config.ObjectClasses = new Type[] { typeof(LoneClass) }; // Act and assert using (var lonelyRealm = Realm.GetInstance(config)) { // Can't create an object with a class not included in this Realm lonelyRealm.Write(() => { Assert.That(() => lonelyRealm.Add(new Person()), Throws.TypeOf<ArgumentException>()); }); } } [Test] public void RealmObjectClassesOnlyAllowRealmObjects() { // Arrange var config = new RealmConfiguration("RealmWithOneClass.realm"); Realm.DeleteRealm(config); config.ObjectClasses = new Type[] { typeof(LoneClass), typeof(object) }; // Act and assert // Can't have classes in the list which are not RealmObjects Assert.That(() => Realm.GetInstance(config), Throws.TypeOf<ArgumentException>()); } [TestCase(true)] [TestCase(false)] #if WINDOWS [Ignore("Compact doesn't work on Windows")] #endif public void ShouldCompact_IsInvokedAfterOpening(bool shouldCompact) { var config = new RealmConfiguration($"shouldcompact.realm"); Realm.DeleteRealm(config); using (var realm = Realm.GetInstance(config)) { AddDummyData(realm); } var oldSize = new FileInfo(config.DatabasePath).Length; long projectedNewSize = 0; bool hasPrompted = false; config.ShouldCompactOnLaunch = (totalBytes, bytesUsed) => { Assert.That(totalBytes, Is.EqualTo(oldSize)); hasPrompted = true; projectedNewSize = (long)bytesUsed; return shouldCompact; }; using (var realm = Realm.GetInstance(config)) { Assert.That(hasPrompted, Is.True); var newSize = new FileInfo(config.DatabasePath).Length; if (shouldCompact) { Assert.That(newSize, Is.LessThan(oldSize)); // Less than 20% error in projections Assert.That((newSize - projectedNewSize) / newSize, Is.LessThan(0.2)); } else { Assert.That(newSize, Is.EqualTo(oldSize)); } Assert.That(realm.All<IntPrimaryKeyWithValueObject>().Count(), Is.EqualTo(500)); } } [TestCase(false, true)] [TestCase(false, false)] #if !ENCRYPTION_DISABLED [TestCase(true, true)] [TestCase(true, false)] #endif #if WINDOWS [Ignore("Compact doesn't work on Windows")] #endif public void Compact_ShouldReduceSize(bool encrypt, bool populate) { var config = new RealmConfiguration($"compactrealm_{encrypt}_{populate}.realm"); if (encrypt) { config.EncryptionKey = new byte[64]; config.EncryptionKey[0] = 5; } Realm.DeleteRealm(config); using (var realm = Realm.GetInstance(config)) { if (populate) { AddDummyData(realm); } } var initialSize = new FileInfo(config.DatabasePath).Length; Assert.That(Realm.Compact(config)); var finalSize = new FileInfo(config.DatabasePath).Length; Assert.That(initialSize >= finalSize); using (var realm = Realm.GetInstance(config)) { Assert.That(realm.All<IntPrimaryKeyWithValueObject>().Count(), Is.EqualTo(populate ? 500 : 0)); } } [Test] #if !WINDOWS [Ignore("Compact works on this platform")] #endif public void Compact_OnWindows_ThrowsRealmException() { Assert.That(() => Realm.Compact(RealmConfiguration.DefaultConfiguration), Throws.TypeOf<RealmException>()); } [Test] #if !WINDOWS [Ignore("Compact works on this platform")] #endif public void ShouldCompactOnLaunch_OnWindows_ThrowsRealmException() { var config = new RealmConfiguration { ShouldCompactOnLaunch = (totalBytes, bytesUsed) => true }; Assert.That(() => Realm.GetInstance(config), Throws.TypeOf<RealmException>()); } [Test] #if WINDOWS [Ignore("Compact doesn't work on Windows")] #endif public void Compact_WhenInTransaction_ShouldThrow() { using (var realm = Realm.GetInstance()) { Assert.That(() => { realm.Write(() => { Realm.Compact(); }); }, Throws.TypeOf<RealmInvalidTransactionException>()); } } [Test] #if WINDOWS [Ignore("Compact doesn't work on Windows")] #endif public void Compact_WhenOpenOnDifferentThread_ShouldReturnFalse() { AsyncContext.Run(async () => { using (var realm = Realm.GetInstance()) { AddDummyData(realm); var initialSize = new FileInfo(realm.Config.DatabasePath).Length; bool? isCompacted = null; await Task.Run(() => { isCompacted = Realm.Compact(realm.Config); }); Assert.That(isCompacted, Is.False); var finalSize = new FileInfo(realm.Config.DatabasePath).Length; Assert.That(finalSize, Is.EqualTo(initialSize)); } }); } [Test, Ignore("Currently doesn't work. Ref #947")] public void Compact_WhenOpenOnSameThread_ShouldReturnFalse() { // TODO: enable when we implement instance caching (#947) // This works because of caching of native instances in ObjectStore. // Technically, we get the same native instance, so Compact goes through. // However, this invalidates the opened realm, but we have no way of communicating that. // That is why, things seem fine until we try to run queries on the opened realm. // Once we handle caching in managed, we should reenable the test. using (var realm = Realm.GetInstance()) { var initialSize = new FileInfo(realm.Config.DatabasePath).Length; Assert.That(() => Realm.Compact(), Is.False); var finalSize = new FileInfo(realm.Config.DatabasePath).Length; Assert.That(finalSize, Is.EqualTo(initialSize)); } } [Test] #if WINDOWS [Ignore("Compact doesn't work on Windows")] #endif public void Compact_WhenResultsAreOpen_ShouldReturnFalse() { using (var realm = Realm.GetInstance()) { var token = realm.All<Person>().SubscribeForNotifications((sender, changes, error) => { Console.WriteLine(changes?.InsertedIndices); }); Assert.That(() => Realm.Compact(), Is.False); token.Dispose(); } } [Test] public void RealmChangedShouldFireForEveryInstance() { AsyncContext.Run(async () => { using (var realm1 = Realm.GetInstance()) using (var realm2 = Realm.GetInstance()) { var changed1 = 0; realm1.RealmChanged += (sender, e) => { changed1++; }; var changed2 = 0; realm2.RealmChanged += (sender, e) => { changed2++; }; realm1.Write(() => { realm1.Add(new Person()); }); await Task.Delay(50); Assert.That(changed1, Is.EqualTo(1)); Assert.That(changed2, Is.EqualTo(1)); Assert.That(realm1.All<Person>().Count(), Is.EqualTo(1)); Assert.That(realm2.All<Person>().Count(), Is.EqualTo(1)); realm2.Write(() => { realm2.Add(new Person()); }); await Task.Delay(50); Assert.That(changed1, Is.EqualTo(2)); Assert.That(changed2, Is.EqualTo(2)); Assert.That(realm1.All<Person>().Count(), Is.EqualTo(2)); Assert.That(realm2.All<Person>().Count(), Is.EqualTo(2)); } }); } [Test] public void Dispose_WhenOnTheSameThread_ShouldNotInvalidateOtherInstances() { Realm.DeleteRealm(RealmConfiguration.DefaultConfiguration); var realm1 = Realm.GetInstance(); var realm2 = Realm.GetInstance(); realm1.Write(() => realm1.Add(new Person())); realm1.Dispose(); var people = realm2.All<Person>(); Assert.That(people.Count(), Is.EqualTo(1)); realm2.Dispose(); } [Test] public void Dispose_WhenCalledMultipletimes_ShouldNotInvalidateOtherInstances() { Realm.DeleteRealm(RealmConfiguration.DefaultConfiguration); var realm1 = Realm.GetInstance(); var realm2 = Realm.GetInstance(); realm1.Write(() => realm1.Add(new Person())); for (var i = 0; i < 5; i++) { realm1.Dispose(); } var people = realm2.All<Person>(); Assert.That(people.Count(), Is.EqualTo(1)); realm2.Dispose(); } [Test] public void Dispose_WhenOnDifferentThread_ShouldNotInvalidateOtherInstances() { AsyncContext.Run(async () => { Realm.DeleteRealm(RealmConfiguration.DefaultConfiguration); var realm1 = Realm.GetInstance(); await Task.Run(() => { var realm2 = Realm.GetInstance(); realm2.Write(() => realm2.Add(new Person())); realm2.Dispose(); }); realm1.Refresh(); var people = realm1.All<Person>(); Assert.That(people.Count(), Is.EqualTo(1)); realm1.Dispose(); }); } [Test] public void UsingDisposedRealm_ShouldThrowObjectDisposedException() { AsyncContext.Run(async () => { var realm = Realm.GetInstance(); realm.Dispose(); Assert.That(realm.IsClosed); var other = Realm.GetInstance(); Assert.That(() => realm.Add(new Person()), Throws.TypeOf<ObjectDisposedException>()); Assert.That(() => realm.All<Person>(), Throws.TypeOf<ObjectDisposedException>()); Assert.That(() => realm.All(nameof(Person)), Throws.TypeOf<ObjectDisposedException>()); Assert.That(() => realm.BeginWrite(), Throws.TypeOf<ObjectDisposedException>()); Assert.That(() => realm.CreateObject(nameof(Person)), Throws.TypeOf<ObjectDisposedException>()); Assert.That(() => realm.Find<Person>(0), Throws.TypeOf<ObjectDisposedException>()); Assert.That(() => realm.GetHashCode(), Throws.TypeOf<ObjectDisposedException>()); Assert.That(() => realm.IsSameInstance(other), Throws.TypeOf<ObjectDisposedException>()); Assert.That(() => realm.Refresh(), Throws.TypeOf<ObjectDisposedException>()); Assert.That(() => realm.Remove(new Person()), Throws.TypeOf<ObjectDisposedException>()); Assert.That(() => realm.RemoveAll<Person>(), Throws.TypeOf<ObjectDisposedException>()); Assert.That(() => realm.Write(() => { }), Throws.TypeOf<ObjectDisposedException>()); try { await realm.WriteAsync(_ => { }); Assert.Fail("An exception should have been thrown."); } catch (Exception ex) { Assert.That(ex, Is.TypeOf<ObjectDisposedException>()); } other.Dispose(); }); } private static void AddDummyData(Realm realm) { for (var i = 0; i < 1000; i++) { realm.Write(() => { realm.Add(new IntPrimaryKeyWithValueObject { Id = i, StringValue = "Super secret product " + i }); }); } for (var i = 0; i < 500; i++) { realm.Write(() => { var item = realm.Find<IntPrimaryKeyWithValueObject>(2 * i); realm.Remove(item); }); } } } }
#region License, Terms and Author(s) // // ELMAH - Error Logging Modules and Handlers for ASP.NET // Copyright (c) 2004-9 Atif Aziz. All rights reserved. // // Author(s): // // Atif Aziz, http://www.raboof.com // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion [assembly: Elmah.Scc("$Id: JsonTextWriter.cs 566 2009-05-11 10:37:10Z azizatif $")] namespace Elmah { #region Imports using System; using System.Globalization; using System.IO; using System.Xml; #endregion /// <summary> /// Represents a writer that provides a fast, non-cached, forward-only /// way of generating streams or files containing JSON Text according /// to the grammar rules laid out in /// <a href="http://www.ietf.org/rfc/rfc4627.txt">RFC 4627</a>. /// </summary> /// <remarks> /// This class supports ELMAH and is not intended to be used directly /// from your code. It may be modified or removed in the future without /// notice. It has public accessibility for testing purposes. If you /// need a general-purpose JSON Text encoder, consult /// <a href="http://www.json.org/">JSON.org</a> for implementations /// or use classes available from the Microsoft .NET Framework. /// </remarks> public sealed class JsonTextWriter { private readonly TextWriter _writer; private readonly int[] _counters; private readonly char[] _terminators; private int _depth; private string _memberName; public JsonTextWriter(TextWriter writer) { Debug.Assert(writer != null); _writer = writer; const int levels = 10 + /* root */ 1; _counters = new int[levels]; _terminators = new char[levels]; } public int Depth { get { return _depth; } } private int ItemCount { get { return _counters[Depth]; } set { _counters[Depth] = value; } } private char Terminator { get { return _terminators[Depth]; } set { _terminators[Depth] = value; } } public JsonTextWriter Object() { return StartStructured("{", "}"); } public JsonTextWriter EndObject() { return Pop(); } public JsonTextWriter Array() { return StartStructured("[", "]"); } public JsonTextWriter EndArray() { return Pop(); } public JsonTextWriter Pop() { return EndStructured(); } public JsonTextWriter Member(string name) { if (name == null) throw new ArgumentNullException("name"); if (name.Length == 0) throw new ArgumentException(null, "name"); if (_memberName != null) throw new InvalidOperationException("Missing member value."); _memberName = name; return this; } private JsonTextWriter Write(string text) { return WriteImpl(text, /* raw */ false); } private JsonTextWriter WriteEnquoted(string text) { return WriteImpl(text, /* raw */ true); } private JsonTextWriter WriteImpl(string text, bool raw) { Debug.Assert(raw || (text != null && text.Length > 0)); if (Depth == 0 && (text.Length > 1 || (text[0] != '{' && text[0] != '['))) throw new InvalidOperationException(); TextWriter writer = _writer; if (ItemCount > 0) writer.Write(','); string name = _memberName; _memberName = null; if (name != null) { writer.Write(' '); Enquote(name, writer); writer.Write(':'); } if (Depth > 0) writer.Write(' '); if (raw) Enquote(text, writer); else writer.Write(text); ItemCount = ItemCount + 1; return this; } public JsonTextWriter Number(int value) { return Write(value.ToString(CultureInfo.InvariantCulture)); } public JsonTextWriter String(string str) { return str == null ? Null() : WriteEnquoted(str); } public JsonTextWriter Null() { return Write("null"); } public JsonTextWriter Boolean(bool value) { return Write(value ? "true" : "false"); } private static readonly DateTime _epoch = /* ... */ #if NET_1_0 || NET_1_1 /* ... */ new DateTime(1970, 1, 1, 0, 0, 0); #else /* ... */ new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); #endif public JsonTextWriter Number(DateTime time) { double seconds = time.ToUniversalTime().Subtract(_epoch).TotalSeconds; return Write(seconds.ToString(CultureInfo.InvariantCulture)); } public JsonTextWriter String(DateTime time) { string xmlTime; #if NET_1_0 || NET_1_1 xmlTime = XmlConvert.ToString(time); #else xmlTime = XmlConvert.ToString(time, XmlDateTimeSerializationMode.Utc); #endif return String(xmlTime); } private JsonTextWriter StartStructured(string start, string end) { if (Depth + 1 == _counters.Length) throw new Exception(); Write(start); _depth++; Terminator = end[0]; return this; } private JsonTextWriter EndStructured() { if (Depth - 1 < 0) throw new Exception(); _writer.Write(' '); _writer.Write(Terminator); ItemCount = 0; _depth--; return this; } private static void Enquote(string s, TextWriter writer) { Debug.Assert(writer != null); int length = Mask.NullString(s).Length; writer.Write('"'); char last; char ch = '\0'; for (int index = 0; index < length; index++) { last = ch; ch = s[index]; switch (ch) { case '\\': case '"': { writer.Write('\\'); writer.Write(ch); break; } case '/': { if (last == '<') writer.Write('\\'); writer.Write(ch); break; } case '\b': writer.Write("\\b"); break; case '\t': writer.Write("\\t"); break; case '\n': writer.Write("\\n"); break; case '\f': writer.Write("\\f"); break; case '\r': writer.Write("\\r"); break; default: { if (ch < ' ') { writer.Write("\\u"); writer.Write(((int)ch).ToString("x4", CultureInfo.InvariantCulture)); } else { writer.Write(ch); } break; } } } writer.Write('"'); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.AcceptanceTestsCompositeBoolIntClient { using Microsoft.Rest; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.IO; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// BoolModel operations. /// </summary> public partial class BoolModel : IServiceOperations<CompositeBoolInt>, IBoolModel { /// <summary> /// Initializes a new instance of the BoolModel class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public BoolModel(CompositeBoolInt client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the CompositeBoolInt /// </summary> public CompositeBoolInt Client { get; private set; } /// <summary> /// Get true Boolean value /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse<bool?>> GetTrueWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetTrue", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "bool/true").ToString(); // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<bool?>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<bool?>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Set Boolean value true /// </summary> /// <param name='boolBody'> /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse> PutTrueWithHttpMessagesAsync(bool boolBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("boolBody", boolBody); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "PutTrue", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "bool/true").ToString(); // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; _requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(boolBody, Client.SerializationSettings); _httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get false Boolean value /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse<bool?>> GetFalseWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetFalse", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "bool/false").ToString(); // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<bool?>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<bool?>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Set Boolean value false /// </summary> /// <param name='boolBody'> /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse> PutFalseWithHttpMessagesAsync(bool boolBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("boolBody", boolBody); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "PutFalse", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "bool/false").ToString(); // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; _requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(boolBody, Client.SerializationSettings); _httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get null Boolean value /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse<bool?>> GetNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetNull", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "bool/null").ToString(); // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<bool?>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<bool?>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get invalid Boolean value /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse<bool?>> GetInvalidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetInvalid", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "bool/invalid").ToString(); // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<bool?>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<bool?>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
// // Copyright (c) 2004-2016 Jaroslaw Kowalski <jaak@jkowalski.net>, 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. // using System.Collections; using System.Linq; using System.Threading; using System.Xml; using NLog.Config; #if !SILVERLIGHT namespace NLog.UnitTests { using System; using System.CodeDom.Compiler; using System.Diagnostics; using System.IO; using System.Text; using Microsoft.CSharp; using Xunit; using System.Collections.Generic; public class ConfigFileLocatorTests : NLogTestBase { private string appConfigContents = @" <configuration> <configSections> <section name='nlog' type='NLog.Config.ConfigSectionHandler, NLog' requirePermission='false' /> </configSections> <nlog> <targets> <target name='c' type='Console' layout='AC ${message}' /> </targets> <rules> <logger name='*' minLevel='Info' writeTo='c' /> </rules> </nlog> </configuration> "; private string appNLogContents = @" <nlog> <targets> <target name='c' type='Console' layout='AN ${message}' /> </targets> <rules> <logger name='*' minLevel='Info' writeTo='c' /> </rules> </nlog> "; private string nlogConfigContents = @" <nlog> <targets> <target name='c' type='Console' layout='NLC ${message}' /> </targets> <rules> <logger name='*' minLevel='Info' writeTo='c' /> </rules> </nlog> "; private string nlogDllNLogContents = @" <nlog> <targets> <target name='c' type='Console' layout='NDN ${message}' /> </targets> <rules> <logger name='*' minLevel='Info' writeTo='c' /> </rules> </nlog> "; private string appConfigOutput = "--BEGIN--|AC InfoMsg|AC WarnMsg|AC ErrorMsg|AC FatalMsg|--END--|"; private string appNLogOutput = "--BEGIN--|AN InfoMsg|AN WarnMsg|AN ErrorMsg|AN FatalMsg|--END--|"; private string nlogConfigOutput = "--BEGIN--|NLC InfoMsg|NLC WarnMsg|NLC ErrorMsg|NLC FatalMsg|--END--|"; private string nlogDllNLogOutput = "--BEGIN--|NDN InfoMsg|NDN WarnMsg|NDN ErrorMsg|NDN FatalMsg|--END--|"; private string missingConfigOutput = "--BEGIN--|--END--|"; private readonly string _tempDirectory; public ConfigFileLocatorTests() { _tempDirectory = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N")); Directory.CreateDirectory(_tempDirectory); } [Fact] public void MissingConfigFileTest() { string output = RunTest(); Assert.Equal(missingConfigOutput, output); } [Fact] public void NLogDotConfigTest() { File.WriteAllText(Path.Combine(_tempDirectory, "NLog.config"), nlogConfigContents); string output = RunTest(); Assert.Equal(nlogConfigOutput, output); } [Fact] public void NLogDotDllDotNLogTest() { File.WriteAllText(Path.Combine(_tempDirectory, "NLog.dll.nlog"), nlogDllNLogContents); string output = RunTest(); Assert.Equal(nlogDllNLogOutput, output); } [Fact] public void NLogDotDllDotNLogInDirectoryWithSpaces() { File.WriteAllText(Path.Combine(_tempDirectory, "NLog.dll.nlog"), nlogDllNLogContents); string output = RunTest(); Assert.Equal(nlogDllNLogOutput, output); } [Fact] public void AppDotConfigTest() { File.WriteAllText(Path.Combine(_tempDirectory, "ConfigFileLocator.exe.config"), appConfigContents); string output = RunTest(); Assert.Equal(appConfigOutput, output); } [Fact] public void AppDotNLogTest() { File.WriteAllText(Path.Combine(_tempDirectory, "ConfigFileLocator.exe.nlog"), appNLogContents); string output = RunTest(); Assert.Equal(appNLogOutput, output); } [Fact] public void PrecedenceTest() { var precedence = new[] { new { File = "ConfigFileLocator.exe.config", Contents = appConfigContents, Output = appConfigOutput }, new { File = "NLog.config", Contents = nlogConfigContents, Output = nlogConfigOutput }, new { File = "ConfigFileLocator.exe.nlog", Contents = appNLogContents, Output = appNLogOutput }, new { File = "NLog.dll.nlog", Contents = nlogDllNLogContents, Output = nlogDllNLogOutput }, }; // deploy all files foreach (var p in precedence) { File.WriteAllText(Path.Combine(_tempDirectory, p.File), p.Contents); } string output; // walk files in precedence order and delete config files foreach (var p in precedence) { output = RunTest(); Assert.Equal(p.Output, output); File.Delete(Path.Combine(_tempDirectory, p.File)); } output = RunTest(); Assert.Equal(missingConfigOutput, output); } [Fact] public void GetCandidateConfigTest() { Assert.NotNull(XmlLoggingConfiguration.GetCandidateConfigFilePaths()); var candidateConfigFilePaths = XmlLoggingConfiguration.GetCandidateConfigFilePaths(); var count = candidateConfigFilePaths.Count(); Assert.True(count > 0); } [Fact] public void GetCandidateConfigTest_list_is_readonly() { Assert.Throws<NotSupportedException>(() => { var list = new List<string> { "c:\\global\\temp.config" }; XmlLoggingConfiguration.SetCandidateConfigFilePaths(list); var candidateConfigFilePaths = XmlLoggingConfiguration.GetCandidateConfigFilePaths(); var list2 = candidateConfigFilePaths as IList; list2.Add("test"); }); } [Fact] public void SetCandidateConfigTest() { var list = new List<string> { "c:\\global\\temp.config" }; XmlLoggingConfiguration.SetCandidateConfigFilePaths(list); Assert.Equal(1, XmlLoggingConfiguration.GetCandidateConfigFilePaths().Count()); //no side effects list.Add("c:\\global\\temp2.config"); Assert.Equal(1, XmlLoggingConfiguration.GetCandidateConfigFilePaths().Count()); } [Fact] public void ResetCandidateConfigTest() { var countBefore = XmlLoggingConfiguration.GetCandidateConfigFilePaths().Count(); var list = new List<string> { "c:\\global\\temp.config" }; XmlLoggingConfiguration.SetCandidateConfigFilePaths(list); Assert.Equal(1, XmlLoggingConfiguration.GetCandidateConfigFilePaths().Count()); XmlLoggingConfiguration.ResetCandidateConfigFilePath(); Assert.Equal(countBefore, XmlLoggingConfiguration.GetCandidateConfigFilePaths().Count()); } private string RunTest() { string sourceCode = @" using System; using System.Reflection; using NLog; class C1 { private static ILogger logger = LogManager.GetCurrentClassLogger(); static void Main(string[] args) { Console.WriteLine(""--BEGIN--""); logger.Trace(""TraceMsg""); logger.Debug(""DebugMsg""); logger.Info(""InfoMsg""); logger.Warn(""WarnMsg""); logger.Error(""ErrorMsg""); logger.Fatal(""FatalMsg""); Console.WriteLine(""--END--""); } }"; var provider = new CSharpCodeProvider(); var options = new CompilerParameters(); options.OutputAssembly = Path.Combine(_tempDirectory, "ConfigFileLocator.exe"); options.GenerateExecutable = true; options.ReferencedAssemblies.Add(typeof(ILogger).Assembly.Location); options.IncludeDebugInformation = true; if (!File.Exists(options.OutputAssembly)) { var results = provider.CompileAssemblyFromSource(options, sourceCode); Assert.False(results.Errors.HasWarnings); Assert.False(results.Errors.HasErrors); File.Copy(typeof(ILogger).Assembly.Location, Path.Combine(_tempDirectory, "NLog.dll")); } return RunAndRedirectOutput(options.OutputAssembly); } public static string RunAndRedirectOutput(string exeFile) { using (var proc = new Process()) { #if MONO var sb = new StringBuilder(); sb.AppendFormat("\"{0}\" ", exeFile); proc.StartInfo.Arguments = sb.ToString(); proc.StartInfo.FileName = "mono"; proc.StartInfo.StandardOutputEncoding = Encoding.UTF8; proc.StartInfo.StandardErrorEncoding = Encoding.UTF8; #else proc.StartInfo.FileName = exeFile; #endif proc.StartInfo.UseShellExecute = false; proc.StartInfo.WindowStyle = ProcessWindowStyle.Normal; proc.StartInfo.RedirectStandardInput = false; proc.StartInfo.RedirectStandardOutput = true; proc.StartInfo.RedirectStandardError = true; proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; proc.StartInfo.CreateNoWindow = true; proc.Start(); proc.WaitForExit(); Assert.Equal(string.Empty, proc.StandardError.ReadToEnd()); return proc.StandardOutput.ReadToEnd().Replace("\r", "").Replace("\n", "|"); } } } } #endif
using System; using System.ComponentModel; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Windows.Forms; using DevExpress.CodeRush.Core; using DevExpress.CodeRush.PlugInCore; using DevExpress.CodeRush.StructuralParser; using DevExpress.CodeRush.Core.Replacement; namespace CR_ObjectInitializerToConstructor { public partial class PlugIn1 : StandardPlugIn { private static ObjectInitializerExpression _InitializerExpression; private string _NewCall; private SourceRange _DeleteRange; private FileChangeCollection _Changes; private static ObjectCreationExpression _ObjectCreationExpression; private static ITypeElement _TypeElement; private bool _WaitingForViewActivate; // DXCore-generated code... #region InitializePlugIn public override void InitializePlugIn() { base.InitializePlugIn(); // // TODO: Add your initialization code here. // } #endregion #region FinalizePlugIn public override void FinalizePlugIn() { // // TODO: Add your finalization code here. // base.FinalizePlugIn(); } #endregion private static string FormatAsParameter(string name) { return CodeRush.Strings.Get("FormatParamName", name); } private void targetPicker1_TargetSelected(object sender, TargetSelectedEventArgs ea) { ElementBuilder elementBuilder = new ElementBuilder(); bool missingDefaultConstructor = _TypeElement.HasDefaultConstructor(); if (missingDefaultConstructor) { Method defaultConstructor = elementBuilder.BuildConstructor(null); defaultConstructor.Visibility = MemberVisibility.Public; defaultConstructor.Name = _TypeElement.Name; elementBuilder.AddNode(null, defaultConstructor); } Method constructor = elementBuilder.BuildConstructor(null); constructor.Visibility = MemberVisibility.Public; constructor.Name = _TypeElement.Name; elementBuilder.AddNode(null, constructor); foreach (Expression initializer in _InitializerExpression.Initializers) { MemberInitializerExpression memberInitializerExpression = initializer as MemberInitializerExpression; if (memberInitializerExpression == null) continue; string parameterName = FormatAsParameter(memberInitializerExpression.Name); IElement initializerType = memberInitializerExpression.GetInitializerType(); if (initializerType != null) { Param param = new Param(initializerType.Name, parameterName); constructor.Parameters.Add(param); Assignment assignment = new Assignment(); ElementReferenceExpression leftSide = new ElementReferenceExpression(memberInitializerExpression.Name); if (CodeRush.Language.IdentifiersMatch(memberInitializerExpression.Name, parameterName)) { // Old way of building a "this.Xxxx" expression: //string selfQualifier = CodeRush.Language.GenerateElement(new ThisReferenceExpression()); //leftSide = new ElementReferenceExpression(selfQualifier + CodeRush.Language.MemberAccessOperator + memberInitializerExpression.Name); // Recommended way of building a "this.Xxxx" expression: leftSide = new QualifiedElementReference(memberInitializerExpression.Name); leftSide.Qualifier = new ThisReferenceExpression(); } assignment.LeftSide = leftSide; assignment.Expression = new ElementReferenceExpression(parameterName); constructor.AddNode(assignment); } } string newConstructorCode = elementBuilder.GenerateCode(); // Use FileChange for multi-file changes... FileChange newConstructor = new FileChange(); newConstructor.Path = _TypeElement.FirstFile.Name; newConstructor.Range = new SourceRange(ea.Location.SourcePoint, ea.Location.SourcePoint); newConstructor.Text = newConstructorCode; _Changes.Add(newConstructor); DevExpress.DXCore.TextBuffers.ICompoundAction action = CodeRush.TextBuffers.NewMultiFileCompoundAction("Create Constructor from Initializer"); try { CodeRush.File.ApplyChanges(_Changes, true, false); } finally { action.Close(); _Changes.Clear(); } } private static bool IsInsideInitializerToTypeWithSource(CheckContentAvailabilityEventArgs ea) { _TypeElement = null; _ObjectCreationExpression = ea.Element as ObjectCreationExpression; if (_ObjectCreationExpression == null) { _ObjectCreationExpression = ea.Element.GetParent(LanguageElementType.ObjectCreationExpression) as ObjectCreationExpression; if (_ObjectCreationExpression == null) return false; } _InitializerExpression = _ObjectCreationExpression.ObjectInitializer; if (_InitializerExpression == null) return false; _TypeElement = _ObjectCreationExpression.ObjectType.Resolve(ParserServices.SourceTreeResolver) as ITypeElement; if (_TypeElement == null) return false; return !_TypeElement.InReferencedAssembly; } private static bool HasMatchingConstructors(ObjectInitializerExpression initializer, ITypeElement typeElement) { ExpressionCollection parameters = initializer.Initializers; IElementCollection foundConstructors = typeElement.FindConstructors(parameters); return foundConstructors != null && foundConstructors.Count > 0; } private void cdeCreateConstructorCall_CheckAvailability(object sender, CheckContentAvailabilityEventArgs ea) { if (!IsInsideInitializerToTypeWithSource(ea)) return; if (!HasMatchingConstructors(_ObjectCreationExpression.ObjectInitializer, _TypeElement)) { ea.Available = true; _NewCall = GetNewConstructorCall(_ObjectCreationExpression, _TypeElement); _DeleteRange = _ObjectCreationExpression.Range; } } private void StartTargetPicker(TextDocument textDocument) { TextView activeView = textDocument.ActiveView; if (activeView == null) { if (textDocument.FirstView != null) { textDocument.Activate(); activeView = textDocument.FirstView; activeView.Activate(); } } // IElement -- Lightweight elements for representing source code, including referenced assemblies. // LanguageElement -- Heavier, bigger elements // We can convert from lightweight to heavy using LanguageElementRestorer.ConvertToLanguageElement(); Class typeElement = _TypeElement.GetLanguageElement() as Class; if (typeElement == null) { // We just opened the file -- we need to get a new resolve on the _TypeElement. _TypeElement = _ObjectCreationExpression.ObjectType.GetTypeDeclaration(); typeElement = _TypeElement.GetLanguageElement() as Class; if (typeElement == null) return; } targetPicker1.Start(activeView, typeElement.FirstChild, InsertCode.UsePicker, null); } private void cdeCreateConstructorCall_Apply(object sender, ApplyContentEventArgs ea) { FileChange newFileChange = new FileChange(); newFileChange.Path = CodeRush.Documents.ActiveTextDocument.FileNode.Name; newFileChange.Range = _DeleteRange; newFileChange.Text = _NewCall; CodeRush.Markers.Drop(_DeleteRange.Start, MarkerStyle.Transient); if (_Changes == null) _Changes = new FileChangeCollection(); else _Changes.Clear(); _Changes.Add(newFileChange); TextDocument textDocument = CodeRush.Documents.Get(_TypeElement.FirstFile.Name) as TextDocument; if (textDocument == null) { _WaitingForViewActivate = true; CodeRush.File.Activate(_TypeElement.FirstFile.Name); return; } StartTargetPicker(textDocument); } private string GetNewConstructorCall(ObjectCreationExpression objectCreationWithInitializer, ITypeElement type) { string result = String.Empty; if (type == null || objectCreationWithInitializer == null || objectCreationWithInitializer.ObjectInitializer == null) return result; ExpressionCollection arguments = objectCreationWithInitializer.ObjectInitializer.Initializers; ExpressionCollection newArgs = new ExpressionCollection(); foreach (Expression argument in arguments) { MemberInitializerExpression memberInitializerExpression = argument as MemberInitializerExpression; if (memberInitializerExpression == null) continue; newArgs.Add(memberInitializerExpression.Value); } ObjectCreationExpression newObjectCreationExpression = new ObjectCreationExpression(new TypeReferenceExpression(type.Name), newArgs); if (newObjectCreationExpression != null) result = CodeRush.Language.GenerateElement(newObjectCreationExpression); return result; } private void refConvertToConstructorCall_CheckAvailability(object sender, CheckContentAvailabilityEventArgs ea) { if (!IsInsideInitializerToTypeWithSource(ea)) return; if (HasMatchingConstructors(_ObjectCreationExpression.ObjectInitializer, _TypeElement)) { ea.Available = true; _NewCall = GetNewConstructorCall(_ObjectCreationExpression, _TypeElement); _DeleteRange = _ObjectCreationExpression.Range; } } private void refConvertToConstructorCall_Apply(object sender, ApplyContentEventArgs ea) { ea.TextDocument.Replace(_DeleteRange, _NewCall, "Convert Initializer to Constructor"); } private void refConvertToConstructorCall_PreparePreview(object sender, PrepareContentPreviewEventArgs ea) { ea.AddCodePreview(_DeleteRange.Start, _NewCall); ea.AddStrikethrough(_DeleteRange); } private void cdeCreateConstructorCall_PreparePreview(object sender, PrepareContentPreviewEventArgs ea) { ea.AddCodePreview(_DeleteRange.Start, _NewCall); ea.AddStrikethrough(_DeleteRange); } private void PlugIn1_TextViewActivated(TextViewEventArgs ea) { if (_WaitingForViewActivate) { _WaitingForViewActivate = false; TextDocument activeTextDocument = CodeRush.Documents.ActiveTextDocument; if (activeTextDocument != null) StartTargetPicker(activeTextDocument); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // This file contains the basic primitive type definitions (int etc) // These types are well known to the compiler and the runtime and are basic interchange types that do not change // CONTRACT with Runtime // Each of the data types has a data contract with the runtime. See the contract in the type definition // using System.Runtime.InteropServices; using System.Runtime.CompilerServices; namespace System { // CONTRACT with Runtime // Place holder type for type hierarchy, Compiler/Runtime requires this class public abstract class ValueType { } // CONTRACT with Runtime, Compiler/Runtime requires this class // Place holder type for type hierarchy public abstract class Enum : ValueType { } /*============================================================ ** ** Class: Boolean ** ** ** Purpose: The boolean class serves as a wrapper for the primitive ** type boolean. ** ** ===========================================================*/ // CONTRACT with Runtime // The Boolean type is one of the primitives understood by the compilers and runtime // Data Contract: Single field of type bool public struct Boolean { private bool m_value; } /*============================================================ ** ** Class: Char ** ** ** Purpose: This is the value class representing a Unicode character ** ** ===========================================================*/ // CONTRACT with Runtime // The Char type is one of the primitives understood by the compilers and runtime // Data Contract: Single field of type char // This type is LayoutKind Sequential [StructLayout(LayoutKind.Sequential)] public struct Char { private char m_value; } /*============================================================ ** ** Class: SByte ** ** ** Purpose: A representation of a 8 bit 2's complement integer. ** ** ===========================================================*/ // CONTRACT with Runtime // The SByte type is one of the primitives understood by the compilers and runtime // Data Contract: Single field of type sbyte // This type is LayoutKind Sequential [StructLayout(LayoutKind.Sequential)] public struct SByte { private sbyte m_value; } /*============================================================ ** ** Class: Byte ** ** ** Purpose: A representation of a 8 bit integer (byte) ** ** ===========================================================*/ // CONTRACT with Runtime // The Byte type is one of the primitives understood by the compilers and runtime // Data Contract: Single field of type bool // This type is LayoutKind Sequential [StructLayout(LayoutKind.Sequential)] public struct Byte { private byte m_value; } /*============================================================ ** ** Class: Int16 ** ** ** Purpose: A representation of a 16 bit 2's complement integer. ** ** ===========================================================*/ // CONTRACT with Runtime // The Int16 type is one of the primitives understood by the compilers and runtime // Data Contract: Single field of type short // This type is LayoutKind Sequential [StructLayout(LayoutKind.Sequential)] public struct Int16 { private short m_value; } /*============================================================ ** ** Class: UInt16 ** ** ** Purpose: A representation of a short (unsigned 16-bit) integer. ** ** ===========================================================*/ // CONTRACT with Runtime // The Uint16 type is one of the primitives understood by the compilers and runtime // Data Contract: Single field of type ushort // This type is LayoutKind Sequential [StructLayout(LayoutKind.Sequential)] public struct UInt16 { private ushort m_value; } /*============================================================ ** ** Class: Int32 ** ** ** Purpose: A representation of a 32 bit 2's complement integer. ** ** ===========================================================*/ // CONTRACT with Runtime // The Int32 type is one of the primitives understood by the compilers and runtime // Data Contract: Single field of type int // This type is LayoutKind Sequential [StructLayout(LayoutKind.Sequential)] public struct Int32 { private int m_value; } /*============================================================ ** ** Class: UInt32 ** ** ** Purpose: A representation of a 32 bit unsigned integer. ** ** ===========================================================*/ // CONTRACT with Runtime // The Uint32 type is one of the primitives understood by the compilers and runtime // Data Contract: Single field of type uint // This type is LayoutKind Sequential [StructLayout(LayoutKind.Sequential)] public struct UInt32 { private uint m_value; } /*============================================================ ** ** Class: Int64 ** ** ** Purpose: A representation of a 64 bit 2's complement integer. ** ** ===========================================================*/ // CONTRACT with Runtime // The Int64 type is one of the primitives understood by the compilers and runtime // Data Contract: Single field of type long // This type is LayoutKind Sequential [StructLayout(LayoutKind.Sequential)] public struct Int64 { private long m_value; } /*============================================================ ** ** Class: UInt64 ** ** ** Purpose: A representation of a 64 bit unsigned integer. ** ** ===========================================================*/ // CONTRACT with Runtime // The UInt64 type is one of the primitives understood by the compilers and runtime // Data Contract: Single field of type ulong // This type is LayoutKind Sequential [StructLayout(LayoutKind.Sequential)] public struct UInt64 { private ulong m_value; } /*============================================================ ** ** Class: Single ** ** ** Purpose: A wrapper class for the primitive type float. ** ** ===========================================================*/ // CONTRACT with Runtime // The Single type is one of the primitives understood by the compilers and runtime // Data Contract: Single field of type float // This type is LayoutKind Sequential [StructLayout(LayoutKind.Sequential)] public struct Single { private float m_value; } /*============================================================ ** ** Class: Double ** ** ** Purpose: A representation of an IEEE double precision ** floating point number. ** ** ===========================================================*/ // CONTRACT with Runtime // The Double type is one of the primitives understood by the compilers and runtime // Data Contract: Single field of type double // This type is LayoutKind Sequential [StructLayout(LayoutKind.Sequential)] public struct Double { private double m_value; } /*============================================================ ** ** Class: IntPtr ** ** ** Purpose: Platform independent integer ** ** ===========================================================*/ // CONTRACT with Runtime // The IntPtr type is one of the primitives understood by the compilers and runtime // Data Contract: Single field of type void * // This type implements == without overriding GetHashCode, disable compiler warning #pragma warning disable 0659, 0661 public struct IntPtr { unsafe private void* m_value; // The compiler treats void* closest to uint hence explicit casts are required to preserve int behavior public static readonly IntPtr Zero; public unsafe IntPtr(void* value) { m_value = value; } public unsafe IntPtr(long value) { #if BIT64 m_value = (void*)value; #else m_value = (void*)checked((int)value); #endif } public unsafe override bool Equals(Object obj) { if (obj is IntPtr) { return (m_value == ((IntPtr)obj).m_value); } return false; } public unsafe bool Equals(IntPtr obj) { return (m_value == obj.m_value); } public static unsafe explicit operator IntPtr(void* value) { return new IntPtr(value); } public unsafe static explicit operator long (IntPtr value) { #if BIT64 return (long)value.m_value; #else return (long)(int)value.m_value; #endif } public unsafe static bool operator ==(IntPtr value1, IntPtr value2) { return value1.m_value == value2.m_value; } public unsafe static bool operator !=(IntPtr value1, IntPtr value2) { return value1.m_value != value2.m_value; } public unsafe void* ToPointer() { return m_value; } } #pragma warning restore 0659, 0661 /*============================================================ ** ** Class: UIntPtr ** ** ** Purpose: Platform independent integer ** ** ===========================================================*/ // CONTRACT with Runtime // The UIntPtr type is one of the primitives understood by the compilers and runtime // Data Contract: Single field of type void * public struct UIntPtr { // Disable compile warning about unused m_value field #pragma warning disable 0169 unsafe private void* m_value; #pragma warning restore 0169 public static readonly UIntPtr Zero; } // Decimal class is not supported in RH. Only here to keep compiler happy [TypeNeededIn(TypeNeededInOptions.SOURCE)] internal struct Decimal { } }
using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public partial class Backoffice_Controls_EditPasien : System.Web.UI.UserControl { protected void Page_Load(object sender, EventArgs e) { } private void GetListStatus(string StatusId) { SIMRS.DataAccess.RS_Status myObj = new SIMRS.DataAccess.RS_Status(); DataTable dt = myObj.GetList(); cmbStatusPasien.Items.Clear(); int i = 0; cmbStatusPasien.Items.Add(""); cmbStatusPasien.Items[i].Text = ""; cmbStatusPasien.Items[i].Value = ""; i++; foreach (DataRow dr in dt.Rows) { cmbStatusPasien.Items.Add(""); cmbStatusPasien.Items[i].Text = dr["Nama"].ToString(); cmbStatusPasien.Items[i].Value = dr["Id"].ToString(); if (dr["Id"].ToString() == StatusId) { cmbStatusPasien.SelectedIndex = i; } i++; } } public void GetListPangkatPasien(string PangkatId) { SIMRS.DataAccess.RS_Pangkat myObj = new SIMRS.DataAccess.RS_Pangkat(); if (cmbStatusPasien.SelectedIndex > 0) myObj.StatusId = int.Parse(cmbStatusPasien.SelectedItem.Value); DataTable dt = myObj.GetListByStatusId(); cmbPangkatPasien.Items.Clear(); int i = 0; cmbPangkatPasien.Items.Add(""); cmbPangkatPasien.Items[i].Text = ""; cmbPangkatPasien.Items[i].Value = ""; i++; foreach (DataRow dr in dt.Rows) { cmbPangkatPasien.Items.Add(""); cmbPangkatPasien.Items[i].Text = dr["Nama"].ToString(); cmbPangkatPasien.Items[i].Value = dr["Id"].ToString(); if (dr["Id"].ToString() == PangkatId) { cmbPangkatPasien.SelectedIndex = i; } i++; } } private void GetListStatusPerkawinan(string StatusPerkawinanId) { BkNet.DataAccess.StatusPerkawinan myObj = new BkNet.DataAccess.StatusPerkawinan(); DataTable dt = myObj.GetList(); cmbStatusPerkawinan.Items.Clear(); int i = 0; cmbStatusPerkawinan.Items.Add(""); cmbStatusPerkawinan.Items[i].Text = ""; cmbStatusPerkawinan.Items[i].Value = ""; i++; foreach (DataRow dr in dt.Rows) { cmbStatusPerkawinan.Items.Add(""); cmbStatusPerkawinan.Items[i].Text = dr["Nama"].ToString(); cmbStatusPerkawinan.Items[i].Value = dr["Id"].ToString(); if (dr["Id"].ToString() == StatusPerkawinanId) cmbStatusPerkawinan.SelectedIndex = i; i++; } } private void GetListAgama(string AgamaId) { BkNet.DataAccess.Agama myObj = new BkNet.DataAccess.Agama(); DataTable dt = myObj.GetList(); cmbAgama.Items.Clear(); int i = 0; cmbAgama.Items.Add(""); cmbAgama.Items[i].Text = ""; cmbAgama.Items[i].Value = ""; i++; foreach (DataRow dr in dt.Rows) { cmbAgama.Items.Add(""); cmbAgama.Items[i].Text = dr["Nama"].ToString(); cmbAgama.Items[i].Value = dr["Id"].ToString(); if (dr["Id"].ToString() == AgamaId) cmbAgama.SelectedIndex = i; i++; } } private void GetListPendidikan(string PendidikanId) { BkNet.DataAccess.Pendidikan myObj = new BkNet.DataAccess.Pendidikan(); DataTable dt = myObj.GetList(); cmbPendidikan.Items.Clear(); int i = 0; cmbPendidikan.Items.Add(""); cmbPendidikan.Items[i].Text = ""; cmbPendidikan.Items[i].Value = ""; i++; foreach (DataRow dr in dt.Rows) { cmbPendidikan.Items.Add(""); cmbPendidikan.Items[i].Text = "[" + dr["Kode"].ToString() + "] " + dr["Nama"].ToString(); cmbPendidikan.Items[i].Value = dr["Id"].ToString(); if (dr["Id"].ToString() == PendidikanId) cmbPendidikan.SelectedIndex = i; i++; } } public void Draw(string PasienId) { HFPasienId.Value = PasienId; SIMRS.DataAccess.RS_Pasien myObj = new SIMRS.DataAccess.RS_Pasien(); myObj.PasienId = int.Parse(PasienId); DataTable dt = myObj.SelectOne(); if (dt.Rows.Count > 0) { DataRow dr = dt.Rows[0]; HFPasienId.Value = dr["PasienId"].ToString(); txtNoRM.Text = dr["NoRM"].ToString(); txtNama.Text = dr["Nama"].ToString(); GetListStatus(dr["StatusId"].ToString()); GetListPangkatPasien(dr["PangkatId"].ToString()); txtNoASKES.Text = dr["NoAskes"].ToString(); txtNoKTP.Text = dr["NoKTP"].ToString(); txtGolDarah.Text = dr["GolDarah"].ToString(); txtNrpPasien.Text = dr["NRP"].ToString(); txtJabatan.Text = dr["Jabatan"].ToString(); //txtKesatuanPasien.Text = dr["Kesatuan"].ToString(); GetListSatuanKerja(dr["Kesatuan"].ToString()); txtAlamatKesatuan.Text = dr["AlamatKesatuan"].ToString(); txtTempatLahir.Text = dr["TempatLahir"].ToString() == "" ? "" : dr["TempatLahir"].ToString(); txtTanggalLahir.Text = dr["TanggalLahir"].ToString() != "" ? ((DateTime)dr["TanggalLahir"]).ToString("dd/MM/yyyy") : ""; txtAlamatPasien.Text = dr["Alamat"].ToString(); txtTeleponPasien.Text = dr["Telepon"].ToString(); cmbJenisKelamin.SelectedIndex = dr["JenisKelamin"].ToString() == "L" ? 1 : 2; GetListStatusPerkawinan(dr["StatusPerkawinanId"].ToString()); GetListAgama(dr["AgamaId"].ToString()); GetListPendidikan(dr["PendidikanId"].ToString()); txtPekerjaan.Text = dr["Pekerjaan"].ToString(); txtAlamatKantorPasien.Text = dr["AlamatKantor"].ToString(); txtTeleponKantorPasien.Text = dr["TeleponKantor"].ToString(); txtKeteranganPasien.Text = dr["Keterangan"].ToString(); } } public bool OnSave() { bool result = false; lblError.Text = ""; if (Session["SIMRS.UserId"] == null) { Response.Redirect(Request.ApplicationPath + "/Backoffice/login.aspx"); } int UserId = (int)Session["SIMRS.UserId"]; if (!Page.IsValid) { return false; } string noRM1 = txtNoRM.Text.Replace("_", ""); string noRM2 = noRM1.Replace(".", ""); if (noRM2 == "") { lblError.Text = "Nomor Rekam Medis Harus diisi"; return false; } else if (noRM2.Length < 5) { lblError.Text = "Nomor Rekam Medis Harus diisi dengan benar"; return false; } SIMRS.DataAccess.RS_Pasien myPasien = new SIMRS.DataAccess.RS_Pasien(); myPasien.PasienId = Int64.Parse(HFPasienId.Value); myPasien.SelectOne(); myPasien.NoRM = txtNoRM.Text.Replace("_", ""); myPasien.Nama = txtNama.Text; if (cmbStatusPasien.SelectedIndex > 0) myPasien.StatusId = int.Parse(cmbStatusPasien.SelectedItem.Value); if (cmbPangkatPasien.SelectedIndex > 0) myPasien.PangkatId = int.Parse(cmbPangkatPasien.SelectedItem.Value); myPasien.NoAskes = txtNoASKES.Text; myPasien.NoKTP = txtNoKTP.Text; myPasien.GolDarah = txtGolDarah.Text; myPasien.NRP = txtNrpPasien.Text; myPasien.Jabatan = txtJabatan.Text; //myPasien.Kesatuan = txtKesatuanPasien.Text; myPasien.Kesatuan = cmbSatuanKerja.SelectedItem.ToString(); myPasien.AlamatKesatuan = txtAlamatKesatuan.Text; myPasien.TempatLahir = txtTempatLahir.Text; if (txtTanggalLahir.Text != "") myPasien.TanggalLahir = DateTime.Parse(txtTanggalLahir.Text); myPasien.Alamat = txtAlamatPasien.Text; myPasien.Telepon = txtTeleponPasien.Text; if (cmbJenisKelamin.SelectedIndex > 0) myPasien.JenisKelamin = cmbJenisKelamin.SelectedItem.Value; if (cmbStatusPerkawinan.SelectedIndex > 0) myPasien.StatusPerkawinanId = int.Parse(cmbStatusPerkawinan.SelectedItem.Value); if (cmbAgama.SelectedIndex > 0) myPasien.AgamaId = int.Parse(cmbAgama.SelectedItem.Value); if (cmbPendidikan.SelectedIndex > 0) myPasien.PendidikanId = int.Parse(cmbPendidikan.SelectedItem.Value); myPasien.Pekerjaan = txtPekerjaan.Text; myPasien.AlamatKantor = txtAlamatKantorPasien.Text; myPasien.TeleponKantor = txtTeleponKantorPasien.Text; myPasien.Keterangan = txtKeteranganPasien.Text; myPasien.ModifiedBy = UserId; myPasien.ModifiedDate = DateTime.Now; if (myPasien.IsExist()) { lblError.Text = myPasien.ErrorMessage.ToString(); return false; } else { result = myPasien.Update(); //string CurrentPage = ""; //if (Request.QueryString["CurrentPage"] != null && Request.QueryString["CurrentPage"].ToString() != "") // CurrentPage = Request.QueryString["CurrentPage"].ToString(); //string RawatJalanId = ""; //if (Request.QueryString["RawatJalanId"] != null && Request.QueryString["RawatJalanId"].ToString() != "") // RawatJalanId = Request.QueryString["RawatJalanId"].ToString(); //string PasienId = ""; //if (Request.QueryString["PasienId"] != null && Request.QueryString["PasienId"].ToString() != "") // PasienId = Request.QueryString["PasienId"].ToString(); //if (RawatJalanId != "") // Response.Redirect("ViewDataRJ.aspx?CurrentPage=" + CurrentPage + "&RawatJalanId=" + RawatJalanId); //else // Response.Redirect("ViewPasien.aspx?CurrentPage=" + CurrentPage + "&PasienId=" + PasienId); } return result; } public void OnCancel() { string CurrentPage = ""; if (Request.QueryString["CurrentPage"] != null && Request.QueryString["CurrentPage"].ToString() != "") CurrentPage = Request.QueryString["CurrentPage"].ToString(); string RawatJalanId = ""; if (Request.QueryString["RawatJalanId"] != null && Request.QueryString["RawatJalanId"].ToString() != "") RawatJalanId = Request.QueryString["RawatJalanId"].ToString(); string PasienId = ""; if (Request.QueryString["PasienId"] != null && Request.QueryString["PasienId"].ToString() != "") PasienId = Request.QueryString["PasienId"].ToString(); if (RawatJalanId != "") Response.Redirect("ViewDataRJ.aspx?CurrentPage=" + CurrentPage + "&RawatJalanId=" + RawatJalanId); else Response.Redirect("ViewPasien.aspx?CurrentPage=" + CurrentPage + "&PasienId=" + PasienId); } protected void cmbStatusPasien_SelectedIndexChanged(object sender, EventArgs e) { GetListPangkatPasien(""); } private void GetListSatuanKerja(string Kesatuan) { SIMRS.DataAccess.RS_SatuanKerja myObj = new SIMRS.DataAccess.RS_SatuanKerja(); DataTable dt = myObj.GetList(); cmbSatuanKerja.Items.Clear(); int i = 0; cmbSatuanKerja.Items.Add(""); cmbSatuanKerja.Items[i].Text = ""; cmbSatuanKerja.Items[i].Value = ""; i++; foreach (DataRow dr in dt.Rows) { cmbSatuanKerja.Items.Add(""); cmbSatuanKerja.Items[i].Text = dr["NamaSatker"].ToString(); cmbSatuanKerja.Items[i].Value = dr["IdSatuanKerja"].ToString(); if (dr["NamaSatker"].ToString() == Kesatuan) { cmbSatuanKerja.SelectedIndex = i; } i++; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Android.Support.V4.App; using Android.Support.V4.View; using Android.Support.V7.App; using Android.Support.Design.Widget; using Android.Views.InputMethods; namespace Solitude.Droid { /// <summary> /// The adapter for getting the fragments for the edit panels on signup and edit/new event. /// </summary> public abstract class EditDataAdapter : FragmentPagerAdapter, ViewPager.IOnPageChangeListener, IMenuItemOnMenuItemClickListener { /// <summary> /// A MenuItem for going to the next fragment. /// </summary> protected IMenuItem Next { get; set; } /// <summary> /// A MenuItem for going to the previous fragment. /// </summary> protected IMenuItem Previous { get; set; } /// <summary> /// The activity the adapter is a part of. /// </summary> protected AppCompatActivity Activity { get; set; } /// <summary> /// The viewpager this adapter is contained in /// </summary> protected ViewPager Pager { get; set; } /// <summary> /// The button for finishing the information edition process. /// </summary> protected FloatingActionButton Finish { get; set; } /// <summary> /// The ProgressBar showing how far the user is through the information editing. /// </summary> protected ProgressBar Progress { get; set; } /// <summary> /// All the fragments in the adapter. /// </summary> protected List<EditFragment> Items { get; set; } /// <summary> /// The item currently on the screen. /// </summary> public int Selected { get; set; } /// <summary> /// The total number of Items. /// </summary> public override int Count { get { return Items.Count; } } public EditDataAdapter(AppCompatActivity activity, ViewPager pager, FloatingActionButton finish, ProgressBar progress, IMenuItem prev = null, IMenuItem next = null) : base(activity.SupportFragmentManager) { Activity = activity; Pager = pager; Finish = finish; Progress = progress; Items = new List<EditFragment>(); Finish.Click += (s, e) => NextPage(); Pager.Adapter = this; Progress.Progress = 1; SetNextButton(next); SetPreviousButton(prev); } /// <summary> /// Add a page to the ViewPager. /// </summary> public virtual void AddPager(EditFragment frag) { Items.Add(frag); Progress.Max = Items.Count; NotifyDataSetChanged(); } /// <summary> /// Get the item at a position. /// </summary> public override Android.Support.V4.App.Fragment GetItem(int position) { return Items[position]; } /// <summary> /// Go to the next page in the ViewPager. /// </summary> public virtual void NextPage() { if (Items[Pager.CurrentItem].IsValidData()) { Items[Pager.CurrentItem].SaveInfo(); // If current page is not the last. if (Pager.CurrentItem >= Items.Count - 1) { UpdateData(); } else { // Hide keyboard if the currentitems HidesKeyboard poperty is true. if (Items[Pager.CurrentItem + 1].HidesKeyboard) { InputMethodManager imm = (InputMethodManager)Activity.GetSystemService(Context.InputMethodService); imm.HideSoftInputFromWindow(Pager.WindowToken, 0); } // Set the current item to be the next item. Pager.SetCurrentItem(Pager.CurrentItem + 1, true); Progress.Progress++; // Update finish button is visible only on the last page if (Pager.CurrentItem >= Items.Count - 1) Finish.Visibility = ViewStates.Visible; } } } /// <summary> /// Go to the previous page in the ViewPager. /// </summary> public virtual void PreviousPage() { // If current page is the first if (Pager.CurrentItem <= 0) { BackWarning(); } else { Items[Pager.CurrentItem].SaveInfo(); // Set the current item to be the previous item. Pager.SetCurrentItem(Pager.CurrentItem - 1, true); Progress.Progress--; Finish.Visibility = ViewStates.Gone; } } /// <summary> /// A method for updating data when the finish button is pressed. /// </summary> protected abstract void UpdateData(); /// <summary> /// A method called, to giv the user a warning, when the user is about to leave /// the process, without finishing. /// </summary> protected abstract void BackWarning(); /// <summary> /// A method for going to the activty that this ViewPager should lead to. /// </summary> protected abstract void Back(); public virtual void OnPageScrollStateChanged(int state) { } public virtual void OnPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } /// <summary> /// A method called when the ViewPager selects a new page /// </summary> public virtual void OnPageSelected(int position) { // If the postion changed, to something above the current if (position > Selected) { if (Items[Selected].IsValidData()) { // Hide keyboard if the currentitems HidesKeyboard poperty is true. if (Items[position].HidesKeyboard) { InputMethodManager imm = (InputMethodManager)Activity.GetSystemService(Context.InputMethodService); imm.HideSoftInputFromWindow(Pager.WindowToken, 0); } Items[Selected].SaveInfo(); Selected = position; Progress.Progress = position + 1; // Update finish button is visible only on the last page if (Selected >= Items.Count - 1) Finish.Visibility = ViewStates.Visible; //Update the navigation buttons visibility if (Selected >= Count - 1 && Next != null) Next.SetVisible(false); else if (!(Selected <= 0 && Previous != null)) Previous.SetVisible(true); } else { // If the page couldn't save the data, revert the ViewPager back to the page // that is missing data Pager.SetCurrentItem(Selected, true); } } else { Selected = position; Progress.Progress = position + 1; Finish.Visibility = ViewStates.Gone; //Update the navigation buttons visibility if (Selected <= 0 && Previous != null) Previous.SetVisible(false); else if (!(Selected >= Count - 1) && Next != null) Next.SetVisible(true); } } /// <summary> /// A method called when one of the navigation buttons are clicked. /// </summary> public virtual bool OnMenuItemClick(IMenuItem item) { if (item.ItemId == Previous.ItemId) PreviousPage(); else if (item.ItemId == Next.ItemId) NextPage(); else return false; return true; } /// <summary> /// A method for setting the Next Button /// </summary> public virtual void SetNextButton(IMenuItem next) { Next = next; if (Next != null) { // Update visibility base on position if (Selected >= Count - 1) Next.SetVisible(false); // Set the buttons listner to this Next.SetOnMenuItemClickListener(this); } } /// <summary> /// A method for setting the Next Button /// </summary> public virtual void SetPreviousButton(IMenuItem prev) { Previous = prev; if (Previous != null) { // Update visibility base on position if (Selected <= 0) Previous.SetVisible(false); // Set the buttons listner to this Previous.SetOnMenuItemClickListener(this); } } } }