context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
// Copyright 2008-2011. This work is licensed under the BSD license, available at
// http://www.movesinstitute.org/licenses
//
// Orignal authors: DMcG, Jason Nelson
// Modified for use with C#:
// - Peter Smith (Naval Air Warfare Center - Training Systems Division)
// - Zvonko Bostjancic (Blubit d.o.o. - zvonko.bostjancic@blubit.si)
using System;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
namespace OpenDis.Enumerations.Entity.Management
{
/// <summary>
/// Enumeration values for AggregateSubcategory (eman.aggregate.type.subcategory, Subcategory,
/// section 11.1.3.3)
/// The enumeration values are generated from the SISO DIS XML EBV document (R35), which was
/// obtained from http://discussions.sisostds.org/default.asp?action=10&fd=31
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Serializable]
public enum AggregateSubcategory : byte
{
/// <summary>
/// Other.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Other.")]
Other = 0,
/// <summary>
/// Cavalry Troop.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Cavalry Troop.")]
CavalryTroop = 1,
/// <summary>
/// Armor.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Armor.")]
Armor = 2,
/// <summary>
/// Infantry.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Infantry.")]
Infantry = 3,
/// <summary>
/// Mechanized Infantry.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Mechanized Infantry.")]
MechanizedInfantry = 4,
/// <summary>
/// Cavalry.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Cavalry.")]
Cavalry = 5,
/// <summary>
/// Armored Cavalry.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Armored Cavalry.")]
ArmoredCavalry = 6,
/// <summary>
/// Artillery.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Artillery.")]
Artillery = 7,
/// <summary>
/// Self-propelled Artillery.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Self-propelled Artillery.")]
SelfPropelledArtillery = 8,
/// <summary>
/// Close Air Support.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Close Air Support.")]
CloseAirSupport = 9,
/// <summary>
/// Engineer.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Engineer.")]
Engineer = 10,
/// <summary>
/// Air Defense Artillery.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Air Defense Artillery.")]
AirDefenseArtillery = 11,
/// <summary>
/// Anti-tank.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Anti-tank.")]
AntiTank = 12,
/// <summary>
/// Army Aviation Fixed-wing.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Army Aviation Fixed-wing.")]
ArmyAviationFixedWing = 13,
/// <summary>
/// Army Aviation Rotary-wing.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Army Aviation Rotary-wing.")]
ArmyAviationRotaryWing = 14,
/// <summary>
/// Army Attack Helicopter.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Army Attack Helicopter.")]
ArmyAttackHelicopter = 15,
/// <summary>
/// Air Cavalry.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Air Cavalry.")]
AirCavalry = 16,
/// <summary>
/// Armor Heavy Task Force.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Armor Heavy Task Force.")]
ArmorHeavyTaskForce = 17,
/// <summary>
/// Motorized Rifle.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Motorized Rifle.")]
MotorizedRifle = 18,
/// <summary>
/// Mechanized Heavy Task Force.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Mechanized Heavy Task Force.")]
MechanizedHeavyTaskForce = 19,
/// <summary>
/// Command Post.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Command Post.")]
CommandPost = 20,
/// <summary>
/// CEWI.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("CEWI.")]
CEWI = 21,
/// <summary>
/// Tank only.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Tank only.")]
TankOnly = 22
}
}
| |
using System;
using FluentAssertions.Execution;
#if !OLD_MSTEST
using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
#else
using Microsoft.VisualStudio.TestTools.UnitTesting;
#endif
namespace FluentAssertions.Specs
{
[TestClass]
public class NullableBooleanAssertionSpecs
{
[TestMethod]
public void When_asserting_nullable_boolean_value_with_a_value_to_have_a_value_it_should_succeed()
{
bool? nullableBoolean = true;
nullableBoolean.Should().HaveValue();
}
[TestMethod]
public void When_asserting_nullable_boolean_value_with_a_value_to_not_be_null_it_should_succeed()
{
bool? nullableBoolean = true;
nullableBoolean.Should().NotBeNull();
}
[TestMethod]
public void When_asserting_nullable_boolean_value_without_a_value_to_have_a_value_it_should_fail()
{
bool? nullableBoolean = null;
Action act = () => nullableBoolean.Should().HaveValue();
act.ShouldThrow<AssertFailedException>();
}
[TestMethod]
public void When_asserting_nullable_boolean_value_without_a_value_to_not_be_null_it_should_fail()
{
bool? nullableBoolean = null;
Action act = () => nullableBoolean.Should().NotBeNull();
act.ShouldThrow<AssertFailedException>();
}
[TestMethod]
public void When_asserting_nullable_boolean_value_without_a_value_to_have_a_value_it_should_fail_with_descriptive_message()
{
bool? nullableBoolean = null;
var assertions = nullableBoolean.Should();
assertions.Invoking(x => x.HaveValue("because we want to test the failure {0}", "message"))
.ShouldThrow<AssertFailedException>()
.WithMessage("Expected a value because we want to test the failure message.");
}
[TestMethod]
public void When_asserting_nullable_boolean_value_without_a_value_to_not_be_null_it_should_fail_with_descriptive_message()
{
bool? nullableBoolean = null;
var assertions = nullableBoolean.Should();
assertions.Invoking(x => x.NotBeNull("because we want to test the failure {0}", "message"))
.ShouldThrow<AssertFailedException>()
.WithMessage("Expected a value because we want to test the failure message.");
}
[TestMethod]
public void When_asserting_nullable_boolean_value_without_a_value_to_not_have_a_value_it_should_succeed()
{
bool? nullableBoolean = null;
nullableBoolean.Should().NotHaveValue();
}
[TestMethod]
public void When_asserting_nullable_boolean_value_without_a_value_to_be_null_it_should_succeed()
{
bool? nullableBoolean = null;
nullableBoolean.Should().BeNull();
}
[TestMethod]
public void When_asserting_nullable_boolean_value_with_a_value_to_not_have_a_value_it_should_fail()
{
bool? nullableBoolean = true;
Action act = () => nullableBoolean.Should().NotHaveValue();
act.ShouldThrow<AssertFailedException>();
}
[TestMethod]
public void When_asserting_nullable_boolean_value_with_a_value_to_be_null_it_should_fail()
{
bool? nullableBoolean = true;
Action act = () => nullableBoolean.Should().BeNull();
act.ShouldThrow<AssertFailedException>();
}
[TestMethod]
public void When_asserting_nullable_boolean_value_with_a_value_to_be_not_have_a_value_it_should_fail_with_descriptive_message()
{
bool? nullableBoolean = true;
var assertions = nullableBoolean.Should();
assertions.Invoking(x => x.NotHaveValue("because we want to test the failure {0}", "message"))
.ShouldThrow<AssertFailedException>()
.WithMessage("Did not expect a value because we want to test the failure message, but found True.");
}
[TestMethod]
public void When_asserting_nullable_boolean_value_with_a_value_to_be_null_it_should_fail_with_descriptive_message()
{
bool? nullableBoolean = true;
var assertions = nullableBoolean.Should();
assertions.Invoking(x => x.BeNull("because we want to test the failure {0}", "message"))
.ShouldThrow<AssertFailedException>()
.WithMessage("Did not expect a value because we want to test the failure message, but found True.");
}
[TestMethod]
public void When_asserting_boolean_null_value_is_false_it_should_fail()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange
//-----------------------------------------------------------------------------------------------------------
bool? nullableBoolean = null;
//-----------------------------------------------------------------------------------------------------------
// Act
//-----------------------------------------------------------------------------------------------------------
Action action = () =>
nullableBoolean.Should().BeFalse("we want to test the failure {0}", "message");
//-----------------------------------------------------------------------------------------------------------
// Assert
//-----------------------------------------------------------------------------------------------------------
action.ShouldThrow<AssertFailedException>()
.WithMessage("Expected False because we want to test the failure message, but found <null>.");
}
[TestMethod]
public void When_asserting_boolean_null_value_is_true_it_sShould_fail()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange
//-----------------------------------------------------------------------------------------------------------
bool? nullableBoolean = null;
//-----------------------------------------------------------------------------------------------------------
// Act
//-----------------------------------------------------------------------------------------------------------
Action action = () =>
nullableBoolean.Should().BeTrue("we want to test the failure {0}", "message");
//-----------------------------------------------------------------------------------------------------------
// Assert
//-----------------------------------------------------------------------------------------------------------
action.ShouldThrow<AssertFailedException>()
.WithMessage("Expected True because we want to test the failure message, but found <null>.");
}
[TestMethod]
public void When_asserting_boolean_null_value_to_be_equal_to_different_nullable_boolean_should_fail()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange
//-----------------------------------------------------------------------------------------------------------
bool? nullableBoolean = null;
bool? differentNullableBoolean = false;
//-----------------------------------------------------------------------------------------------------------
// Act
//-----------------------------------------------------------------------------------------------------------
Action action = () =>
nullableBoolean.Should().Be(differentNullableBoolean, "we want to test the failure {0}", "message");
//-----------------------------------------------------------------------------------------------------------
// Arrange
//-----------------------------------------------------------------------------------------------------------
action.ShouldThrow<AssertFailedException>()
.WithMessage("Expected False because we want to test the failure message, but found <null>.");
}
[TestMethod]
public void When_asserting_boolean_null_value_to_be_equal_to_null_it_sShould_succeed()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange
//-----------------------------------------------------------------------------------------------------------
bool? nullableBoolean = null;
bool? otherNullableBoolean = null;
//-----------------------------------------------------------------------------------------------------------
// Act
//-----------------------------------------------------------------------------------------------------------
Action action = () =>
nullableBoolean.Should().Be(otherNullableBoolean);
//-----------------------------------------------------------------------------------------------------------
// Arrange
//-----------------------------------------------------------------------------------------------------------
action.ShouldNotThrow();
}
[TestMethod]
public void When_asserting_true_is_not_false_it_should_succeed()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
bool? trueBoolean = true;
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action action = () =>
trueBoolean.Should().NotBeFalse();
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
action.ShouldNotThrow();
}
[TestMethod]
public void When_asserting_null_is_not_false_it_should_succeed()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
bool? nullValue = null;
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action action = () =>
nullValue.Should().NotBeFalse();
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
action.ShouldNotThrow();
}
[TestMethod]
public void When_asserting_false_is_not_false_it_should_fail_with_descriptive_message()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
bool? falseBoolean = false;
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action action = () =>
falseBoolean.Should().NotBeFalse("we want to test the failure message");
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
action.ShouldThrow<AssertFailedException>()
.WithMessage("Expected*nullable*boolean*not*False*because we want to test the failure message, but found False.");
}
[TestMethod]
public void When_asserting_false_is_not_true_it_should_succeed()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
bool? trueBoolean = false;
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action action = () =>
trueBoolean.Should().NotBeTrue();
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
action.ShouldNotThrow();
}
[TestMethod]
public void When_asserting_null_is_not_true_it_should_succeed()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
bool? nullValue = null;
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action action = () =>
nullValue.Should().NotBeTrue();
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
action.ShouldNotThrow();
}
[TestMethod]
public void When_asserting_true_is_not_true_it_should_fail_with_descriptive_message()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
bool? falseBoolean = true;
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action action = () =>
falseBoolean.Should().NotBeTrue("we want to test the failure message");
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
action.ShouldThrow<AssertFailedException>()
.WithMessage("Expected*nullable*boolean*not*True*because we want to test the failure message, but found True.");
}
[TestMethod]
public void Should_support_chaining_constraints_with_and()
{
bool? nullableBoolean = true;
nullableBoolean.Should()
.HaveValue()
.And
.BeTrue();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using bv.common;
using bv.common.Configuration;
using bv.common.Core;
using bv.common.db.Core;
using bv.common.Enums;
using bv.common.Resources;
using bv.model.Model.Core;
using bv.winclient.Core;
using DevExpress.Data.Filtering;
using DevExpress.Utils;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraPivotGrid;
using eidss.avr.BaseComponents;
using eidss.avr.BaseComponents.Views;
using eidss.avr.db.Common;
using eidss.avr.db.DBService;
using eidss.avr.db.DBService.DataSource;
using eidss.avr.PivotComponents;
using eidss.avr.Tools;
using eidss.model.Avr.Chart;
using eidss.model.Avr.Commands;
using eidss.model.Avr.Commands.Layout;
using eidss.model.Avr.Pivot;
using eidss.model.AVR.SourceData;
using eidss.model.Enums;
using eidss.model.Reports.OperationContext;
using eidss.model.Resources;
using EIDSS;
using BaseReferenceType = bv.common.db.BaseReferenceType;
using Localizer = bv.common.Core.Localizer;
namespace eidss.avr.PivotForm
{
public sealed class PivotDetailPresenter : RelatedObjectPresenter
{
private readonly IPivotDetailView m_PivotView;
private readonly BaseAvrDbService m_PivotFormService;
private readonly LayoutMediator m_LayoutMediator;
static PivotDetailPresenter()
{
InitGisTypes();
}
public PivotDetailPresenter(SharedPresenter sharedPresenter, IPivotDetailView view)
: base(sharedPresenter, view)
{
m_PivotFormService = new BaseAvrDbService();
m_PivotView = view;
m_PivotView.DBService = PivotFormService;
m_LayoutMediator = new LayoutMediator(this);
}
public bool Changed { get; set; }
public static Dictionary<string, GisCaseType> GisTypeDictionary { get; private set; }
public BaseAvrDbService PivotFormService
{
get { return m_PivotFormService; }
}
public string CorrectedLayoutName
{
get
{
return (Utils.IsEmpty(LayoutName))
? EidssMessages.Get("msgNoReportHeader", "[Untitled]")
: LayoutName;
}
}
public string LayoutName
{
get
{
return (ModelUserContext.CurrentLanguage == Localizer.lngEn)
? m_LayoutMediator.LayoutRow.strDefaultLayoutName
: m_LayoutMediator.LayoutRow.strLayoutName;
}
}
public long LayoutId
{
get { return m_LayoutMediator.LayoutRow.idflLayout; }
}
public bool ApplyFilter
{
get { return m_LayoutMediator.LayoutRow.blnApplyPivotGridFilter; }
}
public bool ShowDataInPivotGrid
{
get { return m_LayoutMediator.LayoutRow.blnShowDataInPivotGrid; }
}
public bool CompactPivotGrid
{
get { return m_LayoutMediator.LayoutRow.blnCompactPivotGrid; }
set { m_LayoutMediator.LayoutRow.blnCompactPivotGrid = value; }
}
private PivotGridXmlVersion PivotGridXmlVersion
{
get { return (PivotGridXmlVersion) m_LayoutMediator.LayoutRow.intPivotGridXmlVersion; }
}
public LayoutDetailDataSet.LayoutSearchFieldDataTable LayoutSearchFieldTable
{
get { return m_LayoutMediator.LayoutDataSet.LayoutSearchField; }
}
public string SettingsXml
{
get
{
string basicXml = m_LayoutMediator.LayoutRow.IsstrPivotGridSettingsNull()
? String.Empty
: m_LayoutMediator.LayoutRow.strPivotGridSettings;
return basicXml;
}
set { m_LayoutMediator.LayoutRow.strPivotGridSettings = value; }
}
public bool ReadOnly
{
get { return m_LayoutMediator.LayoutRow.blnReadOnly; }
}
public bool FreezeRowHeaders
{
get { return m_LayoutMediator.LayoutRow.blnFreezeRowHeaders; }
}
public bool ShowMissedValues
{
get { return m_LayoutMediator.LayoutRow.blnShowMissedValuesInPivotGrid; }
set { m_LayoutMediator.LayoutRow.blnShowMissedValuesInPivotGrid = value; }
}
public bool CopyPivotName { get; set; }
public bool CopyMapName { get; set; }
public bool CopyChartName { get; set; }
#region Binding
public void BindFreezeRowHeaders(CheckEdit checkEdit)
{
BindingHelper.BindCheckEdit(checkEdit,
m_LayoutMediator.LayoutDataSet,
m_LayoutMediator.LayoutTable.TableName,
m_LayoutMediator.LayoutTable.blnFreezeRowHeadersColumn.ColumnName);
}
public void BindShareLayout(CheckEdit checkEdit)
{
BindingHelper.BindCheckEdit(checkEdit,
m_LayoutMediator.LayoutDataSet,
m_LayoutMediator.LayoutTable.TableName,
m_LayoutMediator.LayoutTable.blnShareLayoutColumn.ColumnName);
}
public void BindApplyFilter(CheckEdit checkEdit)
{
BindingHelper.BindCheckEdit(checkEdit,
m_LayoutMediator.LayoutDataSet,
m_LayoutMediator.LayoutTable.TableName,
m_LayoutMediator.LayoutTable.blnApplyPivotGridFilterColumn.ColumnName);
}
public void BindShowDataInPivotGrid(CheckEdit checkEdit)
{
BindingHelper.BindCheckEdit(checkEdit,
m_LayoutMediator.LayoutDataSet,
m_LayoutMediator.LayoutTable.TableName,
m_LayoutMediator.LayoutTable.blnShowDataInPivotGridColumn.ColumnName);
}
public void BindCompactPivotGrid(CheckEdit checkEdit)
{
BindingHelper.BindCheckEdit(checkEdit,
m_LayoutMediator.LayoutDataSet,
m_LayoutMediator.LayoutTable.TableName,
m_LayoutMediator.LayoutTable.blnCompactPivotGridColumn.ColumnName);
}
public void BindShowMissedValues(CheckEdit checkEdit)
{
BindingHelper.BindCheckEdit(checkEdit,
m_LayoutMediator.LayoutDataSet,
m_LayoutMediator.LayoutTable.TableName,
m_LayoutMediator.LayoutTable.blnShowMissedValuesInPivotGridColumn.ColumnName);
}
public void BindDefaultLayoutName(TextEdit edit)
{
BindingHelper.BindEditor(edit,
m_LayoutMediator.LayoutDataSet,
m_LayoutMediator.LayoutTable.TableName,
m_LayoutMediator.LayoutTable.strDefaultLayoutNameColumn.ColumnName);
}
public void BindLayoutName(TextEdit edit)
{
BindingHelper.BindEditor(edit,
m_LayoutMediator.LayoutDataSet,
m_LayoutMediator.LayoutTable.TableName,
m_LayoutMediator.LayoutTable.strLayoutNameColumn.ColumnName);
}
public void BindDescription(TextEdit edit)
{
BindingHelper.BindEditor(edit,
m_LayoutMediator.LayoutDataSet,
m_LayoutMediator.LayoutTable.TableName,
m_LayoutMediator.LayoutTable.strDescriptionColumn.ColumnName);
}
internal void BindGroupInterval(LookUpEdit comboBox)
{
BindingHelper.BindCombobox(comboBox,
m_LayoutMediator.LayoutDataSet,
m_LayoutMediator.LayoutTable.TableName,
m_LayoutMediator.LayoutTable.idfsDefaultGroupDateColumn.ColumnName,
BaseReferenceType.rftGroupInterval,
(long) DBGroupInterval.gitDateYear);
}
public void BindShowTotalCols(CheckedComboBoxEdit edit)
{
edit.Properties.Items[0].CheckState = GetCheckState(m_LayoutMediator.LayoutRow.blnShowColsTotals);
edit.Properties.Items[1].CheckState = GetCheckState(m_LayoutMediator.LayoutRow.blnShowRowsTotals);
edit.Properties.Items[2].CheckState = GetCheckState(m_LayoutMediator.LayoutRow.blnShowColGrandTotals);
edit.Properties.Items[3].CheckState = GetCheckState(m_LayoutMediator.LayoutRow.blnShowRowGrandTotals);
edit.Properties.Items[4].CheckState = GetCheckState(m_LayoutMediator.LayoutRow.blnShowForSingleTotals);
edit.RefreshEditValue();
edit.Properties.TextEditStyle = TextEditStyles.DisableTextEditor;
if (Utils.IsEmpty(edit.EditValue))
{
edit.EditValue = DBNull.Value;
}
}
public void BindBackShowTotalCols(CheckedComboBoxEdit edit, PivotGridOptionsView optionsView, bool isCompact)
{
if (isCompact)
{
optionsView.ShowRowTotals = true;
optionsView.ShowTotalsForSingleValues = true;
optionsView.RowTotalsLocation = PivotRowTotalsLocation.Tree;
}
else
{
optionsView.RowTotalsLocation = PivotRowTotalsLocation.Far;
m_LayoutMediator.LayoutRow.blnShowColsTotals = IsChecked(edit, 0);
m_LayoutMediator.LayoutRow.blnShowRowsTotals = IsChecked(edit, 1);
m_LayoutMediator.LayoutRow.blnShowColGrandTotals = IsChecked(edit, 2);
m_LayoutMediator.LayoutRow.blnShowRowGrandTotals = IsChecked(edit, 3);
m_LayoutMediator.LayoutRow.blnShowForSingleTotals = IsChecked(edit, 4);
optionsView.ShowColumnTotals = m_LayoutMediator.LayoutRow.blnShowColsTotals;
optionsView.ShowRowTotals = m_LayoutMediator.LayoutRow.blnShowRowsTotals;
optionsView.ShowColumnGrandTotals = m_LayoutMediator.LayoutRow.blnShowColGrandTotals;
optionsView.ShowRowGrandTotals = m_LayoutMediator.LayoutRow.blnShowRowGrandTotals;
optionsView.ShowTotalsForSingleValues = m_LayoutMediator.LayoutRow.blnShowForSingleTotals;
optionsView.ShowGrandTotalsForSingleValues = m_LayoutMediator.LayoutRow.blnShowForSingleTotals;
}
}
private static CheckState GetCheckState(bool flag)
{
return flag
? CheckState.Checked
: CheckState.Unchecked;
}
private static bool IsChecked(CheckedComboBoxEdit edit, int index)
{
if (index >= edit.Properties.Items.Count || index < 0)
{
throw new ArgumentException("Index out of range");
}
return edit.Properties.Items[index].CheckState == CheckState.Checked;
}
#endregion
/// <summary>
/// It's workaround method. don't use it
/// </summary>
/// <param name="layoutName"> </param>
public void SetLayoutName(string layoutName)
{
m_LayoutMediator.LayoutRow.strLayoutName = layoutName;
}
/// <summary>
/// It's workaround method. don't use it
/// </summary>
/// <param name="layoutName"> </param>
public void SetDefaultLayoutName(string layoutName)
{
m_LayoutMediator.LayoutRow.strDefaultLayoutName = layoutName;
}
public void InitAdmUnit(LookUpEdit cbAdministrativeUnit, IAvrPivotGridField selectedField)
{
using (SharedPresenter.ContextKeeper.CreateNewContext(ContextValue.InitAdmUnit))
{
long queryId = m_SharedPresenter.SharedModel.SelectedQueryId;
DataView dataView = AvrPivotGridHelper.GetAdministrativeUnitView(queryId, m_PivotView.AvrFields.ToList());
string fieldAlias = SharedPresenter.GetSelectedAdministrativeFieldAlias(dataView, selectedField);
BindComboBox(cbAdministrativeUnit, dataView, fieldAlias);
}
}
public void InitStatDate(LookUpEdit cbStatDate, IAvrPivotGridField selectedField)
{
DataView dataView = AvrPivotGridHelper.GetStatisticDateView(m_PivotView.AvrFields);
string fieldAlias = selectedField == null
? null
: selectedField.GetSelectedDateFieldAlias();
BindComboBox(cbStatDate, dataView, fieldAlias);
}
private static void BindComboBox(LookUpEdit combo, DataView dataView, string fieldAlias)
{
combo.DataBindings.Clear();
combo.Properties.Columns.Clear();
var info = new LookUpColumnInfo("Caption", EidssMessages.Get("colCaption", "Caption"),
200, FormatType.None, "", true, HorzAlignment.Near);
combo.Properties.Columns.AddRange(new[] {info});
combo.Properties.PopupWidth = combo.Width;
combo.Properties.NullText = string.Empty;
combo.Properties.DataSource = dataView;
combo.Properties.ValueMember = "Alias";
combo.Properties.DisplayMember = "Caption";
DataRow[] found = dataView.Table.Select(string.Format("Alias='{0}'", fieldAlias));
if (found.Length > 0)
{
combo.EditValue = found[0]["Alias"];
}
else
{
combo.EditValue = (dataView.Count > 0)
? dataView[0]["Alias"]
: DBNull.Value;
}
}
public override void Process(Command cmd)
{
try
{
var fieldCommand = cmd as PivotFieldCommand;
if (fieldCommand != null)
{
switch (fieldCommand.FieldOperation)
{
case PivotFieldOperation.Rename:
ProcessRenameFieldCaption(fieldCommand);
break;
case PivotFieldOperation.Copy:
ProcessCopyField(fieldCommand);
break;
case PivotFieldOperation.DeleteCopy:
ProcessDeleteField(fieldCommand);
break;
case PivotFieldOperation.AddMissedValues:
case PivotFieldOperation.EditMissedValues:
ProcessAddEditMissedValues(fieldCommand);
break;
case PivotFieldOperation.DeleteMissedValues:
ProcessDeleteMissedValues(fieldCommand);
break;
}
}
var fieldGroupDateCommand = cmd as PivotFieldGroupIntervalCommand;
if (fieldGroupDateCommand != null)
{
ProcessGroupInterval(fieldGroupDateCommand);
}
}
catch (Exception ex)
{
if (BaseSettings.ThrowExceptionOnError)
{
throw;
}
ErrorForm.ShowError(ex);
}
}
private void ProcessRenameFieldCaption(PivotFieldCommand command)
{
if (command == null || command.Field == null)
{
return;
}
command.State = CommandState.Pending;
LayoutDetailDataSet.LayoutSearchFieldRow row = GetLayoutSearchFieldRowByField(command.Field);
using (var form = new RenameFieldDialog(row.strOriginalFieldENCaption, row.strOriginalFieldCaption,
row.strNewFieldENCaption, row.strNewFieldCaption))
{
if (form.ShowDialog(m_PivotView.ParentForm) == DialogResult.OK)
{
row.strNewFieldENCaption = form.NewEnglishCaption;
row.strNewFieldCaption = ModelUserContext.CurrentLanguage == Localizer.lngEn
? form.NewEnglishCaption
: form.NewNationalCaption;
command.Field.Caption = row.strNewFieldCaption;
}
}
command.State = CommandState.Processed;
}
private void ProcessCopyField(PivotFieldCommand command)
{
if (command == null || command.Field == null)
{
return;
}
command.State = CommandState.Pending;
using (m_PivotView.PivotGridView.BeginTransaction())
{
CreateFieldCopy<WinPivotGridField>(command.Field);
m_PivotView.PivotGridView.ClearCacheDataRowColumnAreaFields();
}
m_PivotView.ClickOnFocusedCell(true);
command.State = CommandState.Processed;
}
private void ProcessDeleteField(PivotFieldCommand command)
{
if (command == null || command.Field == null)
{
return;
}
command.State = CommandState.Pending;
using (m_PivotView.PivotGridView.BeginTransaction())
{
DeleteFieldCopy(command.Field);
m_PivotView.PivotGridView.ClearCacheDataRowColumnAreaFields();
}
m_PivotView.ClickOnFocusedCell(true);
//AjustCreateDeleteFieldsEnable();
command.State = CommandState.Processed;
}
private void ProcessAddEditMissedValues(PivotFieldCommand command)
{
if (command == null || command.Field == null)
{
return;
}
command.State = CommandState.Pending;
IAvrPivotGridField field = command.Field;
bool needToChange = !field.IsDateTimeField;
if (field.IsDateTimeField)
{
using (var form = new DateDiapasonDialog(field.DiapasonStartDate, field.DiapasonEndDate))
{
if (form.ShowDialog(m_PivotView.ParentForm) == DialogResult.OK)
{
if (field.DiapasonStartDate != form.DateFrom || field.DiapasonEndDate != form.DateTo)
{
field.DiapasonStartDate = form.DateFrom;
field.DiapasonEndDate = form.DateTo;
needToChange = true;
}
}
}
}
if (needToChange)
{
foreach (IAvrPivotGridField change in GetFieldCopiesExceptHidden(command))
{
if (change.Visible && (change.Area == PivotArea.ColumnArea || change.Area == PivotArea.RowArea))
{
change.AddMissedValues = true;
change.DiapasonStartDate = field.DiapasonStartDate;
change.DiapasonEndDate = field.DiapasonEndDate;
change.UpdateImageIndex();
}
}
Changed = true;
if (m_PivotView.ShowMissedValues && m_PivotView.ShowData)
{
using (m_PivotView.BeginTransaction())
{
m_PivotView.FillAbsentAndMissingValues();
m_PivotView.RefreshPivotData();
}
}
}
command.State = CommandState.Processed;
}
private void ProcessDeleteMissedValues(PivotFieldCommand command)
{
if (command == null || command.Field == null)
{
return;
}
command.State = CommandState.Pending;
foreach (IAvrPivotGridField change in GetFieldCopiesExceptHidden(command))
{
change.DiapasonStartDate = null;
change.DiapasonEndDate = null;
change.AddMissedValues = false;
change.UpdateImageIndex();
}
Changed = true;
if (m_PivotView.ShowMissedValues && m_PivotView.ShowData)
{
using (m_PivotView.BeginTransaction())
{
m_PivotView.FillAbsentAndMissingValues();
m_PivotView.RefreshPivotData();
}
}
command.State = CommandState.Processed;
}
internal IEnumerable<IAvrPivotGridField> GetFieldCopiesExceptHidden(PivotFieldCommand command)
{
return GetFieldCopiesExceptHidden(command.Field);
}
internal IEnumerable<IAvrPivotGridField> GetFieldCopiesExceptHidden(IAvrPivotGridField field)
{
return m_PivotView.AvrFields.Where(f => !f.IsHiddenFilterField && f.OriginalFieldName == field.OriginalFieldName);
}
private void ProcessGroupInterval(PivotFieldGroupIntervalCommand command)
{
if (command == null || command.Field == null)
{
return;
}
command.State = CommandState.Pending;
IAvrPivotGridField field = command.Field;
using (m_PivotView.BeginTransaction())
{
field.PrivateGroupInterval = command.GroupInterval;
m_PivotView.FillAbsentAndMissingValues();
}
command.State = CommandState.Processed;
}
#region Prepare Data Source For Pivot Grid
public AvrDataTable GetPreparedDataSource()
{
if (m_SharedPresenter.IsQueryResultNull)
{
return null;
}
bool isNewObject = IsNewObject || LayoutSearchFieldTable.Count == 0;
var filter = isNewObject
? null
: m_LayoutMediator.LayoutRow.strPivotGridSettings;
AvrDataTable newDataSource = m_SharedPresenter.GetQueryResultCopy(filter);
long queryId = m_SharedPresenter.SharedModel.SelectedQueryId;
var res = AvrPivotGridHelper.GetPreparedDataSource(LayoutSearchFieldTable, queryId, LayoutId, newDataSource, isNewObject);
return res;
}
public AvrDataTable GetPreparedDataSourceFiltered(string expression)
{
if (m_SharedPresenter.IsQueryResultNull)
{
return null;
}
AvrDataTable newDataSource = m_SharedPresenter.GetQueryResultCopy(expression);
long queryId = m_SharedPresenter.SharedModel.SelectedQueryId;
var res = AvrPivotGridHelper.GetPreparedDataSource(LayoutSearchFieldTable, queryId, LayoutId, newDataSource, false);
return res;
}
#endregion
#region Load Pivot Grid
public void LoadPivotFromDB()
{
List<IAvrPivotGridField> avrFields = m_PivotView.AvrFields.ToList();
if (!IsNewObject)
{
if (PivotGridXmlVersion == PivotGridXmlVersion.Version5)
{
LoadPivotVersionFiveFromDB();
}
else
{
long intervalId = m_LayoutMediator.LayoutRow.idfsDefaultGroupDate;
AvrPivotGridHelper.LoadSearchFieldsVersionSixFromDB(avrFields, LayoutSearchFieldTable, intervalId);
LoadPivotFilterVersionSixFromDB();
}
}
AvrPivotGridHelper.LoadExstraSearchFieldsProperties(avrFields, LayoutSearchFieldTable);
}
private void LoadPivotFilterVersionSixFromDB()
{
try
{
m_PivotView.FilterCriteria = CriteriaOperator.Parse(SettingsXml);
}
catch (Exception ex)
{
m_PivotView.FilterCriteria = null;
Trace.WriteLine(ex);
if (BaseSettings.ThrowExceptionOnError)
{
throw;
}
string msg = EidssMessages.Get("errCannotRestoreAvrFilterFromDb", "Pivot Grid filter can't be restored from Database");
ErrorForm.ShowErrorDirect(msg, ex);
}
}
private void LoadPivotVersionFiveFromDB()
{
if (!string.IsNullOrEmpty(SettingsXml))
{
using (var stream = new MemoryStream())
{
using (var streamWriter = new StreamWriter(stream))
{
streamWriter.Write(SettingsXml);
streamWriter.Flush();
stream.Position = 0;
m_PivotView.PivotGridView.RestoreLayoutFromStream(stream);
}
}
}
}
#endregion
#region Save Pivot Grid
public void SavePivotFilterToDB(CriteriaOperator filter)
{
Changed = false;
SettingsXml = (ReferenceEquals(filter, null)) ? null : filter.ToString();
}
#endregion
#region Create and delete Field Copy
public Dictionary<IAvrPivotGridField, IAvrPivotGridField> GetFieldsAndCopies()
{
var fieldsAndCopies = new Dictionary<IAvrPivotGridField, IAvrPivotGridField>();
foreach (IAvrPivotGridField field in m_PivotView.AvrFields.Where(f => !f.IsHiddenFilterField))
{
IAvrPivotGridField fieldCopy =
m_PivotView.AvrFields.FirstOrDefault(f => f.IsHiddenFilterField && f.OriginalFieldName == field.OriginalFieldName);
if (fieldCopy != null)
{
fieldsAndCopies.Add(field, fieldCopy);
}
}
return fieldsAndCopies;
}
public void CreateFieldCopy<T>(IAvrPivotGridField sourceField) where T : IAvrPivotGridField, new()
{
var copy = AvrPivotGridHelper.CreateFieldCopy<T>(sourceField,
m_LayoutMediator.LayoutDataSet,
m_PivotView.DataSource,
m_SharedPresenter.SharedModel.SelectedQueryId,
LayoutId);
m_PivotView.AddField(copy);
m_PivotView.RefreshPivotData();
}
private LayoutDetailDataSet.LayoutSearchFieldRow GetLayoutSearchFieldRowByField(IAvrPivotGridField sourceField)
{
return AvrPivotGridHelper.GetLayoutSearchFieldRowByField(sourceField, m_LayoutMediator.LayoutDataSet);
}
public void DeleteFieldCopy(IAvrPivotGridField sourceField)
{
string message = String.Format(BvMessages.Get("msgDeleteAVRFieldPrompt", "{0} field will be deleted. Delete field?"),
sourceField.Caption);
DialogResult dialogResult = MessageForm.Show(message, BvMessages.Get("Confirmation"),
MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (dialogResult != DialogResult.Yes)
{
return;
}
AvrPivotGridHelper.DeleteFieldCopy(sourceField, m_LayoutMediator.LayoutDataSet, m_PivotView.DataSource);
m_PivotView.RemoveField(sourceField);
m_PivotView.RefreshPivotData();
}
#endregion
#region Helper Methods
private static void InitGisTypes()
{
GisTypeDictionary = new Dictionary<string, GisCaseType>();
DataView lookupGisTypes = LookupCache.Get(LookupTables.CaseType.ToString());
if (lookupGisTypes == null)
{
return;
}
foreach (DataRowView row in lookupGisTypes)
{
string key = row["name"].ToString();
if (!GisTypeDictionary.ContainsKey(key))
{
var id = (long) row["idfsReference"];
switch (id)
{
case (long) CaseTypeEnum.Human:
GisTypeDictionary.Add(key, GisCaseType.Human);
break;
case (long) CaseTypeEnum.Livestock:
GisTypeDictionary.Add(key, GisCaseType.Livestock);
break;
case (long) CaseTypeEnum.Avian:
GisTypeDictionary.Add(key, GisCaseType.Avian);
break;
case (long) CaseTypeEnum.Veterinary:
GisTypeDictionary.Add(key, GisCaseType.Vet);
break;
case (long) CaseTypeEnum.Vector:
GisTypeDictionary.Add(key, GisCaseType.Vector);
break;
default:
GisTypeDictionary.Add(key, GisCaseType.Unkown);
break;
}
}
}
}
public static bool AskQuestion(string text, string caption)
{
return MessageForm.Show(text, caption,
MessageBoxButtons.YesNo,
MessageBoxIcon.Question,
MessageBoxDefaultButton.Button2) == DialogResult.Yes;
}
public static string AppendLanguageNameTo(string text)
{
if (!Utils.IsEmpty(text))
{
int bracketInd = text.IndexOf("(", StringComparison.Ordinal);
if (bracketInd >= 0)
{
text = text.Substring(0, bracketInd).Trim();
}
string languageName = Localizer.GetLanguageName(ModelUserContext.CurrentLanguage);
text = String.Format("{0} ({1})", text, languageName);
}
return text;
}
#endregion
}
}
| |
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABILITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Automation;
using Microsoft.PythonTools;
using Microsoft.PythonTools.Parsing;
using Microsoft.PythonTools.Project;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.VisualStudioTools;
using TestUtilities;
using TestUtilities.UI;
using TestUtilities.UI.Python;
namespace PythonToolsUITests {
public class BuildTasksUITests {
internal void Execute(PythonProjectNode projectNode, string commandName) {
Console.WriteLine("Executing command {0}", commandName);
var t = projectNode.Site.GetUIThread().InvokeTask(() => projectNode._customCommands.First(cc => cc.DisplayLabel == commandName).ExecuteAsync(projectNode));
t.GetAwaiter().GetResult();
}
internal Task ExecuteAsync(PythonProjectNode projectNode, string commandName) {
Console.WriteLine("Executing command {0} asynchronously", commandName);
return projectNode.Site.GetUIThread().InvokeTask(() => projectNode._customCommands.First(cc => cc.DisplayLabel == commandName).ExecuteAsync(projectNode));
}
internal void OpenProject(VisualStudioApp app, string slnName, PythonVersion python, out PythonProjectNode projectNode, out EnvDTE.Project dteProject) {
dteProject = app.OpenProject(app.CopyProjectForTest("TestData\\Targets\\" + slnName));
var pn = projectNode = dteProject.GetPythonProject();
var fact = projectNode.InterpreterFactories.Where(x => x.Configuration.Id == python.Id).FirstOrDefault();
Assert.IsNotNull(fact, "Project does not contain expected interpreter");
app.ServiceProvider.GetUIThread().Invoke(() => pn.ActiveInterpreter = fact);
dteProject.Save();
}
public void CustomCommandsAdded(VisualStudioApp app, PythonVersion python) {
PythonProjectNode node;
EnvDTE.Project proj;
OpenProject(app, "Commands1.sln", python, out node, out proj);
AssertUtil.ContainsExactly(
node._customCommands.Select(cc => cc.DisplayLabel),
"Test Command 1",
"Test Command 2"
);
app.OpenSolutionExplorer().FindItem("Solution 'Commands1' (1 of 1 project)", "Commands1").Select();
var menuBar = app.FindByAutomationId("MenuBar").AsWrapper();
Assert.IsNotNull(menuBar, "Unable to find menu bar");
var projectMenu = menuBar.FindByName("Project").AsWrapper();
Assert.IsNotNull(projectMenu, "Unable to find Project menu");
projectMenu.Element.EnsureExpanded();
try {
foreach (var name in node._customCommands.Select(cc => cc.DisplayLabelWithoutAccessKeys)) {
Assert.IsNotNull(projectMenu.FindByName(name), name + " not found");
}
} finally {
try {
// Try really really hard to collapse and deselect the
// Project menu, since VS will keep it selected and it
// may not come back for some reason...
projectMenu.Element.Collapse();
Keyboard.PressAndRelease(System.Windows.Input.Key.Escape);
Keyboard.PressAndRelease(System.Windows.Input.Key.Escape);
} catch {
// ...but don't try so hard that we fail if we can't
// simulate keypresses.
}
}
}
public void CustomCommandsWithResourceLabel(VisualStudioApp app, PythonVersion python) {
PythonProjectNode node;
EnvDTE.Project proj;
OpenProject(app, "Commands2.sln", python, out node, out proj);
AssertUtil.ContainsExactly(
node._customCommands.Select(cc => cc.Label),
"resource:PythonToolsUITests;PythonToolsUITests.Resources;CommandName"
);
AssertUtil.ContainsExactly(
node._customCommands.Select(cc => cc.DisplayLabel),
"Command from Resource"
);
}
public void CustomCommandsReplWithResourceLabel(PythonVisualStudioApp app, PythonVersion python) {
PythonProjectNode node;
EnvDTE.Project proj;
OpenProject(app, "Commands2.sln", python, out node, out proj);
Execute(node, "Command from Resource");
using (var repl = app.GetInteractiveWindow("Repl from Resource")) {
Assert.IsNotNull(repl, "Could not find repl window");
repl.WaitForTextEnd(
"Program.py completed",
">"
);
}
using (var repl = app.GetInteractiveWindow("resource:PythonToolsUITests;PythonToolsUITests.Resources;ReplName")) {
Assert.IsNull(repl);
}
}
public void CustomCommandsRunInRepl(PythonVisualStudioApp app, PythonVersion python) {
PythonProjectNode node;
EnvDTE.Project proj;
OpenProject(app, "Commands1.sln", python, out node, out proj);
Execute(node, "Test Command 2");
using (var repl = app.GetInteractiveWindow("Test Repl")) {
Assert.IsNotNull(repl, "Could not find repl window");
repl.WaitForTextEnd(
"Program.py completed",
">"
);
}
app.Dte.Solution.Close();
using (var repl = app.GetInteractiveWindow("Test Repl")) {
Assert.IsNull(repl, "Repl window was not closed");
}
}
public void CustomCommandsRunProcessInRepl(PythonVisualStudioApp app, PythonVersion python) {
PythonProjectNode node;
EnvDTE.Project proj;
OpenProject(app, "Commands3.sln", python, out node, out proj);
Execute(node, "Write to Repl");
using (var repl = app.GetInteractiveWindow("Test Repl")) {
Assert.IsNotNull(repl, "Could not find repl window");
repl.WaitForTextEnd(
string.Format("({0}, {1})", python.Configuration.Version.Major, python.Configuration.Version.Minor),
">"
);
}
}
private static void ExpectOutputWindowText(VisualStudioApp app, string expected) {
var outputWindow = app.Element.FindFirst(TreeScope.Descendants,
new AndCondition(
new PropertyCondition(AutomationElement.ClassNameProperty, "GenericPane"),
new PropertyCondition(AutomationElement.NameProperty, "Output")
)
);
Assert.IsNotNull(outputWindow, "Output Window was not opened");
var outputText = "";
for (int retries = 100; !outputText.Contains(expected) && retries > 0; --retries) {
Thread.Sleep(100);
outputText = outputWindow.FindFirst(TreeScope.Descendants,
new PropertyCondition(AutomationElement.ClassNameProperty, "WpfTextView")
).AsWrapper().GetValue();
}
Console.WriteLine("Output Window: " + outputText);
Assert.IsTrue(outputText.Contains(expected), string.Format("Expected to see:\r\n\r\n{0}\r\n\r\nActual content:\r\n\r\n{1}", expected, outputText));
}
public void CustomCommandsRunProcessInOutput(PythonVisualStudioApp app, PythonVersion python) {
PythonProjectNode node;
EnvDTE.Project proj;
OpenProject(app, "Commands3.sln", python, out node, out proj);
Execute(node, "Write to Output");
var outputWindow = app.Element.FindFirst(TreeScope.Descendants,
new AndCondition(
new PropertyCondition(AutomationElement.ClassNameProperty, "GenericPane"),
new PropertyCondition(AutomationElement.NameProperty, "Output")
)
);
Assert.IsNotNull(outputWindow, "Output Window was not opened");
ExpectOutputWindowText(app, string.Format("({0}, {1})", python.Configuration.Version.Major, python.Configuration.Version.Minor));
}
public void CustomCommandsRunProcessInConsole(PythonVisualStudioApp app, PythonVersion python) {
PythonProjectNode node;
EnvDTE.Project proj;
OpenProject(app, "Commands3.sln", python, out node, out proj);
var existingProcesses = new HashSet<int>(Process.GetProcessesByName("cmd").Select(p => p.Id));
Execute(node, "Write to Console");
Process newProcess = null;
for (int retries = 100; retries > 0 && newProcess == null; --retries) {
Thread.Sleep(100);
newProcess = Process.GetProcessesByName("cmd").Where(p => !existingProcesses.Contains(p.Id)).FirstOrDefault();
}
Assert.IsNotNull(newProcess, "Process did not start");
try {
newProcess.CloseMainWindow();
newProcess.WaitForExit(1000);
if (newProcess.HasExited) {
newProcess = null;
}
} finally {
if (newProcess != null) {
newProcess.Kill();
}
}
}
public void CustomCommandsErrorList(PythonVisualStudioApp app, PythonVersion python) {
PythonProjectNode node;
EnvDTE.Project proj;
OpenProject(app, "ErrorCommand.sln", python, out node, out proj);
var expectedItems = new[] {
new { Document = "Program.py", Line = 0, Column = 1, Category = __VSERRORCATEGORY.EC_ERROR, Message = "This is an error with a relative path." },
new { Document = Path.Combine(node.ProjectHome, "Program.py"), Line = 2, Column = 3, Category = __VSERRORCATEGORY.EC_WARNING, Message = "This is a warning with an absolute path." },
new { Document = ">>>", Line = 4, Column = -1, Category = __VSERRORCATEGORY.EC_ERROR, Message = "This is an error with an invalid path." },
};
Execute(node, "Produce Errors");
var items = app.WaitForErrorListItems(3);
Console.WriteLine("Got errors:");
foreach (var item in items) {
string document, text;
Assert.AreEqual(0, item.Document(out document), "HRESULT getting document");
Assert.AreEqual(0, item.get_Text(out text), "HRESULT getting message");
Console.WriteLine(" {0}: {1}", document ?? "(null)", text ?? "(null)");
}
Assert.AreEqual(expectedItems.Length, items.Count);
// Second invoke should replace the error items in the list, not add new ones to those already existing.
Execute(node, "Produce Errors");
items = app.WaitForErrorListItems(3);
Assert.AreEqual(expectedItems.Length, items.Count);
items.Sort(Comparer<IVsTaskItem>.Create((x, y) => {
int lx, ly;
x.Line(out lx);
y.Line(out ly);
return lx.CompareTo(ly);
}));
for (int i = 0; i < expectedItems.Length; ++i) {
var item = items[i];
var expectedItem = expectedItems[i];
string document, message;
item.get_Text(out message);
item.Document(out document);
int line, column;
item.Line(out line);
item.Column(out column);
uint category;
((IVsErrorItem)item).GetCategory(out category);
Assert.AreEqual(expectedItem.Document, document);
Assert.AreEqual(expectedItem.Line, line);
Assert.AreEqual(expectedItem.Column, column);
Assert.AreEqual(expectedItem.Message, message);
Assert.AreEqual(expectedItem.Category, (__VSERRORCATEGORY)category);
}
app.ServiceProvider.GetUIThread().Invoke((Action)delegate { items[0].NavigateTo(); });
var doc = app.Dte.ActiveDocument;
Assert.IsNotNull(doc);
Assert.AreEqual("Program.py", doc.Name);
var textDoc = (EnvDTE.TextDocument)doc.Object("TextDocument");
Assert.AreEqual(1, textDoc.Selection.ActivePoint.Line);
Assert.AreEqual(2, textDoc.Selection.ActivePoint.DisplayColumn);
}
public void CustomCommandsRequiredPackages(PythonVisualStudioApp app, PythonVersion python) {
using (var dis = app.SelectDefaultInterpreter(python, "virtualenv")) {
PythonProjectNode node;
EnvDTE.Project proj;
OpenProject(app, "CommandRequirePackages.sln", python, out node, out proj);
string envName;
var env = app.CreateProjectVirtualEnvironment(proj, out envName);
env.Select();
app.Dte.ExecuteCommand("Python.ActivateEnvironment");
// Ensure that no error dialog appears
app.WaitForNoDialog(TimeSpan.FromSeconds(5.0));
// First, execute the command and cancel it.
var task = ExecuteAsync(node, "Require Packages");
try {
var dialogHandle = app.WaitForDialog(task);
if (dialogHandle == IntPtr.Zero) {
if (task.IsFaulted && task.Exception != null) {
Assert.Fail("Unexpected exception in package install confirmation dialog:\n{0}", task.Exception);
} else {
Assert.AreNotEqual(IntPtr.Zero, dialogHandle);
}
}
using (var dialog = new AutomationDialog(app, AutomationElement.FromHandle(dialogHandle))) {
var label = dialog.FindByAutomationId("CommandLink_1000");
Assert.IsNotNull(label);
string expectedLabel =
"The following packages will be installed using pip:\r\n" +
"\r\n" +
"ptvsd\r\n" +
"azure==0.1"; ;
Assert.AreEqual(expectedLabel, label.Current.HelpText);
dialog.Cancel();
try {
task.Wait(1000);
Assert.Fail("Command was not canceled after dismissing the package install confirmation dialog");
} catch (AggregateException ex) {
if (!(ex.InnerException is TaskCanceledException)) {
throw;
}
}
}
} finally {
if (!task.IsCanceled && !task.IsCompleted && !task.IsFaulted) {
if (task.Wait(10000)) {
task.Dispose();
}
} else {
task.Dispose();
}
}
// Then, execute command and allow it to proceed.
task = ExecuteAsync(node, "Require Packages");
try {
var dialogHandle = app.WaitForDialog(task);
if (dialogHandle == IntPtr.Zero) {
if (task.IsFaulted && task.Exception != null) {
Assert.Fail("Unexpected exception in package install confirmation dialog:\n{0}", task.Exception);
} else {
Assert.AreNotEqual(IntPtr.Zero, dialogHandle);
}
}
using (var dialog = new AutomationDialog(app, AutomationElement.FromHandle(dialogHandle))) {
dialog.ClickButtonAndClose("CommandLink_1000", nameIsAutomationId: true);
}
task.Wait();
var ver = python.Version.ToVersion();
ExpectOutputWindowText(app, string.Format("pass {0}.{1}", ver.Major, ver.Minor));
} finally {
if (!task.IsCanceled && !task.IsCompleted && !task.IsFaulted) {
if (task.Wait(10000)) {
task.Dispose();
}
} else {
task.Dispose();
}
}
}
}
public void CustomCommandsSearchPath(PythonVisualStudioApp app, PythonVersion python) {
var expectedSearchPath = string.Format("['{0}', '{1}', '{2}']",
// Includes CWD (ProjectHome) first
TestData.GetPath(@"TestData\Targets\Package\Subpackage").Replace("\\", "\\\\"),
// Specified as '..\..' from ProjectHome
TestData.GetPath(@"TestData\Targets").Replace("\\", "\\\\"),
// Specified as '..' from ProjectHome
TestData.GetPath(@"TestData\Targets\Package").Replace("\\", "\\\\")
);
PythonProjectNode node;
EnvDTE.Project proj;
OpenProject(app, "CommandSearchPath.sln", python, out node, out proj);
Execute(node, "Import From Search Path");
var outputWindow = app.Element.FindFirst(TreeScope.Descendants,
new AndCondition(
new PropertyCondition(AutomationElement.ClassNameProperty, "GenericPane"),
new PropertyCondition(AutomationElement.NameProperty, "Output")
)
);
Assert.IsNotNull(outputWindow, "Output Window was not opened");
ExpectOutputWindowText(app, expectedSearchPath);
}
}
}
| |
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
[CanEditMultipleObjects]
[CustomEditor(typeof(SgtNebulaStarfield))]
public class SgtNebulaStarfield_Editor : SgtPointStarfield_Editor<SgtNebulaStarfield>
{
protected override void OnInspector()
{
var updateMaterial = false;
var updateMeshesAndModels = false;
DrawMaterial(ref updateMaterial);
Separator();
DrawAtlas(ref updateMaterial, ref updateMeshesAndModels);
Separator();
DrawPointMaterial(ref updateMaterial);
Separator();
DrawDefault("Seed", ref updateMeshesAndModels);
BeginError(Any(t => t.SourceTex == null));
DrawDefault("SourceTex", ref updateMeshesAndModels);
EndError();
DrawDefault("Threshold", ref updateMeshesAndModels);
DrawDefault("Jitter", ref updateMeshesAndModels);
DrawDefault("Samples", ref updateMeshesAndModels);
DrawDefault("HeightSource", ref updateMeshesAndModels);
DrawDefault("ScaleSource", ref updateMeshesAndModels);
BeginError(Any(t => t.Size.x <= 0.0f || t.Size.y <= 0.0f || t.Size.z <= 0.0f));
DrawDefault("Size", ref updateMeshesAndModels);
EndError();
Separator();
BeginError(Any(t => t.HorizontalBrightness < 0.0f));
DrawDefault("HorizontalBrightness");
EndError();
BeginError(Any(t => t.HorizontalPower < 0.0f));
DrawDefault("HorizontalPower");
EndError();
Separator();
BeginError(Any(t => t.StarRadiusMin < 0.0f || t.StarRadiusMin > t.StarRadiusMax));
DrawDefault("StarRadiusMin", ref updateMeshesAndModels);
EndError();
BeginError(Any(t => t.StarRadiusMax < 0.0f || t.StarRadiusMin > t.StarRadiusMax));
DrawDefault("StarRadiusMax", ref updateMeshesAndModels);
EndError();
DrawDefault("StarPulseMax", ref updateMeshesAndModels);
DrawDefault("StarCount", ref updateMeshesAndModels);
RequireObserver();
serializedObject.ApplyModifiedProperties();
if (updateMaterial == true) DirtyEach(t => t.UpdateMaterial ());
if (updateMeshesAndModels == true) DirtyEach(t => t.UpdateMeshesAndModels());
}
}
#endif
[ExecuteInEditMode]
[AddComponentMenu(SgtHelper.ComponentMenuPrefix + "Nebula Starfield")]
public class SgtNebulaStarfield : SgtPointStarfield
{
[Tooltip("The random seed used when generating the stars")]
[SgtSeed]
public int Seed;
[Tooltip("This texture used to color the nebula particles")]
public Texture SourceTex;
[Tooltip("This brightness of the sampled SourceTex pixel for a particle to be spawned")]
[Range(0.0f, 1.0f)]
public float Threshold = 0.1f;
[Tooltip("The amount of times a nebula point is randomly sampled, before the brightest sample is used")]
[Range(1, 5)]
public int Samples = 2;
[Tooltip("This allows you to randomly offset each nebula particle position")]
[Range(0.0f, 1.0f)]
public float Jitter;
[Tooltip("The calculation used to find the height offset of a particle in the nebula")]
public SgtNebulaSource HeightSource = SgtNebulaSource.None;
[Tooltip("The calculation used to find the scale modified of each particle in the nebula")]
public SgtNebulaSource ScaleSource = SgtNebulaSource.None;
[Tooltip("The size of the generated nebula")]
public Vector3 Size = new Vector3(1.0f, 1.0f, 1.0f);
[Tooltip("The brightness of the nebula when viewed from the side (good for galaxies)")]
public float HorizontalBrightness = 0.25f;
[Tooltip("The relationship between the Brightness and HorizontalBrightness relative to the viweing angle")]
public float HorizontalPower = 1.0f;
[Tooltip("The amount of stars that will be generated in the starfield")]
public int StarCount = 1000;
[Tooltip("The minimum radius of stars in the starfield")]
public float StarRadiusMin = 0.0f;
[Tooltip("The maximum radius of stars in the starfield")]
public float StarRadiusMax = 0.05f;
[Tooltip("The maximum amount a star's size can pulse over time. A value of 1 means the star can potentially pulse between its maximum size, and 0")]
[Range(0.0f, 1.0f)]
public float StarPulseMax = 1.0f;
// Temp vars used during generation
private static Texture2D sourceTex2D;
private static Vector3 halfSize;
public static SgtNebulaStarfield CreateNebulaStarfield(int layer = 0, Transform parent = null)
{
return CreateNebulaStarfield(layer, parent, Vector3.zero, Quaternion.identity, Vector3.one);
}
public static SgtNebulaStarfield CreateNebulaStarfield(int layer, Transform parent, Vector3 localPosition, Quaternion localRotation, Vector3 localScale)
{
var gameObject = SgtHelper.CreateGameObject("Nebula Starfield", layer, parent, localPosition, localRotation, localScale);
var starfield = gameObject.AddComponent<SgtNebulaStarfield>();
return starfield;
}
#if UNITY_EDITOR
[MenuItem(SgtHelper.GameObjectMenuPrefix + "Nebula Starfield", false, 10)]
private static void CreateNebulaStarfieldMenuItem()
{
var parent = SgtHelper.GetSelectedParent();
var starfield = CreateNebulaStarfield(parent != null ? parent.gameObject.layer : 0, parent);
SgtHelper.SelectAndPing(starfield);
}
#endif
#if UNITY_EDITOR
protected override void OnDrawGizmosSelected()
{
base.OnDrawGizmosSelected();
Gizmos.matrix = transform.localToWorldMatrix;
Gizmos.DrawWireCube(Vector3.zero, Size);
}
#endif
protected override int BeginQuads()
{
SgtHelper.BeginRandomSeed(Seed);
sourceTex2D = SourceTex as Texture2D;
if (sourceTex2D != null && Samples > 0)
{
#if UNITY_EDITOR
SgtHelper.MakeTextureReadable(sourceTex2D);
SgtHelper.MakeTextureTruecolor(sourceTex2D);
#endif
halfSize = Size * 0.5f;
return StarCount;
}
return 0;
}
protected override void NextQuad(ref SgtPointStar quad, int starIndex)
{
for (var i = Samples - 1; i >= 0; i--)
{
var sampleX = Random.Range(0.0f, 1.0f);
var sampleY = Random.Range(0.0f, 1.0f);
var pixel = sourceTex2D.GetPixelBilinear(sampleX, sampleY);
var gray = pixel.grayscale;
if (gray > Threshold || i == 0)
{
var position = -halfSize + Random.insideUnitSphere * Jitter * StarRadiusMax;
position.x += Size.x * sampleX;
position.y += Size.y * GetWeight(HeightSource, pixel, 0.5f);
position.z += Size.z * sampleY;
quad.Variant = Random.Range(int.MinValue, int.MaxValue);
quad.Color = pixel;
quad.Radius = Random.Range(StarRadiusMin, StarRadiusMax) * GetWeight(ScaleSource, pixel, 1.0f);
quad.Angle = Random.Range(-180.0f, 180.0f);
quad.Position = position;
quad.PulseRange = Random.value * StarPulseMax;
quad.PulseSpeed = Random.value;
quad.PulseOffset = Random.value;
return;
}
}
}
protected override void EndQuads()
{
SgtHelper.EndRandomSeed();
}
protected override void CameraPreCull(Camera camera)
{
base.CameraPreCull(camera);
// Change brightness based on viewing angle?
if (Material != null)
{
var dir = (transform.position - camera.transform.position).normalized;
var theta = Mathf.Abs(Vector3.Dot(transform.up, dir));
var bright = Mathf.Lerp(HorizontalBrightness, Brightness, Mathf.Pow(theta, HorizontalPower));
var color = SgtHelper.Brighten(Color, Color.a * bright);
Material.SetColor("_Color", color);
}
}
private float GetWeight(SgtNebulaSource source, Color pixel, float defaultWeight)
{
switch (source)
{
case SgtNebulaSource.Red: return pixel.r;
case SgtNebulaSource.Green: return pixel.g;
case SgtNebulaSource.Blue: return pixel.b;
case SgtNebulaSource.Alpha: return pixel.a;
case SgtNebulaSource.AverageRgb: return (pixel.r + pixel.g + pixel.b) / 3.0f;
case SgtNebulaSource.MinRgb: return Mathf.Min(pixel.r, Mathf.Min(pixel.g, pixel.b));
case SgtNebulaSource.MaxRgb: return Mathf.Max(pixel.r, Mathf.Max(pixel.g, pixel.b));
}
return defaultWeight;
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Reflection;
using Microsoft.FSharp.Core.CompilerServices;
namespace TypeProviderInCSharp
{
public class ArtificialType : Type
{
string _Namespace;
string _Name;
bool _IsGenericType;
bool _IsValueType; // value type = not class / not interface
bool _IsByRef; // is the value passed by reference?
bool _IsEnum;
bool _IsPointer;
Type _BaseType;
MethodInfo _Method1;
PropertyInfo _Property1;
EventInfo _Event1;
FieldInfo _Field1;
ConstructorInfo _Ctor1;
public ArtificialType(string @namespace, string name, bool isGenericType, Type basetype, bool isValueType, bool isByRef, bool isEnum, bool IsPointer)
{
_Name = name;
_Namespace = @namespace;
_IsGenericType = isGenericType;
_BaseType = basetype;
_IsValueType = isValueType;
_IsByRef = isByRef;
_IsEnum = isEnum;
_IsPointer = IsPointer;
_Method1 = new ArtificialMethodInfo("M", this, typeof(int[]), MethodAttributes.Public | MethodAttributes.Static);
_Property1 = new ArtificialPropertyInfo("StaticProp", this, typeof(decimal), true, false);
_Event1 = new ArtificalEventInfo("Event1", this, typeof(EventHandler));
_Ctor1 = new ArtificialConstructorInfo(this, new ParameterInfo[] {} ); // parameter-less ctor
}
public override System.Reflection.Assembly Assembly
{
get
{
return Assembly.GetExecutingAssembly();
}
}
public override string Name
{
get
{
return _Name;
}
}
public override Type BaseType
{
get
{
return _BaseType;
}
}
public override string Namespace
{
get
{
return _Namespace;
}
}
public override string FullName
{
get
{
return string.Format("{0}.{1}", _Namespace, _Name);
}
}
public override object[] GetCustomAttributes(Type attributeType, bool inherit)
{
Debug.Assert(false, "Why are we calling into GetCustomAttributes()?");
return null;
}
public override object[] GetCustomAttributes(bool inherit)
{
Debug.Assert(false, "Why are we calling into GetCustomAttributes()?");
return null;
}
// TODO: what is this?
protected override System.Reflection.TypeAttributes GetAttributeFlagsImpl()
{
return TypeAttributes.Class | TypeAttributes.Public | (TypeAttributes)0x40000000; // add the special flag to indicate an erased type, see TypeProviderTypeAttributes
}
// This one seems to be invoked when in IDE, I type something like:
// let _ = typeof<N.
// In this case => no constructors
public override System.Reflection.ConstructorInfo[] GetConstructors(System.Reflection.BindingFlags bindingAttr)
{
// According to the spec, we should only expect these 4, so we guard against that here!
Debug.Assert(bindingAttr == (BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly), "bindingAttr has value not according to the spec!");
if (_Ctor1!=null)
return new System.Reflection.ConstructorInfo[] { _Ctor1 };
else
return new System.Reflection.ConstructorInfo[] { };
}
// When you start typing more interesting things like...
// let a = N.T.M()
// this one gets invoked...
public override System.Reflection.MethodInfo[] GetMethods(System.Reflection.BindingFlags bindingAttr)
{
// According to the spec, we should only expect these 4, so we guard against that here!
Debug.Assert(bindingAttr == (BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly), "bindingAttr has value not according to the spec!");
return new[] { _Method1 };
}
// This method is called when in the source file we have something like:
// - N.T.StaticProp
// (most likely also when we have an instance prop...)
// name -> "StaticProp"
protected override System.Reflection.PropertyInfo GetPropertyImpl(string name, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, Type returnType, Type[] types, System.Reflection.ParameterModifier[] modifiers)
{
// According to the spec, we should only expect these 4, so we guard against that here!
Debug.Assert(bindingAttr == (BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly), "bindingAttr has value not according to the spec!");
Debug.Assert(binder == null && returnType == null && types == null && modifiers == null, "One of binder, returnType, types, or modifiers was not null");
if (name == _Property1.Name)
return _Property1;
else
return null;
}
// Advertise our property...
// I think that is this one returns an empty array => you don't get intellisense/autocomplete in IDE/FSI
public override System.Reflection.PropertyInfo[] GetProperties(System.Reflection.BindingFlags bindingAttr)
{
// According to the spec, we should only expect these 4, so we guard against that here!
Debug.Assert(bindingAttr == (BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly), "bindingAttr has value not according to the spec!");
return new PropertyInfo[] { _Property1 };
}
// No fields...
public override System.Reflection.FieldInfo GetField(string name, System.Reflection.BindingFlags bindingAttr)
{
// According to the spec, we should only expect these 4, so we guard against that here!
Debug.Assert(bindingAttr == (BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly), "bindingAttr has value not according to the spec!");
return null;
}
public override System.Reflection.FieldInfo[] GetFields(System.Reflection.BindingFlags bindingAttr)
{
// According to the spec, we should only expect these 4, so we guard against that here!
Debug.Assert(bindingAttr == (BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly), "bindingAttr has value not according to the spec!");
return new System.Reflection.FieldInfo[] { };
}
// Events
public override System.Reflection.EventInfo GetEvent(string name, System.Reflection.BindingFlags bindingAttr)
{
// According to the spec, we should only expect these 4, so we guard against that here!
Debug.Assert(bindingAttr == (BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly), "bindingAttr has value not according to the spec!");
if (_Event1 != null && _Event1.Name == name)
return _Event1;
else
return null;
}
// Events...
public override System.Reflection.EventInfo[] GetEvents(System.Reflection.BindingFlags bindingAttr)
{
return _Event1 != null ? new [] { _Event1 } : new System.Reflection.EventInfo[] { };
}
// TODO: according to the spec, this should not be invoked... instead it seems like it may be invoked...
// ?? I have no idea what this is used for... ??
public override Type UnderlyingSystemType
{
get
{
return null;
}
}
// According to the spec, this should always be 'false'
protected override bool IsArrayImpl()
{
return false;
}
// No interfaces...
public override Type[] GetInterfaces()
{
return new Type[] { };
}
// No nested type
// This method is invoked on the type 'T', e.g.:
// let _ = N.T.M
// to figure out if M is a nested type.
public override Type GetNestedType(string name, System.Reflection.BindingFlags bindingAttr)
{
return null;
}
public override Type[] GetNestedTypes(System.Reflection.BindingFlags bindingAttr)
{
// According to the spec, we should only expect these 4, so we guard against that here!
Debug.Assert(bindingAttr == (BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly), "bindingAttr has value not according to the spec!");
return new Type[] { };
}
// This one is invoked when the type has a .ctor
// and the code looks like
// let _ = new N.T()
// for example.
// It was observed that the
// TODO: cover both cases!
public override bool IsGenericType
{
get
{
return _IsGenericType;
}
}
// This is invoked if the IsGenericType is true
public override Type[] GetGenericArguments()
{
if (_IsGenericType)
return new Type[] { typeof(int), typeof(decimal), typeof(System.Guid) }; // This is currently triggering an ICE...
else
{
Debug.Assert(false, "Why are we here?");
throw new NotImplementedException();
}
}
// This one seems to be invoked when compiling something like
// let a = new N.T()
// Let's just stay away from generics...
public override bool IsGenericTypeDefinition
{
get
{
return _IsGenericType;
}
}
// This one seems to be invoked when compiling something like
// let a = new N.T()
// Let's just stay away from generics...
public override bool ContainsGenericParameters
{
get
{
return _IsGenericType;
}
}
// This one seems to be checked when in IDE.
// let b = N.T(
protected override bool IsValueTypeImpl()
{
return _IsValueType;
}
// This one seems to be checked when in IDE.
// let b = N.T(
protected override bool IsByRefImpl()
{
return _IsByRef;
}
// This one seems to be checked when in IDE.
// let b = N.T(
public override bool IsEnum
{
get
{
return _IsEnum;
}
}
// This one seems to be checked when in IDE.
// let b = N.T(
protected override bool IsPointerImpl()
{
return _IsPointer;
}
public override string AssemblyQualifiedName
{
get
{
Debug.Assert(false, "NYI");
throw new NotImplementedException();
}
}
public override Guid GUID
{
get
{
Debug.Assert(false, "NYI");
throw new NotImplementedException();
}
}
protected override System.Reflection.ConstructorInfo GetConstructorImpl(System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, System.Reflection.CallingConventions callConvention, Type[] types, System.Reflection.ParameterModifier[] modifiers)
{
Debug.Assert(false, "NYI");
throw new NotImplementedException();
}
public override Type GetElementType()
{
Debug.Assert(false, "NYI");
throw new NotImplementedException();
}
public override Type GetInterface(string name, bool ignoreCase)
{
Debug.Assert(false, "NYI");
throw new NotImplementedException();
}
public override System.Reflection.MemberInfo[] GetMembers(System.Reflection.BindingFlags bindingAttr)
{
Debug.Assert(false, "NYI");
throw new NotImplementedException();
}
protected override System.Reflection.MethodInfo GetMethodImpl(string name, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, System.Reflection.CallingConventions callConvention, Type[] types, System.Reflection.ParameterModifier[] modifiers)
{
Debug.Assert(false, "NYI");
throw new NotImplementedException();
}
protected override bool HasElementTypeImpl()
{
Debug.Assert(false, "NYI");
throw new NotImplementedException();
}
public override object InvokeMember(string name, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, object target, object[] args, System.Reflection.ParameterModifier[] modifiers, System.Globalization.CultureInfo culture, string[] namedParameters)
{
Debug.Assert(false, "NYI");
throw new NotImplementedException();
}
protected override bool IsCOMObjectImpl()
{
Debug.Assert(false, "NYI");
throw new NotImplementedException();
}
protected override bool IsPrimitiveImpl()
{
Debug.Assert(false, "NYI");
throw new NotImplementedException();
}
public override System.Reflection.Module Module
{
get {
Debug.Assert(false, "NYI");
throw new NotImplementedException();
}
}
public override bool IsDefined(Type attributeType, bool inherit)
{
Debug.Assert(false, "NYI");
throw new NotImplementedException();
}
public override MethodBase DeclaringMethod
{
get
{
Debug.Assert(false, "NYI");
return base.DeclaringMethod;
}
}
// This one is invoked by the F# compiler!
public override Type DeclaringType
{
get
{
return null; // base.DeclaringType;
}
}
public override Type[] FindInterfaces(TypeFilter filter, object filterCriteria)
{
Debug.Assert(false, "NYI");
return base.FindInterfaces(filter, filterCriteria);
}
public override MemberInfo[] FindMembers(MemberTypes memberType, BindingFlags bindingAttr, MemberFilter filter, object filterCriteria)
{
Debug.Assert(false, "NYI");
return base.FindMembers(memberType, bindingAttr, filter, filterCriteria);
}
public override GenericParameterAttributes GenericParameterAttributes
{
get
{
Debug.Assert(false, "NYI");
return base.GenericParameterAttributes;
}
}
public override int GenericParameterPosition
{
get
{
Debug.Assert(false, "NYI");
return base.GenericParameterPosition;
}
}
public override int GetArrayRank()
{
Debug.Assert(false, "NYI");
return base.GetArrayRank();
}
public override MemberInfo[] GetDefaultMembers()
{
Debug.Assert(false, "NYI");
return base.GetDefaultMembers();
}
public override string GetEnumName(object value)
{
Debug.Assert(false, "NYI");
return base.GetEnumName(value);
}
public override string[] GetEnumNames()
{
Debug.Assert(false, "NYI");
return base.GetEnumNames();
}
public override Type GetEnumUnderlyingType()
{
Debug.Assert(false, "NYI");
return base.GetEnumUnderlyingType();
}
public override Array GetEnumValues()
{
Debug.Assert(false, "NYI");
return base.GetEnumValues();
}
public override EventInfo[] GetEvents()
{
Debug.Assert(false, "NYI");
return base.GetEvents();
}
public override Type[] GetGenericParameterConstraints()
{
Debug.Assert(false, "NYI");
return base.GetGenericParameterConstraints();
}
public override Type GetGenericTypeDefinition()
{
Debug.Assert(false, "NYI");
return base.GetGenericTypeDefinition();
}
public override InterfaceMapping GetInterfaceMap(Type interfaceType)
{
Debug.Assert(false, "NYI");
return base.GetInterfaceMap(interfaceType);
}
public override MemberInfo[] GetMember(string name, BindingFlags bindingAttr)
{
Debug.Assert(false, "NYI");
return base.GetMember(name, bindingAttr);
}
public override MemberInfo[] GetMember(string name, MemberTypes type, BindingFlags bindingAttr)
{
Debug.Assert(false, "NYI");
return base.GetMember(name, type, bindingAttr);
}
protected override TypeCode GetTypeCodeImpl()
{
Debug.Assert(false, "NYI");
return base.GetTypeCodeImpl();
}
public override bool IsAssignableFrom(Type c)
{
Debug.Assert(false, "NYI");
return base.IsAssignableFrom(c);
}
protected override bool IsContextfulImpl()
{
Debug.Assert(false, "NYI");
return base.IsContextfulImpl();
}
public override bool IsEnumDefined(object value)
{
Debug.Assert(false, "NYI");
return base.IsEnumDefined(value);
}
public override bool IsEquivalentTo(Type other)
{
Debug.Assert(false, "NYI");
return base.IsEquivalentTo(other);
}
public override bool IsGenericParameter
{
get
{
return _IsGenericType;
}
}
public override bool IsInstanceOfType(object o)
{
Debug.Assert(false, "NYI");
return base.IsInstanceOfType(o);
}
protected override bool IsMarshalByRefImpl()
{
Debug.Assert(false, "NYI");
return base.IsMarshalByRefImpl();
}
public override bool IsSecurityCritical
{
get
{
Debug.Assert(false, "NYI");
return base.IsSecurityCritical;
}
}
public override bool IsSecuritySafeCritical
{
get
{
Debug.Assert(false, "NYI");
return base.IsSecuritySafeCritical;
}
}
public override bool IsSecurityTransparent
{
get
{
Debug.Assert(false, "NYI");
return base.IsSecurityTransparent;
}
}
public override bool IsSerializable
{
get
{
Debug.Assert(false, "NYI");
return base.IsSerializable;
}
}
public override bool IsSubclassOf(Type c)
{
Debug.Assert(false, "NYI");
return base.IsSubclassOf(c);
}
public override Type MakeArrayType()
{
Debug.Assert(false, "NYI");
return base.MakeArrayType();
}
public override Type MakeArrayType(int rank)
{
Debug.Assert(false, "NYI");
return base.MakeArrayType(rank);
}
public override Type MakeByRefType()
{
return base.MakeByRefType();
}
public override Type MakeGenericType(params Type[] typeArguments)
{
Debug.Assert(false, "NYI");
return base.MakeGenericType(typeArguments);
}
public override Type MakePointerType()
{
Debug.Assert(false, "NYI");
return base.MakePointerType();
}
public override MemberTypes MemberType
{
get
{
Debug.Assert(false, "NYI");
return base.MemberType;
}
}
public override int MetadataToken
{
get
{
Debug.Assert(false, "NYI");
return base.MetadataToken;
}
}
public override Type ReflectedType
{
get
{
Debug.Assert(false, "NYI");
return base.ReflectedType;
}
}
public override System.Runtime.InteropServices.StructLayoutAttribute StructLayoutAttribute
{
get
{
Debug.Assert(false, "NYI");
return base.StructLayoutAttribute;
}
}
public override RuntimeTypeHandle TypeHandle
{
get
{
Debug.Assert(false, "NYI");
return base.TypeHandle;
}
}
public override string ToString()
{
Debug.Assert(false, "NYI");
return base.ToString();
}
public override IList<CustomAttributeData> GetCustomAttributesData()
{
var attrs = new List<CustomAttributeData>();
attrs.Add(new Helpers.TypeProviderCustomAttributeData(new TypeProviderXmlDocAttribute(null)));
attrs.Add(new Helpers.TypeProviderCustomAttributeData(new TypeProviderDefinitionLocationAttribute() { Column = 21, FilePath = "File.fs", Line = 3 }));
attrs.Add(new Helpers.TypeProviderCustomAttributeData(new TypeProviderEditorHideMethodsAttribute()));
return attrs;
}
}
}
| |
/*
* 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.Reflection;
using System.Text;
using System.Xml;
using System.Collections.Generic;
using System.IO;
using Nini.Config;
using OpenSim.Framework;
using OpenSim.Server.Base;
using OpenSim.Services.Interfaces;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Server.Handlers.Base;
using log4net;
using OpenMetaverse;
namespace OpenSim.Server.Handlers.Asset
{
public class XInventoryInConnector : ServiceConnector
{
private IInventoryService m_InventoryService;
private string m_ConfigName = "InventoryService";
public XInventoryInConnector(IConfigSource config, IHttpServer server, string configName) :
base(config, server, configName)
{
if (configName != String.Empty)
m_ConfigName = configName;
IConfig serverConfig = config.Configs[m_ConfigName];
if (serverConfig == null)
throw new Exception(String.Format("No section '{0}' in config file", m_ConfigName));
string inventoryService = serverConfig.GetString("LocalServiceModule",
String.Empty);
if (inventoryService == String.Empty)
throw new Exception("No InventoryService in config file");
Object[] args = new Object[] { config };
m_InventoryService =
ServerUtils.LoadPlugin<IInventoryService>(inventoryService, args);
server.AddStreamHandler(new XInventoryConnectorPostHandler(m_InventoryService));
}
}
public class XInventoryConnectorPostHandler : BaseStreamHandler
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private IInventoryService m_InventoryService;
public XInventoryConnectorPostHandler(IInventoryService service) :
base("POST", "/xinventory")
{
m_InventoryService = service;
}
public override byte[] Handle(string path, Stream requestData,
OSHttpRequest httpRequest, OSHttpResponse 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();
request.Remove("METHOD");
switch (method)
{
case "CREATEUSERINVENTORY":
return HandleCreateUserInventory(request);
case "GETINVENTORYSKELETON":
return HandleGetInventorySkeleton(request);
case "GETROOTFOLDER":
return HandleGetRootFolder(request);
case "GETFOLDERFORTYPE":
return HandleGetFolderForType(request);
case "GETFOLDERCONTENT":
return HandleGetFolderContent(request);
case "GETFOLDERITEMS":
return HandleGetFolderItems(request);
case "ADDFOLDER":
return HandleAddFolder(request);
case "UPDATEFOLDER":
return HandleUpdateFolder(request);
case "MOVEFOLDER":
return HandleMoveFolder(request);
case "DELETEFOLDERS":
return HandleDeleteFolders(request);
case "PURGEFOLDER":
return HandlePurgeFolder(request);
case "ADDITEM":
return HandleAddItem(request);
case "UPDATEITEM":
return HandleUpdateItem(request);
case "MOVEITEMS":
return HandleMoveItems(request);
case "DELETEITEMS":
return HandleDeleteItems(request);
case "GETITEM":
return HandleGetItem(request);
case "GETFOLDER":
return HandleGetFolder(request);
case "GETACTIVEGESTURES":
return HandleGetActiveGestures(request);
case "GETASSETPERMISSIONS":
return HandleGetAssetPermissions(request);
}
m_log.DebugFormat("[XINVENTORY HANDLER]: unknown method request: {0}", method);
}
catch (Exception e)
{
m_log.Debug("[XINVENTORY HANDLER]: Exception {0}" + e);
}
return FailureResult();
}
private byte[] FailureResult()
{
return BoolResult(false);
}
private byte[] SuccessResult()
{
return BoolResult(true);
}
private byte[] BoolResult(bool value)
{
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(value.ToString()));
rootElement.AppendChild(result);
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();
}
byte[] HandleCreateUserInventory(Dictionary<string,object> request)
{
Dictionary<string,object> result = new Dictionary<string,object>();
if (!request.ContainsKey("PRINCIPAL"))
return FailureResult();
if (m_InventoryService.CreateUserInventory(new UUID(request["PRINCIPAL"].ToString())))
result["RESULT"] = "True";
else
result["RESULT"] = "False";
string xmlString = ServerUtils.BuildXmlResponse(result);
//m_log.DebugFormat("[XXX]: resp string: {0}", xmlString);
UTF8Encoding encoding = new UTF8Encoding();
return encoding.GetBytes(xmlString);
}
byte[] HandleGetInventorySkeleton(Dictionary<string,object> request)
{
Dictionary<string,object> result = new Dictionary<string,object>();
if (!request.ContainsKey("PRINCIPAL"))
return FailureResult();
List<InventoryFolderBase> folders = m_InventoryService.GetInventorySkeleton(new UUID(request["PRINCIPAL"].ToString()));
Dictionary<string, object> sfolders = new Dictionary<string, object>();
if (folders != null)
{
int i = 0;
foreach (InventoryFolderBase f in folders)
{
sfolders["folder_" + i.ToString()] = EncodeFolder(f);
i++;
}
}
result["FOLDERS"] = sfolders;
string xmlString = ServerUtils.BuildXmlResponse(result);
//m_log.DebugFormat("[XXX]: resp string: {0}", xmlString);
UTF8Encoding encoding = new UTF8Encoding();
return encoding.GetBytes(xmlString);
}
byte[] HandleGetRootFolder(Dictionary<string,object> request)
{
Dictionary<string,object> result = new Dictionary<string,object>();
UUID principal = UUID.Zero;
UUID.TryParse(request["PRINCIPAL"].ToString(), out principal);
InventoryFolderBase rfolder = m_InventoryService.GetRootFolder(principal);
if (rfolder != null)
result["folder"] = EncodeFolder(rfolder);
string xmlString = ServerUtils.BuildXmlResponse(result);
//m_log.DebugFormat("[XXX]: resp string: {0}", xmlString);
UTF8Encoding encoding = new UTF8Encoding();
return encoding.GetBytes(xmlString);
}
byte[] HandleGetFolderForType(Dictionary<string,object> request)
{
Dictionary<string,object> result = new Dictionary<string,object>();
UUID principal = UUID.Zero;
UUID.TryParse(request["PRINCIPAL"].ToString(), out principal);
int type = 0;
Int32.TryParse(request["TYPE"].ToString(), out type);
InventoryFolderBase folder = m_InventoryService.GetFolderForType(principal, (AssetType)type);
if (folder != null)
result["folder"] = EncodeFolder(folder);
string xmlString = ServerUtils.BuildXmlResponse(result);
//m_log.DebugFormat("[XXX]: resp string: {0}", xmlString);
UTF8Encoding encoding = new UTF8Encoding();
return encoding.GetBytes(xmlString);
}
byte[] HandleGetFolderContent(Dictionary<string,object> request)
{
Dictionary<string,object> result = new Dictionary<string,object>();
UUID principal = UUID.Zero;
UUID.TryParse(request["PRINCIPAL"].ToString(), out principal);
UUID folderID = UUID.Zero;
UUID.TryParse(request["FOLDER"].ToString(), out folderID);
InventoryCollection icoll = m_InventoryService.GetFolderContent(principal, folderID);
if (icoll != null)
{
Dictionary<string, object> folders = new Dictionary<string, object>();
int i = 0;
foreach (InventoryFolderBase f in icoll.Folders)
{
folders["folder_" + i.ToString()] = EncodeFolder(f);
i++;
}
result["FOLDERS"] = folders;
i = 0;
Dictionary<string, object> items = new Dictionary<string, object>();
foreach (InventoryItemBase it in icoll.Items)
{
items["item_" + i.ToString()] = EncodeItem(it);
i++;
}
result["ITEMS"] = items;
}
string xmlString = ServerUtils.BuildXmlResponse(result);
//m_log.DebugFormat("[XXX]: resp string: {0}", xmlString);
UTF8Encoding encoding = new UTF8Encoding();
return encoding.GetBytes(xmlString);
}
byte[] HandleGetFolderItems(Dictionary<string,object> request)
{
Dictionary<string,object> result = new Dictionary<string,object>();
UUID principal = UUID.Zero;
UUID.TryParse(request["PRINCIPAL"].ToString(), out principal);
UUID folderID = UUID.Zero;
UUID.TryParse(request["FOLDER"].ToString(), out folderID);
List<InventoryItemBase> items = m_InventoryService.GetFolderItems(principal, folderID);
Dictionary<string, object> sitems = new Dictionary<string, object>();
if (items != null)
{
int i = 0;
foreach (InventoryItemBase item in items)
{
sitems["item_" + i.ToString()] = EncodeItem(item);
i++;
}
}
result["ITEMS"] = sitems;
string xmlString = ServerUtils.BuildXmlResponse(result);
//m_log.DebugFormat("[XXX]: resp string: {0}", xmlString);
UTF8Encoding encoding = new UTF8Encoding();
return encoding.GetBytes(xmlString);
}
byte[] HandleAddFolder(Dictionary<string,object> request)
{
Dictionary<string,object> result = new Dictionary<string,object>();
InventoryFolderBase folder = BuildFolder(request);
if (m_InventoryService.AddFolder(folder))
return SuccessResult();
else
return FailureResult();
}
byte[] HandleUpdateFolder(Dictionary<string,object> request)
{
Dictionary<string, object> result = new Dictionary<string, object>();
InventoryFolderBase folder = BuildFolder(request);
if (m_InventoryService.UpdateFolder(folder))
return SuccessResult();
else
return FailureResult();
}
byte[] HandleMoveFolder(Dictionary<string,object> request)
{
Dictionary<string, object> result = new Dictionary<string, object>();
UUID parentID = UUID.Zero;
UUID.TryParse(request["ParentID"].ToString(), out parentID);
UUID folderID = UUID.Zero;
UUID.TryParse(request["ID"].ToString(), out folderID);
UUID principal = UUID.Zero;
UUID.TryParse(request["PRINCIPAL"].ToString(), out principal);
InventoryFolderBase folder = new InventoryFolderBase(folderID, "", principal, parentID);
if (m_InventoryService.MoveFolder(folder))
return SuccessResult();
else
return FailureResult();
}
byte[] HandleDeleteFolders(Dictionary<string,object> request)
{
Dictionary<string,object> result = new Dictionary<string,object>();
UUID principal = UUID.Zero;
UUID.TryParse(request["PRINCIPAL"].ToString(), out principal);
List<string> slist = (List<string>)request["FOLDERS"];
List<UUID> uuids = new List<UUID>();
foreach (string s in slist)
{
UUID u = UUID.Zero;
if (UUID.TryParse(s, out u))
uuids.Add(u);
}
if (m_InventoryService.DeleteFolders(principal, uuids))
return SuccessResult();
else
return
FailureResult();
}
byte[] HandlePurgeFolder(Dictionary<string,object> request)
{
Dictionary<string,object> result = new Dictionary<string,object>();
UUID folderID = UUID.Zero;
UUID.TryParse(request["ID"].ToString(), out folderID);
InventoryFolderBase folder = new InventoryFolderBase(folderID);
if (m_InventoryService.PurgeFolder(folder))
return SuccessResult();
else
return FailureResult();
}
byte[] HandleAddItem(Dictionary<string,object> request)
{
Dictionary<string, object> result = new Dictionary<string, object>();
InventoryItemBase item = BuildItem(request);
if (m_InventoryService.AddItem(item))
return SuccessResult();
else
return FailureResult();
}
byte[] HandleUpdateItem(Dictionary<string,object> request)
{
Dictionary<string, object> result = new Dictionary<string, object>();
InventoryItemBase item = BuildItem(request);
if (m_InventoryService.UpdateItem(item))
return SuccessResult();
else
return FailureResult();
}
byte[] HandleMoveItems(Dictionary<string,object> request)
{
Dictionary<string,object> result = new Dictionary<string,object>();
List<string> idlist = (List<string>)request["IDLIST"];
List<string> destlist = (List<string>)request["DESTLIST"];
UUID principal = UUID.Zero;
UUID.TryParse(request["PRINCIPAL"].ToString(), out principal);
List<InventoryItemBase> items = new List<InventoryItemBase>();
int n = 0;
try
{
foreach (string s in idlist)
{
UUID u = UUID.Zero;
if (UUID.TryParse(s, out u))
{
UUID fid = UUID.Zero;
if (UUID.TryParse(destlist[n++], out fid))
{
InventoryItemBase item = new InventoryItemBase(u, principal);
item.Folder = fid;
items.Add(item);
}
}
}
}
catch (Exception e)
{
m_log.DebugFormat("[XINVENTORY IN CONNECTOR]: Exception in HandleMoveItems: {0}", e.Message);
return FailureResult();
}
if (m_InventoryService.MoveItems(principal, items))
return SuccessResult();
else
return FailureResult();
}
byte[] HandleDeleteItems(Dictionary<string,object> request)
{
Dictionary<string, object> result = new Dictionary<string, object>();
UUID principal = UUID.Zero;
UUID.TryParse(request["PRINCIPAL"].ToString(), out principal);
List<string> slist = (List<string>)request["ITEMS"];
List<UUID> uuids = new List<UUID>();
foreach (string s in slist)
{
UUID u = UUID.Zero;
if (UUID.TryParse(s, out u))
uuids.Add(u);
}
if (m_InventoryService.DeleteItems(principal, uuids))
return SuccessResult();
else
return
FailureResult();
}
byte[] HandleGetItem(Dictionary<string,object> request)
{
Dictionary<string,object> result = new Dictionary<string,object>();
UUID id = UUID.Zero;
UUID.TryParse(request["ID"].ToString(), out id);
InventoryItemBase item = new InventoryItemBase(id);
item = m_InventoryService.GetItem(item);
if (item != null)
result["item"] = EncodeItem(item);
string xmlString = ServerUtils.BuildXmlResponse(result);
//m_log.DebugFormat("[XXX]: resp string: {0}", xmlString);
UTF8Encoding encoding = new UTF8Encoding();
return encoding.GetBytes(xmlString);
}
byte[] HandleGetFolder(Dictionary<string,object> request)
{
Dictionary<string, object> result = new Dictionary<string, object>();
UUID id = UUID.Zero;
UUID.TryParse(request["ID"].ToString(), out id);
InventoryFolderBase folder = new InventoryFolderBase(id);
folder = m_InventoryService.GetFolder(folder);
if (folder != null)
result["folder"] = EncodeFolder(folder);
string xmlString = ServerUtils.BuildXmlResponse(result);
//m_log.DebugFormat("[XXX]: resp string: {0}", xmlString);
UTF8Encoding encoding = new UTF8Encoding();
return encoding.GetBytes(xmlString);
}
byte[] HandleGetActiveGestures(Dictionary<string,object> request)
{
Dictionary<string,object> result = new Dictionary<string,object>();
UUID principal = UUID.Zero;
UUID.TryParse(request["PRINCIPAL"].ToString(), out principal);
List<InventoryItemBase> gestures = m_InventoryService.GetActiveGestures(principal);
Dictionary<string, object> items = new Dictionary<string, object>();
if (gestures != null)
{
int i = 0;
foreach (InventoryItemBase item in gestures)
{
items["item_" + i.ToString()] = EncodeItem(item);
i++;
}
}
result["ITEMS"] = items;
string xmlString = ServerUtils.BuildXmlResponse(result);
//m_log.DebugFormat("[XXX]: resp string: {0}", xmlString);
UTF8Encoding encoding = new UTF8Encoding();
return encoding.GetBytes(xmlString);
}
byte[] HandleGetAssetPermissions(Dictionary<string,object> request)
{
Dictionary<string,object> result = new Dictionary<string,object>();
UUID principal = UUID.Zero;
UUID.TryParse(request["PRINCIPAL"].ToString(), out principal);
UUID assetID = UUID.Zero;
UUID.TryParse(request["ASSET"].ToString(), out assetID);
int perms = m_InventoryService.GetAssetPermissions(principal, assetID);
result["RESULT"] = perms.ToString();
string xmlString = ServerUtils.BuildXmlResponse(result);
//m_log.DebugFormat("[XXX]: resp string: {0}", xmlString);
UTF8Encoding encoding = new UTF8Encoding();
return encoding.GetBytes(xmlString);
}
private Dictionary<string, object> EncodeFolder(InventoryFolderBase f)
{
Dictionary<string, object> ret = new Dictionary<string, object>();
ret["ParentID"] = f.ParentID.ToString();
ret["Type"] = f.Type.ToString();
ret["Version"] = f.Version.ToString();
ret["Name"] = f.Name;
ret["Owner"] = f.Owner.ToString();
ret["ID"] = f.ID.ToString();
return ret;
}
private Dictionary<string, object> EncodeItem(InventoryItemBase item)
{
Dictionary<string, object> ret = new Dictionary<string, object>();
ret["AssetID"] = item.AssetID.ToString();
ret["AssetType"] = item.AssetType.ToString();
ret["BasePermissions"] = item.BasePermissions.ToString();
ret["CreationDate"] = item.CreationDate.ToString();
ret["CreatorId"] = item.CreatorId.ToString();
ret["CurrentPermissions"] = item.CurrentPermissions.ToString();
ret["Description"] = item.Description.ToString();
ret["EveryOnePermissions"] = item.EveryOnePermissions.ToString();
ret["Flags"] = item.Flags.ToString();
ret["Folder"] = item.Folder.ToString();
ret["GroupID"] = item.GroupID.ToString();
ret["GroupOwned"] = item.GroupOwned.ToString();
ret["GroupPermissions"] = item.GroupPermissions.ToString();
ret["ID"] = item.ID.ToString();
ret["InvType"] = item.InvType.ToString();
ret["Name"] = item.Name.ToString();
ret["NextPermissions"] = item.NextPermissions.ToString();
ret["Owner"] = item.Owner.ToString();
ret["SalePrice"] = item.SalePrice.ToString();
ret["SaleType"] = item.SaleType.ToString();
return ret;
}
private InventoryFolderBase BuildFolder(Dictionary<string,object> data)
{
InventoryFolderBase folder = new InventoryFolderBase();
folder.ParentID = new UUID(data["ParentID"].ToString());
folder.Type = short.Parse(data["Type"].ToString());
folder.Version = ushort.Parse(data["Version"].ToString());
folder.Name = data["Name"].ToString();
folder.Owner = new UUID(data["Owner"].ToString());
folder.ID = new UUID(data["ID"].ToString());
return folder;
}
private InventoryItemBase BuildItem(Dictionary<string,object> data)
{
InventoryItemBase item = new InventoryItemBase();
item.AssetID = new UUID(data["AssetID"].ToString());
item.AssetType = int.Parse(data["AssetType"].ToString());
item.Name = data["Name"].ToString();
item.Owner = new UUID(data["Owner"].ToString());
item.ID = new UUID(data["ID"].ToString());
item.InvType = int.Parse(data["InvType"].ToString());
item.Folder = new UUID(data["Folder"].ToString());
item.CreatorId = data["CreatorId"].ToString();
item.Description = data["Description"].ToString();
item.NextPermissions = uint.Parse(data["NextPermissions"].ToString());
item.CurrentPermissions = uint.Parse(data["CurrentPermissions"].ToString());
item.BasePermissions = uint.Parse(data["BasePermissions"].ToString());
item.EveryOnePermissions = uint.Parse(data["EveryOnePermissions"].ToString());
item.GroupPermissions = uint.Parse(data["GroupPermissions"].ToString());
item.GroupID = new UUID(data["GroupID"].ToString());
item.GroupOwned = bool.Parse(data["GroupOwned"].ToString());
item.SalePrice = int.Parse(data["SalePrice"].ToString());
item.SaleType = byte.Parse(data["SaleType"].ToString());
item.Flags = uint.Parse(data["Flags"].ToString());
item.CreationDate = int.Parse(data["CreationDate"].ToString());
return item;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Sql
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// ElasticPoolsOperations operations.
/// </summary>
internal partial class ElasticPoolsOperations : IServiceOperations<SqlManagementClient>, IElasticPoolsOperations
{
/// <summary>
/// Initializes a new instance of the ElasticPoolsOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal ElasticPoolsOperations(SqlManagementClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the SqlManagementClient
/// </summary>
public SqlManagementClient Client { get; private set; }
/// <summary>
/// Returns elastic pool metrics.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='elasticPoolName'>
/// The name of the elastic pool.
/// </param>
/// <param name='filter'>
/// An OData filter expression that describes a subset of metrics to return.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IEnumerable<Metric>>> ListMetricsWithHttpMessagesAsync(string resourceGroupName, string serverName, string elasticPoolName, string filter, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (serverName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "serverName");
}
if (elasticPoolName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "elasticPoolName");
}
if (filter == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "filter");
}
string apiVersion = "2014-04-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serverName", serverName);
tracingParameters.Add("elasticPoolName", elasticPoolName);
tracingParameters.Add("filter", filter);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListMetrics", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/elasticPools/{elasticPoolName}/metrics").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{serverName}", System.Uri.EscapeDataString(serverName));
_url = _url.Replace("{elasticPoolName}", System.Uri.EscapeDataString(elasticPoolName));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (filter != null)
{
_queryParameters.Add(string.Format("$filter={0}", System.Uri.EscapeDataString(filter)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IEnumerable<Metric>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<Metric>>(_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>
/// Returns elastic pool metric definitions.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='elasticPoolName'>
/// The name of the elastic pool.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IEnumerable<MetricDefinition>>> ListMetricDefinitionsWithHttpMessagesAsync(string resourceGroupName, string serverName, string elasticPoolName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (serverName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "serverName");
}
if (elasticPoolName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "elasticPoolName");
}
string apiVersion = "2014-04-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serverName", serverName);
tracingParameters.Add("elasticPoolName", elasticPoolName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListMetricDefinitions", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/elasticPools/{elasticPoolName}/metricDefinitions").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{serverName}", System.Uri.EscapeDataString(serverName));
_url = _url.Replace("{elasticPoolName}", System.Uri.EscapeDataString(elasticPoolName));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IEnumerable<MetricDefinition>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<MetricDefinition>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Creates a new elastic pool or updates an existing elastic pool.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='elasticPoolName'>
/// The name of the elastic pool to be operated on (updated or created).
/// </param>
/// <param name='parameters'>
/// The required parameters for creating or updating an elastic pool.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse<ElasticPool>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string serverName, string elasticPoolName, ElasticPool parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send Request
AzureOperationResponse<ElasticPool> _response = await BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, serverName, elasticPoolName, parameters, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Updates an existing elastic pool.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='elasticPoolName'>
/// The name of the elastic pool to be updated.
/// </param>
/// <param name='parameters'>
/// The required parameters for updating an elastic pool.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse<ElasticPool>> UpdateWithHttpMessagesAsync(string resourceGroupName, string serverName, string elasticPoolName, ElasticPoolUpdate parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send Request
AzureOperationResponse<ElasticPool> _response = await BeginUpdateWithHttpMessagesAsync(resourceGroupName, serverName, elasticPoolName, parameters, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Deletes the elastic pool.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='elasticPoolName'>
/// The name of the elastic pool to be deleted.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string serverName, string elasticPoolName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (serverName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "serverName");
}
if (elasticPoolName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "elasticPoolName");
}
string apiVersion = "2014-04-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serverName", serverName);
tracingParameters.Add("elasticPoolName", elasticPoolName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Delete", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/elasticPools/{elasticPoolName}").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{serverName}", System.Uri.EscapeDataString(serverName));
_url = _url.Replace("{elasticPoolName}", System.Uri.EscapeDataString(elasticPoolName));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("DELETE");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 204)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets an elastic pool.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='elasticPoolName'>
/// The name of the elastic pool to be retrieved.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<ElasticPool>> GetWithHttpMessagesAsync(string resourceGroupName, string serverName, string elasticPoolName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (serverName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "serverName");
}
if (elasticPoolName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "elasticPoolName");
}
string apiVersion = "2014-04-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serverName", serverName);
tracingParameters.Add("elasticPoolName", elasticPoolName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/elasticPools/{elasticPoolName}").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{serverName}", System.Uri.EscapeDataString(serverName));
_url = _url.Replace("{elasticPoolName}", System.Uri.EscapeDataString(elasticPoolName));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<ElasticPool>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<ElasticPool>(_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>
/// Returns a list of elastic pools in a server.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IEnumerable<ElasticPool>>> ListByServerWithHttpMessagesAsync(string resourceGroupName, string serverName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (serverName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "serverName");
}
string apiVersion = "2014-04-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serverName", serverName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListByServer", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/elasticPools").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{serverName}", System.Uri.EscapeDataString(serverName));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IEnumerable<ElasticPool>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<ElasticPool>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Creates a new elastic pool or updates an existing elastic pool.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='elasticPoolName'>
/// The name of the elastic pool to be operated on (updated or created).
/// </param>
/// <param name='parameters'>
/// The required parameters for creating or updating an elastic pool.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<ElasticPool>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string serverName, string elasticPoolName, ElasticPool parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (serverName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "serverName");
}
if (elasticPoolName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "elasticPoolName");
}
if (parameters == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "parameters");
}
if (parameters != null)
{
parameters.Validate();
}
string apiVersion = "2014-04-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serverName", serverName);
tracingParameters.Add("elasticPoolName", elasticPoolName);
tracingParameters.Add("parameters", parameters);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginCreateOrUpdate", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/elasticPools/{elasticPoolName}").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{serverName}", System.Uri.EscapeDataString(serverName));
_url = _url.Replace("{elasticPoolName}", System.Uri.EscapeDataString(elasticPoolName));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(parameters != null)
{
_requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 201 && (int)_statusCode != 202)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<ElasticPool>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<ElasticPool>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
// Deserialize Response
if ((int)_statusCode == 201)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<ElasticPool>(_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>
/// Updates an existing elastic pool.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='elasticPoolName'>
/// The name of the elastic pool to be updated.
/// </param>
/// <param name='parameters'>
/// The required parameters for updating an elastic pool.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<ElasticPool>> BeginUpdateWithHttpMessagesAsync(string resourceGroupName, string serverName, string elasticPoolName, ElasticPoolUpdate parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (serverName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "serverName");
}
if (elasticPoolName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "elasticPoolName");
}
if (parameters == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "parameters");
}
string apiVersion = "2014-04-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serverName", serverName);
tracingParameters.Add("elasticPoolName", elasticPoolName);
tracingParameters.Add("parameters", parameters);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginUpdate", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/elasticPools/{elasticPoolName}").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{serverName}", System.Uri.EscapeDataString(serverName));
_url = _url.Replace("{elasticPoolName}", System.Uri.EscapeDataString(elasticPoolName));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PATCH");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(parameters != null)
{
_requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 202)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<ElasticPool>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<ElasticPool>(_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;
}
}
}
| |
#region License
/*
* Copyright 2002-2010 the original author or 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.
*/
#endregion
#region Imports
using System;
using NUnit.Framework;
using Spring.Context;
using Spring.Core.IO;
using Spring.Expressions;
using Spring.Objects.Factory.Config;
using Spring.Objects.Factory.Support;
using Spring.Objects.Factory.Xml;
using Spring.Threading;
using System.Threading;
using System.Diagnostics;
using System.Collections;
#endregion
namespace Spring.Objects.Factory
{
/// <summary>
/// Subclasses must override SetUp () to initialize the object factory
/// and any other variables they need.
/// </summary>
/// <author>Rod Johnson</author>
/// <author>Rick Evans (.NET)</author>
public abstract class AbstractObjectFactoryTests
{
#region Properties
protected internal abstract AbstractObjectFactory CreateObjectFactory(bool caseSensitive);
private AbstractObjectFactory cachedFactory;
protected AbstractObjectFactory ObjectFactory
{
get { return cachedFactory; }
set { cachedFactory = value; }
}
#endregion
#region Case Insensitive Tests
[Test]
public void RespectsCaseInsensitiveNamesAndAliases()
{
AbstractObjectFactory of = CreateObjectFactory(false);
object testObject = new object();
of.RegisterSingleton("name", testObject);
of.RegisterAlias("NAME", "alias");
try
{
of.RegisterAlias("NaMe", "AlIaS");
Assert.Fail();
}
catch (ObjectDefinitionStoreException ex)
{
Assert.IsTrue(-1 < ex.Message.IndexOf("already registered"));
}
Assert.AreEqual(1, of.GetAliases("nAmE").Count);
Assert.AreEqual(testObject, of.GetObject("nAmE"));
Assert.AreEqual(testObject, of.GetObject("ALIAS"));
}
#endregion
/// <summary>
/// Roderick objects inherits from rod, overriding name only.
/// </summary>
[Test]
public void Inheritance()
{
Assert.IsTrue(ObjectFactory.ContainsObject("rod"));
Assert.IsTrue(ObjectFactory.ContainsObject("roderick"));
TestObject rod = (TestObject)ObjectFactory["rod"];
TestObject roderick = (TestObject)ObjectFactory["roderick"];
Assert.IsTrue(rod != roderick, "not == ");
Assert.IsTrue(rod.Name.Equals("Rod"), "rod.name is Rod");
Assert.IsTrue(rod.Age == 31, "rod.age is 31");
Assert.IsTrue(roderick.Name.Equals("Roderick"), "roderick.name is Roderick");
Assert.IsTrue(roderick.Age == rod.Age, "roderick.age was inherited");
}
[Test]
[ExpectedException(typeof(ArgumentNullException))]
public virtual void GetObjectWithNullName()
{
ObjectFactory.GetObject(null);
}
/// <summary>
/// Test that InitializingObject objects receive the AfterPropertiesSet () callback.
/// </summary>
[Test]
public void InitializingObjectCallback()
{
MustBeInitialized mbi =
(MustBeInitialized)ObjectFactory["mustBeInitialized"];
// The dummy business method will throw an exception if the
// AfterPropertiesSet () callback wasn't invoked
mbi.BusinessMethod();
}
/// <summary>
/// Test that InitializingObject/ObjectFactoryAware/DisposableObject objects
/// receive the AfterPropertiesSet () callback before ObjectFactoryAware
/// callbacks.
/// </summary>
[Test]
public void LifecycleCallbacks()
{
LifecycleObject lb = (LifecycleObject)ObjectFactory.GetObject("lifecycle");
Assert.AreEqual("lifecycle", lb.ObjectName);
// The dummy business method will throw an exception if the
// necessary callbacks weren't invoked in the right order
lb.BusinessMethod();
Assert.IsFalse(lb.Destroyed, "Was destroyed");
}
[Test(Description = "SPRNET-1208")]
public void AddObjectFactoryOnObjectFactoryAwareObjectPostProcessors()
{
AbstractObjectFactory aof = ObjectFactory;
LifecycleObject.PostProcessor lb = new LifecycleObject.PostProcessor();
aof.AddObjectPostProcessor(lb);
Assert.AreSame(aof, lb.ObjectFactory);
}
[Test]
public void FindsValidInstance()
{
object o = ObjectFactory.GetObject("rod");
Assert.IsTrue(o is TestObject, "Rod object is a TestObject");
TestObject rod = (TestObject)o;
Assert.IsTrue(rod.Name.Equals("Rod"), "rod.name is Rod");
Assert.IsTrue(rod.Age == 31, "rod.age is 31");
}
[Test]
public void GetInstanceByMatchingClass()
{
object o = ObjectFactory.GetObject("rod", typeof(TestObject));
Assert.IsTrue(o is TestObject, "Rod object is a TestObject");
}
[Test]
public void GetInstanceByNonmatchingClass()
{
try
{
ObjectFactory.GetObject("rod", typeof(IObjectFactory));
Assert.Fail("Rod object is not of type IObjectFactory; GetObjectInstance(rod, typeof (IObjectFactory)) should throw ObjectNotOfRequiredTypeException");
}
catch (ObjectNotOfRequiredTypeException ex)
{
Assert.IsTrue(ex.ObjectName.Equals("rod"), "Exception has correct object name");
Assert.IsTrue(ex.RequiredType.Equals(typeof(IObjectFactory)), "Exception requiredType must be ObjectFactory.class");
Assert.IsTrue(typeof(TestObject).IsAssignableFrom(ex.ActualType), "Exception actualType as TestObject.class");
Assert.IsTrue(ex.ActualInstance == ObjectFactory.GetObject("rod"), "Actual instance is correct");
}
}
[Test]
public virtual void GetSharedInstanceByMatchingClass()
{
object o = ObjectFactory.GetObject("rod", typeof(TestObject));
Assert.IsTrue(o is TestObject, "Rod object is a TestObject");
}
[Test]
public virtual void GetSharedInstanceByMatchingClassNoCatch()
{
object o = ObjectFactory.GetObject("rod", typeof(TestObject));
Assert.IsTrue(o is TestObject, "Rod object is a TestObject");
}
[Test]
public void GetSharedInstanceByNonmatchingClass()
{
try
{
ObjectFactory.GetObject("rod", typeof(IObjectFactory));
Assert.Fail("Rod object is not of type ObjectFactory; getObjectInstance(rod, ObjectFactory.class) should throw ObjectNotOfRequiredTypeException");
}
catch (ObjectNotOfRequiredTypeException ex)
{
// So far, so good
Assert.IsTrue(ex.ObjectName.Equals("rod"), "Exception has correct object name");
Assert.IsTrue(ex.RequiredType.Equals(typeof(IObjectFactory)), "Exception requiredType must be IObjectFactory class");
Assert.IsTrue(typeof(TestObject).IsAssignableFrom(ex.ActualType), "Exception actualType as TestObject class");
}
catch (Exception ex)
{
Assert.Fail("Shouldn't throw exception on getting valid instance with matching class : " + ex.Message);
}
}
[Test]
public virtual void SharedInstancesAreEqual()
{
try
{
object o = ObjectFactory.GetObject("rod");
Assert.IsTrue(o is TestObject, "Rod object1 is a TestObject");
object o1 = ObjectFactory.GetObject("rod");
Assert.IsTrue(o1 is TestObject, "Rod object2 is a TestObject");
Assert.IsTrue(o == o1, "Object equals applies");
}
catch
{
Assert.Fail("Shouldn't throw exception on getting valid instance");
}
}
[Test]
[ExpectedException(typeof(NoSuchObjectDefinitionException))]
public void NotThere()
{
Assert.IsFalse(ObjectFactory.ContainsObject("Mr Squiggle"));
ObjectFactory.GetObject("Mr Squiggle");
}
[Test]
public void ValidEmpty()
{
try
{
object o = ObjectFactory.GetObject("validEmpty");
Assert.IsTrue(o is TestObject, "validEmpty object is a TestObject");
TestObject ve = (TestObject)o;
Assert.IsTrue(ve.Name == null && ve.Age == 0 && ve.Spouse == null, "Valid empty has defaults");
}
catch
{
Assert.Fail("Shouldn't throw exception on valid empty");
}
}
[Test]
[ExpectedException(typeof(ArgumentNullException))]
public void RegisterNullCustomTypeConverter()
{
ObjectFactory.RegisterCustomConverter(null, null);
}
[Test]
public virtual void TypeMismatch()
{
try
{
ObjectFactory.GetObject("typeMismatch");
Assert.Fail("Shouldn't succeed with type mismatch");
}
catch (ObjectCreationException wex)
{
Assert.IsTrue(wex.InnerException is PropertyAccessExceptionsException);
PropertyAccessExceptionsException ex = (PropertyAccessExceptionsException)wex.InnerException;
// Furthers
Assert.IsTrue(ex.ExceptionCount == 1, "Has one error");
Assert.IsTrue(ex.GetPropertyAccessException("age") != null, "Error is for field age");
TestObject tb = (TestObject)ex.ObjectWrapper.WrappedInstance;
Assert.IsTrue(tb.Age == 0, "Age still has default");
Assert.IsTrue(ex.GetPropertyAccessException("age").PropertyChangeArgs.NewValue.Equals("34x"), "We have rejected age in exception");
Assert.IsTrue(tb.Name.Equals("typeMismatch"), "valid name stuck");
Assert.IsTrue(tb.Spouse.Name.Equals("Rod"), "valid spouse stuck");
}
}
[Test]
public virtual void GrandParentDefinitionFoundInObjectFactory()
{
TestObject dad = (TestObject)ObjectFactory.GetObject("father");
Assert.IsTrue(dad.Name.Equals("Albert"), "Dad has correct name");
}
[Test]
public virtual void GrandParentDefinitionFoundInObjectFactoryWithType()
{
TestObject dad = (TestObject)ObjectFactory.GetObject("typedfather", typeof(TestObject));
Assert.AreEqual(null, dad.Name, "Dad has not correct name");
}
[Test]
public virtual void GrandParentDefinitionFoundInObjectFactoryWithArguments()
{
TestObject dad = (TestObject)ObjectFactory.GetObject("namedfather", new object[] { "Hugo", 65 });
Assert.AreEqual("Hugo", dad.Name, "Dad has not correct name");
Assert.AreEqual(65, dad.Age, "Dad has not correct age");
}
[Test]
public virtual void GrandParentDefinitionFoundInObjectFactoryWithTypeAndArguments()
{
TestObject dad = (TestObject)ObjectFactory.GetObject("typedfather", typeof(TestObject), new object[] { "Chris", 66 });
Assert.AreEqual("Chris", dad.Name, "Dad has not correct name");
Assert.AreEqual(66, dad.Age, "Dad has not correct age");
}
[Test(Description = "Extra check that the type is really passed on to the parent factory")]
public virtual void GrandParentDefinitionFoundInObjectFactoryWithTypeAndArgumentsWithWrongType()
{
try
{
TestObject dad = (TestObject)ObjectFactory.GetObject("typedfather", typeof(string), new object[] { "Chris", 66 });
Assert.Fail("should throw ObjectNotOfRequiredTypeException");
}
catch (ObjectNotOfRequiredTypeException)
{
}
}
[Test]
public virtual void FactorySingleton()
{
Assert.IsTrue(ObjectFactory.IsSingleton("&singletonFactory"));
Assert.IsTrue(ObjectFactory.IsSingleton("singletonFactory"));
TestObject tb = (TestObject)ObjectFactory.GetObject("singletonFactory");
Assert.IsTrue(tb.Name.Equals(DummyFactory.SINGLETON_NAME), "Singleton from factory has correct name, not " + tb.Name);
DummyFactory factory = (DummyFactory)ObjectFactory.GetObject("&singletonFactory");
TestObject tb2 = (TestObject)ObjectFactory.GetObject("singletonFactory");
Assert.IsTrue(tb == tb2, "Singleton references ==");
Assert.IsTrue(factory.ObjectFactory != null, "FactoryObject is ObjectFactoryAware");
}
[Test]
public virtual void FactoryPrototype()
{
Assert.IsTrue(ObjectFactory.IsSingleton("&prototypeFactory"));
Assert.IsFalse(ObjectFactory.IsSingleton("prototypeFactory"));
TestObject tb = (TestObject)ObjectFactory.GetObject("prototypeFactory");
Assert.IsTrue(!tb.Name.Equals(DummyFactory.SINGLETON_NAME));
TestObject tb2 = (TestObject)ObjectFactory.GetObject("prototypeFactory");
Assert.IsTrue(tb != tb2, "Prototype references !=");
}
/// <summary>
/// Check that we can get the factory object itself.
/// This is only possible if we're dealing with a factory
/// </summary>
[Test]
public virtual void GetFactoryItself()
{
DummyFactory factory = (DummyFactory)ObjectFactory.GetObject("&singletonFactory");
Assert.IsTrue(factory != null);
}
/// <summary>Check that AfterPropertiesSet gets called on factory.</summary>
[Test]
public virtual void FactoryIsInitialized()
{
TestObject tb = (TestObject)ObjectFactory.GetObject("singletonFactory");
DummyFactory factory = (DummyFactory)ObjectFactory.GetObject("&singletonFactory");
Assert.IsTrue(factory.WasInitialized, "Factory was not initialized even though it implemented IInitializingObject");
}
/// <summary>
/// It should be illegal to dereference a normal object as a factory.
/// </summary>
[Test]
[ExpectedException(typeof(ObjectIsNotAFactoryException))]
public virtual void RejectsFactoryGetOnNormalObject()
{
ObjectFactory.GetObject("&rod");
}
[Test]
[ExpectedException(typeof(ObjectDefinitionStoreException))]
public virtual void Aliasing()
{
string alias = "rods alias";
try
{
ObjectFactory.GetObject(alias);
Assert.Fail("Shouldn't permit factory get on normal object");
}
catch (NoSuchObjectDefinitionException ex)
{
Assert.IsTrue(alias.Equals(ex.ObjectName));
}
// Create alias
ObjectFactory.RegisterAlias("rod", alias);
object rod = ObjectFactory.GetObject("rod");
object aliasRod = ObjectFactory.GetObject(alias);
Assert.IsTrue(rod == aliasRod);
ObjectFactory.RegisterAlias("father", alias);
}
[Test]
[ExpectedException(typeof(ArgumentNullException))]
public void RegisterSingletonWithEmptyName()
{
((AbstractObjectFactory)ObjectFactory)
.RegisterSingleton(Environment.NewLine, DBNull.Value);
}
[Test]
[ExpectedException(typeof(ArgumentNullException))]
public void RegisterSingletonWithNullName()
{
((AbstractObjectFactory)ObjectFactory)
.RegisterSingleton(null, DBNull.Value);
}
[Test]
public void GetSingletonNamesReflectsOrderOfRegistration()
{
AbstractObjectFactory of;
of = CreateObjectFactory(true);
of.RegisterSingleton("A", new object());
of.RegisterSingleton("C", new object());
of.RegisterSingleton("B", new object());
Assert.AreEqual(new string[] { "A", "C", "B" }, of.GetSingletonNames());
of = CreateObjectFactory(false);
of.RegisterSingleton("A", new object());
of.RegisterSingleton("C", new object());
of.RegisterSingleton("B", new object());
Assert.AreEqual(new string[] { "A", "C", "B" }, of.GetSingletonNames(typeof(object)));
}
[Test]
[ExpectedException(typeof(ArgumentNullException))]
public void ContainsSingletonWithEmptyName()
{
((AbstractObjectFactory)ObjectFactory)
.ContainsSingleton(Environment.NewLine);
}
[Test]
[ExpectedException(typeof(ArgumentNullException))]
public void ContainsSingletonWithNullName()
{
((AbstractObjectFactory)ObjectFactory)
.ContainsSingleton(null);
}
[Test]
[ExpectedException(typeof(ArgumentNullException))]
public void AliasWithEmptyName()
{
((AbstractObjectFactory)ObjectFactory).RegisterAlias(Environment.NewLine, "the whipping boy");
}
[Test]
[ExpectedException(typeof(ArgumentNullException))]
public void AliasWithEmptyAlias()
{
((AbstractObjectFactory)ObjectFactory).RegisterAlias("rick", Environment.NewLine);
}
// [Test]
// [ExpectedException(typeof(ObjectDefinitionStoreException))]
// public void ChokesIfNotGivenSupportedIObjectDefinitionImplementation()
// {
// ObjectFactory.GetObject("unsupportedDefinition");
// }
/// <summary>
/// This test resembles a scenario that may happen e.g. using ProxyFactoryObject proxying sibling objects with cyclic dependencies
/// </summary>
[Test]
public void CanResolveCyclicSingletonFactoryObjectProductDependencies()
{
AbstractObjectFactory of = this.CreateObjectFactory(true);
GenericObjectDefinition od = new GenericObjectDefinition();
od.ObjectTypeName = typeof(TestObject).FullName;
od.IsSingleton = true;
od.PropertyValues.Add(new PropertyValue("Spouse", new RuntimeObjectReference("product2")));
of.RegisterObjectDefinition("product1Target", od);
GenericObjectDefinition od2 = new GenericObjectDefinition();
od2.ObjectTypeName = typeof(TestObject).FullName;
od2.IsSingleton = true;
od2.PropertyValues.Add(new PropertyValue("Sibling", new RuntimeObjectReference("product1")));
of.RegisterObjectDefinition("product2Target", od2);
of.RegisterSingleton("product1", new ObjectReferenceFactoryObject("product1Target", of));
of.RegisterSingleton("product2", new ObjectReferenceFactoryObject("product2Target", of));
TestObject to = (TestObject)of.GetObject("product1");
Assert.NotNull(to);
Assert.NotNull(to.Spouse);
Assert.NotNull(((TestObject)to.Spouse).Sibling);
}
[Test]
public void ThrowsOnCyclicDependenciesOnNonSingletons()
{
AbstractObjectFactory of = this.CreateObjectFactory(true);
GenericObjectDefinition od = new GenericObjectDefinition();
od.ObjectTypeName = typeof(TestObject).FullName;
od.IsSingleton = false;
od.PropertyValues.Add(new PropertyValue("Spouse", new RuntimeObjectReference("product2")));
of.RegisterObjectDefinition("product1", od);
GenericObjectDefinition od2 = new GenericObjectDefinition();
od2.ObjectTypeName = typeof(TestObject).FullName;
od2.IsSingleton = false;
od2.PropertyValues.Add(new PropertyValue("Sibling", new RuntimeObjectReference("product1")));
of.RegisterObjectDefinition("product2", od2);
try
{
of.GetObject("product1");
Assert.Fail();
}
catch (ObjectCurrentlyInCreationException ex)
{
Assert.AreEqual("product1", ex.ObjectName);
}
}
private void GetTheTestObject()
{
if (DateTime.Now.Millisecond % 2 == 0)
{
ObjectFactory.GetObject("theObject");
}
else
{
ObjectFactory.GetObject("theSpouse");
}
}
[Test]
public void GetObjectIsThreadSafe()
{
ObjectFactory = CreateObjectFactory(true);
GenericObjectDefinition theSpouse = new GenericObjectDefinition();
theSpouse.ObjectTypeName = typeof(TestObject).FullName;
theSpouse.IsSingleton = false;
ObjectFactory.RegisterObjectDefinition("theSpouse", theSpouse);
GenericObjectDefinition theObject = new GenericObjectDefinition();
theObject.ObjectTypeName = typeof(TestObject).FullName;
theObject.IsSingleton = false;
theObject.PropertyValues.Add("Spouse", theSpouse);
ObjectFactory.RegisterObjectDefinition("theObject", theObject);
AsyncTestTask t1 = new AsyncTestMethod(20000, new ThreadStart(GetTheTestObject)).Start();
AsyncTestTask t2 = new AsyncTestMethod(20000, new ThreadStart(GetTheTestObject)).Start();
AsyncTestTask t3 = new AsyncTestMethod(20000, new ThreadStart(GetTheTestObject)).Start();
AsyncTestTask t4 = new AsyncTestMethod(20000, new ThreadStart(GetTheTestObject)).Start();
t1.AssertNoException();
t2.AssertNoException();
t3.AssertNoException();
t4.AssertNoException();
}
}
[TestFixture]
public class SPRNET_1334
{
public static AbstractObjectFactory CreateObjectFactory(bool caseSensitive)
{
return new DefaultListableObjectFactory(caseSensitive);
}
[Test]
public void CanDisposeFactoryWhenDependentObjectCallsFactoryInDispose()
{
AbstractObjectFactory factory = CreateObjectFactory(false);
ConfigureObjectFactory(factory as IObjectDefinitionRegistry);
ParentClass parent = (ParentClass)factory.GetObject("Parent");
Assert.That(parent, Is.Not.Null);
DisposableClass innerObject = (DisposableClass)parent.InnerObject;
innerObject.ObjectFactory = factory;
factory.Dispose();
Assert.Pass("Test concluded successfully.");
}
private void ConfigureObjectFactory(IObjectDefinitionRegistry factory)
{
XmlObjectDefinitionReader reader = new XmlObjectDefinitionReader(factory);
reader.LoadObjectDefinitions(new StringResource(@"<?xml version='1.0' encoding='UTF-8' ?>
<objects xmlns='http://www.springframework.net'
xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
xsi:schemaLocation='http://www.springframework.net http://www.springframework.net/xsd/spring-objects.xsd'>
<object id='Parent' type='Spring.Objects.Factory.SPRNET_1334+ParentClass, Spring.Core.Tests'>
<property name='Name' value='Foo!'/>
<property name='InnerObject'>
<object type='Spring.Objects.Factory.SPRNET_1334+DisposableClass, Spring.Core.Tests'/>
</property>
</object>
<!--
<object id='Parent' type='Spring.Objects.Factory.SPRNET_1334+ParentClass, Spring.Core.Tests'>
<property name='Name' value='Foo!'/>
<property name='InnerObject' ref='Inner'/>
</object>
<object id='Inner' type='Spring.Objects.Factory.SPRNET_1334+DisposableClass, Spring.Core.Tests'/>
-->
</objects>
"));
}
public class ParentClass
{
private string _name;
public string Name
{
get { return _name; }
set { _name = value; }
}
private IDisposable _innerObject;
public IDisposable InnerObject
{
get { return _innerObject; }
set { _innerObject = value; }
}
}
public class DisposableClass : IDisposable
{
private AbstractObjectFactory _objectFactory;
public AbstractObjectFactory ObjectFactory
{
get { return _objectFactory; }
set { _objectFactory = value; }
}
public void Dispose()
{
Console.WriteLine("DisposableClass.Dispose()");
if (ObjectFactory == null)
return;
object parent = ObjectFactory.GetObject("Parent");
if (parent == null)
Console.WriteLine("parent == null");
}
}
}
[TestFixture]
public class SPRNET_1338
{
private static AbstractObjectFactory _cachedFactory;
protected static AbstractObjectFactory ObjectFactory
{
get { return _cachedFactory; }
set { _cachedFactory = value; }
}
[SetUp]
public void _SetUp()
{
ObjectFactory = CreateObjectFactory(true);
GenericObjectDefinition threadCreatorInsideConstructor = new GenericObjectDefinition();
threadCreatorInsideConstructor.ObjectTypeName = typeof(ThreadCreatorInsideConstructor).FullName;
threadCreatorInsideConstructor.IsSingleton = true;
ObjectFactory.RegisterObjectDefinition("threadCreatorInsideConstructor", threadCreatorInsideConstructor);
GenericObjectDefinition threadCreatorInsideDispose = new GenericObjectDefinition();
threadCreatorInsideDispose.ObjectTypeName = typeof(ThreadCreatorInsideDispose).FullName;
threadCreatorInsideDispose.IsSingleton = true;
ObjectFactory.RegisterObjectDefinition("threadCreatorInsideDispose", threadCreatorInsideDispose);
}
[Test]
[Ignore("Test fails -- waiting for verification re: if bug exists in Java impl")]
public void CanAvoidLockContentionDuringObjectFactoryDisposal()
{
Thread t = new Thread(CreateThreadContentionFromDispose);
t.Start();
t.Join(20000);
if (t.ThreadState == System.Threading.ThreadState.WaitSleepJoin)
Assert.Fail("Lock Contention Blocked Successful Dispose of ObjectFactory!");
}
[Test]
public void CanAvoidLockContentionDuringObjectInstantiation()
{
Thread t = new Thread(CreateThreadContentionFromConstructor);
t.Start();
t.Join(20000);
if (t.ThreadState == System.Threading.ThreadState.WaitSleepJoin)
Assert.Fail("Lock Contention Blocked Successful Instantiation of Singleton Test Object!");
}
public static AbstractObjectFactory CreateObjectFactory(bool caseSensitive)
{
return new DefaultListableObjectFactory(caseSensitive);
}
private void CreateThreadContentionFromConstructor()
{
ObjectFactory.GetObject("threadCreatorInsideConstructor");
}
private void CreateThreadContentionFromDispose()
{
ObjectFactory.GetObject("threadCreatorInsideDispose");
ObjectFactory.Dispose();
}
internal class ThreadCreatorInsideDispose : IDisposable
{
public ThreadCreatorInsideDispose()
{
}
public void Dispose()
{
Thread t = new Thread(ConcurentThreadDisposeProc);
t.Start();
t.Join();
}
private static void ConcurentThreadDisposeProc()
{
ObjectFactory.GetObject("threadCreatorInsideConstructor");
}
}
internal class ThreadCreatorInsideConstructor
{
public ThreadCreatorInsideConstructor()
{
Thread t = new Thread(ConcurentThreadProc);
t.Start();
t.Join();
}
private static void ConcurentThreadProc()
{
ObjectFactory.GetObject("threadCreatorInsideDispose");
}
}
}
[TestFixture]
public class SPRNET_1315
{
private static AbstractObjectFactory _cachedFactory;
private static int _childCounter;
private static int _parentCounter;
private static ArrayList invocationLog = new ArrayList();
protected static AbstractObjectFactory ObjectFactory
{
get { return _cachedFactory; }
set { _cachedFactory = value; }
}
[SetUp]
public void _Setup()
{
ObjectFactory = new DefaultListableObjectFactory(true);
invocationLog.Clear();
_parentCounter = 0;
_childCounter = 0;
}
[Test]
public void When_ParentAndChildArePrototypes_ConstructorInjection_DoesNotEnforceDestructionOrder()
{
WireParentAndChildWWithImpliedDependencyByConstructorInjection(false, false);
Parent theParent = ObjectFactory.GetObject("parent") as Parent;
theParent.Dispose();
Assert.AreEqual(0, _parentCounter, "Should have no remaining parent objects after dispose");
Assert.AreEqual(1, _childCounter, "Should have exactly ONE child object");
Assert.IsNotNull(theParent.InjectedChild, "Parent's child dependency not set as expected");
Assert.AreEqual("Parent Destructor", invocationLog[2], "Parent Destructor wasn't called third!");
Assert.AreEqual(3, invocationLog.Count, "Should have no further object lifecycle behavior after parent destruction!");
}
[Test]
public void When_ParentAndChildArePrototypes_ConstructorInjection_EnforcesConstructionOrder()
{
WireParentAndChildWWithImpliedDependencyByConstructorInjection(false, false);
Parent theParent = ObjectFactory.GetObject("parent") as Parent;
Assert.AreEqual(1, _parentCounter, "Should have exactly ONE parent object");
Assert.AreEqual(1, _childCounter, "Should have exactly ONE child object");
Assert.IsNotNull(theParent.InjectedChild, "Parent's child dependency not set as expected");
Assert.AreEqual("Child Constructor", invocationLog[0], "Child Constructor wasn't called first!");
Assert.AreEqual("Parent Constructor", invocationLog[1], "Parent Constructor wasn't called second!");
}
[Test]
public void When_ParentAndChildArePrototypes_DependsOn_DoesNotEnforceDestructionOrder()
{
WireParentAndChildWithDependsOnDeclarationDependency(false, false);
Parent theParent = ObjectFactory.GetObject("parent") as Parent;
theParent.Dispose();
Assert.AreEqual(0, _parentCounter, "Should have no remaining parent objects after dispose");
Assert.AreEqual(1, _childCounter, "Should have exactly ONE child object");
Assert.AreEqual("Parent Destructor", invocationLog[2], "Parent Destructor wasn't called third!");
Assert.AreEqual(3, invocationLog.Count, "Should have no further object lifecycle behavior after parent destruction!");
}
[Test]
public void When_ParentAndChildArePrototypes_DependsOn_EnforcesConstructionOrder()
{
WireParentAndChildWithDependsOnDeclarationDependency(false, false);
Parent theParent = ObjectFactory.GetObject("parent") as Parent;
Assert.AreEqual(1, _parentCounter, "Should have exactly ONE parent object");
Assert.AreEqual(1, _childCounter, "Should have exactly ONE child object");
Assert.AreEqual("Child Constructor", invocationLog[0], "Child Constructor wasn't called first!");
Assert.AreEqual("Parent Constructor", invocationLog[1], "Parent Constructor wasn't called second!");
}
[Test]
public void When_ParentAndChildAreSingletons_ConstructorInjection_EnforcesDestructionOrder()
{
WireParentAndChildWWithImpliedDependencyByConstructorInjection(true, true);
//triger the construction of the singletons
ObjectFactory.GetObject("parent");
//trigger the disposal of the singletons
ObjectFactory.Dispose();
Assert.AreEqual(0, _parentCounter, "Should have no remaining parent objects after dispose");
Assert.AreEqual(0, _childCounter, "Should have no remaining child objects after dispose");
Assert.AreEqual("Parent Destructor", invocationLog[2], "Parent Destructor wasn't called third!");
Assert.AreEqual("Child Destructor", invocationLog[3], "Child Destructor wasn't called fourth!");
Assert.AreEqual(4, invocationLog.Count, "Should have no further object lifecycle behavior after parent destruction!");
}
[Test]
public void When_ParentAndChildAreSingletons_DependsOn_EnforcesDestructionOrder()
{
WireParentAndChildWithDependsOnDeclarationDependency(true, true);
//triger the construction of the singletons
ObjectFactory.GetObject("parent");
//make certain they are created successfully
Assert.AreEqual(1, _parentCounter, "Should have exactly ONE parent object");
Assert.AreEqual(1, _childCounter, "Should have exactly ONE child object");
//trigger the disposal of the singletons
ObjectFactory.Dispose();
Assert.AreEqual(0, _parentCounter, "Should have no remaining parent objects after dispose");
Assert.AreEqual(0, _childCounter, "Should have no remaining child objects after dispose");
Assert.AreEqual("Parent Destructor", invocationLog[2], "Parent Destructor wasn't called third!");
Assert.AreEqual("Child Destructor", invocationLog[3], "Child Destructor wasn't called fourth!");
Assert.AreEqual(4, invocationLog.Count, "Should have no further object lifecycle behavior after child destruction!");
}
[Test]
public void When_ParentIsProttpyeAndChildIsSingleton_ConstructorInjection_DoesNotEnforcesDestructionOrder()
{
WireParentAndChildWWithImpliedDependencyByConstructorInjection(false, true);
//triger the construction of the singletons
ObjectFactory.GetObject("parent");
//trigger the disposal of the singletons
ObjectFactory.Dispose();
Assert.AreEqual(1, _parentCounter, "Should have ONE remaining parent objects after dispose");
Assert.AreEqual(0, _childCounter, "Should have no remaining child objects after dispose");
Assert.AreEqual("Child Destructor", invocationLog[2], "Child Destructor wasn't called third!");
Assert.AreEqual(3, invocationLog.Count, "Should have no further object lifecycle behavior after child destruction!");
}
[Test]
public void When_ParentIsSingletonAndChildIsPrototype_ConstructorInjection_DoesNotEnforcesDestructionOrder()
{
WireParentAndChildWWithImpliedDependencyByConstructorInjection(true, false);
//triger the construction of the singletons
ObjectFactory.GetObject("parent");
//trigger the disposal of the singletons
ObjectFactory.Dispose();
Assert.AreEqual(0, _parentCounter, "Should have no remaining parent objects after dispose");
Assert.AreEqual(1, _childCounter, "Should have ONE remaining child object after dispose");
Assert.AreEqual("Parent Destructor", invocationLog[2], "Child Destructor wasn't called third!");
Assert.AreEqual(3, invocationLog.Count, "Should have no further object lifecycle behavior after parent destruction!");
}
[Test]
public void When_ParentIsSingletonAndChildIsPrototype_DependsOn_EnforcesDestructionOrder()
{
WireParentAndChildWithDependsOnDeclarationDependency(true, false);
//triger the construction of the singletons
ObjectFactory.GetObject("parent");
//make certain they are created successfully
Assert.AreEqual(1, _parentCounter, "Should have exactly ONE parent object");
Assert.AreEqual(1, _childCounter, "Should have exactly ONE child object");
//trigger the disposal of the singletons
ObjectFactory.Dispose();
Assert.AreEqual(0, _parentCounter, "Should have no remaining parent objects after dispose");
Assert.AreEqual(1, _childCounter, "Should have no remaining child objects after dispose");
Assert.AreEqual("Parent Destructor", invocationLog[2], "Parent Destructor wasn't called third!");
Assert.AreEqual(3, invocationLog.Count, "Should have no further object lifecycle behavior after parent destruction!");
}
private void WireParentAndChildWithDependsOnDeclarationDependency(bool parentIsSingleton, bool childIsSingleton)
{
GenericObjectDefinition child = new GenericObjectDefinition();
child.ObjectTypeName = typeof(Child).FullName;
child.IsSingleton = childIsSingleton;
ObjectFactory.RegisterObjectDefinition("child", child);
GenericObjectDefinition parent = new GenericObjectDefinition();
parent.ObjectTypeName = typeof(Parent).FullName;
parent.IsSingleton = parentIsSingleton;
parent.DependsOn = new string[] { "child" };
ObjectFactory.RegisterObjectDefinition("parent", parent);
}
private static void WireParentAndChildWWithImpliedDependencyByConstructorInjection(bool parentIsSingleton, bool childIsSingleton)
{
GenericObjectDefinition child = new GenericObjectDefinition();
child.ObjectTypeName = typeof(Child).FullName;
child.IsSingleton = childIsSingleton;
ObjectFactory.RegisterObjectDefinition("child", child);
GenericObjectDefinition parent = new GenericObjectDefinition();
parent.ObjectTypeName = typeof(Parent).FullName;
parent.IsSingleton = parentIsSingleton;
parent.ConstructorArgumentValues.AddIndexedArgumentValue(0, new RuntimeObjectReference("child"));
ObjectFactory.RegisterObjectDefinition("parent", parent);
}
public class Parent : IDisposable
{
private Child _child;
public Parent()
: this(null)
{
}
public Parent(Child child)
{
_child = child;
_parentCounter++;
invocationLog.Add("Parent Constructor");
}
public Child InjectedChild
{
get { return _child; }
}
public void Dispose()
{
_parentCounter--;
invocationLog.Add("Parent Destructor");
}
}
public class Child : IDisposable
{
public Child()
{
_childCounter++;
invocationLog.Add("Child Constructor");
}
public void Dispose()
{
_childCounter--;
invocationLog.Add("Child Destructor");
}
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Cloud.ResourceManager.V3.Snippets
{
using Google.Api.Gax;
using Google.Cloud.Iam.V1;
using Google.LongRunning;
using Google.Protobuf.WellKnownTypes;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
/// <summary>Generated snippets.</summary>
public sealed class GeneratedTagKeysClientSnippets
{
/// <summary>Snippet for ListTagKeys</summary>
public void ListTagKeysRequestObject()
{
// Snippet: ListTagKeys(ListTagKeysRequest, CallSettings)
// Create client
TagKeysClient tagKeysClient = TagKeysClient.Create();
// Initialize request argument(s)
ListTagKeysRequest request = new ListTagKeysRequest
{
ParentAsResourceName = new UnparsedResourceName("a/wildcard/resource"),
};
// Make the request
PagedEnumerable<ListTagKeysResponse, TagKey> response = tagKeysClient.ListTagKeys(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (TagKey item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListTagKeysResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (TagKey item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<TagKey> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (TagKey item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListTagKeysAsync</summary>
public async Task ListTagKeysRequestObjectAsync()
{
// Snippet: ListTagKeysAsync(ListTagKeysRequest, CallSettings)
// Create client
TagKeysClient tagKeysClient = await TagKeysClient.CreateAsync();
// Initialize request argument(s)
ListTagKeysRequest request = new ListTagKeysRequest
{
ParentAsResourceName = new UnparsedResourceName("a/wildcard/resource"),
};
// Make the request
PagedAsyncEnumerable<ListTagKeysResponse, TagKey> response = tagKeysClient.ListTagKeysAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((TagKey item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListTagKeysResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (TagKey item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<TagKey> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (TagKey item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListTagKeys</summary>
public void ListTagKeys()
{
// Snippet: ListTagKeys(string, string, int?, CallSettings)
// Create client
TagKeysClient tagKeysClient = TagKeysClient.Create();
// Initialize request argument(s)
string parent = "a/wildcard/resource";
// Make the request
PagedEnumerable<ListTagKeysResponse, TagKey> response = tagKeysClient.ListTagKeys(parent);
// Iterate over all response items, lazily performing RPCs as required
foreach (TagKey item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListTagKeysResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (TagKey item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<TagKey> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (TagKey item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListTagKeysAsync</summary>
public async Task ListTagKeysAsync()
{
// Snippet: ListTagKeysAsync(string, string, int?, CallSettings)
// Create client
TagKeysClient tagKeysClient = await TagKeysClient.CreateAsync();
// Initialize request argument(s)
string parent = "a/wildcard/resource";
// Make the request
PagedAsyncEnumerable<ListTagKeysResponse, TagKey> response = tagKeysClient.ListTagKeysAsync(parent);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((TagKey item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListTagKeysResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (TagKey item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<TagKey> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (TagKey item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListTagKeys</summary>
public void ListTagKeysResourceNames()
{
// Snippet: ListTagKeys(IResourceName, string, int?, CallSettings)
// Create client
TagKeysClient tagKeysClient = TagKeysClient.Create();
// Initialize request argument(s)
IResourceName parent = new UnparsedResourceName("a/wildcard/resource");
// Make the request
PagedEnumerable<ListTagKeysResponse, TagKey> response = tagKeysClient.ListTagKeys(parent);
// Iterate over all response items, lazily performing RPCs as required
foreach (TagKey item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListTagKeysResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (TagKey item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<TagKey> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (TagKey item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListTagKeysAsync</summary>
public async Task ListTagKeysResourceNamesAsync()
{
// Snippet: ListTagKeysAsync(IResourceName, string, int?, CallSettings)
// Create client
TagKeysClient tagKeysClient = await TagKeysClient.CreateAsync();
// Initialize request argument(s)
IResourceName parent = new UnparsedResourceName("a/wildcard/resource");
// Make the request
PagedAsyncEnumerable<ListTagKeysResponse, TagKey> response = tagKeysClient.ListTagKeysAsync(parent);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((TagKey item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListTagKeysResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (TagKey item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<TagKey> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (TagKey item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for GetTagKey</summary>
public void GetTagKeyRequestObject()
{
// Snippet: GetTagKey(GetTagKeyRequest, CallSettings)
// Create client
TagKeysClient tagKeysClient = TagKeysClient.Create();
// Initialize request argument(s)
GetTagKeyRequest request = new GetTagKeyRequest
{
TagKeyName = TagKeyName.FromTagKey("[TAG_KEY]"),
};
// Make the request
TagKey response = tagKeysClient.GetTagKey(request);
// End snippet
}
/// <summary>Snippet for GetTagKeyAsync</summary>
public async Task GetTagKeyRequestObjectAsync()
{
// Snippet: GetTagKeyAsync(GetTagKeyRequest, CallSettings)
// Additional: GetTagKeyAsync(GetTagKeyRequest, CancellationToken)
// Create client
TagKeysClient tagKeysClient = await TagKeysClient.CreateAsync();
// Initialize request argument(s)
GetTagKeyRequest request = new GetTagKeyRequest
{
TagKeyName = TagKeyName.FromTagKey("[TAG_KEY]"),
};
// Make the request
TagKey response = await tagKeysClient.GetTagKeyAsync(request);
// End snippet
}
/// <summary>Snippet for GetTagKey</summary>
public void GetTagKey()
{
// Snippet: GetTagKey(string, CallSettings)
// Create client
TagKeysClient tagKeysClient = TagKeysClient.Create();
// Initialize request argument(s)
string name = "tagKeys/[TAG_KEY]";
// Make the request
TagKey response = tagKeysClient.GetTagKey(name);
// End snippet
}
/// <summary>Snippet for GetTagKeyAsync</summary>
public async Task GetTagKeyAsync()
{
// Snippet: GetTagKeyAsync(string, CallSettings)
// Additional: GetTagKeyAsync(string, CancellationToken)
// Create client
TagKeysClient tagKeysClient = await TagKeysClient.CreateAsync();
// Initialize request argument(s)
string name = "tagKeys/[TAG_KEY]";
// Make the request
TagKey response = await tagKeysClient.GetTagKeyAsync(name);
// End snippet
}
/// <summary>Snippet for GetTagKey</summary>
public void GetTagKeyResourceNames()
{
// Snippet: GetTagKey(TagKeyName, CallSettings)
// Create client
TagKeysClient tagKeysClient = TagKeysClient.Create();
// Initialize request argument(s)
TagKeyName name = TagKeyName.FromTagKey("[TAG_KEY]");
// Make the request
TagKey response = tagKeysClient.GetTagKey(name);
// End snippet
}
/// <summary>Snippet for GetTagKeyAsync</summary>
public async Task GetTagKeyResourceNamesAsync()
{
// Snippet: GetTagKeyAsync(TagKeyName, CallSettings)
// Additional: GetTagKeyAsync(TagKeyName, CancellationToken)
// Create client
TagKeysClient tagKeysClient = await TagKeysClient.CreateAsync();
// Initialize request argument(s)
TagKeyName name = TagKeyName.FromTagKey("[TAG_KEY]");
// Make the request
TagKey response = await tagKeysClient.GetTagKeyAsync(name);
// End snippet
}
/// <summary>Snippet for CreateTagKey</summary>
public void CreateTagKeyRequestObject()
{
// Snippet: CreateTagKey(CreateTagKeyRequest, CallSettings)
// Create client
TagKeysClient tagKeysClient = TagKeysClient.Create();
// Initialize request argument(s)
CreateTagKeyRequest request = new CreateTagKeyRequest
{
TagKey = new TagKey(),
ValidateOnly = false,
};
// Make the request
Operation<TagKey, CreateTagKeyMetadata> response = tagKeysClient.CreateTagKey(request);
// Poll until the returned long-running operation is complete
Operation<TagKey, CreateTagKeyMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
TagKey result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<TagKey, CreateTagKeyMetadata> retrievedResponse = tagKeysClient.PollOnceCreateTagKey(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
TagKey retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for CreateTagKeyAsync</summary>
public async Task CreateTagKeyRequestObjectAsync()
{
// Snippet: CreateTagKeyAsync(CreateTagKeyRequest, CallSettings)
// Additional: CreateTagKeyAsync(CreateTagKeyRequest, CancellationToken)
// Create client
TagKeysClient tagKeysClient = await TagKeysClient.CreateAsync();
// Initialize request argument(s)
CreateTagKeyRequest request = new CreateTagKeyRequest
{
TagKey = new TagKey(),
ValidateOnly = false,
};
// Make the request
Operation<TagKey, CreateTagKeyMetadata> response = await tagKeysClient.CreateTagKeyAsync(request);
// Poll until the returned long-running operation is complete
Operation<TagKey, CreateTagKeyMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
TagKey result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<TagKey, CreateTagKeyMetadata> retrievedResponse = await tagKeysClient.PollOnceCreateTagKeyAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
TagKey retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for CreateTagKey</summary>
public void CreateTagKey()
{
// Snippet: CreateTagKey(TagKey, CallSettings)
// Create client
TagKeysClient tagKeysClient = TagKeysClient.Create();
// Initialize request argument(s)
TagKey tagKey = new TagKey();
// Make the request
Operation<TagKey, CreateTagKeyMetadata> response = tagKeysClient.CreateTagKey(tagKey);
// Poll until the returned long-running operation is complete
Operation<TagKey, CreateTagKeyMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
TagKey result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<TagKey, CreateTagKeyMetadata> retrievedResponse = tagKeysClient.PollOnceCreateTagKey(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
TagKey retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for CreateTagKeyAsync</summary>
public async Task CreateTagKeyAsync()
{
// Snippet: CreateTagKeyAsync(TagKey, CallSettings)
// Additional: CreateTagKeyAsync(TagKey, CancellationToken)
// Create client
TagKeysClient tagKeysClient = await TagKeysClient.CreateAsync();
// Initialize request argument(s)
TagKey tagKey = new TagKey();
// Make the request
Operation<TagKey, CreateTagKeyMetadata> response = await tagKeysClient.CreateTagKeyAsync(tagKey);
// Poll until the returned long-running operation is complete
Operation<TagKey, CreateTagKeyMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
TagKey result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<TagKey, CreateTagKeyMetadata> retrievedResponse = await tagKeysClient.PollOnceCreateTagKeyAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
TagKey retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for UpdateTagKey</summary>
public void UpdateTagKeyRequestObject()
{
// Snippet: UpdateTagKey(UpdateTagKeyRequest, CallSettings)
// Create client
TagKeysClient tagKeysClient = TagKeysClient.Create();
// Initialize request argument(s)
UpdateTagKeyRequest request = new UpdateTagKeyRequest
{
TagKey = new TagKey(),
UpdateMask = new FieldMask(),
ValidateOnly = false,
};
// Make the request
Operation<TagKey, UpdateTagKeyMetadata> response = tagKeysClient.UpdateTagKey(request);
// Poll until the returned long-running operation is complete
Operation<TagKey, UpdateTagKeyMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
TagKey result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<TagKey, UpdateTagKeyMetadata> retrievedResponse = tagKeysClient.PollOnceUpdateTagKey(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
TagKey retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for UpdateTagKeyAsync</summary>
public async Task UpdateTagKeyRequestObjectAsync()
{
// Snippet: UpdateTagKeyAsync(UpdateTagKeyRequest, CallSettings)
// Additional: UpdateTagKeyAsync(UpdateTagKeyRequest, CancellationToken)
// Create client
TagKeysClient tagKeysClient = await TagKeysClient.CreateAsync();
// Initialize request argument(s)
UpdateTagKeyRequest request = new UpdateTagKeyRequest
{
TagKey = new TagKey(),
UpdateMask = new FieldMask(),
ValidateOnly = false,
};
// Make the request
Operation<TagKey, UpdateTagKeyMetadata> response = await tagKeysClient.UpdateTagKeyAsync(request);
// Poll until the returned long-running operation is complete
Operation<TagKey, UpdateTagKeyMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
TagKey result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<TagKey, UpdateTagKeyMetadata> retrievedResponse = await tagKeysClient.PollOnceUpdateTagKeyAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
TagKey retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for UpdateTagKey</summary>
public void UpdateTagKey()
{
// Snippet: UpdateTagKey(TagKey, FieldMask, CallSettings)
// Create client
TagKeysClient tagKeysClient = TagKeysClient.Create();
// Initialize request argument(s)
TagKey tagKey = new TagKey();
FieldMask updateMask = new FieldMask();
// Make the request
Operation<TagKey, UpdateTagKeyMetadata> response = tagKeysClient.UpdateTagKey(tagKey, updateMask);
// Poll until the returned long-running operation is complete
Operation<TagKey, UpdateTagKeyMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
TagKey result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<TagKey, UpdateTagKeyMetadata> retrievedResponse = tagKeysClient.PollOnceUpdateTagKey(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
TagKey retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for UpdateTagKeyAsync</summary>
public async Task UpdateTagKeyAsync()
{
// Snippet: UpdateTagKeyAsync(TagKey, FieldMask, CallSettings)
// Additional: UpdateTagKeyAsync(TagKey, FieldMask, CancellationToken)
// Create client
TagKeysClient tagKeysClient = await TagKeysClient.CreateAsync();
// Initialize request argument(s)
TagKey tagKey = new TagKey();
FieldMask updateMask = new FieldMask();
// Make the request
Operation<TagKey, UpdateTagKeyMetadata> response = await tagKeysClient.UpdateTagKeyAsync(tagKey, updateMask);
// Poll until the returned long-running operation is complete
Operation<TagKey, UpdateTagKeyMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
TagKey result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<TagKey, UpdateTagKeyMetadata> retrievedResponse = await tagKeysClient.PollOnceUpdateTagKeyAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
TagKey retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DeleteTagKey</summary>
public void DeleteTagKeyRequestObject()
{
// Snippet: DeleteTagKey(DeleteTagKeyRequest, CallSettings)
// Create client
TagKeysClient tagKeysClient = TagKeysClient.Create();
// Initialize request argument(s)
DeleteTagKeyRequest request = new DeleteTagKeyRequest
{
TagKeyName = TagKeyName.FromTagKey("[TAG_KEY]"),
ValidateOnly = false,
Etag = "",
};
// Make the request
Operation<TagKey, DeleteTagKeyMetadata> response = tagKeysClient.DeleteTagKey(request);
// Poll until the returned long-running operation is complete
Operation<TagKey, DeleteTagKeyMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
TagKey result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<TagKey, DeleteTagKeyMetadata> retrievedResponse = tagKeysClient.PollOnceDeleteTagKey(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
TagKey retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DeleteTagKeyAsync</summary>
public async Task DeleteTagKeyRequestObjectAsync()
{
// Snippet: DeleteTagKeyAsync(DeleteTagKeyRequest, CallSettings)
// Additional: DeleteTagKeyAsync(DeleteTagKeyRequest, CancellationToken)
// Create client
TagKeysClient tagKeysClient = await TagKeysClient.CreateAsync();
// Initialize request argument(s)
DeleteTagKeyRequest request = new DeleteTagKeyRequest
{
TagKeyName = TagKeyName.FromTagKey("[TAG_KEY]"),
ValidateOnly = false,
Etag = "",
};
// Make the request
Operation<TagKey, DeleteTagKeyMetadata> response = await tagKeysClient.DeleteTagKeyAsync(request);
// Poll until the returned long-running operation is complete
Operation<TagKey, DeleteTagKeyMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
TagKey result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<TagKey, DeleteTagKeyMetadata> retrievedResponse = await tagKeysClient.PollOnceDeleteTagKeyAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
TagKey retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DeleteTagKey</summary>
public void DeleteTagKey()
{
// Snippet: DeleteTagKey(string, CallSettings)
// Create client
TagKeysClient tagKeysClient = TagKeysClient.Create();
// Initialize request argument(s)
string name = "tagKeys/[TAG_KEY]";
// Make the request
Operation<TagKey, DeleteTagKeyMetadata> response = tagKeysClient.DeleteTagKey(name);
// Poll until the returned long-running operation is complete
Operation<TagKey, DeleteTagKeyMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
TagKey result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<TagKey, DeleteTagKeyMetadata> retrievedResponse = tagKeysClient.PollOnceDeleteTagKey(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
TagKey retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DeleteTagKeyAsync</summary>
public async Task DeleteTagKeyAsync()
{
// Snippet: DeleteTagKeyAsync(string, CallSettings)
// Additional: DeleteTagKeyAsync(string, CancellationToken)
// Create client
TagKeysClient tagKeysClient = await TagKeysClient.CreateAsync();
// Initialize request argument(s)
string name = "tagKeys/[TAG_KEY]";
// Make the request
Operation<TagKey, DeleteTagKeyMetadata> response = await tagKeysClient.DeleteTagKeyAsync(name);
// Poll until the returned long-running operation is complete
Operation<TagKey, DeleteTagKeyMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
TagKey result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<TagKey, DeleteTagKeyMetadata> retrievedResponse = await tagKeysClient.PollOnceDeleteTagKeyAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
TagKey retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DeleteTagKey</summary>
public void DeleteTagKeyResourceNames()
{
// Snippet: DeleteTagKey(TagKeyName, CallSettings)
// Create client
TagKeysClient tagKeysClient = TagKeysClient.Create();
// Initialize request argument(s)
TagKeyName name = TagKeyName.FromTagKey("[TAG_KEY]");
// Make the request
Operation<TagKey, DeleteTagKeyMetadata> response = tagKeysClient.DeleteTagKey(name);
// Poll until the returned long-running operation is complete
Operation<TagKey, DeleteTagKeyMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
TagKey result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<TagKey, DeleteTagKeyMetadata> retrievedResponse = tagKeysClient.PollOnceDeleteTagKey(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
TagKey retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DeleteTagKeyAsync</summary>
public async Task DeleteTagKeyResourceNamesAsync()
{
// Snippet: DeleteTagKeyAsync(TagKeyName, CallSettings)
// Additional: DeleteTagKeyAsync(TagKeyName, CancellationToken)
// Create client
TagKeysClient tagKeysClient = await TagKeysClient.CreateAsync();
// Initialize request argument(s)
TagKeyName name = TagKeyName.FromTagKey("[TAG_KEY]");
// Make the request
Operation<TagKey, DeleteTagKeyMetadata> response = await tagKeysClient.DeleteTagKeyAsync(name);
// Poll until the returned long-running operation is complete
Operation<TagKey, DeleteTagKeyMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
TagKey result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<TagKey, DeleteTagKeyMetadata> retrievedResponse = await tagKeysClient.PollOnceDeleteTagKeyAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
TagKey retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for GetIamPolicy</summary>
public void GetIamPolicyRequestObject()
{
// Snippet: GetIamPolicy(GetIamPolicyRequest, CallSettings)
// Create client
TagKeysClient tagKeysClient = TagKeysClient.Create();
// Initialize request argument(s)
GetIamPolicyRequest request = new GetIamPolicyRequest
{
ResourceAsResourceName = new UnparsedResourceName("a/wildcard/resource"),
Options = new GetPolicyOptions(),
};
// Make the request
Policy response = tagKeysClient.GetIamPolicy(request);
// End snippet
}
/// <summary>Snippet for GetIamPolicyAsync</summary>
public async Task GetIamPolicyRequestObjectAsync()
{
// Snippet: GetIamPolicyAsync(GetIamPolicyRequest, CallSettings)
// Additional: GetIamPolicyAsync(GetIamPolicyRequest, CancellationToken)
// Create client
TagKeysClient tagKeysClient = await TagKeysClient.CreateAsync();
// Initialize request argument(s)
GetIamPolicyRequest request = new GetIamPolicyRequest
{
ResourceAsResourceName = new UnparsedResourceName("a/wildcard/resource"),
Options = new GetPolicyOptions(),
};
// Make the request
Policy response = await tagKeysClient.GetIamPolicyAsync(request);
// End snippet
}
/// <summary>Snippet for GetIamPolicy</summary>
public void GetIamPolicy()
{
// Snippet: GetIamPolicy(string, CallSettings)
// Create client
TagKeysClient tagKeysClient = TagKeysClient.Create();
// Initialize request argument(s)
string resource = "a/wildcard/resource";
// Make the request
Policy response = tagKeysClient.GetIamPolicy(resource);
// End snippet
}
/// <summary>Snippet for GetIamPolicyAsync</summary>
public async Task GetIamPolicyAsync()
{
// Snippet: GetIamPolicyAsync(string, CallSettings)
// Additional: GetIamPolicyAsync(string, CancellationToken)
// Create client
TagKeysClient tagKeysClient = await TagKeysClient.CreateAsync();
// Initialize request argument(s)
string resource = "a/wildcard/resource";
// Make the request
Policy response = await tagKeysClient.GetIamPolicyAsync(resource);
// End snippet
}
/// <summary>Snippet for GetIamPolicy</summary>
public void GetIamPolicyResourceNames()
{
// Snippet: GetIamPolicy(IResourceName, CallSettings)
// Create client
TagKeysClient tagKeysClient = TagKeysClient.Create();
// Initialize request argument(s)
IResourceName resource = new UnparsedResourceName("a/wildcard/resource");
// Make the request
Policy response = tagKeysClient.GetIamPolicy(resource);
// End snippet
}
/// <summary>Snippet for GetIamPolicyAsync</summary>
public async Task GetIamPolicyResourceNamesAsync()
{
// Snippet: GetIamPolicyAsync(IResourceName, CallSettings)
// Additional: GetIamPolicyAsync(IResourceName, CancellationToken)
// Create client
TagKeysClient tagKeysClient = await TagKeysClient.CreateAsync();
// Initialize request argument(s)
IResourceName resource = new UnparsedResourceName("a/wildcard/resource");
// Make the request
Policy response = await tagKeysClient.GetIamPolicyAsync(resource);
// End snippet
}
/// <summary>Snippet for SetIamPolicy</summary>
public void SetIamPolicyRequestObject()
{
// Snippet: SetIamPolicy(SetIamPolicyRequest, CallSettings)
// Create client
TagKeysClient tagKeysClient = TagKeysClient.Create();
// Initialize request argument(s)
SetIamPolicyRequest request = new SetIamPolicyRequest
{
ResourceAsResourceName = new UnparsedResourceName("a/wildcard/resource"),
Policy = new Policy(),
};
// Make the request
Policy response = tagKeysClient.SetIamPolicy(request);
// End snippet
}
/// <summary>Snippet for SetIamPolicyAsync</summary>
public async Task SetIamPolicyRequestObjectAsync()
{
// Snippet: SetIamPolicyAsync(SetIamPolicyRequest, CallSettings)
// Additional: SetIamPolicyAsync(SetIamPolicyRequest, CancellationToken)
// Create client
TagKeysClient tagKeysClient = await TagKeysClient.CreateAsync();
// Initialize request argument(s)
SetIamPolicyRequest request = new SetIamPolicyRequest
{
ResourceAsResourceName = new UnparsedResourceName("a/wildcard/resource"),
Policy = new Policy(),
};
// Make the request
Policy response = await tagKeysClient.SetIamPolicyAsync(request);
// End snippet
}
/// <summary>Snippet for SetIamPolicy</summary>
public void SetIamPolicy()
{
// Snippet: SetIamPolicy(string, Policy, CallSettings)
// Create client
TagKeysClient tagKeysClient = TagKeysClient.Create();
// Initialize request argument(s)
string resource = "a/wildcard/resource";
Policy policy = new Policy();
// Make the request
Policy response = tagKeysClient.SetIamPolicy(resource, policy);
// End snippet
}
/// <summary>Snippet for SetIamPolicyAsync</summary>
public async Task SetIamPolicyAsync()
{
// Snippet: SetIamPolicyAsync(string, Policy, CallSettings)
// Additional: SetIamPolicyAsync(string, Policy, CancellationToken)
// Create client
TagKeysClient tagKeysClient = await TagKeysClient.CreateAsync();
// Initialize request argument(s)
string resource = "a/wildcard/resource";
Policy policy = new Policy();
// Make the request
Policy response = await tagKeysClient.SetIamPolicyAsync(resource, policy);
// End snippet
}
/// <summary>Snippet for SetIamPolicy</summary>
public void SetIamPolicyResourceNames()
{
// Snippet: SetIamPolicy(IResourceName, Policy, CallSettings)
// Create client
TagKeysClient tagKeysClient = TagKeysClient.Create();
// Initialize request argument(s)
IResourceName resource = new UnparsedResourceName("a/wildcard/resource");
Policy policy = new Policy();
// Make the request
Policy response = tagKeysClient.SetIamPolicy(resource, policy);
// End snippet
}
/// <summary>Snippet for SetIamPolicyAsync</summary>
public async Task SetIamPolicyResourceNamesAsync()
{
// Snippet: SetIamPolicyAsync(IResourceName, Policy, CallSettings)
// Additional: SetIamPolicyAsync(IResourceName, Policy, CancellationToken)
// Create client
TagKeysClient tagKeysClient = await TagKeysClient.CreateAsync();
// Initialize request argument(s)
IResourceName resource = new UnparsedResourceName("a/wildcard/resource");
Policy policy = new Policy();
// Make the request
Policy response = await tagKeysClient.SetIamPolicyAsync(resource, policy);
// End snippet
}
/// <summary>Snippet for TestIamPermissions</summary>
public void TestIamPermissionsRequestObject()
{
// Snippet: TestIamPermissions(TestIamPermissionsRequest, CallSettings)
// Create client
TagKeysClient tagKeysClient = TagKeysClient.Create();
// Initialize request argument(s)
TestIamPermissionsRequest request = new TestIamPermissionsRequest
{
ResourceAsResourceName = new UnparsedResourceName("a/wildcard/resource"),
Permissions = { "", },
};
// Make the request
TestIamPermissionsResponse response = tagKeysClient.TestIamPermissions(request);
// End snippet
}
/// <summary>Snippet for TestIamPermissionsAsync</summary>
public async Task TestIamPermissionsRequestObjectAsync()
{
// Snippet: TestIamPermissionsAsync(TestIamPermissionsRequest, CallSettings)
// Additional: TestIamPermissionsAsync(TestIamPermissionsRequest, CancellationToken)
// Create client
TagKeysClient tagKeysClient = await TagKeysClient.CreateAsync();
// Initialize request argument(s)
TestIamPermissionsRequest request = new TestIamPermissionsRequest
{
ResourceAsResourceName = new UnparsedResourceName("a/wildcard/resource"),
Permissions = { "", },
};
// Make the request
TestIamPermissionsResponse response = await tagKeysClient.TestIamPermissionsAsync(request);
// End snippet
}
/// <summary>Snippet for TestIamPermissions</summary>
public void TestIamPermissions()
{
// Snippet: TestIamPermissions(string, IEnumerable<string>, CallSettings)
// Create client
TagKeysClient tagKeysClient = TagKeysClient.Create();
// Initialize request argument(s)
string resource = "a/wildcard/resource";
IEnumerable<string> permissions = new string[] { "", };
// Make the request
TestIamPermissionsResponse response = tagKeysClient.TestIamPermissions(resource, permissions);
// End snippet
}
/// <summary>Snippet for TestIamPermissionsAsync</summary>
public async Task TestIamPermissionsAsync()
{
// Snippet: TestIamPermissionsAsync(string, IEnumerable<string>, CallSettings)
// Additional: TestIamPermissionsAsync(string, IEnumerable<string>, CancellationToken)
// Create client
TagKeysClient tagKeysClient = await TagKeysClient.CreateAsync();
// Initialize request argument(s)
string resource = "a/wildcard/resource";
IEnumerable<string> permissions = new string[] { "", };
// Make the request
TestIamPermissionsResponse response = await tagKeysClient.TestIamPermissionsAsync(resource, permissions);
// End snippet
}
/// <summary>Snippet for TestIamPermissions</summary>
public void TestIamPermissionsResourceNames()
{
// Snippet: TestIamPermissions(IResourceName, IEnumerable<string>, CallSettings)
// Create client
TagKeysClient tagKeysClient = TagKeysClient.Create();
// Initialize request argument(s)
IResourceName resource = new UnparsedResourceName("a/wildcard/resource");
IEnumerable<string> permissions = new string[] { "", };
// Make the request
TestIamPermissionsResponse response = tagKeysClient.TestIamPermissions(resource, permissions);
// End snippet
}
/// <summary>Snippet for TestIamPermissionsAsync</summary>
public async Task TestIamPermissionsResourceNamesAsync()
{
// Snippet: TestIamPermissionsAsync(IResourceName, IEnumerable<string>, CallSettings)
// Additional: TestIamPermissionsAsync(IResourceName, IEnumerable<string>, CancellationToken)
// Create client
TagKeysClient tagKeysClient = await TagKeysClient.CreateAsync();
// Initialize request argument(s)
IResourceName resource = new UnparsedResourceName("a/wildcard/resource");
IEnumerable<string> permissions = new string[] { "", };
// Make the request
TestIamPermissionsResponse response = await tagKeysClient.TestIamPermissionsAsync(resource, permissions);
// End snippet
}
}
}
| |
#region Namespaces
using System;
using System.Globalization;
using System.Linq;
using System.IO;
using System.Collections.Generic;
using System.Diagnostics;
using Application = Autodesk.Revit.ApplicationServices.Application;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.DB.Analysis;
using Autodesk.Revit.UI;
using Autodesk.Revit.UI.Selection;
using Autodesk.Revit.DB.Mechanical;
using Autodesk.Revit.DB.Electrical;
using Autodesk.Revit.DB.Lighting;
using System.Windows.Forms;
#endregion
namespace STFExporter
{
/// <summary>
/// Default decimal writer
/// </summary>
public static class DoubleExtensions
{
public static string ToDecimalString(this double value)
{
return value.ToString(CultureInfo.GetCultureInfo("en-US"));
}
}
/// <summary>
/// Command Class
/// </summary>
[Transaction(TransactionMode.Manual)]
[Regeneration(RegenerationOption.Manual)]
public class Command : IExternalCommand
{
public Application _app;
public Document _doc;
public string writer = "";
public double meterMultiplier = 0.3048;
public List<ElementId> distinctLuminaires = new List<ElementId>();
public string stfVersionNum = "1.0.5";
public bool intlVersion;
public Result Execute(
ExternalCommandData commandData,
ref string message,
ElementSet elements)
{
UIApplication uiapp = commandData.Application;
UIDocument uidoc = uiapp.ActiveUIDocument;
Application app = uiapp.Application;
Document doc = uidoc.Document;
_app = app;
_doc = doc;
// Set project units to Meters then back after
// This is how DIALux reads the data from the STF File.
Units pUnit = doc.GetUnits();
FormatOptions formatOptions = pUnit.GetFormatOptions(UnitType.UT_Length);
//DisplayUnitType curUnitType = pUnit.GetDisplayUnitType();
DisplayUnitType curUnitType = formatOptions.DisplayUnits;
using (Transaction tx = new Transaction(doc))
{
tx.Start("STF EXPORT");
const DisplayUnitType meters = DisplayUnitType.DUT_METERS;
formatOptions.DisplayUnits = meters;
// Comment out, different in 2014
//formatOptions.Units = meters;
//formatOptions.Rounding = 0.0000000001;]
formatOptions.Accuracy = 0.0000000001;
// Fix decimal symbol for int'l versions (set back again after finish)
if (pUnit.DecimalSymbol == DecimalSymbol.Comma)
{
intlVersion = true;
//TESTING
//TaskDialog.Show("INTL", "You have an internationalized version of Revit!");
formatOptions.UseDigitGrouping = false;
pUnit.DecimalSymbol = DecimalSymbol.Dot;
}
try
{
// Filter for only active view.
ElementLevelFilter filter = new ElementLevelFilter(doc.ActiveView.GenLevel.Id);
FilteredElementCollector fec = new FilteredElementCollector(doc, doc.ActiveView.Id)
.OfCategory(BuiltInCategory.OST_MEPSpaces)
.WherePasses(filter);
int numOfRooms = fec.Count();
writer += "[VERSION]\n"
+ "STFF=" + stfVersionNum + "\n"
+ "Progname=Revit\n"
+ "Progvers=" + app.VersionNumber + "\n"
+ "[Project]\n"
+ "Name=" + _doc.ProjectInformation.Name + "\n"
+ "Date=" + DateTime.Now.Year.ToString() + "-" + DateTime.Now.Month.ToString() + "-" +
DateTime.Now.Day.ToString() + "\n"
+ "Operator=" + app.Username + "\n"
+ "NrRooms=" + numOfRooms + "\n";
for (int i = 1; i < numOfRooms + 1; i++)
{
string _dialuxRoomName = "Room" + i.ToString() + "=ROOM.R" + i.ToString();
writer += _dialuxRoomName + "\n";
}
int increment = 1;
// Space writer
try
{
foreach (Element e in fec)
{
Space s = e as Space;
string roomRNum = "ROOM.R" + increment.ToString();
writer += "[" + roomRNum + "]\n";
SpaceInfoWriter(s.Id, roomRNum);
increment++;
}
// Write out Luminaires to bottom
writeLumenairs();
// Reset back to original units
formatOptions.DisplayUnits = curUnitType;
if (intlVersion)
pUnit.DecimalSymbol = DecimalSymbol.Comma;
tx.Commit();
SaveFileDialog dialog = new SaveFileDialog
{
FileName = doc.ProjectInformation.Name,
Filter = "STF File | *.stf",
FilterIndex = 2,
RestoreDirectory = true
};
if (dialog.ShowDialog() == DialogResult.OK)
{
StreamWriter sw = new StreamWriter(dialog.FileName);
string[] ar = writer.Split('\n');
for (int i = 0; i < ar.Length; i++)
{
sw.WriteLine(ar[i]);
}
sw.Close();
}
return Result.Succeeded;
}
catch (IndexOutOfRangeException)
{
return Result.Failed;
}
}
catch (NullReferenceException)
{
TaskDialog.Show("Incorrect View", "Cannot find Spaces to export.\nMake sure you are in a Floorplan or Ceiling Plan view and Spaces are visible.");
return Result.Failed;
}
}
}
#region Private Methods
private void writeLumenairs()
{
FilteredElementCollector fecFixtures = new FilteredElementCollector(_doc)
.OfCategory(BuiltInCategory.OST_LightingFixtures)
.OfClass(typeof(FamilySymbol));
foreach (Element e in fecFixtures)
{
FamilySymbol fs = e as FamilySymbol;
string load = "";
string flux = "";
Parameter pload = fs.get_Parameter(BuiltInParameter.RBS_ELEC_APPARENT_LOAD);
Parameter pflux = fs.get_Parameter(BuiltInParameter.FBX_LIGHT_LIMUNOUS_FLUX);
if (pflux != null)
{
load = pload.AsValueString();
flux = pflux.AsValueString();
writer += "[" + fs.Name.Replace(" ", "") + "]\n";
writer += "Manufacturer=" + "\n"
+ "Name=" + "\n"
+ "OrderNr=" + "\n"
+ "Box=1 1 0" + "\n" //need to fix per bounding box size (i guess);
+ "Shape=0" + "\n"
+ "Load=" + load.Remove(load.Length - 3) + "\n"
+ "Flux=" + flux.Remove(flux.Length - 3) + "\n"
+ "NrLamps=" + getNumLamps(fs) + "\n"
+ "MountingType=1\n";
}
}
}
private string getNumLamps(FamilySymbol fs)
{
if (fs.get_Parameter("Number of Lamps") != null)
{
return fs.get_Parameter("Number of Lamps").ToString();
}
else
{
// TODO:
// Parse from IES file
var file = fs.get_Parameter(BuiltInParameter.FBX_LIGHT_PHOTOMETRIC_FILE);
return "1"; //for now
}
}
private void SpaceInfoWriter(ElementId spaceID, string RoomRNum)
{
try
{
//const double MAX_ROUNDING_PRECISION = 0.000000000001;
// Get info from Space
Space roomSpace = _doc.GetElement(spaceID) as Space;
//Space roomSpace = _doc.get_Element(spaceID) as Space;
// VARS
string name = roomSpace.Name;
double height = roomSpace.UnboundedHeight * meterMultiplier;
double workPlane = roomSpace.LightingCalculationWorkplane * meterMultiplier;
// Get room vertices
List<String> verticies = new List<string>();
verticies = getVertexPoints(roomSpace);
int numPoints = getVertexPointNums(roomSpace);
// Write out Top part of room entry
writer += "Name=" + name + "\n"
+ "Height=" + height.ToDecimalString() + "\n"
+ "WorkingPlane=" + workPlane.ToDecimalString() + "\n"
+ "NrPoints=" + numPoints.ToString() + "\n";
// Write vertices for each point in vertex numbers
for (int i = 0; i < numPoints; i++)
{
int i2 = i + 1;
writer += "Point" + i2 + "=" + verticies.ElementAt(i) + "\n";
}
double cReflect = roomSpace.CeilingReflectance;
double fReflect = roomSpace.FloorReflectance;
double wReflect = roomSpace.WallReflectance;
// Write out ceiling reflectance
writer += "R_Ceiling=" + cReflect.ToDecimalString() + "\n";
IList<ElementId> elemIds = roomSpace.GetMonitoredLocalElementIds();
foreach (ElementId e in elemIds)
{
TaskDialog.Show("s", _doc.GetElement(e).Name);
}
// Get fixtures within space
FilteredElementCollector fec = new FilteredElementCollector(_doc)
.OfCategory(BuiltInCategory.OST_LightingFixtures)
.OfClass(typeof(FamilyInstance));
int count = 0;
foreach (Element e in fec)
{
FamilyInstance fi = e as FamilyInstance;
if (fi.Space != null)
{
if (fi.Space.Id == spaceID)
{
FamilySymbol fs = _doc.GetElement(fi.GetTypeId()) as FamilySymbol;
//FamilySymbol fs = _doc.get_Element(fi.GetTypeId()) as FamilySymbol;
int lumNum = count + 1;
string lumName = "Lum" + lumNum.ToString();
LocationPoint locpt = fi.Location as LocationPoint;
XYZ fixtureloc = locpt.Point;
double X = fixtureloc.X * meterMultiplier;
double Y = fixtureloc.Y * meterMultiplier;
double Z = fixtureloc.Z * meterMultiplier;
double rotation = locpt.Rotation;
writer += lumName + "=" + fs.Name.Replace(" ", "") + "\n";
writer += lumName + ".Pos=" + X.ToDecimalString() + " " + Y.ToDecimalString() + " " + Z.ToDecimalString() + "\n";
writer += lumName + ".Rot=0 0 0" + "\n"; //need to figure out this rotation; Update: cannot determine. Almost impossible for Dialux
count++;
}
}
}
// Write out Lums part
writer += "NrLums=" + count.ToString() + "\n";
// Write out Struct part
writer += "NrStruct=0\n";
// Write out Furn part
writer += "NrFurns=" + getFurns(spaceID, RoomRNum);
}
catch (IndexOutOfRangeException)
{
throw new IndexOutOfRangeException();
}
}
private string getFurns(ElementId spaceID, string RoomRNum)
{
string furnsOutput = String.Empty;
// Go through the room and write out the windows/doors
// DOORS //
// Get all doors that have space where id equals current space.
FilteredElementCollector fecDoors = new FilteredElementCollector(_doc)
.OfCategory(BuiltInCategory.OST_Doors)
.OfClass(typeof(FamilyInstance));
// WINDOWS //
FilteredElementCollector fecWindows = new FilteredElementCollector(_doc)
.OfCategory(BuiltInCategory.OST_Windows)
.OfClass(typeof(FamilyInstance));
List<Element> doorsList = new List<Element>();
List<Element> windowList = new List<Element>();
foreach (Element e in fecDoors)
{
FamilyInstance fi = e as FamilyInstance;
if (fi != null && fi.Space != null && fi.Space.Id == spaceID)
doorsList.Add(fi);
}
foreach (Element e in fecWindows)
{
FamilyInstance fi = e as FamilyInstance;
if (fi != null && fi.Space != null && fi.Space.Id == spaceID)
windowList.Add(fi);
}
//Add Number of Furns to string
furnsOutput += (doorsList.Count + windowList.Count).ToString() + "\n";
// Loop through new list of Doors
int furnNumber = 1;
foreach (Element e in doorsList)
{
FamilyInstance fi = e as FamilyInstance;
// Door Width (in meters)
string doorWidth = (fi.Symbol.get_Parameter(BuiltInParameter.DOOR_WIDTH).AsDouble() * 0.3048).ToDecimalString();
// Door height (in meters)
string doorHeight = (fi.Symbol.get_Parameter(BuiltInParameter.DOOR_HEIGHT).AsDouble() * 0.3048).ToDecimalString();
LocationPoint lp = fi.Location as LocationPoint;
XYZ p = new XYZ(lp.Point.X * 0.30, lp.Point.Y * 0.30, 0);
//XYZ p = new XYZ(lp.Point.X, lp.Point.Y, 0);
string lps = p.ToString().Substring(1, p.ToString().Length - 2);
//string lps = lp.Point.ToDecimalString().Substring(1, lp.Point.ToDecimalString().Length - 2);
string sfurnNumber = "Furn" + furnNumber.ToString();
//Furn1=door
//Furn1.Ref=ROOM.R1.F1
//Furn1.Rot=90.00 0.00 0.00
//Furn1.Pos=1.151 3.67 0
//Furn1.Size=1.0 2.0 0.0
furnsOutput += sfurnNumber + "=door\n";
furnsOutput += sfurnNumber + ".Ref=" + RoomRNum + ".F" + furnNumber.ToString() + "\n";
// TODO: fix rotation
furnsOutput += sfurnNumber + ".Rot=90.00 0.00 0.00" + "\n"; //rotation???
// TODO: fix positioning...
furnsOutput += sfurnNumber + ".Pos=" + lps + "\n";
furnsOutput += sfurnNumber + ".Size=" + doorWidth + " " + doorHeight + " 0.00\n";
//Inrement furns
furnNumber++;
}
// WINDOWS //
foreach (Element e in fecWindows)
{
FamilyInstance fi = e as FamilyInstance;
// Window Width
string windowWidth = (fi.Symbol.get_Parameter(BuiltInParameter.WINDOW_WIDTH).AsDouble() * 0.3048).ToDecimalString();
// Window Height
string windowHeight = (fi.Symbol.get_Parameter(BuiltInParameter.WINDOW_HEIGHT).AsDouble() * 0.3048).ToDecimalString();
LocationPoint lp = fi.Location as LocationPoint;
//XYZ p = new XYZ(lp.Point.X * 0.30, lp.Point.Y * 0.30, lp.Point.Z * 0.30);
Transform t1 = fi.GetTransform();
XYZ p = new XYZ(t1.BasisX.X * 0.30, t1.BasisX.Y * 0.30, lp.Point.Z * 0.30);
string lps = p.ToString().Substring(1, p.ToString().Length - 2);
string sFurnNumber = "Furn" + furnNumber.ToString();
furnsOutput += sFurnNumber + "=win\n";
furnsOutput += sFurnNumber + ".Ref=" + RoomRNum + ".F" + furnNumber.ToString() + "\n";
// TODO: fix rotation
furnsOutput += sFurnNumber + ".Rot=90.00 0.00 0.00" + "\n"; //rotation???
// TODO: fix positioning...
furnsOutput += sFurnNumber + ".Pos=" + lps + "\n";
furnsOutput += sFurnNumber + ".Size=" + windowWidth + " " + windowHeight + " 0.00\n";
//Inrement furns
furnNumber++;
}
return furnsOutput;
}
private List<string> getVertexPoints(Space roomSpace)
{
List<string> verticies = new List<string>();
SpatialElementBoundaryOptions opts = new SpatialElementBoundaryOptions();
IList<IList<Autodesk.Revit.DB.BoundarySegment>> bsa = roomSpace.GetBoundarySegments(opts);
if (bsa.Count > 0)
{
foreach (Autodesk.Revit.DB.BoundarySegment bs in bsa[0])
{
// For 2014
//var X = bs.Curve.get_EndPoint(0).X * meterMultiplier;
//var Y = bs.Curve.get_EndPoint(0).Y * meterMultiplier;
var X = bs.Curve.GetEndPoint(0).X * meterMultiplier;
var Y = bs.Curve.GetEndPoint(0).Y * meterMultiplier;
verticies.Add(X.ToDecimalString() + " " + Y.ToDecimalString());
}
}
else
{
verticies.Add("0 0");
}
return verticies;
}
private int getVertexPointNums(Space roomSpace)
{
SpatialElementBoundaryOptions opts = new SpatialElementBoundaryOptions();
try
{
IList<IList<Autodesk.Revit.DB.BoundarySegment>> bsa = roomSpace.GetBoundarySegments(opts);
return bsa[0].Count;
}
catch (Exception)
{
TaskDialog.Show("OOPS!", "Seems you have a Space in your view that is not in a properly enclosed region. \n\nPlease remove these Spaces or re-establish them inside of boundary walls and run the Exporter again.");
throw new IndexOutOfRangeException();
}
}
#endregion
}
}
| |
//
// TagSelectionWidget.cs
//
// Author:
// Ruben Vermeersch <ruben@savanne.be>
// Mike Gemuende <mike@gemuende.de>
//
// Copyright (C) 2008-2010 Novell, Inc.
// Copyright (C) 2008, 2010 Ruben Vermeersch
// Copyright (C) 2009 Mike Gemuende
//
// 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.Collections;
using System.Collections.Generic;
using System.IO;
using System;
using GLib;
using Gdk;
using Gtk;
using Mono.Unix;
using FSpot;
using FSpot.Core;
using FSpot.Database;
using FSpot.Utils;
using FSpot.Widgets;
using FSpot.UI.Dialog;
using Hyena.Widgets;
namespace FSpot {
public class TagSelectionWidget : SaneTreeView {
Db database;
TagStore tag_store;
// FIXME this is a hack.
private static Pixbuf empty_pixbuf = new Pixbuf (Colorspace.Rgb, true, 8, 1, 1);
// If these are changed, the base () call in the constructor must be updated.
private const int IdColumn = 0;
private const int NameColumn = 1;
// Selection management.
public Tag TagAtPosition (double x, double y)
{
return TagAtPosition((int) x, (int) y);
}
public Tag TagAtPosition (int x, int y)
{
TreePath path;
// Work out which tag we're dropping onto
if (!this.GetPathAtPos (x, y, out path))
return null;
return TagByPath (path);
}
public Tag TagByPath (TreePath path)
{
TreeIter iter;
if (!Model.GetIter (out iter, path))
return null;
return TagByIter (iter);
}
public Tag TagByIter (TreeIter iter)
{
GLib.Value val = new GLib.Value ();
Model.GetValue (iter, IdColumn, ref val);
uint tag_id = (uint) val;
return tag_store.Get (tag_id) as Tag;
}
// Loading up the store.
private void LoadCategory (Category category, TreeIter parent_iter)
{
IList<Tag> tags = category.Children;
foreach (Tag t in tags) {
TreeIter iter = (Model as TreeStore).AppendValues (parent_iter, t.Id, t.Name);
if (t is Category)
LoadCategory (t as Category, iter);
}
}
public void ScrollTo (Tag tag)
{
TreeIter iter;
if (! TreeIterForTag (tag, out iter))
return;
TreePath path = Model.GetPath (iter);
ScrollToCell (path, null, false, 0, 0);
}
public Tag [] TagHighlight {
get {
TreeModel model;
TreeIter iter;
TreePath [] rows = Selection.GetSelectedRows(out model);
Tag [] tags = new Tag [rows.Length];
int i = 0;
foreach (TreePath path in rows) {
GLib.Value value = new GLib.Value ();
Model.GetIter (out iter, path);
Model.GetValue (iter, IdColumn, ref value);
uint tag_id = (uint) value;
tags[i] = tag_store.Get (tag_id) as Tag;
i++;
}
return tags;
}
set {
if (value == null)
return;
Selection.UnselectAll ();
TreeIter iter;
foreach (Tag tag in value)
if (TreeIterForTag (tag, out iter))
Selection.SelectIter (iter);
}
}
public void Update ()
{
(Model as TreeStore).Clear ();
// GRRR We have to special case the root because I can't pass null for a
// Gtk.TreeIter (since it's a struct, and not a class).
// FIXME: This should be fixed in GTK#... It's gross.
foreach (Tag t in tag_store.RootCategory.Children) {
TreeIter iter = (Model as TreeStore).AppendValues (t.Id, t.Name);
if (t is Category)
LoadCategory (t as Category, iter);
}
}
// Data functions.
private void SetBackground (CellRenderer renderer, Tag tag)
{
// FIXME this should be themable but Gtk# doesn't give me access to the proper
// members in GtkStyle for that.
/*
if (tag is Category)
renderer.CellBackground = ToHashColor (this.Style.MidColors [(int) Gtk.StateType.Normal]);
else
renderer.CellBackground = ToHashColor (this.Style.LightColors [(int) Gtk.StateType.Normal]);
*/
}
private void IconDataFunc (TreeViewColumn column,
CellRenderer renderer,
TreeModel model,
TreeIter iter)
{
GLib.Value value = new GLib.Value ();
Model.GetValue (iter, IdColumn, ref value);
uint tag_id = (uint) value;
Tag tag = tag_store.Get (tag_id) as Tag;
if (tag == null)
return;
SetBackground (renderer, tag);
if (tag.SizedIcon != null) {
Cms.Profile screen_profile;
if (FSpot.ColorManagement.Profiles.TryGetValue (Preferences.Get<string> (Preferences.COLOR_MANAGEMENT_DISPLAY_PROFILE), out screen_profile)) {
//FIXME, we're leaking a pixbuf here
Gdk.Pixbuf temp = tag.SizedIcon.Copy();
FSpot.ColorManagement.ApplyProfile (temp, screen_profile);
(renderer as CellRendererPixbuf).Pixbuf = temp;
} else
(renderer as CellRendererPixbuf).Pixbuf = tag.SizedIcon;
} else
(renderer as CellRendererPixbuf).Pixbuf = empty_pixbuf;
}
private void NameDataFunc (TreeViewColumn column,
CellRenderer renderer,
TreeModel model,
TreeIter iter)
{
// FIXME not sure why it happens...
if (model == null)
return;
GLib.Value value = new GLib.Value ();
Model.GetValue (iter, IdColumn, ref value);
uint tag_id = (uint) value;
Tag tag = tag_store.Get (tag_id) as Tag;
if (tag == null)
return;
SetBackground (renderer, tag);
(renderer as CellRendererText).Text = tag.Name;
}
private bool TreeIterForTag(Tag tag, out TreeIter iter)
{
TreeIter root = TreeIter.Zero;
iter = TreeIter.Zero;
bool valid = Model.GetIterFirst (out root);
while (valid) {
if (TreeIterForTagRecurse (tag, root, out iter))
return true;
valid = Model.IterNext (ref root);
}
return false;
}
// Depth first traversal
private bool TreeIterForTagRecurse (Tag tag, TreeIter parent, out TreeIter iter)
{
bool valid = Model.IterChildren (out iter, parent);
while (valid) {
if (TreeIterForTagRecurse (tag, iter, out iter))
return true;
valid = Model.IterNext (ref iter);
}
GLib.Value value = new GLib.Value ();
Model.GetValue (parent, IdColumn, ref value);
iter = parent;
if (tag.Id == (uint) value)
return true;
return false;
}
// Copy a branch of the tree to a new parent
// (note, this doesn't work generically as it only copies the first value of each node)
private void CopyBranch (TreeIter src, TreeIter dest, bool is_root, bool is_parent)
{
TreeIter copy, iter;
GLib.Value value = new GLib.Value ();
TreeStore store = Model as TreeStore;
bool valid;
store.GetValue (src, IdColumn, ref value);
Tag tag = (Tag) tag_store.Get ((uint)value);
if (is_parent) {
// we need to figure out where to insert it in the correct order
copy = InsertInOrder(dest, is_root, tag);
} else {
copy = store.AppendValues (dest, (uint)value, tag.Name);
}
valid = Model.IterChildren (out iter, src);
while (valid) {
// child nodes are already ordered
CopyBranch (iter, copy, false, false);
valid = Model.IterNext (ref iter);
}
}
// insert tag into the correct place in the tree, with parent. return the new TagIter in iter.
private TreeIter InsertInOrder (TreeIter parent, bool is_root, Tag tag)
{
TreeStore store = Model as TreeStore;
TreeIter iter;
Tag compare;
bool valid;
if (is_root)
valid = store.GetIterFirst (out iter);
else
valid = store.IterChildren (out iter, parent);
while (valid) {
//I have no desire to figure out a more performant sort over this...
GLib.Value value = new GLib.Value ();
store.GetValue(iter, IdColumn, ref value);
compare = (Tag) tag_store.Get ((uint) value);
if (compare.CompareTo (tag) > 0) {
iter = store.InsertNodeBefore (iter);
store.SetValue (iter, IdColumn, tag.Id);
store.SetValue (iter, NameColumn, tag.Name);
if (!is_root)
ExpandRow (Model.GetPath (parent), false);
return iter;
}
valid = store.IterNext(ref iter);
}
if (is_root)
iter = store.AppendNode ();
else {
iter = store.AppendNode (parent);
ExpandRow (Model.GetPath (parent), false);
}
store.SetValue (iter, IdColumn, tag.Id);
store.SetValue (iter, NameColumn, tag.Name);
return iter;
}
private void HandleTagsRemoved (object sender, DbItemEventArgs<Tag> args)
{
TreeIter iter;
foreach (Tag tag in args.Items) {
if (TreeIterForTag (tag, out iter))
(Model as TreeStore).Remove (ref iter);
}
}
private void HandleTagsAdded (object sender, DbItemEventArgs<Tag> args)
{
TreeIter iter = TreeIter.Zero;
foreach (Tag tag in args.Items) {
if (tag.Category != tag_store.RootCategory)
TreeIterForTag (tag.Category, out iter);
InsertInOrder (iter,
tag.Category.Name == tag_store.RootCategory.Name,
tag);
}
}
private void HandleTagsChanged (object sender, DbItemEventArgs<Tag> args)
{
TreeStore store = Model as TreeStore;
TreeIter iter, category_iter, parent_iter;
foreach (Tag tag in args.Items) {
TreeIterForTag (tag, out iter);
bool category_valid = TreeIterForTag(tag.Category, out category_iter);
bool parent_valid = Model.IterParent(out parent_iter, iter);
if ((category_valid && (category_iter.Equals (parent_iter))) || (!category_valid && !parent_valid)) {
// if we haven't been reparented
TreePath path = store.GetPath (iter);
store.EmitRowChanged (path, iter);
} else {
// It is a bit tougher. We need to do an annoying clone of structs...
CopyBranch (iter, category_iter, !category_valid, true);
store.Remove (ref iter);
}
}
}
void ExpandDefaults ()
{
int [] tags = FSpot.Preferences.Get<int []> (FSpot.Preferences.EXPANDED_TAGS);
if (tags == null) {
ExpandAll ();
return;
}
TreeIter [] iters = ModelIters ();
if (iters == null || iters.Length == 0 || tags.Length == 0)
return;
foreach (TreeIter iter in iters)
{
GLib.Value v = new GLib.Value ();
Model.GetValue (iter, IdColumn, ref v);
int tag_id = (int)(uint) v;
if (Array.IndexOf (tags, tag_id) > -1) {
ExpandRow (Model.GetPath (iter), false);
}
}
}
// Returns a flattened array of TreeIter's from the Model
TreeIter [] ModelIters ()
{
TreeIter root;
if (Model.GetIterFirst (out root))
{
return ModelIters (root, true).ToArray (typeof (TreeIter)) as TreeIter [];
}
return null;
}
// Returns ArrayList containing the root TreeIter and all TreeIters at root's level and
// descended from it
ArrayList ModelIters (TreeIter root, bool first)
{
ArrayList model_iters = new ArrayList (Model.IterNChildren ());
model_iters.Add (root);
// Append any children
TreeIter child;
if (Model.IterChildren (out child, root))
model_iters.AddRange (ModelIters (child, true));
// Append any siblings and their children
if (first) {
while (Model.IterNext (ref root)) {
model_iters.AddRange (ModelIters (root, false));
}
}
return model_iters;
}
public void SaveExpandDefaults ()
{
ArrayList expanded_tags = new ArrayList ();
TreeIter [] iters = ModelIters ();
if (iters == null)
return;
foreach (TreeIter iter in iters)
{
if (GetRowExpanded (Model.GetPath (iter))) {
GLib.Value v = new GLib.Value ();
Model.GetValue (iter, IdColumn, ref v);
expanded_tags.Add ((int)(uint) v);
}
}
#if GCONF_SHARP_2_18
FSpot.Preferences.Set ( FSpot.Preferences.EXPANDED_TAGS, (int []) expanded_tags.ToArray (typeof (int)));
#else
if (expanded_tags.Count == 0)
expanded_tags.Add (-1);
FSpot.Preferences.Set ( FSpot.Preferences.EXPANDED_TAGS,
(int []) expanded_tags.ToArray (typeof (int)));
#endif
}
public void EditSelectedTagName ()
{
TreePath [] rows = Selection.GetSelectedRows();
if (rows.Length != 1)
return;
//SetCursor (rows[0], NameColumn, true);
text_render.Editable = true;
text_render.Edited += HandleTagNameEdited;
SetCursor (rows[0], complete_column, true);
text_render.Editable = false;
}
public void HandleTagNameEdited (object sender, EditedArgs args)
{
args.RetVal = false;
TreeIter iter;
if (!Model.GetIterFromString (out iter, args.Path))
return;
GLib.Value value = new GLib.Value ();
Model.GetValue (iter, IdColumn, ref value);
uint tag_id = (uint) value;
Tag tag = tag_store.Get (tag_id) as Tag;
// Ignore if it hasn't changed
if (tag.Name == args.NewText)
return;
// Check that the tag doesn't already exist
if (String.Compare (args.NewText, tag.Name, true) != 0 &&
tag_store.GetTagByName (args.NewText) != null) {
HigMessageDialog md = new HigMessageDialog (App.Instance.Organizer.Window,
DialogFlags.DestroyWithParent,
MessageType.Warning, ButtonsType.Ok,
Catalog.GetString ("Error renaming tag"),
Catalog.GetString ("This name is already in use"));
md.Run ();
md.Destroy ();
this.GrabFocus ();
return;
}
tag.Name = args.NewText;
tag_store.Commit (tag, true);
text_render.Edited -= HandleTagNameEdited;
args.RetVal = true;
return;
}
private static TargetList tagSourceTargetList = new TargetList();
private static TargetList tagDestTargetList = new TargetList();
static TagSelectionWidget()
{
tagSourceTargetList.AddTargetEntry(DragDropTargets.TagListEntry);
tagDestTargetList.AddTargetEntry(DragDropTargets.PhotoListEntry);
tagDestTargetList.AddUriTargets((uint)DragDropTargets.TargetType.UriList);
tagDestTargetList.AddTargetEntry(DragDropTargets.TagListEntry);
}
CellRendererPixbuf pix_render;
TreeViewColumn complete_column;
CellRendererText text_render;
protected TagSelectionWidget (IntPtr raw) : base (raw) { }
// Constructor.
public TagSelectionWidget (TagStore tag_store)
: base (new TreeStore (typeof(uint), typeof(string)))
{
database = App.Instance.Database;
HeadersVisible = false;
complete_column = new TreeViewColumn ();
pix_render = new CellRendererPixbuf ();
complete_column.PackStart (pix_render, false);
complete_column.SetCellDataFunc (pix_render, new TreeCellDataFunc (IconDataFunc));
//complete_column.AddAttribute (pix_render, "pixbuf", OpenIconColumn);
//icon_column = AppendColumn ("icon",
//, new TreeCellDataFunc (IconDataFunc));
//icon_column = AppendColumn ("icon", new CellRendererPixbuf (), new TreeCellDataFunc (IconDataFunc));
text_render = new CellRendererText ();
complete_column.PackStart (text_render, true);
complete_column.SetCellDataFunc (text_render, new TreeCellDataFunc (NameDataFunc));
AppendColumn (complete_column);
this.tag_store = tag_store;
Update ();
ExpandDefaults ();
tag_store.ItemsAdded += HandleTagsAdded;
tag_store.ItemsRemoved += HandleTagsRemoved;
tag_store.ItemsChanged += HandleTagsChanged;
// TODO make the search find tags that are not currently expanded
EnableSearch = true;
SearchColumn = NameColumn;
// Transparent white
empty_pixbuf.Fill(0xffffff00);
/* set up drag and drop */
DragDataGet += HandleDragDataGet;
DragDrop += HandleDragDrop;
DragBegin += HandleDragBegin;
Gtk.Drag.SourceSet (this,
Gdk.ModifierType.Button1Mask | Gdk.ModifierType.Button3Mask,
(TargetEntry[])tagSourceTargetList,
DragAction.Copy | DragAction.Move);
DragDataReceived += HandleDragDataReceived;
DragMotion += HandleDragMotion;
Gtk.Drag.DestSet (this,
DestDefaults.All,
(TargetEntry[])tagDestTargetList,
DragAction.Copy | DragAction.Move);
}
void HandleDragBegin (object sender, DragBeginArgs args)
{
Tag [] tags = TagHighlight;
int len = tags.Length;
int size = 32;
int csize = size/2 + len * size / 2 + 2;
Pixbuf container = new Pixbuf (Gdk.Colorspace.Rgb, true, 8, csize, csize);
container.Fill (0x00000000);
bool use_icon = false;;
while (len-- > 0) {
Pixbuf thumbnail = tags[len].Icon;
if (thumbnail != null) {
Pixbuf small = PixbufUtils.ScaleToMaxSize (thumbnail, size, size);
int x = len * (size/2) + (size - small.Width)/2;
int y = len * (size/2) + (size - small.Height)/2;
small.Composite (container, x, y, small.Width, small.Height, x, y, 1.0, 1.0, Gdk.InterpType.Nearest, 0xff);
small.Dispose ();
use_icon = true;
}
}
if (use_icon)
Gtk.Drag.SetIconPixbuf (args.Context, container, 0, 0);
container.Dispose ();
}
void HandleDragDataGet (object sender, DragDataGetArgs args)
{
if (args.Info == DragDropTargets.TagListEntry.Info) {
args.SelectionData.SetTagsData (TagHighlight, args.Context.Targets[0]);
return;
}
}
void HandleDragDrop (object sender, DragDropArgs args)
{
args.RetVal = true;
}
public void HandleDragMotion (object o, DragMotionArgs args)
{
TreePath path;
TreeViewDropPosition position = TreeViewDropPosition.IntoOrAfter;
GetPathAtPos (args.X, args.Y, out path);
if (path == null)
return;
// Tags can be dropped before, after, or into another tag
if (args.Context.Targets[0].Name == "application/x-fspot-tags") {
Gdk.Rectangle rect = GetCellArea(path, Columns[0]);
double vpos = Math.Abs(rect.Y - args.Y) / (double)rect.Height;
if (vpos < 0.2) {
position = TreeViewDropPosition.Before;
} else if (vpos > 0.8) {
position = TreeViewDropPosition.After;
}
}
SetDragDestRow (path, position);
// Scroll if within 20 pixels of the top or bottom of the tag list
if (args.Y < 20)
Vadjustment.Value -= 30;
else if (((o as Gtk.Widget).Allocation.Height - args.Y) < 20)
Vadjustment.Value += 30;
}
public void HandleDragDataReceived (object o, DragDataReceivedArgs args)
{
TreePath path;
TreeViewDropPosition position;
if ( ! GetDestRowAtPos ((int)args.X, (int)args.Y, out path, out position))
return;
Tag tag = path == null ? null : TagByPath (path);
if (tag == null)
return;
if (args.Info == DragDropTargets.PhotoListEntry.Info) {
database.BeginTransaction ();
Photo[] photos = args.SelectionData.GetPhotosData ();
foreach (Photo photo in photos) {
if (photo == null)
continue;
photo.AddTag (tag);
database.Photos.Commit (photo);
// FIXME: AddTagExtendes from Mainwindow.cs does some tag-icon handling.
// this should be done here or completely located to the Tag-class.
}
database.CommitTransaction ();
// FIXME: this needs to be done somewhere:
//query_widget.PhotoTagsChanged (new Tag[] {tag});
return;
}
if (args.Info == (uint)DragDropTargets.TargetType.UriList) {
UriList list = args.SelectionData.GetUriListData ();
database.BeginTransaction ();
List<Photo> photos = new List<Photo> ();
foreach (var photo_uri in list) {
Photo photo = database.Photos.GetByUri (photo_uri);
// FIXME - at this point we should import the photo, and then continue
if (photo == null)
continue;
// FIXME this should really follow the AddTagsExtended path too
photo.AddTag (new Tag[] {tag});
photos.Add (photo);
}
database.Photos.Commit (photos.ToArray ());
database.CommitTransaction ();
// FIXME: this need to be done
//InvalidateViews (); // but it seems not to be needed. tags are updated through in IconView through PhotoChanged
return;
}
if (args.Info == DragDropTargets.TagListEntry.Info) {
Category parent;
if (position == TreeViewDropPosition.Before || position == TreeViewDropPosition.After) {
parent = tag.Category;
} else {
parent = tag as Category;
}
if (parent == null || TagHighlight.Length < 1) {
args.RetVal = false;
return;
}
int moved_count = 0;
Tag [] highlighted_tags = TagHighlight;
foreach (Tag child in TagHighlight) {
// FIXME with this reparenting via dnd, you cannot move a tag to root.
if (child != parent && child.Category != parent && !child.IsAncestorOf(parent)) {
child.Category = parent as Category;
// Saving changes will automatically cause the TreeView to be updated
database.Tags.Commit (child);
moved_count++;
}
}
// Reselect the same tags
TagHighlight = highlighted_tags;
args.RetVal = moved_count > 0;
return;
}
}
#if TEST_TAG_SELECTION_WIDGET
class Test {
private TagSelectionWidget selection_widget;
private void OnSelectionChanged ()
{
Log.Debug ("Selection changed:");
foreach (Tag t in selection_widget.TagSelection)
Log.DebugFormat ("\t{0}", t.Name);
}
private Test ()
{
const string path = "/tmp/TagSelectionTest.db";
try {
File.Delete (path);
} catch {}
Db db = new Db (path, true);
Category people_category = db.Tags.CreateCategory (null, "People");
db.Tags.CreateTag (people_category, "Anna");
db.Tags.CreateTag (people_category, "Ettore");
db.Tags.CreateTag (people_category, "Miggy");
db.Tags.CreateTag (people_category, "Nat");
Category places_category = db.Tags.CreateCategory (null, "Places");
db.Tags.CreateTag (places_category, "Milan");
db.Tags.CreateTag (places_category, "Boston");
Category exotic_category = db.Tags.CreateCategory (places_category, "Exotic");
db.Tags.CreateTag (exotic_category, "Bengalore");
db.Tags.CreateTag (exotic_category, "Manila");
db.Tags.CreateTag (exotic_category, "Tokyo");
selection_widget = new TagSelectionWidget (db.Tags);
selection_widget.SelectionChanged += new SelectionChangedHandler (OnSelectionChanged);
Window window = new Window (WindowType.Toplevel);
window.SetDefaultSize (400, 200);
ScrolledWindow scrolled = new ScrolledWindow (null, null);
scrolled.SetPolicy (PolicyType.Automatic, PolicyType.Automatic);
scrolled.Add (selection_widget);
window.Add (scrolled);
window.ShowAll ();
}
static private void Main (string [] args)
{
Program program = new Program ("TagSelectionWidgetTest", "0.0", Modules.UI, args);
Test test = new Test ();
program.Run ();
}
}
#endif
}
}
| |
using System;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Windows.Forms;
using EDEngineer.Localization;
using EDEngineer.Models.Utils;
using EDEngineer.Properties;
using Microsoft.WindowsAPICodePack.Dialogs;
using Newtonsoft.Json;
using Application = System.Windows.Application;
namespace EDEngineer.Utils.System
{
public static class Helpers
{
static Helpers()
{
blueprintsJson = ReadResource("blueprints");
releaseNotesJson = ReadResource("releaseNotes");
localizationJson = ReadResource("localization");
entryDatasJson = ReadResource("entryData");
equipmentsJson = ReadResource("equipment");
}
public static string ReadResource(string resource)
{
using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream($"EDEngineer.Resources.Data.{resource}.json"))
using (var reader = new StreamReader(stream))
{
return reader.ReadToEnd();
}
}
private static readonly string blueprintsJson;
private static readonly string releaseNotesJson;
private static readonly string localizationJson;
private static readonly string entryDatasJson;
private static readonly string equipmentsJson;
public static string GetBlueprintsJson()
{
return blueprintsJson;
}
public static string GetReleaseNotesJson()
{
return releaseNotesJson;
}
public static string GetLocalizationJson()
{
return localizationJson;
}
public static string GetEntryDatasJson()
{
return entryDatasJson;
}
public static string GetEquipmentsJson()
{
return equipmentsJson;
}
public static string RetrieveLogDirectory(bool forcePickFolder, string currentLogDirectory)
{
var translator = Languages.Instance;
string logDirectory = null;
if (!forcePickFolder)
{
logDirectory = Settings.Default.LogDirectory;
if (string.IsNullOrEmpty(logDirectory))
{
var userProfile = Environment.GetEnvironmentVariable("USERPROFILE");
if (userProfile != null)
{
logDirectory = Path.Combine(userProfile, @"saved games\Frontier Developments\Elite Dangerous");
}
}
}
if (forcePickFolder || logDirectory == null || !Directory.Exists(logDirectory))
{
var dialog = new CommonOpenFileDialog
{
Title = forcePickFolder ?
translator.Translate("Select a new log directory") :
translator.Translate("Couldn't find the log folder for elite, you'll have to specify it"),
AllowNonFileSystemItems = false,
Multiselect = false,
IsFolderPicker = true,
EnsurePathExists = true
};
if (forcePickFolder && !string.IsNullOrEmpty(currentLogDirectory))
{
dialog.InitialDirectory = currentLogDirectory;
}
var pickFolderResult = dialog.ShowDialog();
if (pickFolderResult == CommonFileDialogResult.Ok)
{
if (!Directory.GetFiles(dialog.FileName).Any(f => Path.GetFileName(f).StartsWith("Journal.") &&
Path.GetFileName(f).EndsWith(".log")))
{
var result =
MessageBox.Show(
translator.Translate("Selected directory doesn't seem to contain any log file ; are you sure?"),
translator.Translate("Warning"), MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Warning);
if (result == DialogResult.Retry)
{
RetrieveLogDirectory(forcePickFolder, null);
}
if (result == DialogResult.Abort)
{
if (forcePickFolder)
{
return currentLogDirectory;
}
Application.Current.Shutdown();
}
}
logDirectory = dialog.FileName;
}
else if (forcePickFolder)
{
return currentLogDirectory;
}
else
{
MessageBox.Show(translator.Translate("You did not select a log directory, EDEngineer won't be able to track changes. You can still use the app manually though."),
translator.Translate("Warning"), MessageBoxButtons.OK, MessageBoxIcon.Warning);
logDirectory = @"\" + translator.Translate("No folder in use ; click to change");
}
}
Settings.Default.LogDirectory = logDirectory;
Settings.Default.Save();
return logDirectory;
}
public static bool TryRetrieveShoppingList(out StringCollection result)
{
var translator = Languages.Instance;
var dialog = new CommonOpenFileDialog
{
Title = translator.Translate("Select a shopping list to import"),
AllowNonFileSystemItems = false,
Multiselect = false,
IsFolderPicker = false,
EnsurePathExists = true,
DefaultExtension = ".shoppingList",
DefaultDirectory = IO.GetManualChangesDirectory()
};
dialog.Filters.Add(new CommonFileDialogFilter("Shopping List Files (*.shoppingList)", ".shoppingList"));
dialog.Filters.Add(new CommonFileDialogFilter("Json Files (*.json)", ".json"));
dialog.Filters.Add(new CommonFileDialogFilter("All Files (*.*)", ".*"));
var pickFileResult = dialog.ShowDialog();
if (pickFileResult == CommonFileDialogResult.Ok)
{
if (File.Exists(dialog.FileName))
{
var contents = File.ReadAllText(dialog.FileName);
result = JsonConvert.DeserializeObject<StringCollection>(contents);
return true;
}
}
result = null;
return false;
}
public static void SaveShoppingList(string commanderName)
{
var contents = JsonConvert.SerializeObject(Settings.Default.ShoppingList.Cast<string>().Where(x => x != null && x.StartsWith(commanderName + ":")));
var translator = Languages.Instance;
var dialog = new CommonSaveFileDialog
{
Title = translator.Translate("Select a shopping list file to export over, or enter new name for a new file"),
EnsurePathExists = true,
DefaultDirectory = IO.GetManualChangesDirectory(),
DefaultFileName = "engineering.shoppingList",
DefaultExtension = ".shoppingList",
OverwritePrompt = true
};
dialog.Filters.Add(new CommonFileDialogFilter("Shopping List Files (*.shoppingList)", ".shoppingList"));
var pickFileResult = dialog.ShowDialog();
if (pickFileResult == CommonFileDialogResult.Ok)
{
File.WriteAllText(dialog.FileName, contents);
}
}
}
}
| |
// 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.Globalization;
using System.Linq;
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Audio.Sample;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.OpenGL.Textures;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Graphics.Textures;
using osu.Game.Audio;
using osu.Game.Graphics;
using osu.Game.Graphics.Sprites;
using osu.Game.Skinning;
using osuTK;
using osuTK.Graphics;
namespace osu.Game.Tests.Visual.Gameplay
{
public class TestSceneSkinnableDrawable : OsuTestScene
{
[Test]
public void TestConfineScaleDown()
{
FillFlowContainer<ExposedSkinnableDrawable> fill = null;
AddStep("setup layout larger source", () =>
{
Child = new SkinProvidingContainer(new SizedSource(50))
{
RelativeSizeAxes = Axes.Both,
Child = fill = new FillFlowContainer<ExposedSkinnableDrawable>
{
Size = new Vector2(30),
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Spacing = new Vector2(10),
Children = new[]
{
new ExposedSkinnableDrawable("default", _ => new DefaultBox()),
new ExposedSkinnableDrawable("available", _ => new DefaultBox()),
new ExposedSkinnableDrawable("available", _ => new DefaultBox(), ConfineMode.NoScaling)
}
},
};
});
AddAssert("check sizes", () => fill.Children.Select(c => c.Drawable.DrawWidth).SequenceEqual(new float[] { 30, 30, 50 }));
AddStep("adjust scale", () => fill.Scale = new Vector2(2));
AddAssert("check sizes unchanged by scale", () => fill.Children.Select(c => c.Drawable.DrawWidth).SequenceEqual(new float[] { 30, 30, 50 }));
}
[Test]
public void TestConfineScaleUp()
{
FillFlowContainer<ExposedSkinnableDrawable> fill = null;
AddStep("setup layout larger source", () =>
{
Child = new SkinProvidingContainer(new SizedSource(30))
{
RelativeSizeAxes = Axes.Both,
Child = fill = new FillFlowContainer<ExposedSkinnableDrawable>
{
Size = new Vector2(50),
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Spacing = new Vector2(10),
Children = new[]
{
new ExposedSkinnableDrawable("default", _ => new DefaultBox()),
new ExposedSkinnableDrawable("available", _ => new DefaultBox()),
new ExposedSkinnableDrawable("available", _ => new DefaultBox(), ConfineMode.NoScaling)
}
},
};
});
AddAssert("check sizes", () => fill.Children.Select(c => c.Drawable.DrawWidth).SequenceEqual(new float[] { 50, 50, 30 }));
AddStep("adjust scale", () => fill.Scale = new Vector2(2));
AddAssert("check sizes unchanged by scale", () => fill.Children.Select(c => c.Drawable.DrawWidth).SequenceEqual(new float[] { 50, 50, 30 }));
}
[Test]
public void TestInitialLoad()
{
var secondarySource = new SecondarySource();
SkinConsumer consumer = null;
AddStep("setup layout", () =>
{
Child = new SkinSourceContainer
{
RelativeSizeAxes = Axes.Both,
Child = new SkinProvidingContainer(secondarySource)
{
RelativeSizeAxes = Axes.Both,
Child = consumer = new SkinConsumer("test", name => new NamedBox("Default Implementation"))
}
};
});
AddAssert("consumer using override source", () => consumer.Drawable is SecondarySourceBox);
AddAssert("skinchanged only called once", () => consumer.SkinChangedCount == 1);
}
[Test]
public void TestOverride()
{
var secondarySource = new SecondarySource();
SkinConsumer consumer = null;
Container target = null;
AddStep("setup layout", () =>
{
Child = new SkinSourceContainer
{
RelativeSizeAxes = Axes.Both,
Child = target = new SkinProvidingContainer(secondarySource)
{
RelativeSizeAxes = Axes.Both,
}
};
});
AddStep("add permissive", () => target.Add(consumer = new SkinConsumer("test", name => new NamedBox("Default Implementation"))));
AddAssert("consumer using override source", () => consumer.Drawable is SecondarySourceBox);
AddAssert("skinchanged only called once", () => consumer.SkinChangedCount == 1);
}
[Test]
public void TestSwitchOff()
{
SkinConsumer consumer = null;
SwitchableSkinProvidingContainer target = null;
AddStep("setup layout", () =>
{
Child = new SkinSourceContainer
{
RelativeSizeAxes = Axes.Both,
Child = target = new SwitchableSkinProvidingContainer(new SecondarySource())
{
RelativeSizeAxes = Axes.Both,
}
};
});
AddStep("add permissive", () => target.Add(consumer = new SkinConsumer("test", name => new NamedBox("Default Implementation"))));
AddAssert("consumer using override source", () => consumer.Drawable is SecondarySourceBox);
AddStep("disable", () => target.Disable());
AddAssert("consumer using base source", () => consumer.Drawable is BaseSourceBox);
}
private class SwitchableSkinProvidingContainer : SkinProvidingContainer
{
private bool allow = true;
protected override bool AllowDrawableLookup(ISkinComponent component) => allow;
public void Disable()
{
allow = false;
TriggerSourceChanged();
}
public SwitchableSkinProvidingContainer(ISkin skin)
: base(skin)
{
}
}
private class ExposedSkinnableDrawable : SkinnableDrawable
{
public new Drawable Drawable => base.Drawable;
public ExposedSkinnableDrawable(string name, Func<ISkinComponent, Drawable> defaultImplementation, ConfineMode confineMode = ConfineMode.ScaleToFit)
: base(new TestSkinComponent(name), defaultImplementation, confineMode)
{
}
}
private class DefaultBox : DrawWidthBox
{
public DefaultBox()
{
RelativeSizeAxes = Axes.Both;
}
}
private class DrawWidthBox : Container
{
private readonly OsuSpriteText text;
public DrawWidthBox()
{
Children = new Drawable[]
{
new Box
{
Colour = Color4.Gray,
RelativeSizeAxes = Axes.Both,
},
text = new OsuSpriteText
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
}
};
}
protected override void UpdateAfterChildren()
{
base.UpdateAfterChildren();
text.Text = DrawWidth.ToString(CultureInfo.InvariantCulture);
}
}
private class NamedBox : Container
{
public NamedBox(string name)
{
Children = new Drawable[]
{
new Box
{
Colour = Color4.Black,
RelativeSizeAxes = Axes.Both,
},
new OsuSpriteText
{
Font = OsuFont.Default.With(size: 40),
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Text = name
}
};
}
}
private class SkinConsumer : SkinnableDrawable
{
public new Drawable Drawable => base.Drawable;
public int SkinChangedCount { get; private set; }
public SkinConsumer(string name, Func<ISkinComponent, Drawable> defaultImplementation)
: base(new TestSkinComponent(name), defaultImplementation)
{
}
protected override void SkinChanged(ISkinSource skin)
{
base.SkinChanged(skin);
SkinChangedCount++;
}
}
private class BaseSourceBox : NamedBox
{
public BaseSourceBox()
: base("Base Source")
{
}
}
private class SecondarySourceBox : NamedBox
{
public SecondarySourceBox()
: base("Secondary Source")
{
}
}
private class SizedSource : ISkin
{
private readonly float size;
public SizedSource(float size)
{
this.size = size;
}
public Drawable GetDrawableComponent(ISkinComponent componentName) =>
componentName.LookupName == "available"
? new DrawWidthBox
{
Colour = Color4.Yellow,
Size = new Vector2(size)
}
: null;
public Texture GetTexture(string componentName, WrapMode wrapModeS, WrapMode wrapModeT) => throw new NotImplementedException();
public ISample GetSample(ISampleInfo sampleInfo) => throw new NotImplementedException();
public IBindable<TValue> GetConfig<TLookup, TValue>(TLookup lookup) => throw new NotImplementedException();
}
private class SecondarySource : ISkin
{
public Drawable GetDrawableComponent(ISkinComponent componentName) => new SecondarySourceBox();
public Texture GetTexture(string componentName, WrapMode wrapModeS, WrapMode wrapModeT) => throw new NotImplementedException();
public ISample GetSample(ISampleInfo sampleInfo) => throw new NotImplementedException();
public IBindable<TValue> GetConfig<TLookup, TValue>(TLookup lookup) => throw new NotImplementedException();
}
[Cached(typeof(ISkinSource))]
private class SkinSourceContainer : Container, ISkinSource
{
public Drawable GetDrawableComponent(ISkinComponent componentName) => new BaseSourceBox();
public Texture GetTexture(string componentName, WrapMode wrapModeS, WrapMode wrapModeT) => throw new NotImplementedException();
public ISample GetSample(ISampleInfo sampleInfo) => throw new NotImplementedException();
public IBindable<TValue> GetConfig<TLookup, TValue>(TLookup lookup) => throw new NotImplementedException();
public ISkin FindProvider(Func<ISkin, bool> lookupFunction) => throw new NotImplementedException();
public IEnumerable<ISkin> AllSources => throw new NotImplementedException();
public event Action SourceChanged
{
add { }
remove { }
}
}
private class TestSkinComponent : ISkinComponent
{
public TestSkinComponent(string name)
{
LookupName = name;
}
public string ComponentGroup => string.Empty;
public string LookupName { get; }
}
}
}
| |
using System;
using System.Data;
using System.Data.SqlClient;
using DbUp;
using DbUp.Builder;
using DbUp.Engine.Output;
using DbUp.Engine.Transactions;
using DbUp.Support.SqlServer;
/// <summary>
/// Configuration extension methods for SQL Server.
/// </summary>
// NOTE: DO NOT MOVE THIS TO A NAMESPACE
// Since the class just contains extension methods, we leave it in the root so that it is always discovered
// and people don't have to manually add using statements.
// ReSharper disable CheckNamespace
public static class SqlServerExtensions
// ReSharper restore CheckNamespace
{
/// <summary>
/// Creates an upgrader for SQL Server databases.
/// </summary>
/// <param name="supported">Fluent helper type.</param>
/// <param name="connectionString">The connection string.</param>
/// <returns>
/// A builder for a database upgrader designed for SQL Server databases.
/// </returns>
public static UpgradeEngineBuilder SqlDatabase(this SupportedDatabases supported, string connectionString)
{
return SqlDatabase(supported, connectionString, null);
}
/// <summary>
/// Creates an upgrader for SQL Server databases.
/// </summary>
/// <param name="supported">Fluent helper type.</param>
/// <param name="connectionString">The connection string.</param>
/// <param name="schema">The SQL schema name to use. Defaults to 'dbo'.</param>
/// <returns>
/// A builder for a database upgrader designed for SQL Server databases.
/// </returns>
public static UpgradeEngineBuilder SqlDatabase(this SupportedDatabases supported, string connectionString, string schema)
{
return SqlDatabase(new SqlConnectionManager(connectionString), schema);
}
/// <summary>
/// Creates an upgrader for SQL Server databases.
/// </summary>
/// <param name="supported">Fluent helper type.</param>
/// <param name="connectionFactory">The connection factory.</param>
/// <returns>
/// A builder for a database upgrader designed for SQL Server databases.
/// </returns>
[Obsolete("Pass connection string instead, then use .WithTransaction() and .WithTransactionPerScript() to manage connection behaviour")]
public static UpgradeEngineBuilder SqlDatabase(this SupportedDatabases supported, Func<IDbConnection> connectionFactory)
{
return SqlDatabase(supported, connectionFactory, null);
}
/// <summary>
/// Creates an upgrader for SQL Server databases.
/// </summary>
/// <param name="supported">Fluent helper type.</param>
/// <param name="connectionFactory">The connection factory.</param>
/// <param name="schema">The SQL schema name to use. Defaults to 'dbo'.</param>
/// <returns>
/// A builder for a database upgrader designed for SQL Server databases.
/// </returns>
[Obsolete("Pass connection string instead, then use .WithTransaction() and .WithTransactionPerScript() to manage connection behaviour")]
public static UpgradeEngineBuilder SqlDatabase(this SupportedDatabases supported, Func<IDbConnection> connectionFactory, string schema)
{
return SqlDatabase(new LegacySqlConnectionManager(connectionFactory), schema);
}
/// <summary>
///
/// </summary>
/// <param name="connectionManager"></param>
/// <param name="schema"></param>
/// <returns></returns>
private static UpgradeEngineBuilder SqlDatabase(IConnectionManager connectionManager, string schema)
{
var builder = new UpgradeEngineBuilder();
builder.Configure(c => c.ConnectionManager = connectionManager);
builder.Configure(c => c.ScriptExecutor = new SqlScriptExecutor(() => c.ConnectionManager, () => c.Log, schema, () => c.VariablesEnabled, c.ScriptPreprocessors));
builder.Configure(c => c.Journal = new SqlTableJournal(() => c.ConnectionManager, () => c.Log, schema, "SchemaVersions"));
return builder;
}
/// <summary>
/// Tracks the list of executed scripts in a SQL Server table.
/// </summary>
/// <param name="builder">The builder.</param>
/// <param name="schema">The schema.</param>
/// <param name="table">The table.</param>
/// <returns></returns>
public static UpgradeEngineBuilder JournalToSqlTable(this UpgradeEngineBuilder builder, string schema, string table)
{
builder.Configure(c => c.Journal = new SqlTableJournal(() => c.ConnectionManager, () => c.Log, schema, table));
return builder;
}
/// <summary>
/// Ensures that the database specified in the connection string exists.
/// </summary>
/// <param name="supported">Fluent helper type.</param>
/// <param name="connectionString">The connection string.</param>
/// <returns></returns>
public static void SqlDatabase(this SupportedDatabasesForEnsureDatabase supported, string connectionString)
{
SqlDatabase(supported, connectionString, new ConsoleUpgradeLog());
}
/// <summary>
/// Ensures that the database specified in the connection string exists.
/// </summary>
/// <param name="supported">Fluent helper type.</param>
/// <param name="connectionString">The connection string.</param>
/// <param name="commandTimeout">Use this to set the command time out for creating a database in case you're encountering a time out in this operation.</param>
/// <returns></returns>
public static void SqlDatabase(this SupportedDatabasesForEnsureDatabase supported, string connectionString, int commandTimeout)
{
SqlDatabase(supported, connectionString, new ConsoleUpgradeLog(), commandTimeout);
}
/// <summary>
/// Ensures that the database specified in the connection string exists.
/// </summary>
/// <param name="supported">Fluent helper type.</param>
/// <param name="connectionString">The connection string.</param>
/// <param name="logger">The <see cref="DbUp.Engine.Output.IUpgradeLog"/> used to record actions.</param>
/// <param name="timeout">Use this to set the command time out for creating a database in case you're encountering a time out in this operation.</param>
/// <returns></returns>
public static void SqlDatabase(this SupportedDatabasesForEnsureDatabase supported, string connectionString, IUpgradeLog logger, int timeout = -1)
{
if (supported == null) throw new ArgumentNullException("supported");
if (string.IsNullOrEmpty(connectionString) || connectionString.Trim() == string.Empty)
{
throw new ArgumentNullException("connectionString");
}
if (logger == null) throw new ArgumentNullException("logger");
var masterConnectionStringBuilder = new SqlConnectionStringBuilder(connectionString);
var databaseName = masterConnectionStringBuilder.InitialCatalog;
if (string.IsNullOrEmpty(databaseName) || databaseName.Trim() == string.Empty)
{
throw new InvalidOperationException("The connection string does not specify a database name.");
}
masterConnectionStringBuilder.InitialCatalog = "master";
var logMasterConnectionStringBuilder = new SqlConnectionStringBuilder(masterConnectionStringBuilder.ConnectionString)
{
Password = String.Empty.PadRight(masterConnectionStringBuilder.Password.Length, '*')
};
logger.WriteInformation("Master ConnectionString => {0}", logMasterConnectionStringBuilder.ConnectionString);
using (var connection = new SqlConnection(masterConnectionStringBuilder.ConnectionString))
{
connection.Open();
var sqlCommandText = string.Format
(
@"SELECT TOP 1 case WHEN dbid IS NOT NULL THEN 1 ELSE 0 end FROM sys.sysdatabases WHERE name = '{0}';",
databaseName
);
// check to see if the database already exists..
using (var command = new SqlCommand(sqlCommandText, connection)
{
CommandType = CommandType.Text
})
{
var results = (int?)command.ExecuteScalar();
// if the database exists, we're done here...
if (results.HasValue && results.Value == 1)
{
return;
}
}
sqlCommandText = string.Format
(
@"create database [{0}];",
databaseName
);
// Create the database...
using (var command = new SqlCommand(sqlCommandText, connection)
{
CommandType = CommandType.Text
})
{
if (timeout >= 0)
{
command.CommandTimeout = timeout;
}
command.ExecuteNonQuery();
}
logger.WriteInformation(@"Created database {0}", databaseName);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Orchard.Caching;
using Orchard.ContentManagement;
using Orchard.Environment.Extensions.Models;
using Orchard.FileSystems.WebSite;
using Orchard.Localization;
using Orchard.Logging;
using Orchard.Utility.Extensions;
using Orchard.Exceptions;
namespace Orchard.Environment.Extensions.Folders {
public class ExtensionHarvester : IExtensionHarvester {
private const string NameSection = "name";
private const string PathSection = "path";
private const string DescriptionSection = "description";
private const string VersionSection = "version";
private const string OrchardVersionSection = "orchardversion";
private const string AuthorSection = "author";
private const string WebsiteSection = "website";
private const string TagsSection = "tags";
private const string AntiForgerySection = "antiforgery";
private const string ZonesSection = "zones";
private const string BaseThemeSection = "basetheme";
private const string DependenciesSection = "dependencies";
private const string CategorySection = "category";
private const string FeatureDescriptionSection = "featuredescription";
private const string FeatureNameSection = "featurename";
private const string PrioritySection = "priority";
private const string FeaturesSection = "features";
private const string SessionStateSection = "sessionstate";
private const string LifecycleStatusSection = "lifecyclestatus";
private readonly ICacheManager _cacheManager;
private readonly IWebSiteFolder _webSiteFolder;
private readonly ICriticalErrorProvider _criticalErrorProvider;
public ExtensionHarvester(ICacheManager cacheManager, IWebSiteFolder webSiteFolder, ICriticalErrorProvider criticalErrorProvider) {
_cacheManager = cacheManager;
_webSiteFolder = webSiteFolder;
_criticalErrorProvider = criticalErrorProvider;
Logger = NullLogger.Instance;
T = NullLocalizer.Instance;
}
public Localizer T { get; set; }
public ILogger Logger { get; set; }
public bool DisableMonitoring { get; set; }
public IEnumerable<ExtensionDescriptor> HarvestExtensions(IEnumerable<string> paths, string extensionType, string manifestName, bool manifestIsOptional) {
return paths
.SelectMany(path => HarvestExtensions(path, extensionType, manifestName, manifestIsOptional))
.ToList();
}
private IEnumerable<ExtensionDescriptor> HarvestExtensions(string path, string extensionType, string manifestName, bool manifestIsOptional) {
string key = string.Format("{0}-{1}-{2}", path, manifestName, extensionType);
return _cacheManager.Get(key, true, ctx => {
if (!DisableMonitoring) {
Logger.Debug("Monitoring virtual path \"{0}\"", path);
ctx.Monitor(_webSiteFolder.WhenPathChanges(path));
}
return AvailableExtensionsInFolder(path, extensionType, manifestName, manifestIsOptional).ToReadOnlyCollection();
});
}
private List<ExtensionDescriptor> AvailableExtensionsInFolder(string path, string extensionType, string manifestName, bool manifestIsOptional) {
Logger.Information("Start looking for extensions in '{0}'...", path);
var subfolderPaths = _webSiteFolder.ListDirectories(path);
var localList = new List<ExtensionDescriptor>();
foreach (var subfolderPath in subfolderPaths) {
var extensionId = Path.GetFileName(subfolderPath.TrimEnd('/', '\\'));
var manifestPath = Path.Combine(subfolderPath, manifestName);
try {
var descriptor = GetExtensionDescriptor(path, extensionId, extensionType, manifestPath, manifestIsOptional);
if (descriptor == null)
continue;
if (descriptor.Path != null && !descriptor.Path.IsValidUrlSegment()) {
Logger.Error("The module '{0}' could not be loaded because it has an invalid Path ({1}). It was ignored. The Path if specified must be a valid URL segment. The best bet is to stick with letters and numbers with no spaces.",
extensionId,
descriptor.Path);
_criticalErrorProvider.RegisterErrorMessage(T("The extension '{0}' could not be loaded because it has an invalid Path ({1}). It was ignored. The Path if specified must be a valid URL segment. The best bet is to stick with letters and numbers with no spaces.",
extensionId,
descriptor.Path));
continue;
}
if (descriptor.Path == null) {
descriptor.Path = descriptor.Name.IsValidUrlSegment()
? descriptor.Name
: descriptor.Id;
}
localList.Add(descriptor);
}
catch (Exception ex) {
// Ignore invalid module manifests
if (ex.IsFatal()) {
throw;
}
Logger.Error(ex, "The module '{0}' could not be loaded. It was ignored.", extensionId);
_criticalErrorProvider.RegisterErrorMessage(T("The extension '{0}' manifest could not be loaded. It was ignored.", extensionId));
}
}
Logger.Information("Done looking for extensions in '{0}': {1}", path, string.Join(", ", localList.Select(d => d.Id)));
return localList;
}
public static ExtensionDescriptor GetDescriptorForExtension(string locationPath, string extensionId, string extensionType, string manifestText) {
Dictionary<string, string> manifest = ParseManifest(manifestText);
var extensionDescriptor = new ExtensionDescriptor {
Location = locationPath,
Id = extensionId,
ExtensionType = extensionType,
Name = GetValue(manifest, NameSection) ?? extensionId,
Path = GetValue(manifest, PathSection),
Description = GetValue(manifest, DescriptionSection),
Version = GetValue(manifest, VersionSection),
OrchardVersion = GetValue(manifest, OrchardVersionSection),
Author = GetValue(manifest, AuthorSection),
WebSite = GetValue(manifest, WebsiteSection),
Tags = GetValue(manifest, TagsSection),
AntiForgery = GetValue(manifest, AntiForgerySection),
Zones = GetValue(manifest, ZonesSection),
BaseTheme = GetValue(manifest, BaseThemeSection),
SessionState = GetValue(manifest, SessionStateSection),
LifecycleStatus = GetValue(manifest, LifecycleStatusSection, LifecycleStatus.Production)
};
extensionDescriptor.Features = GetFeaturesForExtension(manifest, extensionDescriptor);
return extensionDescriptor;
}
private ExtensionDescriptor GetExtensionDescriptor(string locationPath, string extensionId, string extensionType, string manifestPath, bool manifestIsOptional) {
return _cacheManager.Get(manifestPath, true, context => {
if (!DisableMonitoring) {
Logger.Debug("Monitoring virtual path \"{0}\"", manifestPath);
context.Monitor(_webSiteFolder.WhenPathChanges(manifestPath));
}
var manifestText = _webSiteFolder.ReadFile(manifestPath);
if (manifestText == null) {
if (manifestIsOptional) {
manifestText = string.Format("Id: {0}", extensionId);
}
else {
return null;
}
}
return GetDescriptorForExtension(locationPath, extensionId, extensionType, manifestText);
});
}
private static Dictionary<string, string> ParseManifest(string manifestText) {
var manifest = new Dictionary<string, string>();
using (StringReader reader = new StringReader(manifestText)) {
string line;
while ((line = reader.ReadLine()) != null) {
string[] field = line.Split(new[] { ":" }, 2, StringSplitOptions.None);
int fieldLength = field.Length;
if (fieldLength != 2)
continue;
for (int i = 0; i < fieldLength; i++) {
field[i] = field[i].Trim();
}
switch (field[0].ToLowerInvariant()) {
case NameSection:
manifest.Add(NameSection, field[1]);
break;
case PathSection:
manifest.Add(PathSection, field[1]);
break;
case DescriptionSection:
manifest.Add(DescriptionSection, field[1]);
break;
case VersionSection:
manifest.Add(VersionSection, field[1]);
break;
case OrchardVersionSection:
manifest.Add(OrchardVersionSection, field[1]);
break;
case AuthorSection:
manifest.Add(AuthorSection, field[1]);
break;
case WebsiteSection:
manifest.Add(WebsiteSection, field[1]);
break;
case TagsSection:
manifest.Add(TagsSection, field[1]);
break;
case AntiForgerySection:
manifest.Add(AntiForgerySection, field[1]);
break;
case ZonesSection:
manifest.Add(ZonesSection, field[1]);
break;
case BaseThemeSection:
manifest.Add(BaseThemeSection, field[1]);
break;
case DependenciesSection:
manifest.Add(DependenciesSection, field[1]);
break;
case CategorySection:
manifest.Add(CategorySection, field[1]);
break;
case FeatureDescriptionSection:
manifest.Add(FeatureDescriptionSection, field[1]);
break;
case FeatureNameSection:
manifest.Add(FeatureNameSection, field[1]);
break;
case PrioritySection:
manifest.Add(PrioritySection, field[1]);
break;
case SessionStateSection:
manifest.Add(SessionStateSection, field[1]);
break;
case LifecycleStatusSection:
manifest.Add(LifecycleStatusSection, field[1]);
break;
case FeaturesSection:
manifest.Add(FeaturesSection, reader.ReadToEnd());
break;
}
}
}
return manifest;
}
private static IEnumerable<FeatureDescriptor> GetFeaturesForExtension(IDictionary<string, string> manifest, ExtensionDescriptor extensionDescriptor) {
var featureDescriptors = new List<FeatureDescriptor>();
// Default feature
FeatureDescriptor defaultFeature = new FeatureDescriptor {
Id = extensionDescriptor.Id,
Name = GetValue(manifest, FeatureNameSection) ?? extensionDescriptor.Name,
Priority = GetValue(manifest, PrioritySection) != null ? int.Parse(GetValue(manifest, PrioritySection)) : 0,
Description = GetValue(manifest, FeatureDescriptionSection) ?? GetValue(manifest, DescriptionSection) ?? string.Empty,
Dependencies = ParseFeatureDependenciesEntry(GetValue(manifest, DependenciesSection)),
Extension = extensionDescriptor,
Category = GetValue(manifest, CategorySection)
};
featureDescriptors.Add(defaultFeature);
// Remaining features
string featuresText = GetValue(manifest, FeaturesSection);
if (featuresText != null) {
FeatureDescriptor featureDescriptor = null;
using (StringReader reader = new StringReader(featuresText)) {
string line;
while ((line = reader.ReadLine()) != null) {
if (IsFeatureDeclaration(line)) {
if (featureDescriptor != null) {
if (!featureDescriptor.Equals(defaultFeature)) {
featureDescriptors.Add(featureDescriptor);
}
featureDescriptor = null;
}
string[] featureDeclaration = line.Split(new[] { ":" }, StringSplitOptions.RemoveEmptyEntries);
string featureDescriptorId = featureDeclaration[0].Trim();
if (String.Equals(featureDescriptorId, extensionDescriptor.Id, StringComparison.OrdinalIgnoreCase)) {
featureDescriptor = defaultFeature;
featureDescriptor.Name = extensionDescriptor.Name;
}
else {
featureDescriptor = new FeatureDescriptor {
Id = featureDescriptorId,
Extension = extensionDescriptor
};
}
}
else if (IsFeatureFieldDeclaration(line)) {
if (featureDescriptor != null) {
string[] featureField = line.Split(new[] { ":" }, 2, StringSplitOptions.None);
int featureFieldLength = featureField.Length;
if (featureFieldLength != 2)
continue;
for (int i = 0; i < featureFieldLength; i++) {
featureField[i] = featureField[i].Trim();
}
switch (featureField[0].ToLowerInvariant()) {
case NameSection:
featureDescriptor.Name = featureField[1];
break;
case DescriptionSection:
featureDescriptor.Description = featureField[1];
break;
case CategorySection:
featureDescriptor.Category = featureField[1];
break;
case PrioritySection:
featureDescriptor.Priority = int.Parse(featureField[1]);
break;
case DependenciesSection:
featureDescriptor.Dependencies = ParseFeatureDependenciesEntry(featureField[1]);
break;
}
}
else {
string message = string.Format("The line {0} in manifest for extension {1} was ignored", line, extensionDescriptor.Id);
throw new ArgumentException(message);
}
}
else {
string message = string.Format("The line {0} in manifest for extension {1} was ignored", line, extensionDescriptor.Id);
throw new ArgumentException(message);
}
}
if (featureDescriptor != null && !featureDescriptor.Equals(defaultFeature))
featureDescriptors.Add(featureDescriptor);
}
}
return featureDescriptors;
}
private static bool IsFeatureFieldDeclaration(string line) {
if (line.StartsWith("\t\t") ||
line.StartsWith("\t ") ||
line.StartsWith(" ") ||
line.StartsWith(" \t"))
return true;
return false;
}
private static bool IsFeatureDeclaration(string line) {
int lineLength = line.Length;
if (line.StartsWith("\t") && lineLength >= 2) {
return !Char.IsWhiteSpace(line[1]);
}
if (line.StartsWith(" ") && lineLength >= 5)
return !Char.IsWhiteSpace(line[4]);
return false;
}
private static IEnumerable<string> ParseFeatureDependenciesEntry(string dependenciesEntry) {
if (string.IsNullOrEmpty(dependenciesEntry))
return Enumerable.Empty<string>();
var dependencies = new List<string>();
foreach (var s in dependenciesEntry.Split(',')) {
dependencies.Add(s.Trim());
}
return dependencies;
}
private static string GetValue(IDictionary<string, string> fields, string key) {
string value;
return fields.TryGetValue(key, out value) ? value : null;
}
private static T GetValue<T>(IDictionary<string, string> fields, string key, T defaultValue = default(T)) {
var value = GetValue(fields, key);
return String.IsNullOrWhiteSpace(value) ? defaultValue : XmlHelper.Parse<T>(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.Buffers;
using System.Runtime.CompilerServices;
using System.Collections.Generic;
using System.Diagnostics;
using Internal.Runtime.CompilerServices;
using System.Diagnostics.CodeAnalysis;
namespace System.Runtime.InteropServices
{
/// <summary>
/// Provides a collection of methods for interoperating with <see cref="Memory{T}"/>, <see cref="ReadOnlyMemory{T}"/>,
/// <see cref="Span{T}"/>, and <see cref="ReadOnlySpan{T}"/>.
/// </summary>
public static class MemoryMarshal
{
/// <summary>
/// Casts a Span of one primitive type <typeparamref name="T"/> to Span of bytes.
/// That type may not contain pointers or references. This is checked at runtime in order to preserve type safety.
/// </summary>
/// <param name="span">The source slice, of type <typeparamref name="T"/>.</param>
/// <exception cref="System.ArgumentException">
/// Thrown when <typeparamref name="T"/> contains pointers.
/// </exception>
/// <exception cref="System.OverflowException">
/// Thrown if the Length property of the new Span would exceed int.MaxValue.
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Span<byte> AsBytes<T>(Span<T> span)
where T : struct
{
if (RuntimeHelpers.IsReferenceOrContainsReferences<T>())
ThrowHelper.ThrowInvalidTypeWithPointersNotSupported(typeof(T));
return new Span<byte>(
ref Unsafe.As<T, byte>(ref GetReference(span)),
checked(span.Length * Unsafe.SizeOf<T>()));
}
/// <summary>
/// Casts a ReadOnlySpan of one primitive type <typeparamref name="T"/> to ReadOnlySpan of bytes.
/// That type may not contain pointers or references. This is checked at runtime in order to preserve type safety.
/// </summary>
/// <param name="span">The source slice, of type <typeparamref name="T"/>.</param>
/// <exception cref="System.ArgumentException">
/// Thrown when <typeparamref name="T"/> contains pointers.
/// </exception>
/// <exception cref="System.OverflowException">
/// Thrown if the Length property of the new Span would exceed int.MaxValue.
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ReadOnlySpan<byte> AsBytes<T>(ReadOnlySpan<T> span)
where T : struct
{
if (RuntimeHelpers.IsReferenceOrContainsReferences<T>())
ThrowHelper.ThrowInvalidTypeWithPointersNotSupported(typeof(T));
return new ReadOnlySpan<byte>(
ref Unsafe.As<T, byte>(ref GetReference(span)),
checked(span.Length * Unsafe.SizeOf<T>()));
}
/// <summary>Creates a <see cref="Memory{T}"/> from a <see cref="ReadOnlyMemory{T}"/>.</summary>
/// <param name="memory">The <see cref="ReadOnlyMemory{T}"/>.</param>
/// <returns>A <see cref="Memory{T}"/> representing the same memory as the <see cref="ReadOnlyMemory{T}"/>, but writable.</returns>
/// <remarks>
/// <see cref="AsMemory{T}(ReadOnlyMemory{T})"/> must be used with extreme caution. <see cref="ReadOnlyMemory{T}"/> is used
/// to represent immutable data and other memory that is not meant to be written to; <see cref="Memory{T}"/> instances created
/// by <see cref="AsMemory{T}(ReadOnlyMemory{T})"/> should not be written to. The method exists to enable variables typed
/// as <see cref="Memory{T}"/> but only used for reading to store a <see cref="ReadOnlyMemory{T}"/>.
/// </remarks>
public static Memory<T> AsMemory<T>(ReadOnlyMemory<T> memory) =>
Unsafe.As<ReadOnlyMemory<T>, Memory<T>>(ref memory);
/// <summary>
/// Returns a reference to the 0th element of the Span. If the Span is empty, returns a reference to the location where the 0th element
/// would have been stored. Such a reference may or may not be null. It can be used for pinning but must never be dereferenced.
/// </summary>
public static ref T GetReference<T>(Span<T> span) => ref span._pointer.Value;
/// <summary>
/// Returns a reference to the 0th element of the ReadOnlySpan. If the ReadOnlySpan is empty, returns a reference to the location where the 0th element
/// would have been stored. Such a reference may or may not be null. It can be used for pinning but must never be dereferenced.
/// </summary>
public static ref T GetReference<T>(ReadOnlySpan<T> span) => ref span._pointer.Value;
/// <summary>
/// Returns a reference to the 0th element of the Span. If the Span is empty, returns a reference to fake non-null pointer. Such a reference can be used
/// for pinning but must never be dereferenced. This is useful for interop with methods that do not accept null pointers for zero-sized buffers.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static unsafe ref T GetNonNullPinnableReference<T>(Span<T> span) => ref (span.Length != 0) ? ref span._pointer.Value : ref Unsafe.AsRef<T>((void*)1);
/// <summary>
/// Returns a reference to the 0th element of the ReadOnlySpan. If the ReadOnlySpan is empty, returns a reference to fake non-null pointer. Such a reference
/// can be used for pinning but must never be dereferenced. This is useful for interop with methods that do not accept null pointers for zero-sized buffers.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static unsafe ref T GetNonNullPinnableReference<T>(ReadOnlySpan<T> span) => ref (span.Length != 0) ? ref span._pointer.Value : ref Unsafe.AsRef<T>((void*)1);
/// <summary>
/// Casts a Span of one primitive type <typeparamref name="TFrom"/> to another primitive type <typeparamref name="TTo"/>.
/// These types may not contain pointers or references. This is checked at runtime in order to preserve type safety.
/// </summary>
/// <remarks>
/// Supported only for platforms that support misaligned memory access or when the memory block is aligned by other means.
/// </remarks>
/// <param name="span">The source slice, of type <typeparamref name="TFrom"/>.</param>
/// <exception cref="System.ArgumentException">
/// Thrown when <typeparamref name="TFrom"/> or <typeparamref name="TTo"/> contains pointers.
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Span<TTo> Cast<TFrom, TTo>(Span<TFrom> span)
where TFrom : struct
where TTo : struct
{
if (RuntimeHelpers.IsReferenceOrContainsReferences<TFrom>())
ThrowHelper.ThrowInvalidTypeWithPointersNotSupported(typeof(TFrom));
if (RuntimeHelpers.IsReferenceOrContainsReferences<TTo>())
ThrowHelper.ThrowInvalidTypeWithPointersNotSupported(typeof(TTo));
// Use unsigned integers - unsigned division by constant (especially by power of 2)
// and checked casts are faster and smaller.
uint fromSize = (uint)Unsafe.SizeOf<TFrom>();
uint toSize = (uint)Unsafe.SizeOf<TTo>();
uint fromLength = (uint)span.Length;
int toLength;
if (fromSize == toSize)
{
// Special case for same size types - `(ulong)fromLength * (ulong)fromSize / (ulong)toSize`
// should be optimized to just `length` but the JIT doesn't do that today.
toLength = (int)fromLength;
}
else if (fromSize == 1)
{
// Special case for byte sized TFrom - `(ulong)fromLength * (ulong)fromSize / (ulong)toSize`
// becomes `(ulong)fromLength / (ulong)toSize` but the JIT can't narrow it down to `int`
// and can't eliminate the checked cast. This also avoids a 32 bit specific issue,
// the JIT can't eliminate long multiply by 1.
toLength = (int)(fromLength / toSize);
}
else
{
// Ensure that casts are done in such a way that the JIT is able to "see"
// the uint->ulong casts and the multiply together so that on 32 bit targets
// 32x32to64 multiplication is used.
ulong toLengthUInt64 = (ulong)fromLength * (ulong)fromSize / (ulong)toSize;
toLength = checked((int)toLengthUInt64);
}
return new Span<TTo>(
ref Unsafe.As<TFrom, TTo>(ref span._pointer.Value),
toLength);
}
/// <summary>
/// Casts a ReadOnlySpan of one primitive type <typeparamref name="TFrom"/> to another primitive type <typeparamref name="TTo"/>.
/// These types may not contain pointers or references. This is checked at runtime in order to preserve type safety.
/// </summary>
/// <remarks>
/// Supported only for platforms that support misaligned memory access or when the memory block is aligned by other means.
/// </remarks>
/// <param name="span">The source slice, of type <typeparamref name="TFrom"/>.</param>
/// <exception cref="System.ArgumentException">
/// Thrown when <typeparamref name="TFrom"/> or <typeparamref name="TTo"/> contains pointers.
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ReadOnlySpan<TTo> Cast<TFrom, TTo>(ReadOnlySpan<TFrom> span)
where TFrom : struct
where TTo : struct
{
if (RuntimeHelpers.IsReferenceOrContainsReferences<TFrom>())
ThrowHelper.ThrowInvalidTypeWithPointersNotSupported(typeof(TFrom));
if (RuntimeHelpers.IsReferenceOrContainsReferences<TTo>())
ThrowHelper.ThrowInvalidTypeWithPointersNotSupported(typeof(TTo));
// Use unsigned integers - unsigned division by constant (especially by power of 2)
// and checked casts are faster and smaller.
uint fromSize = (uint)Unsafe.SizeOf<TFrom>();
uint toSize = (uint)Unsafe.SizeOf<TTo>();
uint fromLength = (uint)span.Length;
int toLength;
if (fromSize == toSize)
{
// Special case for same size types - `(ulong)fromLength * (ulong)fromSize / (ulong)toSize`
// should be optimized to just `length` but the JIT doesn't do that today.
toLength = (int)fromLength;
}
else if (fromSize == 1)
{
// Special case for byte sized TFrom - `(ulong)fromLength * (ulong)fromSize / (ulong)toSize`
// becomes `(ulong)fromLength / (ulong)toSize` but the JIT can't narrow it down to `int`
// and can't eliminate the checked cast. This also avoids a 32 bit specific issue,
// the JIT can't eliminate long multiply by 1.
toLength = (int)(fromLength / toSize);
}
else
{
// Ensure that casts are done in such a way that the JIT is able to "see"
// the uint->ulong casts and the multiply together so that on 32 bit targets
// 32x32to64 multiplication is used.
ulong toLengthUInt64 = (ulong)fromLength * (ulong)fromSize / (ulong)toSize;
toLength = checked((int)toLengthUInt64);
}
return new ReadOnlySpan<TTo>(
ref Unsafe.As<TFrom, TTo>(ref MemoryMarshal.GetReference(span)),
toLength);
}
/// <summary>
/// Create a new span over a portion of a regular managed object. This can be useful
/// if part of a managed object represents a "fixed array." This is dangerous because the
/// <paramref name="length"/> is not checked.
/// </summary>
/// <param name="reference">A reference to data.</param>
/// <param name="length">The number of <typeparamref name="T"/> elements the memory contains.</param>
/// <returns>The lifetime of the returned span will not be validated for safety by span-aware languages.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Span<T> CreateSpan<T>(ref T reference, int length) => new Span<T>(ref reference, length);
/// <summary>
/// Create a new read-only span over a portion of a regular managed object. This can be useful
/// if part of a managed object represents a "fixed array." This is dangerous because the
/// <paramref name="length"/> is not checked.
/// </summary>
/// <param name="reference">A reference to data.</param>
/// <param name="length">The number of <typeparamref name="T"/> elements the memory contains.</param>
/// <returns>The lifetime of the returned span will not be validated for safety by span-aware languages.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ReadOnlySpan<T> CreateReadOnlySpan<T>(ref T reference, int length) => new ReadOnlySpan<T>(ref reference, length);
/// <summary>
/// Get an array segment from the underlying memory.
/// If unable to get the array segment, return false with a default array segment.
/// </summary>
public static bool TryGetArray<T>(ReadOnlyMemory<T> memory, out ArraySegment<T> segment)
{
object? obj = memory.GetObjectStartLength(out int index, out int length);
// As an optimization, we skip the "is string?" check below if typeof(T) is not char,
// as Memory<T> / ROM<T> can't possibly contain a string instance in this case.
if (obj != null && !(
(typeof(T) == typeof(char) && obj.GetType() == typeof(string))
#if FEATURE_UTF8STRING
|| ((typeof(T) == typeof(byte) || typeof(T) == typeof(Char8)) && obj.GetType() == typeof(Utf8String))
#endif // FEATURE_UTF8STRING
))
{
if (RuntimeHelpers.ObjectHasComponentSize(obj))
{
// The object has a component size, which means it's variable-length, but we already
// checked above that it's not a string. The only remaining option is that it's a T[]
// or a U[] which is blittable to a T[] (e.g., int[] and uint[]).
// The array may be prepinned, so remove the high bit from the start index in the line below.
// The ArraySegment<T> ctor will perform bounds checking on index & length.
segment = new ArraySegment<T>(Unsafe.As<T[]>(obj), index & ReadOnlyMemory<T>.RemoveFlagsBitMask, length);
return true;
}
else
{
// The object isn't null, and it's not variable-length, so the only remaining option
// is MemoryManager<T>. The ArraySegment<T> ctor will perform bounds checking on index & length.
Debug.Assert(obj is MemoryManager<T>);
if (Unsafe.As<MemoryManager<T>>(obj).TryGetArray(out ArraySegment<T> tempArraySegment))
{
segment = new ArraySegment<T>(tempArraySegment.Array!, tempArraySegment.Offset + index, length);
return true;
}
}
}
// If we got to this point, the object is null, or it's a string, or it's a MemoryManager<T>
// which isn't backed by an array. We'll quickly homogenize all zero-length Memory<T> instances
// to an empty array for the purposes of reporting back to our caller.
if (length == 0)
{
segment = ArraySegment<T>.Empty;
return true;
}
// Otherwise, there's *some* data, but it's not convertible to T[].
segment = default;
return false;
}
/// <summary>
/// Gets an <see cref="MemoryManager{T}"/> from the underlying read-only memory.
/// If unable to get the <typeparamref name="TManager"/> type, returns false.
/// </summary>
/// <typeparam name="T">The element type of the <paramref name="memory" />.</typeparam>
/// <typeparam name="TManager">The type of <see cref="MemoryManager{T}"/> to try and retrive.</typeparam>
/// <param name="memory">The memory to get the manager for.</param>
/// <param name="manager">The returned manager of the <see cref="ReadOnlyMemory{T}"/>.</param>
/// <returns>A <see cref="bool"/> indicating if it was successful.</returns>
public static bool TryGetMemoryManager<T, TManager>(ReadOnlyMemory<T> memory, [NotNullWhen(true)] out TManager? manager)
where TManager : MemoryManager<T>
{
TManager? localManager; // Use register for null comparison rather than byref
manager = localManager = memory.GetObjectStartLength(out _, out _) as TManager;
return localManager != null;
}
/// <summary>
/// Gets an <see cref="MemoryManager{T}"/> and <paramref name="start" />, <paramref name="length" /> from the underlying read-only memory.
/// If unable to get the <typeparamref name="TManager"/> type, returns false.
/// </summary>
/// <typeparam name="T">The element type of the <paramref name="memory" />.</typeparam>
/// <typeparam name="TManager">The type of <see cref="MemoryManager{T}"/> to try and retrive.</typeparam>
/// <param name="memory">The memory to get the manager for.</param>
/// <param name="manager">The returned manager of the <see cref="ReadOnlyMemory{T}"/>.</param>
/// <param name="start">The offset from the start of the <paramref name="manager" /> that the <paramref name="memory" /> represents.</param>
/// <param name="length">The length of the <paramref name="manager" /> that the <paramref name="memory" /> represents.</param>
/// <returns>A <see cref="bool"/> indicating if it was successful.</returns>
public static bool TryGetMemoryManager<T, TManager>(ReadOnlyMemory<T> memory, [NotNullWhen(true)] out TManager? manager, out int start, out int length)
where TManager : MemoryManager<T>
{
TManager? localManager; // Use register for null comparison rather than byref
manager = localManager = memory.GetObjectStartLength(out start, out length) as TManager;
Debug.Assert(length >= 0);
if (localManager == null)
{
start = default;
length = default;
return false;
}
return true;
}
/// <summary>
/// Creates an <see cref="IEnumerable{T}"/> view of the given <paramref name="memory" /> to allow
/// the <paramref name="memory" /> to be used in existing APIs that take an <see cref="IEnumerable{T}"/>.
/// </summary>
/// <typeparam name="T">The element type of the <paramref name="memory" />.</typeparam>
/// <param name="memory">The ReadOnlyMemory to view as an <see cref="IEnumerable{T}"/></param>
/// <returns>An <see cref="IEnumerable{T}"/> view of the given <paramref name="memory" /></returns>
public static IEnumerable<T> ToEnumerable<T>(ReadOnlyMemory<T> memory)
{
for (int i = 0; i < memory.Length; i++)
yield return memory.Span[i];
}
/// <summary>Attempts to get the underlying <see cref="string"/> from a <see cref="ReadOnlyMemory{T}"/>.</summary>
/// <param name="memory">The memory that may be wrapping a <see cref="string"/> object.</param>
/// <param name="text">The string.</param>
/// <param name="start">The starting location in <paramref name="text"/>.</param>
/// <param name="length">The number of items in <paramref name="text"/>.</param>
/// <returns></returns>
public static bool TryGetString(ReadOnlyMemory<char> memory, [NotNullWhen(true)] out string? text, out int start, out int length)
{
if (memory.GetObjectStartLength(out int offset, out int count) is string s)
{
Debug.Assert(offset >= 0);
Debug.Assert(count >= 0);
text = s;
start = offset;
length = count;
return true;
}
else
{
text = null;
start = 0;
length = 0;
return false;
}
}
/// <summary>
/// Reads a structure of type T out of a read-only span of bytes.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static T Read<T>(ReadOnlySpan<byte> source)
where T : struct
{
if (RuntimeHelpers.IsReferenceOrContainsReferences<T>())
{
ThrowHelper.ThrowInvalidTypeWithPointersNotSupported(typeof(T));
}
if (Unsafe.SizeOf<T>() > source.Length)
{
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.length);
}
return Unsafe.ReadUnaligned<T>(ref GetReference(source));
}
/// <summary>
/// Reads a structure of type T out of a span of bytes.
/// <returns>If the span is too small to contain the type T, return false.</returns>
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool TryRead<T>(ReadOnlySpan<byte> source, out T value)
where T : struct
{
if (RuntimeHelpers.IsReferenceOrContainsReferences<T>())
{
ThrowHelper.ThrowInvalidTypeWithPointersNotSupported(typeof(T));
}
if (Unsafe.SizeOf<T>() > (uint)source.Length)
{
value = default;
return false;
}
value = Unsafe.ReadUnaligned<T>(ref GetReference(source));
return true;
}
/// <summary>
/// Writes a structure of type T into a span of bytes.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Write<T>(Span<byte> destination, ref T value)
where T : struct
{
if (RuntimeHelpers.IsReferenceOrContainsReferences<T>())
{
ThrowHelper.ThrowInvalidTypeWithPointersNotSupported(typeof(T));
}
if ((uint)Unsafe.SizeOf<T>() > (uint)destination.Length)
{
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.length);
}
Unsafe.WriteUnaligned<T>(ref GetReference(destination), value);
}
/// <summary>
/// Writes a structure of type T into a span of bytes.
/// <returns>If the span is too small to contain the type T, return false.</returns>
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool TryWrite<T>(Span<byte> destination, ref T value)
where T : struct
{
if (RuntimeHelpers.IsReferenceOrContainsReferences<T>())
{
ThrowHelper.ThrowInvalidTypeWithPointersNotSupported(typeof(T));
}
if (Unsafe.SizeOf<T>() > (uint)destination.Length)
{
return false;
}
Unsafe.WriteUnaligned<T>(ref GetReference(destination), value);
return true;
}
/// <summary>
/// Re-interprets a span of bytes as a reference to structure of type T.
/// The type may not contain pointers or references. This is checked at runtime in order to preserve type safety.
/// </summary>
/// <remarks>
/// Supported only for platforms that support misaligned memory access or when the memory block is aligned by other means.
/// </remarks>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ref T AsRef<T>(Span<byte> span)
where T : struct
{
if (RuntimeHelpers.IsReferenceOrContainsReferences<T>())
{
ThrowHelper.ThrowInvalidTypeWithPointersNotSupported(typeof(T));
}
if (Unsafe.SizeOf<T>() > (uint)span.Length)
{
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.length);
}
return ref Unsafe.As<byte, T>(ref GetReference(span));
}
/// <summary>
/// Re-interprets a span of bytes as a reference to structure of type T.
/// The type may not contain pointers or references. This is checked at runtime in order to preserve type safety.
/// </summary>
/// <remarks>
/// Supported only for platforms that support misaligned memory access or when the memory block is aligned by other means.
/// </remarks>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ref readonly T AsRef<T>(ReadOnlySpan<byte> span)
where T : struct
{
if (RuntimeHelpers.IsReferenceOrContainsReferences<T>())
{
ThrowHelper.ThrowInvalidTypeWithPointersNotSupported(typeof(T));
}
if (Unsafe.SizeOf<T>() > (uint)span.Length)
{
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.length);
}
return ref Unsafe.As<byte, T>(ref GetReference(span));
}
/// <summary>
/// Creates a new memory over the portion of the pre-pinned target array beginning
/// at 'start' index and ending at 'end' index (exclusive).
/// </summary>
/// <param name="array">The pre-pinned target array.</param>
/// <param name="start">The index at which to begin the memory.</param>
/// <param name="length">The number of items in the memory.</param>
/// <remarks>This method should only be called on an array that is already pinned and
/// that array should not be unpinned while the returned Memory<typeparamref name="T"/> is still in use.
/// Calling this method on an unpinned array could result in memory corruption.</remarks>
/// <remarks>Returns default when <paramref name="array"/> is null.</remarks>
/// <exception cref="System.ArrayTypeMismatchException">Thrown when <paramref name="array"/> is covariant and array's type is not exactly T[].</exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="start"/> or end index is not in the range (<0 or >=Length).
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Memory<T> CreateFromPinnedArray<T>(T[]? array, int start, int length)
{
if (array == null)
{
if (start != 0 || length != 0)
ThrowHelper.ThrowArgumentOutOfRangeException();
return default;
}
if (default(T)! == null && array.GetType() != typeof(T[])) // TODO-NULLABLE: default(T) == null warning (https://github.com/dotnet/roslyn/issues/34757)
ThrowHelper.ThrowArrayTypeMismatchException();
if ((uint)start > (uint)array.Length || (uint)length > (uint)(array.Length - start))
ThrowHelper.ThrowArgumentOutOfRangeException();
// Before using _index, check if _index < 0, then 'and' it with RemoveFlagsBitMask
return new Memory<T>((object)array, start | (1 << 31), length);
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#region Using directives
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Management.Automation;
using System.Threading;
using System.Globalization;
#endregion
namespace Microsoft.Management.Infrastructure.CimCmdlets
{
/// <summary>
/// <para>
/// Async operation base class, it will issue async operation through
/// 1...* CimSession object(s), processing the async results, extended
/// pssemantics operations, and manage the lifecycle of created
/// CimSession object(s).
/// </para>
/// </summary>
internal abstract class CimAsyncOperation : IDisposable
{
#region Constructor
/// <summary>
/// Constructor.
/// </summary>
public CimAsyncOperation()
{
this.moreActionEvent = new ManualResetEventSlim(false);
this.actionQueue = new ConcurrentQueue<CimBaseAction>();
this._disposed = 0;
this.operationCount = 0;
}
#endregion
#region Event handler
/// <summary>
/// <para>
/// Handler used to handle new action event from
/// <seealso cref="CimSessionProxy"/> object.
/// </para>
/// </summary>
/// <param name="cimSession">
/// <seealso cref="CimSession"/> object raised the event
/// </param>
/// <param name="actionArgs">Event argument.</param>
protected void NewCmdletActionHandler(object cimSession, CmdletActionEventArgs actionArgs)
{
DebugHelper.WriteLogEx("Disposed {0}, action type = {1}", 0, this._disposed, actionArgs.Action);
if (this.Disposed)
{
if (actionArgs.Action is CimSyncAction)
{
// unblock the thread waiting for response
(actionArgs.Action as CimSyncAction).OnComplete();
}
return;
}
bool isEmpty = this.actionQueue.IsEmpty;
this.actionQueue.Enqueue(actionArgs.Action);
if (isEmpty)
{
this.moreActionEvent.Set();
}
}
/// <summary>
/// <para>
/// Handler used to handle new operation event from
/// <seealso cref="CimSessionProxy"/> object.
/// </para>
/// </summary>
/// <param name="cimSession">
/// <seealso cref="CimSession"/> object raised the event
/// </param>
/// <param name="actionArgs">Event argument.</param>
protected void OperationCreatedHandler(object cimSession, OperationEventArgs actionArgs)
{
DebugHelper.WriteLogEx();
lock (this.myLock)
{
this.operationCount++;
}
}
/// <summary>
/// <para>
/// Handler used to handle operation deletion event from
/// <seealso cref="CimSessionProxy"/> object.
/// </para>
/// </summary>
/// <param name="cimSession">
/// <seealso cref="CimSession"/> object raised the event
/// </param>
/// <param name="actionArgs">Event argument.</param>
protected void OperationDeletedHandler(object cimSession, OperationEventArgs actionArgs)
{
DebugHelper.WriteLogEx();
lock (this.myLock)
{
this.operationCount--;
if (this.operationCount == 0)
{
this.moreActionEvent.Set();
}
}
}
#endregion
/// <summary>
/// <para>
/// process all actions in the action queue
/// </para>
/// </summary>
/// <param name="cmdletOperation">
/// wrapper of cmdlet, <seealso cref="CmdletOperationBase"/> for details
/// </param>
public void ProcessActions(CmdletOperationBase cmdletOperation)
{
if (!this.actionQueue.IsEmpty)
{
CimBaseAction action;
while (GetActionAndRemove(out action))
{
action.Execute(cmdletOperation);
if (this.Disposed)
{
break;
}
}
}
}
/// <summary>
/// <para>
/// process remaining actions until all operations are completed or
/// current cmdlet is terminated by user
/// </para>
/// </summary>
/// <param name="cmdletOperation">
/// wrapper of cmdlet, <seealso cref="CmdletOperationBase"/> for details
/// </param>
public void ProcessRemainActions(CmdletOperationBase cmdletOperation)
{
DebugHelper.WriteLogEx();
while (true)
{
ProcessActions(cmdletOperation);
if (!this.IsActive())
{
DebugHelper.WriteLogEx("Either disposed or all operations completed.", 2);
break;
}
try
{
this.moreActionEvent.Wait();
this.moreActionEvent.Reset();
}
catch (ObjectDisposedException ex)
{
// This might happen if this object is being disposed,
// while another thread is processing the remaining actions
DebugHelper.WriteLogEx("moreActionEvent was disposed: {0}.", 2, ex);
break;
}
}
ProcessActions(cmdletOperation);
}
#region helper methods
/// <summary>
/// <para>
/// Get action object from action queue
/// </para>
/// </summary>
/// <param name="action">Next action to execute.</param>
/// <returns>True indicates there is an valid action, otherwise false.</returns>
protected bool GetActionAndRemove(out CimBaseAction action)
{
return this.actionQueue.TryDequeue(out action);
}
/// <summary>
/// <para>
/// Add temporary <seealso cref="CimSessionProxy"/> object to cache.
/// </para>
/// </summary>
/// <param name="computerName">Computer name of the cimsession.</param>
/// <param name="sessionproxy">Cimsession wrapper object.</param>
protected void AddCimSessionProxy(CimSessionProxy sessionproxy)
{
lock (cimSessionProxyCacheLock)
{
if (this.cimSessionProxyCache == null)
{
this.cimSessionProxyCache = new List<CimSessionProxy>();
}
if (!this.cimSessionProxyCache.Contains(sessionproxy))
{
this.cimSessionProxyCache.Add(sessionproxy);
}
}
}
/// <summary>
/// <para>
/// Are there active operations?
/// </para>
/// </summary>
/// <returns>True for having active operations, otherwise false.</returns>
protected bool IsActive()
{
DebugHelper.WriteLogEx("Disposed {0}, Operation Count {1}", 2, this.Disposed, this.operationCount);
bool isActive = (!this.Disposed) && (this.operationCount > 0);
return isActive;
}
/// <summary>
/// Create <see cref="CimSessionProxy"/> object.
/// </summary>
/// <param name="session"></param>
protected CimSessionProxy CreateCimSessionProxy(CimSessionProxy originalProxy)
{
CimSessionProxy proxy = new CimSessionProxy(originalProxy);
this.SubscribeEventAndAddProxytoCache(proxy);
return proxy;
}
/// <summary>
/// Create <see cref="CimSessionProxy"/> object.
/// </summary>
/// <param name="session"></param>
protected CimSessionProxy CreateCimSessionProxy(CimSessionProxy originalProxy, bool passThru)
{
CimSessionProxy proxy = new CimSessionProxySetCimInstance(originalProxy, passThru);
this.SubscribeEventAndAddProxytoCache(proxy);
return proxy;
}
/// <summary>
/// Create <see cref="CimSessionProxy"/> object.
/// </summary>
/// <param name="session"></param>
protected CimSessionProxy CreateCimSessionProxy(CimSession session)
{
CimSessionProxy proxy = new CimSessionProxy(session);
this.SubscribeEventAndAddProxytoCache(proxy);
return proxy;
}
/// <summary>
/// Create <see cref="CimSessionProxy"/> object.
/// </summary>
/// <param name="session"></param>
protected CimSessionProxy CreateCimSessionProxy(CimSession session, bool passThru)
{
CimSessionProxy proxy = new CimSessionProxySetCimInstance(session, passThru);
this.SubscribeEventAndAddProxytoCache(proxy);
return proxy;
}
/// <summary>
/// Create <see cref="CimSessionProxy"/> object, and
/// add the proxy into cache.
/// </summary>
/// <param name="computerName"></param>
protected CimSessionProxy CreateCimSessionProxy(string computerName)
{
CimSessionProxy proxy = new CimSessionProxy(computerName);
this.SubscribeEventAndAddProxytoCache(proxy);
return proxy;
}
/// <summary>
/// Create <see cref="CimSessionProxy"/> object, and
/// add the proxy into cache.
/// </summary>
/// <param name="computerName"></param>
/// <param name="cimInstance"></param>
/// <returns></returns>
protected CimSessionProxy CreateCimSessionProxy(string computerName,
CimInstance cimInstance)
{
CimSessionProxy proxy = new CimSessionProxy(computerName, cimInstance);
this.SubscribeEventAndAddProxytoCache(proxy);
return proxy;
}
/// <summary>
/// Create <see cref="CimSessionProxy"/> object, and
/// add the proxy into cache.
/// </summary>
/// <param name="computerName"></param>
/// <param name="cimInstance"></param>
/// <param name="passThru"></param>
protected CimSessionProxy CreateCimSessionProxy(string computerName, CimInstance cimInstance, bool passThru)
{
CimSessionProxy proxy = new CimSessionProxySetCimInstance(computerName, cimInstance, passThru);
this.SubscribeEventAndAddProxytoCache(proxy);
return proxy;
}
/// <summary>
/// Subscribe event from proxy and add proxy to cache.
/// </summary>
/// <param name="proxy"></param>
protected void SubscribeEventAndAddProxytoCache(CimSessionProxy proxy)
{
this.AddCimSessionProxy(proxy);
SubscribeToCimSessionProxyEvent(proxy);
}
/// <summary>
/// <para>
/// Subscribe to the events issued by <see cref="CimSessionProxy"/>.
/// </para>
/// </summary>
/// <param name="proxy"></param>
protected virtual void SubscribeToCimSessionProxyEvent(CimSessionProxy proxy)
{
DebugHelper.WriteLogEx();
proxy.OnNewCmdletAction += this.NewCmdletActionHandler;
proxy.OnOperationCreated += this.OperationCreatedHandler;
proxy.OnOperationDeleted += this.OperationDeletedHandler;
}
/// <summary>
/// Retrieve the base object out if wrapped in psobject.
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
protected object GetBaseObject(object value)
{
PSObject psObject = value as PSObject;
if (psObject == null)
{
return value;
}
else
{
object baseObject = psObject.BaseObject;
var arrayObject = baseObject as object[];
if (arrayObject == null)
{
return baseObject;
}
else
{
object[] arraybaseObject = new object[arrayObject.Length];
for (int i = 0; i < arrayObject.Length; i++)
{
arraybaseObject[i] = GetBaseObject(arrayObject[i]);
}
return arraybaseObject;
}
}
}
/// <summary>
/// Retrieve the reference object or reference array object.
/// The returned object has to be either CimInstance or CImInstance[] type,
/// if not thrown exception.
/// </summary>
/// <param name="value"></param>
/// <param name="referenceType">Output the cimtype of the value, either Reference or ReferenceArray.</param>
/// <returns></returns>
protected object GetReferenceOrReferenceArrayObject(object value, ref CimType referenceType)
{
PSReference cimReference = value as PSReference;
if (cimReference != null)
{
object baseObject = GetBaseObject(cimReference.Value);
CimInstance cimInstance = baseObject as CimInstance;
if (cimInstance == null)
{
return null;
}
referenceType = CimType.Reference;
return cimInstance;
}
else
{
object[] cimReferenceArray = value as object[];
if (cimReferenceArray == null)
{
return null;
}
else if (!(cimReferenceArray[0] is PSReference))
{
return null;
}
CimInstance[] cimInstanceArray = new CimInstance[cimReferenceArray.Length];
for (int i = 0; i < cimReferenceArray.Length; i++)
{
PSReference tempCimReference = cimReferenceArray[i] as PSReference;
if (tempCimReference == null)
{
return null;
}
object baseObject = GetBaseObject(tempCimReference.Value);
cimInstanceArray[i] = baseObject as CimInstance;
if (cimInstanceArray[i] == null)
{
return null;
}
}
referenceType = CimType.ReferenceArray;
return cimInstanceArray;
}
}
#endregion
#region IDisposable
/// <summary>
/// <para>
/// Indicates whether this object was disposed or not
/// </para>
/// </summary>
protected bool Disposed
{
get
{
return (Interlocked.Read(ref this._disposed) == 1);
}
}
private long _disposed;
/// <summary>
/// <para>
/// Dispose() calls Dispose(true).
/// Implement IDisposable. Do not make this method virtual.
/// A derived class should not be able to override this method.
/// </para>
/// </summary>
public void Dispose()
{
Dispose(true);
// This object will be cleaned up by the Dispose method.
// Therefore, you should call GC.SuppressFinalize to
// take this object off the finalization queue
// and prevent finalization code for this object
// from executing a second time.
GC.SuppressFinalize(this);
}
/// <summary>
/// <para>
/// Dispose(bool disposing) executes in two distinct scenarios.
/// If disposing equals true, the method has been called directly
/// or indirectly by a user's code. Managed and unmanaged resources
/// can be disposed.
/// If disposing equals false, the method has been called by the
/// runtime from inside the finalizer and you should not reference
/// other objects. Only unmanaged resources can be disposed.
/// </para>
/// </summary>
/// <param name="disposing">Whether it is directly called.</param>
protected virtual void Dispose(bool disposing)
{
if (Interlocked.CompareExchange(ref this._disposed, 1, 0) == 0)
{
if (disposing)
{
// free managed resources
Cleanup();
}
// free native resources if there are any
}
}
/// <summary>
/// <para>
/// Clean up managed resources
/// </para>
/// </summary>
private void Cleanup()
{
DebugHelper.WriteLogEx();
// unblock thread that waiting for more actions
this.moreActionEvent.Set();
CimBaseAction action;
while (GetActionAndRemove(out action))
{
DebugHelper.WriteLog("Action {0}", 2, action);
if (action is CimSyncAction)
{
// unblock the thread waiting for response
(action as CimSyncAction).OnComplete();
}
}
if (this.cimSessionProxyCache != null)
{
List<CimSessionProxy> temporaryProxy;
lock (this.cimSessionProxyCache)
{
temporaryProxy = new List<CimSessionProxy>(this.cimSessionProxyCache);
this.cimSessionProxyCache.Clear();
}
// clean up all proxy objects
foreach (CimSessionProxy proxy in temporaryProxy)
{
DebugHelper.WriteLog("Dispose proxy ", 2);
proxy.Dispose();
}
}
this.moreActionEvent.Dispose();
if (this.ackedEvent != null)
{
this.ackedEvent.Dispose();
}
DebugHelper.WriteLog("Cleanup complete.", 2);
}
#endregion
#region private members
/// <summary>
/// Lock object.
/// </summary>
private readonly object myLock = new object();
/// <summary>
/// Number of active operations.
/// </summary>
private UInt32 operationCount = 0;
/// <summary>
/// Event to notify ps thread that more action is available.
/// </summary>
private ManualResetEventSlim moreActionEvent;
/// <summary>
/// The following is the definition of action queue.
/// The queue holding all actions to be executed in the context of either
/// ProcessRecord or EndProcessing.
/// </summary>
private ConcurrentQueue<CimBaseAction> actionQueue;
/// <summary>
/// Lock object.
/// </summary>
private readonly object cimSessionProxyCacheLock = new object();
/// <summary>
/// Cache all <see cref="CimSessionProxy"/> objects related to
/// the current operation.
/// </summary>
private List<CimSessionProxy> cimSessionProxyCache;
#endregion
#region protected members
/// <summary>
/// Event to notify ps thread that either a ACK message sent back
/// or a error happened. Currently only used by class
/// <see cref="CimRegisterCimIndication"/>.
/// </summary>
protected ManualResetEventSlim ackedEvent;
#endregion
#region const strings
internal const string ComputerNameArgument = @"ComputerName";
internal const string CimSessionArgument = @"CimSession";
#endregion
}
}
| |
// -------------------------------------------
// Control Freak 2
// Copyright (C) 2013-2016 Dan's Game Tools
// http://DansGameTools.com
// -------------------------------------------
#if UNITY_EDITOR
using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;
using ControlFreak2;
using ControlFreak2Editor.Internal;
namespace ControlFreak2Editor
{
public class Assistant : EditorWindow
{
static Assistant mInst;
static bool mPrefsChecked;
static bool mAutoOpen;
public bool recordingOn;
public bool propBoxOn;
public InputRig selectedRig;
const string AUTO_OPEN_PREF_KEY = "CF2AutoOpenAssistant";
private List<LogEntry> logEntries;
private LogEntry selectedEntry;
// ------------------
public enum CallType
{
Axis,
Button,
Key,
Touch,
ScrollWheel,
MousePosition,
CursorLock
}
// -----------------
public Assistant()
{
this.logEntries = new List<LogEntry>(128);
this.minSize = new Vector2(200, 200);
}
// ---------------------
[MenuItem("Control Freak 2/CF2 Assistant")]
static void ShowListenerMenuItem()
{ ShowListener(true); }
// ---------------------
static private Assistant ShowListener(bool focus)
{
Assistant listener = (GetWindow(typeof(Assistant), true, "Control Freak 2 Assistant", focus) as Assistant);
if (listener == null)
return null;
return listener;
}
// ----------------------
static private bool IsAutoOpenEnabled()
{
if (!mPrefsChecked)
{
mPrefsChecked = true;
mAutoOpen = EditorPrefs.GetBool(AUTO_OPEN_PREF_KEY);
}
return mAutoOpen;
}
// ---------------------
static public void CaptureKey (KeyCode keyParam) { CaptureEx(CallType.Key, "", keyParam); }
static public void CaptureButton (string buttonName) { CaptureEx(CallType.Button, buttonName, KeyCode.None); }
static public void CaptureAxis (string axisName) { CaptureEx(CallType.Axis, axisName, KeyCode.None); }
static public void CaptureMousePos () { CaptureEx(CallType.MousePosition,"", KeyCode.None); }
static public void CaptureScrollWheel() { CaptureEx(CallType.ScrollWheel, "", KeyCode.None); }
static public void CaptureTouch () { CaptureEx(CallType.Touch, "", KeyCode.None); }
static public void CaptureCursorLock() { CaptureEx(CallType.CursorLock, "", KeyCode.None); }
// ---------------------
static private void CaptureEx(CallType callType, string strParam, KeyCode keyParam)
{
if (mInst == null)
{
if (IsAutoOpenEnabled())
mInst = ShowListener(false);
}
if (mInst == null)
return;
mInst.CaptureCall(callType, strParam, keyParam);
}
// -------------------
private InputRig GetCurrentlySelectedRig()
{
InputRig rig = TouchControlWizardUtils.GetRigFromSelection(this.selectedRig, true);
if (rig == null)
rig = CF2Input.activeRig;
return rig;
//if (Selection.activeTransform == null)
// return null;
//return Selection.activeTransform.GetComponent<InputRig>();
}
// ------------------
private void OnSelectionChange()
{
this.selectedRig = this.GetCurrentlySelectedRig();
this.RefreshRigState();
this.Repaint();
}
// -------------------
public void ClearEntries()
{
this.logEntries.Clear();
this.selectedEntry = null;
}
// ------------------
public void RefreshRigState()
{
for (int i = 0; i < this.logEntries.Count; ++i)
{
this.logEntries[i].CheckRigState(this.selectedRig);
}
//this.Repaint();
}
// ------------------
private void CaptureCall(CallType callType, string strParam, KeyCode keyParam)
{
if (!this.recordingOn)
return;
if (string.IsNullOrEmpty(strParam) && (keyParam == KeyCode.None))
return;
System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(1, true);
string stackTrace = trace.ToString();
if (this.logEntries.Find(x => x.IsDuplicateOf(callType, strParam, keyParam, stackTrace)) == null)
{
this.logEntries.Add(new LogEntry(callType, strParam, keyParam, trace));
this.RefreshRigState();
this.Repaint();
}
}
// -------------------
void OnEnable()
{
//Debug.Log("ENABLE LISTENER : " + ((this.logEntries == null) ? "NULL" : this.logEntries.Count.ToString()) +
// " MSGS: " + ((this.logEntries == null) ? "NULL" : this.msgs.Count.ToString()) + " INST: " + ((mInst == null) ? "NULL" : "NOT NULL"));
mInst = this;
//Selection.selectionChanged += this.OnSelChange;
this.selectedEntry = null;
this.propBoxOn = true;
this.recordingOn = true;
this.OnSelectionChange();
this.Repaint();
}
// ------------------
void OnDisable()
{
//Selection.selectionChanged -= this.OnSelChange;
}
// -----------------
void OnFocus()
{
this.RefreshRigState();
}
private Vector2
scrollPos,
propBoxScroll;
// ------------------
public void SelectEntry(LogEntry entry)
{
this.selectedEntry = entry;
}
// -----------------
public bool IsEntrySelected(LogEntry entry)
{
return (entry == this.selectedEntry);
}
// -----------------------
void OnGUI()
{
const float BUTTON_HEIGHT = 30;
const float TOOLBAR_HEIGHT = 34;
const float PROP_BOX_BUTTON_HEIGHT = 20;
const float MAX_PROP_BOX_HEIGHT = 300;
const float ENTRY_LIST_REL_HEIGHT = 0.55f;
float entryListHeight = (this.position.height - TOOLBAR_HEIGHT) - PROP_BOX_BUTTON_HEIGHT - 100;
float propBoxHeight = Mathf.Min((MAX_PROP_BOX_HEIGHT), (entryListHeight * (1.0f - ENTRY_LIST_REL_HEIGHT)));
GUILayout.Box(GUIContent.none, CFEditorStyles.Inst.headerAssistant, GUILayout.ExpandWidth(true));
EditorGUILayout.BeginHorizontal(CFEditorStyles.Inst.toolbarBG);
this.recordingOn = CFGUI.PushButton(
new GUIContent("Capture in progress!", CFEditorStyles.Inst.greenDotTex, "Editor must be in Play mode to catch Input calls!"),
new GUIContent("Stopped. Press to begin capture", CFEditorStyles.Inst.pauseTex, "Editor must be in Play mode to catch Input calls!"),
this.recordingOn, CFEditorStyles.Inst.buttonStyle, GUILayout.Height(BUTTON_HEIGHT), GUILayout.ExpandWidth(true));
GUI.backgroundColor = (Color.white);
if (GUILayout.Button("Clear", GUILayout.Height(BUTTON_HEIGHT), GUILayout.Width(70)))
this.ClearEntries();
EditorGUILayout.EndHorizontal();
if (this.selectedRig == null)
EditorGUILayout.HelpBox("No rig selected!! Select one to be able to easily create controls or bind commands!", MessageType.Warning);
else
EditorGUILayout.HelpBox("Rig: " + this.selectedRig.name, MessageType.None);
if (!CFUtils.editorStopped && (this.logEntries.Count > 0))
EditorGUILayout.HelpBox("Remember to stop Editor before binding or creating controls!", MessageType.Warning);
this.scrollPos = EditorGUILayout.BeginScrollView(this.scrollPos, CFEditorStyles.Inst.transpSunkenBG, GUILayout.ExpandHeight(true)); //GUILayout.Height(entryListHeight));
if (this.logEntries.Count == 0)
{
GUILayout.Box("Nothing captured yet!" + (CFUtils.editorStopped ? "\nTo capture anything hit the PLAY button!" : ""),
CFEditorStyles.Inst.centeredTextTranspBG);
}
else
{
for (int i = this.logEntries.Count - 1; i >= 0; --i)
{
//GUILayout.Label("[" + i + "] : " + this.logEntries[i].ToString());
this.logEntries[i].DrawListElemGUI(this);
}
}
EditorGUILayout.EndScrollView();
if (this.selectedEntry != null)
{
this.propBoxOn = CFGUI.PushButton(
new GUIContent("Hide Properties", CFEditorStyles.Inst.texMoveDown),
new GUIContent("Show Properties", CFEditorStyles.Inst.texMoveUp),
this.propBoxOn, CFEditorStyles.Inst.buttonStyle);
if (this.propBoxOn)
{
this.propBoxScroll = EditorGUILayout.BeginScrollView(this.propBoxScroll, CFEditorStyles.Inst.transpSunkenBG, GUILayout.Height(propBoxHeight));
this.selectedEntry.DrawPropertiesGUI();
EditorGUILayout.EndScrollView();
}
}
}
// ---------------------
[System.Serializable]
public class LogEntry
{
private List<Frame> frames;
private CallType callType;
private string strParam;
private KeyCode keyParam;
//private string sceneName;
private string stackTrace;
private int rigAxisId;
private bool
availableInRig,
availableOnMobile;
const string PATH_TO_IGNORE = "Assets/Plugins/Control-Freak-2/";
// ------------------
public enum SourceAvailablity
{
Not,
MobileOnly,
NotOnMobile
}
// ----------------
public LogEntry(CallType callType, string strParam, KeyCode keyParam, System.Diagnostics.StackTrace trace)
{
this.callType = callType;
this.keyParam = keyParam;
this.strParam = strParam;
this.stackTrace = trace.ToString();
int frameCount = trace.FrameCount;
this.frames = new List<Frame>(frameCount);
for (int i = 0; i < frameCount; ++i)
{
System.Diagnostics.StackFrame fr = trace.GetFrame(i);
if (IsFileInternal(fr.GetFileName()))
{
continue;
}
//outsideMethodFound = true;
this.frames.Add(new Frame(fr));
}
}
// --------------------
public void CheckRigState(InputRig rig)
{
this.availableInRig = false;
this.availableOnMobile = false;
if (rig == null)
return;
switch (this.callType)
{
case CallType.Button :
case CallType.Axis :
this.availableInRig = rig.IsAxisDefined(this.strParam, ref this.rigAxisId);
this.availableOnMobile = rig.IsAxisAvailableOnMobile(this.strParam);
break;
case CallType.Key :
this.availableInRig = true;
this.availableOnMobile = rig.IsKeyAvailableOnMobile(this.keyParam);
break;
case CallType.Touch :
this.availableInRig =
this.availableOnMobile = rig.IsTouchEmulatedOnMobile();
break;
case CallType.MousePosition :
this.availableInRig =
this.availableOnMobile = rig.IsMousePositionEmulatedOnMobile();
break;
case CallType.ScrollWheel :
this.availableInRig = true;
this.availableOnMobile = rig.IsScrollWheelEmulatedOnMobile();
break;
}
}
// -----------------
public bool IsDuplicateOf(CallType call, string strParam, KeyCode keyParam, string stackTrace)
{
return ((this.callType == call) && (this.strParam == strParam) && (this.keyParam == keyParam) && (this.stackTrace == stackTrace));
}
// -----------------
static private bool IsFileInternal(string path)
{
return ((path == null) || (path.Length == 0) || (path.Replace('\\', '/').IndexOf(PATH_TO_IGNORE) >= 0));
}
// -----------------
public override string ToString()
{
string s = this.callType.ToString() + " (frames: " + this.frames.Count + ")\n";
foreach (Frame frame in this.frames)
s += "\t" + frame.ToString() + "\n";
return s;
}
// ----------------------
public void DrawListElemGUI(Assistant listener)
{
//const float AXIS_BUTTON_WIDTH = 30;
const float HEIGHT = 20;
if (listener.IsEntrySelected(this))
GUI.backgroundColor = new Color(0.7f, 0.7f, 0.9f, 1.0f);
else
GUI.backgroundColor = new Color(0.7f, 0.7f, 0.7f, 1.0f);
EditorGUILayout.BeginHorizontal(CFEditorStyles.Inst.whiteBevelBG);
GUI.backgroundColor = Color.white;
GUIContent stateContent = GUIContent.none;
GUIContent nameContent = GUIContent.none;
if (listener.selectedRig == null)
stateContent = new GUIContent(CFEditorStyles.Inst.texError, "No rig selected!");
switch (this.callType)
{
case CallType.Axis :
case CallType.Button :
nameContent = new GUIContent(this.strParam, ((this.callType == Assistant.CallType.Axis) ? "Axis Name" : "Button Name"));
if (listener.selectedRig != null)
{
if (!this.availableInRig)
stateContent = new GUIContent(CFEditorStyles.Inst.texError, "Axis not available in [" + listener.selectedRig.name + "] rig!");
else if (!this.availableOnMobile)
stateContent = new GUIContent(CFEditorStyles.Inst.texWarning, "Axis not available in [" + listener.selectedRig.name + "] rig in Mobile Mode!");
else
stateContent = new GUIContent(CFEditorStyles.Inst.texOk, "Axis available in desktop and mobile modes!");
}
break;
case CallType.Key :
nameContent = new GUIContent(this.keyParam.ToString(), "Key code");
if (listener.selectedRig != null)
{
if (!this.availableInRig)
stateContent = new GUIContent(CFEditorStyles.Inst.texError, "Key not available in [" + listener.selectedRig.name + "] rig!");
else if (!this.availableOnMobile)
stateContent = new GUIContent(CFEditorStyles.Inst.texWarning, "Key not available in [" + listener.selectedRig.name + "] rig in Mobile Mode!");
else
stateContent = new GUIContent(CFEditorStyles.Inst.texOk, "Key available in desktop and mobile modes!");
}
break;
case CallType.ScrollWheel :
if (listener.selectedRig != null)
{
if (!this.availableInRig)
stateContent = new GUIContent(CFEditorStyles.Inst.texError, "Scroll Wheel not available in [" + listener.selectedRig.name + "] rig! Create an axis of SCROLL type and bind it as one of scroll wheel axes in Input Rig's Scroll Wheel Settings!");
else if (!this.availableOnMobile)
stateContent = new GUIContent(CFEditorStyles.Inst.texWarning, "Scroll Wheel not available in [" + listener.selectedRig.name + "] rig in Mobile Mode! Create an axis of SCROLL type and bind it as one of scroll wheel axes in Input Rig's Scroll Wheel Settings!");
else
stateContent = new GUIContent(CFEditorStyles.Inst.texOk, "Scroll Wheel available in desktop and mobile modes!");
}
break;
case CallType.MousePosition :
if (listener.selectedRig != null)
{
if (!this.availableInRig)
stateContent = new GUIContent(CFEditorStyles.Inst.texError, "Mouse Position is not available in [" + listener.selectedRig.name + "] rig! Create an Touch Zone and bind mouse position to it.");
else if (!this.availableOnMobile)
stateContent = new GUIContent(CFEditorStyles.Inst.texError, "Mouse Position is not available in [" + listener.selectedRig.name + "] rig! Create an Touch Zone and bind mouse position to it.");
else
stateContent = new GUIContent(CFEditorStyles.Inst.texOk, "Mouse Position available in desktop and mobile modes!");
}
break;
case CallType.Touch :
if (listener.selectedRig != null)
{
if (!this.availableInRig)
stateContent = new GUIContent(CFEditorStyles.Inst.texError, "Emulated Touches are not available in [" + listener.selectedRig.name + "] rig! Create an Touch Zone and bind emulated touches to it.");
else if (!this.availableOnMobile)
stateContent = new GUIContent(CFEditorStyles.Inst.texError, "Emulated Touches are not available in [" + listener.selectedRig.name + "] rig! Create an Touch Zone and bind emulated touches to it.");
else
stateContent = new GUIContent(CFEditorStyles.Inst.texOk, "Emulated Touches are available in desktop and mobile modes!");
}
break;
case CallType.CursorLock:
stateContent = GUIContent.none;
break;
}
EditorGUILayout.LabelField(stateContent, GUILayout.Width(20), GUILayout.Height(HEIGHT));
if ((listener.selectedRig != null)) //&& ((this.callType == Assistant.CallType.Axis) || (this.callType == CallType.Button)) && !this.availableInRig)
{
switch (this.callType)
{
case CallType.Axis :
if (GUILayout.Button(new GUIContent((this.availableInRig ? CFEditorStyles.Inst.texWrench : CFEditorStyles.Inst.createNewTex),
"Add or bind this axis..."), GUILayout.Width(20), GUILayout.Height(HEIGHT)))
{
WizardMenuUtils.CreateContextMenuForAxisBinding(listener.selectedRig, this.strParam, listener.RefreshRigState);
}
break;
case CallType.Button :
if (GUILayout.Button(new GUIContent((this.availableInRig ? CFEditorStyles.Inst.texWrench : CFEditorStyles.Inst.createNewTex),
"Add or bind this button..."), GUILayout.Width(20), GUILayout.Height(HEIGHT)))
{
WizardMenuUtils.CreateContextMenuForAxisBinding(listener.selectedRig, this.strParam, listener.RefreshRigState);
}
break;
case CallType.Key :
if (GUILayout.Button(new GUIContent(CFEditorStyles.Inst.texWrench,
"Bind this key..."), GUILayout.Width(20), GUILayout.Height(HEIGHT)))
{
WizardMenuUtils.CreateContextMenuForKeyBinding(listener.selectedRig, this.keyParam, listener.RefreshRigState);
}
break;
case CallType.MousePosition :
if (GUILayout.Button(new GUIContent(CFEditorStyles.Inst.texWrench,
"Bind mouse position..."), GUILayout.Width(20), GUILayout.Height(HEIGHT)))
{
WizardMenuUtils.CreateContextMenuForMousePositionBinding(listener.selectedRig, listener.RefreshRigState);
}
break;
case CallType.Touch :
if (GUILayout.Button(new GUIContent(CFEditorStyles.Inst.texWrench,
"Bind emu. touch..."), GUILayout.Width(20), GUILayout.Height(HEIGHT)))
{
WizardMenuUtils.CreateContextMenuForEmuTouchBinding(listener.selectedRig, listener.RefreshRigState);
}
break;
}
}
bool showPropertiesClicked = false;
if (GUILayout.Button(new GUIContent(this.callType.ToString()), CFEditorStyles.Inst.transpBevelBG, GUILayout.Width(100), GUILayout.Height(HEIGHT)))
showPropertiesClicked = true;
GUI.backgroundColor = new Color(1, 1, 1, 0.3f);
if (GUILayout.Button(nameContent, CFEditorStyles.Inst.whiteBevelBG, GUILayout.ExpandWidth(true), GUILayout.Height(HEIGHT)))
showPropertiesClicked = true;
GUI.backgroundColor = Color.white;
if (showPropertiesClicked)
listener.SelectEntry(this);
EditorGUILayout.EndHorizontal();
}
// ---------------------
public void DrawPropertiesGUI()
{
string propStr = this.callType.ToString();
if ((this.callType == Assistant.CallType.Axis) ||
(this.callType == Assistant.CallType.Button))
propStr += " : " + this.strParam;
else if (this.callType == Assistant.CallType.Key)
propStr += " : " + this.keyParam;
GUILayout.Box(propStr, CFEditorStyles.Inst.transpBevelBG);
EditorGUILayout.Space();
EditorGUILayout.BeginVertical(CFEditorStyles.Inst.transpSunkenBG);
EditorGUILayout.LabelField("Call stack trace:");
for (int i = 0; i < this.frames.Count; ++i)
{
Frame fr = this.frames[i];;
if (GUILayout.Button(new GUIContent(//"Method: " + fr.method + "\n" + "Class: + " + fr.classname + "\n" +
" Line: " + fr.line + " in " + fr.relFilename, CFEditorStyles.Inst.magnifiyingGlassTex, "Open this line in IDE.")))
{
fr.ShowInIDE();
}
}
EditorGUILayout.EndVertical();
}
// ---------------------
[System.Serializable]
private class Frame
{
public string
filename,
relFilename,
classname,
method;
public int
line;
// -----------------
public Frame(System.Diagnostics.StackFrame frame)
{
this.filename = frame.GetFileName();
this.filename = ((this.filename == null) ? "" : this.filename.Replace('\\', '/'));
this.relFilename = filename.Replace(Application.dataPath.Replace('\\', '/'), "");
this.classname = frame.GetType().ToString();
this.method = frame.GetMethod().ToString();
this.line = frame.GetFileLineNumber();
}
// ------------------
public void ShowInIDE()
{
CFEditorUtils.OpenScriptInIDE(this.filename, this.line);
}
// ------------------
override public string ToString()
{
return (this.method + "\t at line:" + this.line + " in [" + this.relFilename + "]");
}
}
}
}
}
#endif
| |
//
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
//
using UnityEngine;
using System.Collections;
using HUX;
using HUX.Interaction;
using HUX.Focus;
/// <summary>
/// <see cref="MonoBehaviour"/>
///
/// </summary>
public class WorldCursor : MonoBehaviour
{
public float SurfaceRayOffset = 0.1f;
public float CursorSize = 0.02f;
public bool Clamp = false;
public float ClampScale = 1.3f;
public float ScreenClampDotThresh = 0.71f;
public Vector2 DistanceClamp = new Vector2(0.1f, 7.5f);
public float DepthOffset = 0;
public bool AccrueInputsForUpdate;
bool cursorActive;
public bool IsActive
{
get
{
return cursorActive;
}
}
Vector2 accruedDelta;
public Vector2 currentScreenPos;
GameObject pointer;
void Start()
{
pointer = transform.GetChild(0).gameObject;
CenterCursor();
UpdateCursorPlacement();
}
public void AddDepthDelta(float delta)
{
DepthOffset += delta;
//transform.position = CastCursor(HUXGazer.Instance.GetRay());
}
public void SnapToGazeDir()
{
CastCursor(FocusManager.Instance.GazeFocuser.FocusRay);
}
public void ApplyMovementDelta(Vector2 mouseDelta, bool forceApply = false)
{
if (mouseDelta != Vector2.zero)
{
// If desired, just add up the delta inputs to apply once in update, in case there are many inputs each frame
if (AccrueInputsForUpdate && !forceApply)
{
accruedDelta += mouseDelta;
return;
}
//FocusManager focus = FocusManager.Instance;
Transform focusTransform = Veil.Instance.HeadTransform;// focus.GazeTransform;
// Get ray to current mouse pos
Ray newRay = new Ray(focusTransform.transform.position, Vector3.forward);//focus.FocusRay;
Vector3 newDirection = transform.position - newRay.origin;
// Move mouse
float vFov = 0.5f * Mathf.Sin(Mathf.Deg2Rad * Veil.Instance.DeviceFOV);
float hFov = 0.5f * Mathf.Sin(Mathf.Deg2Rad * (Veil.Instance.DeviceFOV * Veil.c_horiz_ratio));
float dist = newDirection.magnitude;
newDirection += dist * (focusTransform.up * mouseDelta.y * vFov + focusTransform.right * mouseDelta.x * hFov);
newDirection.Normalize();
// Clamp direction to screen tho
if (Clamp)
{
// Snap mouse to screen if looking far enough away from mouse
float headMouseDot = Vector3.Dot(newDirection, focusTransform.forward);
if (headMouseDot < Mathf.Max(0, ScreenClampDotThresh))
{
newDirection = focusTransform.forward;
}
// Clamp mouse to view bounds (times a scale) so that we can't move the mouse forever away and have to bring it back
float dot = Vector3.Dot(newDirection, focusTransform.up);
float delta = Mathf.Abs(dot) - vFov * ClampScale;
currentScreenPos.y = dot / vFov;
if (delta > 0)
{
newDirection -= Mathf.Sign(dot) * delta * focusTransform.up;
}
dot = Vector3.Dot(newDirection, focusTransform.right);
delta = Mathf.Abs(dot) - hFov * ClampScale;
currentScreenPos.x = dot / hFov;
if (delta > 0)
{
newDirection -= Mathf.Sign(dot) * delta * focusTransform.right;
}
newDirection.Normalize();
}
// Re-cast with new direction
newRay.direction = newDirection;
transform.position = RaycastPosition(newRay);
UpdateCursorPlacement();
}
}
public void CastCursor(Ray ray)
{
transform.position = RaycastPosition(ray);
UpdateCursorPlacement();
}
void Update()
{
if (AccrueInputsForUpdate && accruedDelta != Vector2.zero)
{
ApplyMovementDelta(accruedDelta, true);
accruedDelta = Vector2.zero;
}
}
public void SetCursorActive(bool active)
{
if (active == cursorActive)
{
return;
}
//Debug.Log("SetMouseCursorActive: " + active);
cursorActive = active;
if (active)
{
pointer.SetActive(true);
CenterCursor();
}
else
{
pointer.SetActive(false);
}
}
public void SetCursorPosition(Vector3 worldPos)
{
transform.position = worldPos;
UpdateCursorPlacement();
}
public void CenterCursor()
{
transform.position = FocusManager.Instance.GazeFocuser.TargetOrigin + FocusManager.Instance.GazeFocuser.TargetDirection * 2.5f;
CastCursor(GetRayForScreenPos(Vector2.zero));
}
public Ray GetRayForScreenPos(Vector2 pos)
{
AFocuser focus = FocusManager.Instance.GazeFocuser;
Ray newRay = focus.FocusRay;
float vFov = 0.5f * Mathf.Sin(Mathf.Deg2Rad * Veil.Instance.DeviceFOV);
float hFov = 0.5f * Mathf.Sin(Mathf.Deg2Rad * (Veil.Instance.DeviceFOV * Veil.c_horiz_ratio));
newRay.direction += (focus.TargetOrientation * Vector3.up) * pos.y * vFov + (focus.TargetOrientation * Vector3.right) * pos.x * hFov;
return newRay;
}
public Vector3 RaycastPosition(Ray newRay)
{
AFocuser focus = FocusManager.Instance.GazeFocuser;
Vector3 newPos = Vector3.zero;
RaycastHit newHit;
if (Physics.Raycast(newRay, out newHit))
{
Vector3 backupDir = newHit.point - focus.TargetOrigin;
newPos = newHit.point - backupDir * SurfaceRayOffset;
}
else
{
float currentDepth = Mathf.Clamp((transform.position - focus.TargetOrigin).magnitude, DistanceClamp.x, DistanceClamp.y);
Debug.DrawLine(focus.TargetOrigin, newRay.origin);
newPos = focus.TargetOrigin + newRay.direction * currentDepth;
}
//newPos += newRay.direction * DepthOffset;
return newPos;
}
public void UpdateCursorPlacement()
{
Vector3 vec = transform.position - FocusManager.Instance.GazeFocuser.TargetOrigin;
float dist = vec.magnitude;
transform.localScale = Vector3.one * dist * CursorSize;
if (vec.sqrMagnitude > 0)
{
transform.rotation = Quaternion.LookRotation(vec);
}
}
}
| |
/// This code was generated by
/// \ / _ _ _| _ _
/// | (_)\/(_)(_|\/| |(/_ v1.0.0
/// / /
using System;
using System.Collections.Generic;
using Twilio.Base;
using Twilio.Converters;
namespace Twilio.Rest.Taskrouter.V1
{
/// <summary>
/// FetchWorkspaceOptions
/// </summary>
public class FetchWorkspaceOptions : IOptions<WorkspaceResource>
{
/// <summary>
/// The SID of the resource to fetch
/// </summary>
public string PathSid { get; }
/// <summary>
/// Construct a new FetchWorkspaceOptions
/// </summary>
/// <param name="pathSid"> The SID of the resource to fetch </param>
public FetchWorkspaceOptions(string pathSid)
{
PathSid = pathSid;
}
/// <summary>
/// Generate the necessary parameters
/// </summary>
public List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
return p;
}
}
/// <summary>
/// UpdateWorkspaceOptions
/// </summary>
public class UpdateWorkspaceOptions : IOptions<WorkspaceResource>
{
/// <summary>
/// The SID of the resource to update
/// </summary>
public string PathSid { get; }
/// <summary>
/// The SID of the Activity that will be used when new Workers are created in the Workspace
/// </summary>
public string DefaultActivitySid { get; set; }
/// <summary>
/// The URL we should call when an event occurs
/// </summary>
public Uri EventCallbackUrl { get; set; }
/// <summary>
/// The list of Workspace events for which to call event_callback_url
/// </summary>
public string EventsFilter { get; set; }
/// <summary>
/// A string to describe the Workspace resource
/// </summary>
public string FriendlyName { get; set; }
/// <summary>
/// Whether multi-tasking is enabled
/// </summary>
public bool? MultiTaskEnabled { get; set; }
/// <summary>
/// The SID of the Activity that will be assigned to a Worker when a Task reservation times out without a response
/// </summary>
public string TimeoutActivitySid { get; set; }
/// <summary>
/// The type of TaskQueue to prioritize when Workers are receiving Tasks from both types of TaskQueues
/// </summary>
public WorkspaceResource.QueueOrderEnum PrioritizeQueueOrder { get; set; }
/// <summary>
/// Construct a new UpdateWorkspaceOptions
/// </summary>
/// <param name="pathSid"> The SID of the resource to update </param>
public UpdateWorkspaceOptions(string pathSid)
{
PathSid = pathSid;
}
/// <summary>
/// Generate the necessary parameters
/// </summary>
public List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
if (DefaultActivitySid != null)
{
p.Add(new KeyValuePair<string, string>("DefaultActivitySid", DefaultActivitySid.ToString()));
}
if (EventCallbackUrl != null)
{
p.Add(new KeyValuePair<string, string>("EventCallbackUrl", Serializers.Url(EventCallbackUrl)));
}
if (EventsFilter != null)
{
p.Add(new KeyValuePair<string, string>("EventsFilter", EventsFilter));
}
if (FriendlyName != null)
{
p.Add(new KeyValuePair<string, string>("FriendlyName", FriendlyName));
}
if (MultiTaskEnabled != null)
{
p.Add(new KeyValuePair<string, string>("MultiTaskEnabled", MultiTaskEnabled.Value.ToString().ToLower()));
}
if (TimeoutActivitySid != null)
{
p.Add(new KeyValuePair<string, string>("TimeoutActivitySid", TimeoutActivitySid.ToString()));
}
if (PrioritizeQueueOrder != null)
{
p.Add(new KeyValuePair<string, string>("PrioritizeQueueOrder", PrioritizeQueueOrder.ToString()));
}
return p;
}
}
/// <summary>
/// ReadWorkspaceOptions
/// </summary>
public class ReadWorkspaceOptions : ReadOptions<WorkspaceResource>
{
/// <summary>
/// The friendly_name of the Workspace resources to read
/// </summary>
public string FriendlyName { get; set; }
/// <summary>
/// Generate the necessary parameters
/// </summary>
public override List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
if (FriendlyName != null)
{
p.Add(new KeyValuePair<string, string>("FriendlyName", FriendlyName));
}
if (PageSize != null)
{
p.Add(new KeyValuePair<string, string>("PageSize", PageSize.ToString()));
}
return p;
}
}
/// <summary>
/// CreateWorkspaceOptions
/// </summary>
public class CreateWorkspaceOptions : IOptions<WorkspaceResource>
{
/// <summary>
/// A string to describe the Workspace resource
/// </summary>
public string FriendlyName { get; }
/// <summary>
/// The URL we should call when an event occurs
/// </summary>
public Uri EventCallbackUrl { get; set; }
/// <summary>
/// The list of Workspace events for which to call event_callback_url
/// </summary>
public string EventsFilter { get; set; }
/// <summary>
/// Whether multi-tasking is enabled
/// </summary>
public bool? MultiTaskEnabled { get; set; }
/// <summary>
/// An available template name
/// </summary>
public string Template { get; set; }
/// <summary>
/// The type of TaskQueue to prioritize when Workers are receiving Tasks from both types of TaskQueues
/// </summary>
public WorkspaceResource.QueueOrderEnum PrioritizeQueueOrder { get; set; }
/// <summary>
/// Construct a new CreateWorkspaceOptions
/// </summary>
/// <param name="friendlyName"> A string to describe the Workspace resource </param>
public CreateWorkspaceOptions(string friendlyName)
{
FriendlyName = friendlyName;
}
/// <summary>
/// Generate the necessary parameters
/// </summary>
public List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
if (FriendlyName != null)
{
p.Add(new KeyValuePair<string, string>("FriendlyName", FriendlyName));
}
if (EventCallbackUrl != null)
{
p.Add(new KeyValuePair<string, string>("EventCallbackUrl", Serializers.Url(EventCallbackUrl)));
}
if (EventsFilter != null)
{
p.Add(new KeyValuePair<string, string>("EventsFilter", EventsFilter));
}
if (MultiTaskEnabled != null)
{
p.Add(new KeyValuePair<string, string>("MultiTaskEnabled", MultiTaskEnabled.Value.ToString().ToLower()));
}
if (Template != null)
{
p.Add(new KeyValuePair<string, string>("Template", Template));
}
if (PrioritizeQueueOrder != null)
{
p.Add(new KeyValuePair<string, string>("PrioritizeQueueOrder", PrioritizeQueueOrder.ToString()));
}
return p;
}
}
/// <summary>
/// DeleteWorkspaceOptions
/// </summary>
public class DeleteWorkspaceOptions : IOptions<WorkspaceResource>
{
/// <summary>
/// The SID of the resource to delete
/// </summary>
public string PathSid { get; }
/// <summary>
/// Construct a new DeleteWorkspaceOptions
/// </summary>
/// <param name="pathSid"> The SID of the resource to delete </param>
public DeleteWorkspaceOptions(string pathSid)
{
PathSid = pathSid;
}
/// <summary>
/// Generate the necessary parameters
/// </summary>
public List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
return p;
}
}
}
| |
//
// ScrollViewBackend.cs
//
// Author:
// Lluis Sanchez Gual <lluis@xamarin.com>
//
// Copyright (c) 2012 Xamarin Inc
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using Xwt.Backends;
using MonoMac.AppKit;
namespace Xwt.Mac
{
public class ScrollViewBackend: ViewBackend<NSScrollView,IScrollViewEventSink>, IScrollViewBackend
{
IWidgetBackend child;
ScrollPolicy verticalScrollPolicy;
ScrollPolicy horizontalScrollPolicy;
NormalClipView clipView;
public override void Initialize ()
{
ViewObject = new CustomScrollView ();
Widget.HasHorizontalScroller = true;
Widget.HasVerticalScroller = true;
Widget.AutoresizesSubviews = true;
}
protected override Size GetNaturalSize ()
{
return EventSink.GetDefaultNaturalSize ();
}
public void SetChild (IWidgetBackend child)
{
this.child = child;
ViewBackend backend = (ViewBackend) child;
if (backend.EventSink.SupportsCustomScrolling ()) {
var vs = new ScrollAdjustmentBackend (Widget, true);
var hs = new ScrollAdjustmentBackend (Widget, false);
CustomClipView clipView = new CustomClipView (hs, vs);
Widget.ContentView = clipView;
var dummy = new DummyClipView ();
dummy.AddSubview (backend.Widget);
backend.Widget.Frame = new System.Drawing.RectangleF (0, 0, clipView.Frame.Width, clipView.Frame.Height);
clipView.DocumentView = dummy;
backend.EventSink.SetScrollAdjustments (hs, vs);
vertScroll = vs;
horScroll = hs;
}
else {
clipView = new NormalClipView ();
clipView.Scrolled += OnScrolled;
Widget.ContentView = clipView;
Widget.DocumentView = backend.Widget;
UpdateChildSize ();
}
}
public ScrollPolicy VerticalScrollPolicy {
get {
return verticalScrollPolicy;
}
set {
verticalScrollPolicy = value;
Widget.HasVerticalScroller = verticalScrollPolicy != ScrollPolicy.Never;
}
}
public ScrollPolicy HorizontalScrollPolicy {
get {
return horizontalScrollPolicy;
}
set {
horizontalScrollPolicy = value;
Widget.HasHorizontalScroller = horizontalScrollPolicy != ScrollPolicy.Never;
}
}
IScrollControlBackend vertScroll;
public IScrollControlBackend CreateVerticalScrollControl ()
{
if (vertScroll == null)
vertScroll = new ScrollControlBackend (ApplicationContext, Widget, true);
return vertScroll;
}
IScrollControlBackend horScroll;
public IScrollControlBackend CreateHorizontalScrollControl ()
{
if (horScroll == null)
horScroll = new ScrollControlBackend (ApplicationContext, Widget, false);
return horScroll;
}
void OnScrolled (object o, EventArgs e)
{
if (vertScroll is ScrollControlBackend)
((ScrollControlBackend)vertScroll).NotifyValueChanged ();
if (horScroll is ScrollControlBackend)
((ScrollControlBackend)horScroll).NotifyValueChanged ();
}
public Rectangle VisibleRect {
get {
return Rectangle.Zero;
}
}
public bool BorderVisible {
get {
return false;
}
set {
}
}
void UpdateChildSize ()
{
if (child == null)
return;
if (Widget.ContentView is CustomClipView) {
} else {
NSView view = (NSView)Widget.DocumentView;
ViewBackend c = (ViewBackend)child;
Size s;
if (horizontalScrollPolicy == ScrollPolicy.Never) {
s = c.Frontend.Surface.GetPreferredSize (SizeConstraint.WithSize (Widget.ContentView.Frame.Width), SizeConstraint.Unconstrained);
}
else if (verticalScrollPolicy == ScrollPolicy.Never) {
s = c.Frontend.Surface.GetPreferredSize (SizeConstraint.Unconstrained, SizeConstraint.WithSize (Widget.ContentView.Frame.Width));
}
else {
s = c.Frontend.Surface.GetPreferredSize ();
}
var w = Math.Max (s.Width, Widget.ContentView.Frame.Width);
var h = Math.Max (s.Height, Widget.ContentView.Frame.Height);
view.Frame = new System.Drawing.RectangleF (view.Frame.X, view.Frame.Y, (float)w, (float)h);
}
}
public void SetChildSize (Size s)
{
UpdateChildSize ();
}
}
class CustomScrollView: NSScrollView, IViewObject
{
public NSView View {
get {
return this;
}
}
public ViewBackend Backend { get; set; }
public override bool IsFlipped {
get {
return true;
}
}
}
class DummyClipView: NSView
{
public override bool IsFlipped {
get {
return true;
}
}
}
class CustomClipView: NSClipView
{
ScrollAdjustmentBackend hScroll;
ScrollAdjustmentBackend vScroll;
float currentX;
float currentY;
float ratioX = 1, ratioY = 1;
public CustomClipView (ScrollAdjustmentBackend hScroll, ScrollAdjustmentBackend vScroll)
{
this.hScroll = hScroll;
this.vScroll = vScroll;
CopiesOnScroll = false;
}
public double CurrentX {
get {
return hScroll.LowerValue + (currentX / ratioX);
}
set {
ScrollToPoint (new System.Drawing.PointF ((float)(value - hScroll.LowerValue) * ratioX, currentY));
}
}
public double CurrentY {
get {
return vScroll.LowerValue + (currentY / ratioY);
}
set {
ScrollToPoint (new System.Drawing.PointF (currentX, (float)(value - vScroll.LowerValue) * ratioY));
}
}
public override bool IsFlipped {
get {
return true;
}
}
public override void SetFrameSize (System.Drawing.SizeF newSize)
{
base.SetFrameSize (newSize);
var v = DocumentView.Subviews [0];
v.Frame = new System.Drawing.RectangleF (v.Frame.X, v.Frame.Y, newSize.Width, newSize.Height);
}
public override void ScrollToPoint (System.Drawing.PointF newOrigin)
{
base.ScrollToPoint (newOrigin);
var v = DocumentView.Subviews [0];
currentX = newOrigin.X >= 0 ? newOrigin.X : 0;
currentY = newOrigin.Y >= 0 ? newOrigin.Y : 0;
if (currentX + v.Frame.Width > DocumentView.Frame.Width)
currentX = DocumentView.Frame.Width - v.Frame.Width;
if (currentY + v.Frame.Height > DocumentView.Frame.Height)
currentY = DocumentView.Frame.Height - v.Frame.Height;
v.Frame = new System.Drawing.RectangleF (currentX, currentY, v.Frame.Width, v.Frame.Height);
hScroll.NotifyValueChanged ();
vScroll.NotifyValueChanged ();
}
public void UpdateDocumentSize ()
{
var vr = DocumentVisibleRect ();
ratioX = hScroll.PageSize != 0 ? vr.Width / (float)hScroll.PageSize : 1;
ratioY = vScroll.PageSize != 0 ? vr.Height / (float)vScroll.PageSize : 1;
DocumentView.Frame = new System.Drawing.RectangleF (0, 0, (float)(hScroll.UpperValue - hScroll.LowerValue) * ratioX, (float)(vScroll.UpperValue - vScroll.LowerValue) * ratioY);
}
}
class NormalClipView: NSClipView
{
public event EventHandler Scrolled;
public override void ScrollToPoint (System.Drawing.PointF newOrigin)
{
base.ScrollToPoint (newOrigin);
if (Scrolled != null)
Scrolled (this, EventArgs.Empty);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Threading.Tasks;
using Orleans.Runtime;
using Orleans.Providers;
using Orleans.Runtime.Configuration;
namespace Orleans.Streams
{
/// <summary>
/// Provider-facing interface for manager of streaming providers
/// </summary>
internal interface IStreamProviderRuntime : IProviderRuntime
{
/// <summary>
/// Retrieves the opaque identity of currently executing grain or client object.
/// Just for logging purposes.
/// </summary>
/// <param name="handler"></param>
string ExecutingEntityIdentity();
SiloAddress ExecutingSiloAddress { get; }
StreamDirectory GetStreamDirectory();
void RegisterSystemTarget(ISystemTarget target);
void UnRegisterSystemTarget(ISystemTarget target);
/// <summary>
/// Binds an extension to an addressable object, if not already done.
/// </summary>
/// <typeparam name="TExtension">The type of the extension (e.g. StreamConsumerExtension).</typeparam>
/// <param name="newExtensionFunc">A factory function that constructs a new extension object.</param>
/// <returns>A tuple, containing first the extension and second an addressable reference to the extension's interface.</returns>
Task<Tuple<TExtension, TExtensionInterface>> BindExtension<TExtension, TExtensionInterface>(Func<TExtension> newExtensionFunc)
where TExtension : IGrainExtension
where TExtensionInterface : IGrainExtension;
/// <summary>
/// A Pub Sub runtime interface.
/// </summary>
/// <returns></returns>
IStreamPubSub PubSub(StreamPubSubType pubSubType);
/// <summary>
/// A consistent ring interface.
/// </summary>
/// <param name="numSubRanges">Total number of sub ranges within this silo range.</param>
/// <returns></returns>
IConsistentRingProviderForGrains GetConsistentRingProvider(int mySubRangeIndex, int numSubRanges);
/// <summary>
/// Return true if this runtime executes inside silo, false otherwise (on the client).
/// </summary>
/// <param name="pubSubType"></param>
/// <returns></returns>
bool InSilo { get; }
object GetCurrentSchedulingContext();
}
/// <summary>
/// Provider-facing interface for manager of streaming providers
/// </summary>
internal interface ISiloSideStreamProviderRuntime : IStreamProviderRuntime
{
/// <summary>
/// Start the pulling agents for a given persistent stream provider.
/// </summary>
/// <param name="streamProviderName"></param>
/// <param name="balancerType"></param>
/// <param name="pubSubType"></param>
/// <param name="adapterFactory"></param>
/// <param name="queueAdapter"></param>
/// <param name="getQueueMsgsTimerPeriod"></param>
/// <param name="initQueueTimeout"></param>
/// <returns></returns>
Task<IPersistentStreamPullingManager> InitializePullingAgents(
string streamProviderName,
IQueueAdapterFactory adapterFactory,
IQueueAdapter queueAdapter,
PersistentStreamProviderConfig config);
}
public enum StreamPubSubType
{
ExplicitGrainBasedAndImplicit,
ExplicitGrainBasedOnly,
ImplicitOnly,
}
[Serializable]
public class PersistentStreamProviderConfig
{
public const string GET_QUEUE_MESSAGES_TIMER_PERIOD = "GetQueueMessagesTimerPeriod";
public static readonly TimeSpan DEFAULT_GET_QUEUE_MESSAGES_TIMER_PERIOD = TimeSpan.FromMilliseconds(100);
public const string INIT_QUEUE_TIMEOUT = "InitQueueTimeout";
public static readonly TimeSpan DEFAULT_INIT_QUEUE_TIMEOUT = TimeSpan.FromSeconds(5);
public const string MAX_EVENT_DELIVERY_TIME = "MaxEventDeliveryTime";
public static readonly TimeSpan DEFAULT_MAX_EVENT_DELIVERY_TIME = TimeSpan.FromMinutes(1);
public const string STREAM_INACTIVITY_PERIOD = "StreamInactivityPeriod";
public static readonly TimeSpan DEFAULT_STREAM_INACTIVITY_PERIOD = TimeSpan.FromMinutes(30);
public const string QUEUE_BALANCER_TYPE = "QueueBalancerType";
public const StreamQueueBalancerType DEFAULT_STREAM_QUEUE_BALANCER_TYPE = StreamQueueBalancerType.ConsistentRingBalancer;
public const string STREAM_PUBSUB_TYPE = "PubSubType";
public const StreamPubSubType DEFAULT_STREAM_PUBSUB_TYPE = StreamPubSubType.ExplicitGrainBasedAndImplicit;
public const string SILO_MATURITY_PERIOD = "SiloMaturityPeriod";
public static readonly TimeSpan DEFAULT_SILO_MATURITY_PERIOD = TimeSpan.FromMinutes(2);
public TimeSpan GetQueueMsgsTimerPeriod { get; set; } = DEFAULT_GET_QUEUE_MESSAGES_TIMER_PERIOD;
public TimeSpan InitQueueTimeout { get; set; } = DEFAULT_INIT_QUEUE_TIMEOUT;
public TimeSpan MaxEventDeliveryTime { get; set; } = DEFAULT_MAX_EVENT_DELIVERY_TIME;
public TimeSpan StreamInactivityPeriod { get; set; } = DEFAULT_STREAM_INACTIVITY_PERIOD;
public StreamQueueBalancerType BalancerType { get; set; } = DEFAULT_STREAM_QUEUE_BALANCER_TYPE;
public StreamPubSubType PubSubType { get; set; } = DEFAULT_STREAM_PUBSUB_TYPE;
public TimeSpan SiloMaturityPeriod { get; set; } = DEFAULT_SILO_MATURITY_PERIOD;
public PersistentStreamProviderConfig()
{
}
public PersistentStreamProviderConfig(IProviderConfiguration config)
{
string timePeriod;
if (config.Properties.TryGetValue(GET_QUEUE_MESSAGES_TIMER_PERIOD, out timePeriod))
GetQueueMsgsTimerPeriod = ConfigUtilities.ParseTimeSpan(timePeriod,
"Invalid time value for the " + GET_QUEUE_MESSAGES_TIMER_PERIOD + " property in the provider config values.");
string timeout;
if (config.Properties.TryGetValue(INIT_QUEUE_TIMEOUT, out timeout))
InitQueueTimeout = ConfigUtilities.ParseTimeSpan(timeout,
"Invalid time value for the " + INIT_QUEUE_TIMEOUT + " property in the provider config values.");
string balanceTypeString;
if (config.Properties.TryGetValue(QUEUE_BALANCER_TYPE, out balanceTypeString))
BalancerType = (StreamQueueBalancerType)Enum.Parse(typeof(StreamQueueBalancerType), balanceTypeString);
if (config.Properties.TryGetValue(MAX_EVENT_DELIVERY_TIME, out timeout))
MaxEventDeliveryTime = ConfigUtilities.ParseTimeSpan(timeout,
"Invalid time value for the " + MAX_EVENT_DELIVERY_TIME + " property in the provider config values.");
if (config.Properties.TryGetValue(STREAM_INACTIVITY_PERIOD, out timeout))
StreamInactivityPeriod = ConfigUtilities.ParseTimeSpan(timeout,
"Invalid time value for the " + STREAM_INACTIVITY_PERIOD + " property in the provider config values.");
string pubSubTypeString;
if (config.Properties.TryGetValue(STREAM_PUBSUB_TYPE, out pubSubTypeString))
PubSubType = (StreamPubSubType)Enum.Parse(typeof(StreamPubSubType), pubSubTypeString);
string immaturityPeriod;
if (config.Properties.TryGetValue(SILO_MATURITY_PERIOD, out immaturityPeriod))
SiloMaturityPeriod = ConfigUtilities.ParseTimeSpan(immaturityPeriod,
"Invalid time value for the " + SILO_MATURITY_PERIOD + " property in the provider config values.");
}
/// <summary>
/// Utility function to convert config to property bag for use in stream provider configuration
/// </summary>
/// <returns></returns>
public void WriteProperties(Dictionary<string, string> properties)
{
properties[GET_QUEUE_MESSAGES_TIMER_PERIOD] = ConfigUtilities.ToParseableTimeSpan(GetQueueMsgsTimerPeriod);
properties[INIT_QUEUE_TIMEOUT] = ConfigUtilities.ToParseableTimeSpan(InitQueueTimeout);
properties[QUEUE_BALANCER_TYPE] = BalancerType.ToString();
properties[MAX_EVENT_DELIVERY_TIME] = ConfigUtilities.ToParseableTimeSpan(MaxEventDeliveryTime);
properties[STREAM_INACTIVITY_PERIOD] = ConfigUtilities.ToParseableTimeSpan(StreamInactivityPeriod);
properties[STREAM_PUBSUB_TYPE] = PubSubType.ToString();
properties[SILO_MATURITY_PERIOD] = ConfigUtilities.ToParseableTimeSpan(SiloMaturityPeriod);
}
public override string ToString()
{
return String.Format("{0}={1}, {2}={3}, {4}={5}, {6}={7}, {8}={9}, {10}={11}, {12}={13}",
GET_QUEUE_MESSAGES_TIMER_PERIOD, GetQueueMsgsTimerPeriod,
INIT_QUEUE_TIMEOUT, InitQueueTimeout,
MAX_EVENT_DELIVERY_TIME, MaxEventDeliveryTime,
STREAM_INACTIVITY_PERIOD, StreamInactivityPeriod,
QUEUE_BALANCER_TYPE, BalancerType,
STREAM_PUBSUB_TYPE, PubSubType,
SILO_MATURITY_PERIOD, SiloMaturityPeriod);
}
}
internal interface IStreamPubSub // Compare with: IPubSubRendezvousGrain
{
Task<ISet<PubSubSubscriptionState>> RegisterProducer(StreamId streamId, string streamProvider, IStreamProducerExtension streamProducer);
Task UnregisterProducer(StreamId streamId, string streamProvider, IStreamProducerExtension streamProducer);
Task RegisterConsumer(GuidId subscriptionId, StreamId streamId, string streamProvider, IStreamConsumerExtension streamConsumer, IStreamFilterPredicateWrapper filter);
Task UnregisterConsumer(GuidId subscriptionId, StreamId streamId, string streamProvider);
Task<int> ProducerCount(Guid streamId, string streamProvider, string streamNamespace);
Task<int> ConsumerCount(Guid streamId, string streamProvider, string streamNamespace);
Task<List<GuidId>> GetAllSubscriptions(StreamId streamId, IStreamConsumerExtension streamConsumer);
GuidId CreateSubscriptionId(StreamId streamId, IStreamConsumerExtension streamConsumer);
Task<bool> FaultSubscription(StreamId streamId, GuidId subscriptionId);
}
}
| |
// 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 SigningServiceApiCaller
{
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Models;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
public partial class LykkeSigningAPI : ServiceClient<LykkeSigningAPI>, ILykkeSigningAPI
{
/// <summary>
/// The base URI of the service.
/// </summary>
public System.Uri BaseUri { get; set; }
/// <summary>
/// Gets or sets json serialization settings.
/// </summary>
public JsonSerializerSettings SerializationSettings { get; private set; }
/// <summary>
/// Gets or sets json deserialization settings.
/// </summary>
public JsonSerializerSettings DeserializationSettings { get; private set; }
/// <summary>
/// Initializes a new instance of the LykkeSigningAPI class.
/// </summary>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
public LykkeSigningAPI(params DelegatingHandler[] handlers) : base(handlers)
{
Initialize();
}
/// <summary>
/// Initializes a new instance of the LykkeSigningAPI class.
/// </summary>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
public LykkeSigningAPI(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers)
{
Initialize();
}
/// <summary>
/// Initializes a new instance of the LykkeSigningAPI class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public LykkeSigningAPI(System.Uri baseUri, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the LykkeSigningAPI class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public LykkeSigningAPI(System.Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
BaseUri = baseUri;
}
/// <summary>
/// An optional partial-method to perform custom initialization.
///</summary>
partial void CustomInitialize();
/// <summary>
/// Initializes client properties.
/// </summary>
private void Initialize()
{
BaseUri = new System.Uri("http://localhost/");
SerializationSettings = new JsonSerializerSettings
{
Formatting = Newtonsoft.Json.Formatting.Indented,
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
DeserializationSettings = new JsonSerializerSettings
{
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
CustomInitialize();
}
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="HttpOperationException">
/// 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<PubKeyResponse>> ApiBitcoinKeyGetWithHttpMessagesAsync(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, "ApiBitcoinKeyGet", tracingParameters);
}
// Construct URL
var _baseUrl = BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/Bitcoin/key").ToString();
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (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 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 HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
if (_httpResponse.Content != null) {
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
else {
_responseContent = string.Empty;
}
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<PubKeyResponse>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<PubKeyResponse>(_responseContent, 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;
}
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="HttpOperationException">
/// 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> ApiBitcoinTempKeyGetWithHttpMessagesAsync(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, "ApiBitcoinTempKeyGet", tracingParameters);
}
// Construct URL
var _baseUrl = BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/Bitcoin/tempKey").ToString();
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (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 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 HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
if (_httpResponse.Content != null) {
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
else {
_responseContent = string.Empty;
}
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;
}
/// <param name='model'>
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="HttpOperationException">
/// 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> ApiBitcoinAddkeyPostWithHttpMessagesAsync(AddKeyRequest model = default(AddKeyRequest), 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("model", model);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ApiBitcoinAddkeyPost", tracingParameters);
}
// Construct URL
var _baseUrl = BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/Bitcoin/addkey").ToString();
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("POST");
_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;
if(model != null)
{
_requestContent = SafeJsonConvert.SerializeObject(model, SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await 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 HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
if (_httpResponse.Content != null) {
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
else {
_responseContent = string.Empty;
}
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;
}
/// <param name='signRequest'>
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="HttpOperationException">
/// 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<TransactionSignResponse>> ApiBitcoinSignPostWithHttpMessagesAsync(BitcoinTransactionSignRequest signRequest = default(BitcoinTransactionSignRequest), 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("signRequest", signRequest);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ApiBitcoinSignPost", tracingParameters);
}
// Construct URL
var _baseUrl = BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/Bitcoin/sign").ToString();
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("POST");
_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;
if(signRequest != null)
{
_requestContent = SafeJsonConvert.SerializeObject(signRequest, SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await 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 HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
if (_httpResponse.Content != null) {
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
else {
_responseContent = string.Empty;
}
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<TransactionSignResponse>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<TransactionSignResponse>(_responseContent, 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;
}
/// <param name='address'>
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="HttpOperationException">
/// 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<PrivateKeyResponse>> ApiBitcoinGetkeyGetWithHttpMessagesAsync(string address = default(string), 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("address", address);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ApiBitcoinGetkeyGet", tracingParameters);
}
// Construct URL
var _baseUrl = BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/Bitcoin/getkey").ToString();
List<string> _queryParameters = new List<string>();
if (address != null)
{
_queryParameters.Add(string.Format("address={0}", System.Uri.EscapeDataString(address)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (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 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 HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
if (_httpResponse.Content != null) {
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
else {
_responseContent = string.Empty;
}
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<PrivateKeyResponse>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<PrivateKeyResponse>(_responseContent, 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;
}
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="HttpOperationException">
/// 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<EthereumAddressResponse>> ApiEthereumKeyGetWithHttpMessagesAsync(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, "ApiEthereumKeyGet", tracingParameters);
}
// Construct URL
var _baseUrl = BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/Ethereum/key").ToString();
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (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 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 HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
if (_httpResponse.Content != null) {
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
else {
_responseContent = string.Empty;
}
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<EthereumAddressResponse>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<EthereumAddressResponse>(_responseContent, 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;
}
/// <param name='model'>
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="HttpOperationException">
/// 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> ApiEthereumAddkeyPostWithHttpMessagesAsync(AddKeyRequest model = default(AddKeyRequest), 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("model", model);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ApiEthereumAddkeyPost", tracingParameters);
}
// Construct URL
var _baseUrl = BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/Ethereum/addkey").ToString();
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("POST");
_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;
if(model != null)
{
_requestContent = SafeJsonConvert.SerializeObject(model, SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await 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 HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
if (_httpResponse.Content != null) {
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
else {
_responseContent = string.Empty;
}
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;
}
/// <param name='signRequest'>
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="HttpOperationException">
/// 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<TransactionSignResponse>> ApiEthereumSignPostWithHttpMessagesAsync(EthereumTransactionSignRequest signRequest = default(EthereumTransactionSignRequest), 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("signRequest", signRequest);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ApiEthereumSignPost", tracingParameters);
}
// Construct URL
var _baseUrl = BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/Ethereum/sign").ToString();
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("POST");
_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;
if(signRequest != null)
{
_requestContent = SafeJsonConvert.SerializeObject(signRequest, SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await 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 HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
if (_httpResponse.Content != null) {
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
else {
_responseContent = string.Empty;
}
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<TransactionSignResponse>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<TransactionSignResponse>(_responseContent, 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;
}
/// <param name='signRequest'>
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="HttpOperationException">
/// 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<HashSignResponse>> ApiEthereumSignHashPostWithHttpMessagesAsync(EthereumHashSignRequest signRequest = default(EthereumHashSignRequest), 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("signRequest", signRequest);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ApiEthereumSignHashPost", tracingParameters);
}
// Construct URL
var _baseUrl = BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/Ethereum/signHash").ToString();
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("POST");
_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;
if(signRequest != null)
{
_requestContent = SafeJsonConvert.SerializeObject(signRequest, SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await 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 HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
if (_httpResponse.Content != null) {
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
else {
_responseContent = string.Empty;
}
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<HashSignResponse>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<HashSignResponse>(_responseContent, 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;
}
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="HttpOperationException">
/// 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<IsAliveResponse>> ApiIsAliveGetWithHttpMessagesAsync(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, "ApiIsAliveGet", tracingParameters);
}
// Construct URL
var _baseUrl = BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/IsAlive").ToString();
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (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 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 HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
if (_httpResponse.Content != null) {
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
else {
_responseContent = string.Empty;
}
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<IsAliveResponse>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<IsAliveResponse>(_responseContent, 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) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
// Testing JIT handling and GC reporting of liveness of GC variable
using System;
using System.Collections.Generic;
internal class Test
{
public static int aExists;
public static int bExists;
private abstract class A
{
}
private class B : A
{
public B()
{
aExists++;
}
~B()
{
aExists--;
Console.WriteLine("~B");
}
public void F()
{
Console.WriteLine("B.F");
}
}
private class C : B
{
public C()
{
bExists++;
}
~C()
{
bExists--;
Console.WriteLine("~C");
}
public void G()
{
Console.WriteLine("C.G");
}
}
private static int f1()
{
B a = new B();
a.F();
Console.WriteLine();
Console.WriteLine("testcase f1-1");
if (aExists != 1)
{
Console.WriteLine("f1-1 failed");
return -1;
}
GC.KeepAlive(a);
a = null;
GC.Collect();
GC.WaitForPendingFinalizers();
Console.WriteLine();
Console.WriteLine("testcase f1-2");
if (aExists != 0)
{
Console.WriteLine("f1-2 failed");
return -1;
}
C b = new C();
b.G();
Console.WriteLine();
Console.WriteLine("testcase f1-3");
if ((aExists != 1) || (bExists != 1))
{
Console.WriteLine("f1-3 failed");
return -1;
}
GC.KeepAlive(b);
b = null;
GC.Collect();
GC.WaitForPendingFinalizers();
Console.WriteLine();
Console.WriteLine("testcase f1-4");
if ((aExists != 0) || (bExists != 0))
{
Console.WriteLine("f1-4 failed");
return -1;
}
return 100;
}
private static int f2()
{
B a = new B();
{
C b = new C();
b.G();
b = null;
}
GC.Collect();
GC.WaitForPendingFinalizers();
a.F();
Console.WriteLine();
Console.WriteLine("testcase f2-1");
if ((aExists != 1) || (bExists != 0))
{
Console.WriteLine("f2-1 failed");
return -1;
}
GC.KeepAlive(a);
a = null;
GC.Collect();
GC.WaitForPendingFinalizers();
Console.WriteLine();
Console.WriteLine("testcase f2-2");
if (aExists != 0)
{
Console.WriteLine("f2-2 failed");
return -1;
}
return 100;
}
private static int f3()
{
C b = new C();
b = null;
GC.Collect();
GC.WaitForPendingFinalizers();
Console.WriteLine();
Console.WriteLine("testcase f3");
if (aExists != 0)
{
Console.WriteLine("f3 failed");
return -1;
}
b = null;
return 100;
}
private static int f4()
{
B a = new B();
a.F();
C b = new C();
b.G();
Console.WriteLine();
Console.WriteLine("testcase f4");
if ((aExists != 2) || (bExists != 1))
{
Console.WriteLine("f4 failed");
return -1;
}
GC.KeepAlive(a);
GC.KeepAlive(b);
return 100;
}
private static int f5()
{
Console.WriteLine();
Console.WriteLine("testcase f5");
if ((aExists != 0) || (bExists != 0))
{
Console.WriteLine("f5 failed");
return -1;
}
return 100;
}
private static int Main()
{
if (f1() != 100)
return -1;
CleanGC();
if (f2() != 100)
return -1;
CleanGC();
if (f3() != 100)
return -1;
CleanGC();
if (f4() != 100)
return -1;
CleanGC();
if (f5() != 100)
return -1;
CleanGC();
Console.WriteLine("PASSED");
return 100;
}
private static void CleanGC()
{
GC.Collect();
GC.WaitForPendingFinalizers();
}
}
| |
/*
* 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.Reflection;
using System.Collections.Generic;
using log4net;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
namespace OpenSim.Framework
{
/// <summary>
/// Circuit data for an agent. Connection information shared between
/// regions that accept UDP connections from a client
/// </summary>
public class AgentCircuitData
{
// DEBUG ON
private static readonly ILog m_log =
LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
// DEBUG OFF
/// <summary>
/// Avatar Unique Agent Identifier
/// </summary>
public UUID AgentID;
/// <summary>
/// Avatar's Appearance
/// </summary>
public AvatarAppearance Appearance;
/// <summary>
/// Agent's root inventory folder
/// </summary>
public UUID BaseFolder;
/// <summary>
/// Base Caps path for user
/// </summary>
public string CapsPath = String.Empty;
/// <summary>
/// Seed caps for neighbor regions that the user can see into
/// </summary>
public Dictionary<ulong, string> ChildrenCapSeeds;
/// <summary>
/// Root agent, or Child agent
/// </summary>
public bool child;
/// <summary>
/// Number given to the client when they log-in that they provide
/// as credentials to the UDP server
/// </summary>
public uint circuitcode;
/// <summary>
/// How this agent got here
/// </summary>
public uint teleportFlags;
/// <summary>
/// Agent's account first name
/// </summary>
public string firstname;
public UUID InventoryFolder;
/// <summary>
/// Agent's account last name
/// </summary>
public string lastname;
/// <summary>
/// Agent's full name.
/// </summary>
public string Name { get { return string.Format("{0} {1}", firstname, lastname); } }
/// <summary>
/// Random Unique GUID for this session. Client gets this at login and it's
/// only supposed to be disclosed over secure channels
/// </summary>
public UUID SecureSessionID;
/// <summary>
/// Non secure Session ID
/// </summary>
public UUID SessionID;
/// <summary>
/// Hypergrid service token; generated by the user domain, consumed by the receiving grid.
/// There is one such unique token for each grid visited.
/// </summary>
public string ServiceSessionID = string.Empty;
/// <summary>
/// The client's IP address, as captured by the login service
/// </summary>
public string IPAddress;
/// <summary>
/// Viewer's version string as reported by the viewer at login
/// </summary>
public string Viewer;
/// <summary>
/// The channel strinf sent by the viewer at login
/// </summary>
public string Channel;
/// <summary>
/// The Mac address as reported by the viewer at login
/// </summary>
public string Mac;
/// <summary>
/// The id0 as reported by the viewer at login
/// </summary>
public string Id0;
/// <summary>
/// Position the Agent's Avatar starts in the region
/// </summary>
public Vector3 startpos;
public Dictionary<string, object> ServiceURLs;
public AgentCircuitData()
{
}
/// <summary>
/// Pack AgentCircuitData into an OSDMap for transmission over LLSD XML or LLSD json
/// </summary>
/// <returns>map of the agent circuit data</returns>
public OSDMap PackAgentCircuitData()
{
OSDMap args = new OSDMap();
args["agent_id"] = OSD.FromUUID(AgentID);
args["base_folder"] = OSD.FromUUID(BaseFolder);
args["caps_path"] = OSD.FromString(CapsPath);
if (ChildrenCapSeeds != null)
{
OSDArray childrenSeeds = new OSDArray(ChildrenCapSeeds.Count);
foreach (KeyValuePair<ulong, string> kvp in ChildrenCapSeeds)
{
OSDMap pair = new OSDMap();
pair["handle"] = OSD.FromString(kvp.Key.ToString());
pair["seed"] = OSD.FromString(kvp.Value);
childrenSeeds.Add(pair);
}
if (ChildrenCapSeeds.Count > 0)
args["children_seeds"] = childrenSeeds;
}
args["child"] = OSD.FromBoolean(child);
args["circuit_code"] = OSD.FromString(circuitcode.ToString());
args["first_name"] = OSD.FromString(firstname);
args["last_name"] = OSD.FromString(lastname);
args["inventory_folder"] = OSD.FromUUID(InventoryFolder);
args["secure_session_id"] = OSD.FromUUID(SecureSessionID);
args["session_id"] = OSD.FromUUID(SessionID);
args["service_session_id"] = OSD.FromString(ServiceSessionID);
args["start_pos"] = OSD.FromString(startpos.ToString());
args["client_ip"] = OSD.FromString(IPAddress);
args["viewer"] = OSD.FromString(Viewer);
args["channel"] = OSD.FromString(Channel);
args["mac"] = OSD.FromString(Mac);
args["id0"] = OSD.FromString(Id0);
if (Appearance != null)
{
args["appearance_serial"] = OSD.FromInteger(Appearance.Serial);
OSDMap appmap = Appearance.Pack();
args["packed_appearance"] = appmap;
}
// Old, bad way. Keeping it fow now for backwards compatibility
// OBSOLETE -- soon to be deleted
if (ServiceURLs != null && ServiceURLs.Count > 0)
{
OSDArray urls = new OSDArray(ServiceURLs.Count * 2);
foreach (KeyValuePair<string, object> kvp in ServiceURLs)
{
//System.Console.WriteLine("XXX " + kvp.Key + "=" + kvp.Value);
urls.Add(OSD.FromString(kvp.Key));
urls.Add(OSD.FromString((kvp.Value == null) ? string.Empty : kvp.Value.ToString()));
}
args["service_urls"] = urls;
}
// again, this time the right way
if (ServiceURLs != null && ServiceURLs.Count > 0)
{
OSDMap urls = new OSDMap();
foreach (KeyValuePair<string, object> kvp in ServiceURLs)
{
//System.Console.WriteLine("XXX " + kvp.Key + "=" + kvp.Value);
urls[kvp.Key] = OSD.FromString((kvp.Value == null) ? string.Empty : kvp.Value.ToString());
}
args["serviceurls"] = urls;
}
return args;
}
/// <summary>
/// Unpack agent circuit data map into an AgentCiruitData object
/// </summary>
/// <param name="args"></param>
public void UnpackAgentCircuitData(OSDMap args)
{
if (args["agent_id"] != null)
AgentID = args["agent_id"].AsUUID();
if (args["base_folder"] != null)
BaseFolder = args["base_folder"].AsUUID();
if (args["caps_path"] != null)
CapsPath = args["caps_path"].AsString();
if ((args["children_seeds"] != null) && (args["children_seeds"].Type == OSDType.Array))
{
OSDArray childrenSeeds = (OSDArray)(args["children_seeds"]);
ChildrenCapSeeds = new Dictionary<ulong, string>();
foreach (OSD o in childrenSeeds)
{
if (o.Type == OSDType.Map)
{
ulong handle = 0;
string seed = "";
OSDMap pair = (OSDMap)o;
if (pair["handle"] != null)
if (!UInt64.TryParse(pair["handle"].AsString(), out handle))
continue;
if (pair["seed"] != null)
seed = pair["seed"].AsString();
if (!ChildrenCapSeeds.ContainsKey(handle))
ChildrenCapSeeds.Add(handle, seed);
}
}
}
else
ChildrenCapSeeds = new Dictionary<ulong, string>();
if (args["child"] != null)
child = args["child"].AsBoolean();
if (args["circuit_code"] != null)
UInt32.TryParse(args["circuit_code"].AsString(), out circuitcode);
if (args["first_name"] != null)
firstname = args["first_name"].AsString();
if (args["last_name"] != null)
lastname = args["last_name"].AsString();
if (args["inventory_folder"] != null)
InventoryFolder = args["inventory_folder"].AsUUID();
if (args["secure_session_id"] != null)
SecureSessionID = args["secure_session_id"].AsUUID();
if (args["session_id"] != null)
SessionID = args["session_id"].AsUUID();
if (args["service_session_id"] != null)
ServiceSessionID = args["service_session_id"].AsString();
if (args["client_ip"] != null)
IPAddress = args["client_ip"].AsString();
if (args["viewer"] != null)
Viewer = args["viewer"].AsString();
if (args["channel"] != null)
Channel = args["channel"].AsString();
if (args["mac"] != null)
Mac = args["mac"].AsString();
if (args["id0"] != null)
Id0 = args["id0"].AsString();
if (args["start_pos"] != null)
Vector3.TryParse(args["start_pos"].AsString(), out startpos);
//m_log.InfoFormat("[AGENTCIRCUITDATA]: agentid={0}, child={1}, startpos={2}", AgentID, child, startpos);
try
{
// Unpack various appearance elements
Appearance = new AvatarAppearance();
// Eventually this code should be deprecated, use full appearance
// packing in packed_appearance
if (args["appearance_serial"] != null)
Appearance.Serial = args["appearance_serial"].AsInteger();
if (args.ContainsKey("packed_appearance") && (args["packed_appearance"].Type == OSDType.Map))
{
Appearance.Unpack((OSDMap)args["packed_appearance"]);
// m_log.InfoFormat("[AGENTCIRCUITDATA] unpacked appearance");
}
else
{
m_log.Warn("[AGENTCIRCUITDATA]: failed to find a valid packed_appearance");
}
}
catch (Exception e)
{
m_log.ErrorFormat("[AGENTCIRCUITDATA] failed to unpack appearance; {0}",e.Message);
}
ServiceURLs = new Dictionary<string, object>();
// Try parse the new way, OSDMap
if (args.ContainsKey("serviceurls") && args["serviceurls"] != null && (args["serviceurls"]).Type == OSDType.Map)
{
OSDMap urls = (OSDMap)(args["serviceurls"]);
foreach (KeyValuePair<String, OSD> kvp in urls)
{
ServiceURLs[kvp.Key] = kvp.Value.AsString();
//System.Console.WriteLine("XXX " + kvp.Key + "=" + ServiceURLs[kvp.Key]);
}
}
// else try the old way, OSDArray
// OBSOLETE -- soon to be deleted
else if (args.ContainsKey("service_urls") && args["service_urls"] != null && (args["service_urls"]).Type == OSDType.Array)
{
OSDArray urls = (OSDArray)(args["service_urls"]);
for (int i = 0; i < urls.Count / 2; i++)
{
ServiceURLs[urls[i * 2].AsString()] = urls[(i * 2) + 1].AsString();
//System.Console.WriteLine("XXX " + urls[i * 2].AsString() + "=" + urls[(i * 2) + 1].AsString());
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Lucene.Net.Analysis.Standard;
using Lucene.Net.Documents;
using Lucene.Net.Index;
using Lucene.Net.QueryParsers;
using Lucene.Net.Search;
using Lucene.Net.Search.Similar;
using PagedList;
using Version = Lucene.Net.Util.Version;
namespace Biggy.Lucene
{
/// <summary>
/// Decorator class that adds lucene full text functionality to any store
/// </summary>
/// <typeparam name="T"></typeparam>
public class LuceneStoreDecorator<T> : IQueryableBiggyStore<T>, IUpdateableBiggyStore<T>, IDisposable where T : new()
{
private readonly IBiggyStore<T> _biggyStore;
private readonly LuceneIndexer<T> _luceneIndexer;
private readonly IQueryableBiggyStore<T> _queryableStore;
private readonly IUpdateableBiggyStore<T> _updateableBiggyStore;
public LuceneStoreDecorator(IBiggyStore<T> biggyStore, bool useRamDirectory = false)
{
_biggyStore = biggyStore;
_queryableStore = _biggyStore as IQueryableBiggyStore<T>;
_updateableBiggyStore = _biggyStore as IUpdateableBiggyStore<T>;
_luceneIndexer = new LuceneIndexer<T>(useRamDirectory);
}
public List<T> Load()
{
List<T> items = _biggyStore.Load();
_luceneIndexer.DeleteAll();
_luceneIndexer.AddDocumentsToIndex(items);
return items;
}
public void SaveAll(List<T> items)
{
_biggyStore.SaveAll(items);
_luceneIndexer.DeleteAll();
_luceneIndexer.AddDocumentsToIndex(items);
}
public void Clear()
{
_biggyStore.Clear();
_luceneIndexer.DeleteAll();
}
public T Add(T item)
{
item = _biggyStore.Add(item);
_luceneIndexer.AddDocumentToIndex(item);
return item;
}
public List<T> Add(List<T> items)
{
items = _biggyStore.Add(items);
_luceneIndexer.AddDocumentsToIndex(items);
return items;
}
public void Dispose()
{
_luceneIndexer.Dispose();
}
public IQueryable<T> AsQueryable()
{
return _queryableStore.AsQueryable();
}
public virtual T Update(T item)
{
if (_updateableBiggyStore != null)
{
_updateableBiggyStore.Update(item);
_luceneIndexer.UpdateDocumentInIndex(item);
}
return item;
}
public virtual T Remove(T item)
{
if (_updateableBiggyStore != null)
{
_updateableBiggyStore.Remove(item);
_luceneIndexer.DeleteDocumentFromIndex(item);
}
return item;
}
public List<T> Remove(List<T> items)
{
if (_updateableBiggyStore != null)
{
_updateableBiggyStore.Remove(items);
_luceneIndexer.DeleteDocumentsFromIndex(items);
}
else
{
throw new InvalidOperationException("You must Implement IUpdatableBiggySotre to call this operation");
}
return items;
}
/// <summary>
/// Uses lucenes MoreLikeThis feature to find items similar to the one passed in
/// </summary>
/// <param name="item">The item to find similar items</param>
/// <param name="pageNo">Page number of the result set</param>
/// <param name="pageSize">Number of items to return in the result set</param>
/// <returns>Items similar to the one pased in</returns>
public IPagedList<T> MoreLikeThis(T item, int pageNo, int pageSize)
{
using (IndexSearcher indexSearcher = _luceneIndexer.GetSearcher())
{
var itemId = _luceneIndexer.GetIdentifier(item);
var docQuery = new TermQuery(new Term(_luceneIndexer.PrimaryKeyField, itemId));
var docHit = indexSearcher.Search(docQuery, 1);
if (docHit.ScoreDocs.Any())
{
var moreLikeThis = new MoreLikeThis(indexSearcher.IndexReader)
{
MaxDocFreq = 0,
MinTermFreq = 0
};
//moreLikeThis.SetFieldNames(_luceneIndexer.FullTextFields);
var likeQuery = moreLikeThis.Like(docHit.ScoreDocs[0].Doc);
var query = new BooleanQuery
{
{likeQuery, Occur.MUST},
//{docQuery, Occur.MUST_NOT} // Exclude the doc we basing similar matches on
};
return Search(query, pageNo, pageSize, indexSearcher);
}
return NoResults(pageNo, pageSize);
}
}
public IPagedList<T> NoResults(int pageNo, int pageSize)
{
return new StaticPagedList<T>(new List<T>(), pageNo, pageSize, 0);
}
public IPagedList<T> Search(string query, int pageNo = 1, int pageSize = 25)
{
var queryParser = new MultiFieldQueryParser(Version.LUCENE_30, _luceneIndexer.FullTextFields, new StandardAnalyzer(Version.LUCENE_30));
using (IndexSearcher indexSearcher = _luceneIndexer.GetSearcher())
{
Query searchQuery = queryParser.Parse(query);
return Search(searchQuery, pageNo, pageSize, indexSearcher);
}
}
private IPagedList<T> Search(Query searchQuery, int pageNo, int pageSize, IndexSearcher indexSearcher)
{
TopDocs hits = indexSearcher.Search(searchQuery, pageNo * pageSize);
var results = new List<T>();
int startIndex = (pageNo - 1)*pageSize;
int endIndex = pageNo*pageSize;
if (hits.TotalHits < endIndex)
endIndex = hits.TotalHits;
for (int i = startIndex; i < endIndex; i++)
{
ScoreDoc scoreDoc = hits.ScoreDocs[i];
Document doc = indexSearcher.Doc(scoreDoc.Doc);
string id = doc.Get(_luceneIndexer.PrimaryKeyField);
// We need some way to match up lucene docs to the objects
// so we use dictionary here to keep the references
if (_luceneIndexer.ItemCache.ContainsKey(id))
results.Add(_luceneIndexer.ItemCache[id]);
}
return new StaticPagedList<T>(results, pageNo, pageSize, hits.TotalHits);;
}
}
}
| |
// ==========================================================
// Updated to use UGUI, March 2015
// Dennis Trevillyan - WatreGames
//
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using UMA;
public class UMACustomization : MonoBehaviour
{
public UMAData umaData;
public UMADynamicAvatar umaDynamicAvatar;
public CameraTrack cameraTrack;
private UMADnaHumanoid umaDna;
private UMADnaTutorial umaTutorialDna;
private GameObject DnaPanel; // This is the parent panel
#pragma warning disable 0649, 0169
private GameObject DnaScrollPanel; // This is the scrollable panel that holds the sliders
// Slider objects
private Slider HeightSlider;
private Slider UpperMuscleSlider;
private Slider UpperWeightSlider;
private Slider LowerMuscleSlider;
private Slider LowerWeightSlider;
private Slider ArmLengthSlider;
private Slider ForearmLengthSlider;
private Slider LegSeparationSlider;
private Slider HandSizeSlider;
private Slider FeetSizeSlider;
private Slider LegSizeSlider;
private Slider ArmWidthSlider;
private Slider ForearmWidthSlider;
private Slider BreastSlider;
private Slider BellySlider;
private Slider WaistSizeSlider;
private Slider GlueteusSizeSlider;
private Slider HeadSizeSlider;
private Slider NeckThickSlider;
private Slider EarSizeSlider;
private Slider EarPositionSlider;
private Slider EarRotationSlider;
private Slider NoseSizeSlider;
private Slider NoseCurveSlider;
private Slider NoseWidthSlider;
private Slider NoseInclinationSlider;
private Slider NosePositionSlider;
private Slider NosePronuncedSlider;
private Slider NoseFlattenSlider;
private Slider ChinSizeSlider;
private Slider ChinPronouncedSlider;
private Slider ChinPositionSlider;
private Slider MandibleSizeSlider;
private Slider JawSizeSlider;
private Slider JawPositionSlider;
private Slider CheekSizeSlider;
private Slider CheekPositionSlider;
private Slider lowCheekPronSlider;
private Slider ForeHeadSizeSlider;
private Slider ForeHeadPositionSlider;
private Slider LipSizeSlider;
private Slider MouthSlider;
private Slider EyeSizeSlider;
private Slider EyeRotationSlider;
private Slider EyeSpacingSlider;
private Slider LowCheekPosSlider;
private Slider HeadWidthSlider;
#pragma warning disable 0649, 0169
private Slider[] sliders;
private Rect ViewPortFull = new Rect(0, 0, 1, 1);
private Rect ViewPortReduced;
private Transform baseTarget;
private Button DnaHide;
// get the sliders and store for later use
void Awake()
{
HeightSlider = GameObject.Find("HeightSlider").GetComponent<Slider>();
UpperMuscleSlider = GameObject.Find("UpperMuscleSlider").GetComponent<Slider>();
UpperWeightSlider = GameObject.Find("UpperWeightSlider").GetComponent<Slider>();
LowerMuscleSlider = GameObject.Find("LowerMuscleSlider").GetComponent<Slider>();
LowerWeightSlider = GameObject.Find("LowerWeightSlider").GetComponent<Slider>();
ArmLengthSlider = GameObject.Find("ArmLengthSlider").GetComponent<Slider>();
ForearmLengthSlider = GameObject.Find("ForearmLengthSlider").GetComponent<Slider>();
LegSeparationSlider = GameObject.Find("LegSepSlider").GetComponent<Slider>();
HandSizeSlider = GameObject.Find("HandSizeSlider").GetComponent<Slider>();
FeetSizeSlider = GameObject.Find("FeetSizeSlider").GetComponent<Slider>();
LegSizeSlider = GameObject.Find("LegSizeSlider").GetComponent<Slider>();
ArmWidthSlider = GameObject.Find("ArmWidthSlider").GetComponent<Slider>();
ForearmWidthSlider = GameObject.Find("ForearmWidthSlider").GetComponent<Slider>();
BreastSlider = GameObject.Find("BreastSizeSlider").GetComponent<Slider>();
BellySlider = GameObject.Find("BellySlider").GetComponent<Slider>();
WaistSizeSlider = GameObject.Find("WaistSizeSlider").GetComponent<Slider>();
GlueteusSizeSlider = GameObject.Find("GluteusSlider").GetComponent<Slider>();
HeadSizeSlider = GameObject.Find("HeadSizeSlider").GetComponent<Slider>();
HeadWidthSlider = GameObject.Find("HeadWidthSlider").GetComponent<Slider>();
NeckThickSlider = GameObject.Find("NeckSlider").GetComponent<Slider>();
EarSizeSlider = GameObject.Find("EarSizeSlider").GetComponent<Slider>();
EarPositionSlider = GameObject.Find("EarPosSlider").GetComponent<Slider>();
EarRotationSlider = GameObject.Find("EarRotSlider").GetComponent<Slider>();
NoseSizeSlider = GameObject.Find("NoseSizeSlider").GetComponent<Slider>();
NoseCurveSlider = GameObject.Find("NoseCurveSlider").GetComponent<Slider>();
NoseWidthSlider = GameObject.Find("NoseWidthSlider").GetComponent<Slider>();
NoseInclinationSlider = GameObject.Find("NoseInclineSlider").GetComponent<Slider>();
NosePositionSlider = GameObject.Find("NosePosSlider").GetComponent<Slider>();
NosePronuncedSlider = GameObject.Find("NosePronSlider").GetComponent<Slider>();
NoseFlattenSlider = GameObject.Find("NoseFlatSlider").GetComponent<Slider>();
ChinSizeSlider = GameObject.Find("ChinSizeSlider").GetComponent<Slider>();
ChinPronouncedSlider = GameObject.Find("ChinPronSlider").GetComponent<Slider>();
ChinPositionSlider = GameObject.Find("ChinPosSlider").GetComponent<Slider>();
MandibleSizeSlider = GameObject.Find("MandibleSizeSlider").GetComponent<Slider>();
JawSizeSlider = GameObject.Find("JawSizeSlider").GetComponent<Slider>();
JawPositionSlider = GameObject.Find("JawPosSlider").GetComponent<Slider>();
CheekSizeSlider = GameObject.Find("CheekSizeSlider").GetComponent<Slider>();
CheekPositionSlider = GameObject.Find("CheekPosSlider").GetComponent<Slider>();
lowCheekPronSlider = GameObject.Find("LowCheekPronSlider").GetComponent<Slider>();
ForeHeadSizeSlider = GameObject.Find("ForeheadSizeSlider").GetComponent<Slider>();
ForeHeadPositionSlider = GameObject.Find("ForeheadPosSlider").GetComponent<Slider>();
LipSizeSlider = GameObject.Find("LipSizeSlider").GetComponent<Slider>();
MouthSlider = GameObject.Find("MouthSizeSlider").GetComponent<Slider>();
EyeSizeSlider = GameObject.Find("EyeSizeSlider").GetComponent<Slider>();
EyeRotationSlider = GameObject.Find("EyeRotSlider").GetComponent<Slider>();
EyeSpacingSlider = GameObject.Find("EyeSpaceSlider").GetComponent<Slider>();
LowCheekPosSlider = GameObject.Find("LowCheekPosSlider").GetComponent<Slider>();
// Find the panels and hide for now
DnaPanel = GameObject.Find("DnaEditorPanel");
// DnaScrollPanel = GameObject.Find("ScrollPanel");
DnaPanel.SetActive(false);
#if UNITY_5 && !UNITY_5_1 && !UNITY_5_0
var oldUIMask = DnaPanel.GetComponent<Mask>();
if (oldUIMask != null)
{
DestroyImmediate(oldUIMask);
DnaPanel.AddComponent<RectMask2D>();
}
#endif
// Find the DNA hide button and hide it for now
DnaHide = GameObject.Find("MessagePanel").GetComponentInChildren<Button>();
DnaHide.gameObject.SetActive(false);
}
protected virtual void Start()
{
float vpWidth;
// sliders = DnaScrollPanel.GetComponentsInChildren<Slider>(); // Create an array of the sliders to use for initialization
vpWidth = ((float)Screen.width - 175) / (float)Screen.width; // Get the width of the screen so that we can adjust the viewport
ViewPortReduced = new Rect(0, 0, vpWidth, 1);
Camera.main.rect = ViewPortFull;
baseTarget = GameObject.Find("UMACrowd").transform; // Get the transform of the UMA Crown GO to use when retargeting the camera
}
void Update ()
{
if (umaTutorialDna != null)
EyeSpacingSlider.interactable = true;
else
EyeSpacingSlider.interactable = false;
// Don't raycast if the editor is open
if (umaData != null)
return;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if(Input.GetMouseButtonDown(0) || Input.GetMouseButtonDown(1))
{
if (Physics.Raycast(ray, out hit, 100))
{
Transform tempTransform = hit.collider.transform;
umaData = tempTransform.GetComponent<UMAData>();
if(umaData)
{
AvatarSetup();
}
}
}
}
// An avatar has been selected, setup the camera, sliders, retarget the camera, and adjust the viewport
// to account for the DNA slider scroll panel
public void AvatarSetup()
{
umaDynamicAvatar = umaData.gameObject.GetComponent<UMADynamicAvatar>();
if(cameraTrack){
cameraTrack.target = umaData.umaRoot.transform;
}
umaDna = umaData.GetDna<UMADnaHumanoid>();
umaTutorialDna = umaData.GetDna<UMADnaTutorial>();
SetSliders();
SetCamera(true);
}
// Set the camera target and viewport
private void SetCamera(bool show)
{
// Camera cam = cameraTrack.GetComponent<Camera>();
if(show)
{
Camera.main.rect = ViewPortReduced;
DnaPanel.SetActive(true);
DnaHide.gameObject.SetActive(true);
#if UNITY_5 && !UNITY_5_1 && !UNITY_5_0
// really Unity? Yes we change the value and set it back to trigger a ui recalculation...
// because setting the damn game object active doesn't do that!
var rt = DnaPanel.GetComponent<RectTransform>();
var pos = rt.offsetMin;
rt.offsetMin = new Vector2(pos.x + 1, pos.y);
rt.offsetMin = pos;
#endif
}
else
{
cameraTrack.target = baseTarget;
Camera.main.rect = ViewPortFull;
DnaPanel.SetActive(false);
DnaHide.gameObject.SetActive(false);
umaData = null;
umaDna = null;
umaTutorialDna = null;
}
}
// Button callback to hide slider scroll panel
public void HideDnaSlider()
{
SetCamera(false);
}
public void UpdateUMAAtlas()
{
if (umaData != null)
{
umaData.isTextureDirty = true;
umaData.Dirty();
}
}
public void UpdateUMAShape()
{
if (umaData != null)
{
umaData.isShapeDirty = true;
umaData.Dirty();
}
}
// Set all of the sliders to the values contained in the UMA Character
public void SetSliders()
{
HeightSlider.value = umaDna.height;
UpperMuscleSlider.value = umaDna.upperMuscle;
UpperWeightSlider.value = umaDna.upperWeight;
LowerMuscleSlider.value = umaDna.lowerMuscle;
LowerWeightSlider.value = umaDna.lowerWeight;
ArmLengthSlider.value = umaDna.armLength;
ForearmLengthSlider.value = umaDna.forearmLength;
LegSeparationSlider.value = umaDna.legSeparation;
HandSizeSlider.value = umaDna.handsSize;
FeetSizeSlider.value = umaDna.feetSize;
LegSizeSlider.value = umaDna.legsSize;
ArmWidthSlider.value = umaDna.armWidth;
ForearmWidthSlider.value = umaDna.forearmWidth;
BreastSlider.value = umaDna.breastSize;
BellySlider.value = umaDna.belly;
WaistSizeSlider.value = umaDna.waist;
GlueteusSizeSlider.value = umaDna.gluteusSize;
HeadSizeSlider.value = umaDna.headSize;
HeadWidthSlider.value = umaDna.headWidth;
NeckThickSlider.value = umaDna.neckThickness;
EarSizeSlider.value = umaDna.earsSize;
EarPositionSlider.value = umaDna.earsPosition;
EarRotationSlider.value = umaDna.earsRotation;
NoseSizeSlider.value = umaDna.noseSize;
NoseCurveSlider.value = umaDna.noseCurve;
NoseWidthSlider.value = umaDna.noseWidth;
NoseInclinationSlider.value = umaDna.noseInclination;
NosePositionSlider.value = umaDna.nosePosition;
NosePronuncedSlider.value = umaDna.nosePronounced;
NoseFlattenSlider.value = umaDna.noseFlatten;
ChinSizeSlider.value = umaDna.chinSize;
ChinPronouncedSlider.value = umaDna.chinPronounced;
ChinPositionSlider.value = umaDna.chinPosition;
MandibleSizeSlider.value = umaDna.mandibleSize;
JawSizeSlider.value = umaDna.jawsSize;
JawPositionSlider.value = umaDna.jawsPosition;
CheekSizeSlider.value = umaDna.cheekSize;
CheekPositionSlider.value = umaDna.cheekPosition;
lowCheekPronSlider.value = umaDna.lowCheekPronounced;
ForeHeadSizeSlider.value = umaDna.foreheadSize;
ForeHeadPositionSlider.value = umaDna.foreheadPosition;
LipSizeSlider.value = umaDna.lipsSize;
MouthSlider.value = umaDna.mouthSize;
EyeSizeSlider.value = umaDna.eyeSize;
EyeRotationSlider.value = umaDna.eyeRotation;
LowCheekPosSlider.value = umaDna.lowCheekPosition;
if (umaTutorialDna != null) EyeSpacingSlider.value = umaTutorialDna.eyeSpacing;
}
// Slider callbacks
public void OnHeightChange() { if (umaDna != null) umaDna.height = HeightSlider.value; UpdateUMAShape(); }
public void OnUpperMuscleChange() { if (umaDna != null) umaDna.upperMuscle = UpperMuscleSlider.value; UpdateUMAShape(); }
public void OnUpperWeightChange() { if (umaDna != null) umaDna.upperWeight = UpperWeightSlider.value; UpdateUMAShape(); }
public void OnLowerMuscleChange() { if (umaDna != null) umaDna.lowerMuscle = LowerMuscleSlider.value; UpdateUMAShape(); }
public void OnLowerWeightChange() { if (umaDna != null) umaDna.lowerWeight = LowerWeightSlider.value; UpdateUMAShape(); }
public void OnArmLengthChange() { if (umaDna != null) umaDna.armLength = ArmLengthSlider.value; UpdateUMAShape(); }
public void OnForearmLengthChange() { if (umaDna != null) umaDna.forearmLength = ForearmLengthSlider.value; UpdateUMAShape(); }
public void OnLegSeparationChange() { if (umaDna != null) umaDna.legSeparation = LegSeparationSlider.value; UpdateUMAShape(); }
public void OnHandSizeChange() { if (umaDna != null) umaDna.handsSize = HandSizeSlider.value; UpdateUMAShape(); }
public void OnFootSizeChange() { if (umaDna != null) umaDna.feetSize = FeetSizeSlider.value; UpdateUMAShape(); }
public void OnLegSizeChange() { if (umaDna != null) umaDna.legsSize = LegSizeSlider.value; UpdateUMAShape(); }
public void OnArmWidthChange() { if (umaDna != null) umaDna.armWidth = ArmWidthSlider.value; UpdateUMAShape(); }
public void OnForearmWidthChange() { if (umaDna != null) umaDna.forearmWidth = ForearmWidthSlider.value; UpdateUMAShape(); }
public void OnBreastSizeChange() { if (umaDna != null) umaDna.breastSize = BreastSlider.value; UpdateUMAShape(); }
public void OnBellySizeChange() { if (umaDna != null) umaDna.belly = BellySlider.value; UpdateUMAShape(); }
public void OnWaistSizeChange() { if (umaDna != null) umaDna.waist = WaistSizeSlider.value; UpdateUMAShape(); }
public void OnGluteusSizeChange() { if (umaDna != null) umaDna.gluteusSize = GlueteusSizeSlider.value; UpdateUMAShape(); }
public void OnHeadSizeChange() { if (umaDna != null) umaDna.headSize = HeadSizeSlider.value; UpdateUMAShape(); }
public void OnHeadWidthChange() { if (umaDna != null) umaDna.headWidth = HeadWidthSlider.value; UpdateUMAShape(); }
public void OnNeckThicknessChange() { if (umaDna != null) umaDna.neckThickness = NeckThickSlider.value; UpdateUMAShape(); }
public void OnEarSizeChange() { if (umaDna != null) umaDna.earsSize = EarSizeSlider.value; UpdateUMAShape(); }
public void OnEarPositionChange() { if (umaDna != null) umaDna.earsPosition = EarPositionSlider.value; UpdateUMAShape(); }
public void OnEarRotationChange() { if (umaDna != null) umaDna.earsRotation = EarRotationSlider.value; UpdateUMAShape(); }
public void OnNoseSizeChange() { if (umaDna != null) umaDna.noseSize = NoseSizeSlider.value; UpdateUMAShape(); }
public void OnNoseCurveChange() { if (umaDna != null) umaDna.noseCurve = NoseCurveSlider.value; UpdateUMAShape(); }
public void OnNoseWidthChange() { if (umaDna != null) umaDna.noseWidth = NoseWidthSlider.value; UpdateUMAShape(); }
public void OnNoseInclinationChange() { if (umaDna != null) umaDna.noseInclination = NoseInclinationSlider.value; UpdateUMAShape(); }
public void OnNosePositionChange() { if (umaDna != null) umaDna.nosePosition = NosePositionSlider.value; UpdateUMAShape(); }
public void OnNosePronouncedChange() { if (umaDna != null) umaDna.nosePronounced = NosePronuncedSlider.value; UpdateUMAShape(); }
public void OnNoseFlattenChange() { if (umaDna != null) umaDna.noseFlatten = NoseFlattenSlider.value; UpdateUMAShape(); }
public void OnChinSizeChange() { if (umaDna != null) umaDna.chinSize = ChinSizeSlider.value; UpdateUMAShape(); }
public void OnChinPronouncedChange() { if (umaDna != null) umaDna.chinPronounced = ChinPronouncedSlider.value; UpdateUMAShape(); }
public void OnChinPositionChange() { if (umaDna != null) umaDna.chinPosition = ChinPositionSlider.value; UpdateUMAShape(); }
public void OnMandibleSizeChange() { if (umaDna != null) umaDna.mandibleSize = MandibleSizeSlider.value; UpdateUMAShape(); }
public void OnJawSizeChange() { if (umaDna != null) umaDna.jawsSize = JawSizeSlider.value; UpdateUMAShape(); }
public void OnJawPositionChange() { if (umaDna != null) umaDna.jawsPosition = JawPositionSlider.value; UpdateUMAShape(); }
public void OnCheekSizeChange() { if (umaDna != null) umaDna.cheekSize = CheekSizeSlider.value; UpdateUMAShape(); }
public void OnCheekPositionChange() { if (umaDna != null) umaDna.cheekPosition = CheekPositionSlider.value; UpdateUMAShape(); }
public void OnCheekLowPronouncedChange() { if (umaDna != null) umaDna.lowCheekPronounced = lowCheekPronSlider.value; UpdateUMAShape(); }
public void OnForeheadSizeChange() { if (umaDna != null) umaDna.foreheadSize = ForeHeadSizeSlider.value; UpdateUMAShape(); }
public void OnForeheadPositionChange() { if (umaDna != null) umaDna.foreheadPosition = ForeHeadPositionSlider.value; UpdateUMAShape(); }
public void OnLipSizeChange() { if (umaDna != null) umaDna.lipsSize = LipSizeSlider.value; UpdateUMAShape(); }
public void OnMouthSizeChange() { if (umaDna != null) umaDna.mouthSize = MouthSlider.value; UpdateUMAShape(); }
public void OnEyeSizechange() { if (umaDna != null) umaDna.eyeSize = EyeSizeSlider.value; UpdateUMAShape(); }
public void OnEyeRotationChange() { if (umaDna != null) umaDna.eyeRotation = EyeRotationSlider.value; UpdateUMAShape(); }
public void OnLowCheekPositionChange() { if (umaDna != null) umaDna.lowCheekPosition = LowCheekPosSlider.value; UpdateUMAShape(); }
public void OnEyeSpacingChange() { if (umaTutorialDna != null) umaTutorialDna.eyeSpacing = EyeSpacingSlider.value; UpdateUMAShape(); }
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.KeyVault
{
using System;
using System.Linq;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// The Azure management API provides a RESTful set of web services that
/// interact with Azure Key Vault.
/// </summary>
public partial class KeyVaultManagementClient : ServiceClient<KeyVaultManagementClient>, IKeyVaultManagementClient, IAzureClient
{
/// <summary>
/// The base URI of the service.
/// </summary>
public Uri BaseUri { get; set; }
/// <summary>
/// Gets or sets json serialization settings.
/// </summary>
public JsonSerializerSettings SerializationSettings { get; private set; }
/// <summary>
/// Gets or sets json deserialization settings.
/// </summary>
public JsonSerializerSettings DeserializationSettings { get; private set; }
/// <summary>
/// Credentials needed for the client to connect to Azure.
/// </summary>
public ServiceClientCredentials Credentials { get; private set; }
/// <summary>
/// Gets subscription credentials which uniquely identify Microsoft Azure
/// subscription. The subscription ID forms part of the URI for every service
/// call.
/// </summary>
public string SubscriptionId { get; set; }
/// <summary>
/// Client Api Version.
/// </summary>
public string ApiVersion { get; private set; }
/// <summary>
/// Gets or sets the preferred language for the response.
/// </summary>
public string AcceptLanguage { get; set; }
/// <summary>
/// Gets or sets the retry timeout in seconds for Long Running Operations.
/// Default value is 30.
/// </summary>
public int? LongRunningOperationRetryTimeout { get; set; }
/// <summary>
/// When set to true a unique x-ms-client-request-id value is generated and
/// included in each request. Default is true.
/// </summary>
public bool? GenerateClientRequestId { get; set; }
/// <summary>
/// Gets the IVaultsOperations.
/// </summary>
public virtual IVaultsOperations Vaults { get; private set; }
/// <summary>
/// Initializes a new instance of the KeyVaultManagementClient class.
/// </summary>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected KeyVaultManagementClient(params DelegatingHandler[] handlers) : base(handlers)
{
this.Initialize();
}
/// <summary>
/// Initializes a new instance of the KeyVaultManagementClient class.
/// </summary>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected KeyVaultManagementClient(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers)
{
this.Initialize();
}
/// <summary>
/// Initializes a new instance of the KeyVaultManagementClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
protected KeyVaultManagementClient(Uri baseUri, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this.BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the KeyVaultManagementClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
protected KeyVaultManagementClient(Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this.BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the KeyVaultManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public KeyVaultManagementClient(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the KeyVaultManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public KeyVaultManagementClient(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the KeyVaultManagementClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public KeyVaultManagementClient(Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this.BaseUri = baseUri;
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the KeyVaultManagementClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public KeyVaultManagementClient(Uri baseUri, ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this.BaseUri = baseUri;
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// An optional partial-method to perform custom initialization.
/// </summary>
partial void CustomInitialize();
/// <summary>
/// Initializes client properties.
/// </summary>
private void Initialize()
{
this.Vaults = new VaultsOperations(this);
this.BaseUri = new Uri("https://management.azure.com");
this.ApiVersion = "2016-10-01";
this.AcceptLanguage = "en-US";
this.LongRunningOperationRetryTimeout = 30;
this.GenerateClientRequestId = true;
SerializationSettings = new JsonSerializerSettings
{
Formatting = Formatting.Indented,
DateFormatHandling = DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = DateTimeZoneHandling.Utc,
NullValueHandling = NullValueHandling.Ignore,
ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
DeserializationSettings = new JsonSerializerSettings
{
DateFormatHandling = DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = DateTimeZoneHandling.Utc,
NullValueHandling = NullValueHandling.Ignore,
ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
CustomInitialize();
DeserializationSettings.Converters.Add(new CloudErrorJsonConverter());
}
}
}
| |
#if !DONOTREFPRINTINGASMMETA
//---------------------------------------------------------------------------
//
// <copyright file=SerializerDescriptor.cs company=Microsoft>
// Copyright (C) Microsoft Corporation. All rights reserved.
// </copyright>
//
//
// Description: Plug-in document serializers implement this class
//
// See spec at <Need to post existing spec>
//
// History:
// 07/16/2005 : oliverfo - Created
//
//---------------------------------------------------------------------------
namespace System.Windows.Documents.Serialization
{
using System;
using System.Globalization;
using System.Collections.Generic;
using System.Reflection;
using System.Windows;
using System.Security;
using System.Security.Permissions;
using System.Diagnostics.CodeAnalysis;
using Microsoft.Win32;
using MS.Internal.PresentationFramework;
/// <summary>
/// SerializerDescriptor describes an individual plug-in serializer
/// </summary>
public sealed class SerializerDescriptor
{
#region Constructors
private SerializerDescriptor()
{
}
#endregion
#region Private Methods
private static string GetNonEmptyRegistryString(RegistryKey key, string value)
{
string result = key.GetValue(value) as string;
if ( result == null )
{
throw new KeyNotFoundException();
}
return result;
}
#endregion
#region Public Methods
/// <summary>
/// Creates a SerializerDescriptor. The interface must be defined in the calling assembly
/// The WinFX version, and assembly name, and version are initialized by reflecting on the calling assembly
/// </summary>
/// <remarks>
/// Create a SerializerDescriptor from a ISerializerFactory instance
///
/// This method currently requires full trust to run.
/// </remarks>
///<SecurityNote>
/// Critical : Creates untrusted object via reflection
/// Safe : Demands DemandPlugInSerializerPermissions
/// The DemandPlugInSerializerPermissions() ensures that this method only works in full trust.
/// Full trust is required, so that partial trust applications do not load or use potentially
/// unsafe serializer plug ins
///</SecurityNote>
[SecuritySafeCritical]
public static SerializerDescriptor CreateFromFactoryInstance(
ISerializerFactory factoryInstance
)
{
SecurityHelper.DemandPlugInSerializerPermissions();
if (factoryInstance == null)
{
throw new ArgumentNullException("factoryInstance");
}
if (factoryInstance.DisplayName == null)
{
throw new ArgumentException(SR.Get(SRID.SerializerProviderDisplayNameNull));
}
if (factoryInstance.ManufacturerName == null)
{
throw new ArgumentException(SR.Get(SRID.SerializerProviderManufacturerNameNull));
}
if (factoryInstance.ManufacturerWebsite == null)
{
throw new ArgumentException(SR.Get(SRID.SerializerProviderManufacturerWebsiteNull));
}
if (factoryInstance.DefaultFileExtension == null)
{
throw new ArgumentException(SR.Get(SRID.SerializerProviderDefaultFileExtensionNull));
}
SerializerDescriptor sd = new SerializerDescriptor();
sd._displayName = factoryInstance.DisplayName;
sd._manufacturerName = factoryInstance.ManufacturerName;
sd._manufacturerWebsite = factoryInstance.ManufacturerWebsite;
sd._defaultFileExtension = factoryInstance.DefaultFileExtension;
// When this is called with an instantiated factory object, it must be loadable
sd._isLoadable = true;
Type factoryType = factoryInstance.GetType();
sd._assemblyName = factoryType.Assembly.FullName;
sd._assemblyPath = factoryType.Assembly.Location;
sd._assemblyVersion = factoryType.Assembly.GetName().Version;
sd._factoryInterfaceName = factoryType.FullName;
sd._winFXVersion = typeof(System.Windows.Controls.Button).Assembly.GetName().Version;
return sd;
}
/// <summary>
/// From a SerializerDescriptor (which required full trust to create)
/// creates an ISerializerFactory by loading the assembly and reflecting on the type
/// </summary>
/// <remarks>
/// Create an ISerializerFactory from a SerializerDescriptor
///
/// This method currently requires full trust to run.
/// </remarks>
///<SecurityNote>
/// Safe : The DemandPlugInSerializerPermissions() ensures that this method only works in full trust.
/// Critical : Full trust is required, so that partial trust applications do not load or use potentially
/// unsafe serializer plug ins
///</SecurityNote>
[SecuritySafeCritical]
[SuppressMessage("Microsoft.Security", "CA2001:AvoidCallingProblematicMethods")]
internal ISerializerFactory CreateSerializerFactory()
{
SecurityHelper.DemandPlugInSerializerPermissions();
string assemblyPath = AssemblyPath;
// This is the only way to load the plug-in assembly. The only permitted permission
// if file read access to the actual plug-in assembly.
Assembly plugIn = Assembly.LoadFrom(assemblyPath);
ISerializerFactory factory = plugIn.CreateInstance(FactoryInterfaceName) as ISerializerFactory;
return factory;
}
#endregion
#region Internal Methods
internal void WriteToRegistryKey(RegistryKey key)
{
key.SetValue("uiLanguage", CultureInfo.CurrentUICulture.Name);
key.SetValue("displayName", this.DisplayName);
key.SetValue("manufacturerName", this.ManufacturerName);
key.SetValue("manufacturerWebsite", this.ManufacturerWebsite);
key.SetValue("defaultFileExtension", this.DefaultFileExtension);
key.SetValue("assemblyName", this.AssemblyName);
key.SetValue("assemblyPath", this.AssemblyPath);
key.SetValue("factoryInterfaceName", this.FactoryInterfaceName);
key.SetValue("assemblyVersion", this.AssemblyVersion.ToString());
key.SetValue("winFXVersion", this.WinFXVersion.ToString());
}
/// <summary>
/// Load a SerializerDescriptor from the registry
/// </summary>
/// <remarks>
/// Create a SerializerDescriptor from the registry
///
/// This method currently requires full trust to run.
/// </remarks>
///<SecurityNote>
/// Critical : Creates untrusted object via reflection
/// Safe : Demands DemandPlugInSerializerPermissions
/// The DemandPlugInSerializerPermissions() ensures that this method only works in full trust.
/// Full trust is required, so that partial trust applications do not load or use potentially
/// unsafe serializer plug ins
///</SecurityNote>
[SecuritySafeCritical]
internal static SerializerDescriptor CreateFromRegistry(RegistryKey plugIns, string keyName)
{
SecurityHelper.DemandPlugInSerializerPermissions();
SerializerDescriptor sd = new SerializerDescriptor();
try
{
RegistryKey key = plugIns.OpenSubKey(keyName);
sd._displayName = GetNonEmptyRegistryString(key, "displayName");
sd._manufacturerName = GetNonEmptyRegistryString(key, "manufacturerName");
sd._manufacturerWebsite = new Uri(GetNonEmptyRegistryString(key, "manufacturerWebsite"));
sd._defaultFileExtension = GetNonEmptyRegistryString(key, "defaultFileExtension");
sd._assemblyName = GetNonEmptyRegistryString(key, "assemblyName");
sd._assemblyPath = GetNonEmptyRegistryString(key, "assemblyPath");
sd._factoryInterfaceName = GetNonEmptyRegistryString(key, "factoryInterfaceName");
sd._assemblyVersion = new Version(GetNonEmptyRegistryString(key, "assemblyVersion"));
sd._winFXVersion = new Version(GetNonEmptyRegistryString(key, "winFXVersion"));
string uiLanguage = GetNonEmptyRegistryString(key, "uiLanguage");
key.Close();
// update language strings.
if (!uiLanguage.Equals(CultureInfo.CurrentUICulture.Name))
{
ISerializerFactory factory = sd.CreateSerializerFactory();
sd._displayName = factory.DisplayName;
sd._manufacturerName = factory.ManufacturerName;
sd._manufacturerWebsite = factory.ManufacturerWebsite;
sd._defaultFileExtension = factory.DefaultFileExtension;
key = plugIns.CreateSubKey(keyName);
sd.WriteToRegistryKey(key);
key.Close();
}
}
catch (KeyNotFoundException)
{
sd = null;
}
if (sd != null)
{
Assembly plugIn = Assembly.ReflectionOnlyLoadFrom(sd._assemblyPath);
if (typeof(System.Windows.Controls.Button).Assembly.GetName().Version == sd._winFXVersion &&
plugIn != null &&
plugIn.GetName().Version == sd._assemblyVersion)
{
sd._isLoadable = true;
}
}
return sd;
}
#endregion
#region Public Properties
/// <summary>
/// DisplayName of the Serializer
/// </summary>
public string DisplayName
{
get
{
return _displayName;
}
}
/// <summary>
/// ManufacturerName of the Serializer
/// </summary>
public string ManufacturerName
{
get
{
return _manufacturerName;
}
}
/// <summary>
/// ManufacturerWebsite of the Serializer
/// </summary>
public Uri ManufacturerWebsite
{
get
{
return _manufacturerWebsite;
}
}
/// <summary>
/// Default File Extension of files produced the Serializer
/// </summary>
public string DefaultFileExtension
{
get
{
return _defaultFileExtension;
}
}
/// <summary>
/// AssemblyName of the Serializer
/// </summary>
public string AssemblyName
{
get
{
return _assemblyName;
}
}
/// <summary>
/// AssemblyPath of the Serializer
/// </summary>
public string AssemblyPath
{
get
{
return _assemblyPath;
}
}
/// <summary>
/// FactoryInterfaceName of the Serializer
/// </summary>
public string FactoryInterfaceName
{
get
{
return _factoryInterfaceName;
}
}
/// <summary>
/// AssemblyVersion of the Serializer
/// </summary>
public Version AssemblyVersion
{
get
{
return _assemblyVersion;
}
}
/// <summary>
/// DisplayName of the Serializer
/// </summary>
public Version WinFXVersion
{
get
{
return _winFXVersion;
}
}
/// <summary>
/// returns false if serializer plug-in cannot be loaded on current WinFX version
/// </summary>
public bool IsLoadable
{
get
{
return _isLoadable;
}
}
/// <summary>
/// Compares two SerializerDescriptor for equality
/// </summary>
public override bool Equals(object obj)
{
SerializerDescriptor sd = obj as SerializerDescriptor;
if (sd != null)
{
return sd._displayName == _displayName
&& sd._assemblyName == _assemblyName
&& sd._assemblyPath == _assemblyPath
&& sd._factoryInterfaceName == _factoryInterfaceName
&& sd._defaultFileExtension == _defaultFileExtension
&& sd._assemblyVersion == _assemblyVersion
&& sd._winFXVersion == _winFXVersion;
}
return false;
}
/// <summary>
/// Returns a hashcode for this serializer
/// </summary>
public override int GetHashCode()
{
string id = _displayName + "/" + _assemblyName + "/" + _assemblyPath + "/" + _factoryInterfaceName + "/" + _assemblyVersion + "/" + _winFXVersion;
return id.GetHashCode();
}
#endregion
#region Data
private string _displayName;
private string _manufacturerName;
private Uri _manufacturerWebsite;
private string _defaultFileExtension;
private string _assemblyName;
private string _assemblyPath;
private string _factoryInterfaceName;
private Version _assemblyVersion;
private Version _winFXVersion;
private bool _isLoadable;
#endregion
}
}
#endif
| |
using System;
namespace System.Globalization
{
internal static class SR
{
public static string Arg_HexStyleNotSupported
{
get { return Environment.GetResourceString("Arg_HexStyleNotSupported"); }
}
public static string Arg_InvalidHexStyle
{
get { return Environment.GetResourceString("Arg_InvalidHexStyle"); }
}
public static string ArgumentNull_Array
{
get { return Environment.GetResourceString("ArgumentNull_Array"); }
}
public static string ArgumentNull_ArrayValue
{
get { return Environment.GetResourceString("ArgumentNull_ArrayValue"); }
}
public static string ArgumentNull_Obj
{
get { return Environment.GetResourceString("ArgumentNull_Obj"); }
}
public static string ArgumentNull_String
{
get { return Environment.GetResourceString("ArgumentNull_String"); }
}
public static string ArgumentOutOfRange_AddValue
{
get { return Environment.GetResourceString("ArgumentOutOfRange_AddValue"); }
}
public static string ArgumentOutOfRange_BadHourMinuteSecond
{
get { return Environment.GetResourceString("ArgumentOutOfRange_BadHourMinuteSecond"); }
}
public static string ArgumentOutOfRange_BadYearMonthDay
{
get { return Environment.GetResourceString("ArgumentOutOfRange_BadYearMonthDay"); }
}
public static string ArgumentOutOfRange_Bounds_Lower_Upper
{
get { return Environment.GetResourceString("ArgumentOutOfRange_Bounds_Lower_Upper"); }
}
public static string ArgumentOutOfRange_CalendarRange
{
get { return Environment.GetResourceString("ArgumentOutOfRange_CalendarRange"); }
}
public static string ArgumentOutOfRange_Count
{
get { return Environment.GetResourceString("ArgumentOutOfRange_Count"); }
}
public static string ArgumentOutOfRange_Day
{
get { return Environment.GetResourceString("ArgumentOutOfRange_Day"); }
}
public static string ArgumentOutOfRange_Enum
{
get { return Environment.GetResourceString("ArgumentOutOfRange_Enum"); }
}
public static string ArgumentOutOfRange_Era
{
get { return Environment.GetResourceString("ArgumentOutOfRange_Era"); }
}
public static string ArgumentOutOfRange_Index
{
get { return Environment.GetResourceString("ArgumentOutOfRange_Index"); }
}
public static string ArgumentOutOfRange_InvalidEraValue
{
get { return Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue"); }
}
public static string ArgumentOutOfRange_Month
{
get { return Environment.GetResourceString("ArgumentOutOfRange_Month"); }
}
public static string ArgumentOutOfRange_NeedNonNegNum
{
get { return Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"); }
}
public static string ArgumentOutOfRange_NeedPosNum
{
get { return Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"); }
}
public static string ArgumentOutOfRange_OffsetLength
{
get { return Environment.GetResourceString("ArgumentOutOfRange_OffsetLength"); }
}
public static string ArgumentOutOfRange_Range
{
get { return Environment.GetResourceString("ArgumentOutOfRange_Range"); }
}
public static string Argument_CompareOptionOrdinal
{
get { return Environment.GetResourceString("Argument_CompareOptionOrdinal"); }
}
public static string Argument_ConflictingDateTimeRoundtripStyles
{
get { return Environment.GetResourceString("Argument_ConflictingDateTimeRoundtripStyles"); }
}
public static string Argument_ConflictingDateTimeStyles
{
get { return Environment.GetResourceString("Argument_ConflictingDateTimeStyles"); }
}
public static string Argument_CultureInvalidIdentifier
{
get { return Environment.GetResourceString("Argument_CultureInvalidIdentifier"); }
}
public static string Argument_CultureNotSupported
{
get { return Environment.GetResourceString("Argument_CultureNotSupported"); }
}
public static string Argument_EmptyDecString
{
get { return Environment.GetResourceString("Argument_EmptyDecString"); }
}
public static string Argument_InvalidArrayLength
{
get { return Environment.GetResourceString("Argument_InvalidArrayLength"); }
}
public static string Argument_InvalidCalendar
{
get { return Environment.GetResourceString("Argument_InvalidCalendar"); }
}
public static string Argument_InvalidCultureName
{
get { return Environment.GetResourceString("Argument_InvalidCultureName"); }
}
public static string Argument_InvalidDateTimeStyles
{
get { return Environment.GetResourceString("Argument_InvalidDateTimeStyles"); }
}
public static string Argument_InvalidFlag
{
get { return Environment.GetResourceString("Argument_InvalidFlag"); }
}
public static string Argument_InvalidGroupSize
{
get { return Environment.GetResourceString("Argument_InvalidGroupSize"); }
}
public static string Argument_InvalidNeutralRegionName
{
get { return Environment.GetResourceString("Argument_InvalidNeutralRegionName"); }
}
public static string Argument_InvalidNumberStyles
{
get { return Environment.GetResourceString("Argument_InvalidNumberStyles"); }
}
public static string Argument_InvalidResourceCultureName
{
get { return Environment.GetResourceString("Argument_InvalidResourceCultureName"); }
}
public static string Argument_NoEra
{
get { return Environment.GetResourceString("Argument_NoEra"); }
}
public static string Argument_NoRegionInvariantCulture
{
get { return Environment.GetResourceString("Argument_NoRegionInvariantCulture"); }
}
public static string Argument_ResultCalendarRange
{
get { return Environment.GetResourceString("Argument_ResultCalendarRange"); }
}
public static string Format_BadFormatSpecifier
{
get { return Environment.GetResourceString("Format_BadFormatSpecifier"); }
}
public static string InvalidOperation_DateTimeParsing
{
get { return Environment.GetResourceString("InvalidOperation_DateTimeParsing"); }
}
public static string InvalidOperation_EnumEnded
{
get { return Environment.GetResourceString("InvalidOperation_EnumEnded"); }
}
public static string InvalidOperation_EnumNotStarted
{
get { return Environment.GetResourceString("InvalidOperation_EnumNotStarted"); }
}
public static string InvalidOperation_ReadOnly
{
get { return Environment.GetResourceString("InvalidOperation_ReadOnly"); }
}
public static string Overflow_TimeSpanTooLong
{
get { return Environment.GetResourceString("Overflow_TimeSpanTooLong"); }
}
public static string Serialization_MemberOutOfRange
{
get { return Environment.GetResourceString("Serialization_MemberOutOfRange"); }
}
public static string Format(string formatString, params object[] args)
{
return string.Format(CultureInfo.CurrentCulture, formatString, args);
}
}
}
| |
//
// PerformanceCounterPermissionTest.cs -
// NUnit Test Cases for PerformanceCounterPermission
//
// Author:
// Sebastien Pouliot <sebastien@ximian.com>
//
// Copyright (C) 2004-2005 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using NUnit.Framework;
using System;
using System.Diagnostics;
using System.Security;
using System.Security.Permissions;
namespace MonoTests.System.Diagnostics {
[TestFixture]
public class PerformanceCounterPermissionTest {
static PerformanceCounterPermissionAccess[] AllAccess = {
PerformanceCounterPermissionAccess.None,
PerformanceCounterPermissionAccess.Browse,
#if NET_2_0
PerformanceCounterPermissionAccess.Read,
PerformanceCounterPermissionAccess.Write,
#endif
PerformanceCounterPermissionAccess.Instrument,
PerformanceCounterPermissionAccess.Administer,
};
[Test]
public void PermissionState_None ()
{
PermissionState ps = PermissionState.None;
PerformanceCounterPermission pcp = new PerformanceCounterPermission (ps);
Assert.AreEqual (0, pcp.PermissionEntries.Count, "PermissionEntries");
Assert.IsFalse (pcp.IsUnrestricted (), "IsUnrestricted");
SecurityElement se = pcp.ToXml ();
// only class and version are present
Assert.AreEqual (2, se.Attributes.Count, "Xml-Attributes");
Assert.IsNull (se.Children, "Xml-Children");
PerformanceCounterPermission copy = (PerformanceCounterPermission)pcp.Copy ();
Assert.IsFalse (Object.ReferenceEquals (pcp, copy), "ReferenceEquals");
Assert.AreEqual (pcp.PermissionEntries.Count, copy.PermissionEntries.Count, "copy-PermissionEntries");
Assert.AreEqual (pcp.IsUnrestricted (), copy.IsUnrestricted (), "IsUnrestricted ()");
}
[Test]
public void PermissionState_Unrestricted ()
{
PermissionState ps = PermissionState.Unrestricted;
PerformanceCounterPermission pcp = new PerformanceCounterPermission (ps);
Assert.AreEqual (0, pcp.PermissionEntries.Count, "PermissionEntries");
Assert.IsTrue (pcp.IsUnrestricted (), "IsUnrestricted");
SecurityElement se = pcp.ToXml ();
// only class and version are present
Assert.AreEqual ("true", se.Attribute ("Unrestricted"), "Xml-Unrestricted");
Assert.IsNull (se.Children, "Xml-Children");
PerformanceCounterPermission copy = (PerformanceCounterPermission)pcp.Copy ();
Assert.IsFalse (Object.ReferenceEquals (pcp, copy), "ReferenceEquals");
Assert.AreEqual (pcp.PermissionEntries.Count, copy.PermissionEntries.Count, "copy-PermissionEntries");
Assert.AreEqual (pcp.IsUnrestricted (), copy.IsUnrestricted (), "copy-IsUnrestricted ()");
}
[Test]
#if NET_2_0
[ExpectedException (typeof (ArgumentException))]
#endif
public void PermissionState_Bad ()
{
PermissionState ps = (PermissionState)77;
PerformanceCounterPermission pcp = new PerformanceCounterPermission (ps);
Assert.IsFalse (pcp.IsUnrestricted (), "IsUnrestricted");
}
[Test]
[ExpectedException (typeof (ArgumentNullException))]
public void Constructor_PermissionEntries_Null ()
{
PerformanceCounterPermission pcp = new PerformanceCounterPermission (null);
}
[Test]
#if NET_2_0
[ExpectedException (typeof (ArgumentNullException))]
#else
[ExpectedException (typeof (ArgumentException))]
#endif
public void Constructor_MachineName_Null ()
{
PerformanceCounterPermission pcp = new PerformanceCounterPermission (PerformanceCounterPermissionAccess.None, null, String.Empty);
}
[Test]
[ExpectedException (typeof (ArgumentNullException))]
public void Constructor_CategoryName_Null ()
{
PerformanceCounterPermission pcp = new PerformanceCounterPermission (PerformanceCounterPermissionAccess.None, "localhost", null);
}
[Test]
#if NET_2_0
[ExpectedException (typeof (ArgumentException))]
#endif
public void PerformanceCounterPermissionAccesss_Bad ()
{
PerformanceCounterPermissionAccess pcpa = (PerformanceCounterPermissionAccess)Int32.MinValue;
PerformanceCounterPermission pcp = new PerformanceCounterPermission (pcpa, "localhost", String.Empty);
Assert.AreEqual (1, pcp.PermissionEntries.Count, "Count");
Assert.AreEqual ((PerformanceCounterPermissionAccess)Int32.MinValue, pcp.PermissionEntries [0].PermissionAccess, "PermissionAccess");
}
[Test]
public void PermissionEntries ()
{
PerformanceCounterPermissionAccess pcpa = PerformanceCounterPermissionAccess.None;
PerformanceCounterPermission pcp = new PerformanceCounterPermission (pcpa, "localhost", String.Empty);
PerformanceCounterPermissionEntryCollection pcpec = pcp.PermissionEntries;
Assert.AreEqual (1, pcpec.Count, "Count==1");
PerformanceCounterPermissionEntry pcpe = new PerformanceCounterPermissionEntry (PerformanceCounterPermissionAccess.Browse, "*", String.Empty);
pcp.PermissionEntries.Add (pcpe);
Assert.AreEqual (2, pcpec.Count, "Count==2");
// remove (same instance)
pcp.PermissionEntries.Remove (pcpe);
Assert.AreEqual (1, pcpec.Count, "Count==1 (b)");
// remove different instance (doesn't work)
pcpe = new PerformanceCounterPermissionEntry (PerformanceCounterPermissionAccess.None, "localhost", String.Empty);
Assert.AreEqual (1, pcpec.Count, "Count==1");
}
[Test]
public void Copy ()
{
foreach (PerformanceCounterPermissionAccess pcpa in AllAccess) {
PerformanceCounterPermission pcp = new PerformanceCounterPermission (PermissionState.None);
PerformanceCounterPermissionEntry pcpe = new PerformanceCounterPermissionEntry (pcpa, pcpa.ToString (), String.Empty);
pcp.PermissionEntries.Add (pcpe);
PerformanceCounterPermission copy = (PerformanceCounterPermission)pcp.Copy ();
Assert.AreEqual (1, copy.PermissionEntries.Count, "Count==1");
Assert.AreEqual (pcpa, pcp.PermissionEntries [0].PermissionAccess, pcpa.ToString ());
}
}
[Test]
public void Intersect_Null ()
{
PerformanceCounterPermission pcp = new PerformanceCounterPermission (PermissionState.None);
// No intersection with null
Assert.IsNull (pcp.Intersect (null), "None N null");
}
[Test]
public void Intersect_None ()
{
PerformanceCounterPermission pcp1 = new PerformanceCounterPermission (PermissionState.None);
PerformanceCounterPermission pcp2 = new PerformanceCounterPermission (PermissionState.None);
// 1. None N None
PerformanceCounterPermission result = (PerformanceCounterPermission)pcp1.Intersect (pcp2);
Assert.IsNull (result, "Empty N Empty");
// 2. None N Entry
pcp2.PermissionEntries.Add (new PerformanceCounterPermissionEntry (PerformanceCounterPermissionAccess.None, "localhost", String.Empty));
result = (PerformanceCounterPermission)pcp1.Intersect (pcp2);
Assert.IsNull (result, "Empty N Entry");
// 3. Entry N None
result = (PerformanceCounterPermission)pcp2.Intersect (pcp1);
Assert.IsNull (result, "Entry N Empty");
}
[Test]
public void Intersect_Unrestricted ()
{
// Intersection with unrestricted == Copy
// a. source (this) is unrestricted
PerformanceCounterPermission pcp1 = new PerformanceCounterPermission (PermissionState.Unrestricted);
PerformanceCounterPermission pcp2 = new PerformanceCounterPermission (PermissionState.None);
// 1. Unrestricted N None
PerformanceCounterPermission result = (PerformanceCounterPermission)pcp1.Intersect (pcp2);
Assert.IsFalse (result.IsUnrestricted (), "(Unrestricted N None).IsUnrestricted");
Assert.AreEqual (0, result.PermissionEntries.Count, "(Unrestricted N None).Count");
// 2. None N Unrestricted
result = (PerformanceCounterPermission)pcp2.Intersect (pcp1);
Assert.IsFalse (result.IsUnrestricted (), "(None N Unrestricted).IsUnrestricted");
Assert.AreEqual (0, result.PermissionEntries.Count, "(None N Unrestricted).Count");
// 3. Unrestricted N Unrestricted
result = (PerformanceCounterPermission)pcp1.Intersect (pcp1);
Assert.IsTrue (result.IsUnrestricted (), "(Unrestricted N Unrestricted).IsUnrestricted");
Assert.AreEqual (0, result.PermissionEntries.Count, "(Unrestricted N Unrestricted).Count");
// 4. Unrestricted N Entry
pcp2.PermissionEntries.Add (new PerformanceCounterPermissionEntry (PerformanceCounterPermissionAccess.None, "localhost", String.Empty));
result = (PerformanceCounterPermission)pcp1.Intersect (pcp2);
Assert.IsFalse (result.IsUnrestricted (), "(Unrestricted N Entry).IsUnrestricted");
Assert.AreEqual (1, result.PermissionEntries.Count, "(Unrestricted N Entry).Count");
// 5. Entry N Unrestricted
result = (PerformanceCounterPermission)pcp2.Intersect (pcp1);
Assert.IsFalse (result.IsUnrestricted (), "(Entry N Unrestricted).IsUnrestricted");
Assert.AreEqual (1, result.PermissionEntries.Count, "(Entry N Unrestricted).Count");
// 6. Unrestricted N Unrestricted
pcp1.PermissionEntries.Add (new PerformanceCounterPermissionEntry (PerformanceCounterPermissionAccess.None, "localhost", String.Empty));
result = (PerformanceCounterPermission)pcp1.Intersect (pcp1);
Assert.IsTrue (result.IsUnrestricted (), "(Unrestricted N Unrestricted).IsUnrestricted");
Assert.AreEqual (1, result.PermissionEntries.Count, "(Unrestricted N Unrestricted).Count");
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void Intersect_BadPermission ()
{
PerformanceCounterPermission pcp1 = new PerformanceCounterPermission (PermissionState.Unrestricted);
pcp1.Intersect (new SecurityPermission (SecurityPermissionFlag.Assertion));
}
[Test]
public void IsSubset_Null ()
{
PerformanceCounterPermission pcp = new PerformanceCounterPermission (PermissionState.None);
#if NET_2_0
Assert.IsTrue (pcp.IsSubsetOf (null), "null");
#else
Assert.IsFalse (pcp.IsSubsetOf (null), "null");
#endif
}
[Test]
public void IsSubset_None ()
{
// IsSubset with none
// a. source (this) is none -> target is never a subset
// b. destination (target) is none -> target is always a subset
PerformanceCounterPermission pcp1 = new PerformanceCounterPermission (PermissionState.None);
foreach (PerformanceCounterPermissionAccess pcpa in AllAccess) {
PerformanceCounterPermission pcp2 = new PerformanceCounterPermission (PermissionState.None);
pcp2.PermissionEntries.Add (new PerformanceCounterPermissionEntry (pcpa, pcpa.ToString (), String.Empty));
Assert.IsTrue (pcp1.IsSubsetOf (pcp2), "target " + pcpa.ToString ());
Assert.IsFalse (pcp2.IsSubsetOf (pcp1), "source " + pcpa.ToString ());
}
}
[Test]
public void IsSubset_Self ()
{
foreach (PerformanceCounterPermissionAccess pcpa in AllAccess) {
PerformanceCounterPermission pcp = new PerformanceCounterPermission (PermissionState.None);
pcp.PermissionEntries.Add (new PerformanceCounterPermissionEntry (pcpa, pcpa.ToString (), String.Empty));
Assert.IsTrue (pcp.IsSubsetOf (pcp), pcpa.ToString ());
}
}
[Test]
public void IsSubset_Unrestricted ()
{
// IsSubset with unrestricted
// a. source (this) is unrestricted -> target is never a subset
// b. destination (target) is unrestricted -> source is always a subset
PerformanceCounterPermission pcp1 = new PerformanceCounterPermission (PermissionState.Unrestricted);
foreach (PerformanceCounterPermissionAccess pcpa in AllAccess) {
PerformanceCounterPermission pcp2 = new PerformanceCounterPermission (PermissionState.None);
pcp2.PermissionEntries.Add (new PerformanceCounterPermissionEntry (pcpa, pcpa.ToString (), String.Empty));
Assert.IsFalse (pcp1.IsSubsetOf (pcp2), "target " + pcpa.ToString ());
Assert.IsTrue (pcp2.IsSubsetOf (pcp1), "source " + pcpa.ToString ());
}
Assert.IsTrue (pcp1.IsSubsetOf (pcp1), "Unrestricted.IsSubsetOf(Unrestricted)");
}
[Test]
// "special" behavior inherited from ResourceBasePermission
// [ExpectedException (typeof (ArgumentException))]
public void IsSubsetOf_BadPermission ()
{
PerformanceCounterPermission pcp1 = new PerformanceCounterPermission (PermissionState.Unrestricted);
Assert.IsFalse (pcp1.IsSubsetOf (new SecurityPermission (SecurityPermissionFlag.Assertion)));
}
[Test]
public void Union_Null ()
{
PerformanceCounterPermission pcp = new PerformanceCounterPermission (PermissionState.None);
pcp.PermissionEntries.Add (new PerformanceCounterPermissionEntry (PerformanceCounterPermissionAccess.None, "localhost", String.Empty));
// Union with null is a simple copy
PerformanceCounterPermission union = (PerformanceCounterPermission)pcp.Union (null);
Assert.IsNotNull (pcp.PermissionEntries.Count, "Count");
}
[Test]
public void Union_None ()
{
PerformanceCounterPermission pcp1 = new PerformanceCounterPermission (PermissionState.None);
foreach (PerformanceCounterPermissionAccess pcpa in AllAccess) {
PerformanceCounterPermission pcp2 = new PerformanceCounterPermission (PermissionState.None);
pcp2.PermissionEntries.Add (new PerformanceCounterPermissionEntry (pcpa, pcpa.ToString (), String.Empty));
PerformanceCounterPermission union = (PerformanceCounterPermission)pcp1.Union (pcp2);
Assert.IsFalse (union.IsUnrestricted (), "target.IsUnrestricted " + pcpa.ToString ());
Assert.AreEqual (1, union.PermissionEntries.Count, "target.Count " + pcpa.ToString ());
union = (PerformanceCounterPermission)pcp2.Union (pcp1);
Assert.IsFalse (union.IsUnrestricted (), "source.IsUnrestricted " + pcpa.ToString ());
Assert.AreEqual (1, union.PermissionEntries.Count, "source.Count " + pcpa.ToString ());
}
}
[Test]
public void Union_Self ()
{
foreach (PerformanceCounterPermissionAccess pcpa in AllAccess) {
PerformanceCounterPermission pcp = new PerformanceCounterPermission (PermissionState.None);
pcp.PermissionEntries.Add (new PerformanceCounterPermissionEntry (pcpa, pcpa.ToString (), String.Empty));
PerformanceCounterPermission union = (PerformanceCounterPermission)pcp.Union (pcp);
Assert.IsFalse (union.IsUnrestricted (), "IsUnrestricted " + pcpa.ToString ());
Assert.AreEqual (1, union.PermissionEntries.Count, "Count " + pcpa.ToString ());
}
}
[Test]
public void Union_Unrestricted ()
{
// Union with unrestricted is unrestricted
PerformanceCounterPermission pcp1 = new PerformanceCounterPermission (PermissionState.Unrestricted);
foreach (PerformanceCounterPermissionAccess pcpa in AllAccess) {
PerformanceCounterPermission pcp2 = new PerformanceCounterPermission (PermissionState.None);
pcp2.PermissionEntries.Add (new PerformanceCounterPermissionEntry (pcpa, pcpa.ToString (), String.Empty));
PerformanceCounterPermission union = (PerformanceCounterPermission)pcp1.Union (pcp2);
Assert.IsTrue (union.IsUnrestricted (), "target.IsUnrestricted " + pcpa.ToString ());
Assert.AreEqual (0, union.PermissionEntries.Count, "target.Count " + pcpa.ToString ());
union = (PerformanceCounterPermission)pcp2.Union (pcp1);
Assert.IsTrue (union.IsUnrestricted (), "source.IsUnrestricted " + pcpa.ToString ());
Assert.AreEqual (0, union.PermissionEntries.Count, "source.Count " + pcpa.ToString ());
}
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void Union_BadPermission ()
{
PerformanceCounterPermission pcp1 = new PerformanceCounterPermission (PermissionState.Unrestricted);
pcp1.Union (new SecurityPermission (SecurityPermissionFlag.Assertion));
}
[Test]
#if NET_2_0
[ExpectedException (typeof (ArgumentNullException))]
#else
// Problem inherited from ResourcePermissionBase
[ExpectedException (typeof (NullReferenceException))]
#endif
public void FromXml_Null ()
{
PerformanceCounterPermission pcp = new PerformanceCounterPermission (PermissionState.None);
pcp.FromXml (null);
}
[Test]
#if NET_2_0
[ExpectedException (typeof (ArgumentException))]
#endif
public void FromXml_WrongTag ()
{
PerformanceCounterPermission pcp = new PerformanceCounterPermission (PermissionState.None);
SecurityElement se = pcp.ToXml ();
se.Tag = "IMono";
pcp.FromXml (se);
// note: normally IPermission classes (in corlib) DO care about the
// IPermission tag
}
[Test]
#if NET_2_0
[ExpectedException (typeof (ArgumentException))]
#endif
public void FromXml_WrongTagCase ()
{
PerformanceCounterPermission pcp = new PerformanceCounterPermission (PermissionState.None);
SecurityElement se = pcp.ToXml ();
se.Tag = "IPERMISSION"; // instead of IPermission
pcp.FromXml (se);
// note: normally IPermission classes (in corlib) DO care about the
// IPermission tag
}
[Test]
public void FromXml_WrongClass ()
{
PerformanceCounterPermission pcp = new PerformanceCounterPermission (PermissionState.None);
SecurityElement se = pcp.ToXml ();
SecurityElement w = new SecurityElement (se.Tag);
w.AddAttribute ("class", "Wrong" + se.Attribute ("class"));
w.AddAttribute ("version", se.Attribute ("version"));
pcp.FromXml (w);
// doesn't care of the class name at that stage
// anyway the class has already be created so...
}
[Test]
public void FromXml_NoClass ()
{
PerformanceCounterPermission pcp = new PerformanceCounterPermission (PermissionState.None);
SecurityElement se = pcp.ToXml ();
SecurityElement w = new SecurityElement (se.Tag);
w.AddAttribute ("version", se.Attribute ("version"));
pcp.FromXml (w);
// doesn't even care of the class attribute presence
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void FromXml_WrongVersion ()
{
PerformanceCounterPermission pcp = new PerformanceCounterPermission (PermissionState.None);
SecurityElement se = pcp.ToXml ();
se.Attributes.Remove ("version");
se.Attributes.Add ("version", "2");
pcp.FromXml (se);
}
[Test]
public void FromXml_NoVersion ()
{
PerformanceCounterPermission pcp = new PerformanceCounterPermission (PermissionState.None);
SecurityElement se = pcp.ToXml ();
SecurityElement w = new SecurityElement (se.Tag);
w.AddAttribute ("class", se.Attribute ("class"));
pcp.FromXml (w);
}
}
}
| |
// 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.IO;
using System.Linq;
using System.Net.Security;
using System.Net.Sockets;
using System.Security.Authentication;
using System.Text;
using System.Threading.Tasks;
using Xunit;
namespace System.Net.Test.Common
{
public sealed partial class LoopbackServer : GenericLoopbackServer, IDisposable
{
private Socket _listenSocket;
private Options _options;
private Uri _uri;
// Use CreateServerAsync or similar to create
private LoopbackServer(Socket listenSocket, Options options)
{
_listenSocket = listenSocket;
_options = options;
var localEndPoint = (IPEndPoint)listenSocket.LocalEndPoint;
string host = options.Address.AddressFamily == AddressFamily.InterNetworkV6 ?
$"[{localEndPoint.Address}]" :
localEndPoint.Address.ToString();
string scheme = options.UseSsl ? "https" : "http";
if (options.WebSocketEndpoint)
{
scheme = options.UseSsl ? "wss" : "ws";
}
_uri = new Uri($"{scheme}://{host}:{localEndPoint.Port}/");
}
public override void Dispose()
{
if (_listenSocket != null)
{
_listenSocket.Dispose();
_listenSocket = null;
}
}
public Socket ListenSocket => _listenSocket;
public Uri Uri => _uri;
public static async Task CreateServerAsync(Func<LoopbackServer, Task> funcAsync, Options options = null)
{
options = options ?? new Options();
using (var listenSocket = new Socket(options.Address.AddressFamily, SocketType.Stream, ProtocolType.Tcp))
{
listenSocket.Bind(new IPEndPoint(options.Address, 0));
listenSocket.Listen(options.ListenBacklog);
using (var server = new LoopbackServer(listenSocket, options))
{
await funcAsync(server).ConfigureAwait(false);
}
}
}
public static Task CreateServerAsync(Func<LoopbackServer, Uri, Task> funcAsync, Options options = null)
{
return CreateServerAsync(server => funcAsync(server, server.Uri), options);
}
public static Task CreateClientAndServerAsync(Func<Uri, Task> clientFunc, Func<LoopbackServer, Task> serverFunc, Options options = null)
{
return CreateServerAsync(async server =>
{
Task clientTask = clientFunc(server.Uri);
Task serverTask = serverFunc(server);
await new Task[] { clientTask, serverTask }.WhenAllOrAnyFailed().ConfigureAwait(false);
}, options);
}
public async Task<Connection> EstablishConnectionAsync()
{
Socket s = await _listenSocket.AcceptAsync().ConfigureAwait(false);
try
{
s.NoDelay = true;
Stream stream = new NetworkStream(s, ownsSocket: false);
if (_options.UseSsl)
{
var sslStream = new SslStream(stream, false, delegate { return true; });
using (var cert = Configuration.Certificates.GetServerCertificate())
{
await sslStream.AuthenticateAsServerAsync(
cert,
clientCertificateRequired: true, // allowed but not required
enabledSslProtocols: _options.SslProtocols,
checkCertificateRevocation: false).ConfigureAwait(false);
}
stream = sslStream;
}
if (_options.StreamWrapper != null)
{
stream = _options.StreamWrapper(stream);
}
return new Connection(s, stream);
}
catch (Exception)
{
s.Close();
throw;
}
}
public async Task AcceptConnectionAsync(Func<Connection, Task> funcAsync)
{
using (Connection connection = await EstablishConnectionAsync().ConfigureAwait(false))
{
await funcAsync(connection).ConfigureAwait(false);
}
}
public async Task<List<string>> AcceptConnectionSendCustomResponseAndCloseAsync(string response)
{
List<string> lines = null;
// Note, we assume there's no request body.
// We'll close the connection after reading the request header and sending the response.
await AcceptConnectionAsync(async connection =>
{
lines = await connection.ReadRequestHeaderAndSendCustomResponseAsync(response).ConfigureAwait(false);
}).ConfigureAwait(false);
return lines;
}
public async Task<List<string>> AcceptConnectionSendCustomResponseAndCloseAsync(byte[] response)
{
List<string> lines = null;
// Note, we assume there's no request body.
// We'll close the connection after reading the request header and sending the response.
await AcceptConnectionAsync(async connection =>
{
lines = await connection.ReadRequestHeaderAndSendCustomResponseAsync(response).ConfigureAwait(false);
}).ConfigureAwait(false);
return lines;
}
public async Task<List<string>> AcceptConnectionSendResponseAndCloseAsync(HttpStatusCode statusCode = HttpStatusCode.OK, string additionalHeaders = null, string content = null)
{
List<string> lines = null;
// Note, we assume there's no request body.
// We'll close the connection after reading the request header and sending the response.
await AcceptConnectionAsync(async connection =>
{
lines = await connection.ReadRequestHeaderAndSendResponseAsync(statusCode, additionalHeaders + "Connection: close\r\n", content).ConfigureAwait(false);
}).ConfigureAwait(false);
return lines;
}
public static string GetRequestHeaderValue(List<string> headers, string name)
{
var sep = new char[] { ':' };
foreach (string line in headers)
{
string[] tokens = line.Split(sep, 2);
if (name.Equals(tokens[0], StringComparison.InvariantCultureIgnoreCase))
{
return tokens[1].Trim();
}
}
return null;
}
public static string GetRequestMethod(List<string> headers)
{
if (headers != null && headers.Count > 1)
{
return headers[0].Split()[1].Trim();
}
return null;
}
// Stolen from HttpStatusDescription code in the product code
private static string GetStatusDescription(HttpStatusCode code)
{
switch ((int)code)
{
case 100:
return "Continue";
case 101:
return "Switching Protocols";
case 102:
return "Processing";
case 200:
return "OK";
case 201:
return "Created";
case 202:
return "Accepted";
case 203:
return "Non-Authoritative Information";
case 204:
return "No Content";
case 205:
return "Reset Content";
case 206:
return "Partial Content";
case 207:
return "Multi-Status";
case 300:
return "Multiple Choices";
case 301:
return "Moved Permanently";
case 302:
return "Found";
case 303:
return "See Other";
case 304:
return "Not Modified";
case 305:
return "Use Proxy";
case 307:
return "Temporary Redirect";
case 400:
return "Bad Request";
case 401:
return "Unauthorized";
case 402:
return "Payment Required";
case 403:
return "Forbidden";
case 404:
return "Not Found";
case 405:
return "Method Not Allowed";
case 406:
return "Not Acceptable";
case 407:
return "Proxy Authentication Required";
case 408:
return "Request Timeout";
case 409:
return "Conflict";
case 410:
return "Gone";
case 411:
return "Length Required";
case 412:
return "Precondition Failed";
case 413:
return "Request Entity Too Large";
case 414:
return "Request-Uri Too Long";
case 415:
return "Unsupported Media Type";
case 416:
return "Requested Range Not Satisfiable";
case 417:
return "Expectation Failed";
case 422:
return "Unprocessable Entity";
case 423:
return "Locked";
case 424:
return "Failed Dependency";
case 426:
return "Upgrade Required"; // RFC 2817
case 500:
return "Internal Server Error";
case 501:
return "Not Implemented";
case 502:
return "Bad Gateway";
case 503:
return "Service Unavailable";
case 504:
return "Gateway Timeout";
case 505:
return "Http Version Not Supported";
case 507:
return "Insufficient Storage";
}
return null;
}
public enum ContentMode
{
ContentLength,
SingleChunk,
BytePerChunk,
ConnectionClose
}
public static string GetContentModeResponse(ContentMode mode, string content, bool connectionClose = false)
{
switch (mode)
{
case ContentMode.ContentLength:
return GetHttpResponse(content: content, connectionClose: connectionClose);
case ContentMode.SingleChunk:
return GetSingleChunkHttpResponse(content: content, connectionClose: connectionClose);
case ContentMode.BytePerChunk:
return GetBytePerChunkHttpResponse(content: content, connectionClose: connectionClose);
case ContentMode.ConnectionClose:
Assert.True(connectionClose);
return GetConnectionCloseResponse(content: content);
default:
Assert.True(false, $"Unknown content mode: {mode}");
return null;
}
}
public static string GetHttpResponse(HttpStatusCode statusCode = HttpStatusCode.OK, string additionalHeaders = null, string content = null, bool connectionClose = false) =>
GetHttpResponseHeaders(statusCode, additionalHeaders, content, connectionClose) +
content;
public static string GetHttpResponseHeaders(HttpStatusCode statusCode = HttpStatusCode.OK, string additionalHeaders = null, string content = null, bool connectionClose = false) =>
GetHttpResponseHeaders(statusCode, additionalHeaders, content == null ? 0 : content.Length, connectionClose);
public static string GetHttpResponseHeaders(HttpStatusCode statusCode = HttpStatusCode.OK, string additionalHeaders = null, int contentLength = 0, bool connectionClose = false) =>
$"HTTP/1.1 {(int)statusCode} {GetStatusDescription(statusCode)}\r\n" +
(connectionClose ? "Connection: close\r\n" : "") +
$"Date: {DateTimeOffset.UtcNow:R}\r\n" +
$"Content-Length: {contentLength}\r\n" +
additionalHeaders +
"\r\n";
public static string GetSingleChunkHttpResponse(HttpStatusCode statusCode = HttpStatusCode.OK, string additionalHeaders = null, string content = null, bool connectionClose = false) =>
$"HTTP/1.1 {(int)statusCode} {GetStatusDescription(statusCode)}\r\n" +
(connectionClose ? "Connection: close\r\n" : "") +
$"Date: {DateTimeOffset.UtcNow:R}\r\n" +
"Transfer-Encoding: chunked\r\n" +
additionalHeaders +
"\r\n" +
(string.IsNullOrEmpty(content) ? "" :
$"{content.Length:X}\r\n" +
$"{content}\r\n") +
$"0\r\n" +
$"\r\n";
public static string GetBytePerChunkHttpResponse(HttpStatusCode statusCode = HttpStatusCode.OK, string additionalHeaders = null, string content = null, bool connectionClose = false) =>
$"HTTP/1.1 {(int)statusCode} {GetStatusDescription(statusCode)}\r\n" +
(connectionClose ? "Connection: close\r\n" : "") +
$"Date: {DateTimeOffset.UtcNow:R}\r\n" +
"Transfer-Encoding: chunked\r\n" +
additionalHeaders +
"\r\n" +
(string.IsNullOrEmpty(content) ? "" : string.Concat(content.Select(c => $"1\r\n{c}\r\n"))) +
$"0\r\n" +
$"\r\n";
public static string GetConnectionCloseResponse(HttpStatusCode statusCode = HttpStatusCode.OK, string additionalHeaders = null, string content = null) =>
$"HTTP/1.1 {(int)statusCode} {GetStatusDescription(statusCode)}\r\n" +
"Connection: close\r\n" +
$"Date: {DateTimeOffset.UtcNow:R}\r\n" +
additionalHeaders +
"\r\n" +
content;
public class Options : GenericLoopbackOptions
{
public int ListenBacklog { get; set; } = 1;
public bool UseSsl { get; set; } = false;
public SslProtocols SslProtocols { get; set; } =
#if !NETSTANDARD2_0
SslProtocols.Tls13 |
#endif
SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12;
public bool WebSocketEndpoint { get; set; } = false;
public Func<Stream, Stream> StreamWrapper { get; set; }
public string Username { get; set; }
public string Domain { get; set; }
public string Password { get; set; }
public bool IsProxy { get; set; } = false;
}
public sealed class Connection : GenericLoopbackConnection
{
private const int BufferSize = 4000;
private Socket _socket;
private Stream _stream;
private StreamWriter _writer;
private byte[] _readBuffer;
private int _readStart;
private int _readEnd;
private int _contentLength = 0;
private bool _bodyRead = false;
public Connection(Socket socket, Stream stream)
{
_socket = socket;
_stream = stream;
_writer = new StreamWriter(stream, Encoding.ASCII) { AutoFlush = true };
_readBuffer = new byte[BufferSize];
_readStart = 0;
_readEnd = 0;
}
public Socket Socket => _socket;
public Stream Stream => _stream;
public StreamWriter Writer => _writer;
public async Task<int> ReadAsync(Memory<byte> buffer, int offset, int size)
{
if (_readEnd - _readStart > 0)
{
// Use buffered data first.
int copyLength = Math.Min(size, _readEnd - _readStart);
Memory<byte> source = new Memory<byte>(_readBuffer).Slice(_readStart, copyLength);
source.CopyTo(buffer.Slice(offset));
_readStart += copyLength;
return copyLength;
}
#if NETSTANDARD2_0
// stream does not have Memory<t> overload
byte[] tempBuffer = new byte[size];
int readLength = await _stream.ReadAsync(tempBuffer, 0, size).ConfigureAwait(false);
if (readLength > 0)
{
tempBuffer.AsSpan(readLength).CopyTo(buffer.Span.Slice(offset, size));
}
return readLength;
#else
return await _stream.ReadAsync(buffer.Slice(offset, size)).ConfigureAwait(false);
#endif
}
// Read until we either get requested data or we hit end of stream.
public async Task<int> ReadBlockAsync(Memory<byte> buffer, int offset, int size)
{
int totalLength = 0;
while (size != 0)
{
int readLength = await ReadAsync(buffer, offset, size).ConfigureAwait(false);
if (readLength == 0)
{
throw new Exception("Unexpected EOF trying to read");
}
totalLength += readLength;
offset += readLength;
size -= readLength;
}
return totalLength;
}
public async Task<int> ReadBlockAsync(char[] result, int offset, int size)
{
byte[] buffer = new byte[size];
int readLength = await ReadBlockAsync(buffer, 0, size).ConfigureAwait(false);
string asString = System.Text.Encoding.ASCII.GetString(buffer, 0, readLength);
for (int i = 0; i < readLength; i++)
{
result[offset + i] = asString[i];
}
return readLength;
}
public async Task<string> ReadToEndAsync()
{
byte[] buffer = new byte[BufferSize];
int offset = 0;
int totalLength = 0;
int bytesRead;
do
{
bytesRead = await ReadAsync(buffer, offset, buffer.Length - offset).ConfigureAwait(false);
totalLength += bytesRead;
offset += bytesRead;
if (bytesRead == buffer.Length)
{
byte[] newBuffer = new byte[buffer.Length + BufferSize];
buffer.CopyTo(newBuffer, 0);
offset = buffer.Length;
buffer = newBuffer;
}
} while (bytesRead > 0);
return System.Text.Encoding.ASCII.GetString(buffer, 0, totalLength);
}
public string ReadLine()
{
return ReadLineAsync().GetAwaiter().GetResult();
}
public async Task<string> ReadLineAsync()
{
int index = 0;
int startSearch = _readStart;
while (true)
{
if (_readStart == _readEnd || index == -1)
{
// We either have no data or we did not find LF in stream.
// In either case, read more.
if (_readEnd + 2 > _readBuffer.Length)
{
// We no longer have space to read CRLF. Allocate new buffer and start over.
byte[] newBuffer = new byte[_readBuffer.Length + BufferSize];
int dataLength = _readEnd - _readStart;
if (dataLength > 0)
{
Array.Copy(_readBuffer, _readStart, newBuffer, 0, dataLength);
_readStart = 0;
_readEnd = dataLength;
_readBuffer = newBuffer;
}
}
int bytesRead = await _stream.ReadAsync(_readBuffer, _readEnd, _readBuffer.Length - _readEnd).ConfigureAwait(false);
if (bytesRead == 0)
{
break;
}
_readEnd += bytesRead;
}
index = Array.IndexOf(_readBuffer, (byte)'\n', startSearch, _readEnd - startSearch);
if (index == -1)
{
// We did not find it, look for more data.
startSearch = _readEnd;
continue;
}
int stringLength = index - _readStart;
// Consume CRLF if present.
if (_readBuffer[_readStart + stringLength] == '\n') { stringLength--; }
if (_readBuffer[_readStart + stringLength] == '\r') { stringLength--; }
string line = System.Text.Encoding.ASCII.GetString(_readBuffer, _readStart, stringLength + 1);
_readStart = index + 1;
return line;
}
return null;
}
public override void Dispose()
{
try
{
// Try to shutdown the send side of the socket.
// This seems to help avoid connection reset issues caused by buffered data
// that has not been sent/acked when the graceful shutdown timeout expires.
// This may throw if the socket was already closed, so eat any exception.
_socket.Shutdown(SocketShutdown.Send);
}
catch (Exception) { }
_writer.Dispose();
_stream.Dispose();
_socket.Dispose();
}
public async Task<List<string>> ReadRequestHeaderAsync()
{
var lines = new List<string>();
string line;
while (!string.IsNullOrEmpty(line = await ReadLineAsync().ConfigureAwait(false)))
{
lines.Add(line);
}
if (line == null)
{
throw new IOException("Unexpected EOF trying to read request header");
}
return lines;
}
public async Task SendResponseAsync(string response)
{
await _writer.WriteAsync(response).ConfigureAwait(false);
}
public async Task SendResponseAsync(HttpStatusCode statusCode = HttpStatusCode.OK, string additionalHeaders = null, string content = null)
{
await SendResponseAsync(GetHttpResponse(statusCode, additionalHeaders, content)).ConfigureAwait(false);
}
public async Task<List<string>> ReadRequestHeaderAndSendCustomResponseAsync(string response)
{
List<string> lines = await ReadRequestHeaderAsync().ConfigureAwait(false);
await _writer.WriteAsync(response).ConfigureAwait(false);
return lines;
}
public async Task<List<string>> ReadRequestHeaderAndSendCustomResponseAsync(byte[] response)
{
List<string> lines = await ReadRequestHeaderAsync().ConfigureAwait(false);
await _stream.WriteAsync(response, 0, response.Length).ConfigureAwait(false);
return lines;
}
public async Task<List<string>> ReadRequestHeaderAndSendResponseAsync(HttpStatusCode statusCode = HttpStatusCode.OK, string additionalHeaders = null, string content = null)
{
List<string> lines = await ReadRequestHeaderAsync().ConfigureAwait(false);
await SendResponseAsync(statusCode, additionalHeaders, content).ConfigureAwait(false);
return lines;
}
//
// GenericLoopbackServer implementation
//
public override async Task<HttpRequestData> ReadRequestDataAsync(bool readBody = true)
{
List<string> headerLines = null;
HttpRequestData requestData = new HttpRequestData();
headerLines = await ReadRequestHeaderAsync().ConfigureAwait(false);
// Parse method and path
string[] splits = headerLines[0].Split(' ');
requestData.Method = splits[0];
requestData.Path = splits[1];
// Convert header lines to key/value pairs
// Skip first line since it's the status line
foreach (var line in headerLines.Skip(1))
{
int offset = line.IndexOf(':');
string name = line.Substring(0, offset);
string value = line.Substring(offset + 1).TrimStart();
requestData.Headers.Add(new HttpHeaderData(name, value));
}
if (requestData.Method != "GET")
{
if (requestData.GetHeaderValueCount("Content-Length") != 0)
{
_contentLength = Int32.Parse(requestData.GetSingleHeaderValue("Content-Length"));
}
else if (requestData.GetHeaderValueCount("Transfer-Encoding") != 0 && requestData.GetSingleHeaderValue("Transfer-Encoding") == "chunked")
{
_contentLength = -1;
}
}
if (readBody)
{
requestData.Body = await ReadRequestBodyAsync().ConfigureAwait(false);
_bodyRead = true;
}
return requestData;
}
public override async Task<Byte[]> ReadRequestBodyAsync()
{
byte[] buffer = null;
if (_bodyRead)
{
throw new InvalidOperationException("Body already done");
}
if (_contentLength == 0)
{
buffer = new byte[0];
}
if (_contentLength > 0)
{
buffer = new byte[_contentLength];
int bytesRead = await ReadBlockAsync(buffer, 0, _contentLength).ConfigureAwait(false);
Assert.Equal(_contentLength, bytesRead);
}
else if (_contentLength < 0)
{
// Chunked Encoding
while (true)
{
string chunkHeader = await ReadLineAsync().ConfigureAwait(false);
int chunkLength = int.Parse(chunkHeader, System.Globalization.NumberStyles.HexNumber);
if (chunkLength == 0)
{
// Last chunk. Read CRLF and exit.
await ReadLineAsync().ConfigureAwait(false);
break;
}
byte[] chunk = new byte[chunkLength];
await ReadBlockAsync(chunk, 0, chunkLength).ConfigureAwait(false);
await ReadLineAsync().ConfigureAwait(false);
if (buffer == null)
{
buffer = chunk;
}
else
{
byte[] newBuffer = new byte[buffer.Length + chunkLength];
buffer.CopyTo(newBuffer, 0);
chunk.CopyTo(newBuffer, buffer.Length);
buffer = newBuffer;
}
}
}
return buffer;
}
public override async Task SendResponseAsync(HttpStatusCode? statusCode = HttpStatusCode.OK, IList<HttpHeaderData> headers = null, string content = null, bool isFinal = true, int requestId = 0)
{
string headerString = null;
int contentLength = -1;
bool isChunked = false;
bool hasContentLength = false;
if (headers != null)
{
// Process given headers and look for some well-known cases.
foreach (HttpHeaderData headerData in headers)
{
if (headerData.Name.Equals("Content-Length", StringComparison.OrdinalIgnoreCase))
{
hasContentLength = true;
if (headerData.Value == null)
{
continue;
}
contentLength = int.Parse(headerData.Value);
}
else if (headerData.Name.Equals("Transfer-Encoding", StringComparison.OrdinalIgnoreCase) && headerData.Value.Equals("chunked", StringComparison.OrdinalIgnoreCase))
{
isChunked = true;
}
headerString = headerString + $"{headerData.Name}: {headerData.Value}\r\n";
}
}
bool endHeaders = content != null || isFinal;
if (statusCode != null)
{
// If we need to send status line, prepped it to headers and possibly add missing headers to the end.
headerString =
$"HTTP/1.1 {(int)statusCode} {GetStatusDescription((HttpStatusCode)statusCode)}\r\n" +
(!hasContentLength && !isChunked && content != null ? $"Content-length: {content.Length}\r\n" : "") +
headerString +
(endHeaders ? "\r\n" : "");
}
await SendResponseAsync(headerString).ConfigureAwait(false);
if (content != null)
{
await SendResponseBodyAsync(content, isFinal: isFinal, requestId: requestId).ConfigureAwait(false);
}
}
public override async Task SendResponseHeadersAsync(HttpStatusCode statusCode = HttpStatusCode.OK, IList<HttpHeaderData> headers = null, int requestId = 0)
{
string headerString = null;
if (headers != null)
{
foreach (HttpHeaderData headerData in headers)
{
headerString = headerString + $"{headerData.Name}: {headerData.Value}\r\n";
}
}
headerString = GetHttpResponseHeaders(statusCode, headerString, 0, connectionClose: true);
await SendResponseAsync(headerString).ConfigureAwait(false);
}
public override async Task SendResponseBodyAsync(byte[] body, bool isFinal = true, int requestId = 0)
{
await SendResponseAsync(Encoding.UTF8.GetString(body)).ConfigureAwait(false);
}
public override async Task WaitForCancellationAsync(bool ignoreIncomingData = true, int requestId = 0)
{
var buffer = new byte[1024];
while (true)
{
int bytesRead = await ReadAsync(buffer, 0, buffer.Length).ConfigureAwait(false);
if (!ignoreIncomingData)
{
Assert.Equal(0, bytesRead);
}
if (bytesRead == 0)
{
break;
}
}
}
}
public override async Task<HttpRequestData> HandleRequestAsync(HttpStatusCode statusCode = HttpStatusCode.OK, IList<HttpHeaderData> headers = null, string content = "")
{
using (Connection connection = await EstablishConnectionAsync().ConfigureAwait(false))
{
HttpRequestData requestData = await connection.ReadRequestDataAsync().ConfigureAwait(false);
// For historical reasons, we added Date and "Connection: close" (to improve test reliability)
bool hasDate = false;
List<HttpHeaderData> newHeaders = new List<HttpHeaderData>();
if (headers != null)
{
foreach (var header in headers)
{
newHeaders.Add(header);
if (header.Name.Equals("Date", StringComparison.OrdinalIgnoreCase))
{
hasDate = true;
}
}
}
newHeaders.Add(new HttpHeaderData("Connection", "Close"));
if (!hasDate)
{
newHeaders.Add(new HttpHeaderData("Date", "{DateTimeOffset.UtcNow:R}"));
}
await connection.SendResponseAsync(statusCode, newHeaders, content: content).ConfigureAwait(false);
return requestData;
}
}
public override Task AcceptConnectionAsync(Func<GenericLoopbackConnection, Task> funcAsync)
{
return AcceptConnectionAsync((Func<Connection, Task>)funcAsync);
}
}
public sealed class Http11LoopbackServerFactory : LoopbackServerFactory
{
public static readonly Http11LoopbackServerFactory Singleton = new Http11LoopbackServerFactory();
public override Task CreateServerAsync(Func<GenericLoopbackServer, Uri, Task> funcAsync, int millisecondsTimeout = 60_000, GenericLoopbackOptions options = null)
{
LoopbackServer.Options newOptions = new LoopbackServer.Options();
if (options != null)
{
newOptions.Address = options.Address;
}
return LoopbackServer.CreateServerAsync((server, uri) => funcAsync(server, uri), options: newOptions);
}
public override bool IsHttp11 => true;
public override bool IsHttp2 => false;
}
}
| |
using System;
using System.Collections;
using System.IO;
using Org.BouncyCastle.Asn1;
using Org.BouncyCastle.Asn1.Cms;
using Org.BouncyCastle.Asn1.X509;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Security.Certificates;
using Org.BouncyCastle.Utilities;
using Org.BouncyCastle.X509;
namespace Org.BouncyCastle.Cms
{
/**
* general class for generating a pkcs7-signature message.
* <p>
* A simple example of usage.
*
* <pre>
* IX509Store certs...
* IX509Store crls...
* CmsSignedDataGenerator gen = new CmsSignedDataGenerator();
*
* gen.AddSigner(privKey, cert, CmsSignedGenerator.DigestSha1);
* gen.AddCertificates(certs);
* gen.AddCrls(crls);
*
* CmsSignedData data = gen.Generate(content);
* </pre>
* </p>
*/
public class CmsSignedDataGenerator
: CmsSignedGenerator
{
private static readonly CmsSignedHelper Helper = CmsSignedHelper.Instance;
private readonly IList signerInfs = Platform.CreateArrayList();
private class SignerInf
{
private readonly CmsSignedGenerator outer;
private readonly AsymmetricKeyParameter key;
private readonly SignerIdentifier signerIdentifier;
private readonly string digestOID;
private readonly string encOID;
private readonly CmsAttributeTableGenerator sAttr;
private readonly CmsAttributeTableGenerator unsAttr;
private readonly Asn1.Cms.AttributeTable baseSignedTable;
internal SignerInf(
CmsSignedGenerator outer,
AsymmetricKeyParameter key,
SignerIdentifier signerIdentifier,
string digestOID,
string encOID,
CmsAttributeTableGenerator sAttr,
CmsAttributeTableGenerator unsAttr,
Asn1.Cms.AttributeTable baseSignedTable)
{
this.outer = outer;
this.key = key;
this.signerIdentifier = signerIdentifier;
this.digestOID = digestOID;
this.encOID = encOID;
this.sAttr = sAttr;
this.unsAttr = unsAttr;
this.baseSignedTable = baseSignedTable;
}
internal AlgorithmIdentifier DigestAlgorithmID
{
get { return new AlgorithmIdentifier(new DerObjectIdentifier(digestOID), DerNull.Instance); }
}
internal CmsAttributeTableGenerator SignedAttributes
{
get { return sAttr; }
}
internal CmsAttributeTableGenerator UnsignedAttributes
{
get { return unsAttr; }
}
internal SignerInfo ToSignerInfo(
DerObjectIdentifier contentType,
CmsProcessable content,
SecureRandom random)
{
AlgorithmIdentifier digAlgId = DigestAlgorithmID;
string digestName = Helper.GetDigestAlgName(digestOID);
string signatureName = digestName + "with" + Helper.GetEncryptionAlgName(encOID);
ISigner sig = Helper.GetSignatureInstance(signatureName);
byte[] hash;
if (outer._digests.Contains(digestOID))
{
hash = (byte[])outer._digests[digestOID];
}
else
{
IDigest dig = Helper.GetDigestInstance(digestName);
if (content != null)
{
content.Write(new DigOutputStream(dig));
}
hash = DigestUtilities.DoFinal(dig);
outer._digests.Add(digestOID, hash.Clone());
}
sig.Init(true, new ParametersWithRandom(key, random));
#if NETCF_1_0 || NETCF_2_0 || SILVERLIGHT
Stream sigStr = new SigOutputStream(sig);
#else
Stream sigStr = new BufferedStream(new SigOutputStream(sig));
#endif
Asn1Set signedAttr = null;
if (sAttr != null)
{
IDictionary parameters = outer.GetBaseParameters(contentType, digAlgId, hash);
// Asn1.Cms.AttributeTable signed = sAttr.GetAttributes(Collections.unmodifiableMap(parameters));
Asn1.Cms.AttributeTable signed = sAttr.GetAttributes(parameters);
if (contentType == null) //counter signature
{
if (signed != null && signed[CmsAttributes.ContentType] != null)
{
IDictionary tmpSigned = signed.ToDictionary();
tmpSigned.Remove(CmsAttributes.ContentType);
signed = new Asn1.Cms.AttributeTable(tmpSigned);
}
}
// TODO Validate proposed signed attributes
signedAttr = outer.GetAttributeSet(signed);
// sig must be composed from the DER encoding.
new DerOutputStream(sigStr).WriteObject(signedAttr);
}
else if (content != null)
{
// TODO Use raw signature of the hash value instead
content.Write(sigStr);
}
sigStr.Close();
byte[] sigBytes = sig.GenerateSignature();
Asn1Set unsignedAttr = null;
if (unsAttr != null)
{
IDictionary baseParameters = outer.GetBaseParameters(contentType, digAlgId, hash);
baseParameters[CmsAttributeTableParameter.Signature] = sigBytes.Clone();
// Asn1.Cms.AttributeTable unsigned = unsAttr.GetAttributes(Collections.unmodifiableMap(baseParameters));
Asn1.Cms.AttributeTable unsigned = unsAttr.GetAttributes(baseParameters);
// TODO Validate proposed unsigned attributes
unsignedAttr = outer.GetAttributeSet(unsigned);
}
// TODO[RSAPSS] Need the ability to specify non-default parameters
Asn1Encodable sigX509Parameters = SignerUtilities.GetDefaultX509Parameters(signatureName);
AlgorithmIdentifier encAlgId = CmsSignedGenerator.GetEncAlgorithmIdentifier(
new DerObjectIdentifier(encOID), sigX509Parameters);
return new SignerInfo(signerIdentifier, digAlgId,
signedAttr, encAlgId, new DerOctetString(sigBytes), unsignedAttr);
}
}
public CmsSignedDataGenerator()
{
}
/// <summary>Constructor allowing specific source of randomness</summary>
/// <param name="rand">Instance of <c>SecureRandom</c> to use.</param>
public CmsSignedDataGenerator(
SecureRandom rand)
: base(rand)
{
}
/**
* add a signer - no attributes other than the default ones will be
* provided here.
*
* @param key signing key to use
* @param cert certificate containing corresponding public key
* @param digestOID digest algorithm OID
*/
public void AddSigner(
AsymmetricKeyParameter privateKey,
X509Certificate cert,
string digestOID)
{
AddSigner(privateKey, cert, GetEncOid(privateKey, digestOID), digestOID);
}
/**
* add a signer, specifying the digest encryption algorithm to use - no attributes other than the default ones will be
* provided here.
*
* @param key signing key to use
* @param cert certificate containing corresponding public key
* @param encryptionOID digest encryption algorithm OID
* @param digestOID digest algorithm OID
*/
public void AddSigner(
AsymmetricKeyParameter privateKey,
X509Certificate cert,
string encryptionOID,
string digestOID)
{
doAddSigner(privateKey, GetSignerIdentifier(cert), encryptionOID, digestOID,
new DefaultSignedAttributeTableGenerator(), null, null);
}
/**
* add a signer - no attributes other than the default ones will be
* provided here.
*/
public void AddSigner(
AsymmetricKeyParameter privateKey,
byte[] subjectKeyID,
string digestOID)
{
AddSigner(privateKey, subjectKeyID, GetEncOid(privateKey, digestOID), digestOID);
}
/**
* add a signer, specifying the digest encryption algorithm to use - no attributes other than the default ones will be
* provided here.
*/
public void AddSigner(
AsymmetricKeyParameter privateKey,
byte[] subjectKeyID,
string encryptionOID,
string digestOID)
{
doAddSigner(privateKey, GetSignerIdentifier(subjectKeyID), encryptionOID, digestOID,
new DefaultSignedAttributeTableGenerator(), null, null);
}
/**
* add a signer with extra signed/unsigned attributes.
*
* @param key signing key to use
* @param cert certificate containing corresponding public key
* @param digestOID digest algorithm OID
* @param signedAttr table of attributes to be included in signature
* @param unsignedAttr table of attributes to be included as unsigned
*/
public void AddSigner(
AsymmetricKeyParameter privateKey,
X509Certificate cert,
string digestOID,
Asn1.Cms.AttributeTable signedAttr,
Asn1.Cms.AttributeTable unsignedAttr)
{
AddSigner(privateKey, cert, GetEncOid(privateKey, digestOID), digestOID,
signedAttr, unsignedAttr);
}
/**
* add a signer, specifying the digest encryption algorithm, with extra signed/unsigned attributes.
*
* @param key signing key to use
* @param cert certificate containing corresponding public key
* @param encryptionOID digest encryption algorithm OID
* @param digestOID digest algorithm OID
* @param signedAttr table of attributes to be included in signature
* @param unsignedAttr table of attributes to be included as unsigned
*/
public void AddSigner(
AsymmetricKeyParameter privateKey,
X509Certificate cert,
string encryptionOID,
string digestOID,
Asn1.Cms.AttributeTable signedAttr,
Asn1.Cms.AttributeTable unsignedAttr)
{
doAddSigner(privateKey, GetSignerIdentifier(cert), encryptionOID, digestOID,
new DefaultSignedAttributeTableGenerator(signedAttr),
new SimpleAttributeTableGenerator(unsignedAttr),
signedAttr);
}
/**
* add a signer with extra signed/unsigned attributes.
*
* @param key signing key to use
* @param subjectKeyID subjectKeyID of corresponding public key
* @param digestOID digest algorithm OID
* @param signedAttr table of attributes to be included in signature
* @param unsignedAttr table of attributes to be included as unsigned
*/
public void AddSigner(
AsymmetricKeyParameter privateKey,
byte[] subjectKeyID,
string digestOID,
Asn1.Cms.AttributeTable signedAttr,
Asn1.Cms.AttributeTable unsignedAttr)
{
AddSigner(privateKey, subjectKeyID, GetEncOid(privateKey, digestOID), digestOID,
signedAttr, unsignedAttr);
}
/**
* add a signer, specifying the digest encryption algorithm, with extra signed/unsigned attributes.
*
* @param key signing key to use
* @param subjectKeyID subjectKeyID of corresponding public key
* @param encryptionOID digest encryption algorithm OID
* @param digestOID digest algorithm OID
* @param signedAttr table of attributes to be included in signature
* @param unsignedAttr table of attributes to be included as unsigned
*/
public void AddSigner(
AsymmetricKeyParameter privateKey,
byte[] subjectKeyID,
string encryptionOID,
string digestOID,
Asn1.Cms.AttributeTable signedAttr,
Asn1.Cms.AttributeTable unsignedAttr)
{
doAddSigner(privateKey, GetSignerIdentifier(subjectKeyID), encryptionOID, digestOID,
new DefaultSignedAttributeTableGenerator(signedAttr),
new SimpleAttributeTableGenerator(unsignedAttr),
signedAttr);
}
/**
* add a signer with extra signed/unsigned attributes based on generators.
*/
public void AddSigner(
AsymmetricKeyParameter privateKey,
X509Certificate cert,
string digestOID,
CmsAttributeTableGenerator signedAttrGen,
CmsAttributeTableGenerator unsignedAttrGen)
{
AddSigner(privateKey, cert, GetEncOid(privateKey, digestOID), digestOID,
signedAttrGen, unsignedAttrGen);
}
/**
* add a signer, specifying the digest encryption algorithm, with extra signed/unsigned attributes based on generators.
*/
public void AddSigner(
AsymmetricKeyParameter privateKey,
X509Certificate cert,
string encryptionOID,
string digestOID,
CmsAttributeTableGenerator signedAttrGen,
CmsAttributeTableGenerator unsignedAttrGen)
{
doAddSigner(privateKey, GetSignerIdentifier(cert), encryptionOID, digestOID, signedAttrGen,
unsignedAttrGen, null);
}
/**
* add a signer with extra signed/unsigned attributes based on generators.
*/
public void AddSigner(
AsymmetricKeyParameter privateKey,
byte[] subjectKeyID,
string digestOID,
CmsAttributeTableGenerator signedAttrGen,
CmsAttributeTableGenerator unsignedAttrGen)
{
AddSigner(privateKey, subjectKeyID, GetEncOid(privateKey, digestOID), digestOID,
signedAttrGen, unsignedAttrGen);
}
/**
* add a signer, including digest encryption algorithm, with extra signed/unsigned attributes based on generators.
*/
public void AddSigner(
AsymmetricKeyParameter privateKey,
byte[] subjectKeyID,
string encryptionOID,
string digestOID,
CmsAttributeTableGenerator signedAttrGen,
CmsAttributeTableGenerator unsignedAttrGen)
{
doAddSigner(privateKey, GetSignerIdentifier(subjectKeyID), encryptionOID, digestOID,
signedAttrGen, unsignedAttrGen, null);
}
private void doAddSigner(
AsymmetricKeyParameter privateKey,
SignerIdentifier signerIdentifier,
string encryptionOID,
string digestOID,
CmsAttributeTableGenerator signedAttrGen,
CmsAttributeTableGenerator unsignedAttrGen,
Asn1.Cms.AttributeTable baseSignedTable)
{
signerInfs.Add(new SignerInf(this, privateKey, signerIdentifier, digestOID, encryptionOID,
signedAttrGen, unsignedAttrGen, baseSignedTable));
}
/**
* generate a signed object that for a CMS Signed Data object
*/
public CmsSignedData Generate(
CmsProcessable content)
{
return Generate(content, false);
}
/**
* generate a signed object that for a CMS Signed Data
* object - if encapsulate is true a copy
* of the message will be included in the signature. The content type
* is set according to the OID represented by the string signedContentType.
*/
public CmsSignedData Generate(
string signedContentType,
// FIXME Avoid accessing more than once to support CmsProcessableInputStream
CmsProcessable content,
bool encapsulate)
{
Asn1EncodableVector digestAlgs = new Asn1EncodableVector();
Asn1EncodableVector signerInfos = new Asn1EncodableVector();
_digests.Clear(); // clear the current preserved digest state
//
// add the precalculated SignerInfo objects.
//
foreach (SignerInformation signer in _signers)
{
digestAlgs.Add(Helper.FixAlgID(signer.DigestAlgorithmID));
// TODO Verify the content type and calculated digest match the precalculated SignerInfo
signerInfos.Add(signer.ToSignerInfo());
}
//
// add the SignerInfo objects
//
bool isCounterSignature = (signedContentType == null);
DerObjectIdentifier contentTypeOid = isCounterSignature
? null
: new DerObjectIdentifier(signedContentType);
foreach (SignerInf signer in signerInfs)
{
try
{
digestAlgs.Add(signer.DigestAlgorithmID);
signerInfos.Add(signer.ToSignerInfo(contentTypeOid, content, rand));
}
catch (IOException e)
{
throw new CmsException("encoding error.", e);
}
catch (InvalidKeyException e)
{
throw new CmsException("key inappropriate for signature.", e);
}
catch (SignatureException e)
{
throw new CmsException("error creating signature.", e);
}
catch (CertificateEncodingException e)
{
throw new CmsException("error creating sid.", e);
}
}
Asn1Set certificates = null;
if (_certs.Count != 0)
{
certificates = CmsUtilities.CreateBerSetFromList(_certs);
}
Asn1Set certrevlist = null;
if (_crls.Count != 0)
{
certrevlist = CmsUtilities.CreateBerSetFromList(_crls);
}
Asn1OctetString octs = null;
if (encapsulate)
{
MemoryStream bOut = new MemoryStream();
if (content != null)
{
try
{
content.Write(bOut);
}
catch (IOException e)
{
throw new CmsException("encapsulation error.", e);
}
}
octs = new BerOctetString(bOut.ToArray());
}
ContentInfo encInfo = new ContentInfo(contentTypeOid, octs);
SignedData sd = new SignedData(
new DerSet(digestAlgs),
encInfo,
certificates,
certrevlist,
new DerSet(signerInfos));
ContentInfo contentInfo = new ContentInfo(CmsObjectIdentifiers.SignedData, sd);
return new CmsSignedData(content, contentInfo);
}
/**
* generate a signed object that for a CMS Signed Data
* object - if encapsulate is true a copy
* of the message will be included in the signature with the
* default content type "data".
*/
public CmsSignedData Generate(
CmsProcessable content,
bool encapsulate)
{
return this.Generate(Data, content, encapsulate);
}
/**
* generate a set of one or more SignerInformation objects representing counter signatures on
* the passed in SignerInformation object.
*
* @param signer the signer to be countersigned
* @param sigProvider the provider to be used for counter signing.
* @return a store containing the signers.
*/
public SignerInformationStore GenerateCounterSigners(
SignerInformation signer)
{
return this.Generate(null, new CmsProcessableByteArray(signer.GetSignature()), false).GetSignerInfos();
}
}
}
| |
using System;
using System.Globalization;
using System.Collections.Generic;
using Sasoma.Utils;
using Sasoma.Microdata.Interfaces;
using Sasoma.Languages.Core;
using Sasoma.Microdata.Properties;
namespace Sasoma.Microdata.Types
{
/// <summary>
/// A library.
/// </summary>
public class Library_Core : TypeCore, ILocalBusiness
{
public Library_Core()
{
this._TypeId = 150;
this._Id = "Library";
this._Schema_Org_Url = "http://schema.org/Library";
string label = "";
GetLabel(out label, "Library", typeof(Library_Core));
this._Label = label;
this._Ancestors = new int[]{266,193,155};
this._SubTypes = new int[0];
this._SuperTypes = new int[]{155};
this._Properties = new int[]{67,108,143,229,5,10,49,85,91,98,115,135,159,199,196,47,75,77,94,95,130,137,36,60,152,156,167};
}
/// <summary>
/// Physical address of the item.
/// </summary>
private Address_Core address;
public Address_Core Address
{
get
{
return address;
}
set
{
address = value;
SetPropertyInstance(address);
}
}
/// <summary>
/// The overall rating, based on a collection of reviews or ratings, of the item.
/// </summary>
private Properties.AggregateRating_Core aggregateRating;
public Properties.AggregateRating_Core AggregateRating
{
get
{
return aggregateRating;
}
set
{
aggregateRating = value;
SetPropertyInstance(aggregateRating);
}
}
/// <summary>
/// The larger organization that this local business is a branch of, if any.
/// </summary>
private BranchOf_Core branchOf;
public BranchOf_Core BranchOf
{
get
{
return branchOf;
}
set
{
branchOf = value;
SetPropertyInstance(branchOf);
}
}
/// <summary>
/// A contact point for a person or organization.
/// </summary>
private ContactPoints_Core contactPoints;
public ContactPoints_Core ContactPoints
{
get
{
return contactPoints;
}
set
{
contactPoints = value;
SetPropertyInstance(contactPoints);
}
}
/// <summary>
/// The basic containment relation between places.
/// </summary>
private ContainedIn_Core containedIn;
public ContainedIn_Core ContainedIn
{
get
{
return containedIn;
}
set
{
containedIn = value;
SetPropertyInstance(containedIn);
}
}
/// <summary>
/// The currency accepted (in <a href=\http://en.wikipedia.org/wiki/ISO_4217\ target=\new\>ISO 4217 currency format</a>).
/// </summary>
private CurrenciesAccepted_Core currenciesAccepted;
public CurrenciesAccepted_Core CurrenciesAccepted
{
get
{
return currenciesAccepted;
}
set
{
currenciesAccepted = value;
SetPropertyInstance(currenciesAccepted);
}
}
/// <summary>
/// A short description of the item.
/// </summary>
private Description_Core description;
public Description_Core Description
{
get
{
return description;
}
set
{
description = value;
SetPropertyInstance(description);
}
}
/// <summary>
/// Email address.
/// </summary>
private Email_Core email;
public Email_Core Email
{
get
{
return email;
}
set
{
email = value;
SetPropertyInstance(email);
}
}
/// <summary>
/// People working for this organization.
/// </summary>
private Employees_Core employees;
public Employees_Core Employees
{
get
{
return employees;
}
set
{
employees = value;
SetPropertyInstance(employees);
}
}
/// <summary>
/// Upcoming or past events associated with this place or organization.
/// </summary>
private Events_Core events;
public Events_Core Events
{
get
{
return events;
}
set
{
events = value;
SetPropertyInstance(events);
}
}
/// <summary>
/// The fax number.
/// </summary>
private FaxNumber_Core faxNumber;
public FaxNumber_Core FaxNumber
{
get
{
return faxNumber;
}
set
{
faxNumber = value;
SetPropertyInstance(faxNumber);
}
}
/// <summary>
/// A person who founded this organization.
/// </summary>
private Founders_Core founders;
public Founders_Core Founders
{
get
{
return founders;
}
set
{
founders = value;
SetPropertyInstance(founders);
}
}
/// <summary>
/// The date that this organization was founded.
/// </summary>
private FoundingDate_Core foundingDate;
public FoundingDate_Core FoundingDate
{
get
{
return foundingDate;
}
set
{
foundingDate = value;
SetPropertyInstance(foundingDate);
}
}
/// <summary>
/// The geo coordinates of the place.
/// </summary>
private Geo_Core geo;
public Geo_Core Geo
{
get
{
return geo;
}
set
{
geo = value;
SetPropertyInstance(geo);
}
}
/// <summary>
/// URL of an image of the item.
/// </summary>
private Image_Core image;
public Image_Core Image
{
get
{
return image;
}
set
{
image = value;
SetPropertyInstance(image);
}
}
/// <summary>
/// A count of a specific user interactions with this item\u2014for example, <code>20 UserLikes</code>, <code>5 UserComments</code>, or <code>300 UserDownloads</code>. The user interaction type should be one of the sub types of <a href=\http://schema.org/UserInteraction\>UserInteraction</a>.
/// </summary>
private InteractionCount_Core interactionCount;
public InteractionCount_Core InteractionCount
{
get
{
return interactionCount;
}
set
{
interactionCount = value;
SetPropertyInstance(interactionCount);
}
}
/// <summary>
/// The location of the event or organization.
/// </summary>
private Location_Core location;
public Location_Core Location
{
get
{
return location;
}
set
{
location = value;
SetPropertyInstance(location);
}
}
/// <summary>
/// A URL to a map of the place.
/// </summary>
private Maps_Core maps;
public Maps_Core Maps
{
get
{
return maps;
}
set
{
maps = value;
SetPropertyInstance(maps);
}
}
/// <summary>
/// A member of this organization.
/// </summary>
private Members_Core members;
public Members_Core Members
{
get
{
return members;
}
set
{
members = value;
SetPropertyInstance(members);
}
}
/// <summary>
/// The name of the item.
/// </summary>
private Name_Core name;
public Name_Core Name
{
get
{
return name;
}
set
{
name = value;
SetPropertyInstance(name);
}
}
/// <summary>
/// The opening hours for a business. Opening hours can be specified as a weekly time range, starting with days, then times per day. Multiple days can be listed with commas ',' separating each day. Day or time ranges are specified using a hyphen '-'.<br/>- Days are specified using the following two-letter combinations: <code>Mo</code>, <code>Tu</code>, <code>We</code>, <code>Th</code>, <code>Fr</code>, <code>Sa</code>, <code>Su</code>.<br/>- Times are specified using 24:00 time. For example, 3pm is specified as <code>15:00</code>. <br/>- Here is an example: <code><time itemprop=\openingHours\ datetime=\Tu,Th 16:00-20:00\>Tuesdays and Thursdays 4-8pm</time></code>. <br/>- If a business is open 7 days a week, then it can be specified as <code><time itemprop=\openingHours\ datetime=\Mo-Su\>Monday through Sunday, all day</time></code>.
/// </summary>
private OpeningHours_Core openingHours;
public OpeningHours_Core OpeningHours
{
get
{
return openingHours;
}
set
{
openingHours = value;
SetPropertyInstance(openingHours);
}
}
/// <summary>
/// Cash, credit card, etc.
/// </summary>
private PaymentAccepted_Core paymentAccepted;
public PaymentAccepted_Core PaymentAccepted
{
get
{
return paymentAccepted;
}
set
{
paymentAccepted = value;
SetPropertyInstance(paymentAccepted);
}
}
/// <summary>
/// Photographs of this place.
/// </summary>
private Photos_Core photos;
public Photos_Core Photos
{
get
{
return photos;
}
set
{
photos = value;
SetPropertyInstance(photos);
}
}
/// <summary>
/// The price range of the business, for example <code>$$$</code>.
/// </summary>
private PriceRange_Core priceRange;
public PriceRange_Core PriceRange
{
get
{
return priceRange;
}
set
{
priceRange = value;
SetPropertyInstance(priceRange);
}
}
/// <summary>
/// Review of the item.
/// </summary>
private Reviews_Core reviews;
public Reviews_Core Reviews
{
get
{
return reviews;
}
set
{
reviews = value;
SetPropertyInstance(reviews);
}
}
/// <summary>
/// The telephone number.
/// </summary>
private Telephone_Core telephone;
public Telephone_Core Telephone
{
get
{
return telephone;
}
set
{
telephone = value;
SetPropertyInstance(telephone);
}
}
/// <summary>
/// URL of the item.
/// </summary>
private Properties.URL_Core uRL;
public Properties.URL_Core URL
{
get
{
return uRL;
}
set
{
uRL = value;
SetPropertyInstance(uRL);
}
}
}
}
| |
// 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;
using Microsoft.Win32.SafeHandles;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security.Principal;
using Xunit;
using System.Text;
namespace System.Diagnostics.Tests
{
public partial class ProcessStartInfoTests : ProcessTestBase
{
[Fact]
public void TestEnvironmentProperty()
{
Assert.NotEqual(0, new Process().StartInfo.Environment.Count);
ProcessStartInfo psi = new ProcessStartInfo();
// Creating a detached ProcessStartInfo will pre-populate the environment
// with current environmental variables.
IDictionary<string, string> environment = psi.Environment;
Assert.NotEqual(environment.Count, 0);
int CountItems = environment.Count;
environment.Add("NewKey", "NewValue");
environment.Add("NewKey2", "NewValue2");
Assert.Equal(CountItems + 2, environment.Count);
environment.Remove("NewKey");
Assert.Equal(CountItems + 1, environment.Count);
//Exception not thrown with invalid key
Assert.Throws<ArgumentException>(() => { environment.Add("NewKey2", "NewValue2"); });
//Clear
environment.Clear();
Assert.Equal(0, environment.Count);
//ContainsKey
environment.Add("NewKey", "NewValue");
environment.Add("NewKey2", "NewValue2");
Assert.True(environment.ContainsKey("NewKey"));
Assert.Equal(RuntimeInformation.IsOSPlatform(OSPlatform.Windows), environment.ContainsKey("newkey"));
Assert.False(environment.ContainsKey("NewKey99"));
//Iterating
string result = null;
int index = 0;
foreach (string e1 in environment.Values)
{
index++;
result += e1;
}
Assert.Equal(2, index);
Assert.Equal("NewValueNewValue2", result);
result = null;
index = 0;
foreach (string e1 in environment.Keys)
{
index++;
result += e1;
}
Assert.Equal("NewKeyNewKey2", result);
Assert.Equal(2, index);
result = null;
index = 0;
foreach (KeyValuePair<string, string> e1 in environment)
{
index++;
result += e1.Key;
}
Assert.Equal("NewKeyNewKey2", result);
Assert.Equal(2, index);
//Contains
Assert.True(environment.Contains(new KeyValuePair<string, string>("NewKey", "NewValue")));
Assert.Equal(RuntimeInformation.IsOSPlatform(OSPlatform.Windows), environment.Contains(new KeyValuePair<string, string>("nEwKeY", "NewValue")));
Assert.False(environment.Contains(new KeyValuePair<string, string>("NewKey99", "NewValue99")));
//Exception not thrown with invalid key
Assert.Throws<ArgumentNullException>(() => environment.Contains(new KeyValuePair<string, string>(null, "NewValue99")));
environment.Add(new KeyValuePair<string, string>("NewKey98", "NewValue98"));
//Indexed
string newIndexItem = environment["NewKey98"];
Assert.Equal("NewValue98", newIndexItem);
//TryGetValue
string stringout = null;
Assert.True(environment.TryGetValue("NewKey", out stringout));
Assert.Equal("NewValue", stringout);
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
Assert.True(environment.TryGetValue("NeWkEy", out stringout));
Assert.Equal("NewValue", stringout);
}
stringout = null;
Assert.False(environment.TryGetValue("NewKey99", out stringout));
Assert.Equal(null, stringout);
//Exception not thrown with invalid key
Assert.Throws<ArgumentNullException>(() =>
{
string stringout1 = null;
environment.TryGetValue(null, out stringout1);
});
//Exception not thrown with invalid key
Assert.Throws<ArgumentNullException>(() => environment.Add(null, "NewValue2"));
//Invalid Key to add
Assert.Throws<ArgumentException>(() => environment.Add("NewKey2", "NewValue2"));
//Remove Item
environment.Remove("NewKey98");
environment.Remove("NewKey98"); //2nd occurrence should not assert
//Exception not thrown with null key
Assert.Throws<ArgumentNullException>(() => { environment.Remove(null); });
//"Exception not thrown with null key"
Assert.Throws<KeyNotFoundException>(() => environment["1bB"]);
Assert.True(environment.Contains(new KeyValuePair<string, string>("NewKey2", "NewValue2")));
Assert.Equal(RuntimeInformation.IsOSPlatform(OSPlatform.Windows), environment.Contains(new KeyValuePair<string, string>("NEWKeY2", "NewValue2")));
Assert.False(environment.Contains(new KeyValuePair<string, string>("NewKey2", "newvalue2")));
Assert.False(environment.Contains(new KeyValuePair<string, string>("newkey2", "newvalue2")));
//Use KeyValuePair Enumerator
var x = environment.GetEnumerator();
x.MoveNext();
var y1 = x.Current;
Assert.Equal("NewKey NewValue", y1.Key + " " + y1.Value);
x.MoveNext();
y1 = x.Current;
Assert.Equal("NewKey2 NewValue2", y1.Key + " " + y1.Value);
//IsReadonly
Assert.False(environment.IsReadOnly);
environment.Add(new KeyValuePair<string, string>("NewKey3", "NewValue3"));
environment.Add(new KeyValuePair<string, string>("NewKey4", "NewValue4"));
//CopyTo
KeyValuePair<string, string>[] kvpa = new KeyValuePair<string, string>[10];
environment.CopyTo(kvpa, 0);
Assert.Equal("NewKey", kvpa[0].Key);
Assert.Equal("NewKey3", kvpa[2].Key);
environment.CopyTo(kvpa, 6);
Assert.Equal("NewKey", kvpa[6].Key);
//Exception not thrown with null key
Assert.Throws<ArgumentOutOfRangeException>(() => { environment.CopyTo(kvpa, -1); });
//Exception not thrown with null key
Assert.Throws<ArgumentException>(() => { environment.CopyTo(kvpa, 9); });
//Exception not thrown with null key
Assert.Throws<ArgumentNullException>(() =>
{
KeyValuePair<string, string>[] kvpanull = null;
environment.CopyTo(kvpanull, 0);
});
}
[Fact]
public void TestEnvironmentOfChildProcess()
{
const string ItemSeparator = "CAFF9451396B4EEF8A5155A15BDC2080"; // random string that shouldn't be in any env vars; used instead of newline to separate env var strings
const string ExtraEnvVar = "TestEnvironmentOfChildProcess_SpecialStuff";
Environment.SetEnvironmentVariable(ExtraEnvVar, "\x1234" + Environment.NewLine + "\x5678"); // ensure some Unicode characters and newlines are in the output
try
{
// Schedule a process to see what env vars it gets. Have it write out those variables
// to its output stream so we can read them.
Process p = CreateProcess(() =>
{
Console.Write(string.Join(ItemSeparator, Environment.GetEnvironmentVariables().Cast<DictionaryEntry>().Select(e => e.Key + "=" + e.Value)));
return SuccessExitCode;
});
p.StartInfo.StandardOutputEncoding = Encoding.UTF8;
p.StartInfo.RedirectStandardOutput = true;
p.Start();
string output = p.StandardOutput.ReadToEnd();
Assert.True(p.WaitForExit(WaitInMS));
// Parse the env vars from the child process
var actualEnv = new HashSet<string>(output.Split(new[] { ItemSeparator }, StringSplitOptions.None));
// Validate against StartInfo.Environment.
var startInfoEnv = new HashSet<string>(p.StartInfo.Environment.Select(e => e.Key + "=" + e.Value));
Assert.True(startInfoEnv.SetEquals(actualEnv),
string.Format("Expected: {0}{1}Actual: {2}",
string.Join(", ", startInfoEnv.Except(actualEnv)),
Environment.NewLine,
string.Join(", ", actualEnv.Except(startInfoEnv))));
// Validate against current process. (Profilers / code coverage tools can add own environment variables
// but we start child process without them. Thus the set of variables from the child process could
// be a subset of variables from current process.)
var envEnv = new HashSet<string>(Environment.GetEnvironmentVariables().Cast<DictionaryEntry>().Select(e => e.Key + "=" + e.Value));
Assert.True(envEnv.IsSupersetOf(actualEnv),
string.Format("Expected: {0}{1}Actual: {2}",
string.Join(", ", envEnv.Except(actualEnv)),
Environment.NewLine,
string.Join(", ", actualEnv.Except(envEnv))));
}
finally
{
Environment.SetEnvironmentVariable(ExtraEnvVar, null);
}
}
[PlatformSpecific(PlatformID.Windows)] // UseShellExecute currently not supported on Windows
[Fact]
public void TestUseShellExecuteProperty_SetAndGet_Windows()
{
ProcessStartInfo psi = new ProcessStartInfo();
Assert.False(psi.UseShellExecute);
// Calling the setter
Assert.Throws<PlatformNotSupportedException>(() => { psi.UseShellExecute = true; });
psi.UseShellExecute = false;
// Calling the getter
Assert.False(psi.UseShellExecute, "UseShellExecute=true is not supported on onecore.");
}
[PlatformSpecific(PlatformID.AnyUnix)]
[Fact]
public void TestUseShellExecuteProperty_SetAndGet_Unix()
{
ProcessStartInfo psi = new ProcessStartInfo();
Assert.False(psi.UseShellExecute);
psi.UseShellExecute = true;
Assert.True(psi.UseShellExecute);
psi.UseShellExecute = false;
Assert.False(psi.UseShellExecute);
}
[PlatformSpecific(PlatformID.AnyUnix)]
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(2)]
public void TestUseShellExecuteProperty_Redirects_NotSupported(int std)
{
Process p = CreateProcessLong();
p.StartInfo.UseShellExecute = true;
switch (std)
{
case 0: p.StartInfo.RedirectStandardInput = true; break;
case 1: p.StartInfo.RedirectStandardOutput = true; break;
case 2: p.StartInfo.RedirectStandardError = true; break;
}
Assert.Throws<InvalidOperationException>(() => p.Start());
}
[Fact]
public void TestArgumentsProperty()
{
ProcessStartInfo psi = new ProcessStartInfo();
Assert.Equal(string.Empty, psi.Arguments);
psi = new ProcessStartInfo("filename", "-arg1 -arg2");
Assert.Equal("-arg1 -arg2", psi.Arguments);
psi.Arguments = "-arg3 -arg4";
Assert.Equal("-arg3 -arg4", psi.Arguments);
}
[Theory, InlineData(true), InlineData(false)]
public void TestCreateNoWindowProperty(bool value)
{
Process testProcess = CreateProcessLong();
try
{
testProcess.StartInfo.CreateNoWindow = value;
testProcess.Start();
Assert.Equal(value, testProcess.StartInfo.CreateNoWindow);
}
finally
{
if (!testProcess.HasExited)
testProcess.Kill();
Assert.True(testProcess.WaitForExit(WaitInMS));
}
}
[Fact, PlatformSpecific(PlatformID.AnyUnix)]
public void TestUserCredentialsPropertiesOnUnix()
{
Assert.Throws<PlatformNotSupportedException>(() => _process.StartInfo.Domain);
Assert.Throws<PlatformNotSupportedException>(() => _process.StartInfo.UserName);
Assert.Throws<PlatformNotSupportedException>(() => _process.StartInfo.PasswordInClearText);
Assert.Throws<PlatformNotSupportedException>(() => _process.StartInfo.LoadUserProfile);
}
[Fact]
public void TestWorkingDirectoryProperty()
{
// check defaults
Assert.Equal(string.Empty, _process.StartInfo.WorkingDirectory);
Process p = CreateProcessLong();
p.StartInfo.WorkingDirectory = Directory.GetCurrentDirectory();
try
{
p.Start();
Assert.Equal(Directory.GetCurrentDirectory(), p.StartInfo.WorkingDirectory);
}
finally
{
if (!p.HasExited)
p.Kill();
Assert.True(p.WaitForExit(WaitInMS));
}
}
}
}
| |
// 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.Immutable;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using System.Reflection;
using System.Collections.Generic;
namespace Microsoft.CodeAnalysis.Scripting
{
/// <summary>
/// The result of running a script.
/// </summary>
public abstract class ScriptState
{
/// <summary>
/// The script that ran to produce this result.
/// </summary>
public Script Script { get; }
/// <summary>
/// Caught exception originating from the script top-level code.
/// </summary>
/// <remarks>
/// Exceptions are only caught and stored here if the API returning the <see cref="ScriptState"/> is instructed to do so.
/// By default they are propagated to the caller of the API.
/// </remarks>
public Exception Exception { get; }
internal ScriptExecutionState ExecutionState { get; }
private ImmutableArray<ScriptVariable> _lazyVariables;
private IReadOnlyDictionary<string, int> _lazyVariableMap;
internal ScriptState(ScriptExecutionState executionState, Script script, Exception exceptionOpt)
{
Debug.Assert(executionState != null);
Debug.Assert(script != null);
ExecutionState = executionState;
Script = script;
Exception = exceptionOpt;
}
/// <summary>
/// The final value produced by running the script.
/// </summary>
public object ReturnValue => GetReturnValue();
internal abstract object GetReturnValue();
/// <summary>
/// Returns variables defined by the scripts in the declaration order.
/// </summary>
public ImmutableArray<ScriptVariable> Variables
{
get
{
if (_lazyVariables == null)
{
ImmutableInterlocked.InterlockedInitialize(ref _lazyVariables, CreateVariables());
}
return _lazyVariables;
}
}
/// <summary>
/// Returns a script variable of the specified name.
/// </summary>
/// <remarks>
/// If multiple script variables are defined in the script (in distinct submissions) returns the last one.
/// Name lookup is case sensitive in C# scripts and case insensitive in VB scripts.
/// </remarks>
/// <returns><see cref="ScriptVariable"/> or null, if no variable of the specified <paramref name="name"/> is defined in the script.</returns>
/// <exception cref="ArgumentNullException"><paramref name="name"/> is null.</exception>
public ScriptVariable GetVariable(string name)
{
if (name == null)
{
throw new ArgumentNullException(nameof(name));
}
int index;
return GetVariableMap().TryGetValue(name, out index) ? Variables[index] : null;
}
private ImmutableArray<ScriptVariable> CreateVariables()
{
var result = ImmutableArray.CreateBuilder<ScriptVariable>();
var executionState = ExecutionState;
// Don't include the globals object (slot #0)
for (int i = 1; i < executionState.SubmissionStateCount; i++)
{
var state = executionState.GetSubmissionState(i);
Debug.Assert(state != null);
foreach (var field in state.GetType().GetTypeInfo().DeclaredFields)
{
// TODO: synthesized fields of submissions shouldn't be public
if (field.IsPublic && field.Name.Length > 0 && (char.IsLetterOrDigit(field.Name[0]) || field.Name[0] == '_'))
{
result.Add(new ScriptVariable(state, field));
}
}
}
return result.ToImmutable();
}
private IReadOnlyDictionary<string, int> GetVariableMap()
{
if (_lazyVariableMap == null)
{
var map = new Dictionary<string, int>(Script.Compiler.IdentifierComparer);
for (int i = 0; i < Variables.Length; i++)
{
map[Variables[i].Name] = i;
}
_lazyVariableMap = map;
}
return _lazyVariableMap;
}
/// <summary>
/// Continues script execution from the state represented by this instance by running the specified code snippet.
/// </summary>
/// <param name="code">The code to be executed.</param>
/// <param name="options">Options.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>A <see cref="ScriptState"/> that represents the state after running <paramref name="code"/>, including all declared variables and return value.</returns>
public Task<ScriptState<object>> ContinueWithAsync(string code, ScriptOptions options, CancellationToken cancellationToken)
=> ContinueWithAsync<object>(code, options, null, cancellationToken);
/// <summary>
/// Continues script execution from the state represented by this instance by running the specified code snippet.
/// </summary>
/// <param name="code">The code to be executed.</param>
/// <param name="options">Options.</param>
/// <param name="catchException">
/// If specified, any exception thrown by the script top-level code is passed to <paramref name="catchException"/>.
/// If it returns true the exception is caught and stored on the resulting <see cref="ScriptState"/>, otherwise the exception is propagated to the caller.
/// </param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>A <see cref="ScriptState"/> that represents the state after running <paramref name="code"/>, including all declared variables, return value and caught exception (if applicable).</returns>
public Task<ScriptState<object>> ContinueWithAsync(string code, ScriptOptions options = null, Func<Exception, bool> catchException = null, CancellationToken cancellationToken = default(CancellationToken))
=> Script.ContinueWith<object>(code, options).RunFromAsync(this, catchException, cancellationToken);
/// <summary>
/// Continues script execution from the state represented by this instance by running the specified code snippet.
/// </summary>
/// <param name="code">The code to be executed.</param>
/// <param name="options">Options.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>A <see cref="ScriptState"/> that represents the state after running <paramref name="code"/>, including all declared variables and return value.</returns>
public Task<ScriptState<TResult>> ContinueWithAsync<TResult>(string code, ScriptOptions options, CancellationToken cancellationToken)
=> ContinueWithAsync<TResult>(code, options, null, cancellationToken);
/// <summary>
/// Continues script execution from the state represented by this instance by running the specified code snippet.
/// </summary>
/// <param name="code">The code to be executed.</param>
/// <param name="options">Options.</param>
/// <param name="catchException">
/// If specified, any exception thrown by the script top-level code is passed to <paramref name="catchException"/>.
/// If it returns true the exception is caught and stored on the resulting <see cref="ScriptState"/>, otherwise the exception is propagated to the caller.
/// </param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>A <see cref="ScriptState"/> that represents the state after running <paramref name="code"/>, including all declared variables, return value and caught exception (if applicable).</returns>
public Task<ScriptState<TResult>> ContinueWithAsync<TResult>(string code, ScriptOptions options = null, Func<Exception, bool> catchException = null, CancellationToken cancellationToken = default(CancellationToken))
=> Script.ContinueWith<TResult>(code, options).RunFromAsync(this, catchException, cancellationToken);
// How do we resolve overloads? We should use the language semantics.
// https://github.com/dotnet/roslyn/issues/3720
#if TODO
/// <summary>
/// Invoke a method declared by the script.
/// </summary>
public object Invoke(string name, params object[] args)
{
var func = this.FindMethod(name, args != null ? args.Length : 0);
if (func != null)
{
return func(args);
}
return null;
}
private Func<object[], object> FindMethod(string name, int argCount)
{
for (int i = _executionState.Count - 1; i >= 0; i--)
{
var sub = _executionState[i];
if (sub != null)
{
var type = sub.GetType();
var method = FindMethod(type, name, argCount);
if (method != null)
{
return (args) => method.Invoke(sub, args);
}
}
}
return null;
}
private MethodInfo FindMethod(Type type, string name, int argCount)
{
return type.GetMethod(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
}
/// <summary>
/// Create a delegate to a method declared by the script.
/// </summary>
public TDelegate CreateDelegate<TDelegate>(string name)
{
var delegateInvokeMethod = typeof(TDelegate).GetMethod("Invoke", BindingFlags.Instance | BindingFlags.Public);
for (int i = _executionState.Count - 1; i >= 0; i--)
{
var sub = _executionState[i];
if (sub != null)
{
var type = sub.GetType();
var method = FindMatchingMethod(type, name, delegateInvokeMethod);
if (method != null)
{
return (TDelegate)(object)method.CreateDelegate(typeof(TDelegate), sub);
}
}
}
return default(TDelegate);
}
private MethodInfo FindMatchingMethod(Type instanceType, string name, MethodInfo delegateInvokeMethod)
{
var dprms = delegateInvokeMethod.GetParameters();
foreach (var mi in instanceType.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic))
{
if (mi.Name == name)
{
var prms = mi.GetParameters();
if (prms.Length == dprms.Length)
{
// TODO: better matching..
return mi;
}
}
}
return null;
}
#endif
}
public sealed class ScriptState<T> : ScriptState
{
public new T ReturnValue { get; }
internal override object GetReturnValue() => ReturnValue;
internal ScriptState(ScriptExecutionState executionState, Script script, T value, Exception exceptionOpt)
: base(executionState, script, exceptionOpt)
{
ReturnValue = value;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using LibGit2Sharp.Core;
using LibGit2Sharp.Tests.TestHelpers;
using Xunit;
using Xunit.Extensions;
namespace LibGit2Sharp.Tests
{
public class CommitFixture : BaseFixture
{
private const string sha = "8496071c1b46c854b31185ea97743be6a8774479";
private readonly List<string> expectedShas = new List<string> { "a4a7d", "c4780", "9fd73", "4a202", "5b5b0", "84960" };
[Fact]
public void CanCountCommits()
{
string path = SandboxBareTestRepo();
using (var repo = new Repository(path))
{
Assert.Equal(7, repo.Commits.Count());
}
}
[Fact]
public void CanCorrectlyCountCommitsWhenSwitchingToAnotherBranch()
{
string path = SandboxStandardTestRepo();
using (var repo = new Repository(path))
{
// Hard reset and then remove untracked files
repo.Reset(ResetMode.Hard);
repo.RemoveUntrackedFiles();
repo.Checkout("test");
Assert.Equal(2, repo.Commits.Count());
Assert.Equal("e90810b8df3e80c413d903f631643c716887138d", repo.Commits.First().Id.Sha);
repo.Checkout("master");
Assert.Equal(9, repo.Commits.Count());
Assert.Equal("32eab9cb1f450b5fe7ab663462b77d7f4b703344", repo.Commits.First().Id.Sha);
}
}
[Fact]
public void CanEnumerateCommits()
{
int count = 0;
string path = SandboxBareTestRepo();
using (var repo = new Repository(path))
{
foreach (Commit commit in repo.Commits)
{
Assert.NotNull(commit);
count++;
}
}
Assert.Equal(7, count);
}
[Fact]
public void CanEnumerateCommitsInDetachedHeadState()
{
string path = SandboxBareTestRepo();
using (var repo = new Repository(path))
{
ObjectId parentOfHead = repo.Head.Tip.Parents.First().Id;
repo.Refs.Add("HEAD", parentOfHead.Sha, true);
Assert.Equal(true, repo.Info.IsHeadDetached);
Assert.Equal(6, repo.Commits.Count());
}
}
[Fact]
public void DefaultOrderingWhenEnumeratingCommitsIsTimeBased()
{
string path = SandboxBareTestRepo();
using (var repo = new Repository(path))
{
Assert.Equal(CommitSortStrategies.Time, repo.Commits.SortedBy);
}
}
[Fact]
public void CanEnumerateCommitsFromSha()
{
int count = 0;
string path = SandboxBareTestRepo();
using (var repo = new Repository(path))
{
foreach (Commit commit in repo.Commits.QueryBy(new CommitFilter { Since = "a4a7dce85cf63874e984719f4fdd239f5145052f" }))
{
Assert.NotNull(commit);
count++;
}
}
Assert.Equal(6, count);
}
[Fact]
public void QueryingTheCommitHistoryWithUnknownShaOrInvalidEntryPointThrows()
{
string path = SandboxBareTestRepo();
using (var repo = new Repository(path))
{
Assert.Throws<LibGit2SharpException>(() => repo.Commits.QueryBy(new CommitFilter { Since = Constants.UnknownSha }).Count());
Assert.Throws<LibGit2SharpException>(() => repo.Commits.QueryBy(new CommitFilter { Since = "refs/heads/deadbeef" }).Count());
Assert.Throws<ArgumentNullException>(() => repo.Commits.QueryBy(new CommitFilter { Since = null }).Count());
}
}
[Fact]
public void QueryingTheCommitHistoryFromACorruptedReferenceThrows()
{
string path = SandboxBareTestRepo();
using (var repo = new Repository(path))
{
CreateCorruptedDeadBeefHead(repo.Info.Path);
Assert.Throws<LibGit2SharpException>(() => repo.Commits.QueryBy(new CommitFilter { Since = repo.Branches["deadbeef"] }).Count());
Assert.Throws<LibGit2SharpException>(() => repo.Commits.QueryBy(new CommitFilter { Since = repo.Refs["refs/heads/deadbeef"] }).Count());
}
}
[Fact]
public void QueryingTheCommitHistoryWithBadParamsThrows()
{
string path = SandboxBareTestRepo();
using (var repo = new Repository(path))
{
Assert.Throws<ArgumentException>(() => repo.Commits.QueryBy(new CommitFilter { Since = string.Empty }));
Assert.Throws<ArgumentNullException>(() => repo.Commits.QueryBy(new CommitFilter { Since = null }));
Assert.Throws<ArgumentNullException>(() => repo.Commits.QueryBy(default(CommitFilter)));
}
}
[Fact]
public void CanEnumerateCommitsWithReverseTimeSorting()
{
var reversedShas = new List<string>(expectedShas);
reversedShas.Reverse();
int count = 0;
string path = SandboxBareTestRepo();
using (var repo = new Repository(path))
{
foreach (Commit commit in repo.Commits.QueryBy(new CommitFilter
{
Since = "a4a7dce85cf63874e984719f4fdd239f5145052f",
SortBy = CommitSortStrategies.Time | CommitSortStrategies.Reverse
}))
{
Assert.NotNull(commit);
Assert.True(commit.Sha.StartsWith(reversedShas[count]));
count++;
}
}
Assert.Equal(6, count);
}
[Fact]
public void CanEnumerateCommitsWithReverseTopoSorting()
{
string path = SandboxBareTestRepo();
using (var repo = new Repository(path))
{
List<Commit> commits = repo.Commits.QueryBy(new CommitFilter
{
Since = "a4a7dce85cf63874e984719f4fdd239f5145052f",
SortBy = CommitSortStrategies.Time | CommitSortStrategies.Reverse
}).ToList();
foreach (Commit commit in commits)
{
Assert.NotNull(commit);
foreach (Commit p in commit.Parents)
{
Commit parent = commits.Single(x => x.Id == p.Id);
Assert.True(commits.IndexOf(commit) > commits.IndexOf(parent));
}
}
}
}
[Fact]
public void CanSimplifyByFirstParent()
{
AssertEnumerationOfCommits(
repo => new CommitFilter { Since = repo.Head, FirstParentOnly = true },
new[]
{
"4c062a6", "be3563a", "9fd738e",
"4a202b3", "5b5b025", "8496071",
});
}
[Fact]
public void CanGetParentsCount()
{
string path = SandboxBareTestRepo();
using (var repo = new Repository(path))
{
Assert.Equal(1, repo.Commits.First().Parents.Count());
}
}
[Fact]
public void CanEnumerateCommitsWithTimeSorting()
{
int count = 0;
string path = SandboxBareTestRepo();
using (var repo = new Repository(path))
{
foreach (Commit commit in repo.Commits.QueryBy(new CommitFilter
{
Since = "a4a7dce85cf63874e984719f4fdd239f5145052f",
SortBy = CommitSortStrategies.Time
}))
{
Assert.NotNull(commit);
Assert.True(commit.Sha.StartsWith(expectedShas[count]));
count++;
}
}
Assert.Equal(6, count);
}
[Fact]
public void CanEnumerateCommitsWithTopoSorting()
{
string path = SandboxBareTestRepo();
using (var repo = new Repository(path))
{
List<Commit> commits = repo.Commits.QueryBy(new CommitFilter
{
Since = "a4a7dce85cf63874e984719f4fdd239f5145052f",
SortBy = CommitSortStrategies.Topological
}).ToList();
foreach (Commit commit in commits)
{
Assert.NotNull(commit);
foreach (Commit p in commit.Parents)
{
Commit parent = commits.Single(x => x.Id == p.Id);
Assert.True(commits.IndexOf(commit) < commits.IndexOf(parent));
}
}
}
}
[Fact]
public void CanEnumerateFromHead()
{
AssertEnumerationOfCommits(
repo => new CommitFilter { Since = repo.Head },
new[]
{
"4c062a6", "be3563a", "c47800c", "9fd738e",
"4a202b3", "5b5b025", "8496071",
});
}
[Fact]
public void CanEnumerateFromDetachedHead()
{
string path = SandboxStandardTestRepo();
using (var repoClone = new Repository(path))
{
// Hard reset and then remove untracked files
repoClone.Reset(ResetMode.Hard);
repoClone.RemoveUntrackedFiles();
string headSha = repoClone.Head.Tip.Sha;
repoClone.Checkout(headSha);
AssertEnumerationOfCommitsInRepo(repoClone,
repo => new CommitFilter { Since = repo.Head },
new[]
{
"32eab9c", "592d3c8", "4c062a6",
"be3563a", "c47800c", "9fd738e",
"4a202b3", "5b5b025", "8496071",
});
}
}
[Fact]
public void CanEnumerateUsingTwoHeadsAsBoundaries()
{
AssertEnumerationOfCommits(
repo => new CommitFilter { Since = "HEAD", Until = "refs/heads/br2" },
new[] { "4c062a6", "be3563a" }
);
}
[Fact]
public void CanEnumerateUsingImplicitHeadAsSinceBoundary()
{
AssertEnumerationOfCommits(
repo => new CommitFilter { Until = "refs/heads/br2" },
new[] { "4c062a6", "be3563a" }
);
}
[Fact]
public void CanEnumerateUsingTwoAbbreviatedShasAsBoundaries()
{
AssertEnumerationOfCommits(
repo => new CommitFilter { Since = "a4a7dce", Until = "4a202b3" },
new[] { "a4a7dce", "c47800c", "9fd738e" }
);
}
[Fact]
public void CanEnumerateCommitsFromTwoHeads()
{
AssertEnumerationOfCommits(
repo => new CommitFilter { Since = new[] { "refs/heads/br2", "refs/heads/master" } },
new[]
{
"4c062a6", "a4a7dce", "be3563a", "c47800c",
"9fd738e", "4a202b3", "5b5b025", "8496071",
});
}
[Fact]
public void CanEnumerateCommitsFromMixedStartingPoints()
{
AssertEnumerationOfCommits(
repo => new CommitFilter { Since = new object[] { repo.Branches["br2"],
"refs/heads/master",
new ObjectId("e90810b8df3e80c413d903f631643c716887138d") } },
new[]
{
"4c062a6", "e90810b", "6dcf9bf", "a4a7dce",
"be3563a", "c47800c", "9fd738e", "4a202b3",
"5b5b025", "8496071",
});
}
[Fact]
public void CanEnumerateCommitsUsingGlob()
{
AssertEnumerationOfCommits(
repo => new CommitFilter { Since = repo.Refs.FromGlob("refs/heads/*") },
new[]
{
"4c062a6", "e90810b", "6dcf9bf", "a4a7dce", "be3563a", "c47800c", "9fd738e", "4a202b3", "41bc8c6", "5001298", "5b5b025", "8496071"
});
}
[Fact]
public void CanHideCommitsUsingGlob()
{
AssertEnumerationOfCommits(
repo => new CommitFilter { Since = "refs/heads/packed-test", Until = repo.Refs.FromGlob("*/packed") },
new[]
{
"4a202b3", "5b5b025", "8496071"
});
}
[Fact]
public void CanEnumerateCommitsFromAnAnnotatedTag()
{
CanEnumerateCommitsFromATag(t => t);
}
[Fact]
public void CanEnumerateCommitsFromATagAnnotation()
{
CanEnumerateCommitsFromATag(t => t.Annotation);
}
private void CanEnumerateCommitsFromATag(Func<Tag, object> transformer)
{
AssertEnumerationOfCommits(
repo => new CommitFilter { Since = transformer(repo.Tags["test"]) },
new[] { "e90810b", "6dcf9bf", }
);
}
[Fact]
public void CanEnumerateAllCommits()
{
AssertEnumerationOfCommits(
repo => new CommitFilter
{
Since = repo.Refs.OrderBy(r => r.CanonicalName, StringComparer.Ordinal),
},
new[]
{
"44d5d18", "bb65291", "532740a", "503a16f", "3dfd6fd",
"4409de1", "902c60b", "4c062a6", "e90810b", "6dcf9bf",
"a4a7dce", "be3563a", "c47800c", "9fd738e", "4a202b3",
"41bc8c6", "5001298", "5b5b025", "8496071",
});
}
[Fact]
public void CanEnumerateCommitsFromATagWhichPointsToABlob()
{
AssertEnumerationOfCommits(
repo => new CommitFilter { Since = repo.Tags["point_to_blob"] },
new string[] { });
}
[Fact]
public void CanEnumerateCommitsFromATagWhichPointsToATree()
{
string path = SandboxBareTestRepo();
using (var repo = new Repository(path))
{
string headTreeSha = repo.Head.Tip.Tree.Sha;
Tag tag = repo.ApplyTag("point_to_tree", headTreeSha);
AssertEnumerationOfCommitsInRepo(repo,
r => new CommitFilter { Since = tag },
new string[] { });
}
}
private void AssertEnumerationOfCommits(Func<IRepository, CommitFilter> filterBuilder, IEnumerable<string> abbrevIds)
{
string path = SandboxBareTestRepo();
using (var repo = new Repository(path))
{
AssertEnumerationOfCommitsInRepo(repo, filterBuilder, abbrevIds);
}
}
private static void AssertEnumerationOfCommitsInRepo(IRepository repo, Func<IRepository, CommitFilter> filterBuilder, IEnumerable<string> abbrevIds)
{
ICommitLog commits = repo.Commits.QueryBy(filterBuilder(repo));
IEnumerable<string> commitShas = commits.Select(c => c.Id.ToString(7)).ToArray();
Assert.Equal(abbrevIds, commitShas);
}
[Fact]
public void CanLookupCommitGeneric()
{
string path = SandboxBareTestRepo();
using (var repo = new Repository(path))
{
var commit = repo.Lookup<Commit>(sha);
Assert.Equal("testing\n", commit.Message);
Assert.Equal("testing", commit.MessageShort);
Assert.Equal(sha, commit.Sha);
}
}
[Fact]
public void CanReadCommitData()
{
string path = SandboxBareTestRepo();
using (var repo = new Repository(path))
{
GitObject obj = repo.Lookup(sha);
Assert.NotNull(obj);
Assert.Equal(typeof(Commit), obj.GetType());
var commit = (Commit)obj;
Assert.Equal("testing\n", commit.Message);
Assert.Equal("testing", commit.MessageShort);
Assert.Equal("UTF-8", commit.Encoding);
Assert.Equal(sha, commit.Sha);
Assert.NotNull(commit.Author);
Assert.Equal("Scott Chacon", commit.Author.Name);
Assert.Equal("schacon@gmail.com", commit.Author.Email);
Assert.Equal(1273360386, commit.Author.When.ToSecondsSinceEpoch());
Assert.NotNull(commit.Committer);
Assert.Equal("Scott Chacon", commit.Committer.Name);
Assert.Equal("schacon@gmail.com", commit.Committer.Email);
Assert.Equal(1273360386, commit.Committer.When.ToSecondsSinceEpoch());
Assert.Equal("181037049a54a1eb5fab404658a3a250b44335d7", commit.Tree.Sha);
Assert.Equal(0, commit.Parents.Count());
}
}
[Fact]
public void CanReadCommitWithMultipleParents()
{
string path = SandboxBareTestRepo();
using (var repo = new Repository(path))
{
var commit = repo.Lookup<Commit>("a4a7dce85cf63874e984719f4fdd239f5145052f");
Assert.Equal(2, commit.Parents.Count());
}
}
[Fact]
public void CanDirectlyAccessABlobOfTheCommit()
{
string path = SandboxBareTestRepo();
using (var repo = new Repository(path))
{
var commit = repo.Lookup<Commit>("4c062a6");
var blob = commit["1/branch_file.txt"].Target as Blob;
Assert.NotNull(blob);
Assert.Equal("hi\n", blob.GetContentText());
}
}
[Fact]
public void CanDirectlyAccessATreeOfTheCommit()
{
string path = SandboxBareTestRepo();
using (var repo = new Repository(path))
{
var commit = repo.Lookup<Commit>("4c062a6");
var tree1 = commit["1"].Target as Tree;
Assert.NotNull(tree1);
}
}
[Fact]
public void DirectlyAccessingAnUnknownTreeEntryOfTheCommitReturnsNull()
{
string path = SandboxBareTestRepo();
using (var repo = new Repository(path))
{
var commit = repo.Lookup<Commit>("4c062a6");
Assert.Null(commit["I-am-not-here"]);
}
}
[Theory]
[InlineData(null, "x@example.com")]
[InlineData("", "x@example.com")]
[InlineData("X", null)]
[InlineData("X", "")]
public void CommitWithInvalidSignatureConfigThrows(string name, string email)
{
string repoPath = InitNewRepository();
string configPath = CreateConfigurationWithDummyUser(name, email);
var options = new RepositoryOptions { GlobalConfigurationLocation = configPath };
using (var repo = new Repository(repoPath, options))
{
Assert.Equal(name, repo.Config.GetValueOrDefault<string>("user.name"));
Assert.Equal(email, repo.Config.GetValueOrDefault<string>("user.email"));
Assert.Throws<LibGit2SharpException>(
() => repo.Commit("Initial egotistic commit", new CommitOptions { AllowEmptyCommit = true }));
}
}
[Fact]
public void CanCommitWithSignatureFromConfig()
{
string repoPath = InitNewRepository();
string configPath = CreateConfigurationWithDummyUser(Constants.Signature);
var options = new RepositoryOptions { GlobalConfigurationLocation = configPath };
using (var repo = new Repository(repoPath, options))
{
string dir = repo.Info.Path;
Assert.True(Path.IsPathRooted(dir));
Assert.True(Directory.Exists(dir));
const string relativeFilepath = "new.txt";
string filePath = Touch(repo.Info.WorkingDirectory, relativeFilepath, "null");
repo.Stage(relativeFilepath);
File.AppendAllText(filePath, "token\n");
repo.Stage(relativeFilepath);
Assert.Null(repo.Head[relativeFilepath]);
Commit commit = repo.Commit("Initial egotistic commit");
AssertBlobContent(repo.Head[relativeFilepath], "nulltoken\n");
AssertBlobContent(commit[relativeFilepath], "nulltoken\n");
AssertCommitSignaturesAre(commit, Constants.Signature);
}
}
[Fact]
public void CommitParentsAreMergeHeads()
{
string path = SandboxStandardTestRepo();
using (var repo = new Repository(path))
{
repo.Reset(ResetMode.Hard, "c47800");
CreateAndStageANewFile(repo);
Touch(repo.Info.Path, "MERGE_HEAD", "9fd738e8f7967c078dceed8190330fc8648ee56a\n");
Assert.Equal(CurrentOperation.Merge, repo.Info.CurrentOperation);
Commit newMergedCommit = repo.Commit("Merge commit", Constants.Signature, Constants.Signature);
Assert.Equal(CurrentOperation.None, repo.Info.CurrentOperation);
Assert.Equal(2, newMergedCommit.Parents.Count());
Assert.Equal(newMergedCommit.Parents.First().Sha, "c47800c7266a2be04c571c04d5a6614691ea99bd");
Assert.Equal(newMergedCommit.Parents.Skip(1).First().Sha, "9fd738e8f7967c078dceed8190330fc8648ee56a");
// Assert reflog entry is created
var reflogEntry = repo.Refs.Log(repo.Refs.Head).First();
Assert.Equal(repo.Head.Tip.Id, reflogEntry.To);
Assert.NotNull(reflogEntry.Commiter.Email);
Assert.NotNull(reflogEntry.Commiter.Name);
Assert.Equal(string.Format("commit (merge): {0}", newMergedCommit.MessageShort), reflogEntry.Message);
}
}
[Fact]
public void CommitCleansUpMergeMetadata()
{
string repoPath = InitNewRepository();
using (var repo = new Repository(repoPath))
{
string dir = repo.Info.Path;
Assert.True(Path.IsPathRooted(dir));
Assert.True(Directory.Exists(dir));
const string relativeFilepath = "new.txt";
Touch(repo.Info.WorkingDirectory, relativeFilepath, "this is a new file");
repo.Stage(relativeFilepath);
string mergeHeadPath = Touch(repo.Info.Path, "MERGE_HEAD", "abcdefabcdefabcdefabcdefabcdefabcdefabcd");
string mergeMsgPath = Touch(repo.Info.Path, "MERGE_MSG", "This is a dummy merge.\n");
string mergeModePath = Touch(repo.Info.Path, "MERGE_MODE", "no-ff");
string origHeadPath = Touch(repo.Info.Path, "ORIG_HEAD", "beefbeefbeefbeefbeefbeefbeefbeefbeefbeef");
Assert.True(File.Exists(mergeHeadPath));
Assert.True(File.Exists(mergeMsgPath));
Assert.True(File.Exists(mergeModePath));
Assert.True(File.Exists(origHeadPath));
var author = Constants.Signature;
repo.Commit("Initial egotistic commit", author, author);
Assert.False(File.Exists(mergeHeadPath));
Assert.False(File.Exists(mergeMsgPath));
Assert.False(File.Exists(mergeModePath));
Assert.True(File.Exists(origHeadPath));
}
}
[Fact]
public void CanCommitALittleBit()
{
string repoPath = InitNewRepository();
using (var repo = new Repository(repoPath))
{
string dir = repo.Info.Path;
Assert.True(Path.IsPathRooted(dir));
Assert.True(Directory.Exists(dir));
const string relativeFilepath = "new.txt";
string filePath = Touch(repo.Info.WorkingDirectory, relativeFilepath, "null");
repo.Stage(relativeFilepath);
File.AppendAllText(filePath, "token\n");
repo.Stage(relativeFilepath);
Assert.Null(repo.Head[relativeFilepath]);
var author = Constants.Signature;
const string shortMessage = "Initial egotistic commit";
const string commitMessage = shortMessage + "\n\nOnly the coolest commits from us";
Commit commit = repo.Commit(commitMessage, author, author);
AssertBlobContent(repo.Head[relativeFilepath], "nulltoken\n");
AssertBlobContent(commit[relativeFilepath], "nulltoken\n");
Assert.Equal(0, commit.Parents.Count());
Assert.False(repo.Info.IsHeadUnborn);
// Assert a reflog entry is created on HEAD
Assert.Equal(1, repo.Refs.Log("HEAD").Count());
var reflogEntry = repo.Refs.Log("HEAD").First();
Assert.Equal(author, reflogEntry.Commiter);
Assert.Equal(commit.Id, reflogEntry.To);
Assert.Equal(ObjectId.Zero, reflogEntry.From);
Assert.Equal(string.Format("commit (initial): {0}", shortMessage), reflogEntry.Message);
// Assert a reflog entry is created on HEAD target
var targetCanonicalName = repo.Refs.Head.TargetIdentifier;
Assert.Equal(1, repo.Refs.Log(targetCanonicalName).Count());
Assert.Equal(commit.Id, repo.Refs.Log(targetCanonicalName).First().To);
File.WriteAllText(filePath, "nulltoken commits!\n");
repo.Stage(relativeFilepath);
var author2 = new Signature(author.Name, author.Email, author.When.AddSeconds(5));
Commit commit2 = repo.Commit("Are you trying to fork me?", author2, author2);
AssertBlobContent(repo.Head[relativeFilepath], "nulltoken commits!\n");
AssertBlobContent(commit2[relativeFilepath], "nulltoken commits!\n");
Assert.Equal(1, commit2.Parents.Count());
Assert.Equal(commit.Id, commit2.Parents.First().Id);
// Assert the reflog is shifted
Assert.Equal(2, repo.Refs.Log("HEAD").Count());
Assert.Equal(reflogEntry.To, repo.Refs.Log("HEAD").First().From);
Branch firstCommitBranch = repo.CreateBranch("davidfowl-rules", commit);
repo.Checkout(firstCommitBranch);
File.WriteAllText(filePath, "davidfowl commits!\n");
var author3 = new Signature("David Fowler", "david.fowler@microsoft.com", author.When.AddSeconds(2));
repo.Stage(relativeFilepath);
Commit commit3 = repo.Commit("I'm going to branch you backwards in time!", author3, author3);
AssertBlobContent(repo.Head[relativeFilepath], "davidfowl commits!\n");
AssertBlobContent(commit3[relativeFilepath], "davidfowl commits!\n");
Assert.Equal(1, commit3.Parents.Count());
Assert.Equal(commit.Id, commit3.Parents.First().Id);
AssertBlobContent(firstCommitBranch[relativeFilepath], "nulltoken\n");
}
}
private static void AssertBlobContent(TreeEntry entry, string expectedContent)
{
Assert.Equal(TreeEntryTargetType.Blob, entry.TargetType);
Assert.Equal(expectedContent, ((Blob)(entry.Target)).GetContentText());
}
private static void AddCommitToRepo(string path)
{
using (var repo = new Repository(path))
{
const string relativeFilepath = "test.txt";
Touch(repo.Info.WorkingDirectory, relativeFilepath, "test\n");
repo.Stage(relativeFilepath);
var author = new Signature("nulltoken", "emeric.fermas@gmail.com", DateTimeOffset.Parse("Wed, Dec 14 2011 08:29:03 +0100"));
repo.Commit("Initial commit", author, author);
}
}
[Fact]
public void CanGeneratePredictableObjectShas()
{
string repoPath = InitNewRepository();
AddCommitToRepo(repoPath);
using (var repo = new Repository(repoPath))
{
Commit commit = repo.Commits.Single();
Assert.Equal("1fe3126578fc4eca68c193e4a3a0a14a0704624d", commit.Sha);
Tree tree = commit.Tree;
Assert.Equal("2b297e643c551e76cfa1f93810c50811382f9117", tree.Sha);
GitObject blob = tree.Single().Target;
Assert.IsAssignableFrom<Blob>(blob);
Assert.Equal("9daeafb9864cf43055ae93beb0afd6c7d144bfa4", blob.Sha);
}
}
[Fact]
public void CanAmendARootCommit()
{
string repoPath = InitNewRepository();
AddCommitToRepo(repoPath);
using (var repo = new Repository(repoPath))
{
Assert.Equal(1, repo.Head.Commits.Count());
Commit originalCommit = repo.Head.Tip;
Assert.Equal(0, originalCommit.Parents.Count());
CreateAndStageANewFile(repo);
Commit amendedCommit = repo.Commit("I'm rewriting the history!", Constants.Signature, Constants.Signature,
new CommitOptions { AmendPreviousCommit = true });
Assert.Equal(1, repo.Head.Commits.Count());
AssertCommitHasBeenAmended(repo, amendedCommit, originalCommit);
}
}
[Fact]
public void CanAmendACommitWithMoreThanOneParent()
{
string path = SandboxStandardTestRepo();
using (var repo = new Repository(path))
{
var mergedCommit = repo.Lookup<Commit>("be3563a");
Assert.NotNull(mergedCommit);
Assert.Equal(2, mergedCommit.Parents.Count());
repo.Reset(ResetMode.Soft, mergedCommit.Sha);
CreateAndStageANewFile(repo);
const string commitMessage = "I'm rewriting the history!";
Commit amendedCommit = repo.Commit(commitMessage, Constants.Signature, Constants.Signature,
new CommitOptions { AmendPreviousCommit = true });
AssertCommitHasBeenAmended(repo, amendedCommit, mergedCommit);
AssertRefLogEntry(repo, "HEAD",
amendedCommit.Id,
string.Format("commit (amend): {0}", commitMessage),
mergedCommit.Id,
amendedCommit.Committer);
}
}
private static void CreateAndStageANewFile(IRepository repo)
{
string relativeFilepath = string.Format("new-file-{0}.txt", Path.GetRandomFileName());
Touch(repo.Info.WorkingDirectory, relativeFilepath, "brand new content\n");
repo.Stage(relativeFilepath);
}
private static void AssertCommitHasBeenAmended(IRepository repo, Commit amendedCommit, Commit originalCommit)
{
Commit headCommit = repo.Head.Tip;
Assert.Equal(amendedCommit, headCommit);
Assert.NotEqual(originalCommit.Sha, amendedCommit.Sha);
Assert.Equal(originalCommit.Parents, amendedCommit.Parents);
}
[Fact]
public void CanNotAmendAnEmptyRepository()
{
string repoPath = InitNewRepository();
using (var repo = new Repository(repoPath))
{
Assert.Throws<UnbornBranchException>(() =>
repo.Commit("I can not amend anything !:(", Constants.Signature, Constants.Signature, new CommitOptions { AmendPreviousCommit = true }));
}
}
[Fact]
public void CanRetrieveChildrenOfASpecificCommit()
{
string path = SandboxStandardTestRepo();
using (var repo = new Repository(path))
{
const string parentSha = "5b5b025afb0b4c913b4c338a42934a3863bf3644";
var filter = new CommitFilter
{
/* Revwalk from all the refs (git log --all) ... */
Since = repo.Refs,
/* ... and stop when the parent is reached */
Until = parentSha
};
var commits = repo.Commits.QueryBy(filter);
var children = from c in commits
from p in c.Parents
let pId = p.Id
where pId.Sha == parentSha
select c;
var expectedChildren = new[] { "c47800c7266a2be04c571c04d5a6614691ea99bd",
"4a202b346bb0fb0db7eff3cffeb3c70babbd2045" };
Assert.Equal(expectedChildren, children.Select(c => c.Id.Sha));
}
}
[Fact]
public void CanCorrectlyDistinguishAuthorFromCommitter()
{
string path = SandboxStandardTestRepo();
using (var repo = new Repository(path))
{
var author = new Signature("Wilbert van Dolleweerd", "getit@xs4all.nl",
Epoch.ToDateTimeOffset(1244187936, 120));
var committer = new Signature("Henk Westhuis", "Henk_Westhuis@hotmail.com",
Epoch.ToDateTimeOffset(1244286496, 120));
Commit c = repo.Commit("I can haz an author and a committer!", author, committer);
Assert.Equal(author, c.Author);
Assert.Equal(committer, c.Committer);
}
}
[Fact]
public void CanCommitOnOrphanedBranch()
{
string newBranchName = "refs/heads/newBranch";
string repoPath = InitNewRepository();
using (var repo = new Repository(repoPath))
{
// Set Head to point to branch other than master
repo.Refs.UpdateTarget("HEAD", newBranchName);
Assert.Equal(newBranchName, repo.Head.CanonicalName);
const string relativeFilepath = "test.txt";
Touch(repo.Info.WorkingDirectory, relativeFilepath, "test\n");
repo.Stage(relativeFilepath);
repo.Commit("Initial commit", Constants.Signature, Constants.Signature);
Assert.Equal(1, repo.Head.Commits.Count());
}
}
[Fact]
public void CanNotCommitAnEmptyCommit()
{
string path = SandboxStandardTestRepo();
using (var repo = new Repository(path))
{
repo.Reset(ResetMode.Hard);
repo.RemoveUntrackedFiles();
Assert.Throws<EmptyCommitException>(() => repo.Commit("Empty commit!", Constants.Signature, Constants.Signature));
}
}
[Fact]
public void CanCommitAnEmptyCommitWhenForced()
{
string path = SandboxStandardTestRepo();
using (var repo = new Repository(path))
{
repo.Reset(ResetMode.Hard);
repo.RemoveUntrackedFiles();
repo.Commit("Empty commit!", Constants.Signature, Constants.Signature,
new CommitOptions { AllowEmptyCommit = true });
}
}
[Fact]
public void CanNotAmendAnEmptyCommit()
{
string path = SandboxStandardTestRepo();
using (var repo = new Repository(path))
{
repo.Reset(ResetMode.Hard);
repo.RemoveUntrackedFiles();
repo.Commit("Empty commit!", Constants.Signature, Constants.Signature,
new CommitOptions { AllowEmptyCommit = true });
Assert.Throws<EmptyCommitException>(() => repo.Commit("Empty commit!", Constants.Signature, Constants.Signature,
new CommitOptions { AmendPreviousCommit = true }));
}
}
[Fact]
public void CanAmendAnEmptyCommitWhenForced()
{
string path = SandboxStandardTestRepo();
using (var repo = new Repository(path))
{
repo.Reset(ResetMode.Hard);
repo.RemoveUntrackedFiles();
Commit emptyCommit = repo.Commit("Empty commit!", Constants.Signature, Constants.Signature,
new CommitOptions { AllowEmptyCommit = true });
Commit amendedCommit = repo.Commit("I'm rewriting the history!", Constants.Signature, Constants.Signature,
new CommitOptions { AmendPreviousCommit = true, AllowEmptyCommit = true });
AssertCommitHasBeenAmended(repo, amendedCommit, emptyCommit);
}
}
[Fact]
public void CanCommitAnEmptyCommitWhenMerging()
{
string path = SandboxStandardTestRepo();
using (var repo = new Repository(path))
{
repo.Reset(ResetMode.Hard);
repo.RemoveUntrackedFiles();
Touch(repo.Info.Path, "MERGE_HEAD", "f705abffe7015f2beacf2abe7a36583ebee3487e\n");
Assert.Equal(CurrentOperation.Merge, repo.Info.CurrentOperation);
Commit newMergedCommit = repo.Commit("Merge commit", Constants.Signature, Constants.Signature);
Assert.Equal(2, newMergedCommit.Parents.Count());
Assert.Equal(newMergedCommit.Parents.First().Sha, "32eab9cb1f450b5fe7ab663462b77d7f4b703344");
Assert.Equal(newMergedCommit.Parents.Skip(1).First().Sha, "f705abffe7015f2beacf2abe7a36583ebee3487e");
}
}
[Fact]
public void CanAmendAnEmptyMergeCommit()
{
string path = SandboxStandardTestRepo();
using (var repo = new Repository(path))
{
repo.Reset(ResetMode.Hard);
repo.RemoveUntrackedFiles();
Touch(repo.Info.Path, "MERGE_HEAD", "f705abffe7015f2beacf2abe7a36583ebee3487e\n");
Commit newMergedCommit = repo.Commit("Merge commit", Constants.Signature, Constants.Signature);
Commit amendedCommit = repo.Commit("I'm rewriting the history!", Constants.Signature, Constants.Signature,
new CommitOptions { AmendPreviousCommit = true });
AssertCommitHasBeenAmended(repo, amendedCommit, newMergedCommit);
}
}
[Fact]
public void CanNotAmendACommitInAWayThatWouldLeadTheNewCommitToBecomeEmpty()
{
string repoPath = InitNewRepository();
using (var repo = new Repository(repoPath))
{
Touch(repo.Info.WorkingDirectory, "test.txt", "test\n");
repo.Stage("test.txt");
repo.Commit("Initial commit", Constants.Signature, Constants.Signature);
Touch(repo.Info.WorkingDirectory, "new.txt", "content\n");
repo.Stage("new.txt");
repo.Commit("One commit", Constants.Signature, Constants.Signature);
repo.Remove("new.txt");
Assert.Throws<EmptyCommitException>(() => repo.Commit("Oops", Constants.Signature, Constants.Signature,
new CommitOptions { AmendPreviousCommit = true }));
}
}
}
}
| |
// Copyright 2010 ESRI
//
// All rights reserved under the copyright laws of the United States
// and applicable international laws, treaties, and conventions.
//
// You may freely redistribute and use this sample code, with or
// without modification, provided you include the original copyright
// notice and use restrictions.
//
// See the use restrictions at <your ArcGIS install location>/DeveloperKit10.0/userestrictions.txt.
//
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by ESRI license initialization tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace com.esri.gpt.publish
{
using System;
using System.Collections.Generic;
using System.Text;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS;
/// <summary>
/// Initialize ArcObjects runtime environment for this application
/// </summary>
partial class LicenseInitializer
{
/// <summary>
/// Raised when ArcGIS runtime binding hasn't been established.
/// </summary>
public event EventHandler ResolveBindingEvent;
/// <summary>
/// Indicates if implicit binding is allowed.
/// </summary>
/// <remarks>If set to true, LicenseInitializer continues
/// checking out license product when any active version is bound, including pre-10 install.
/// Otherwise, ResolveBindingEvent will be raised unless active version product
/// is bound to an explicit ArcGIS product (i.e. not Product.ArcGIS or Product.Unknown).
/// Default to false.</remarks>
public bool AllowImplicitRuntimeBinding
{
get { return m_fallbackBinding; }
set { m_fallbackBinding = value; }
}
/// <summary>
/// Initialize the application with the specified product and extension license code.
/// </summary>
/// <returns>Initialization is successful.</returns>
/// <remarks>
/// If no active runtime has been bound to the application before license initialization
/// takes place, the ResolveBindingEvent is raised.
/// </remarks>
public bool InitializeApplication(esriLicenseProductCode[] productCodes, esriLicenseExtensionCode[] extensionLics)
{
//Cache product codes by enum int so can be sorted without custom sorter
m_requestedProducts = new List<int>();
foreach (esriLicenseProductCode code in productCodes)
{
int requestCodeNum = Convert.ToInt32(code);
if (!m_requestedProducts.Contains(requestCodeNum))
{
m_requestedProducts.Add(requestCodeNum);
}
}
AddExtensions(extensionLics);
// Make sure an active version has been loaded before calling any ArcObjects code.
RuntimeInfo boundRuntime = RuntimeManager.ActiveRuntime;
if (boundRuntime != null &&
(this.AllowImplicitRuntimeBinding || boundRuntime.Product > ProductCode.ArcGIS))
{
m_AoInit = new AoInitializeClass();
}
else
{
EventHandler temp = ResolveBindingEvent;
if (temp != null)
{
temp(this, new EventArgs());
if (RuntimeManager.ActiveRuntime != null)
m_AoInit = new AoInitializeClass();
}
}
return Initialize();
}
/// <summary>
/// A summary of the status of product and extensions initialization.
/// </summary>
public string LicenseMessage()
{
if (m_AoInit == null)
{
return MessageNoAoInitialize;
}
string prodStatus = string.Empty;
string extStatus = string.Empty;
if (m_productStatus == null || m_productStatus.Count == 0)
{
prodStatus = MessageNoLicensesRequested + Environment.NewLine;
}
else if (m_productStatus.ContainsValue(esriLicenseStatus.esriLicenseAlreadyInitialized)
|| m_productStatus.ContainsValue(esriLicenseStatus.esriLicenseCheckedOut))
{
prodStatus = ReportInformation(m_AoInit as ILicenseInformation,
m_AoInit.InitializedProduct(),
esriLicenseStatus.esriLicenseCheckedOut) + Environment.NewLine;
}
else
{
//Failed...
foreach (KeyValuePair<esriLicenseProductCode, esriLicenseStatus> item in m_productStatus)
{
prodStatus += ReportInformation(m_AoInit as ILicenseInformation,
item.Key, item.Value) + Environment.NewLine;
}
}
foreach (KeyValuePair<esriLicenseExtensionCode, esriLicenseStatus> item in m_extensionStatus)
{
string info = ReportInformation(m_AoInit as ILicenseInformation, item.Key, item.Value);
if (!string.IsNullOrEmpty(info))
extStatus += info + Environment.NewLine;
}
return (prodStatus + extStatus).Trim();
}
/// <summary>
/// Shuts down AoInitialize object and check back in extensions to ensure
/// any ESRI libraries that have been used are unloaded in the correct order.
/// </summary>
/// <remarks>Once Shutdown has been called, you cannot re-initialize the product license
/// and should not make any ArcObjects call.</remarks>
public void ShutdownApplication()
{
if (m_hasShutDown)
return;
//Check back in extensions
if (m_AoInit != null)
{
foreach (KeyValuePair<esriLicenseExtensionCode, esriLicenseStatus> item in m_extensionStatus)
{
if (item.Value == esriLicenseStatus.esriLicenseCheckedOut)
m_AoInit.CheckInExtension(item.Key);
}
m_AoInit.Shutdown();
}
m_requestedProducts = null;
m_requestedExtensions = null;
m_extensionStatus = null;
m_productStatus = null;
m_hasShutDown = true;
}
/// <summary>
/// Indicates if the extension is currently checked out.
/// </summary>
public bool IsExtensionCheckedOut(esriLicenseExtensionCode code)
{
return m_AoInit != null && m_AoInit.IsExtensionCheckedOut(code);
}
/// <summary>
/// Set the extension(s) to be checked out for your ArcObjects code.
/// </summary>
public bool AddExtensions(params esriLicenseExtensionCode[] requestCodes)
{
if (m_requestedExtensions == null)
m_requestedExtensions = new List<esriLicenseExtensionCode>();
foreach (esriLicenseExtensionCode code in requestCodes)
{
if (!m_requestedExtensions.Contains(code))
m_requestedExtensions.Add(code);
}
if (m_hasInitializeProduct)
return CheckOutLicenses(this.InitializedProduct);
return false;
}
/// <summary>
/// Check in extension(s) when it is no longer needed.
/// </summary>
public void RemoveExtensions(params esriLicenseExtensionCode[] requestCodes)
{
if (m_extensionStatus == null || m_extensionStatus.Count == 0)
return;
foreach (esriLicenseExtensionCode code in requestCodes)
{
if (m_extensionStatus.ContainsKey(code))
{
if (m_AoInit.CheckInExtension(code) == esriLicenseStatus.esriLicenseCheckedIn)
{
m_extensionStatus[code] = esriLicenseStatus.esriLicenseCheckedIn;
}
}
}
}
/// <summary>
/// Get/Set the ordering of product code checking. If true, check from lowest to
/// highest license. True by default.
/// </summary>
public bool InitializeLowerProductFirst
{
get
{
return m_productCheckOrdering;
}
set
{
m_productCheckOrdering = value;
}
}
/// <summary>
/// Retrieves the product code initialized in the ArcObjects application
/// </summary>
public esriLicenseProductCode InitializedProduct
{
get
{
try
{
return m_AoInit.InitializedProduct();
}
catch
{
return 0;
}
}
}
#region Helper methods
private bool Initialize()
{
if (m_AoInit == null || m_requestedProducts == null || m_requestedProducts.Count == 0)
return false;
bool productInitialized = false;
m_requestedProducts.Sort();
if (!InitializeLowerProductFirst) //Request license from highest to lowest
m_requestedProducts.Reverse();
esriLicenseProductCode currentProduct = new esriLicenseProductCode();
foreach (int prodNumber in m_requestedProducts)
{
esriLicenseProductCode prod = (esriLicenseProductCode)Enum.ToObject(typeof(esriLicenseProductCode), prodNumber);
esriLicenseStatus status = m_AoInit.IsProductCodeAvailable(prod);
if (status == esriLicenseStatus.esriLicenseAvailable)
{
status = m_AoInit.Initialize(prod);
if (status == esriLicenseStatus.esriLicenseAlreadyInitialized ||
status == esriLicenseStatus.esriLicenseCheckedOut)
{
productInitialized = true;
currentProduct = m_AoInit.InitializedProduct();
}
}
m_productStatus.Add(prod, status);
if (productInitialized)
break;
}
m_hasInitializeProduct = productInitialized;
m_requestedProducts.Clear();
//No product is initialized after trying all requested licenses, quit
if (!productInitialized)
{
return false;
}
//Check out extension licenses
return CheckOutLicenses(currentProduct);
}
private bool CheckOutLicenses(esriLicenseProductCode currentProduct)
{
bool allSuccessful = true;
//Request extensions
if (m_requestedExtensions != null && currentProduct != 0)
{
foreach (esriLicenseExtensionCode ext in m_requestedExtensions)
{
esriLicenseStatus licenseStatus = m_AoInit.IsExtensionCodeAvailable(currentProduct, ext);
if (licenseStatus == esriLicenseStatus.esriLicenseAvailable)//skip unavailable extensions
{
licenseStatus = m_AoInit.CheckOutExtension(ext);
}
allSuccessful = (allSuccessful && licenseStatus == esriLicenseStatus.esriLicenseCheckedOut);
if (m_extensionStatus.ContainsKey(ext))
m_extensionStatus[ext] = licenseStatus;
else
m_extensionStatus.Add(ext, licenseStatus);
}
m_requestedExtensions.Clear();
}
return allSuccessful;
}
private string ReportInformation(ILicenseInformation licInfo,
esriLicenseProductCode code, esriLicenseStatus status)
{
string prodName = string.Empty;
try
{
prodName = licInfo.GetLicenseProductName(code);
}
catch
{
prodName = code.ToString();
}
string statusInfo = string.Empty;
switch (status)
{
case esriLicenseStatus.esriLicenseAlreadyInitialized:
case esriLicenseStatus.esriLicenseCheckedOut:
statusInfo = string.Format(MessageProductAvailable, prodName);
break;
default:
statusInfo = string.Format(MessageProductNotLicensed, prodName);
break;
}
return statusInfo;
}
private string ReportInformation(ILicenseInformation licInfo,
esriLicenseExtensionCode code, esriLicenseStatus status)
{
string extensionName = string.Empty;
try
{
extensionName = licInfo.GetLicenseExtensionName(code);
}
catch
{
extensionName = code.ToString();
}
string statusInfo = string.Empty;
switch (status)
{
case esriLicenseStatus.esriLicenseAlreadyInitialized:
case esriLicenseStatus.esriLicenseCheckedOut:
statusInfo = string.Format(MessageExtensionAvailable, extensionName);
break;
case esriLicenseStatus.esriLicenseCheckedIn:
break;
case esriLicenseStatus.esriLicenseUnavailable:
statusInfo = string.Format(MessageExtensionUnavailable, extensionName);
break;
case esriLicenseStatus.esriLicenseFailure:
statusInfo = string.Format(MessageExtensionFailed, extensionName);
break;
default:
statusInfo = string.Format(MessageExtensionNotLicensed, extensionName);
break;
}
return statusInfo;
}
#endregion
#region Private members
private IAoInitialize m_AoInit = null;
private const string MessageNoAoInitialize = "ArcObjects initialization failed.";
private const string MessageNoLicensesRequested = "Product: No licenses were requested";
private const string MessageProductAvailable = "Product: {0}: Available";
private const string MessageProductNotLicensed = "Product: {0}: Not Licensed";
private const string MessageExtensionAvailable = " Extension: {0}: Available";
private const string MessageExtensionNotLicensed = " Extension: {0}: Not Licensed";
private const string MessageExtensionFailed = " Extension: {0}: Failed";
private const string MessageExtensionUnavailable = " Extension: {0}: Unavailable";
private bool m_hasShutDown = false;
private bool m_hasInitializeProduct = false;
private List<int> m_requestedProducts;
private List<esriLicenseExtensionCode> m_requestedExtensions;
private Dictionary<esriLicenseProductCode, esriLicenseStatus> m_productStatus = new Dictionary<esriLicenseProductCode, esriLicenseStatus>();
private Dictionary<esriLicenseExtensionCode, esriLicenseStatus> m_extensionStatus = new Dictionary<esriLicenseExtensionCode, esriLicenseStatus>();
private bool m_productCheckOrdering = true; //default from low to high
private bool m_fallbackBinding = false;
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.IO.Compression;
using System.Net;
using System.Net.Http;
using System.Net.Test.Common;
using System.Runtime.InteropServices;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
using Xunit.Abstractions;
namespace System.Net.Http.WinHttpHandlerUnitTests
{
public class WinHttpHandlerTest
{
private const string FakeProxy = "http://proxy.contoso.com";
private readonly ITestOutputHelper _output;
public WinHttpHandlerTest(ITestOutputHelper output)
{
_output = output;
TestControl.ResetAll();
}
[Fact]
public void Ctor_ExpectedDefaultPropertyValues()
{
var handler = new WinHttpHandler();
Assert.Equal(SslProtocols.None, handler.SslProtocols);
Assert.Equal(true, handler.AutomaticRedirection);
Assert.Equal(50, handler.MaxAutomaticRedirections);
Assert.Equal(DecompressionMethods.None, handler.AutomaticDecompression);
Assert.Equal(CookieUsePolicy.UseInternalCookieStoreOnly, handler.CookieUsePolicy);
Assert.Equal(null, handler.CookieContainer);
Assert.Equal(null, handler.ServerCertificateValidationCallback);
Assert.Equal(false, handler.CheckCertificateRevocationList);
Assert.Equal(ClientCertificateOption.Manual, handler.ClientCertificateOption);
X509Certificate2Collection certs = handler.ClientCertificates;
Assert.True(certs.Count == 0);
Assert.Equal(false, handler.PreAuthenticate);
Assert.Equal(null, handler.ServerCredentials);
Assert.Equal(WindowsProxyUsePolicy.UseWinHttpProxy, handler.WindowsProxyUsePolicy);
Assert.Equal(null, handler.DefaultProxyCredentials);
Assert.Equal(null, handler.Proxy);
Assert.Equal(int.MaxValue, handler.MaxConnectionsPerServer);
Assert.Equal(TimeSpan.FromSeconds(30), handler.SendTimeout);
Assert.Equal(TimeSpan.FromSeconds(30), handler.ReceiveHeadersTimeout);
Assert.Equal(TimeSpan.FromSeconds(30), handler.ReceiveDataTimeout);
Assert.Equal(64, handler.MaxResponseHeadersLength);
Assert.Equal(64 * 1024, handler.MaxResponseDrainSize);
Assert.NotNull(handler.Properties);
}
[Fact]
public void AutomaticRedirection_SetFalseAndGet_ValueIsFalse()
{
var handler = new WinHttpHandler();
handler.AutomaticRedirection = false;
Assert.False(handler.AutomaticRedirection);
}
[Fact]
public void AutomaticRedirection_SetTrue_ExpectedWinHttpHandleSettings()
{
var handler = new WinHttpHandler();
SendRequestHelper.Send(
handler,
delegate { handler.AutomaticRedirection = true; });
Assert.Equal(
Interop.WinHttp.WINHTTP_OPTION_REDIRECT_POLICY_DISALLOW_HTTPS_TO_HTTP,
APICallHistory.WinHttpOptionRedirectPolicy);
}
[Fact]
public void AutomaticRedirection_SetFalse_ExpectedWinHttpHandleSettings()
{
var handler = new WinHttpHandler();
SendRequestHelper.Send(
handler,
delegate { handler.AutomaticRedirection = false; });
Assert.Equal(
Interop.WinHttp.WINHTTP_OPTION_REDIRECT_POLICY_NEVER,
APICallHistory.WinHttpOptionRedirectPolicy);
}
[Fact]
public void CheckCertificateRevocationList_SetTrue_ExpectedWinHttpHandleSettings()
{
var handler = new WinHttpHandler();
SendRequestHelper.Send(handler, delegate { handler.CheckCertificateRevocationList = true; });
Assert.True(APICallHistory.WinHttpOptionEnableSslRevocation.Value);
}
[Fact]
public void CheckCertificateRevocationList_SetFalse_ExpectedWinHttpHandleSettings()
{
var handler = new WinHttpHandler();
SendRequestHelper.Send(handler, delegate { handler.CheckCertificateRevocationList = false; });
Assert.Equal(false, APICallHistory.WinHttpOptionEnableSslRevocation.HasValue);
}
[Fact]
public void CookieContainer_WhenCreated_ReturnsNull()
{
var handler = new WinHttpHandler();
Assert.Null(handler.CookieContainer);
}
[Fact]
public async Task CookieUsePolicy_UseSpecifiedCookieContainerAndNullContainer_ThrowsInvalidOperationException()
{
var handler = new WinHttpHandler();
Assert.Null(handler.CookieContainer);
handler.CookieUsePolicy = CookieUsePolicy.UseSpecifiedCookieContainer;
using (var client = new HttpClient(handler))
{
TestServer.SetResponse(DecompressionMethods.None, TestServer.ExpectedResponseBody);
var request = new HttpRequestMessage(HttpMethod.Post, TestServer.FakeServerEndpoint);
await Assert.ThrowsAsync<InvalidOperationException>(() => client.SendAsync(request));
}
}
[Fact]
public void CookieUsePolicy_SetUsingInvalidEnum_ThrowsArgumentOutOfRangeException()
{
var handler = new WinHttpHandler();
Assert.Throws<ArgumentOutOfRangeException>(() => { handler.CookieUsePolicy = (CookieUsePolicy)100; });
}
[Fact]
public void CookieUsePolicy_WhenCreated_ReturnsUseInternalCookieStoreOnly()
{
var handler = new WinHttpHandler();
Assert.Equal(CookieUsePolicy.UseInternalCookieStoreOnly, handler.CookieUsePolicy);
}
[Fact]
public void CookieUsePolicy_SetIgnoreCookies_NoExceptionThrown()
{
var handler = new WinHttpHandler();
handler.CookieUsePolicy = CookieUsePolicy.IgnoreCookies;
}
[Fact]
public void CookieUsePolicy_SetUseInternalCookieStoreOnly_NoExceptionThrown()
{
var handler = new WinHttpHandler();
handler.CookieUsePolicy = CookieUsePolicy.UseInternalCookieStoreOnly;
}
[Fact]
public void CookieUsePolicy_SetUseSpecifiedCookieContainer_NoExceptionThrown()
{
var handler = new WinHttpHandler();
handler.CookieUsePolicy = CookieUsePolicy.UseSpecifiedCookieContainer;
}
[Fact]
public void CookieUsePolicy_SetIgnoreCookies_ExpectedWinHttpHandleSettings()
{
var handler = new WinHttpHandler();
SendRequestHelper.Send(handler, delegate { handler.CookieUsePolicy = CookieUsePolicy.IgnoreCookies; });
Assert.True(APICallHistory.WinHttpOptionDisableCookies.Value);
}
[Fact]
public void CookieUsePolicy_SetUseInternalCookieStoreOnly_ExpectedWinHttpHandleSettings()
{
var handler = new WinHttpHandler();
SendRequestHelper.Send(
handler,
delegate { handler.CookieUsePolicy = CookieUsePolicy.UseInternalCookieStoreOnly; });
Assert.Equal(false, APICallHistory.WinHttpOptionDisableCookies.HasValue);
}
[Fact]
public void CookieUsePolicy_SetUseSpecifiedCookieContainerAndContainer_ExpectedWinHttpHandleSettings()
{
var handler = new WinHttpHandler();
SendRequestHelper.Send(
handler,
delegate {
handler.CookieUsePolicy = CookieUsePolicy.UseSpecifiedCookieContainer;
handler.CookieContainer = new CookieContainer();
});
Assert.Equal(true, APICallHistory.WinHttpOptionDisableCookies.HasValue);
}
[Fact]
public void Properties_Get_CountIsZero()
{
var handler = new WinHttpHandler();
IDictionary<string, object> dict = handler.Properties;
Assert.Equal(0, dict.Count);
}
[Fact]
public void Properties_AddItemToDictionary_ItemPresent()
{
var handler = new WinHttpHandler();
IDictionary<string, object> dict = handler.Properties;
Assert.Same(dict, handler.Properties);
var item = new object();
dict.Add("item", item);
object value;
Assert.True(dict.TryGetValue("item", out value));
Assert.Equal(item, value);
}
[Fact]
public void WindowsProxyUsePolicy_SetUsingInvalidEnum_ThrowArgumentOutOfRangeException()
{
var handler = new WinHttpHandler();
Assert.Throws<ArgumentOutOfRangeException>(
() => { handler.WindowsProxyUsePolicy = (WindowsProxyUsePolicy)100; });
}
[Fact]
public void WindowsProxyUsePolicy_SetDoNotUseProxy_NoExceptionThrown()
{
var handler = new WinHttpHandler();
handler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.DoNotUseProxy;
}
[Fact]
public void WindowsProxyUsePolicy_SetUseWinHttpProxy_NoExceptionThrown()
{
var handler = new WinHttpHandler();
handler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseWinHttpProxy;
}
[Fact]
public void WindowsProxyUsePolicy_SetUseWinWinInetProxy_NoExceptionThrown()
{
var handler = new WinHttpHandler();
handler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseWinInetProxy;
}
[Fact]
public void WindowsProxyUsePolicy_SetUseCustomProxy_NoExceptionThrown()
{
var handler = new WinHttpHandler();
handler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseCustomProxy;
}
[Fact]
public async Task WindowsProxyUsePolicy_UseNonNullProxyAndIncorrectWindowsProxyUsePolicy_ThrowsInvalidOperationException()
{
var handler = new WinHttpHandler();
handler.Proxy = new CustomProxy(false);
handler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.DoNotUseProxy;
using (var client = new HttpClient(handler))
{
TestServer.SetResponse(DecompressionMethods.None, TestServer.ExpectedResponseBody);
var request = new HttpRequestMessage(HttpMethod.Post, TestServer.FakeServerEndpoint);
await Assert.ThrowsAsync<InvalidOperationException>(() => client.SendAsync(request));
}
}
[Fact]
public async Task WindowsProxyUsePolicy_UseCustomProxyAndNullProxy_ThrowsInvalidOperationException()
{
var handler = new WinHttpHandler();
handler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseCustomProxy;
handler.Proxy = null;
using (var client = new HttpClient(handler))
{
TestServer.SetResponse(DecompressionMethods.None, TestServer.ExpectedResponseBody);
var request = new HttpRequestMessage(HttpMethod.Post, TestServer.FakeServerEndpoint);
await Assert.ThrowsAsync<InvalidOperationException>(() => client.SendAsync(request));
}
}
[Fact]
public void MaxAutomaticRedirections_SetZero_ThrowsArgumentOutOfRangeException()
{
var handler = new WinHttpHandler();
Assert.Throws<ArgumentOutOfRangeException>(() => { handler.MaxAutomaticRedirections = 0; });
}
[Fact]
public void MaxAutomaticRedirections_SetNegativeValue_ThrowsArgumentOutOfRangeException()
{
var handler = new WinHttpHandler();
Assert.Throws<ArgumentOutOfRangeException>(() => { handler.MaxAutomaticRedirections = -1; });
}
[Fact]
public void MaxAutomaticRedirections_SetValidValue_ExpectedWinHttpHandleSettings()
{
var handler = new WinHttpHandler();
int redirections = 35;
SendRequestHelper.Send(handler, delegate { handler.MaxAutomaticRedirections = redirections; });
Assert.Equal((uint)redirections, APICallHistory.WinHttpOptionMaxHttpAutomaticRedirects);
}
[Fact]
public void MaxConnectionsPerServer_SetZero_ThrowsArgumentOutOfRangeException()
{
var handler = new WinHttpHandler();
Assert.Throws<ArgumentOutOfRangeException>(() => { handler.MaxConnectionsPerServer = 0; });
}
[Fact]
public void MaxConnectionsPerServer_SetNegativeValue_ThrowsArgumentOutOfRangeException()
{
var handler = new WinHttpHandler();
Assert.Throws<ArgumentOutOfRangeException>(() => { handler.MaxConnectionsPerServer = -1; });
}
[Fact]
public void MaxConnectionsPerServer_SetPositiveValue_Success()
{
var handler = new WinHttpHandler();
handler.MaxConnectionsPerServer = 1;
}
[Fact]
public void ReceiveDataTimeout_SetNegativeValue_ThrowsArgumentOutOfRangeException()
{
var handler = new WinHttpHandler();
Assert.Throws<ArgumentOutOfRangeException>(
() => { handler.ReceiveDataTimeout = TimeSpan.FromMinutes(-10); });
}
[Fact]
public void ReceiveDataTimeout_SetTooLargeValue_ThrowsArgumentOutOfRangeException()
{
var handler = new WinHttpHandler();
Assert.Throws<ArgumentOutOfRangeException>(
() => { handler.ReceiveDataTimeout = TimeSpan.FromMilliseconds(int.MaxValue + 1.0); });
}
[Fact]
public void ReceiveDataTimeout_SetZeroValue_ThrowsArgumentOutOfRangeException()
{
var handler = new WinHttpHandler();
Assert.Throws<ArgumentOutOfRangeException>(() => { handler.ReceiveDataTimeout = TimeSpan.FromSeconds(0); });
}
[Fact]
public void ReceiveDataTimeout_SetInfiniteValue_NoExceptionThrown()
{
var handler = new WinHttpHandler();
handler.ReceiveDataTimeout = Timeout.InfiniteTimeSpan;
}
[Fact]
public void ReceiveHeadersTimeout_SetNegativeValue_ThrowsArgumentOutOfRangeException()
{
var handler = new WinHttpHandler();
Assert.Throws<ArgumentOutOfRangeException>(
() => { handler.ReceiveHeadersTimeout = TimeSpan.FromMinutes(-10); });
}
[Fact]
public void ReceiveHeadersTimeout_SetTooLargeValue_ThrowsArgumentOutOfRangeException()
{
var handler = new WinHttpHandler();
Assert.Throws<ArgumentOutOfRangeException>(
() => { handler.ReceiveHeadersTimeout = TimeSpan.FromMilliseconds(int.MaxValue + 1.0); });
}
[Fact]
public void ReceiveHeadersTimeout_SetZeroValue_ThrowsArgumentOutOfRangeException()
{
var handler = new WinHttpHandler();
Assert.Throws<ArgumentOutOfRangeException>(
() => { handler.ReceiveHeadersTimeout = TimeSpan.FromSeconds(0); });
}
[Fact]
public void ReceiveHeadersTimeout_SetInfiniteValue_NoExceptionThrown()
{
var handler = new WinHttpHandler();
handler.ReceiveHeadersTimeout = Timeout.InfiniteTimeSpan;
}
[Theory]
[ClassData(typeof(SslProtocolSupport.SupportedSslProtocolsTestData))]
public void SslProtocols_SetUsingSupported_Success(SslProtocols protocol)
{
var handler = new WinHttpHandler();
handler.SslProtocols = protocol;
}
[Fact]
public void SslProtocols_SetUsingNone_Success()
{
var handler = new WinHttpHandler();
handler.SslProtocols = SslProtocols.None;
}
[Theory]
[InlineData(
SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12,
Interop.WinHttp.WINHTTP_FLAG_SECURE_PROTOCOL_TLS1 |
Interop.WinHttp.WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_1 |
Interop.WinHttp.WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_2)]
#pragma warning disable 0618
[InlineData(
SslProtocols.Ssl2 | SslProtocols.Ssl3,
Interop.WinHttp.WINHTTP_FLAG_SECURE_PROTOCOL_SSL2 |
Interop.WinHttp.WINHTTP_FLAG_SECURE_PROTOCOL_SSL3)]
#pragma warning restore 0618
public void SslProtocols_SetUsingValidEnums_ExpectedWinHttpHandleSettings(
SslProtocols specified, uint expectedProtocols)
{
var handler = new WinHttpHandler();
SendRequestHelper.Send(
handler,
delegate { handler.SslProtocols = specified; });
Assert.Equal(expectedProtocols, APICallHistory.WinHttpOptionSecureProtocols);
}
[Fact]
public async Task GetAsync_MultipleRequestsReusingSameClient_Success()
{
var handler = new WinHttpHandler();
using (var client = new HttpClient(handler))
{
for (int i = 0; i < 3; i++)
{
TestServer.SetResponse(DecompressionMethods.None, TestServer.ExpectedResponseBody);
using (HttpResponseMessage response = await client.GetAsync(TestServer.FakeServerEndpoint))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
}
}
}
[Fact]
public async Task SendAsync_ReadFromStreamingServer_PartialDataRead()
{
var handler = new WinHttpHandler();
using (var client = new HttpClient(handler))
{
TestServer.SetResponse(DecompressionMethods.None, TestServer.ExpectedResponseBody);
TestServer.DataAvailablePercentage = 0.25;
int bytesRead;
byte[] buffer = new byte[TestServer.ExpectedResponseBody.Length];
var request = new HttpRequestMessage(HttpMethod.Get, TestServer.FakeServerEndpoint);
using (var response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
var stream = await response.Content.ReadAsStreamAsync();
bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length);
_output.WriteLine("bytesRead={0}", bytesRead);
}
Assert.True(bytesRead < buffer.Length, "bytesRead should be less than buffer.Length");
}
}
[Fact]
public async Task SendAsync_ReadAllDataFromStreamingServer_AllDataRead()
{
var handler = new WinHttpHandler();
using (var client = new HttpClient(handler))
{
TestServer.SetResponse(DecompressionMethods.None, TestServer.ExpectedResponseBody);
TestServer.DataAvailablePercentage = 0.25;
int totalBytesRead = 0;
int bytesRead;
byte[] buffer = new byte[TestServer.ExpectedResponseBody.Length];
var request = new HttpRequestMessage(HttpMethod.Get, TestServer.FakeServerEndpoint);
using (var response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
var stream = await response.Content.ReadAsStreamAsync();
do
{
bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length);
_output.WriteLine("bytesRead={0}", bytesRead);
totalBytesRead += bytesRead;
} while (bytesRead != 0);
}
Assert.Equal(buffer.Length, totalBytesRead);
}
}
[Fact]
public async Task SendAsync_PostContentWithContentLengthAndChunkedEncodingHeaders_Success()
{
var handler = new WinHttpHandler();
using (var client = new HttpClient(handler))
{
client.DefaultRequestHeaders.TransferEncodingChunked = true;
TestServer.SetResponse(DecompressionMethods.None, TestServer.ExpectedResponseBody);
var content = new StringContent(TestServer.ExpectedResponseBody);
Assert.True(content.Headers.ContentLength.HasValue);
var request = new HttpRequestMessage(HttpMethod.Post, TestServer.FakeServerEndpoint);
request.Content = content;
(await client.SendAsync(request)).Dispose();
}
}
[Fact]
public async Task SendAsync_PostNoContentObjectWithChunkedEncodingHeader_ExpectHttpRequestException()
{
var handler = new WinHttpHandler();
using (var client = new HttpClient(handler))
{
client.DefaultRequestHeaders.TransferEncodingChunked = true;
TestServer.SetResponse(DecompressionMethods.None, TestServer.ExpectedResponseBody);
var request = new HttpRequestMessage(HttpMethod.Post, TestServer.FakeServerEndpoint);
await Assert.ThrowsAsync<HttpRequestException>(() => client.SendAsync(request));
}
}
[Fact]
public async Task SendAsync_NoWinHttpDecompressionSupportAndResponseBodyIsDeflateCompressed_ExpectedResponse()
{
TestControl.WinHttpDecompressionSupport = false;
var handler = new WinHttpHandler();
using (HttpResponseMessage response = SendRequestHelper.Send(
handler,
delegate
{
handler.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
TestServer.SetResponse(DecompressionMethods.Deflate, TestServer.ExpectedResponseBody);
}))
{
await VerifyResponseContent(
TestServer.ExpectedResponseBodyBytes,
response.Content,
responseContentWasOriginallyCompressed: true,
responseContentWasAutoDecompressed: true);
}
}
[Fact]
public async Task SendAsync_NoWinHttpDecompressionSupportAndResponseBodyIsGZipCompressed_ExpectedResponse()
{
TestControl.WinHttpDecompressionSupport = false;
var handler = new WinHttpHandler();
using (HttpResponseMessage response = SendRequestHelper.Send(
handler,
delegate
{
handler.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
TestServer.SetResponse(DecompressionMethods.GZip, TestServer.ExpectedResponseBody);
}))
{
await VerifyResponseContent(
TestServer.ExpectedResponseBodyBytes,
response.Content,
responseContentWasOriginallyCompressed: true,
responseContentWasAutoDecompressed: true);
}
}
[Fact]
public async Task SendAsync_NoWinHttpDecompressionSupportAndResponseBodyIsNotCompressed_ExpectedResponse()
{
TestControl.WinHttpDecompressionSupport = false;
var handler = new WinHttpHandler();
using (HttpResponseMessage response = SendRequestHelper.Send(
handler,
delegate
{
handler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseWinInetProxy;
}))
{
await VerifyResponseContent(
TestServer.ExpectedResponseBodyBytes,
response.Content,
responseContentWasOriginallyCompressed: false,
responseContentWasAutoDecompressed: false);
}
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public async Task SendAsync_NoWinHttpDecompressionSupport_AutoDecompressionSettingDiffers_ResponseIsNotDecompressed(bool responseIsGZip)
{
DecompressionMethods decompressionMethods = responseIsGZip ? DecompressionMethods.Deflate : DecompressionMethods.GZip;
_output.WriteLine("DecompressionMethods = {0}", decompressionMethods.ToString());
TestControl.WinHttpDecompressionSupport = false;
var handler = new WinHttpHandler();
using (HttpResponseMessage response = SendRequestHelper.Send(
handler,
delegate
{
handler.AutomaticDecompression = decompressionMethods;
TestServer.SetResponse(responseIsGZip ? DecompressionMethods.GZip : DecompressionMethods.Deflate, TestServer.ExpectedResponseBody);
}))
{
await VerifyResponseContent(
TestServer.CompressBytes(TestServer.ExpectedResponseBodyBytes, useGZip: responseIsGZip),
response.Content,
responseContentWasOriginallyCompressed: true,
responseContentWasAutoDecompressed: false);
}
}
[Fact]
public void SendAsync_AutomaticProxySupportAndUseWinInetSettings_ExpectedWinHttpSessionProxySettings()
{
TestControl.WinHttpAutomaticProxySupport = true;
var handler = new WinHttpHandler();
SendRequestHelper.Send(
handler,
delegate
{
handler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseWinInetProxy;
});
Assert.Equal(Interop.WinHttp.WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY, APICallHistory.SessionProxySettings.AccessType);
}
[Fact]
public void SendAsync_NoAutomaticProxySupportAndUseWinInetSettingsWithAutoDetectSetting_ExpectedWinHttpProxySettings()
{
TestControl.WinHttpAutomaticProxySupport = false;
FakeRegistry.WinInetProxySettings.AutoDetect = true;
var handler = new WinHttpHandler();
SendRequestHelper.Send(
handler,
delegate
{
handler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseWinInetProxy;
});
Assert.Equal(Interop.WinHttp.WINHTTP_ACCESS_TYPE_NO_PROXY, APICallHistory.SessionProxySettings.AccessType);
Assert.Equal(Interop.WinHttp.WINHTTP_ACCESS_TYPE_NAMED_PROXY, APICallHistory.RequestProxySettings.AccessType);
}
[Fact]
public void SendAsync_NoAutomaticProxySupportAndUseWinInetSettingsWithEmptySettings_ExpectedWinHttpProxySettings()
{
TestControl.WinHttpAutomaticProxySupport = false;
var handler = new WinHttpHandler();
SendRequestHelper.Send(
handler,
delegate
{
handler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseWinInetProxy;
});
Assert.Equal(Interop.WinHttp.WINHTTP_ACCESS_TYPE_NO_PROXY, APICallHistory.SessionProxySettings.AccessType);
Assert.Equal(false, APICallHistory.RequestProxySettings.AccessType.HasValue);
}
[Fact]
public void SendAsync_NoAutomaticProxySupportAndUseWinInetSettingsWithManualSettingsOnly_ExpectedWinHttpProxySettings()
{
TestControl.WinHttpAutomaticProxySupport = false;
FakeRegistry.WinInetProxySettings.Proxy = FakeProxy;
var handler = new WinHttpHandler();
SendRequestHelper.Send(
handler,
delegate
{
handler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseWinInetProxy;
});
Assert.Equal(Interop.WinHttp.WINHTTP_ACCESS_TYPE_NAMED_PROXY, APICallHistory.SessionProxySettings.AccessType);
Assert.Equal(false, APICallHistory.RequestProxySettings.AccessType.HasValue);
}
[Fact]
public void SendAsync_NoAutomaticProxySupportAndUseWinInetSettingsWithMissingRegistrySettings_ExpectedWinHttpProxySettings()
{
TestControl.WinHttpAutomaticProxySupport = false;
FakeRegistry.WinInetProxySettings.RegistryKeyMissing = true;
var handler = new WinHttpHandler();
SendRequestHelper.Send(
handler,
delegate
{
handler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseWinInetProxy;
});
Assert.Equal(Interop.WinHttp.WINHTTP_ACCESS_TYPE_NO_PROXY, APICallHistory.SessionProxySettings.AccessType);
Assert.Equal(false, APICallHistory.RequestProxySettings.AccessType.HasValue);
}
[Fact]
public void SendAsync_NoAutomaticProxySupportAndUseWinInetSettingsWithAutoDetectButPACFileNotDetectedOnNetwork_ExpectedWinHttpProxySettings()
{
TestControl.WinHttpAutomaticProxySupport = false;
TestControl.PACFileNotDetectedOnNetwork = true;
FakeRegistry.WinInetProxySettings.AutoDetect = true;
var handler = new WinHttpHandler();
SendRequestHelper.Send(
handler,
delegate
{
handler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseWinInetProxy;
});
Assert.Equal(Interop.WinHttp.WINHTTP_ACCESS_TYPE_NO_PROXY, APICallHistory.SessionProxySettings.AccessType);
Assert.Null(APICallHistory.RequestProxySettings.AccessType);
}
[Fact]
public void SendAsync_NoAutomaticProxySupportAndUseWinInetSettingsWithAutoDetectSettingAndManualSettingButPACFileNotFoundOnNetwork_ExpectedWinHttpProxySettings()
{
const string manualProxy = FakeProxy;
TestControl.WinHttpAutomaticProxySupport = false;
FakeRegistry.WinInetProxySettings.AutoDetect = true;
FakeRegistry.WinInetProxySettings.Proxy = manualProxy;
TestControl.PACFileNotDetectedOnNetwork = true;
var handler = new WinHttpHandler();
SendRequestHelper.Send(
handler,
delegate
{
handler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseWinInetProxy;
});
// Both AutoDetect and manual proxy are specified. If AutoDetect fails to find
// the PAC file on the network, then we should fall back to manual setting.
Assert.Equal(Interop.WinHttp.WINHTTP_ACCESS_TYPE_NO_PROXY, APICallHistory.SessionProxySettings.AccessType);
Assert.Equal(Interop.WinHttp.WINHTTP_ACCESS_TYPE_NAMED_PROXY, APICallHistory.RequestProxySettings.AccessType);
Assert.Equal(manualProxy, APICallHistory.RequestProxySettings.Proxy);
}
[Fact]
public void SendAsync_UseNoProxy_ExpectedWinHttpProxySettings()
{
var handler = new WinHttpHandler();
SendRequestHelper.Send(handler, delegate { handler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.DoNotUseProxy; });
Assert.Equal(Interop.WinHttp.WINHTTP_ACCESS_TYPE_NO_PROXY, APICallHistory.SessionProxySettings.AccessType);
}
[Fact]
public void SendAsync_UseCustomProxyWithNoBypass_ExpectedWinHttpProxySettings()
{
var handler = new WinHttpHandler();
var customProxy = new CustomProxy(false);
SendRequestHelper.Send(
handler,
delegate
{
handler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseCustomProxy;
handler.Proxy = customProxy;
});
Assert.Equal(Interop.WinHttp.WINHTTP_ACCESS_TYPE_NO_PROXY, APICallHistory.SessionProxySettings.AccessType);
Assert.Equal(Interop.WinHttp.WINHTTP_ACCESS_TYPE_NAMED_PROXY, APICallHistory.RequestProxySettings.AccessType);
Assert.Equal(FakeProxy, APICallHistory.RequestProxySettings.Proxy);
}
[Fact]
public void SendAsync_UseCustomProxyWithBypass_ExpectedWinHttpProxySettings()
{
var handler = new WinHttpHandler();
var customProxy = new CustomProxy(true);
SendRequestHelper.Send(
handler,
delegate
{
handler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseCustomProxy;
handler.Proxy = customProxy;
});
Assert.Equal(Interop.WinHttp.WINHTTP_ACCESS_TYPE_NO_PROXY, APICallHistory.SessionProxySettings.AccessType);
Assert.Equal(Interop.WinHttp.WINHTTP_ACCESS_TYPE_NO_PROXY, APICallHistory.RequestProxySettings.AccessType);
}
[Fact]
public void SendAsync_AutomaticProxySupportAndUseDefaultWebProxy_ExpectedWinHttpSessionProxySettings()
{
TestControl.WinHttpAutomaticProxySupport = true;
var handler = new WinHttpHandler();
SendRequestHelper.Send(
handler,
delegate
{
handler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseCustomProxy;
handler.Proxy = new FakeDefaultWebProxy();
});
Assert.Equal(Interop.WinHttp.WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY, APICallHistory.SessionProxySettings.AccessType);
}
[Fact]
public async Task SendAsync_SlowPostRequestWithTimedCancellation_ExpectTaskCanceledException()
{
var handler = new WinHttpHandler();
TestControl.WinHttpReceiveResponse.Delay = 5000;
CancellationTokenSource cts = new CancellationTokenSource(50);
using (var client = new HttpClient(handler))
{
var request = new HttpRequestMessage(HttpMethod.Post, TestServer.FakeServerEndpoint);
var content = new StringContent(new string('a', 1000));
request.Content = content;
await Assert.ThrowsAsync<TaskCanceledException>(() =>
client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cts.Token));
}
}
[Fact]
public async Task SendAsync_SlowGetRequestWithTimedCancellation_ExpectTaskCanceledException()
{
var handler = new WinHttpHandler();
TestControl.WinHttpReceiveResponse.Delay = 5000;
CancellationTokenSource cts = new CancellationTokenSource(50);
using (var client = new HttpClient(handler))
{
var request = new HttpRequestMessage(HttpMethod.Get, TestServer.FakeServerEndpoint);
await Assert.ThrowsAsync<TaskCanceledException>(() =>
client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cts.Token));
}
}
[Fact]
public async Task SendAsync_RequestWithCanceledToken_ExpectTaskCanceledException()
{
var handler = new WinHttpHandler();
CancellationTokenSource cts = new CancellationTokenSource();
cts.Cancel();
using (var client = new HttpClient(handler))
{
var request = new HttpRequestMessage(HttpMethod.Get, TestServer.FakeServerEndpoint);
await Assert.ThrowsAsync<TaskCanceledException>(() =>
client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cts.Token));
}
}
[Fact]
public async Task SendAsync_WinHttpOpenReturnsError_ExpectHttpRequestException()
{
var handler = new WinHttpHandler();
var client = new HttpClient(handler);
var request = new HttpRequestMessage(HttpMethod.Get, TestServer.FakeServerEndpoint);
TestControl.WinHttpOpen.ErrorWithApiCall = true;
Exception ex = await Assert.ThrowsAsync<HttpRequestException>(() => client.SendAsync(request));
Assert.Equal(typeof(WinHttpException), ex.InnerException.GetType());
}
[Fact]
public void SendAsync_MultipleCallsWithDispose_NoHandleLeaksManuallyVerifiedUsingLogging()
{
for (int i = 0; i < 50; i++)
{
using (var handler = new WinHttpHandler())
using (HttpResponseMessage response = SendRequestHelper.Send(handler, () => { }))
{
}
}
}
private async Task VerifyResponseContent(
byte[] expectedResponseBodyBytes,
HttpContent responseContent,
bool responseContentWasOriginallyCompressed,
bool responseContentWasAutoDecompressed)
{
Nullable<long> contentLength = responseContent.Headers.ContentLength;
ICollection<string> contentEncoding = responseContent.Headers.ContentEncoding;
_output.WriteLine("Response Content.Headers.ContentLength = {0}", contentLength.HasValue ? contentLength.Value.ToString() : "(null)");
_output.WriteLine("Response Content.Headers.ContentEncoding = {0}", contentEncoding.Count > 0 ? contentEncoding.ToString() : "(null)");
byte[] responseBodyBytes = await responseContent.ReadAsByteArrayAsync();
_output.WriteLine($"Response Body = {BitConverter.ToString(responseBodyBytes)}");
_output.WriteLine($"Expected Response Body = {BitConverter.ToString(expectedResponseBodyBytes)}");
if (!responseContentWasOriginallyCompressed)
{
Assert.True(contentLength > 0);
}
else if (responseContentWasAutoDecompressed)
{
Assert.Null(contentLength);
Assert.Equal(0, contentEncoding.Count);
}
else
{
Assert.True(contentLength > 0);
Assert.True(contentEncoding.Count > 0);
}
Assert.Equal<byte>(expectedResponseBodyBytes, responseBodyBytes);
}
// Commented out as the test relies on finalizer for cleanup and only has value as written
// when run on its own and manual analysis is done of logs.
//[Fact]
//public void SendAsync_MultipleCallsWithoutDispose_NoHandleLeaksManuallyVerifiedUsingLogging()
//{
// WinHttpHandler handler;
// HttpResponseMessage response;
// for (int i = 0; i < 50; i++)
// {
// handler = new WinHttpHandler();
// response = SendRequestHelper.Send(handler, () => { });
// }
//}
public class CustomProxy : IWebProxy
{
private const string DefaultDomain = "domain";
private const string DefaultUsername = "username";
private const string DefaultPassword = "password";
private bool bypassAll;
private NetworkCredential networkCredential;
public CustomProxy(bool bypassAll)
{
this.bypassAll = bypassAll;
this.networkCredential = new NetworkCredential(CustomProxy.DefaultUsername, CustomProxy.DefaultPassword, CustomProxy.DefaultDomain);
}
public string UsernameWithDomain
{
get
{
return CustomProxy.DefaultDomain + "\\" + CustomProxy.DefaultUsername;
}
}
public string Password
{
get
{
return CustomProxy.DefaultPassword;
}
}
public NetworkCredential NetworkCredential
{
get
{
return this.networkCredential;
}
}
ICredentials IWebProxy.Credentials
{
get
{
return this.networkCredential;
}
set
{
}
}
Uri IWebProxy.GetProxy(Uri destination)
{
return new Uri(FakeProxy);
}
bool IWebProxy.IsBypassed(Uri host)
{
return this.bypassAll;
}
}
public class FakeDefaultWebProxy : IWebProxy
{
private ICredentials _credentials = null;
public FakeDefaultWebProxy()
{
}
public ICredentials Credentials
{
get
{
return _credentials;
}
set
{
_credentials = value;
}
}
// This is a sentinel object representing the internal default system proxy that a developer would
// use when accessing the System.Net.WebRequest.DefaultWebProxy property (from the System.Net.Requests
// package). It can't support the GetProxy or IsBypassed methods. WinHttpHandler will handle this
// exception and use the appropriate system default proxy.
public Uri GetProxy(Uri destination)
{
throw new PlatformNotSupportedException();
}
public bool IsBypassed(Uri host)
{
throw new PlatformNotSupportedException();
}
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="DataGridViewColumn.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Windows.Forms
{
using System;
using System.Text;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Globalization;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
/// <include file='doc\DataGridViewColumn.uex' path='docs/doc[@for="DataGridViewColumn"]/*' />
/// <devdoc>
/// <para> Base class for the columns in a data grid view.</para>
/// </devdoc>
[
Designer("System.Windows.Forms.Design.DataGridViewColumnDesigner, " + AssemblyRef.SystemDesign),
TypeConverterAttribute(typeof(DataGridViewColumnConverter)),
ToolboxItem(false),
DesignTimeVisible(false)
]
public class DataGridViewColumn : DataGridViewBand, IComponent
{
private const float DATAGRIDVIEWCOLUMN_defaultFillWeight = 100F;
private const int DATAGRIDVIEWCOLUMN_defaultWidth = 100;
private const int DATAGRIDVIEWCOLUMN_defaultMinColumnThickness = 5;
private const byte DATAGRIDVIEWCOLUMN_automaticSort = 0x01;
private const byte DATAGRIDVIEWCOLUMN_programmaticSort = 0x02;
private const byte DATAGRIDVIEWCOLUMN_isDataBound = 0x04;
private const byte DATAGRIDVIEWCOLUMN_isBrowsableInternal = 0x08;
private const byte DATAGRIDVIEWCOLUMN_displayIndexHasChangedInternal = 0x10;
private byte flags; // see DATAGRIDVIEWCOLUMN_ consts above
private DataGridViewCell cellTemplate;
private string name;
private int displayIndex;
private int desiredFillWidth = 0;
private int desiredMinimumWidth = 0;
private float fillWeight, usedFillWeight;
private DataGridViewAutoSizeColumnMode autoSizeMode;
private int boundColumnIndex = -1;
private string dataPropertyName = String.Empty;
private TypeConverter boundColumnConverter = null;
// needed for IComponent
private ISite site = null;
private EventHandler disposed = null;
private static readonly int PropDataGridViewColumnValueType = PropertyStore.CreateKey();
/// <include file='doc\DataGridViewColumn.uex' path='docs/doc[@for="DataGridViewColumn.DataGridViewColumn"]/*' />
/// <devdoc>
/// <para>
/// Initializes a new instance of the <see cref='System.Windows.Forms.DataGridViewColumn'/> class.
/// </para>
/// </devdoc>
public DataGridViewColumn() : this((DataGridViewCell) null)
{
}
/// <include file='doc\DataGridViewColumn.uex' path='docs/doc[@for="DataGridViewColumn.DataGridViewColumn3"]/*' />
public DataGridViewColumn(DataGridViewCell cellTemplate) : base()
{
this.fillWeight = DATAGRIDVIEWCOLUMN_defaultFillWeight;
this.usedFillWeight = DATAGRIDVIEWCOLUMN_defaultFillWeight;
this.Thickness = DATAGRIDVIEWCOLUMN_defaultWidth;
this.MinimumThickness = DATAGRIDVIEWCOLUMN_defaultMinColumnThickness;
this.name = String.Empty;
this.bandIsRow = false;
this.displayIndex = -1;
this.cellTemplate = cellTemplate;
this.autoSizeMode = DataGridViewAutoSizeColumnMode.NotSet;
}
/// <include file='doc\DataGridViewColumn.uex' path='docs/doc[@for="DataGridViewColumn.AutoSizeMode"]/*' />
[
SRCategory(SR.CatLayout),
DefaultValue(DataGridViewAutoSizeColumnMode.NotSet),
SRDescription(SR.DataGridViewColumn_AutoSizeModeDescr),
RefreshProperties(RefreshProperties.Repaint)
]
public DataGridViewAutoSizeColumnMode AutoSizeMode
{
get
{
return this.autoSizeMode;
}
set
{
switch (value)
{
case DataGridViewAutoSizeColumnMode.NotSet:
case DataGridViewAutoSizeColumnMode.None:
case DataGridViewAutoSizeColumnMode.ColumnHeader:
case DataGridViewAutoSizeColumnMode.AllCellsExceptHeader:
case DataGridViewAutoSizeColumnMode.AllCells:
case DataGridViewAutoSizeColumnMode.DisplayedCellsExceptHeader:
case DataGridViewAutoSizeColumnMode.DisplayedCells:
case DataGridViewAutoSizeColumnMode.Fill:
break;
default:
throw new InvalidEnumArgumentException("value", (int)value, typeof(DataGridViewAutoSizeColumnMode));
}
if (this.autoSizeMode != value)
{
if (this.Visible && this.DataGridView != null)
{
if (!this.DataGridView.ColumnHeadersVisible &&
(value == DataGridViewAutoSizeColumnMode.ColumnHeader ||
(value == DataGridViewAutoSizeColumnMode.NotSet && this.DataGridView.AutoSizeColumnsMode == DataGridViewAutoSizeColumnsMode.ColumnHeader)))
{
throw new InvalidOperationException(SR.GetString(SR.DataGridViewColumn_AutoSizeCriteriaCannotUseInvisibleHeaders));
}
if (this.Frozen &&
(value == DataGridViewAutoSizeColumnMode.Fill ||
(value == DataGridViewAutoSizeColumnMode.NotSet && this.DataGridView.AutoSizeColumnsMode == DataGridViewAutoSizeColumnsMode.Fill)))
{
// Cannot set the inherited auto size mode to Fill when the column is frozen
throw new InvalidOperationException(SR.GetString(SR.DataGridViewColumn_FrozenColumnCannotAutoFill));
}
}
DataGridViewAutoSizeColumnMode previousInheritedMode = this.InheritedAutoSizeMode;
bool previousInheritedModeAutoSized = previousInheritedMode != DataGridViewAutoSizeColumnMode.Fill &&
previousInheritedMode != DataGridViewAutoSizeColumnMode.None &&
previousInheritedMode != DataGridViewAutoSizeColumnMode.NotSet;
this.autoSizeMode = value;
if (this.DataGridView == null)
{
if (this.InheritedAutoSizeMode != DataGridViewAutoSizeColumnMode.Fill &&
this.InheritedAutoSizeMode != DataGridViewAutoSizeColumnMode.None &&
this.InheritedAutoSizeMode != DataGridViewAutoSizeColumnMode.NotSet)
{
if (!previousInheritedModeAutoSized)
{
// Save current column width for later reuse
this.CachedThickness = this.Thickness;
}
}
else
{
if (this.Thickness != this.CachedThickness && previousInheritedModeAutoSized)
{
// Restoring cached column width
this.ThicknessInternal = this.CachedThickness;
}
}
}
else
{
this.DataGridView.OnAutoSizeColumnModeChanged(this, previousInheritedMode);
}
}
}
}
// TypeConverter of the PropertyDescriptor attached to this column
// in databound cases. Null otherwise.
internal TypeConverter BoundColumnConverter
{
get
{
return this.boundColumnConverter;
}
set
{
this.boundColumnConverter = value;
}
}
internal int BoundColumnIndex
{
get
{
return this.boundColumnIndex;
}
set
{
this.boundColumnIndex = value;
}
}
/// <include file='doc\DataGridViewColumn.uex' path='docs/doc[@for="DataGridViewColumn.CellTemplate"]/*' />
[
Browsable(false),
EditorBrowsable(EditorBrowsableState.Advanced),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
]
public virtual DataGridViewCell CellTemplate
{
get
{
return this.cellTemplate;
}
set
{
this.cellTemplate = value;
}
}
/// <include file='doc\DataGridViewColumn.uex' path='docs/doc[@for="DataGridViewColumn.CellType"]/*' />
[
Browsable(false),
EditorBrowsable(EditorBrowsableState.Advanced),
]
public Type CellType
{
get
{
if (this.cellTemplate != null)
{
return this.cellTemplate.GetType();
}
else
{
return null;
}
}
}
/// <include file='doc\DataGridViewColumn.uex' path='docs/doc[@for="DataGridViewColumn.ContextMenuStrip"]/*' />
[
DefaultValue(null),
SRCategory(SR.CatBehavior),
SRDescription(SR.DataGridView_ColumnContextMenuStripDescr)
]
public override ContextMenuStrip ContextMenuStrip
{
get
{
return base.ContextMenuStrip;
}
set
{
base.ContextMenuStrip = value;
}
}
/// <include file='doc\DataGridViewColumn.uex' path='docs/doc[@for="DataGridViewColumn.DataPropertyName"]/*' />
[
Browsable(true),
DefaultValue(""),
TypeConverterAttribute("System.Windows.Forms.Design.DataMemberFieldConverter, " + AssemblyRef.SystemDesign),
Editor("System.Windows.Forms.Design.DataGridViewColumnDataPropertyNameEditor, " + AssemblyRef.SystemDesign, typeof(System.Drawing.Design.UITypeEditor)),
SRDescription(SR.DataGridView_ColumnDataPropertyNameDescr),
SRCategory(SR.CatData)
]
public string DataPropertyName
{
get
{
return this.dataPropertyName;
}
set
{
if (value == null)
{
value = String.Empty;
}
if (value != this.dataPropertyName)
{
this.dataPropertyName = value;
if (this.DataGridView != null)
{
this.DataGridView.OnColumnDataPropertyNameChanged(this);
}
}
}
}
/// <include file='doc\DataGridViewColumn.uex' path='docs/doc[@for="DataGridViewColumn.DefaultCellStyle"]/*' />
[
Browsable(true),
SRCategory(SR.CatAppearance),
SRDescription(SR.DataGridView_ColumnDefaultCellStyleDescr)
]
public override DataGridViewCellStyle DefaultCellStyle
{
get
{
return base.DefaultCellStyle;
}
set
{
base.DefaultCellStyle = value;
}
}
private bool ShouldSerializeDefaultCellStyle()
{
if (!this.HasDefaultCellStyle)
{
return false;
}
DataGridViewCellStyle defaultCellStyle = this.DefaultCellStyle;
return (!defaultCellStyle.BackColor.IsEmpty ||
!defaultCellStyle.ForeColor.IsEmpty ||
!defaultCellStyle.SelectionBackColor.IsEmpty ||
!defaultCellStyle.SelectionForeColor.IsEmpty ||
defaultCellStyle.Font != null ||
!defaultCellStyle.IsNullValueDefault ||
!defaultCellStyle.IsDataSourceNullValueDefault ||
!String.IsNullOrEmpty(defaultCellStyle.Format) ||
!defaultCellStyle.FormatProvider.Equals(System.Globalization.CultureInfo.CurrentCulture) ||
defaultCellStyle.Alignment != DataGridViewContentAlignment.NotSet ||
defaultCellStyle.WrapMode != DataGridViewTriState.NotSet ||
defaultCellStyle.Tag != null ||
!defaultCellStyle.Padding.Equals(Padding.Empty));
}
internal int DesiredFillWidth
{
get
{
return this.desiredFillWidth;
}
set
{
this.desiredFillWidth = value;
}
}
internal int DesiredMinimumWidth
{
get
{
return this.desiredMinimumWidth;
}
set
{
this.desiredMinimumWidth = value;
}
}
/// <include file='doc\DataGridViewColumn.uex' path='docs/doc[@for="DataGridViewColumn.DisplayIndex"]/*' />
[
Browsable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
]
public int DisplayIndex
{
get
{
return this.displayIndex;
}
set
{
if (this.displayIndex != value)
{
if (value == Int32.MaxValue)
{
throw new ArgumentOutOfRangeException("DisplayIndex", value, SR.GetString(SR.DataGridViewColumn_DisplayIndexTooLarge, Int32.MaxValue.ToString(CultureInfo.CurrentCulture)));
}
if (this.DataGridView != null)
{
if (value < 0)
{
throw new ArgumentOutOfRangeException("DisplayIndex", value, SR.GetString(SR.DataGridViewColumn_DisplayIndexNegative));
}
if (value >= this.DataGridView.Columns.Count)
{
throw new ArgumentOutOfRangeException("DisplayIndex", value, SR.GetString(SR.DataGridViewColumn_DisplayIndexExceedsColumnCount));
}
// Will throw an error if a visible frozen column is placed inside a non-frozen area or vice-versa.
this.DataGridView.OnColumnDisplayIndexChanging(this, value);
this.displayIndex = value;
try
{
this.DataGridView.InDisplayIndexAdjustments = true;
this.DataGridView.OnColumnDisplayIndexChanged_PreNotification();
this.DataGridView.OnColumnDisplayIndexChanged(this);
this.DataGridView.OnColumnDisplayIndexChanged_PostNotification();
}
finally
{
this.DataGridView.InDisplayIndexAdjustments = false;
}
}
else
{
if (value < -1)
{
throw new ArgumentOutOfRangeException("DisplayIndex", value, SR.GetString(SR.DataGridViewColumn_DisplayIndexTooNegative));
}
this.displayIndex = value;
}
}
}
}
internal bool DisplayIndexHasChanged
{
get
{
return (this.flags & DATAGRIDVIEWCOLUMN_displayIndexHasChangedInternal) != 0;
}
set
{
if (value)
{
this.flags |= (byte) DATAGRIDVIEWCOLUMN_displayIndexHasChangedInternal;
}
else
{
this.flags = (byte)(this.flags & ~DATAGRIDVIEWCOLUMN_displayIndexHasChangedInternal);
}
}
}
internal int DisplayIndexInternal
{
set
{
Debug.Assert(value >= -1);
Debug.Assert(value < Int32.MaxValue);
this.displayIndex = value;
}
}
/// <include file='doc\DataGridViewColumn.uex' path='docs/doc[@for="DataGridViewColumn.Disposed"]/*' />
[
Browsable(false),
EditorBrowsable(EditorBrowsableState.Advanced)
]
public event EventHandler Disposed
{
add
{
this.disposed += value;
}
remove
{
this.disposed -= value;
}
}
/// <include file='doc\DataGridViewColumn.uex' path='docs/doc[@for="DataGridViewColumn.DividerWidth"]/*' />
[
DefaultValue(0),
SRCategory(SR.CatLayout),
SRDescription(SR.DataGridView_ColumnDividerWidthDescr)
]
public int DividerWidth
{
get
{
return this.DividerThickness;
}
set
{
this.DividerThickness = value;
}
}
/// <include file='doc\DataGridViewColumn.uex' path='docs/doc[@for="DataGridViewColumn.FillWeight"]/*' />
[
SRCategory(SR.CatLayout),
DefaultValue(DATAGRIDVIEWCOLUMN_defaultFillWeight),
SRDescription(SR.DataGridViewColumn_FillWeightDescr),
]
public float FillWeight
{
get
{
return this.fillWeight;
}
set
{
if (value <= 0)
{
throw new ArgumentOutOfRangeException("FillWeight", SR.GetString(SR.InvalidLowBoundArgument, "FillWeight", (value).ToString(CultureInfo.CurrentCulture), (0).ToString(CultureInfo.CurrentCulture)));
}
if (value > (float)ushort.MaxValue)
{
throw new ArgumentOutOfRangeException("FillWeight", SR.GetString(SR.InvalidHighBoundArgumentEx, "FillWeight", (value).ToString(CultureInfo.CurrentCulture), (ushort.MaxValue).ToString(CultureInfo.CurrentCulture)));
}
if (this.DataGridView != null)
{
this.DataGridView.OnColumnFillWeightChanging(this, value);
this.fillWeight = value;
this.DataGridView.OnColumnFillWeightChanged(this);
}
else
{
this.fillWeight = value;
}
}
}
internal float FillWeightInternal
{
set
{
Debug.Assert(value > 0);
this.fillWeight = value;
}
}
/// <include file='doc\DataGridViewColumn.uex' path='docs/doc[@for="DataGridViewColumn.Frozen"]/*' />
[
DefaultValue(false),
RefreshProperties(RefreshProperties.All),
SRCategory(SR.CatLayout),
SRDescription(SR.DataGridView_ColumnFrozenDescr)
]
public override bool Frozen
{
get
{
return base.Frozen;
}
set
{
base.Frozen = value;
}
}
/// <include file='doc\DataGridViewColumn.uex' path='docs/doc[@for="DataGridViewColumn.HeaderCell"]/*' />
[
Browsable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
]
public DataGridViewColumnHeaderCell HeaderCell
{
get
{
return (DataGridViewColumnHeaderCell) base.HeaderCellCore;
}
set
{
base.HeaderCellCore = value;
}
}
/// <include file='doc\DataGridViewColumn.uex' path='docs/doc[@for="DataGridViewColumn.HeaderText"]/*' />
[
SRCategory(SR.CatAppearance),
SRDescription(SR.DataGridView_ColumnHeaderTextDescr),
Localizable(true)
]
public string HeaderText
{
get
{
if (this.HasHeaderCell)
{
string headerValue = this.HeaderCell.Value as string;
if (headerValue != null)
{
return headerValue;
}
else
{
return string.Empty;
}
}
else
{
return string.Empty;
}
}
set
{
if ((value != null || this.HasHeaderCell) &&
this.HeaderCell.ValueType != null &&
this.HeaderCell.ValueType.IsAssignableFrom(typeof(System.String)))
{
this.HeaderCell.Value = value;
}
}
}
private bool ShouldSerializeHeaderText()
{
return this.HasHeaderCell && ((DataGridViewColumnHeaderCell) this.HeaderCell).ContainsLocalValue;
}
/// <include file='doc\DataGridViewColumn.uex' path='docs/doc[@for="DataGridViewColumn.InheritedAutoSizeMode"]/*' />
[
Browsable(false),
EditorBrowsable(EditorBrowsableState.Advanced),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
]
public DataGridViewAutoSizeColumnMode InheritedAutoSizeMode
{
get
{
return GetInheritedAutoSizeMode(this.DataGridView);
}
}
/// <include file='doc\DataGridViewColumn.uex' path='docs/doc[@for="DataGridViewColumn.InheritedStyle"]/*' />
[
Browsable(false)
]
public override DataGridViewCellStyle InheritedStyle
{
get
{
DataGridViewCellStyle columnStyle = null;
Debug.Assert(this.Index > -1);
if (this.HasDefaultCellStyle)
{
columnStyle = this.DefaultCellStyle;
Debug.Assert(columnStyle != null);
}
if (this.DataGridView == null)
{
return columnStyle;
}
DataGridViewCellStyle inheritedCellStyleTmp = new DataGridViewCellStyle();
DataGridViewCellStyle dataGridViewStyle = this.DataGridView.DefaultCellStyle;
Debug.Assert(dataGridViewStyle != null);
if (columnStyle != null && !columnStyle.BackColor.IsEmpty)
{
inheritedCellStyleTmp.BackColor = columnStyle.BackColor;
}
else
{
inheritedCellStyleTmp.BackColor = dataGridViewStyle.BackColor;
}
if (columnStyle != null && !columnStyle.ForeColor.IsEmpty)
{
inheritedCellStyleTmp.ForeColor = columnStyle.ForeColor;
}
else
{
inheritedCellStyleTmp.ForeColor = dataGridViewStyle.ForeColor;
}
if (columnStyle != null && !columnStyle.SelectionBackColor.IsEmpty)
{
inheritedCellStyleTmp.SelectionBackColor = columnStyle.SelectionBackColor;
}
else
{
inheritedCellStyleTmp.SelectionBackColor = dataGridViewStyle.SelectionBackColor;
}
if (columnStyle != null && !columnStyle.SelectionForeColor.IsEmpty)
{
inheritedCellStyleTmp.SelectionForeColor = columnStyle.SelectionForeColor;
}
else
{
inheritedCellStyleTmp.SelectionForeColor = dataGridViewStyle.SelectionForeColor;
}
if (columnStyle != null && columnStyle.Font != null)
{
inheritedCellStyleTmp.Font = columnStyle.Font;
}
else
{
inheritedCellStyleTmp.Font = dataGridViewStyle.Font;
}
if (columnStyle != null && !columnStyle.IsNullValueDefault)
{
inheritedCellStyleTmp.NullValue = columnStyle.NullValue;
}
else
{
inheritedCellStyleTmp.NullValue = dataGridViewStyle.NullValue;
}
if (columnStyle != null && !columnStyle.IsDataSourceNullValueDefault)
{
inheritedCellStyleTmp.DataSourceNullValue = columnStyle.DataSourceNullValue;
}
else
{
inheritedCellStyleTmp.DataSourceNullValue = dataGridViewStyle.DataSourceNullValue;
}
if (columnStyle != null && columnStyle.Format.Length != 0)
{
inheritedCellStyleTmp.Format = columnStyle.Format;
}
else
{
inheritedCellStyleTmp.Format = dataGridViewStyle.Format;
}
if (columnStyle != null && !columnStyle.IsFormatProviderDefault)
{
inheritedCellStyleTmp.FormatProvider = columnStyle.FormatProvider;
}
else
{
inheritedCellStyleTmp.FormatProvider = dataGridViewStyle.FormatProvider;
}
if (columnStyle != null && columnStyle.Alignment != DataGridViewContentAlignment.NotSet)
{
inheritedCellStyleTmp.AlignmentInternal = columnStyle.Alignment;
}
else
{
Debug.Assert(dataGridViewStyle.Alignment != DataGridViewContentAlignment.NotSet);
inheritedCellStyleTmp.AlignmentInternal = dataGridViewStyle.Alignment;
}
if (columnStyle != null && columnStyle.WrapMode != DataGridViewTriState.NotSet)
{
inheritedCellStyleTmp.WrapModeInternal = columnStyle.WrapMode;
}
else
{
Debug.Assert(dataGridViewStyle.WrapMode != DataGridViewTriState.NotSet);
inheritedCellStyleTmp.WrapModeInternal = dataGridViewStyle.WrapMode;
}
if (columnStyle != null && columnStyle.Tag != null)
{
inheritedCellStyleTmp.Tag = columnStyle.Tag;
}
else
{
inheritedCellStyleTmp.Tag = dataGridViewStyle.Tag;
}
if (columnStyle != null && columnStyle.Padding != Padding.Empty)
{
inheritedCellStyleTmp.PaddingInternal = columnStyle.Padding;
}
else
{
inheritedCellStyleTmp.PaddingInternal = dataGridViewStyle.Padding;
}
return inheritedCellStyleTmp;
}
}
internal bool IsBrowsableInternal
{
get
{
return (this.flags & DATAGRIDVIEWCOLUMN_isBrowsableInternal) != 0;
}
set
{
if (value)
{
this.flags |= (byte) DATAGRIDVIEWCOLUMN_isBrowsableInternal;
}
else
{
this.flags = (byte)(this.flags & ~DATAGRIDVIEWCOLUMN_isBrowsableInternal);
}
}
}
/// <include file='doc\DataGridViewColumn.uex' path='docs/doc[@for="DataGridViewColumn.IsDataBound"]/*' />
[
Browsable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
]
public bool IsDataBound
{
get
{
return this.IsDataBoundInternal;
}
}
internal bool IsDataBoundInternal
{
get
{
return (this.flags & DATAGRIDVIEWCOLUMN_isDataBound) != 0;
}
set
{
if (value)
{
this.flags |= (byte)DATAGRIDVIEWCOLUMN_isDataBound;
}
else
{
this.flags = (byte)(this.flags & ~DATAGRIDVIEWCOLUMN_isDataBound);
}
}
}
/// <include file='doc\DataGridViewColumn.uex' path='docs/doc[@for="DataGridViewColumn.MinimumWidth"]/*' />
[
DefaultValue(DATAGRIDVIEWCOLUMN_defaultMinColumnThickness),
Localizable(true),
SRCategory(SR.CatLayout),
SRDescription(SR.DataGridView_ColumnMinimumWidthDescr),
RefreshProperties(RefreshProperties.Repaint)
]
public int MinimumWidth
{
get
{
return this.MinimumThickness;
}
set
{
this.MinimumThickness = value;
}
}
/// <include file='doc\DataGridViewColumn.uex' path='docs/doc[@for="DataGridViewColumn.Name"]/*' />
[
Browsable(false)
]
public string Name
{
get
{
//
// Change needed to bring the design time and the runtime "Name" property together.
// The ExtenderProvider adds a "Name" property of its own. It does this for all IComponents.
// The "Name" property added by the ExtenderProvider interacts only w/ the Site property.
// The Control class' Name property can be changed only thru the "Name" property provided by the
// Extender Service.
//
// However, the user can change the DataGridView::Name property in the DataGridViewEditColumnDialog.
// So while the Control can fall back to Site.Name if the user did not explicitly set Control::Name,
// the DataGridViewColumn should always go first to the Site.Name to retrieve the name.
//
// NOTE: one side effect of bringing together the design time and the run time "Name" properties is that DataGridViewColumn::Name changes.
// However, DataGridView does not fire ColumnNameChanged event.
// We can't fix this because ISite does not provide Name change notification. So in effect
// DataGridViewColumn does not know when its name changed.
// I talked w/ MarkRi and he is perfectly fine w/ DataGridViewColumn::Name changing w/o ColumnNameChanged
// being fired.
//
if (this.Site != null && !String.IsNullOrEmpty(this.Site.Name))
{
this.name = this.Site.Name;
}
return name;
}
set
{
string oldName = this.name;
if (String.IsNullOrEmpty(value))
{
this.name = string.Empty;
}
else
{
this.name = value;
}
if (this.DataGridView != null && !string.Equals(this.name, oldName,StringComparison.Ordinal))
{
this.DataGridView.OnColumnNameChanged(this);
}
}
}
/// <include file='doc\DataGridViewColumn.uex' path='docs/doc[@for="DataGridViewColumn.ReadOnly"]/*' />
[
SRCategory(SR.CatBehavior),
SRDescription(SR.DataGridView_ColumnReadOnlyDescr)
]
public override bool ReadOnly
{
get
{
return base.ReadOnly;
}
set
{
if (this.IsDataBound &&
this.DataGridView != null &&
this.DataGridView.DataConnection != null &&
this.boundColumnIndex != -1 &&
this.DataGridView.DataConnection.DataFieldIsReadOnly(this.boundColumnIndex) &&
!value)
{
throw new InvalidOperationException(SR.GetString(SR.DataGridView_ColumnBoundToAReadOnlyFieldMustRemainReadOnly));
}
base.ReadOnly = value;
}
}
/// <include file='doc\DataGridViewColumn.uex' path='docs/doc[@for="DataGridViewColumn.Resizable"]/*' />
[
SRCategory(SR.CatBehavior),
SRDescription(SR.DataGridView_ColumnResizableDescr)
]
public override DataGridViewTriState Resizable
{
get
{
return base.Resizable;
}
set
{
base.Resizable = value;
}
}
/// <include file='doc\DataGridViewColumn.uex' path='docs/doc[@for="DataGridViewColumn.Site"]/*' />
[
Browsable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
]
public ISite Site
{
get
{
return this.site;
}
set
{
this.site = value;
}
}
/// <include file='doc\DataGridViewColumn.uex' path='docs/doc[@for="DataGridViewColumn.SortMode"]/*' />
[
DefaultValue(DataGridViewColumnSortMode.NotSortable),
SRCategory(SR.CatBehavior),
SRDescription(SR.DataGridView_ColumnSortModeDescr)
]
public DataGridViewColumnSortMode SortMode
{
get
{
if ((this.flags & DATAGRIDVIEWCOLUMN_automaticSort) != 0x00)
{
return DataGridViewColumnSortMode.Automatic;
}
else if ((this.flags & DATAGRIDVIEWCOLUMN_programmaticSort) != 0x00)
{
return DataGridViewColumnSortMode.Programmatic;
}
else
{
return DataGridViewColumnSortMode.NotSortable;
}
}
set
{
if (value != this.SortMode)
{
if (value != DataGridViewColumnSortMode.NotSortable)
{
if (this.DataGridView != null &&
!this.DataGridView.InInitialization &&
value == DataGridViewColumnSortMode.Automatic &&
(this.DataGridView.SelectionMode == DataGridViewSelectionMode.FullColumnSelect ||
this.DataGridView.SelectionMode == DataGridViewSelectionMode.ColumnHeaderSelect))
{
throw new InvalidOperationException(SR.GetString(SR.DataGridViewColumn_SortModeAndSelectionModeClash, (value).ToString(), this.DataGridView.SelectionMode.ToString()));
}
if (value == DataGridViewColumnSortMode.Automatic)
{
this.flags = (byte)(this.flags & ~DATAGRIDVIEWCOLUMN_programmaticSort);
this.flags |= (byte)DATAGRIDVIEWCOLUMN_automaticSort;
}
else
{
this.flags = (byte)(this.flags & ~DATAGRIDVIEWCOLUMN_automaticSort);
this.flags |= (byte)DATAGRIDVIEWCOLUMN_programmaticSort;
}
}
else
{
this.flags = (byte)(this.flags & ~DATAGRIDVIEWCOLUMN_automaticSort);
this.flags = (byte)(this.flags & ~DATAGRIDVIEWCOLUMN_programmaticSort);
}
if (this.DataGridView != null)
{
this.DataGridView.OnColumnSortModeChanged(this);
}
}
}
}
/// <include file='doc\DataGridViewColumn.uex' path='docs/doc[@for="DataGridViewColumn.ToolTipText"]/*' />
[
DefaultValue(""),
Localizable(true),
SRCategory(SR.CatAppearance),
SRDescription(SR.DataGridView_ColumnToolTipTextDescr)
]
public string ToolTipText
{
get
{
return this.HeaderCell.ToolTipText;
}
set
{
if (String.Compare(this.ToolTipText, value, false /*ignore case*/, CultureInfo.InvariantCulture) != 0)
{
this.HeaderCell.ToolTipText = value;
if (this.DataGridView != null)
{
this.DataGridView.OnColumnToolTipTextChanged(this);
}
}
}
}
internal float UsedFillWeight
{
get
{
return this.usedFillWeight;
}
set
{
Debug.Assert(value > 0);
this.usedFillWeight = value;
}
}
/// <include file='doc\DataGridViewColumn.uex' path='docs/doc[@for="DataGridViewColumn.ValueType"]/*' />
[
Browsable(false),
DefaultValue(null),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
]
public Type ValueType
{
get
{
return (Type) this.Properties.GetObject(PropDataGridViewColumnValueType);
}
set
{
// what should we do when we modify the ValueType in the dataGridView column???
this.Properties.SetObject(PropDataGridViewColumnValueType, value);
}
}
/// <include file='doc\DataGridViewColumn.uex' path='docs/doc[@for="DataGridViewColumn.Visible"]/*' />
[
DefaultValue(true),
Localizable(true),
SRCategory(SR.CatAppearance),
SRDescription(SR.DataGridView_ColumnVisibleDescr)
]
public override bool Visible
{
get
{
return base.Visible;
}
set
{
base.Visible = value;
}
}
/// <include file='doc\DataGridViewColumn.uex' path='docs/doc[@for="DataGridViewColumn.Width"]/*' />
[
SRCategory(SR.CatLayout),
Localizable(true),
SRDescription(SR.DataGridView_ColumnWidthDescr),
RefreshProperties(RefreshProperties.Repaint)
]
public int Width
{
get
{
return this.Thickness;
}
set
{
this.Thickness = value;
}
}
/// <include file='doc\DataGridViewColumn.uex' path='docs/doc[@for="DataGridViewColumn.Clone"]/*' />
public override object Clone()
{
// SECREVIEW : Late-binding does not represent a security thread, see bug#411899 for more info..
//
DataGridViewColumn dataGridViewColumn = (DataGridViewColumn) System.Activator.CreateInstance(this.GetType());
if (dataGridViewColumn != null)
{
CloneInternal(dataGridViewColumn);
}
return dataGridViewColumn;
}
internal void CloneInternal(DataGridViewColumn dataGridViewColumn)
{
base.CloneInternal(dataGridViewColumn);
dataGridViewColumn.name = this.Name;
dataGridViewColumn.displayIndex = -1;
dataGridViewColumn.HeaderText = this.HeaderText;
dataGridViewColumn.DataPropertyName = this.DataPropertyName;
// dataGridViewColumn.boundColumnConverter = columnTemplate.BoundColumnConverter; setting the DataPropertyName should also set the bound column converter later on.
if (dataGridViewColumn.CellTemplate != null)
{
dataGridViewColumn.cellTemplate = (DataGridViewCell)this.CellTemplate.Clone();
}
else
{
dataGridViewColumn.cellTemplate = null;
}
if (this.HasHeaderCell)
{
dataGridViewColumn.HeaderCell = (DataGridViewColumnHeaderCell) this.HeaderCell.Clone();
}
dataGridViewColumn.AutoSizeMode = this.AutoSizeMode;
dataGridViewColumn.SortMode = this.SortMode;
dataGridViewColumn.FillWeightInternal = this.FillWeight;
}
/// <include file='doc\DataGridViewColumn.uex' path='docs/doc[@for="DataGridViewColumn.Dispose"]/*' />
protected override void Dispose(bool disposing) {
try
{
if (disposing)
{
//
lock(this)
{
if (this.site != null && this.site.Container != null)
{
this.site.Container.Remove(this);
}
if (this.disposed != null)
{
this.disposed(this, EventArgs.Empty);
}
}
}
}
finally
{
base.Dispose(disposing);
}
}
internal DataGridViewAutoSizeColumnMode GetInheritedAutoSizeMode(DataGridView dataGridView)
{
if (dataGridView != null && this.autoSizeMode == DataGridViewAutoSizeColumnMode.NotSet)
{
switch (dataGridView.AutoSizeColumnsMode)
{
case DataGridViewAutoSizeColumnsMode.AllCells:
return DataGridViewAutoSizeColumnMode.AllCells;
case DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader:
return DataGridViewAutoSizeColumnMode.AllCellsExceptHeader;
case DataGridViewAutoSizeColumnsMode.DisplayedCells:
return DataGridViewAutoSizeColumnMode.DisplayedCells;
case DataGridViewAutoSizeColumnsMode.DisplayedCellsExceptHeader:
return DataGridViewAutoSizeColumnMode.DisplayedCellsExceptHeader;
case DataGridViewAutoSizeColumnsMode.ColumnHeader:
return DataGridViewAutoSizeColumnMode.ColumnHeader;
case DataGridViewAutoSizeColumnsMode.Fill:
return DataGridViewAutoSizeColumnMode.Fill;
default: // None
return DataGridViewAutoSizeColumnMode.None;
}
}
return this.autoSizeMode;
}
/// <include file='doc\DataGridViewColumn.uex' path='docs/doc[@for="DataGridViewColumn.GetPreferredWidth"]/*' />
public virtual int GetPreferredWidth(DataGridViewAutoSizeColumnMode autoSizeColumnMode, bool fixedHeight)
{
if (autoSizeColumnMode == DataGridViewAutoSizeColumnMode.NotSet ||
autoSizeColumnMode == DataGridViewAutoSizeColumnMode.None ||
autoSizeColumnMode == DataGridViewAutoSizeColumnMode.Fill)
{
throw new ArgumentException(SR.GetString(SR.DataGridView_NeedColumnAutoSizingCriteria, "autoSizeColumnMode"));
}
switch (autoSizeColumnMode) {
case DataGridViewAutoSizeColumnMode.NotSet:
case DataGridViewAutoSizeColumnMode.None:
case DataGridViewAutoSizeColumnMode.ColumnHeader:
case DataGridViewAutoSizeColumnMode.AllCellsExceptHeader:
case DataGridViewAutoSizeColumnMode.AllCells:
case DataGridViewAutoSizeColumnMode.DisplayedCellsExceptHeader:
case DataGridViewAutoSizeColumnMode.DisplayedCells:
case DataGridViewAutoSizeColumnMode.Fill:
break;
default:
throw new InvalidEnumArgumentException("value", (int) autoSizeColumnMode, typeof(DataGridViewAutoSizeColumnMode));
}
DataGridView dataGridView = this.DataGridView;
Debug.Assert(dataGridView == null || this.Index > -1);
if (dataGridView == null)
{
return -1;
}
DataGridViewAutoSizeColumnCriteriaInternal autoSizeColumnCriteriaInternal = (DataGridViewAutoSizeColumnCriteriaInternal) autoSizeColumnMode;
Debug.Assert(autoSizeColumnCriteriaInternal == DataGridViewAutoSizeColumnCriteriaInternal.Header ||
autoSizeColumnCriteriaInternal == DataGridViewAutoSizeColumnCriteriaInternal.AllRows ||
autoSizeColumnCriteriaInternal == DataGridViewAutoSizeColumnCriteriaInternal.DisplayedRows ||
autoSizeColumnCriteriaInternal == (DataGridViewAutoSizeColumnCriteriaInternal.Header | DataGridViewAutoSizeColumnCriteriaInternal.AllRows) ||
autoSizeColumnCriteriaInternal == (DataGridViewAutoSizeColumnCriteriaInternal.Header | DataGridViewAutoSizeColumnCriteriaInternal.DisplayedRows));
int preferredColumnThickness = 0, preferredCellThickness, rowIndex;
DataGridViewRow dataGridViewRow;
Debug.Assert(dataGridView.ColumnHeadersVisible || autoSizeColumnCriteriaInternal != DataGridViewAutoSizeColumnCriteriaInternal.Header);
// take into account the preferred width of the header cell if displayed and cared about
if (dataGridView.ColumnHeadersVisible &&
(autoSizeColumnCriteriaInternal & DataGridViewAutoSizeColumnCriteriaInternal.Header) != 0)
{
if (fixedHeight)
{
preferredCellThickness = this.HeaderCell.GetPreferredWidth(-1, dataGridView.ColumnHeadersHeight);
}
else
{
preferredCellThickness = this.HeaderCell.GetPreferredSize(-1).Width;
}
if (preferredColumnThickness < preferredCellThickness)
{
preferredColumnThickness = preferredCellThickness;
}
}
if ((autoSizeColumnCriteriaInternal & DataGridViewAutoSizeColumnCriteriaInternal.AllRows) != 0)
{
for (rowIndex = dataGridView.Rows.GetFirstRow(DataGridViewElementStates.Visible);
rowIndex != -1;
rowIndex = dataGridView.Rows.GetNextRow(rowIndex, DataGridViewElementStates.Visible))
{
dataGridViewRow = dataGridView.Rows.SharedRow(rowIndex);
if (fixedHeight)
{
preferredCellThickness = dataGridViewRow.Cells[this.Index].GetPreferredWidth(rowIndex, dataGridViewRow.Thickness);
}
else
{
preferredCellThickness = dataGridViewRow.Cells[this.Index].GetPreferredSize(rowIndex).Width;
}
if (preferredColumnThickness < preferredCellThickness)
{
preferredColumnThickness = preferredCellThickness;
}
}
}
else if ((autoSizeColumnCriteriaInternal & DataGridViewAutoSizeColumnCriteriaInternal.DisplayedRows) != 0)
{
int displayHeight = dataGridView.LayoutInfo.Data.Height;
int cy = 0;
rowIndex = dataGridView.Rows.GetFirstRow(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen);
while (rowIndex != -1 && cy < displayHeight)
{
dataGridViewRow = dataGridView.Rows.SharedRow(rowIndex);
if (fixedHeight)
{
preferredCellThickness = dataGridViewRow.Cells[this.Index].GetPreferredWidth(rowIndex, dataGridViewRow.Thickness);
}
else
{
preferredCellThickness = dataGridViewRow.Cells[this.Index].GetPreferredSize(rowIndex).Width;
}
if (preferredColumnThickness < preferredCellThickness)
{
preferredColumnThickness = preferredCellThickness;
}
cy += dataGridViewRow.Thickness;
rowIndex = dataGridView.Rows.GetNextRow(rowIndex,
DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen);
}
if (cy < displayHeight)
{
rowIndex = dataGridView.DisplayedBandsInfo.FirstDisplayedScrollingRow;
while (rowIndex != -1 && cy < displayHeight)
{
dataGridViewRow = dataGridView.Rows.SharedRow(rowIndex);
if (fixedHeight)
{
preferredCellThickness = dataGridViewRow.Cells[this.Index].GetPreferredWidth(rowIndex, dataGridViewRow.Thickness);
}
else
{
preferredCellThickness = dataGridViewRow.Cells[this.Index].GetPreferredSize(rowIndex).Width;
}
if (preferredColumnThickness < preferredCellThickness)
{
preferredColumnThickness = preferredCellThickness;
}
cy += dataGridViewRow.Thickness;
rowIndex = dataGridView.Rows.GetNextRow(rowIndex, DataGridViewElementStates.Visible);
}
}
}
return preferredColumnThickness;
}
/// <include file='doc\DataGridViewColumn.uex' path='docs/doc[@for="DataGridViewColumn.ToString"]/*' />
public override string ToString()
{
StringBuilder sb = new StringBuilder(64);
sb.Append("DataGridViewColumn { Name=");
sb.Append(this.Name);
sb.Append(", Index=");
sb.Append(this.Index.ToString(CultureInfo.CurrentCulture));
sb.Append(" }");
return sb.ToString();
}
}
}
| |
/*
* Qa full api
*
* No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
*
* OpenAPI spec version: all
*
* 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 NUnit.Framework;
using System;
using System.Linq;
using System.IO;
using System.Collections.Generic;
using HostMe.Sdk.Api;
using HostMe.Sdk.Model;
using HostMe.Sdk.Client;
using System.Reflection;
namespace HostMe.Sdk.Test
{
/// <summary>
/// Class for testing ReservationHostList
/// </summary>
/// <remarks>
/// This file is automatically generated by Swagger Codegen.
/// Please update the test case below to test the model.
/// </remarks>
[TestFixture]
public class ReservationHostListTests
{
// TODO uncomment below to declare an instance variable for ReservationHostList
//private ReservationHostList instance;
/// <summary>
/// Setup before each test
/// </summary>
[SetUp]
public void Init()
{
// TODO uncomment below to create an instance of ReservationHostList
//instance = new ReservationHostList();
}
/// <summary>
/// Clean up after each test
/// </summary>
[TearDown]
public void Cleanup()
{
}
/// <summary>
/// Test an instance of ReservationHostList
/// </summary>
[Test]
public void ReservationHostListInstanceTest()
{
// TODO uncomment below to test "IsInstanceOfType" ReservationHostList
//Assert.IsInstanceOfType<ReservationHostList> (instance, "variable 'instance' is a ReservationHostList");
}
/// <summary>
/// Test the property 'Id'
/// </summary>
[Test]
public void IdTest()
{
// TODO unit test for the property 'Id'
}
/// <summary>
/// Test the property 'Created'
/// </summary>
[Test]
public void CreatedTest()
{
// TODO unit test for the property 'Created'
}
/// <summary>
/// Test the property 'Closed'
/// </summary>
[Test]
public void ClosedTest()
{
// TODO unit test for the property 'Closed'
}
/// <summary>
/// Test the property 'CustomerName'
/// </summary>
[Test]
public void CustomerNameTest()
{
// TODO unit test for the property 'CustomerName'
}
/// <summary>
/// Test the property 'ReservationTime'
/// </summary>
[Test]
public void ReservationTimeTest()
{
// TODO unit test for the property 'ReservationTime'
}
/// <summary>
/// Test the property 'GroupSize'
/// </summary>
[Test]
public void GroupSizeTest()
{
// TODO unit test for the property 'GroupSize'
}
/// <summary>
/// Test the property 'Phone'
/// </summary>
[Test]
public void PhoneTest()
{
// TODO unit test for the property 'Phone'
}
/// <summary>
/// Test the property 'Status'
/// </summary>
[Test]
public void StatusTest()
{
// TODO unit test for the property 'Status'
}
/// <summary>
/// Test the property 'Areas'
/// </summary>
[Test]
public void AreasTest()
{
// TODO unit test for the property 'Areas'
}
/// <summary>
/// Test the property 'InternalNotes'
/// </summary>
[Test]
public void InternalNotesTest()
{
// TODO unit test for the property 'InternalNotes'
}
/// <summary>
/// Test the property 'SpecialRequests'
/// </summary>
[Test]
public void SpecialRequestsTest()
{
// TODO unit test for the property 'SpecialRequests'
}
/// <summary>
/// Test the property 'AboutGuestNotes'
/// </summary>
[Test]
public void AboutGuestNotesTest()
{
// TODO unit test for the property 'AboutGuestNotes'
}
/// <summary>
/// Test the property 'TableNumber'
/// </summary>
[Test]
public void TableNumberTest()
{
// TODO unit test for the property 'TableNumber'
}
/// <summary>
/// Test the property 'Email'
/// </summary>
[Test]
public void EmailTest()
{
// TODO unit test for the property 'Email'
}
/// <summary>
/// Test the property 'Source'
/// </summary>
[Test]
public void SourceTest()
{
// TODO unit test for the property 'Source'
}
/// <summary>
/// Test the property 'EstimatedReleaseTime'
/// </summary>
[Test]
public void EstimatedReleaseTimeTest()
{
// TODO unit test for the property 'EstimatedReleaseTime'
}
/// <summary>
/// Test the property 'RegistrationTime'
/// </summary>
[Test]
public void RegistrationTimeTest()
{
// TODO unit test for the property 'RegistrationTime'
}
/// <summary>
/// Test the property 'EstimatedTurnOverTime'
/// </summary>
[Test]
public void EstimatedTurnOverTimeTest()
{
// TODO unit test for the property 'EstimatedTurnOverTime'
}
/// <summary>
/// Test the property 'Membership'
/// </summary>
[Test]
public void MembershipTest()
{
// TODO unit test for the property 'Membership'
}
/// <summary>
/// Test the property 'UnreadMessageCount'
/// </summary>
[Test]
public void UnreadMessageCountTest()
{
// TODO unit test for the property 'UnreadMessageCount'
}
/// <summary>
/// Test the property 'Party'
/// </summary>
[Test]
public void PartyTest()
{
// TODO unit test for the property 'Party'
}
/// <summary>
/// Test the property 'PartyTypes'
/// </summary>
[Test]
public void PartyTypesTest()
{
// TODO unit test for the property 'PartyTypes'
}
/// <summary>
/// Test the property 'Booth'
/// </summary>
[Test]
public void BoothTest()
{
// TODO unit test for the property 'Booth'
}
/// <summary>
/// Test the property 'HighTop'
/// </summary>
[Test]
public void HighTopTest()
{
// TODO unit test for the property 'HighTop'
}
/// <summary>
/// Test the property 'Table'
/// </summary>
[Test]
public void TableTest()
{
// TODO unit test for the property 'Table'
}
/// <summary>
/// Test the property 'HandicapAccessible'
/// </summary>
[Test]
public void HandicapAccessibleTest()
{
// TODO unit test for the property 'HandicapAccessible'
}
/// <summary>
/// Test the property 'HighChair'
/// </summary>
[Test]
public void HighChairTest()
{
// TODO unit test for the property 'HighChair'
}
/// <summary>
/// Test the property 'Stroller'
/// </summary>
[Test]
public void StrollerTest()
{
// TODO unit test for the property 'Stroller'
}
}
}
| |
// 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.Text;
using Xunit;
namespace System.Text.EncodingTests
{
public class EncoderConvert2Encoder : Encoder
{
private Encoder _encoder = null;
public EncoderConvert2Encoder()
{
_encoder = Encoding.UTF8.GetEncoder();
}
public override int GetByteCount(char[] chars, int index, int count, bool flush)
{
if (index >= count)
throw new ArgumentException();
return _encoder.GetByteCount(chars, index, count, flush);
}
public override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex, bool flush)
{
return _encoder.GetBytes(chars, charIndex, charCount, bytes, byteIndex, flush);
}
}
// Convert(System.Char[],System.Int32,System.Int32,System.Byte[],System.Int32,System.Int32,System.Boolean,System.Int32@,System.Int32@,System.Boolean@)
public class EncoderConvert2
{
#region Private Fields
private const int c_SIZE_OF_ARRAY = 256;
private readonly RandomDataGenerator _generator = new RandomDataGenerator();
#endregion
#region Positive Test Cases
// PosTest1: Call Convert to convert a arbitrary character array with ASCII encoder
[Fact]
public void PosTest1()
{
char[] chars = new char[c_SIZE_OF_ARRAY];
byte[] bytes = new byte[c_SIZE_OF_ARRAY];
Encoder encoder = Encoding.UTF8.GetEncoder();
for (int i = 0; i < chars.Length; ++i)
{
chars[i] = _generator.GetChar(-55);
}
int charsUsed;
int bytesUsed;
bool completed;
encoder.Convert(chars, 0, chars.Length, bytes, 0, bytes.Length, false, out charsUsed, out bytesUsed, out completed);
// set flush to true and try again
encoder.Convert(chars, 0, chars.Length, bytes, 0, bytes.Length, true, out charsUsed, out bytesUsed, out completed);
}
// PosTest2: Call Convert to convert a arbitrary character array with Unicode encoder
[Fact]
public void PosTest2()
{
char[] chars = new char[c_SIZE_OF_ARRAY];
byte[] bytes = new byte[c_SIZE_OF_ARRAY];
Encoder encoder = Encoding.Unicode.GetEncoder();
for (int i = 0; i < chars.Length; ++i)
{
chars[i] = _generator.GetChar(-55);
}
int charsUsed;
int bytesUsed;
bool completed;
encoder.Convert(chars, 0, chars.Length, bytes, 0, bytes.Length, false, out charsUsed, out bytesUsed, out completed);
// set flush to true and try again
encoder.Convert(chars, 0, chars.Length, bytes, 0, bytes.Length, true, out charsUsed, out bytesUsed, out completed);
}
// PosTest3: Call Convert to convert a ASCII character array with ASCII encoder
[Fact]
public void PosTest3()
{
char[] chars = "TestLibrary.TestFramework.BeginScenario".ToCharArray();
byte[] bytes = new byte[chars.Length];
Encoder encoder = Encoding.UTF8.GetEncoder();
VerificationHelper(encoder, chars, 0, chars.Length, bytes, 0, bytes.Length, false, chars.Length, chars.Length, true, "003.1");
VerificationHelper(encoder, chars, 0, chars.Length, bytes, 0, bytes.Length, true, chars.Length, chars.Length, true, "003.2");
VerificationHelper(encoder, chars, 0, 0, bytes, 0, 0, true, 0, 0, true, "003.3");
}
// PosTest4: Call Convert to convert a ASCII character array with user implemented encoder
[Fact]
public void PosTest4()
{
char[] chars = "TestLibrary.TestFramework.BeginScenario".ToCharArray();
byte[] bytes = new byte[chars.Length];
Encoder encoder = new EncoderConvert2Encoder();
VerificationHelper(encoder, chars, 0, chars.Length, bytes, 0, bytes.Length, false, chars.Length, chars.Length, true, "004.1");
VerificationHelper(encoder, chars, 0, chars.Length, bytes, 0, bytes.Length, true, chars.Length, chars.Length, true, "004.2");
}
// PosTest5: Call Convert to convert partial of a ASCII character array with ASCII encoder
[Fact]
public void PosTest5()
{
char[] chars = "TestLibrary.TestFramework.BeginScenario".ToCharArray();
byte[] bytes = new byte[chars.Length];
Encoder encoder = Encoding.UTF8.GetEncoder();
VerificationHelper(encoder, chars, 0, 1, bytes, 0, 1, false, 1, 1, true, "005.1");
VerificationHelper(encoder, chars, 0, 1, bytes, 0, 1, true, 1, 1, true, "005.2");
VerificationHelper(encoder, chars, 1, 1, bytes, 0, 1, false, 1, 1, true, "005.3");
VerificationHelper(encoder, chars, 1, 1, bytes, 0, 1, true, 1, 1, true, "005.4");
VerificationHelper(encoder, chars, 1, 1, bytes, 1, 1, false, 1, 1, true, "005.5");
VerificationHelper(encoder, chars, 1, 1, bytes, 1, 1, true, 1, 1, true, "005.6");
// Verify maxBytes is large than character count
VerificationHelper(encoder, chars, 0, chars.Length - 1, bytes, 0, bytes.Length, false, chars.Length - 1, chars.Length - 1, true, "005.7");
VerificationHelper(encoder, chars, 1, chars.Length - 1, bytes, 0, bytes.Length, true, chars.Length - 1, chars.Length - 1, true, "005.8");
}
// PosTest6: Call Convert to convert a ASCII character array with Unicode encoder
[Fact]
public void PosTest6()
{
char[] chars = "TestLibrary.TestFramework.BeginScenario".ToCharArray();
byte[] bytes = new byte[chars.Length * 2];
Encoder encoder = Encoding.Unicode.GetEncoder();
VerificationHelper(encoder, chars, 0, chars.Length, bytes, 0, bytes.Length, false, chars.Length, bytes.Length, true, "006.1");
VerificationHelper(encoder, chars, 0, chars.Length, bytes, 0, bytes.Length, true, chars.Length, bytes.Length, true, "006.2");
}
// PosTest7: Call Convert to convert partial of a ASCII character array with Unicode encoder
[Fact]
public void PosTest7()
{
char[] chars = "TestLibrary.TestFramework.BeginScenario".ToCharArray();
byte[] bytes = new byte[chars.Length * 2];
Encoder encoder = Encoding.Unicode.GetEncoder();
VerificationHelper(encoder, chars, 0, 1, bytes, 0, 2, false, 1, 2, true, "007.1");
VerificationHelper(encoder, chars, 0, 1, bytes, 0, 2, true, 1, 2, true, "007.2");
VerificationHelper(encoder, chars, 1, 1, bytes, 0, 2, false, 1, 2, true, "007.3");
VerificationHelper(encoder, chars, 1, 1, bytes, 0, 2, true, 1, 2, true, "007.4");
VerificationHelper(encoder, chars, 1, 1, bytes, 1, 2, false, 1, 2, true, "007.5");
VerificationHelper(encoder, chars, 1, 1, bytes, 1, 2, true, 1, 2, true, "007.6");
VerificationHelper(encoder, chars, 0, 1, bytes, 0, bytes.Length, false, 1, 2, true, "007.3");
VerificationHelper(encoder, chars, 0, 1, bytes, 0, bytes.Length, true, 1, 2, true, "007.4");
}
// PosTest8: Call Convert to convert a unicode character array with Unicode encoder
[Fact]
public void PosTest8()
{
char[] chars = "\u8FD9\u4E2A\u4E00\u4E2A\u6D4B\u8BD5".ToCharArray();
byte[] bytes = new byte[chars.Length * 2];
Encoder encoder = Encoding.Unicode.GetEncoder();
VerificationHelper(encoder, chars, 0, chars.Length, bytes, 0, bytes.Length, false, chars.Length, bytes.Length, true, "008.1");
VerificationHelper(encoder, chars, 0, chars.Length, bytes, 0, bytes.Length, true, chars.Length, bytes.Length, true, "008.2");
}
// PosTest9: Call Convert to convert partial of a unicode character array with Unicode encoder
[Fact]
public void PosTest9()
{
char[] chars = "\u8FD9\u4E2A\u4E00\u4E2A\u6D4B\u8BD5".ToCharArray();
byte[] bytes = new byte[chars.Length * 2];
Encoder encoder = Encoding.Unicode.GetEncoder();
VerificationHelper(encoder, chars, 0, 1, bytes, 0, 2, false, 1, 2, true, "009.1");
VerificationHelper(encoder, chars, 0, 1, bytes, 0, 2, true, 1, 2, true, "009.2");
VerificationHelper(encoder, chars, 1, 1, bytes, 0, 2, false, 1, 2, true, "009.3");
VerificationHelper(encoder, chars, 1, 1, bytes, 0, 2, true, 1, 2, true, "009.4");
VerificationHelper(encoder, chars, 1, 1, bytes, 1, 2, false, 1, 2, true, "009.5");
VerificationHelper(encoder, chars, 1, 1, bytes, 1, 2, true, 1, 2, true, "009.6");
VerificationHelper(encoder, chars, 0, 1, bytes, 0, bytes.Length, false, 1, 2, true, "009.3");
VerificationHelper(encoder, chars, 0, 1, bytes, 0, bytes.Length, true, 1, 2, true, "009.4");
}
#endregion
#region Negative Test Cases
// NegTest1: ArgumentNullException should be thrown when chars or bytes is a null reference
[Fact]
public void NegTest1()
{
Encoder encoder = Encoding.UTF8.GetEncoder();
VerificationHelper<ArgumentNullException>(encoder, null, 0, 0, new byte[1], 0, 0, true, typeof(ArgumentNullException), "101.1");
VerificationHelper<ArgumentNullException>(encoder, new char[1], 0, 0, null, 0, 0, true, typeof(ArgumentNullException), "101.2");
}
// NegTest2: ArgumentOutOfRangeException should be thrown when charIndex, charCount, byteIndex, or byteCount is less than zero
[Fact]
public void NegTest2()
{
Encoder encoder = Encoding.UTF8.GetEncoder();
VerificationHelper<ArgumentOutOfRangeException>(encoder, new char[1], 0, -1, new byte[1], 0, 0, true, typeof(ArgumentOutOfRangeException), "102.1");
VerificationHelper<ArgumentOutOfRangeException>(encoder, new char[1], 0, 0, new byte[1], 0, -1, true, typeof(ArgumentOutOfRangeException), "102.2");
VerificationHelper<ArgumentOutOfRangeException>(encoder, new char[1], -1, 0, new byte[1], 0, 0, true, typeof(ArgumentOutOfRangeException), "102.3");
VerificationHelper<ArgumentOutOfRangeException>(encoder, new char[1], 0, 0, new byte[1], -1, 0, true, typeof(ArgumentOutOfRangeException), "102.4");
}
// NegTest3: ArgumentException should be thrown when The output buffer is too small to contain any of the converted input
[Fact]
public void NegTest3()
{
Encoder encoder = Encoding.Unicode.GetEncoder();
char[] chars = new char[c_SIZE_OF_ARRAY];
for (int i = 0; i < chars.Length; ++i)
{
chars[i] = _generator.GetChar(-55);
}
byte[] bytes1 = new byte[1];
VerificationHelper<ArgumentException>(encoder, chars, 0, chars.Length, bytes1, 0, bytes1.Length, true, typeof(ArgumentException), "103.1");
}
// NegTest4: ArgumentOutOfRangeException should be thrown when The length of chars - charIndex is less than charCount
[Fact]
public void NegTest4()
{
Encoder encoder = Encoding.UTF8.GetEncoder();
VerificationHelper<ArgumentOutOfRangeException>(encoder, new char[1], 1, 1, new byte[1], 0, 1, true, typeof(ArgumentOutOfRangeException), "104.1");
}
// NegTest5: ArgumentOutOfRangeException should be thrown when The length of bytes - byteIndex is less than byteCount
[Fact]
public void NegTest5()
{
Encoder encoder = Encoding.UTF8.GetEncoder();
VerificationHelper<ArgumentOutOfRangeException>(encoder, new char[1], 0, 1, new byte[1], 1, 1, true, typeof(ArgumentOutOfRangeException), "105.1");
}
#endregion
private void VerificationHelper(Encoder encoder, char[] chars, int charIndex, int charCount,
byte[] bytes, int byteIndex, int byteCount, bool flush, int expectedCharsUsed, int expectedBytesUsed,
bool expectedCompleted, string errorno)
{
int charsUsed;
int bytesUsed;
bool completed;
encoder.Convert(chars, charIndex, charCount, bytes, byteIndex, byteCount, false, out charsUsed, out bytesUsed, out completed);
Assert.Equal(expectedCharsUsed, charsUsed);
Assert.Equal(expectedBytesUsed, bytesUsed);
Assert.Equal(expectedCompleted, completed);
}
private void VerificationHelper<T>(Encoder encoder, char[] chars, int charIndex, int charCount, byte[] bytes,
int byteIndex, int byteCount, bool flush, Type desired, string errorno) where T : Exception
{
int charsUsed;
int bytesUsed;
bool completed;
Assert.Throws<T>(() =>
{
encoder.Convert(chars, charIndex, charCount, bytes, byteIndex, byteCount, flush, out charsUsed,
out bytesUsed, out completed);
});
}
}
}
| |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public enum eEndPointsMode { AUTO, AUTOCLOSED, EXPLICIT }
public enum eWrapMode { ONCE, LOOP }
public delegate void OnEndCallback();
public class SplineInterpolator : MonoBehaviour
{
eEndPointsMode mEndPointsMode = eEndPointsMode.AUTO;
internal class SplineNode
{
internal Vector3 Point;
internal Quaternion Rot;
internal float Time;
internal Vector2 EaseIO;
internal SplineNode(Vector3 p, Quaternion q, float t, Vector2 io) { Point = p; Rot = q; Time = t; EaseIO = io; }
internal SplineNode(SplineNode o) { Point = o.Point; Rot = o.Rot; Time = o.Time; EaseIO = o.EaseIO; }
}
List<SplineNode> mNodes = new List<SplineNode>();
string mState = "";
bool mRotations;
OnEndCallback mOnEndCallback;
void Awake()
{
Reset();
}
public void StartInterpolation(OnEndCallback endCallback, bool bRotations, eWrapMode mode)
{
if (mState != "Reset")
throw new System.Exception("First reset, add points and then call here");
mState = mode == eWrapMode.ONCE ? "Once" : "Loop";
mRotations = bRotations;
mOnEndCallback = endCallback;
SetInput();
}
public void Reset()
{
mNodes.Clear();
mState = "Reset";
mCurrentIdx = 1;
mCurrentTime = 0;
mRotations = false;
mEndPointsMode = eEndPointsMode.AUTO;
}
public void AddPoint(Vector3 pos, Quaternion quat, float timeInSeconds, Vector2 easeInOut)
{
if (mState != "Reset")
throw new System.Exception("Cannot add points after start");
mNodes.Add(new SplineNode(pos, quat, timeInSeconds, easeInOut));
}
void SetInput()
{
if (mNodes.Count < 2)
throw new System.Exception("Invalid number of points");
if (mRotations)
{
for (int c = 1; c < mNodes.Count; c++)
{
SplineNode node = mNodes[c];
SplineNode prevNode = mNodes[c - 1];
// Always interpolate using the shortest path -> Selective negation
if (Quaternion.Dot(node.Rot, prevNode.Rot) < 0)
{
node.Rot.x = -node.Rot.x;
node.Rot.y = -node.Rot.y;
node.Rot.z = -node.Rot.z;
node.Rot.w = -node.Rot.w;
}
}
}
if (mEndPointsMode == eEndPointsMode.AUTO)
{
mNodes.Insert(0, mNodes[0]);
mNodes.Add(mNodes[mNodes.Count - 1]);
}
else if (mEndPointsMode == eEndPointsMode.EXPLICIT && (mNodes.Count < 4))
throw new System.Exception("Invalid number of points");
}
void SetExplicitMode()
{
if (mState != "Reset")
throw new System.Exception("Cannot change mode after start");
mEndPointsMode = eEndPointsMode.EXPLICIT;
}
public void SetAutoCloseMode(float joiningPointTime)
{
if (mState != "Reset")
throw new System.Exception("Cannot change mode after start");
mEndPointsMode = eEndPointsMode.AUTOCLOSED;
mNodes.Add(new SplineNode(mNodes[0] as SplineNode));
mNodes[mNodes.Count - 1].Time = joiningPointTime;
Vector3 vInitDir = (mNodes[1].Point - mNodes[0].Point).normalized;
Vector3 vEndDir = (mNodes[mNodes.Count - 2].Point - mNodes[mNodes.Count - 1].Point).normalized;
float firstLength = (mNodes[1].Point - mNodes[0].Point).magnitude;
float lastLength = (mNodes[mNodes.Count - 2].Point - mNodes[mNodes.Count - 1].Point).magnitude;
SplineNode firstNode = new SplineNode(mNodes[0] as SplineNode);
firstNode.Point = mNodes[0].Point + vEndDir * firstLength;
SplineNode lastNode = new SplineNode(mNodes[mNodes.Count - 1] as SplineNode);
lastNode.Point = mNodes[0].Point + vInitDir * lastLength;
mNodes.Insert(0, firstNode);
mNodes.Add(lastNode);
}
float mCurrentTime;
int mCurrentIdx = 1;
void Update()
{
if (mState == "Reset" || mState == "Stopped" || mNodes.Count < 4)
return;
mCurrentTime += Time.deltaTime;
// We advance to next point in the path
if (mCurrentTime >= mNodes[mCurrentIdx + 1].Time)
{
if (mCurrentIdx < mNodes.Count - 3)
{
mCurrentIdx++;
}
else
{
if (mState != "Loop")
{
mState = "Stopped";
// We stop right in the end point
transform.position = mNodes[mNodes.Count - 2].Point;
if (mRotations)
transform.rotation = mNodes[mNodes.Count - 2].Rot;
// We call back to inform that we are ended
if (mOnEndCallback != null)
mOnEndCallback();
}
else
{
mCurrentIdx = 1;
mCurrentTime = 0;
}
}
}
if (mState != "Stopped")
{
// Calculates the t param between 0 and 1
float param = (mCurrentTime - mNodes[mCurrentIdx].Time) / (mNodes[mCurrentIdx + 1].Time - mNodes[mCurrentIdx].Time);
// Smooth the param
param = MathUtils.Ease(param, mNodes[mCurrentIdx].EaseIO.x, mNodes[mCurrentIdx].EaseIO.y);
transform.position = GetHermiteInternal(mCurrentIdx, param);
if (mRotations)
{
transform.rotation = GetSquad(mCurrentIdx, param);
}
}
}
Quaternion GetSquad(int idxFirstPoint, float t)
{
Quaternion Q0 = mNodes[idxFirstPoint - 1].Rot;
Quaternion Q1 = mNodes[idxFirstPoint].Rot;
Quaternion Q2 = mNodes[idxFirstPoint + 1].Rot;
Quaternion Q3 = mNodes[idxFirstPoint + 2].Rot;
Quaternion T1 = MathUtils.GetSquadIntermediate(Q0, Q1, Q2);
Quaternion T2 = MathUtils.GetSquadIntermediate(Q1, Q2, Q3);
return MathUtils.GetQuatSquad(t, Q1, Q2, T1, T2);
}
public Vector3 GetHermiteInternal(int idxFirstPoint, float t)
{
float t2 = t * t;
float t3 = t2 * t;
Vector3 P0 = mNodes[idxFirstPoint - 1].Point;
Vector3 P1 = mNodes[idxFirstPoint].Point;
Vector3 P2 = mNodes[idxFirstPoint + 1].Point;
Vector3 P3 = mNodes[idxFirstPoint + 2].Point;
float tension = 0.5f; // 0.5 equivale a catmull-rom
Vector3 T1 = tension * (P2 - P0);
Vector3 T2 = tension * (P3 - P1);
float Blend1 = 2 * t3 - 3 * t2 + 1;
float Blend2 = -2 * t3 + 3 * t2;
float Blend3 = t3 - 2 * t2 + t;
float Blend4 = t3 - t2;
return Blend1 * P1 + Blend2 * P2 + Blend3 * T1 + Blend4 * T2;
}
public Vector3 GetHermiteAtTime(float timeParam)
{
if (timeParam >= mNodes[mNodes.Count - 2].Time)
return mNodes[mNodes.Count - 2].Point;
int c;
for (c = 1; c < mNodes.Count - 2; c++)
{
if (mNodes[c].Time > timeParam)
break;
}
int idx = c - 1;
float param = (timeParam - mNodes[idx].Time) / (mNodes[idx + 1].Time - mNodes[idx].Time);
param = MathUtils.Ease(param, mNodes[idx].EaseIO.x, mNodes[idx].EaseIO.y);
return GetHermiteInternal(idx, param);
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using JCG = J2N.Collections.Generic;
namespace Lucene.Net.Codecs.Lucene45
{
/*
* 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 BlockPackedWriter = Lucene.Net.Util.Packed.BlockPackedWriter;
using BytesRef = Lucene.Net.Util.BytesRef;
using FieldInfo = Lucene.Net.Index.FieldInfo;
using IndexFileNames = Lucene.Net.Index.IndexFileNames;
using IndexOutput = Lucene.Net.Store.IndexOutput;
using IOUtils = Lucene.Net.Util.IOUtils;
using MathUtil = Lucene.Net.Util.MathUtil;
using MonotonicBlockPackedWriter = Lucene.Net.Util.Packed.MonotonicBlockPackedWriter;
using PackedInt32s = Lucene.Net.Util.Packed.PackedInt32s;
using RAMOutputStream = Lucene.Net.Store.RAMOutputStream;
using SegmentWriteState = Lucene.Net.Index.SegmentWriteState;
using StringHelper = Lucene.Net.Util.StringHelper;
/// <summary>
/// Writer for <see cref="Lucene45DocValuesFormat"/> </summary>
public class Lucene45DocValuesConsumer : DocValuesConsumer, IDisposable
{
internal static readonly int BLOCK_SIZE = 16384;
internal static readonly int ADDRESS_INTERVAL = 16;
internal static readonly long MISSING_ORD = -1L;
/// <summary>
/// Compressed using packed blocks of <see cref="int"/>s. </summary>
public const int DELTA_COMPRESSED = 0;
/// <summary>
/// Compressed by computing the GCD. </summary>
public const int GCD_COMPRESSED = 1;
/// <summary>
/// Compressed by giving IDs to unique values. </summary>
public const int TABLE_COMPRESSED = 2;
/// <summary>
/// Uncompressed binary, written directly (fixed length). </summary>
public const int BINARY_FIXED_UNCOMPRESSED = 0;
/// <summary>
/// Uncompressed binary, written directly (variable length). </summary>
public const int BINARY_VARIABLE_UNCOMPRESSED = 1;
/// <summary>
/// Compressed binary with shared prefixes </summary>
public const int BINARY_PREFIX_COMPRESSED = 2;
/// <summary>
/// Standard storage for sorted set values with 1 level of indirection:
/// docId -> address -> ord.
/// </summary>
public static readonly int SORTED_SET_WITH_ADDRESSES = 0;
/// <summary>
/// Single-valued sorted set values, encoded as sorted values, so no level
/// of indirection: docId -> ord.
/// </summary>
public static readonly int SORTED_SET_SINGLE_VALUED_SORTED = 1;
internal IndexOutput data, meta;
internal readonly int maxDoc;
/// <summary>
/// Expert: Creates a new writer. </summary>
public Lucene45DocValuesConsumer(SegmentWriteState state, string dataCodec, string dataExtension, string metaCodec, string metaExtension)
{
bool success = false;
try
{
string dataName = IndexFileNames.SegmentFileName(state.SegmentInfo.Name, state.SegmentSuffix, dataExtension);
data = state.Directory.CreateOutput(dataName, state.Context);
CodecUtil.WriteHeader(data, dataCodec, Lucene45DocValuesFormat.VERSION_CURRENT);
string metaName = IndexFileNames.SegmentFileName(state.SegmentInfo.Name, state.SegmentSuffix, metaExtension);
meta = state.Directory.CreateOutput(metaName, state.Context);
CodecUtil.WriteHeader(meta, metaCodec, Lucene45DocValuesFormat.VERSION_CURRENT);
maxDoc = state.SegmentInfo.DocCount;
success = true;
}
finally
{
if (!success)
{
IOUtils.DisposeWhileHandlingException(this);
}
}
}
public override void AddNumericField(FieldInfo field, IEnumerable<long?> values)
{
AddNumericField(field, values, true);
}
internal virtual void AddNumericField(FieldInfo field, IEnumerable<long?> values, bool optimizeStorage)
{
long count = 0;
long minValue = long.MaxValue;
long maxValue = long.MinValue;
long gcd = 0;
bool missing = false;
// TODO: more efficient?
JCG.HashSet<long> uniqueValues = null;
if (optimizeStorage)
{
uniqueValues = new JCG.HashSet<long>();
foreach (long? nv in values)
{
long v;
if (nv == null)
{
v = 0;
missing = true;
}
else
{
v = nv.Value;
}
if (gcd != 1)
{
if (v < long.MinValue / 2 || v > long.MaxValue / 2)
{
// in that case v - minValue might overflow and make the GCD computation return
// wrong results. Since these extreme values are unlikely, we just discard
// GCD computation for them
gcd = 1;
} // minValue needs to be set first
else if (count != 0)
{
gcd = MathUtil.Gcd(gcd, v - minValue);
}
}
minValue = Math.Min(minValue, v);
maxValue = Math.Max(maxValue, v);
if (uniqueValues != null)
{
if (uniqueValues.Add(v))
{
if (uniqueValues.Count > 256)
{
uniqueValues = null;
}
}
}
++count;
}
}
else
{
foreach (var nv in values)
{
++count;
}
}
long delta = maxValue - minValue;
int format;
if (uniqueValues != null && (delta < 0L || PackedInt32s.BitsRequired(uniqueValues.Count - 1) < PackedInt32s.BitsRequired(delta)) && count <= int.MaxValue)
{
format = TABLE_COMPRESSED;
}
else if (gcd != 0 && gcd != 1)
{
format = GCD_COMPRESSED;
}
else
{
format = DELTA_COMPRESSED;
}
meta.WriteVInt32(field.Number);
meta.WriteByte((byte)Lucene45DocValuesFormat.NUMERIC);
meta.WriteVInt32(format);
if (missing)
{
meta.WriteInt64(data.GetFilePointer());
WriteMissingBitset(values);
}
else
{
meta.WriteInt64(-1L);
}
meta.WriteVInt32(PackedInt32s.VERSION_CURRENT);
meta.WriteInt64(data.GetFilePointer());
meta.WriteVInt64(count);
meta.WriteVInt32(BLOCK_SIZE);
switch (format)
{
case GCD_COMPRESSED:
meta.WriteInt64(minValue);
meta.WriteInt64(gcd);
BlockPackedWriter quotientWriter = new BlockPackedWriter(data, BLOCK_SIZE);
foreach (long? nv in values)
{
quotientWriter.Add((nv.GetValueOrDefault() - minValue) / gcd);
}
quotientWriter.Finish();
break;
case DELTA_COMPRESSED:
BlockPackedWriter writer = new BlockPackedWriter(data, BLOCK_SIZE);
foreach (long? nv in values)
{
writer.Add(nv.GetValueOrDefault());
}
writer.Finish();
break;
case TABLE_COMPRESSED:
// LUCENENET NOTE: diming an array and then using .CopyTo() for better efficiency than LINQ .ToArray()
long[] decode = new long[uniqueValues.Count];
uniqueValues.CopyTo(decode, 0);
Dictionary<long, int> encode = new Dictionary<long, int>();
meta.WriteVInt32(decode.Length);
for (int i = 0; i < decode.Length; i++)
{
meta.WriteInt64(decode[i]);
encode[decode[i]] = i;
}
int bitsRequired = PackedInt32s.BitsRequired(uniqueValues.Count - 1);
PackedInt32s.Writer ordsWriter = PackedInt32s.GetWriterNoHeader(data, PackedInt32s.Format.PACKED, (int)count, bitsRequired, PackedInt32s.DEFAULT_BUFFER_SIZE);
foreach (long? nv in values)
{
ordsWriter.Add(encode[nv.GetValueOrDefault()]);
}
ordsWriter.Finish();
break;
default:
throw new InvalidOperationException();
}
}
// TODO: in some cases representing missing with minValue-1 wouldn't take up additional space and so on,
// but this is very simple, and algorithms only check this for values of 0 anyway (doesnt slow down normal decode)
internal virtual void WriteMissingBitset(IEnumerable values)
{
sbyte bits = 0;
int count = 0;
foreach (object v in values)
{
if (count == 8)
{
data.WriteByte((byte)bits);
count = 0;
bits = 0;
}
if (v != null)
{
bits |= (sbyte)(1 << (count & 7));
}
count++;
}
if (count > 0)
{
data.WriteByte((byte)bits);
}
}
public override void AddBinaryField(FieldInfo field, IEnumerable<BytesRef> values)
{
// write the byte[] data
meta.WriteVInt32(field.Number);
meta.WriteByte((byte)Lucene45DocValuesFormat.BINARY);
int minLength = int.MaxValue;
int maxLength = int.MinValue;
long startFP = data.GetFilePointer();
long count = 0;
bool missing = false;
foreach (BytesRef v in values)
{
int length;
if (v == null)
{
length = 0;
missing = true;
}
else
{
length = v.Length;
}
minLength = Math.Min(minLength, length);
maxLength = Math.Max(maxLength, length);
if (v != null)
{
data.WriteBytes(v.Bytes, v.Offset, v.Length);
}
count++;
}
meta.WriteVInt32(minLength == maxLength ? BINARY_FIXED_UNCOMPRESSED : BINARY_VARIABLE_UNCOMPRESSED);
if (missing)
{
meta.WriteInt64(data.GetFilePointer());
WriteMissingBitset(values);
}
else
{
meta.WriteInt64(-1L);
}
meta.WriteVInt32(minLength);
meta.WriteVInt32(maxLength);
meta.WriteVInt64(count);
meta.WriteInt64(startFP);
// if minLength == maxLength, its a fixed-length byte[], we are done (the addresses are implicit)
// otherwise, we need to record the length fields...
if (minLength != maxLength)
{
meta.WriteInt64(data.GetFilePointer());
meta.WriteVInt32(PackedInt32s.VERSION_CURRENT);
meta.WriteVInt32(BLOCK_SIZE);
MonotonicBlockPackedWriter writer = new MonotonicBlockPackedWriter(data, BLOCK_SIZE);
long addr = 0;
foreach (BytesRef v in values)
{
if (v != null)
{
addr += v.Length;
}
writer.Add(addr);
}
writer.Finish();
}
}
/// <summary>
/// Expert: writes a value dictionary for a sorted/sortedset field. </summary>
protected virtual void AddTermsDict(FieldInfo field, IEnumerable<BytesRef> values)
{
// first check if its a "fixed-length" terms dict
int minLength = int.MaxValue;
int maxLength = int.MinValue;
foreach (BytesRef v in values)
{
minLength = Math.Min(minLength, v.Length);
maxLength = Math.Max(maxLength, v.Length);
}
if (minLength == maxLength)
{
// no index needed: direct addressing by mult
AddBinaryField(field, values);
}
else
{
// header
meta.WriteVInt32(field.Number);
meta.WriteByte((byte)Lucene45DocValuesFormat.BINARY);
meta.WriteVInt32(BINARY_PREFIX_COMPRESSED);
meta.WriteInt64(-1L);
// now write the bytes: sharing prefixes within a block
long startFP = data.GetFilePointer();
// currently, we have to store the delta from expected for every 1/nth term
// we could avoid this, but its not much and less overall RAM than the previous approach!
RAMOutputStream addressBuffer = new RAMOutputStream();
MonotonicBlockPackedWriter termAddresses = new MonotonicBlockPackedWriter(addressBuffer, BLOCK_SIZE);
BytesRef lastTerm = new BytesRef();
long count = 0;
foreach (BytesRef v in values)
{
if (count % ADDRESS_INTERVAL == 0)
{
termAddresses.Add(data.GetFilePointer() - startFP);
// force the first term in a block to be abs-encoded
lastTerm.Length = 0;
}
// prefix-code
int sharedPrefix = StringHelper.BytesDifference(lastTerm, v);
data.WriteVInt32(sharedPrefix);
data.WriteVInt32(v.Length - sharedPrefix);
data.WriteBytes(v.Bytes, v.Offset + sharedPrefix, v.Length - sharedPrefix);
lastTerm.CopyBytes(v);
count++;
}
long indexStartFP = data.GetFilePointer();
// write addresses of indexed terms
termAddresses.Finish();
addressBuffer.WriteTo(data);
addressBuffer = null;
termAddresses = null;
meta.WriteVInt32(minLength);
meta.WriteVInt32(maxLength);
meta.WriteVInt64(count);
meta.WriteInt64(startFP);
meta.WriteVInt32(ADDRESS_INTERVAL);
meta.WriteInt64(indexStartFP);
meta.WriteVInt32(PackedInt32s.VERSION_CURRENT);
meta.WriteVInt32(BLOCK_SIZE);
}
}
public override void AddSortedField(FieldInfo field, IEnumerable<BytesRef> values, IEnumerable<long?> docToOrd)
{
meta.WriteVInt32(field.Number);
meta.WriteByte((byte)Lucene45DocValuesFormat.SORTED);
AddTermsDict(field, values);
AddNumericField(field, docToOrd, false);
}
private static bool IsSingleValued(IEnumerable<long?> docToOrdCount)
{
foreach (var ordCount in docToOrdCount)
{
if (ordCount.GetValueOrDefault() > 1)
return false;
}
return true;
}
public override void AddSortedSetField(FieldInfo field, IEnumerable<BytesRef> values, IEnumerable<long?> docToOrdCount, IEnumerable<long?> ords)
{
meta.WriteVInt32(field.Number);
meta.WriteByte((byte)Lucene45DocValuesFormat.SORTED_SET);
if (IsSingleValued(docToOrdCount))
{
meta.WriteVInt32(SORTED_SET_SINGLE_VALUED_SORTED);
// The field is single-valued, we can encode it as SORTED
AddSortedField(field, values, GetSortedSetEnumerable(docToOrdCount, ords));
return;
}
meta.WriteVInt32(SORTED_SET_WITH_ADDRESSES);
// write the ord -> byte[] as a binary field
AddTermsDict(field, values);
// write the stream of ords as a numeric field
// NOTE: we could return an iterator that delta-encodes these within a doc
AddNumericField(field, ords, false);
// write the doc -> ord count as a absolute index to the stream
meta.WriteVInt32(field.Number);
meta.WriteByte((byte)Lucene45DocValuesFormat.NUMERIC);
meta.WriteVInt32(DELTA_COMPRESSED);
meta.WriteInt64(-1L);
meta.WriteVInt32(PackedInt32s.VERSION_CURRENT);
meta.WriteInt64(data.GetFilePointer());
meta.WriteVInt64(maxDoc);
meta.WriteVInt32(BLOCK_SIZE);
var writer = new MonotonicBlockPackedWriter(data, BLOCK_SIZE);
long addr = 0;
foreach (long? v in docToOrdCount)
{
addr += v.Value;
writer.Add(addr);
}
writer.Finish();
}
private IEnumerable<long?> GetSortedSetEnumerable(IEnumerable<long?> docToOrdCount, IEnumerable<long?> ords)
{
IEnumerator<long?> docToOrdCountIter = docToOrdCount.GetEnumerator();
IEnumerator<long?> ordsIter = ords.GetEnumerator();
const long MISSING_ORD = -1;
while (docToOrdCountIter.MoveNext())
{
long current = docToOrdCountIter.Current.Value;
if (current == 0)
{
yield return MISSING_ORD;
}
else
{
Debug.Assert(current == 1);
ordsIter.MoveNext();
yield return ordsIter.Current;
}
}
Debug.Assert(!ordsIter.MoveNext());
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
bool success = false;
try
{
if (meta != null)
{
meta.WriteVInt32(-1); // write EOF marker
CodecUtil.WriteFooter(meta); // write checksum
}
if (data != null)
{
CodecUtil.WriteFooter(data); // write checksum
}
success = true;
}
finally
{
if (success)
{
IOUtils.Dispose(data, meta);
}
else
{
IOUtils.DisposeWhileHandlingException(data, meta);
}
meta = data = null;
}
}
}
}
}
| |
#region Copyright notice and license
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://github.com/jskeet/dotnet-protobufs/
// Original C++/Java/Python code:
// http://code.google.com/p/protobuf/
//
// 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 Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Google.ProtocolBuffers.Collections;
using Google.ProtocolBuffers.Descriptors;
namespace Google.ProtocolBuffers
{
/// <summary>
/// Implementation of the non-generic IMessage interface as far as possible.
/// </summary>
public abstract partial class AbstractMessage<TMessage, TBuilder> : AbstractMessageLite<TMessage, TBuilder>,
IMessage<TMessage, TBuilder>
where TMessage : AbstractMessage<TMessage, TBuilder>
where TBuilder : AbstractBuilder<TMessage, TBuilder>
{
/// <summary>
/// The serialized size if it's already been computed, or null
/// if we haven't computed it yet.
/// </summary>
private int? memoizedSize = null;
#region Unimplemented members of IMessage
public abstract MessageDescriptor DescriptorForType { get; }
public abstract IDictionary<FieldDescriptor, object> AllFields { get; }
public abstract bool HasField(FieldDescriptor field);
public abstract object this[FieldDescriptor field] { get; }
public abstract int GetRepeatedFieldCount(FieldDescriptor field);
public abstract object this[FieldDescriptor field, int index] { get; }
public abstract UnknownFieldSet UnknownFields { get; }
#endregion
/// <summary>
/// Returns true iff all required fields in the message and all embedded
/// messages are set.
/// </summary>
public override bool IsInitialized
{
get
{
// Check that all required fields are present.
foreach (FieldDescriptor field in DescriptorForType.Fields)
{
if (field.IsRequired && !HasField(field))
{
return false;
}
}
// Check that embedded messages are initialized.
foreach (KeyValuePair<FieldDescriptor, object> entry in AllFields)
{
FieldDescriptor field = entry.Key;
if (field.MappedType == MappedType.Message)
{
if (field.IsRepeated)
{
// We know it's an IList<T>, but not the exact type - so
// IEnumerable is the best we can do. (C# generics aren't covariant yet.)
foreach (IMessageLite element in (IEnumerable) entry.Value)
{
if (!element.IsInitialized)
{
return false;
}
}
}
else
{
if (!((IMessageLite) entry.Value).IsInitialized)
{
return false;
}
}
}
}
return true;
}
}
public override sealed string ToString()
{
return TextFormat.PrintToString(this);
}
public override sealed void PrintTo(TextWriter writer)
{
TextFormat.Print(this, writer);
}
/// <summary>
/// Serializes the message and writes it to the given output stream.
/// This does not flush or close the stream.
/// </summary>
/// <remarks>
/// Protocol Buffers are not self-delimiting. Therefore, if you write
/// any more data to the stream after the message, you must somehow ensure
/// that the parser on the receiving end does not interpret this as being
/// part of the protocol message. One way of doing this is by writing the size
/// of the message before the data, then making sure you limit the input to
/// that size when receiving the data. Alternatively, use WriteDelimitedTo(Stream).
/// </remarks>
public override void WriteTo(ICodedOutputStream output)
{
foreach (KeyValuePair<FieldDescriptor, object> entry in AllFields)
{
FieldDescriptor field = entry.Key;
if (field.IsRepeated)
{
// We know it's an IList<T>, but not the exact type - so
// IEnumerable is the best we can do. (C# generics aren't covariant yet.)
IEnumerable valueList = (IEnumerable) entry.Value;
if (field.IsPacked)
{
output.WritePackedArray(field.FieldType, field.FieldNumber, field.Name, valueList);
}
else
{
output.WriteArray(field.FieldType, field.FieldNumber, field.Name, valueList);
}
}
else
{
output.WriteField(field.FieldType, field.FieldNumber, field.Name, entry.Value);
}
}
UnknownFieldSet unknownFields = UnknownFields;
if (DescriptorForType.Options.MessageSetWireFormat)
{
unknownFields.WriteAsMessageSetTo(output);
}
else
{
unknownFields.WriteTo(output);
}
}
/// <summary>
/// Returns the number of bytes required to encode this message.
/// The result is only computed on the first call and memoized after that.
/// </summary>
public override int SerializedSize
{
get
{
if (memoizedSize != null)
{
return memoizedSize.Value;
}
int size = 0;
foreach (KeyValuePair<FieldDescriptor, object> entry in AllFields)
{
FieldDescriptor field = entry.Key;
if (field.IsRepeated)
{
IEnumerable valueList = (IEnumerable) entry.Value;
if (field.IsPacked)
{
int dataSize = 0;
foreach (object element in valueList)
{
dataSize += CodedOutputStream.ComputeFieldSizeNoTag(field.FieldType, element);
}
size += dataSize;
size += CodedOutputStream.ComputeTagSize(field.FieldNumber);
size += CodedOutputStream.ComputeRawVarint32Size((uint) dataSize);
}
else
{
foreach (object element in valueList)
{
size += CodedOutputStream.ComputeFieldSize(field.FieldType, field.FieldNumber, element);
}
}
}
else
{
size += CodedOutputStream.ComputeFieldSize(field.FieldType, field.FieldNumber, entry.Value);
}
}
UnknownFieldSet unknownFields = UnknownFields;
if (DescriptorForType.Options.MessageSetWireFormat)
{
size += unknownFields.SerializedSizeAsMessageSet;
}
else
{
size += unknownFields.SerializedSize;
}
memoizedSize = size;
return size;
}
}
/// <summary>
/// Compares the specified object with this message for equality.
/// Returns true iff the given object is a message of the same type
/// (as defined by DescriptorForType) and has identical values
/// for all its fields.
/// </summary>
public override bool Equals(object other)
{
if (other == this)
{
return true;
}
IMessage otherMessage = other as IMessage;
if (otherMessage == null || otherMessage.DescriptorForType != DescriptorForType)
{
return false;
}
return Dictionaries.Equals(AllFields, otherMessage.AllFields) &&
UnknownFields.Equals(otherMessage.UnknownFields);
}
/// <summary>
/// Returns the hash code value for this message.
/// TODO(jonskeet): Specify the hash algorithm, but better than the Java one!
/// </summary>
public override int GetHashCode()
{
int hash = 41;
hash = (19*hash) + DescriptorForType.GetHashCode();
hash = (53*hash) + Dictionaries.GetHashCode(AllFields);
hash = (29*hash) + UnknownFields.GetHashCode();
return hash;
}
#region Explicit Members
IBuilder IMessage.WeakCreateBuilderForType()
{
return CreateBuilderForType();
}
IBuilder IMessage.WeakToBuilder()
{
return ToBuilder();
}
IMessage IMessage.WeakDefaultInstanceForType
{
get { return DefaultInstanceForType; }
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.Win32.SafeHandles;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.Text;
using System.Threading;
namespace System.Diagnostics
{
/// <devdoc>
/// <para>
/// Provides access to local and remote
/// processes. Enables you to start and stop system processes.
/// </para>
/// </devdoc>
public partial class Process : Component
{
private bool _haveProcessId;
private int _processId;
private bool _haveProcessHandle;
private SafeProcessHandle _processHandle;
private bool _isRemoteMachine;
private string _machineName;
private ProcessInfo _processInfo;
private ProcessThreadCollection _threads;
private ProcessModuleCollection _modules;
private bool _haveWorkingSetLimits;
private IntPtr _minWorkingSet;
private IntPtr _maxWorkingSet;
private bool _haveProcessorAffinity;
private IntPtr _processorAffinity;
private bool _havePriorityClass;
private ProcessPriorityClass _priorityClass;
private ProcessStartInfo _startInfo;
private bool _watchForExit;
private bool _watchingForExit;
private EventHandler _onExited;
private bool _exited;
private int _exitCode;
private DateTime? _startTime;
private DateTime _exitTime;
private bool _haveExitTime;
private bool _priorityBoostEnabled;
private bool _havePriorityBoostEnabled;
private bool _raisedOnExited;
private RegisteredWaitHandle _registeredWaitHandle;
private WaitHandle _waitHandle;
private StreamReader _standardOutput;
private StreamWriter _standardInput;
private StreamReader _standardError;
private bool _disposed;
private static object s_createProcessLock = new object();
private bool _standardInputAccessed;
private StreamReadMode _outputStreamReadMode;
private StreamReadMode _errorStreamReadMode;
// Support for asynchronously reading streams
public event DataReceivedEventHandler OutputDataReceived;
public event DataReceivedEventHandler ErrorDataReceived;
// Abstract the stream details
internal AsyncStreamReader _output;
internal AsyncStreamReader _error;
internal bool _pendingOutputRead;
internal bool _pendingErrorRead;
/// <devdoc>
/// <para>
/// Initializes a new instance of the <see cref='System.Diagnostics.Process'/> class.
/// </para>
/// </devdoc>
public Process()
{
// This class once inherited a finalizer. For backward compatibility it has one so that
// any derived class that depends on it will see the behaviour expected. Since it is
// not used by this class itself, suppress it immediately if this is not an instance
// of a derived class it doesn't suffer the GC burden of finalization.
if (GetType() == typeof(Process))
{
GC.SuppressFinalize(this);
}
_machineName = ".";
_outputStreamReadMode = StreamReadMode.Undefined;
_errorStreamReadMode = StreamReadMode.Undefined;
}
private Process(string machineName, bool isRemoteMachine, int processId, ProcessInfo processInfo)
{
GC.SuppressFinalize(this);
_processInfo = processInfo;
_machineName = machineName;
_isRemoteMachine = isRemoteMachine;
_processId = processId;
_haveProcessId = true;
_outputStreamReadMode = StreamReadMode.Undefined;
_errorStreamReadMode = StreamReadMode.Undefined;
}
public SafeProcessHandle SafeHandle
{
get
{
EnsureState(State.Associated);
return OpenProcessHandle();
}
}
public IntPtr Handle => SafeHandle.DangerousGetHandle();
/// <devdoc>
/// Returns whether this process component is associated with a real process.
/// </devdoc>
/// <internalonly/>
bool Associated
{
get { return _haveProcessId || _haveProcessHandle; }
}
/// <devdoc>
/// <para>
/// Gets the base priority of
/// the associated process.
/// </para>
/// </devdoc>
public int BasePriority
{
get
{
EnsureState(State.HaveProcessInfo);
return _processInfo.BasePriority;
}
}
/// <devdoc>
/// <para>
/// Gets
/// the
/// value that was specified by the associated process when it was terminated.
/// </para>
/// </devdoc>
public int ExitCode
{
get
{
EnsureState(State.Exited);
return _exitCode;
}
}
/// <devdoc>
/// <para>
/// Gets a
/// value indicating whether the associated process has been terminated.
/// </para>
/// </devdoc>
public bool HasExited
{
get
{
if (!_exited)
{
EnsureState(State.Associated);
UpdateHasExited();
if (_exited)
{
RaiseOnExited();
}
}
return _exited;
}
}
/// <summary>Gets the time the associated process was started.</summary>
public DateTime StartTime
{
get
{
if (!_startTime.HasValue)
{
_startTime = StartTimeCore;
}
return _startTime.Value;
}
}
/// <devdoc>
/// <para>
/// Gets the time that the associated process exited.
/// </para>
/// </devdoc>
public DateTime ExitTime
{
get
{
if (!_haveExitTime)
{
EnsureState(State.Exited);
_exitTime = ExitTimeCore;
_haveExitTime = true;
}
return _exitTime;
}
}
/// <devdoc>
/// <para>
/// Gets
/// the unique identifier for the associated process.
/// </para>
/// </devdoc>
public int Id
{
get
{
EnsureState(State.HaveId);
return _processId;
}
}
/// <devdoc>
/// <para>
/// Gets
/// the name of the computer on which the associated process is running.
/// </para>
/// </devdoc>
public string MachineName
{
get
{
EnsureState(State.Associated);
return _machineName;
}
}
/// <devdoc>
/// <para>
/// Gets or sets the maximum allowable working set for the associated
/// process.
/// </para>
/// </devdoc>
public IntPtr MaxWorkingSet
{
get
{
EnsureWorkingSetLimits();
return _maxWorkingSet;
}
set
{
SetWorkingSetLimits(null, value);
}
}
/// <devdoc>
/// <para>
/// Gets or sets the minimum allowable working set for the associated
/// process.
/// </para>
/// </devdoc>
public IntPtr MinWorkingSet
{
get
{
EnsureWorkingSetLimits();
return _minWorkingSet;
}
set
{
SetWorkingSetLimits(value, null);
}
}
public ProcessModuleCollection Modules
{
get
{
if (_modules == null)
{
EnsureState(State.HaveNonExitedId | State.IsLocal);
_modules = ProcessManager.GetModules(_processId);
}
return _modules;
}
}
public long NonpagedSystemMemorySize64
{
get
{
EnsureState(State.HaveProcessInfo);
return _processInfo.PoolNonPagedBytes;
}
}
[ObsoleteAttribute("This property has been deprecated. Please use System.Diagnostics.Process.NonpagedSystemMemorySize64 instead. https://go.microsoft.com/fwlink/?linkid=14202")]
public int NonpagedSystemMemorySize
{
get
{
EnsureState(State.HaveProcessInfo);
return unchecked((int)_processInfo.PoolNonPagedBytes);
}
}
public long PagedMemorySize64
{
get
{
EnsureState(State.HaveProcessInfo);
return _processInfo.PageFileBytes;
}
}
[ObsoleteAttribute("This property has been deprecated. Please use System.Diagnostics.Process.PagedMemorySize64 instead. https://go.microsoft.com/fwlink/?linkid=14202")]
public int PagedMemorySize
{
get
{
EnsureState(State.HaveProcessInfo);
return unchecked((int)_processInfo.PageFileBytes);
}
}
public long PagedSystemMemorySize64
{
get
{
EnsureState(State.HaveProcessInfo);
return _processInfo.PoolPagedBytes;
}
}
[ObsoleteAttribute("This property has been deprecated. Please use System.Diagnostics.Process.PagedSystemMemorySize64 instead. https://go.microsoft.com/fwlink/?linkid=14202")]
public int PagedSystemMemorySize
{
get
{
EnsureState(State.HaveProcessInfo);
return unchecked((int)_processInfo.PoolPagedBytes);
}
}
public long PeakPagedMemorySize64
{
get
{
EnsureState(State.HaveProcessInfo);
return _processInfo.PageFileBytesPeak;
}
}
[ObsoleteAttribute("This property has been deprecated. Please use System.Diagnostics.Process.PeakPagedMemorySize64 instead. https://go.microsoft.com/fwlink/?linkid=14202")]
public int PeakPagedMemorySize
{
get
{
EnsureState(State.HaveProcessInfo);
return unchecked((int)_processInfo.PageFileBytesPeak);
}
}
public long PeakWorkingSet64
{
get
{
EnsureState(State.HaveProcessInfo);
return _processInfo.WorkingSetPeak;
}
}
[ObsoleteAttribute("This property has been deprecated. Please use System.Diagnostics.Process.PeakWorkingSet64 instead. https://go.microsoft.com/fwlink/?linkid=14202")]
public int PeakWorkingSet
{
get
{
EnsureState(State.HaveProcessInfo);
return unchecked((int)_processInfo.WorkingSetPeak);
}
}
public long PeakVirtualMemorySize64
{
get
{
EnsureState(State.HaveProcessInfo);
return _processInfo.VirtualBytesPeak;
}
}
[ObsoleteAttribute("This property has been deprecated. Please use System.Diagnostics.Process.PeakVirtualMemorySize64 instead. https://go.microsoft.com/fwlink/?linkid=14202")]
public int PeakVirtualMemorySize
{
get
{
EnsureState(State.HaveProcessInfo);
return unchecked((int)_processInfo.VirtualBytesPeak);
}
}
/// <devdoc>
/// <para>
/// Gets or sets a value indicating whether the associated process priority
/// should be temporarily boosted by the operating system when the main window
/// has focus.
/// </para>
/// </devdoc>
public bool PriorityBoostEnabled
{
get
{
if (!_havePriorityBoostEnabled)
{
_priorityBoostEnabled = PriorityBoostEnabledCore;
_havePriorityBoostEnabled = true;
}
return _priorityBoostEnabled;
}
set
{
PriorityBoostEnabledCore = value;
_priorityBoostEnabled = value;
_havePriorityBoostEnabled = true;
}
}
/// <devdoc>
/// <para>
/// Gets or sets the overall priority category for the
/// associated process.
/// </para>
/// </devdoc>
public ProcessPriorityClass PriorityClass
{
get
{
if (!_havePriorityClass)
{
_priorityClass = PriorityClassCore;
_havePriorityClass = true;
}
return _priorityClass;
}
set
{
if (!Enum.IsDefined(typeof(ProcessPriorityClass), value))
{
throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(ProcessPriorityClass));
}
PriorityClassCore = value;
_priorityClass = value;
_havePriorityClass = true;
}
}
public long PrivateMemorySize64
{
get
{
EnsureState(State.HaveProcessInfo);
return _processInfo.PrivateBytes;
}
}
[ObsoleteAttribute("This property has been deprecated. Please use System.Diagnostics.Process.PrivateMemorySize64 instead. https://go.microsoft.com/fwlink/?linkid=14202")]
public int PrivateMemorySize
{
get
{
EnsureState(State.HaveProcessInfo);
return unchecked((int)_processInfo.PrivateBytes);
}
}
/// <devdoc>
/// <para>
/// Gets
/// the friendly name of the process.
/// </para>
/// </devdoc>
public string ProcessName
{
get
{
EnsureState(State.HaveProcessInfo);
return _processInfo.ProcessName;
}
}
/// <devdoc>
/// <para>
/// Gets
/// or sets which processors the threads in this process can be scheduled to run on.
/// </para>
/// </devdoc>
public IntPtr ProcessorAffinity
{
get
{
if (!_haveProcessorAffinity)
{
_processorAffinity = ProcessorAffinityCore;
_haveProcessorAffinity = true;
}
return _processorAffinity;
}
set
{
ProcessorAffinityCore = value;
_processorAffinity = value;
_haveProcessorAffinity = true;
}
}
public int SessionId
{
get
{
EnsureState(State.HaveProcessInfo);
return _processInfo.SessionId;
}
}
/// <devdoc>
/// <para>
/// Gets or sets the properties to pass into the <see cref='System.Diagnostics.Process.Start(System.Diagnostics.ProcessStartInfo)'/> method for the <see cref='System.Diagnostics.Process'/>.
/// </para>
/// </devdoc>
public ProcessStartInfo StartInfo
{
get
{
if (_startInfo == null)
{
if (Associated)
{
throw new InvalidOperationException(SR.CantGetProcessStartInfo);
}
_startInfo = new ProcessStartInfo();
}
return _startInfo;
}
set
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
if (Associated)
{
throw new InvalidOperationException(SR.CantSetProcessStartInfo);
}
_startInfo = value;
}
}
/// <devdoc>
/// <para>
/// Gets the set of threads that are running in the associated
/// process.
/// </para>
/// </devdoc>
public ProcessThreadCollection Threads
{
get
{
if (_threads == null)
{
EnsureState(State.HaveProcessInfo);
int count = _processInfo._threadInfoList.Count;
ProcessThread[] newThreadsArray = new ProcessThread[count];
for (int i = 0; i < count; i++)
{
newThreadsArray[i] = new ProcessThread(_isRemoteMachine, _processId, (ThreadInfo)_processInfo._threadInfoList[i]);
}
ProcessThreadCollection newThreads = new ProcessThreadCollection(newThreadsArray);
_threads = newThreads;
}
return _threads;
}
}
public int HandleCount
{
get
{
EnsureState(State.HaveProcessInfo);
EnsureHandleCountPopulated();
return _processInfo.HandleCount;
}
}
partial void EnsureHandleCountPopulated();
public long VirtualMemorySize64
{
get
{
EnsureState(State.HaveProcessInfo);
return _processInfo.VirtualBytes;
}
}
[ObsoleteAttribute("This property has been deprecated. Please use System.Diagnostics.Process.VirtualMemorySize64 instead. https://go.microsoft.com/fwlink/?linkid=14202")]
public int VirtualMemorySize
{
get
{
EnsureState(State.HaveProcessInfo);
return unchecked((int)_processInfo.VirtualBytes);
}
}
/// <devdoc>
/// <para>
/// Gets or sets whether the <see cref='System.Diagnostics.Process.Exited'/>
/// event is fired
/// when the process terminates.
/// </para>
/// </devdoc>
public bool EnableRaisingEvents
{
get
{
return _watchForExit;
}
set
{
if (value != _watchForExit)
{
if (Associated)
{
if (value)
{
OpenProcessHandle();
EnsureWatchingForExit();
}
else
{
StopWatchingForExit();
}
}
_watchForExit = value;
}
}
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public StreamWriter StandardInput
{
get
{
if (_standardInput == null)
{
throw new InvalidOperationException(SR.CantGetStandardIn);
}
_standardInputAccessed = true;
return _standardInput;
}
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public StreamReader StandardOutput
{
get
{
if (_standardOutput == null)
{
throw new InvalidOperationException(SR.CantGetStandardOut);
}
if (_outputStreamReadMode == StreamReadMode.Undefined)
{
_outputStreamReadMode = StreamReadMode.SyncMode;
}
else if (_outputStreamReadMode != StreamReadMode.SyncMode)
{
throw new InvalidOperationException(SR.CantMixSyncAsyncOperation);
}
return _standardOutput;
}
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public StreamReader StandardError
{
get
{
if (_standardError == null)
{
throw new InvalidOperationException(SR.CantGetStandardError);
}
if (_errorStreamReadMode == StreamReadMode.Undefined)
{
_errorStreamReadMode = StreamReadMode.SyncMode;
}
else if (_errorStreamReadMode != StreamReadMode.SyncMode)
{
throw new InvalidOperationException(SR.CantMixSyncAsyncOperation);
}
return _standardError;
}
}
public long WorkingSet64
{
get
{
EnsureState(State.HaveProcessInfo);
return _processInfo.WorkingSet;
}
}
[ObsoleteAttribute("This property has been deprecated. Please use System.Diagnostics.Process.WorkingSet64 instead. https://go.microsoft.com/fwlink/?linkid=14202")]
public int WorkingSet
{
get
{
EnsureState(State.HaveProcessInfo);
return unchecked((int)_processInfo.WorkingSet);
}
}
public event EventHandler Exited
{
add
{
_onExited += value;
}
remove
{
_onExited -= value;
}
}
/// <devdoc>
/// This is called from the threadpool when a process exits.
/// </devdoc>
/// <internalonly/>
private void CompletionCallback(object waitHandleContext, bool wasSignaled)
{
Debug.Assert(waitHandleContext != null, "Process.CompletionCallback called with no waitHandleContext");
lock (this)
{
// Check the exited event that we get from the threadpool
// matches the event we are waiting for.
if (waitHandleContext != _waitHandle)
{
return;
}
StopWatchingForExit();
RaiseOnExited();
}
}
/// <internalonly/>
/// <devdoc>
/// <para>
/// Free any resources associated with this component.
/// </para>
/// </devdoc>
protected override void Dispose(bool disposing)
{
if (!_disposed)
{
if (disposing)
{
//Dispose managed and unmanaged resources
Close();
}
_disposed = true;
}
}
public bool CloseMainWindow()
{
return CloseMainWindowCore();
}
public bool WaitForInputIdle()
{
return WaitForInputIdle(int.MaxValue);
}
public bool WaitForInputIdle(int milliseconds)
{
return WaitForInputIdleCore(milliseconds);
}
public ISynchronizeInvoke SynchronizingObject { get; set; }
/// <devdoc>
/// <para>
/// Frees any resources associated with this component.
/// </para>
/// </devdoc>
public void Close()
{
if (Associated)
{
if (_haveProcessHandle)
{
// We need to lock to ensure we don't run concurrently with CompletionCallback.
// Without this lock we could reset _raisedOnExited which causes CompletionCallback to
// raise the Exited event a second time for the same process.
lock (this)
{
// This sets _waitHandle to null which causes CompletionCallback to not emit events.
StopWatchingForExit();
}
_processHandle.Dispose();
_processHandle = null;
_haveProcessHandle = false;
}
_haveProcessId = false;
_isRemoteMachine = false;
_machineName = ".";
_raisedOnExited = false;
// Only call close on the streams if the user cannot have a reference on them.
// If they are referenced it is the user's responsibility to dispose of them.
try
{
if (_standardOutput != null && (_outputStreamReadMode == StreamReadMode.AsyncMode || _outputStreamReadMode == StreamReadMode.Undefined))
{
if (_outputStreamReadMode == StreamReadMode.AsyncMode)
{
_output?.CancelOperation();
_output?.Dispose();
}
_standardOutput.Close();
}
if (_standardError != null && (_errorStreamReadMode == StreamReadMode.AsyncMode || _errorStreamReadMode == StreamReadMode.Undefined))
{
if (_errorStreamReadMode == StreamReadMode.AsyncMode)
{
_error?.CancelOperation();
_error?.Dispose();
}
_standardError.Close();
}
if (_standardInput != null && !_standardInputAccessed)
{
_standardInput.Close();
}
}
finally
{
_standardOutput = null;
_standardInput = null;
_standardError = null;
_output = null;
_error = null;
CloseCore();
Refresh();
}
}
}
// Checks if the process hasn't exited on Unix systems.
// This is used to detect recycled child PIDs.
partial void ThrowIfExited(bool refresh);
/// <devdoc>
/// Helper method for checking preconditions when accessing properties.
/// </devdoc>
/// <internalonly/>
private void EnsureState(State state)
{
if ((state & State.Associated) != (State)0)
if (!Associated)
throw new InvalidOperationException(SR.NoAssociatedProcess);
if ((state & State.HaveId) != (State)0)
{
if (!_haveProcessId)
{
if (_haveProcessHandle)
{
SetProcessId(ProcessManager.GetProcessIdFromHandle(_processHandle));
}
else
{
EnsureState(State.Associated);
throw new InvalidOperationException(SR.ProcessIdRequired);
}
}
if ((state & State.HaveNonExitedId) == State.HaveNonExitedId)
{
ThrowIfExited(refresh: false);
}
}
if ((state & State.IsLocal) != (State)0 && _isRemoteMachine)
{
throw new NotSupportedException(SR.NotSupportedRemote);
}
if ((state & State.HaveProcessInfo) != (State)0)
{
if (_processInfo == null)
{
if ((state & State.HaveNonExitedId) != State.HaveNonExitedId)
{
EnsureState(State.HaveNonExitedId);
}
_processInfo = ProcessManager.GetProcessInfo(_processId, _machineName);
if (_processInfo == null)
{
throw new InvalidOperationException(SR.NoProcessInfo);
}
}
}
if ((state & State.Exited) != (State)0)
{
if (!HasExited)
{
throw new InvalidOperationException(SR.WaitTillExit);
}
if (!_haveProcessHandle)
{
throw new InvalidOperationException(SR.NoProcessHandle);
}
}
}
/// <devdoc>
/// Make sure we have obtained the min and max working set limits.
/// </devdoc>
/// <internalonly/>
private void EnsureWorkingSetLimits()
{
if (!_haveWorkingSetLimits)
{
GetWorkingSetLimits(out _minWorkingSet, out _maxWorkingSet);
_haveWorkingSetLimits = true;
}
}
/// <devdoc>
/// Helper to set minimum or maximum working set limits.
/// </devdoc>
/// <internalonly/>
private void SetWorkingSetLimits(IntPtr? min, IntPtr? max)
{
SetWorkingSetLimitsCore(min, max, out _minWorkingSet, out _maxWorkingSet);
_haveWorkingSetLimits = true;
}
/// <devdoc>
/// <para>
/// Returns a new <see cref='System.Diagnostics.Process'/> component given a process identifier and
/// the name of a computer in the network.
/// </para>
/// </devdoc>
public static Process GetProcessById(int processId, string machineName)
{
if (!ProcessManager.IsProcessRunning(processId, machineName))
{
throw new ArgumentException(SR.Format(SR.MissingProccess, processId.ToString()));
}
return new Process(machineName, ProcessManager.IsRemoteMachine(machineName), processId, null);
}
/// <devdoc>
/// <para>
/// Returns a new <see cref='System.Diagnostics.Process'/> component given the
/// identifier of a process on the local computer.
/// </para>
/// </devdoc>
public static Process GetProcessById(int processId)
{
return GetProcessById(processId, ".");
}
/// <devdoc>
/// <para>
/// Creates an array of <see cref='System.Diagnostics.Process'/> components that are
/// associated
/// with process resources on the
/// local computer. These process resources share the specified process name.
/// </para>
/// </devdoc>
public static Process[] GetProcessesByName(string processName)
{
return GetProcessesByName(processName, ".");
}
/// <devdoc>
/// <para>
/// Creates a new <see cref='System.Diagnostics.Process'/>
/// component for each process resource on the local computer.
/// </para>
/// </devdoc>
public static Process[] GetProcesses()
{
return GetProcesses(".");
}
/// <devdoc>
/// <para>
/// Creates a new <see cref='System.Diagnostics.Process'/>
/// component for each
/// process resource on the specified computer.
/// </para>
/// </devdoc>
public static Process[] GetProcesses(string machineName)
{
bool isRemoteMachine = ProcessManager.IsRemoteMachine(machineName);
ProcessInfo[] processInfos = ProcessManager.GetProcessInfos(machineName);
Process[] processes = new Process[processInfos.Length];
for (int i = 0; i < processInfos.Length; i++)
{
ProcessInfo processInfo = processInfos[i];
processes[i] = new Process(machineName, isRemoteMachine, processInfo.ProcessId, processInfo);
}
return processes;
}
/// <devdoc>
/// <para>
/// Returns a new <see cref='System.Diagnostics.Process'/>
/// component and associates it with the current active process.
/// </para>
/// </devdoc>
public static Process GetCurrentProcess()
{
return new Process(".", false, GetCurrentProcessId(), null);
}
/// <devdoc>
/// <para>
/// Raises the <see cref='System.Diagnostics.Process.Exited'/> event.
/// </para>
/// </devdoc>
protected void OnExited()
{
EventHandler exited = _onExited;
if (exited != null)
{
exited(this, EventArgs.Empty);
}
}
/// <devdoc>
/// Raise the Exited event, but make sure we don't do it more than once.
/// </devdoc>
/// <internalonly/>
private void RaiseOnExited()
{
if (!_raisedOnExited)
{
lock (this)
{
if (!_raisedOnExited)
{
_raisedOnExited = true;
OnExited();
}
}
}
}
/// <devdoc>
/// <para>
/// Discards any information about the associated process
/// that has been cached inside the process component. After <see cref='System.Diagnostics.Process.Refresh'/> is called, the
/// first request for information for each property causes the process component
/// to obtain a new value from the associated process.
/// </para>
/// </devdoc>
public void Refresh()
{
_processInfo = null;
_threads = null;
_modules = null;
_exited = false;
_haveWorkingSetLimits = false;
_haveProcessorAffinity = false;
_havePriorityClass = false;
_haveExitTime = false;
_havePriorityBoostEnabled = false;
RefreshCore();
}
/// <summary>
/// Opens a long-term handle to the process, with all access. If a handle exists,
/// then it is reused. If the process has exited, it throws an exception.
/// </summary>
private SafeProcessHandle OpenProcessHandle()
{
if (!_haveProcessHandle)
{
//Cannot open a new process handle if the object has been disposed, since finalization has been suppressed.
if (_disposed)
{
throw new ObjectDisposedException(GetType().Name);
}
SetProcessHandle(GetProcessHandle());
}
return _processHandle;
}
/// <devdoc>
/// Helper to associate a process handle with this component.
/// </devdoc>
/// <internalonly/>
private void SetProcessHandle(SafeProcessHandle processHandle)
{
_processHandle = processHandle;
_haveProcessHandle = true;
if (_watchForExit)
{
EnsureWatchingForExit();
}
}
/// <devdoc>
/// Helper to associate a process id with this component.
/// </devdoc>
/// <internalonly/>
private void SetProcessId(int processId)
{
_processId = processId;
_haveProcessId = true;
ConfigureAfterProcessIdSet();
}
/// <summary>Additional optional configuration hook after a process ID is set.</summary>
partial void ConfigureAfterProcessIdSet();
/// <devdoc>
/// <para>
/// Starts a process specified by the <see cref='System.Diagnostics.Process.StartInfo'/> property of this <see cref='System.Diagnostics.Process'/>
/// component and associates it with the
/// <see cref='System.Diagnostics.Process'/> . If a process resource is reused
/// rather than started, the reused process is associated with this <see cref='System.Diagnostics.Process'/>
/// component.
/// </para>
/// </devdoc>
public bool Start()
{
Close();
ProcessStartInfo startInfo = StartInfo;
if (startInfo.FileName.Length == 0)
{
throw new InvalidOperationException(SR.FileNameMissing);
}
if (startInfo.StandardInputEncoding != null && !startInfo.RedirectStandardInput)
{
throw new InvalidOperationException(SR.StandardInputEncodingNotAllowed);
}
if (startInfo.StandardOutputEncoding != null && !startInfo.RedirectStandardOutput)
{
throw new InvalidOperationException(SR.StandardOutputEncodingNotAllowed);
}
if (startInfo.StandardErrorEncoding != null && !startInfo.RedirectStandardError)
{
throw new InvalidOperationException(SR.StandardErrorEncodingNotAllowed);
}
if (!string.IsNullOrEmpty(startInfo.Arguments) && startInfo.ArgumentList.Count > 0)
{
throw new InvalidOperationException(SR.ArgumentAndArgumentListInitialized);
}
//Cannot start a new process and store its handle if the object has been disposed, since finalization has been suppressed.
if (_disposed)
{
throw new ObjectDisposedException(GetType().Name);
}
return StartCore(startInfo);
}
/// <devdoc>
/// <para>
/// Starts a process resource by specifying the name of a
/// document or application file. Associates the process resource with a new <see cref='System.Diagnostics.Process'/>
/// component.
/// </para>
/// </devdoc>
public static Process Start(string fileName)
{
return Start(new ProcessStartInfo(fileName));
}
/// <devdoc>
/// <para>
/// Starts a process resource by specifying the name of an
/// application and a set of command line arguments. Associates the process resource
/// with a new <see cref='System.Diagnostics.Process'/>
/// component.
/// </para>
/// </devdoc>
public static Process Start(string fileName, string arguments)
{
return Start(new ProcessStartInfo(fileName, arguments));
}
/// <devdoc>
/// <para>
/// Starts a process resource specified by the process start
/// information passed in, for example the file name of the process to start.
/// Associates the process resource with a new <see cref='System.Diagnostics.Process'/>
/// component.
/// </para>
/// </devdoc>
public static Process Start(ProcessStartInfo startInfo)
{
Process process = new Process();
if (startInfo == null)
throw new ArgumentNullException(nameof(startInfo));
process.StartInfo = startInfo;
return process.Start() ?
process :
null;
}
/// <devdoc>
/// Make sure we are not watching for process exit.
/// </devdoc>
/// <internalonly/>
private void StopWatchingForExit()
{
if (_watchingForExit)
{
RegisteredWaitHandle rwh = null;
WaitHandle wh = null;
lock (this)
{
if (_watchingForExit)
{
_watchingForExit = false;
wh = _waitHandle;
_waitHandle = null;
rwh = _registeredWaitHandle;
_registeredWaitHandle = null;
}
}
if (rwh != null)
{
rwh.Unregister(null);
}
if (wh != null)
{
wh.Dispose();
}
}
}
public override string ToString()
{
if (Associated)
{
string processName = ProcessName;
if (processName.Length != 0)
{
return string.Format(CultureInfo.CurrentCulture, "{0} ({1})", base.ToString(), processName);
}
}
return base.ToString();
}
/// <devdoc>
/// <para>
/// Instructs the <see cref='System.Diagnostics.Process'/> component to wait
/// indefinitely for the associated process to exit.
/// </para>
/// </devdoc>
public void WaitForExit()
{
WaitForExit(Timeout.Infinite);
}
/// <summary>
/// Instructs the Process component to wait the specified number of milliseconds for
/// the associated process to exit.
/// </summary>
public bool WaitForExit(int milliseconds)
{
bool exited = WaitForExitCore(milliseconds);
if (exited && _watchForExit)
{
RaiseOnExited();
}
return exited;
}
/// <devdoc>
/// <para>
/// Instructs the <see cref='System.Diagnostics.Process'/> component to start
/// reading the StandardOutput stream asynchronously. The user can register a callback
/// that will be called when a line of data terminated by \n,\r or \r\n is reached, or the end of stream is reached
/// then the remaining information is returned. The user can add an event handler to OutputDataReceived.
/// </para>
/// </devdoc>
public void BeginOutputReadLine()
{
if (_outputStreamReadMode == StreamReadMode.Undefined)
{
_outputStreamReadMode = StreamReadMode.AsyncMode;
}
else if (_outputStreamReadMode != StreamReadMode.AsyncMode)
{
throw new InvalidOperationException(SR.CantMixSyncAsyncOperation);
}
if (_pendingOutputRead)
throw new InvalidOperationException(SR.PendingAsyncOperation);
_pendingOutputRead = true;
// We can't detect if there's a pending synchronous read, stream also doesn't.
if (_output == null)
{
if (_standardOutput == null)
{
throw new InvalidOperationException(SR.CantGetStandardOut);
}
Stream s = _standardOutput.BaseStream;
_output = new AsyncStreamReader(s, OutputReadNotifyUser, _standardOutput.CurrentEncoding);
}
_output.BeginReadLine();
}
/// <devdoc>
/// <para>
/// Instructs the <see cref='System.Diagnostics.Process'/> component to start
/// reading the StandardError stream asynchronously. The user can register a callback
/// that will be called when a line of data terminated by \n,\r or \r\n is reached, or the end of stream is reached
/// then the remaining information is returned. The user can add an event handler to ErrorDataReceived.
/// </para>
/// </devdoc>
public void BeginErrorReadLine()
{
if (_errorStreamReadMode == StreamReadMode.Undefined)
{
_errorStreamReadMode = StreamReadMode.AsyncMode;
}
else if (_errorStreamReadMode != StreamReadMode.AsyncMode)
{
throw new InvalidOperationException(SR.CantMixSyncAsyncOperation);
}
if (_pendingErrorRead)
{
throw new InvalidOperationException(SR.PendingAsyncOperation);
}
_pendingErrorRead = true;
// We can't detect if there's a pending synchronous read, stream also doesn't.
if (_error == null)
{
if (_standardError == null)
{
throw new InvalidOperationException(SR.CantGetStandardError);
}
Stream s = _standardError.BaseStream;
_error = new AsyncStreamReader(s, ErrorReadNotifyUser, _standardError.CurrentEncoding);
}
_error.BeginReadLine();
}
/// <devdoc>
/// <para>
/// Instructs the <see cref='System.Diagnostics.Process'/> component to cancel the asynchronous operation
/// specified by BeginOutputReadLine().
/// </para>
/// </devdoc>
public void CancelOutputRead()
{
if (_output != null)
{
_output.CancelOperation();
}
else
{
throw new InvalidOperationException(SR.NoAsyncOperation);
}
_pendingOutputRead = false;
}
/// <devdoc>
/// <para>
/// Instructs the <see cref='System.Diagnostics.Process'/> component to cancel the asynchronous operation
/// specified by BeginErrorReadLine().
/// </para>
/// </devdoc>
public void CancelErrorRead()
{
if (_error != null)
{
_error.CancelOperation();
}
else
{
throw new InvalidOperationException(SR.NoAsyncOperation);
}
_pendingErrorRead = false;
}
internal void OutputReadNotifyUser(string data)
{
// To avoid race between remove handler and raising the event
DataReceivedEventHandler outputDataReceived = OutputDataReceived;
if (outputDataReceived != null)
{
DataReceivedEventArgs e = new DataReceivedEventArgs(data);
outputDataReceived(this, e); // Call back to user informing data is available
}
}
internal void ErrorReadNotifyUser(string data)
{
// To avoid race between remove handler and raising the event
DataReceivedEventHandler errorDataReceived = ErrorDataReceived;
if (errorDataReceived != null)
{
DataReceivedEventArgs e = new DataReceivedEventArgs(data);
errorDataReceived(this, e); // Call back to user informing data is available.
}
}
private static void AppendArguments(StringBuilder stringBuilder, Collection<string> argumentList)
{
if (argumentList.Count > 0)
{
foreach (string argument in argumentList)
{
PasteArguments.AppendArgument(stringBuilder, argument);
}
}
}
/// <summary>
/// This enum defines the operation mode for redirected process stream.
/// We don't support switching between synchronous mode and asynchronous mode.
/// </summary>
private enum StreamReadMode
{
Undefined,
SyncMode,
AsyncMode
}
/// <summary>A desired internal state.</summary>
private enum State
{
HaveId = 0x1,
IsLocal = 0x2,
HaveNonExitedId = HaveId | 0x4,
HaveProcessInfo = 0x8,
Exited = 0x10,
Associated = 0x20,
}
}
}
| |
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 UdcxRemediation.Console
{
/// <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 app.
/// 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 Gtk;
using PubNubMessaging.Core;
using PubnubMessagingExampleGTK;
using System.Text;
public partial class MainWindow2: Gtk.Window
{
public string PublishMessage
{
get;set;
}
public string Channel
{
get;set;
}
public bool Ssl
{
get;set;
}
public string Cipher
{
get;set;
}
public string CustomUuid
{
get;set;
}
public string Server
{
get;set;
}
public int Port
{
get;set;
}
public string Username
{
get;set;
}
public string Password
{
get;set;
}
public Pubnub pubnub;
public MainWindow2 (): base (Gtk.WindowType.Toplevel)
{
//Build ();
DisableActions();
ShowSettings();
}
protected void OnDeleteEvent (object sender, DeleteEventArgs a)
{
Application.Quit ();
a.RetVal = true;
}
protected void DisplayReturnMessage (string result)
{
WriteToOutput(result);
}
void WriteToOutput(string output)
{
Gtk.Application.Invoke(delegate {
StringBuilder sb = new StringBuilder();
sb.Append(DateTime.Now.ToLongTimeString());
sb.Append(" : ");
sb.AppendLine(output);
//sb.Append(textViewOutput.Buffer.Text);
//textViewOutput.Buffer.Text = sb.ToString();
});
}
protected void DisplayConnectStatusMessage(string result)
{
WriteToOutput(result);
}
protected void SubscribeClicked (object sender, System.EventArgs e)
{
WriteToOutput("Running Subscribe");
pubnub.Subscribe<string>(this.Channel, DisplayReturnMessage, DisplayConnectStatusMessage);
}
protected void PublishClicked (object sender, System.EventArgs e)
{
/*PublishMessageDialog publishMessage = new PublishMessageDialog(this);
publishMessage.Modal = true;
publishMessage.Name = "Enter Message";
publishMessage.Response += delegate(object o, ResponseArgs args) {
if(args.ResponseId == Gtk.ResponseType.Ok)
{
Console.WriteLine(this.PublishMessage);
string []channels = this.Channel.Split(',');
foreach (string ch in channels)
{
pubnub.Publish<string>(ch, this.PublishMessage, DisplayReturnMessage);
}
}
};
publishMessage.Run();
publishMessage.Destroy();*/
}
protected void PresenceClicked (object sender, System.EventArgs e)
{
pubnub.Presence<string>(this.Channel, DisplayReturnMessage, DisplayConnectStatusMessage);
}
public void DisableActions ()
{
btnCancel.Sensitive = false;
btnDetailedHistory.Sensitive = false;
btnHereNow.Sensitive = false;
btnPresence.Sensitive = false;
btnPublish.Sensitive = false;
btnSubscribe.Sensitive = false;
btnTime.Sensitive = false;
btnUnsub.Sensitive = false;
btnUnsubPres.Sensitive = false;
}
protected void EnableActions ()
{
btnCancel.Sensitive = true;
btnDetailedHistory.Sensitive = true;
btnHereNow.Sensitive = true;
btnPresence.Sensitive = true;
btnPublish.Sensitive = true;
btnSubscribe.Sensitive = true;
btnTime.Sensitive = true;
btnUnsub.Sensitive = true;
btnUnsubPres.Sensitive = true;
}
protected void ShowSettings ()
{
/*SettingsDialog settings = new SettingsDialog(this);
settings.Modal = true;
settings.Name = "Settings";
bool errorFree = true;
settings.Response += delegate(object o, ResponseArgs args) {
if(args.ResponseId == Gtk.ResponseType.Ok)
{
//string channel = this.Channel;
pubnub = new Pubnub("demo", "demo", "", this.Cipher , this.Ssl);
pubnub.SessionUUID = this.CustomUuid;
StringBuilder sbHead = new StringBuilder();
sbHead.Append("Ch:");
sbHead.Append(this.Channel);
sbHead.Append("; ");
sbHead.Append((this.Ssl)?"Ssl": "");
this.lblHead.Text = sbHead.ToString();
PubnubProxy proxy = new PubnubProxy();
if(!string.IsNullOrWhiteSpace(this.Server))
{
proxy.ProxyServer = this.Server;
proxy.ProxyPort = this.Port;
proxy.ProxyUserName = this.Username;
proxy.ProxyPassword = this.Password;
try
{
pubnub.Proxy = proxy;
}
catch (MissingFieldException mse)
{
Console.WriteLine(mse.Message);
errorFree = false;
}
}
if(errorFree)
{
EnableActions();
}
else
{
ShowSettings();
}
}
};
settings.Run ();
settings.Destroy();*/
}
protected void SettingsClicked (object sender, System.EventArgs e)
{
ShowSettings();
}
protected void UnsubscribePresenceClicked (object sender, System.EventArgs e)
{
pubnub.PresenceUnsubscribe<string>(this.Channel, DisplayReturnMessage, DisplayReturnMessage, DisplayReturnMessage);
}
protected void UnsubscribeClicked (object sender, System.EventArgs e)
{
pubnub.Unsubscribe<string>(this.Channel, DisplayReturnMessage, DisplayReturnMessage, DisplayReturnMessage);
}
protected void HereNowClicked (object sender, System.EventArgs e)
{
string[] channels = this.Channel.Split(',');
foreach (string ch in channels)
{
pubnub.HereNow<string>(ch, DisplayReturnMessage);
}
}
protected void DetailedHistoryClicked (object sender, System.EventArgs e)
{
string[] channels = this.Channel.Split(',');
foreach (string ch in channels)
{
pubnub.DetailedHistory<string>(ch, 100, DisplayReturnMessage);
}
}
protected void CancelClicked (object sender, System.EventArgs e)
{
pubnub.TerminateCurrentSubscriberRequest();
}
protected void TimeClicked (object sender, System.EventArgs e)
{
pubnub.Time<string>(DisplayReturnMessage);
}
}
| |
// 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 gaxgrpc = Google.Api.Gax.Grpc;
using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore;
using proto = Google.Protobuf;
using grpccore = Grpc.Core;
using grpcinter = Grpc.Core.Interceptors;
using sys = System;
using scg = System.Collections.Generic;
using sco = System.Collections.ObjectModel;
using st = System.Threading;
using stt = System.Threading.Tasks;
namespace Google.Cloud.BinaryAuthorization.V1
{
/// <summary>Settings for <see cref="SystemPolicyV1Client"/> instances.</summary>
public sealed partial class SystemPolicyV1Settings : gaxgrpc::ServiceSettingsBase
{
/// <summary>Get a new instance of the default <see cref="SystemPolicyV1Settings"/>.</summary>
/// <returns>A new instance of the default <see cref="SystemPolicyV1Settings"/>.</returns>
public static SystemPolicyV1Settings GetDefault() => new SystemPolicyV1Settings();
/// <summary>Constructs a new <see cref="SystemPolicyV1Settings"/> object with default settings.</summary>
public SystemPolicyV1Settings()
{
}
private SystemPolicyV1Settings(SystemPolicyV1Settings existing) : base(existing)
{
gax::GaxPreconditions.CheckNotNull(existing, nameof(existing));
GetSystemPolicySettings = existing.GetSystemPolicySettings;
OnCopy(existing);
}
partial void OnCopy(SystemPolicyV1Settings existing);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>SystemPolicyV1Client.GetSystemPolicy</c> and <c>SystemPolicyV1Client.GetSystemPolicyAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>This call will not be retried.</description></item>
/// <item><description>No timeout is applied.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings GetSystemPolicySettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.None);
/// <summary>Creates a deep clone of this object, with all the same property values.</summary>
/// <returns>A deep clone of this <see cref="SystemPolicyV1Settings"/> object.</returns>
public SystemPolicyV1Settings Clone() => new SystemPolicyV1Settings(this);
}
/// <summary>
/// Builder class for <see cref="SystemPolicyV1Client"/> to provide simple configuration of credentials, endpoint
/// etc.
/// </summary>
public sealed partial class SystemPolicyV1ClientBuilder : gaxgrpc::ClientBuilderBase<SystemPolicyV1Client>
{
/// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary>
public SystemPolicyV1Settings Settings { get; set; }
/// <summary>Creates a new builder with default settings.</summary>
public SystemPolicyV1ClientBuilder()
{
UseJwtAccessWithScopes = SystemPolicyV1Client.UseJwtAccessWithScopes;
}
partial void InterceptBuild(ref SystemPolicyV1Client client);
partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<SystemPolicyV1Client> task);
/// <summary>Builds the resulting client.</summary>
public override SystemPolicyV1Client Build()
{
SystemPolicyV1Client client = null;
InterceptBuild(ref client);
return client ?? BuildImpl();
}
/// <summary>Builds the resulting client asynchronously.</summary>
public override stt::Task<SystemPolicyV1Client> BuildAsync(st::CancellationToken cancellationToken = default)
{
stt::Task<SystemPolicyV1Client> task = null;
InterceptBuildAsync(cancellationToken, ref task);
return task ?? BuildAsyncImpl(cancellationToken);
}
private SystemPolicyV1Client BuildImpl()
{
Validate();
grpccore::CallInvoker callInvoker = CreateCallInvoker();
return SystemPolicyV1Client.Create(callInvoker, Settings);
}
private async stt::Task<SystemPolicyV1Client> BuildAsyncImpl(st::CancellationToken cancellationToken)
{
Validate();
grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false);
return SystemPolicyV1Client.Create(callInvoker, Settings);
}
/// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary>
protected override string GetDefaultEndpoint() => SystemPolicyV1Client.DefaultEndpoint;
/// <summary>
/// Returns the default scopes for this builder type, used if no scopes are otherwise specified.
/// </summary>
protected override scg::IReadOnlyList<string> GetDefaultScopes() => SystemPolicyV1Client.DefaultScopes;
/// <summary>Returns the channel pool to use when no other options are specified.</summary>
protected override gaxgrpc::ChannelPool GetChannelPool() => SystemPolicyV1Client.ChannelPool;
/// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary>
protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance;
}
/// <summary>SystemPolicyV1 client wrapper, for convenient use.</summary>
/// <remarks>
/// API for working with the system policy.
/// </remarks>
public abstract partial class SystemPolicyV1Client
{
/// <summary>
/// The default endpoint for the SystemPolicyV1 service, which is a host of "binaryauthorization.googleapis.com"
/// and a port of 443.
/// </summary>
public static string DefaultEndpoint { get; } = "binaryauthorization.googleapis.com:443";
/// <summary>The default SystemPolicyV1 scopes.</summary>
/// <remarks>
/// The default SystemPolicyV1 scopes are:
/// <list type="bullet">
/// <item><description>https://www.googleapis.com/auth/cloud-platform</description></item>
/// </list>
/// </remarks>
public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[]
{
"https://www.googleapis.com/auth/cloud-platform",
});
internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes);
internal static bool UseJwtAccessWithScopes
{
get
{
bool useJwtAccessWithScopes = true;
MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes);
return useJwtAccessWithScopes;
}
}
static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes);
/// <summary>
/// Asynchronously creates a <see cref="SystemPolicyV1Client"/> using the default credentials, endpoint and
/// settings. To specify custom credentials or other settings, use <see cref="SystemPolicyV1ClientBuilder"/>.
/// </summary>
/// <param name="cancellationToken">
/// The <see cref="st::CancellationToken"/> to use while creating the client.
/// </param>
/// <returns>The task representing the created <see cref="SystemPolicyV1Client"/>.</returns>
public static stt::Task<SystemPolicyV1Client> CreateAsync(st::CancellationToken cancellationToken = default) =>
new SystemPolicyV1ClientBuilder().BuildAsync(cancellationToken);
/// <summary>
/// Synchronously creates a <see cref="SystemPolicyV1Client"/> using the default credentials, endpoint and
/// settings. To specify custom credentials or other settings, use <see cref="SystemPolicyV1ClientBuilder"/>.
/// </summary>
/// <returns>The created <see cref="SystemPolicyV1Client"/>.</returns>
public static SystemPolicyV1Client Create() => new SystemPolicyV1ClientBuilder().Build();
/// <summary>
/// Creates a <see cref="SystemPolicyV1Client"/> which uses the specified call invoker for remote operations.
/// </summary>
/// <param name="callInvoker">
/// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null.
/// </param>
/// <param name="settings">Optional <see cref="SystemPolicyV1Settings"/>.</param>
/// <returns>The created <see cref="SystemPolicyV1Client"/>.</returns>
internal static SystemPolicyV1Client Create(grpccore::CallInvoker callInvoker, SystemPolicyV1Settings settings = null)
{
gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker));
grpcinter::Interceptor interceptor = settings?.Interceptor;
if (interceptor != null)
{
callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor);
}
SystemPolicyV1.SystemPolicyV1Client grpcClient = new SystemPolicyV1.SystemPolicyV1Client(callInvoker);
return new SystemPolicyV1ClientImpl(grpcClient, settings);
}
/// <summary>
/// Shuts down any channels automatically created by <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not
/// affected.
/// </summary>
/// <remarks>
/// After calling this method, further calls to <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down
/// by another call to this method.
/// </remarks>
/// <returns>A task representing the asynchronous shutdown operation.</returns>
public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync();
/// <summary>The underlying gRPC SystemPolicyV1 client</summary>
public virtual SystemPolicyV1.SystemPolicyV1Client GrpcClient => throw new sys::NotImplementedException();
/// <summary>
/// Gets the current system policy in the specified location.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual Policy GetSystemPolicy(GetSystemPolicyRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Gets the current system policy in the specified location.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<Policy> GetSystemPolicyAsync(GetSystemPolicyRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Gets the current system policy in the specified location.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<Policy> GetSystemPolicyAsync(GetSystemPolicyRequest request, st::CancellationToken cancellationToken) =>
GetSystemPolicyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Gets the current system policy in the specified location.
/// </summary>
/// <param name="name">
/// Required. The resource name, in the format `locations/*/policy`.
/// Note that the system policy is not associated with a project.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual Policy GetSystemPolicy(string name, gaxgrpc::CallSettings callSettings = null) =>
GetSystemPolicy(new GetSystemPolicyRequest
{
Name = gax::GaxPreconditions.CheckNotNullOrEmpty(name, nameof(name)),
}, callSettings);
/// <summary>
/// Gets the current system policy in the specified location.
/// </summary>
/// <param name="name">
/// Required. The resource name, in the format `locations/*/policy`.
/// Note that the system policy is not associated with a project.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<Policy> GetSystemPolicyAsync(string name, gaxgrpc::CallSettings callSettings = null) =>
GetSystemPolicyAsync(new GetSystemPolicyRequest
{
Name = gax::GaxPreconditions.CheckNotNullOrEmpty(name, nameof(name)),
}, callSettings);
/// <summary>
/// Gets the current system policy in the specified location.
/// </summary>
/// <param name="name">
/// Required. The resource name, in the format `locations/*/policy`.
/// Note that the system policy is not associated with a project.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<Policy> GetSystemPolicyAsync(string name, st::CancellationToken cancellationToken) =>
GetSystemPolicyAsync(name, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Gets the current system policy in the specified location.
/// </summary>
/// <param name="name">
/// Required. The resource name, in the format `locations/*/policy`.
/// Note that the system policy is not associated with a project.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual Policy GetSystemPolicy(PolicyName name, gaxgrpc::CallSettings callSettings = null) =>
GetSystemPolicy(new GetSystemPolicyRequest
{
PolicyName = gax::GaxPreconditions.CheckNotNull(name, nameof(name)),
}, callSettings);
/// <summary>
/// Gets the current system policy in the specified location.
/// </summary>
/// <param name="name">
/// Required. The resource name, in the format `locations/*/policy`.
/// Note that the system policy is not associated with a project.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<Policy> GetSystemPolicyAsync(PolicyName name, gaxgrpc::CallSettings callSettings = null) =>
GetSystemPolicyAsync(new GetSystemPolicyRequest
{
PolicyName = gax::GaxPreconditions.CheckNotNull(name, nameof(name)),
}, callSettings);
/// <summary>
/// Gets the current system policy in the specified location.
/// </summary>
/// <param name="name">
/// Required. The resource name, in the format `locations/*/policy`.
/// Note that the system policy is not associated with a project.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<Policy> GetSystemPolicyAsync(PolicyName name, st::CancellationToken cancellationToken) =>
GetSystemPolicyAsync(name, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
}
/// <summary>SystemPolicyV1 client wrapper implementation, for convenient use.</summary>
/// <remarks>
/// API for working with the system policy.
/// </remarks>
public sealed partial class SystemPolicyV1ClientImpl : SystemPolicyV1Client
{
private readonly gaxgrpc::ApiCall<GetSystemPolicyRequest, Policy> _callGetSystemPolicy;
/// <summary>
/// Constructs a client wrapper for the SystemPolicyV1 service, with the specified gRPC client and settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">The base <see cref="SystemPolicyV1Settings"/> used within this client.</param>
public SystemPolicyV1ClientImpl(SystemPolicyV1.SystemPolicyV1Client grpcClient, SystemPolicyV1Settings settings)
{
GrpcClient = grpcClient;
SystemPolicyV1Settings effectiveSettings = settings ?? SystemPolicyV1Settings.GetDefault();
gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings);
_callGetSystemPolicy = clientHelper.BuildApiCall<GetSystemPolicyRequest, Policy>(grpcClient.GetSystemPolicyAsync, grpcClient.GetSystemPolicy, effectiveSettings.GetSystemPolicySettings).WithGoogleRequestParam("name", request => request.Name);
Modify_ApiCall(ref _callGetSystemPolicy);
Modify_GetSystemPolicyApiCall(ref _callGetSystemPolicy);
OnConstruction(grpcClient, effectiveSettings, clientHelper);
}
partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>;
partial void Modify_GetSystemPolicyApiCall(ref gaxgrpc::ApiCall<GetSystemPolicyRequest, Policy> call);
partial void OnConstruction(SystemPolicyV1.SystemPolicyV1Client grpcClient, SystemPolicyV1Settings effectiveSettings, gaxgrpc::ClientHelper clientHelper);
/// <summary>The underlying gRPC SystemPolicyV1 client</summary>
public override SystemPolicyV1.SystemPolicyV1Client GrpcClient { get; }
partial void Modify_GetSystemPolicyRequest(ref GetSystemPolicyRequest request, ref gaxgrpc::CallSettings settings);
/// <summary>
/// Gets the current system policy in the specified location.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override Policy GetSystemPolicy(GetSystemPolicyRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetSystemPolicyRequest(ref request, ref callSettings);
return _callGetSystemPolicy.Sync(request, callSettings);
}
/// <summary>
/// Gets the current system policy in the specified location.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<Policy> GetSystemPolicyAsync(GetSystemPolicyRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetSystemPolicyRequest(ref request, ref callSettings);
return _callGetSystemPolicy.Async(request, callSettings);
}
}
}
| |
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Extensions.Logging;
using NUnit.Framework;
using Umbraco.Cms.Core;
using Umbraco.Cms.Core.Cache;
using Umbraco.Cms.Core.Models;
using Umbraco.Cms.Core.Persistence;
using Umbraco.Cms.Core.Persistence.Repositories;
using Umbraco.Cms.Core.Scoping;
using Umbraco.Cms.Infrastructure.Persistence.Repositories.Implement;
using Umbraco.Cms.Tests.Common.Builders;
using Umbraco.Cms.Tests.Common.Testing;
using Umbraco.Cms.Tests.Integration.Testing;
namespace Umbraco.Cms.Tests.Integration.Umbraco.Infrastructure.Persistence.Repositories
{
[TestFixture]
[UmbracoTest(Database = UmbracoTestOptions.Database.NewSchemaPerTest)]
public class MediaTypeRepositoryTest : UmbracoIntegrationTest
{
private IContentTypeCommonRepository CommonRepository => GetRequiredService<IContentTypeCommonRepository>();
private ILanguageRepository LanguageRepository => GetRequiredService<ILanguageRepository>();
[Test]
public void Can_Move()
{
IScopeProvider provider = ScopeProvider;
using (IScope scope = provider.CreateScope())
{
EntityContainerRepository containerRepository = CreateContainerRepository(provider);
MediaTypeRepository repository = CreateRepository(provider);
var container1 = new EntityContainer(Constants.ObjectTypes.MediaType) { Name = "blah1" };
containerRepository.Save(container1);
var container2 = new EntityContainer(Constants.ObjectTypes.MediaType) { Name = "blah2", ParentId = container1.Id };
containerRepository.Save(container2);
IMediaType contentType =
MediaTypeBuilder.CreateNewMediaType();
contentType.ParentId = container2.Id;
repository.Save(contentType);
// create a
var contentType2 = (IMediaType)new MediaType(ShortStringHelper, contentType, "hello")
{
Name = "Blahasdfsadf"
};
contentType.ParentId = contentType.Id;
repository.Save(contentType2);
global::Umbraco.Cms.Core.Events.MoveEventInfo<IMediaType>[] result = repository.Move(contentType, container1).ToArray();
Assert.AreEqual(2, result.Length);
// re-get
contentType = repository.Get(contentType.Id);
contentType2 = repository.Get(contentType2.Id);
Assert.AreEqual(container1.Id, contentType.ParentId);
Assert.AreNotEqual(result.Single(x => x.Entity.Id == contentType.Id).OriginalPath, contentType.Path);
Assert.AreNotEqual(result.Single(x => x.Entity.Id == contentType2.Id).OriginalPath, contentType2.Path);
}
}
[Test]
public void Can_Create_Container()
{
IScopeProvider provider = ScopeProvider;
using (IScope scope = provider.CreateScope())
{
EntityContainerRepository containerRepository = CreateContainerRepository(provider);
var container = new EntityContainer(Constants.ObjectTypes.MediaType) { Name = "blah" };
containerRepository.Save(container);
Assert.That(container.Id, Is.GreaterThan(0));
EntityContainer found = containerRepository.Get(container.Id);
Assert.IsNotNull(found);
}
}
[Test]
public void Can_Delete_Container()
{
IScopeProvider provider = ScopeProvider;
using (IScope scope = provider.CreateScope())
{
EntityContainerRepository containerRepository = CreateContainerRepository(provider);
var container = new EntityContainer(Constants.ObjectTypes.MediaType) { Name = "blah" };
containerRepository.Save(container);
Assert.That(container.Id, Is.GreaterThan(0));
// Act
containerRepository.Delete(container);
EntityContainer found = containerRepository.Get(container.Id);
Assert.IsNull(found);
}
}
[Test]
public void Can_Create_Container_Containing_Media_Types()
{
IScopeProvider provider = ScopeProvider;
using (IScope scope = provider.CreateScope())
{
EntityContainerRepository containerRepository = CreateContainerRepository(provider);
MediaTypeRepository repository = CreateRepository(provider);
var container = new EntityContainer(Constants.ObjectTypes.MediaType) { Name = "blah" };
containerRepository.Save(container);
MediaType contentType =
MediaTypeBuilder.CreateSimpleMediaType("test", "Test", propertyGroupAlias: "testGroup", propertyGroupName: "testGroup");
contentType.ParentId = container.Id;
repository.Save(contentType);
Assert.AreEqual(container.Id, contentType.ParentId);
}
}
[Test]
public void Can_Delete_Container_Containing_Media_Types()
{
IScopeProvider provider = ScopeProvider;
using (IScope scope = provider.CreateScope())
{
EntityContainerRepository containerRepository = CreateContainerRepository(provider);
MediaTypeRepository repository = CreateRepository(provider);
var container = new EntityContainer(Constants.ObjectTypes.MediaType) { Name = "blah" };
containerRepository.Save(container);
IMediaType contentType =
MediaTypeBuilder.CreateSimpleMediaType("test", "Test", propertyGroupAlias: "testGroup", propertyGroupName: "testGroup");
contentType.ParentId = container.Id;
repository.Save(contentType);
// Act
containerRepository.Delete(container);
EntityContainer found = containerRepository.Get(container.Id);
Assert.IsNull(found);
contentType = repository.Get(contentType.Id);
Assert.IsNotNull(contentType);
Assert.AreEqual(-1, contentType.ParentId);
}
}
[Test]
public void Can_Perform_Add_On_MediaTypeRepository()
{
// Arrange
IScopeProvider provider = ScopeProvider;
using (IScope scope = provider.CreateScope())
{
MediaTypeRepository repository = CreateRepository(provider);
// Act
MediaType contentType = MediaTypeBuilder.CreateNewMediaType();
repository.Save(contentType);
IMediaType fetched = repository.Get(contentType.Id);
// Assert
Assert.That(contentType.HasIdentity, Is.True);
Assert.That(contentType.PropertyGroups.All(x => x.HasIdentity), Is.True);
Assert.That(contentType.Path.Contains(","), Is.True);
Assert.That(contentType.SortOrder, Is.GreaterThan(0));
TestHelper.AssertPropertyValuesAreEqual(contentType, fetched, ignoreProperties: new[] { "UpdateDate" });
}
}
[Test]
public void Can_Perform_Update_On_MediaTypeRepository()
{
// Arrange
IScopeProvider provider = ScopeProvider;
using (IScope scope = provider.CreateScope())
{
MediaTypeRepository repository = CreateRepository(provider);
MediaType videoMediaType = MediaTypeBuilder.CreateNewMediaType();
repository.Save(videoMediaType);
// Act
IMediaType mediaType = repository.Get(videoMediaType.Id);
mediaType.Thumbnail = "Doc2.png";
mediaType.PropertyGroups["media"].PropertyTypes.Add(new PropertyType(ShortStringHelper, "test", ValueStorageType.Ntext, "subtitle")
{
Name = "Subtitle",
Description = "Optional Subtitle",
Mandatory = false,
SortOrder = 1,
DataTypeId = -88
});
repository.Save(mediaType);
bool dirty = ((MediaType)mediaType).IsDirty();
// Assert
Assert.That(mediaType.HasIdentity, Is.True);
Assert.That(dirty, Is.False);
Assert.That(mediaType.Thumbnail, Is.EqualTo("Doc2.png"));
Assert.That(mediaType.PropertyTypes.Any(x => x.Alias == "subtitle"), Is.True);
}
}
[Test]
public void Can_Perform_Delete_On_MediaTypeRepository()
{
// Arrange
IScopeProvider provider = ScopeProvider;
using (IScope scope = provider.CreateScope())
{
MediaTypeRepository repository = CreateRepository(provider);
// Act
MediaType mediaType = MediaTypeBuilder.CreateNewMediaType();
repository.Save(mediaType);
IMediaType contentType2 = repository.Get(mediaType.Id);
repository.Delete(contentType2);
bool exists = repository.Exists(mediaType.Id);
// Assert
Assert.That(exists, Is.False);
}
}
[Test]
public void Can_Perform_Get_On_MediaTypeRepository()
{
// Arrange
IScopeProvider provider = ScopeProvider;
using (IScope scope = provider.CreateScope())
{
MediaTypeRepository repository = CreateRepository(provider);
// Act
IMediaType mediaType = repository.Get(1033); // File
// Assert
Assert.That(mediaType, Is.Not.Null);
Assert.That(mediaType.Id, Is.EqualTo(1033));
Assert.That(mediaType.Name, Is.EqualTo(Constants.Conventions.MediaTypes.File));
}
}
[Test]
public void Can_Perform_Get_By_Guid_On_MediaTypeRepository()
{
// Arrange
IScopeProvider provider = ScopeProvider;
using (IScope scope = provider.CreateScope())
{
MediaTypeRepository repository = CreateRepository(provider);
IMediaType mediaType = repository.Get(1033); // File
// Act
mediaType = repository.Get(mediaType.Key);
// Assert
Assert.That(mediaType, Is.Not.Null);
Assert.That(mediaType.Id, Is.EqualTo(1033));
Assert.That(mediaType.Name, Is.EqualTo(Constants.Conventions.MediaTypes.File));
}
}
[Test]
public void Can_Perform_GetAll_On_MediaTypeRepository()
{
// Arrange
IScopeProvider provider = ScopeProvider;
using (IScope scope = provider.CreateScope())
{
MediaTypeRepository repository = CreateRepository(provider);
// Act
IEnumerable<IMediaType> mediaTypes = repository.GetMany();
int count =
scope.Database.ExecuteScalar<int>(
"SELECT COUNT(*) FROM umbracoNode WHERE nodeObjectType = @NodeObjectType",
new { NodeObjectType = Constants.ObjectTypes.MediaType });
// Assert
Assert.That(mediaTypes.Any(), Is.True);
Assert.That(mediaTypes.Count(), Is.EqualTo(count));
}
}
[Test]
public void Can_Perform_GetAll_By_Guid_On_MediaTypeRepository()
{
// Arrange
IScopeProvider provider = ScopeProvider;
using (IScope scope = provider.CreateScope())
{
MediaTypeRepository repository = CreateRepository(provider);
Guid[] allGuidIds = repository.GetMany().Select(x => x.Key).ToArray();
// Act
IEnumerable<IMediaType> mediaTypes = ((IReadRepository<Guid, IMediaType>)repository).GetMany(allGuidIds);
int count =
scope.Database.ExecuteScalar<int>(
"SELECT COUNT(*) FROM umbracoNode WHERE nodeObjectType = @NodeObjectType",
new { NodeObjectType = Constants.ObjectTypes.MediaType });
// Assert
Assert.That(mediaTypes.Any(), Is.True);
Assert.That(mediaTypes.Count(), Is.EqualTo(count));
}
}
[Test]
public void Can_Perform_Exists_On_MediaTypeRepository()
{
// Arrange
IScopeProvider provider = ScopeProvider;
using (IScope scope = provider.CreateScope())
{
MediaTypeRepository repository = CreateRepository(provider);
// Act
bool exists = repository.Exists(1032); // Image
// Assert
Assert.That(exists, Is.True);
}
}
[Test]
public void Can_Update_MediaType_With_PropertyType_Removed()
{
// Arrange
IScopeProvider provider = ScopeProvider;
using (IScope scope = provider.CreateScope())
{
MediaTypeRepository repository = CreateRepository(provider);
MediaType mediaType = MediaTypeBuilder.CreateNewMediaType();
repository.Save(mediaType);
// Act
IMediaType mediaTypeV2 = repository.Get(mediaType.Id);
mediaTypeV2.PropertyGroups["media"].PropertyTypes.Remove("title");
repository.Save(mediaTypeV2);
IMediaType mediaTypeV3 = repository.Get(mediaType.Id);
// Assert
Assert.That(mediaTypeV3.PropertyTypes.Any(x => x.Alias == "title"), Is.False);
Assert.That(mediaTypeV2.PropertyGroups.Count, Is.EqualTo(mediaTypeV3.PropertyGroups.Count));
Assert.That(mediaTypeV2.PropertyTypes.Count(), Is.EqualTo(mediaTypeV3.PropertyTypes.Count()));
}
}
[Test]
public void Can_Verify_PropertyTypes_On_Video_MediaType()
{
// Arrange
IScopeProvider provider = ScopeProvider;
using (IScope scope = provider.CreateScope())
{
MediaTypeRepository repository = CreateRepository(provider);
MediaType mediaType = MediaTypeBuilder.CreateNewMediaType();
repository.Save(mediaType);
// Act
IMediaType contentType = repository.Get(mediaType.Id);
// Assert
Assert.That(contentType.PropertyTypes.Count(), Is.EqualTo(2));
Assert.That(contentType.PropertyGroups.Count(), Is.EqualTo(1));
}
}
[Test]
public void Can_Verify_PropertyTypes_On_File_MediaType()
{
// Arrange
IScopeProvider provider = ScopeProvider;
using (IScope scope = provider.CreateScope())
{
MediaTypeRepository repository = CreateRepository(provider);
// Act
IMediaType contentType = repository.Get(1033); // File
// Assert
Assert.That(contentType.PropertyTypes.Count(), Is.EqualTo(3));
Assert.That(contentType.PropertyGroups.Count(), Is.EqualTo(1));
}
}
private MediaTypeRepository CreateRepository(IScopeProvider provider) =>
new MediaTypeRepository((IScopeAccessor)provider, AppCaches.Disabled, LoggerFactory.CreateLogger<MediaTypeRepository>(), CommonRepository, LanguageRepository, ShortStringHelper);
private EntityContainerRepository CreateContainerRepository(IScopeProvider provider) =>
new EntityContainerRepository((IScopeAccessor)provider, AppCaches.Disabled, LoggerFactory.CreateLogger<EntityContainerRepository>(), Constants.ObjectTypes.MediaTypeContainer);
}
}
| |
/*******************************************************************************
* Copyright (c) 2013, Daniel Murphy
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
/**
* Created at 4:11:55 AM Jan 15, 2011
*/
using System;
using SharpBox2D.Callbacks;
using SharpBox2D.Collision;
using SharpBox2D.Collision.Shapes;
using SharpBox2D.Common;
using SharpBox2D.Dynamics;
using SharpBox2D.Dynamics.Contacts;
using SharpBox2D.Dynamics.Joints;
using SharpBox2D.TestBed.Framework;
namespace SharpBox2D.TestBed.Tests
{
/**
* @author Daniel Murphy
*/
public class Cantilever : TestbedTest
{
private int e_count = 8;
public override bool isSaveLoadEnabled()
{
return true;
}
public override void initTest(bool argDeserialized)
{
if (argDeserialized)
{
return;
}
Body ground = null;
{
BodyDef bd = new BodyDef();
ground = getWorld().createBody(bd);
EdgeShape shape = new EdgeShape();
shape.set(new Vec2(-40.0f, 0.0f), new Vec2(40.0f, 0.0f));
ground.createFixture(shape, 0.0f);
}
{
PolygonShape shape = new PolygonShape();
shape.setAsBox(0.5f, 0.125f);
FixtureDef fd = new FixtureDef();
fd.shape = shape;
fd.density = 20.0f;
WeldJointDef jd = new WeldJointDef();
Body prevBody = ground;
for (int i = 0; i < e_count; ++i)
{
BodyDef bd = new BodyDef();
bd.type = BodyType.DYNAMIC;
bd.position.set(-14.5f + 1.0f*i, 5.0f);
Body body = getWorld().createBody(bd);
body.createFixture(fd);
Vec2 anchor = new Vec2(-15.0f + 1.0f*i, 5.0f);
jd.initialize(prevBody, body, anchor);
getWorld().createJoint(jd);
prevBody = body;
}
}
{
PolygonShape shape = new PolygonShape();
shape.setAsBox(1f, 0.125f);
FixtureDef fd = new FixtureDef();
fd.shape = shape;
fd.density = 20.0f;
WeldJointDef jd = new WeldJointDef();
jd.frequencyHz = 5f;
jd.dampingRatio = .7f;
Body prevBody = ground;
for (int i = 0; i < 3; ++i)
{
BodyDef bd = new BodyDef();
bd.type = BodyType.DYNAMIC;
bd.position.set(-14.0f + 2.0f*i, 15.0f);
Body body = getWorld().createBody(bd);
body.createFixture(fd);
Vec2 anchor = new Vec2(-15.0f + 2.0f*i, 15.0f);
jd.initialize(prevBody, body, anchor);
getWorld().createJoint(jd);
prevBody = body;
}
}
{
PolygonShape shape = new PolygonShape();
shape.setAsBox(0.5f, 0.125f);
FixtureDef fd = new FixtureDef();
fd.shape = shape;
fd.density = 20.0f;
WeldJointDef jd = new WeldJointDef();
Body prevBody = ground;
for (int i = 0; i < e_count; ++i)
{
BodyDef bd = new BodyDef();
bd.type = BodyType.DYNAMIC;
bd.position.set(-4.5f + 1.0f*i, 5.0f);
Body body = getWorld().createBody(bd);
body.createFixture(fd);
if (i > 0)
{
Vec2 anchor = new Vec2(-5.0f + 1.0f*i, 5.0f);
jd.initialize(prevBody, body, anchor);
getWorld().createJoint(jd);
}
prevBody = body;
}
}
{
PolygonShape shape = new PolygonShape();
shape.setAsBox(0.5f, 0.125f);
FixtureDef fd = new FixtureDef();
fd.shape = shape;
fd.density = 20.0f;
WeldJointDef jd = new WeldJointDef();
jd.frequencyHz = 8f;
jd.dampingRatio = .7f;
Body prevBody = ground;
for (int i = 0; i < e_count; ++i)
{
BodyDef bd = new BodyDef();
bd.type = BodyType.DYNAMIC;
bd.position.set(5.5f + 1.0f*i, 10.0f);
Body body = getWorld().createBody(bd);
body.createFixture(fd);
if (i > 0)
{
Vec2 anchor = new Vec2(5.0f + 1.0f*i, 10.0f);
jd.initialize(prevBody, body, anchor);
getWorld().createJoint(jd);
}
prevBody = body;
}
}
for (int i = 0; i < 2; ++i)
{
Vec2[] vertices = new Vec2[3];
vertices[0] = new Vec2(-0.5f, 0.0f);
vertices[1] = new Vec2(0.5f, 0.0f);
vertices[2] = new Vec2(0.0f, 1.5f);
PolygonShape shape = new PolygonShape();
shape.set(vertices, 3);
FixtureDef fd = new FixtureDef();
fd.shape = shape;
fd.density = 1.0f;
BodyDef bd = new BodyDef();
bd.type = BodyType.DYNAMIC;
bd.position.set(-8.0f + 8.0f*i, 12.0f);
Body body = getWorld().createBody(bd);
body.createFixture(fd);
}
for (int i = 0; i < 2; ++i)
{
CircleShape shape = new CircleShape();
shape.m_radius = 0.5f;
FixtureDef fd = new FixtureDef();
fd.shape = shape;
fd.density = 1.0f;
BodyDef bd = new BodyDef();
bd.type = BodyType.DYNAMIC;
bd.position.set(-6.0f + 6.0f*i, 10.0f);
Body body = getWorld().createBody(bd);
body.createFixture(fd);
}
}
public override string getTestName()
{
return "Cantilever";
}
}
}
| |
using System;
using System.Collections;
using NUnit.Framework;
namespace FileHelpers.Tests.CommonTests
{
[TestFixture]
public class InheritedTests
{
[Test]
public void Inherited1()
{
var engine = new FileHelperEngine<SampleInheritType>();
Assert.AreEqual(3, engine.Options.FieldCount);
Assert.AreEqual("Field1", engine.Options.FieldsNames[0]);
Assert.AreEqual("Field2", engine.Options.FieldsNames[1]);
Assert.AreEqual("Field3", engine.Options.FieldsNames[2]);
SampleInheritType[] res;
res = TestCommon.ReadTest<SampleInheritType>(engine, "Good", "Test1.txt");
Assert.AreEqual(4, res.Length);
Assert.AreEqual(4, engine.TotalRecords);
Assert.AreEqual(0, engine.ErrorManager.ErrorCount);
Assert.AreEqual(new DateTime(1314, 12, 11), res[0].Field1);
Assert.AreEqual("901", res[0].Field2);
Assert.AreEqual(234, res[0].Field3);
Assert.AreEqual(new DateTime(1314, 11, 10), res[1].Field1);
Assert.AreEqual("012", res[1].Field2);
Assert.AreEqual(345, res[1].Field3);
}
[Test]
public void InheritedEmpty()
{
var engine = new FileHelperEngine<SampleInheritEmpty>();
SampleInheritEmpty[] res;
res = TestCommon.ReadTest<SampleInheritEmpty>(engine, "Good", "Test1.txt");
Assert.AreEqual(4, res.Length);
Assert.AreEqual(4, engine.TotalRecords);
Assert.AreEqual(0, engine.ErrorManager.ErrorCount);
Assert.AreEqual(new DateTime(1314, 12, 11), res[0].Field1);
Assert.AreEqual("901", res[0].Field2);
Assert.AreEqual(234, res[0].Field3);
Assert.AreEqual(new DateTime(1314, 11, 10), res[1].Field1);
Assert.AreEqual("012", res[1].Field2);
Assert.AreEqual(345, res[1].Field3);
}
[Test]
public void Inherited2()
{
var engine = new FileHelperEngine<DelimitedSampleInheritType>();
}
[Test]
public void InheritedEmptyDelimited()
{
var engine = new FileHelperEngine<DelimitedSampleInheritEmpty>();
}
[FixedLengthRecord]
public class SampleBase
{
[FieldFixedLength(8)]
[FieldConverter(ConverterKind.Date, "ddMMyyyy")]
public DateTime Field1;
[FieldFixedLength(3)]
[FieldAlign(AlignMode.Left, ' ')]
[FieldTrim(TrimMode.Both)]
public string Field2;
}
[FixedLengthRecord]
public class SampleInheritType
: SampleBase
{
[FieldFixedLength(3)]
[FieldAlign(AlignMode.Right, '0')]
[FieldTrim(TrimMode.Both)]
public int Field3;
}
[FixedLengthRecord]
public class SampleInheritEmpty
: SampleInheritType
{
[FieldHidden]
public int Field5854;
}
[FixedLengthRecord]
public class DelimitedSampleBase
{
[FieldFixedLength(8)]
[FieldConverter(ConverterKind.Date, "ddMMyyyy")]
public DateTime Field1;
[FieldFixedLength(3)]
[FieldAlign(AlignMode.Left, ' ')]
[FieldTrim(TrimMode.Both)]
public string Field2;
}
[FixedLengthRecord]
public class DelimitedSampleInheritType
: DelimitedSampleBase
{
[FieldFixedLength(3)]
[FieldAlign(AlignMode.Right, '0')]
[FieldTrim(TrimMode.Both)]
public int Field3;
}
[FixedLengthRecord]
public class DelimitedSampleInheritEmpty
: DelimitedSampleInheritType
{
[FieldHidden]
public int Field5854;
}
[FixedLengthRecord(FixedMode.AllowMoreChars)]
public class Type1RecordBase
{
public class MoneyConverter : ConverterBase
{
private const int DECIMAL_PLACES = 2;
public override string FieldToString(object from)
{
Decimal v = Convert.ToDecimal(from);
v *= (10 ^ DECIMAL_PLACES);
return Convert.ToInt64(v).ToString();
}
public override object StringToField(string from)
{
return Convert.ToDecimal(Decimal.Parse(from)/(10 ^ DECIMAL_PLACES));
}
}
#region Fields
[FieldFixedLength(AmexFieldLengths.RecordType)]
public string RecordType;
[FieldFixedLength(AmexFieldLengths.RequestingControlAccount)]
public string RequestingControlAccount;
[FieldFixedLength(AmexFieldLengths.BasicControlAccount)]
public string BasicControlAccount;
[FieldFixedLength(AmexFieldLengths.CardholderAccountNumber)]
public string CardholderAccountNumber;
[FieldFixedLength(AmexFieldLengths.SENumber)]
public string SENumber;
[FieldFixedLength(AmexFieldLengths.ROCID)]
public string ROCID;
[FieldFixedLength(AmexFieldLengths.DBCRIndicator)]
public string DBCRIndicator;
[FieldFixedLength(AmexFieldLengths.TransactionTypeCode)]
public string TransactionTypeCode;
[FieldFixedLength(AmexFieldLengths.FinancialCategory)]
public string FinancialCategory;
[FieldFixedLength(AmexFieldLengths.BatchNumber)]
public string BatchNumber;
[FieldFixedLength(AmexFieldLengths.DateOfCharge)]
[FieldConverter(ConverterKind.Date, "MMddyy")]
public DateTime DateOfCharge;
[FieldFixedLength(AmexFieldLengths.LocalCurrencyAmount)]
[FieldAlign(AlignMode.Right, '0')]
[FieldConverter(typeof (MoneyConverter))]
public decimal LocalCurrencyAmount;
[FieldFixedLength(AmexFieldLengths.CurrencyCode)]
public string CurrencyCode;
[FieldFixedLength(AmexFieldLengths.CaptureDate)]
public string CaptureDate;
[FieldFixedLength(AmexFieldLengths.ProcessDate)]
[FieldConverter(ConverterKind.Date, "MMddyy")]
public DateTime ProcessDate;
[FieldFixedLength(AmexFieldLengths.BillingDate)]
[FieldConverter(ConverterKind.Date, "MMddyy")]
public DateTime BillingDate;
[FieldFixedLength(AmexFieldLengths.BillingAmount)]
[FieldAlign(AlignMode.Right, '0')]
[FieldConverter(typeof (MoneyConverter))]
public decimal BillingAmount;
[FieldFixedLength(AmexFieldLengths.SalesTaxAmount)]
[FieldAlign(AlignMode.Right, '0')]
[FieldConverter(typeof (MoneyConverter))]
public decimal SalesTaxAmount;
[FieldFixedLength(AmexFieldLengths.TipAmount)]
[FieldAlign(AlignMode.Right, '0')]
[FieldConverter(typeof (MoneyConverter))]
public decimal TipAmount;
[FieldFixedLength(AmexFieldLengths.CardmemberName)]
[FieldTrim(TrimMode.Right)]
public string CardmemberName;
[FieldFixedLength(AmexFieldLengths.SpecialBillInd)]
public string SpecialBillInd;
[FieldFixedLength(AmexFieldLengths.OriginatingBCA)]
public string OriginatingBCA;
[FieldFixedLength(AmexFieldLengths.OriginatingAccountNumber)]
public string OriginatingAccountNumber;
[FieldFixedLength(AmexFieldLengths.CMReferenceNumber)]
public string CMReferenceNumber;
[FieldFixedLength(AmexFieldLengths.SupplierReferenceNumber)]
public string SupplierReferenceNumber;
[FieldFixedLength(AmexFieldLengths.ShipToZip)]
public string ShipToZip;
[FieldFixedLength(AmexFieldLengths.SICCode)]
public string SICCode;
[FieldFixedLength(AmexFieldLengths.CostCenter)]
[FieldConverter(ConverterKind.Int32)]
[FieldAlign(AlignMode.Right, ' ')]
public int CostCenter;
[FieldFixedLength(AmexFieldLengths.EmployeeID)]
[FieldConverter(ConverterKind.Int32)]
[FieldAlign(AlignMode.Right, ' ')]
public int EmployeeID;
[FieldFixedLength(AmexFieldLengths.SocialSecurityNumber)]
public string SocialSecurityNumber;
[FieldFixedLength(AmexFieldLengths.UniversalNumber)]
public string UniversalNumber;
[FieldFixedLength(AmexFieldLengths.Street)]
[FieldTrim(TrimMode.Right)]
public string Street;
[FieldFixedLength(AmexFieldLengths.City)]
[FieldTrim(TrimMode.Right)]
public string City;
[FieldFixedLength(AmexFieldLengths.State)]
[FieldTrim(TrimMode.Right)]
public string State;
[FieldFixedLength(AmexFieldLengths.Zip)]
public string Zip;
[FieldFixedLength(AmexFieldLengths.TransLimit)]
public string TransLimit;
[FieldFixedLength(AmexFieldLengths.MonthlyLimit)]
public string MonthlyLimit;
[FieldFixedLength(AmexFieldLengths.ExposureLimit)]
public string ExposureLimit;
[FieldFixedLength(AmexFieldLengths.RevCode)]
public string RevCode;
[FieldFixedLength(AmexFieldLengths.CompanyName)]
[FieldTrim(TrimMode.Right)]
public string CompanyName;
[FieldFixedLength(AmexFieldLengths.ChargeDescriptionLine1)]
[FieldTrim(TrimMode.Right)]
public string ChargeDescriptionLine1;
#endregion
}
/// <summary>
/// Summary description for Type1Default.
/// </summary>
[FixedLengthRecord(FixedMode.AllowMoreChars)]
public class Type1RecordDefault : Type1RecordBase
{
#region Type 1 Fields
[FieldFixedLength(AmexFieldLengths.ChargeDescriptionLine2)]
[FieldTrim(TrimMode.Right)]
public string ChargeDescriptionLine2;
[FieldFixedLength(AmexFieldLengths.ChargeDescriptionLine3)]
[FieldTrim(TrimMode.Right)]
public string ChargeDescriptionLine3;
[FieldFixedLength(AmexFieldLengths.ChargeDescriptionLine4)]
[FieldTrim(TrimMode.Right)]
public string ChargeDescriptionLine4;
[FieldFixedLength(AmexFieldLengths.IndustryCode)]
public string IndustryCode;
[FieldFixedLength(AmexFieldLengths.SequenceNumber)]
public string SequenceNumber;
[FieldFixedLength(AmexFieldLengths.MercatorKey)]
public string MercatorKey;
[FieldFixedLength(AmexFieldLengths.TransactionFeeIndicator)]
[FieldOptional]
public string TransactionFeeIndicator;
[FieldFixedLength(AmexFieldLengths.TailFiller)]
[FieldOptional]
public string TailFiller;
#endregion
}
internal sealed class AmexFieldLengths
{
private AmexFieldLengths() {}
// Type 1 and Shared
internal const int RecordType = 1;
internal const int RequestingControlAccount = 15;
internal const int BasicControlAccount = 15;
internal const int CardholderAccountNumber = 15;
internal const int SENumber = 10;
internal const int ROCID = 13;
internal const int DBCRIndicator = 1;
internal const int TransactionTypeCode = 2;
internal const int FinancialCategory = 1;
internal const int BatchNumber = 3;
internal const int DateOfCharge = 6;
internal const int LocalCurrencyAmount = 9;
internal const int CurrencyCode = 3;
internal const int CaptureDate = 5;
internal const int ProcessDate = 6;
internal const int BillingDate = 6;
internal const int BillingAmount = 9;
internal const int SalesTaxAmount = 9;
internal const int TipAmount = 9;
internal const int CardmemberName = 20;
internal const int SpecialBillInd = 1;
internal const int OriginatingBCA = 15;
internal const int OriginatingAccountNumber = 15;
internal const int CMReferenceNumber = 17;
internal const int SupplierReferenceNumber = 11;
internal const int ShipToZip = 6;
internal const int SICCode = 4;
internal const int CostCenter = 10;
internal const int EmployeeID = 10;
internal const int SocialSecurityNumber = 10;
internal const int UniversalNumber = 25;
internal const int Street = 20;
internal const int City = 18;
internal const int State = 2;
internal const int Zip = 10;
internal const int TransLimit = 5;
internal const int MonthlyLimit = 7;
internal const int ExposureLimit = 7;
internal const int RevCode = 1;
internal const int CompanyName = 20;
internal const int ChargeDescriptionLine1 = 42;
internal const int ChargeDescriptionLine2 = 42;
internal const int ChargeDescriptionLine3 = 42;
internal const int ChargeDescriptionLine4 = 42;
internal const int IndustryCode = 2;
internal const int SequenceNumber = 7;
internal const int MercatorKey = 21;
internal const int TransactionFeeIndicator = 3;
internal const int CarRentalCustomerName = 20;
internal const int CarRentalCity = 18;
internal const int CarRentalState = 2;
internal const int CarRentalDate = 6;
internal const int CarReturnCity = 18;
internal const int CarReturnState = 2;
internal const int CarReturnDate = 6;
internal const int CarRentalDays = 2;
internal const int HotelArrivalDate = 6;
internal const int HotelCity = 18;
internal const int HotelState = 2;
internal const int HotelDepartDate = 6;
internal const int HotelStayDuration = 2;
internal const int HotelRoomRate = 7;
internal const int AirAgencyNumber = 8;
internal const int AirTicketIssuer = 25;
internal const int AirClassOfService = 8;
internal const int AirCarrierCode = 16;
internal const int AirRouting = 27;
internal const int AirDepartureDate = 6;
internal const int AirPassengerName = 20;
internal const int TeleDateOfCall = 6;
internal const int TeleFromCity = 18;
internal const int TeleFromState = 2;
internal const int TeleCallLength = 4;
internal const int TeleReferenceNumber = 8;
internal const int TeleTimeOfCall = 4;
internal const int TeleToNumber = 10;
internal const int TailFiller = 2;
internal const int CarRentalFiller = 52;
internal const int HotelFiller = 85;
internal const int AirFiller = 16;
internal const int TeleFiller = 74;
// Type 2
internal const int CMName = 20;
internal const int CMPreviousBalance = 11;
internal const int CMPreviousBalanceSign = 1;
internal const int CMNewCharges = 11;
internal const int CMNewChargesSign = 1;
internal const int CMOtherDebits = 11;
internal const int CMOtherDebitsSign = 1;
internal const int CMPayments = 11;
internal const int CMPaymentsSign = 1;
internal const int CMOtherCredits = 11;
internal const int CMOtherCreditsSign = 1;
internal const int CMBalance = 11;
internal const int CMBalanceSign = 1;
internal const int CID = 6;
internal const int GroupID = 20;
internal const int Type2Filler = 405;
// Type 3
internal const int BCAName = 20;
internal const int BCADebits = 11;
internal const int BCADebitsSign = 1;
internal const int BCACredits = 11;
internal const int BCACreditsSign = 1;
internal const int BCATransLimit = 5;
internal const int BCAMonthlyLimit = 7;
internal const int BCAExposureLimit = 7;
internal const int BCABudgetaryLimit = 9;
internal const int BCAPreviousBalance = 11;
internal const int BCAPreviousBalanceSign = 1;
internal const int Type3Filler = 448;
// Type 4
internal const int RequestingControlAccountName = 20;
internal const int ControlDebits = 11;
internal const int ControlDebitsSign = 1;
internal const int ControlCredits = 11;
internal const int ControlCreditsSign = 1;
internal const int TransactionLimit = 5;
internal const int BudgetaryLimit = 9;
internal const int ControlPreviousBalance = 11;
internal const int ControlPreviousBalanceSign = 1;
internal const int Type4Filler = 463;
// Type 5
internal const int SEName1 = 25;
internal const int SEName2 = 25;
internal const int SEStreet1 = 25;
internal const int SEStreet2 = 25;
internal const int SECity = 25;
internal const int SEState = 2;
internal const int SEZip = 10;
internal const int SECountry = 25;
internal const int SEPhone = 13;
internal const int SEInductryCode = 2;
internal const int SESubIndustryCode = 3;
internal const int FederalTaxID = 9;
internal const int DandBNumber = 9;
internal const int OwnerTypeCode = 2;
internal const int PurchasingCardCode = 2;
internal const int CorporationStatusIndicator = 1;
internal const int Type5Filler = 357;
}
[FixedLengthRecord]
[IgnoreInheritedClass]
public class SampleInheritIgnoreType
: CollectionBase
{
[FieldFixedLength(8)]
[FieldConverter(ConverterKind.Date, "ddMMyyyy")]
public DateTime Field1;
[FieldFixedLength(3)]
[FieldAlign(AlignMode.Left, ' ')]
[FieldTrim(TrimMode.Both)]
public string Field2;
[FieldFixedLength(3)]
[FieldAlign(AlignMode.Right, '0')]
[FieldTrim(TrimMode.Both)]
public int Field3;
}
[FixedLengthRecord]
public class SampleInheritIgnoreType2
: SampleInheritIgnoreType
{
[FieldOptional]
[FieldNullValue(2)]
[FieldFixedLength(3)]
public int Field4;
}
[Test]
public void IgnoreInherited1()
{
var engine = new FileHelperEngine<SampleInheritIgnoreType>();
Assert.AreEqual(3, engine.Options.FieldCount);
SampleInheritIgnoreType[] res;
res = TestCommon.ReadTest<SampleInheritIgnoreType>(engine, "Good", "Test1.txt");
Assert.AreEqual(4, res.Length);
Assert.AreEqual(4, engine.TotalRecords);
Assert.AreEqual(0, engine.ErrorManager.ErrorCount);
Assert.AreEqual(new DateTime(1314, 12, 11), res[0].Field1);
Assert.AreEqual("901", res[0].Field2);
Assert.AreEqual(234, res[0].Field3);
Assert.AreEqual(new DateTime(1314, 11, 10), res[1].Field1);
Assert.AreEqual("012", res[1].Field2);
Assert.AreEqual(345, res[1].Field3);
}
[Test]
public void IgnoreInherited2()
{
var engine = new FileHelperEngine<SampleInheritIgnoreType2>();
Assert.AreEqual(4, engine.Options.FieldCount);
Assert.AreEqual("Field4", engine.Options.FieldsNames[3]);
SampleInheritIgnoreType2[] res;
res = TestCommon.ReadTest<SampleInheritIgnoreType2>(engine, "Good", "Test1.txt");
Assert.AreEqual(4, res.Length);
Assert.AreEqual(4, engine.TotalRecords);
Assert.AreEqual(0, engine.ErrorManager.ErrorCount);
Assert.AreEqual(new DateTime(1314, 12, 11), res[0].Field1);
Assert.AreEqual("901", res[0].Field2);
Assert.AreEqual(234, res[0].Field3);
Assert.AreEqual(new DateTime(1314, 11, 10), res[1].Field1);
Assert.AreEqual("012", res[1].Field2);
Assert.AreEqual(345, res[1].Field3);
}
}
}
| |
using System;
using System.Reflection;
using CommandLine.Text;
using System.IO;
using CommandLine;
using System.Collections.Generic;
using Newtonsoft.Json;
using System.Linq;
using System.Diagnostics;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
using System.Text.RegularExpressions;
namespace ChainCompressor
{
static class Program
{
private sealed class Options
{
[Option('i', "image", Required = true, HelpText = "The input docker image (usually it is a tar file exported by `docker save`).")]
public string InputImagePath { get; set; }
[Option('o', "output", Required = true, HelpText = "The output image archive file name (for use in `docker load`).")]
public string OutputImagePath { get; set; }
[Option('n', "name", Required = true, HelpText = "The combined image's 'name:version' pair.")]
public string OutputImageNameVersion { get; set; }
[HelpOption]
public string GetUsage()
{
var serverAssembly = typeof(Program).Assembly;
var assemblyName = serverAssembly.GetName();
var title = serverAssembly.GetCustomAttribute<AssemblyTitleAttribute>();
var company = serverAssembly.GetCustomAttribute<AssemblyCompanyAttribute>();
var help = new HelpText {
Heading = new HeadingInfo(title.Title, assemblyName.Version.ToString()),
Copyright = new CopyrightInfo(company.Company, 2015),
AdditionalNewLineAfterOption = true,
AddDashesToOption = true
};
var assemblyExecutableName = Path.GetFileNameWithoutExtension(serverAssembly.Location);
help.AddPreOptionsLine(string.Format("Usage: {0} -i image.tar -o image-unpacked", assemblyExecutableName));
help.AddOptions(this);
return help;
}
}
public static void Main(string[] args)
{
var options = new Options();
if (CommandLine.Parser.Default.ParseArguments(args, options))
{
try
{
Run(options);
}
catch (Exception ex)
{
Console.Error.WriteLine("Unexpected error happened: ");
Console.Error.WriteLine(ex);
}
}
else
{
Console.WriteLine(options.GetUsage());
}
}
private static void Run(Options options)
{
Match imageNameMatch = Regex.Match(options.OutputImageNameVersion, "^(?<name>.+):(?<version>[^:]+)$");
if (!imageNameMatch.Success)
{
Console.Error.WriteLine(string.Format("Invalid name:version pair '{0}'", options.OutputImageNameVersion));
}
string unpackDirectory = Path.Combine(
Path.GetDirectoryName(options.OutputImagePath),
Path.GetFileNameWithoutExtension(options.OutputImagePath) + "_temp");
string inputImageDirectory = Path.Combine(unpackDirectory, "inputImage");
string combinedLayerDataDirectory = Path.Combine(unpackDirectory, "combinedLayersData");
string combinedLayerDataPath = Path.Combine(unpackDirectory, "combinedLayer.tar");
string outputImageDirectory = Path.Combine(unpackDirectory, "outputImage");
InitializeEmptyDirectory(unpackDirectory);
Console.Write("Unpacking image {0} into {1} ... ", options.InputImagePath, inputImageDirectory);
InitializeEmptyDirectory(inputImageDirectory);
UnpackTarOverwrite(options.InputImagePath, inputImageDirectory);
Console.WriteLine("Done");
List<string> layerChain = FindLayersOrder(inputImageDirectory);
CombineLayers(inputImageDirectory, combinedLayerDataDirectory, layerChain);
Console.WriteLine("Packing combined layers into single layer...");
PackTarTo(combinedLayerDataDirectory, combinedLayerDataPath);
Console.Write("Computing filesystem data size... ");
long layerSize = Directory
.EnumerateFiles(combinedLayerDataDirectory, "*", SearchOption.AllDirectories)
.Select(file => new FileInfo(file).Length)
.Sum();
Console.WriteLine("{0} bytes", layerSize);
Console.WriteLine("Creating layer metadata...");
var metadata = JObject.Parse(File.ReadAllText(Path.Combine(
inputImageDirectory, layerChain.Last(), "json")));
metadata.Property("parent").Remove();
metadata.Property("container").Remove();
metadata.Property("Size").Value = layerSize;
metadata.Property("created").Value = DateTime.UtcNow.ToString("O");
Console.Write("Generating random image ID... ");
byte[] bytes = new byte[32];
new Random().NextBytes(bytes); // random 256-bit ID
string finalLayerID = string.Concat(bytes.Select(b => b.ToString("X2"))).ToLowerInvariant();
metadata.Property("id").Value = finalLayerID;
Console.WriteLine(finalLayerID);
Console.WriteLine("Gathering layer filesystem data and metadata to finalize image...");
InitializeEmptyDirectory(outputImageDirectory);
string finalLayerDirectory = Path.Combine(outputImageDirectory, finalLayerID);
Directory.CreateDirectory(finalLayerDirectory);
File.Move(combinedLayerDataPath, Path.Combine(finalLayerDirectory, "layer.tar"));
File.WriteAllText(Path.Combine(finalLayerDirectory, "json"), metadata.ToString());
File.WriteAllText(Path.Combine(finalLayerDirectory, "VERSION"), "1.0");
var imageMetadata = new JObject(
new JProperty(imageNameMatch.Groups["name"].Value, new JObject(
new JProperty(imageNameMatch.Groups["version"].Value, finalLayerID))));
File.WriteAllText(Path.Combine(outputImageDirectory, "repositories"), imageMetadata.ToString());
Console.Write("Packing final image... ");
PackTarTo(outputImageDirectory, options.OutputImagePath);
Console.WriteLine("Success");
Console.Write("Cleaning up... ");
Directory.Delete(unpackDirectory, true);
Console.WriteLine("Done");
}
private static List<string> FindLayersOrder(string inputImageDirectory)
{
var repositories = JsonConvert.DeserializeObject<Dictionary<string, Dictionary<string, string>>>(
File.ReadAllText(Path.Combine(inputImageDirectory, "repositories")));
string layerID = repositories.Single().Value.Single().Value;
var parentChain = new List<string>();
do
{
parentChain.Add(layerID);
layerID = JsonConvert.DeserializeAnonymousType(
File.ReadAllText(Path.Combine(inputImageDirectory, layerID, "json")),
new { parent = "" }).parent;
}
while (layerID != null);
parentChain.Reverse();
Console.WriteLine("Computed layer chain order:");
foreach (string layer in parentChain)
{
Console.WriteLine(" {0}", layer);
}
return parentChain;
}
private static void CombineLayers(
string inputImageDirectory, string combinedLayerDataDirectory, List<string> layerChain)
{
InitializeEmptyDirectory(combinedLayerDataDirectory);
Console.WriteLine("Unpacking layers on top of each other...");
foreach (string layerID in layerChain)
{
Console.Write("Writing layer {0}... ", layerID);
var layerTarPath = Path.Combine(inputImageDirectory, layerID, "layer.tar");
UnpackTarOverwrite(layerTarPath, combinedLayerDataDirectory);
foreach (string file in Directory.EnumerateFiles(
combinedLayerDataDirectory, ".wh.*", SearchOption.AllDirectories))
{
File.Delete(file);
string unprefixed = file.Replace(".wh.", "");
if (File.Exists(unprefixed))
File.Delete(unprefixed);
else if (Directory.Exists(unprefixed))
Directory.Delete(unprefixed, true);
}
Console.WriteLine("Done");
}
}
private static void InitializeEmptyDirectory(string directoryPath)
{
try { Directory.Delete(directoryPath, true); }
catch (DirectoryNotFoundException) { }
Directory.CreateDirectory(directoryPath);
}
private static string AddSuffixToDirectory(string directoryPath, string suffix)
{
return Path.Combine(
Directory.GetParent(directoryPath).FullName,
new DirectoryInfo(directoryPath).Name + suffix);
}
private static void UnpackTarOverwrite(string tarFileName, string outputDirectory)
{
ShellExecute("/bin/tar", string.Format("-xf \"{0}\" -C \"{1}\"",
tarFileName, outputDirectory)).Wait();
}
private static void PackTarTo(string directoryToPack, string outputTarPath)
{
string paths = string.Join(" ",
from entry in Directory.EnumerateFileSystemEntries(directoryToPack)
let relative = File.Exists(entry)
? Path.GetFileName(entry) : new DirectoryInfo(entry).Name
select "\"" + relative + "\"");
ShellExecute("/bin/tar", string.Format("-cf \"{0}\" {1}", outputTarPath, paths),
workingDirectory: directoryToPack).Wait();
}
private static async Task<string> ShellExecute(
string program, string args,
TimeSpan? timeout = null,
string workingDirectory = null)
{
ProcessStartInfo processStartInfo = new ProcessStartInfo(program, args)
{
RedirectStandardOutput = true,
RedirectStandardError = true,
WindowStyle = ProcessWindowStyle.Normal,
UseShellExecute = false,
};
if (workingDirectory != null)
processStartInfo.WorkingDirectory = workingDirectory;
Process process = Process.Start(processStartInfo);
Task<string> output = process.StandardOutput.ReadToEndAsync();
Task<string> error = process.StandardError.ReadToEndAsync();
Task readTask = Task.WhenAll(
output.ContinueWith(t => process.StandardOutput.Close()),
error.ContinueWith(t => process.StandardError.Close()));
if (timeout.HasValue)
await Task.WhenAny(readTask, Task.Delay(timeout.Value));
else
await readTask;
if (readTask.IsCompleted)
{
return string.Format("{0}{1}{2}", await output, Environment.NewLine, await error);
}
else
{
try { process.Kill(); }
catch (Exception) { }
throw new OperationCanceledException("Shell command execution timed out");
}
}
}
}
| |
/*
* 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.Threading;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
namespace OpenSim.Framework
{
public interface IHandle { }
[Serializable, ComVisible(false)]
public class MinHeap<T> : ICollection<T>, ICollection
{
private class Handle : IHandle
{
internal int index = -1;
internal MinHeap<T> heap = null;
internal void Clear()
{
this.index = -1;
this.heap = null;
}
}
private struct HeapItem
{
internal T value;
internal Handle handle;
internal HeapItem(T value, Handle handle)
{
this.value = value;
this.handle = handle;
}
internal void Clear()
{
if (this.handle != null)
this.handle.Clear();
ClearRef();
}
internal void ClearRef()
{
this.value = default(T);
this.handle = null;
}
}
public const int DEFAULT_CAPACITY = 4;
private HeapItem[] items;
private int size;
private object sync_root;
private int version;
private Comparison<T> comparison;
public MinHeap() : this(DEFAULT_CAPACITY, Comparer<T>.Default) { }
public MinHeap(int capacity) : this(capacity, Comparer<T>.Default) { }
public MinHeap(IComparer<T> comparer) : this(DEFAULT_CAPACITY, comparer) { }
public MinHeap(int capacity, IComparer<T> comparer) :
this(capacity, new Comparison<T>(comparer.Compare)) { }
public MinHeap(Comparison<T> comparison) : this(DEFAULT_CAPACITY, comparison) { }
public MinHeap(int capacity, Comparison<T> comparison)
{
this.items = new HeapItem[capacity];
this.comparison = comparison;
this.size = this.version = 0;
}
public int Count { get { return this.size; } }
public bool IsReadOnly { get { return false; } }
public bool IsSynchronized { get { return false; } }
public T this[IHandle key]
{
get
{
Handle handle = ValidateThisHandle(key);
return this.items[handle.index].value;
}
set
{
Handle handle = ValidateThisHandle(key);
this.items[handle.index].value = value;
if (!BubbleUp(handle.index))
BubbleDown(handle.index);
}
}
public object SyncRoot
{
get
{
if (this.sync_root == null)
Interlocked.CompareExchange<object>(ref this.sync_root, new object(), null);
return this.sync_root;
}
}
private Handle ValidateHandle(IHandle ihandle)
{
if (ihandle == null)
throw new ArgumentNullException("handle");
Handle handle = ihandle as Handle;
if (handle == null)
throw new InvalidOperationException("handle is not valid");
return handle;
}
private Handle ValidateThisHandle(IHandle ihandle)
{
Handle handle = ValidateHandle(ihandle);
if (!object.ReferenceEquals(handle.heap, this))
throw new InvalidOperationException("handle is not valid for this heap");
if (handle.index < 0)
throw new InvalidOperationException("handle is not associated to a value");
return handle;
}
private void Set(HeapItem item, int index)
{
this.items[index] = item;
if (item.handle != null)
item.handle.index = index;
}
private bool BubbleUp(int index)
{
HeapItem item = this.items[index];
int current, parent;
for (current = index, parent = (current - 1) / 2;
(current > 0) && (this.comparison(this.items[parent].value, item.value)) > 0;
current = parent, parent = (current - 1) / 2)
{
Set(this.items[parent], current);
}
if (current != index)
{
Set(item, current);
++this.version;
return true;
}
return false;
}
private void BubbleDown(int index)
{
HeapItem item = this.items[index];
int current, child;
for (current = index, child = (2 * current) + 1;
current < this.size / 2;
current = child, child = (2 * current) + 1)
{
if ((child < this.size - 1) && this.comparison(this.items[child].value, this.items[child + 1].value) > 0)
++child;
if (this.comparison(this.items[child].value, item.value) >= 0)
break;
Set(this.items[child], current);
}
if (current != index)
{
Set(item, current);
++this.version;
}
}
public bool TryGetValue(IHandle key, out T value)
{
Handle handle = ValidateHandle(key);
if (handle.index > -1)
{
value = this.items[handle.index].value;
return true;
}
value = default(T);
return false;
}
public bool ContainsHandle(IHandle ihandle)
{
Handle handle = ValidateHandle(ihandle);
return object.ReferenceEquals(handle.heap, this) && handle.index > -1;
}
public void Add(T value, ref IHandle handle)
{
if (handle == null)
handle = new Handle();
Add(value, handle);
}
public void Add(T value, IHandle ihandle)
{
if (this.size == this.items.Length)
{
int capacity = (int)((this.items.Length * 200L) / 100L);
if (capacity < (this.items.Length + DEFAULT_CAPACITY))
capacity = this.items.Length + DEFAULT_CAPACITY;
Array.Resize<HeapItem>(ref this.items, capacity);
}
Handle handle = null;
if (ihandle != null)
{
handle = ValidateHandle(ihandle);
handle.heap = this;
}
HeapItem item = new MinHeap<T>.HeapItem(value, handle);
Set(item, this.size);
BubbleUp(this.size++);
}
public void Add(T value)
{
Add(value, null);
}
public T Min()
{
if (this.size == 0)
throw new InvalidOperationException("Heap is empty");
return this.items[0].value;
}
public void Clear()
{
for (int index = 0; index < this.size; ++index)
this.items[index].Clear();
this.size = 0;
++this.version;
}
public void TrimExcess()
{
int length = (int)(this.items.Length * 0.9);
if (this.size < length)
Array.Resize<HeapItem>(ref this.items, Math.Min(this.size, DEFAULT_CAPACITY));
}
private void RemoveAt(int index)
{
if (this.size == 0)
throw new InvalidOperationException("Heap is empty");
if (index >= this.size)
throw new ArgumentOutOfRangeException("index");
this.items[index].Clear();
if (--this.size > 0 && index != this.size)
{
Set(this.items[this.size], index);
this.items[this.size].ClearRef();
if (!BubbleUp(index))
BubbleDown(index);
}
}
public T RemoveMin()
{
if (this.size == 0)
throw new InvalidOperationException("Heap is empty");
HeapItem item = this.items[0];
RemoveAt(0);
return item.value;
}
public T Remove(IHandle ihandle)
{
Handle handle = ValidateThisHandle(ihandle);
HeapItem item = this.items[handle.index];
RemoveAt(handle.index);
return item.value;
}
private int GetIndex(T value)
{
EqualityComparer<T> comparer = EqualityComparer<T>.Default;
int index;
for (index = 0; index < this.size; ++index)
{
if (comparer.Equals(this.items[index].value, value))
return index;
}
return -1;
}
public bool Contains(T value)
{
return GetIndex(value) != -1;
}
public bool Remove(T value)
{
int index = GetIndex(value);
if (index != -1)
{
RemoveAt(index);
return true;
}
return false;
}
public void CopyTo(T[] array, int index)
{
if (array == null)
throw new ArgumentNullException("array");
if (array.Rank != 1)
throw new ArgumentException("Multidimensional array not supported");
if (array.GetLowerBound(0) != 0)
throw new ArgumentException("Non-zero lower bound array not supported");
int length = array.Length;
if ((index < 0) || (index > length))
throw new ArgumentOutOfRangeException("index");
if ((length - index) < this.size)
throw new ArgumentException("Not enough space available in array starting at index");
for (int i = 0; i < this.size; ++i)
array[index + i] = this.items[i].value;
}
public void CopyTo(Array array, int index)
{
if (array == null)
throw new ArgumentNullException("array");
if (array.Rank != 1)
throw new ArgumentException("Multidimensional array not supported");
if (array.GetLowerBound(0) != 0)
throw new ArgumentException("Non-zero lower bound array not supported");
int length = array.Length;
if ((index < 0) || (index > length))
throw new ArgumentOutOfRangeException("index");
if ((length - index) < this.size)
throw new ArgumentException("Not enough space available in array starting at index");
try
{
for (int i = 0; i < this.size; ++i)
array.SetValue(this.items[i].value, index + i);
}
catch (ArrayTypeMismatchException)
{
throw new ArgumentException("Invalid array type");
}
}
public IEnumerator<T> GetEnumerator()
{
int version = this.version;
for (int index = 0; index < this.size; ++index)
{
if (version != this.version)
throw new InvalidOperationException("Heap was modified while enumerating");
yield return this.items[index].value;
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
}
| |
/*
* Copyright (c) 2012 Stephen A. Pratt
*
* 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.Collections.Generic;
using org.critterai.nmbuild;
using org.critterai.nav;
using org.critterai.nmbuild.u3d.editor;
using org.critterai.nmgen;
using UnityEngine;
/// <summary>
/// Defines a mapping between areas and flags and applies the flags during the NMGen build process.
/// (Editor Only)
/// </summary>
/// <remarks>
/// <para>
/// Any polygon or off-mesh connection assigned to one of the defined areas will have the
/// associated flags added. E.g. The 'water' area gets the 'swim' flag.
/// </para>
/// <para>
/// The flags are applied to <see cref="PolyMesh"/> polygons during the NMGen build, and to
/// off-mesh connections during input post-processing.
/// </para>
/// </remarks>
[System.Serializable]
public sealed class AreaFlagDef
: ScriptableObject, IInputBuildProcessor
{
/// <summary>
/// Flags to associate with areas.
/// </summary>
public List<int> flags;
/// <summary>
/// The area associated with the flags.
/// </summary>
public List<byte> areas;
[SerializeField]
private int mPriority = NMBuild.DefaultPriority;
/// <summary>
/// The priority of the processor.
/// </summary>
public int Priority { get { return mPriority; } }
/// <summary>
/// The name of the processor
/// </summary>
public string Name { get { return name; } }
/// <summary>
/// Sets the priority.
/// </summary>
/// <param name="value">The new priority.</param>
public void SetPriority(int value)
{
mPriority = NMBuild.ClampPriority(value);
}
/// <summary>
/// Duplicates allowed. (Always true.)
/// </summary>
public bool DuplicatesAllowed { get { return true; } }
/// <summary>
/// Processes the context.
/// </summary>
/// <remarks>
/// <para>
/// Applied during the <see cref="InputBuildState.CompileInput"/> and
/// <see cref="InputBuildState.PostProcess"/> states.
/// </para>
/// </remarks>
/// <param name="state">The current state of the input build.</param>
/// <param name="context">The input context to process.</param>
/// <returns>False if the input build should abort.</returns>
public bool ProcessInput(InputBuildContext context, InputBuildState state)
{
if (state == InputBuildState.CompileInput)
return ProcessCompile(context);
if (state == InputBuildState.PostProcess)
return ProcessPost(context);
return true;
}
private bool ProcessPost(InputBuildContext context)
{
if (!ProcessValidation(context))
return false;
context.info.postCount++;
if (areas.Count == 0)
{
context.Log("No area/flag maps. No action taken.", this);
return true;
}
ConnectionSetCompiler conns = context.connCompiler;
bool applied = false;
for (int i = 0; i < areas.Count; i++)
{
byte area = areas[i];
ushort flag = (ushort)flags[i];
int marked = 0;
for (int iConn = 0; iConn < conns.Count; iConn++)
{
OffMeshConnection conn = conns[iConn];
if (conn.area == area)
{
conn.flags |= flag;
conns[iConn] = conn;
marked++;
}
}
if (marked > 0)
{
string msg = string.Format(
"Added '0x{0:X}' flags to {1} connections with the area {2}."
, flag, marked, area);
context.Log(msg, this);
applied = true;
}
}
if (!applied)
context.Log("No flags applied.", this);
return true;
}
private bool ProcessValidation(InputBuildContext context)
{
if (flags == null || areas == null || flags.Count != areas.Count)
{
context.Log("Area/Flag size error. (Invalid processor state.)", this);
return false;
}
return true;
}
private bool ProcessCompile(InputBuildContext context)
{
if (!ProcessValidation(context))
return false;
context.info.compilerCount++;
if (areas.Count == 0)
{
context.Log("No area/flag maps. No action taken.", this);
return true;
}
ushort[] sflags = new ushort[flags.Count];
for (int i = 0; i < sflags.Length; i++)
{
// The editor should prevent overflows.
sflags[i] = (ushort)flags[i];
}
AreaFlagMapper mapper = AreaFlagMapper.Create(name, Priority, areas.ToArray(), sflags);
if (mapper == null)
{
context.LogError("Failed to create NMGen processor. Unexpected invalid data.", this);
return false;
}
context.processors.Add(mapper);
context.Log(string.Format("Added {0} NMGen processor.", typeof(AreaFlagMapper).Name), this);
return true;
}
}
| |
/*
* 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 CookComputing.XmlRpc;
namespace XenAPI
{
/// <summary>
/// A long-running asynchronous task
/// First published in XenServer 4.0.
/// </summary>
public partial class Task : XenObject<Task>
{
public Task()
{
}
public Task(string uuid,
string name_label,
string name_description,
List<task_allowed_operations> allowed_operations,
Dictionary<string, task_allowed_operations> current_operations,
DateTime created,
DateTime finished,
task_status_type status,
XenRef<Host> resident_on,
double progress,
string type,
string result,
string[] error_info,
Dictionary<string, string> other_config,
XenRef<Task> subtask_of,
List<XenRef<Task>> subtasks,
string backtrace)
{
this.uuid = uuid;
this.name_label = name_label;
this.name_description = name_description;
this.allowed_operations = allowed_operations;
this.current_operations = current_operations;
this.created = created;
this.finished = finished;
this.status = status;
this.resident_on = resident_on;
this.progress = progress;
this.type = type;
this.result = result;
this.error_info = error_info;
this.other_config = other_config;
this.subtask_of = subtask_of;
this.subtasks = subtasks;
this.backtrace = backtrace;
}
/// <summary>
/// Creates a new Task from a Proxy_Task.
/// </summary>
/// <param name="proxy"></param>
public Task(Proxy_Task proxy)
{
this.UpdateFromProxy(proxy);
}
public override void UpdateFrom(Task update)
{
uuid = update.uuid;
name_label = update.name_label;
name_description = update.name_description;
allowed_operations = update.allowed_operations;
current_operations = update.current_operations;
created = update.created;
finished = update.finished;
status = update.status;
resident_on = update.resident_on;
progress = update.progress;
type = update.type;
result = update.result;
error_info = update.error_info;
other_config = update.other_config;
subtask_of = update.subtask_of;
subtasks = update.subtasks;
backtrace = update.backtrace;
}
internal void UpdateFromProxy(Proxy_Task proxy)
{
uuid = proxy.uuid == null ? null : (string)proxy.uuid;
name_label = proxy.name_label == null ? null : (string)proxy.name_label;
name_description = proxy.name_description == null ? null : (string)proxy.name_description;
allowed_operations = proxy.allowed_operations == null ? null : Helper.StringArrayToEnumList<task_allowed_operations>(proxy.allowed_operations);
current_operations = proxy.current_operations == null ? null : Maps.convert_from_proxy_string_task_allowed_operations(proxy.current_operations);
created = proxy.created;
finished = proxy.finished;
status = proxy.status == null ? (task_status_type) 0 : (task_status_type)Helper.EnumParseDefault(typeof(task_status_type), (string)proxy.status);
resident_on = proxy.resident_on == null ? null : XenRef<Host>.Create(proxy.resident_on);
progress = Convert.ToDouble(proxy.progress);
type = proxy.type == null ? null : (string)proxy.type;
result = proxy.result == null ? null : (string)proxy.result;
error_info = proxy.error_info == null ? new string[] {} : (string [])proxy.error_info;
other_config = proxy.other_config == null ? null : Maps.convert_from_proxy_string_string(proxy.other_config);
subtask_of = proxy.subtask_of == null ? null : XenRef<Task>.Create(proxy.subtask_of);
subtasks = proxy.subtasks == null ? null : XenRef<Task>.Create(proxy.subtasks);
backtrace = proxy.backtrace == null ? null : (string)proxy.backtrace;
}
public Proxy_Task ToProxy()
{
Proxy_Task result_ = new Proxy_Task();
result_.uuid = (uuid != null) ? uuid : "";
result_.name_label = (name_label != null) ? name_label : "";
result_.name_description = (name_description != null) ? name_description : "";
result_.allowed_operations = (allowed_operations != null) ? Helper.ObjectListToStringArray(allowed_operations) : new string[] {};
result_.current_operations = Maps.convert_to_proxy_string_task_allowed_operations(current_operations);
result_.created = created;
result_.finished = finished;
result_.status = task_status_type_helper.ToString(status);
result_.resident_on = (resident_on != null) ? resident_on : "";
result_.progress = progress;
result_.type = (type != null) ? type : "";
result_.result = (result != null) ? result : "";
result_.error_info = error_info;
result_.other_config = Maps.convert_to_proxy_string_string(other_config);
result_.subtask_of = (subtask_of != null) ? subtask_of : "";
result_.subtasks = (subtasks != null) ? Helper.RefListToStringArray(subtasks) : new string[] {};
result_.backtrace = (backtrace != null) ? backtrace : "";
return result_;
}
/// <summary>
/// Creates a new Task from a Hashtable.
/// </summary>
/// <param name="table"></param>
public Task(Hashtable table)
{
uuid = Marshalling.ParseString(table, "uuid");
name_label = Marshalling.ParseString(table, "name_label");
name_description = Marshalling.ParseString(table, "name_description");
allowed_operations = Helper.StringArrayToEnumList<task_allowed_operations>(Marshalling.ParseStringArray(table, "allowed_operations"));
current_operations = Maps.convert_from_proxy_string_task_allowed_operations(Marshalling.ParseHashTable(table, "current_operations"));
created = Marshalling.ParseDateTime(table, "created");
finished = Marshalling.ParseDateTime(table, "finished");
status = (task_status_type)Helper.EnumParseDefault(typeof(task_status_type), Marshalling.ParseString(table, "status"));
resident_on = Marshalling.ParseRef<Host>(table, "resident_on");
progress = Marshalling.ParseDouble(table, "progress");
type = Marshalling.ParseString(table, "type");
result = Marshalling.ParseString(table, "result");
error_info = Marshalling.ParseStringArray(table, "error_info");
other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config"));
subtask_of = Marshalling.ParseRef<Task>(table, "subtask_of");
subtasks = Marshalling.ParseSetRef<Task>(table, "subtasks");
backtrace = Marshalling.ParseString(table, "backtrace");
}
public bool DeepEquals(Task other, bool ignoreCurrentOperations)
{
if (ReferenceEquals(null, other))
return false;
if (ReferenceEquals(this, other))
return true;
if (!ignoreCurrentOperations && !Helper.AreEqual2(this.current_operations, other.current_operations))
return false;
return Helper.AreEqual2(this._uuid, other._uuid) &&
Helper.AreEqual2(this._name_label, other._name_label) &&
Helper.AreEqual2(this._name_description, other._name_description) &&
Helper.AreEqual2(this._allowed_operations, other._allowed_operations) &&
Helper.AreEqual2(this._created, other._created) &&
Helper.AreEqual2(this._finished, other._finished) &&
Helper.AreEqual2(this._status, other._status) &&
Helper.AreEqual2(this._resident_on, other._resident_on) &&
Helper.AreEqual2(this._progress, other._progress) &&
Helper.AreEqual2(this._type, other._type) &&
Helper.AreEqual2(this._result, other._result) &&
Helper.AreEqual2(this._error_info, other._error_info) &&
Helper.AreEqual2(this._other_config, other._other_config) &&
Helper.AreEqual2(this._subtask_of, other._subtask_of) &&
Helper.AreEqual2(this._subtasks, other._subtasks) &&
Helper.AreEqual2(this._backtrace, other._backtrace);
}
public override string SaveChanges(Session session, string opaqueRef, Task 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))
{
Task.set_other_config(session, opaqueRef, _other_config);
}
return null;
}
}
/// <summary>
/// Get a record containing the current state of the given task.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_task">The opaque_ref of the given task</param>
public static Task get_record(Session session, string _task)
{
return new Task((Proxy_Task)session.proxy.task_get_record(session.uuid, (_task != null) ? _task : "").parse());
}
/// <summary>
/// Get a reference to the task 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<Task> get_by_uuid(Session session, string _uuid)
{
return XenRef<Task>.Create(session.proxy.task_get_by_uuid(session.uuid, (_uuid != null) ? _uuid : "").parse());
}
/// <summary>
/// Get all the task instances with the given label.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_label">label of object to return</param>
public static List<XenRef<Task>> get_by_name_label(Session session, string _label)
{
return XenRef<Task>.Create(session.proxy.task_get_by_name_label(session.uuid, (_label != null) ? _label : "").parse());
}
/// <summary>
/// Get the uuid field of the given task.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_task">The opaque_ref of the given task</param>
public static string get_uuid(Session session, string _task)
{
return (string)session.proxy.task_get_uuid(session.uuid, (_task != null) ? _task : "").parse();
}
/// <summary>
/// Get the name/label field of the given task.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_task">The opaque_ref of the given task</param>
public static string get_name_label(Session session, string _task)
{
return (string)session.proxy.task_get_name_label(session.uuid, (_task != null) ? _task : "").parse();
}
/// <summary>
/// Get the name/description field of the given task.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_task">The opaque_ref of the given task</param>
public static string get_name_description(Session session, string _task)
{
return (string)session.proxy.task_get_name_description(session.uuid, (_task != null) ? _task : "").parse();
}
/// <summary>
/// Get the allowed_operations field of the given task.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_task">The opaque_ref of the given task</param>
public static List<task_allowed_operations> get_allowed_operations(Session session, string _task)
{
return Helper.StringArrayToEnumList<task_allowed_operations>(session.proxy.task_get_allowed_operations(session.uuid, (_task != null) ? _task : "").parse());
}
/// <summary>
/// Get the current_operations field of the given task.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_task">The opaque_ref of the given task</param>
public static Dictionary<string, task_allowed_operations> get_current_operations(Session session, string _task)
{
return Maps.convert_from_proxy_string_task_allowed_operations(session.proxy.task_get_current_operations(session.uuid, (_task != null) ? _task : "").parse());
}
/// <summary>
/// Get the created field of the given task.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_task">The opaque_ref of the given task</param>
public static DateTime get_created(Session session, string _task)
{
return session.proxy.task_get_created(session.uuid, (_task != null) ? _task : "").parse();
}
/// <summary>
/// Get the finished field of the given task.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_task">The opaque_ref of the given task</param>
public static DateTime get_finished(Session session, string _task)
{
return session.proxy.task_get_finished(session.uuid, (_task != null) ? _task : "").parse();
}
/// <summary>
/// Get the status field of the given task.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_task">The opaque_ref of the given task</param>
public static task_status_type get_status(Session session, string _task)
{
return (task_status_type)Helper.EnumParseDefault(typeof(task_status_type), (string)session.proxy.task_get_status(session.uuid, (_task != null) ? _task : "").parse());
}
/// <summary>
/// Get the resident_on field of the given task.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_task">The opaque_ref of the given task</param>
public static XenRef<Host> get_resident_on(Session session, string _task)
{
return XenRef<Host>.Create(session.proxy.task_get_resident_on(session.uuid, (_task != null) ? _task : "").parse());
}
/// <summary>
/// Get the progress field of the given task.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_task">The opaque_ref of the given task</param>
public static double get_progress(Session session, string _task)
{
return Convert.ToDouble(session.proxy.task_get_progress(session.uuid, (_task != null) ? _task : "").parse());
}
/// <summary>
/// Get the type field of the given task.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_task">The opaque_ref of the given task</param>
public static string get_type(Session session, string _task)
{
return (string)session.proxy.task_get_type(session.uuid, (_task != null) ? _task : "").parse();
}
/// <summary>
/// Get the result field of the given task.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_task">The opaque_ref of the given task</param>
public static string get_result(Session session, string _task)
{
return (string)session.proxy.task_get_result(session.uuid, (_task != null) ? _task : "").parse();
}
/// <summary>
/// Get the error_info field of the given task.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_task">The opaque_ref of the given task</param>
public static string[] get_error_info(Session session, string _task)
{
return (string [])session.proxy.task_get_error_info(session.uuid, (_task != null) ? _task : "").parse();
}
/// <summary>
/// Get the other_config field of the given task.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_task">The opaque_ref of the given task</param>
public static Dictionary<string, string> get_other_config(Session session, string _task)
{
return Maps.convert_from_proxy_string_string(session.proxy.task_get_other_config(session.uuid, (_task != null) ? _task : "").parse());
}
/// <summary>
/// Get the subtask_of field of the given task.
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_task">The opaque_ref of the given task</param>
public static XenRef<Task> get_subtask_of(Session session, string _task)
{
return XenRef<Task>.Create(session.proxy.task_get_subtask_of(session.uuid, (_task != null) ? _task : "").parse());
}
/// <summary>
/// Get the subtasks field of the given task.
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_task">The opaque_ref of the given task</param>
public static List<XenRef<Task>> get_subtasks(Session session, string _task)
{
return XenRef<Task>.Create(session.proxy.task_get_subtasks(session.uuid, (_task != null) ? _task : "").parse());
}
/// <summary>
/// Get the backtrace field of the given task.
/// First published in XenServer Dundee.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_task">The opaque_ref of the given task</param>
public static string get_backtrace(Session session, string _task)
{
return (string)session.proxy.task_get_backtrace(session.uuid, (_task != null) ? _task : "").parse();
}
/// <summary>
/// Set the other_config field of the given task.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_task">The opaque_ref of the given task</param>
/// <param name="_other_config">New value to set</param>
public static void set_other_config(Session session, string _task, Dictionary<string, string> _other_config)
{
session.proxy.task_set_other_config(session.uuid, (_task != null) ? _task : "", Maps.convert_to_proxy_string_string(_other_config)).parse();
}
/// <summary>
/// Add the given key-value pair to the other_config field of the given task.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_task">The opaque_ref of the given task</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 _task, string _key, string _value)
{
session.proxy.task_add_to_other_config(session.uuid, (_task != null) ? _task : "", (_key != null) ? _key : "", (_value != null) ? _value : "").parse();
}
/// <summary>
/// Remove the given key and its corresponding value from the other_config field of the given task. If the key is not in that Map, then do nothing.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_task">The opaque_ref of the given task</param>
/// <param name="_key">Key to remove</param>
public static void remove_from_other_config(Session session, string _task, string _key)
{
session.proxy.task_remove_from_other_config(session.uuid, (_task != null) ? _task : "", (_key != null) ? _key : "").parse();
}
/// <summary>
/// Create a new task object which must be manually destroyed.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_label">short label for the new task</param>
/// <param name="_description">longer description for the new task</param>
public static XenRef<Task> create(Session session, string _label, string _description)
{
return XenRef<Task>.Create(session.proxy.task_create(session.uuid, (_label != null) ? _label : "", (_description != null) ? _description : "").parse());
}
/// <summary>
/// Destroy the task object
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_task">The opaque_ref of the given task</param>
public static void destroy(Session session, string _task)
{
session.proxy.task_destroy(session.uuid, (_task != null) ? _task : "").parse();
}
/// <summary>
/// Request that a task be cancelled. Note that a task may fail to be cancelled and may complete or fail normally and note that, even when a task does cancel, it might take an arbitrary amount of time.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_task">The opaque_ref of the given task</param>
public static void cancel(Session session, string _task)
{
session.proxy.task_cancel(session.uuid, (_task != null) ? _task : "").parse();
}
/// <summary>
/// Request that a task be cancelled. Note that a task may fail to be cancelled and may complete or fail normally and note that, even when a task does cancel, it might take an arbitrary amount of time.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_task">The opaque_ref of the given task</param>
public static XenRef<Task> async_cancel(Session session, string _task)
{
return XenRef<Task>.Create(session.proxy.async_task_cancel(session.uuid, (_task != null) ? _task : "").parse());
}
/// <summary>
/// Return a list of all the tasks known to the system.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
public static List<XenRef<Task>> get_all(Session session)
{
return XenRef<Task>.Create(session.proxy.task_get_all(session.uuid).parse());
}
/// <summary>
/// Get all the task 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<Task>, Task> get_all_records(Session session)
{
return XenRef<Task>.Create<Proxy_Task>(session.proxy.task_get_all_records(session.uuid).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>
/// a human-readable name
/// </summary>
public virtual string name_label
{
get { return _name_label; }
set
{
if (!Helper.AreEqual(value, _name_label))
{
_name_label = value;
Changed = true;
NotifyPropertyChanged("name_label");
}
}
}
private string _name_label;
/// <summary>
/// a notes field containing human-readable description
/// </summary>
public virtual string name_description
{
get { return _name_description; }
set
{
if (!Helper.AreEqual(value, _name_description))
{
_name_description = value;
Changed = true;
NotifyPropertyChanged("name_description");
}
}
}
private string _name_description;
/// <summary>
/// list of the operations allowed in this state. This list is advisory only and the server state may have changed by the time this field is read by a client.
/// </summary>
public virtual List<task_allowed_operations> allowed_operations
{
get { return _allowed_operations; }
set
{
if (!Helper.AreEqual(value, _allowed_operations))
{
_allowed_operations = value;
Changed = true;
NotifyPropertyChanged("allowed_operations");
}
}
}
private List<task_allowed_operations> _allowed_operations;
/// <summary>
/// links each of the running tasks using this object (by reference) to a current_operation enum which describes the nature of the task.
/// </summary>
public virtual Dictionary<string, task_allowed_operations> current_operations
{
get { return _current_operations; }
set
{
if (!Helper.AreEqual(value, _current_operations))
{
_current_operations = value;
Changed = true;
NotifyPropertyChanged("current_operations");
}
}
}
private Dictionary<string, task_allowed_operations> _current_operations;
/// <summary>
/// Time task was created
/// </summary>
public virtual DateTime created
{
get { return _created; }
set
{
if (!Helper.AreEqual(value, _created))
{
_created = value;
Changed = true;
NotifyPropertyChanged("created");
}
}
}
private DateTime _created;
/// <summary>
/// Time task finished (i.e. succeeded or failed). If task-status is pending, then the value of this field has no meaning
/// </summary>
public virtual DateTime finished
{
get { return _finished; }
set
{
if (!Helper.AreEqual(value, _finished))
{
_finished = value;
Changed = true;
NotifyPropertyChanged("finished");
}
}
}
private DateTime _finished;
/// <summary>
/// current status of the task
/// </summary>
public virtual task_status_type status
{
get { return _status; }
set
{
if (!Helper.AreEqual(value, _status))
{
_status = value;
Changed = true;
NotifyPropertyChanged("status");
}
}
}
private task_status_type _status;
/// <summary>
/// the host on which the task is running
/// </summary>
public virtual XenRef<Host> resident_on
{
get { return _resident_on; }
set
{
if (!Helper.AreEqual(value, _resident_on))
{
_resident_on = value;
Changed = true;
NotifyPropertyChanged("resident_on");
}
}
}
private XenRef<Host> _resident_on;
/// <summary>
/// This field contains the estimated fraction of the task which is complete. This field should not be used to determine whether the task is complete - for this the status field of the task should be used.
/// </summary>
public virtual double progress
{
get { return _progress; }
set
{
if (!Helper.AreEqual(value, _progress))
{
_progress = value;
Changed = true;
NotifyPropertyChanged("progress");
}
}
}
private double _progress;
/// <summary>
/// if the task has completed successfully, this field contains the type of the encoded result (i.e. name of the class whose reference is in the result field). Undefined otherwise.
/// </summary>
public virtual string type
{
get { return _type; }
set
{
if (!Helper.AreEqual(value, _type))
{
_type = value;
Changed = true;
NotifyPropertyChanged("type");
}
}
}
private string _type;
/// <summary>
/// if the task has completed successfully, this field contains the result value (either Void or an object reference). Undefined otherwise.
/// </summary>
public virtual string result
{
get { return _result; }
set
{
if (!Helper.AreEqual(value, _result))
{
_result = value;
Changed = true;
NotifyPropertyChanged("result");
}
}
}
private string _result;
/// <summary>
/// if the task has failed, this field contains the set of associated error strings. Undefined otherwise.
/// </summary>
public virtual string[] error_info
{
get { return _error_info; }
set
{
if (!Helper.AreEqual(value, _error_info))
{
_error_info = value;
Changed = true;
NotifyPropertyChanged("error_info");
}
}
}
private string[] _error_info;
/// <summary>
/// additional configuration
/// First published in XenServer 4.1.
/// </summary>
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;
/// <summary>
/// Ref pointing to the task this is a substask of.
/// First published in XenServer 5.0.
/// </summary>
public virtual XenRef<Task> subtask_of
{
get { return _subtask_of; }
set
{
if (!Helper.AreEqual(value, _subtask_of))
{
_subtask_of = value;
Changed = true;
NotifyPropertyChanged("subtask_of");
}
}
}
private XenRef<Task> _subtask_of;
/// <summary>
/// List pointing to all the substasks.
/// First published in XenServer 5.0.
/// </summary>
public virtual List<XenRef<Task>> subtasks
{
get { return _subtasks; }
set
{
if (!Helper.AreEqual(value, _subtasks))
{
_subtasks = value;
Changed = true;
NotifyPropertyChanged("subtasks");
}
}
}
private List<XenRef<Task>> _subtasks;
/// <summary>
/// Function call trace for debugging.
/// First published in XenServer Dundee.
/// </summary>
public virtual string backtrace
{
get { return _backtrace; }
set
{
if (!Helper.AreEqual(value, _backtrace))
{
_backtrace = value;
Changed = true;
NotifyPropertyChanged("backtrace");
}
}
}
private string _backtrace;
}
}
| |
//#define TRACE_SERIALIZATION
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
using System.Text;
using Orleans.CodeGeneration;
using Orleans.GrainDirectory;
using Orleans.Runtime;
namespace Orleans.Serialization
{
internal static class BinaryTokenStreamReaderExtensinons
{
/// <summary> Read an <c>GrainId</c> value from the stream. </summary>
/// <returns>Data from current position in stream, converted to the appropriate output type.</returns>
internal static GrainId ReadGrainId<TReader>(this TReader @this) where TReader : IBinaryTokenStreamReader
{
UniqueKey key = @this.ReadUniqueKey();
return GrainId.GetGrainId(key);
}
/// <summary> Read an <c>ActivationId</c> value from the stream. </summary>
/// <returns>Data from current position in stream, converted to the appropriate output type.</returns>
internal static ActivationId ReadActivationId<TReader>(this TReader @this) where TReader : IBinaryTokenStreamReader
{
UniqueKey key = @this.ReadUniqueKey();
return ActivationId.GetActivationId(key);
}
internal static UniqueKey ReadUniqueKey<TReader>(this TReader @this) where TReader : IBinaryTokenStreamReader
{
ulong n0 = @this.ReadULong();
ulong n1 = @this.ReadULong();
ulong typeCodeData = @this.ReadULong();
string keyExt = @this.ReadString();
return UniqueKey.NewKey(n0, n1, typeCodeData, keyExt);
}
internal static CorrelationId ReadCorrelationId<TReader>(this TReader @this) where TReader : IBinaryTokenStreamReader
{
return new CorrelationId(@this.ReadLong());
}
internal static GrainDirectoryEntryStatus ReadMultiClusterStatus<TReader>(this TReader @this) where TReader : IBinaryTokenStreamReader
{
byte val = @this.ReadByte();
return (GrainDirectoryEntryStatus)val;
}
/// <summary> Read an <c>ActivationAddress</c> value from the stream. </summary>
/// <returns>Data from current position in stream, converted to the appropriate output type.</returns>
internal static ActivationAddress ReadActivationAddress<TReader>(this TReader @this) where TReader : IBinaryTokenStreamReader
{
var silo = @this.ReadSiloAddress();
var grain = @this.ReadGrainId();
var act = @this.ReadActivationId();
if (silo.Equals(SiloAddress.Zero))
silo = null;
if (act.Equals(ActivationId.Zero))
act = null;
return ActivationAddress.GetAddress(silo, grain, act);
}
/// <summary>
/// Peek at the next token in this input stream.
/// </summary>
/// <returns>Next token that will be read from the stream.</returns>
internal static SerializationTokenType PeekToken<TReader>(this TReader @this) where TReader : IBinaryTokenStreamReader
{
return (SerializationTokenType)@this.PeekByte();
}
/// <summary> Read a <c>SerializationTokenType</c> value from the stream. </summary>
/// <returns>Data from current position in stream, converted to the appropriate output type.</returns>
internal static SerializationTokenType ReadToken<TReader>(this TReader @this) where TReader : IBinaryTokenStreamReader
{
return (SerializationTokenType)@this.ReadByte();
}
internal static bool TryReadSimpleType<TReader>(this TReader @this, out object result, out SerializationTokenType token) where TReader : IBinaryTokenStreamReader
{
token = @this.ReadToken();
switch (token)
{
case SerializationTokenType.True:
result = true;
break;
case SerializationTokenType.False:
result = false;
break;
case SerializationTokenType.Null:
result = null;
break;
case SerializationTokenType.Object:
result = new object();
break;
case SerializationTokenType.Int:
result = @this.ReadInt();
break;
case SerializationTokenType.Uint:
result = @this.ReadUInt();
break;
case SerializationTokenType.Short:
result = @this.ReadShort();
break;
case SerializationTokenType.Ushort:
result = @this.ReadUShort();
break;
case SerializationTokenType.Long:
result = @this.ReadLong();
break;
case SerializationTokenType.Ulong:
result = @this.ReadULong();
break;
case SerializationTokenType.Byte:
result = @this.ReadByte();
break;
case SerializationTokenType.Sbyte:
result = @this.ReadSByte();
break;
case SerializationTokenType.Float:
result = @this.ReadFloat();
break;
case SerializationTokenType.Double:
result = @this.ReadDouble();
break;
case SerializationTokenType.Decimal:
result = @this.ReadDecimal();
break;
case SerializationTokenType.String:
result = @this.ReadString();
break;
case SerializationTokenType.Character:
result = @this.ReadChar();
break;
case SerializationTokenType.Guid:
#if NETSTANDARD2_1
if (@this is BinaryTokenStreamReader2 reader)
{
Span<byte> bytes = stackalloc byte[16];
reader.ReadBytes(in bytes);
result = new Guid(bytes);
}
else
{
var bytes = @this.ReadBytes(16);
result = new Guid(bytes);
}
#else
var bytes = @this.ReadBytes(16);
result = new Guid(bytes);
#endif
break;
case SerializationTokenType.Date:
result = DateTime.FromBinary(@this.ReadLong());
break;
case SerializationTokenType.TimeSpan:
result = new TimeSpan(@this.ReadLong());
break;
case SerializationTokenType.GrainId:
result = @this.ReadGrainId();
break;
case SerializationTokenType.ActivationId:
result = @this.ReadActivationId();
break;
case SerializationTokenType.SiloAddress:
result = @this.ReadSiloAddress();
break;
case SerializationTokenType.ActivationAddress:
result = @this.ReadActivationAddress();
break;
case SerializationTokenType.IpAddress:
result = @this.ReadIPAddress();
break;
case SerializationTokenType.IpEndPoint:
result = @this.ReadIPEndPoint();
break;
case SerializationTokenType.CorrelationId:
result = new CorrelationId(@this.ReadLong());
break;
default:
result = null;
return false;
}
return true;
}
internal static Type CheckSpecialTypeCode(SerializationTokenType token)
{
switch (token)
{
case SerializationTokenType.Boolean:
return typeof(bool);
case SerializationTokenType.Int:
return typeof(int);
case SerializationTokenType.Short:
return typeof(short);
case SerializationTokenType.Long:
return typeof(long);
case SerializationTokenType.Sbyte:
return typeof(sbyte);
case SerializationTokenType.Uint:
return typeof(uint);
case SerializationTokenType.Ushort:
return typeof(ushort);
case SerializationTokenType.Ulong:
return typeof(ulong);
case SerializationTokenType.Byte:
return typeof(byte);
case SerializationTokenType.Float:
return typeof(float);
case SerializationTokenType.Double:
return typeof(double);
case SerializationTokenType.Decimal:
return typeof(decimal);
case SerializationTokenType.String:
return typeof(string);
case SerializationTokenType.Character:
return typeof(char);
case SerializationTokenType.Guid:
return typeof(Guid);
case SerializationTokenType.Date:
return typeof(DateTime);
case SerializationTokenType.TimeSpan:
return typeof(TimeSpan);
case SerializationTokenType.IpAddress:
return typeof(IPAddress);
case SerializationTokenType.IpEndPoint:
return typeof(IPEndPoint);
case SerializationTokenType.GrainId:
return typeof(GrainId);
case SerializationTokenType.ActivationId:
return typeof(ActivationId);
case SerializationTokenType.SiloAddress:
return typeof(SiloAddress);
case SerializationTokenType.ActivationAddress:
return typeof(ActivationAddress);
case SerializationTokenType.CorrelationId:
return typeof(CorrelationId);
#if false // Note: not yet implemented as simple types on the Writer side
case SerializationTokenType.Object:
return typeof(Object);
case SerializationTokenType.ByteArray:
return typeof(byte[]);
case SerializationTokenType.ShortArray:
return typeof(short[]);
case SerializationTokenType.IntArray:
return typeof(int[]);
case SerializationTokenType.LongArray:
return typeof(long[]);
case SerializationTokenType.UShortArray:
return typeof(ushort[]);
case SerializationTokenType.UIntArray:
return typeof(uint[]);
case SerializationTokenType.ULongArray:
return typeof(ulong[]);
case SerializationTokenType.FloatArray:
return typeof(float[]);
case SerializationTokenType.DoubleArray:
return typeof(double[]);
case SerializationTokenType.CharArray:
return typeof(char[]);
case SerializationTokenType.BoolArray:
return typeof(bool[]);
#endif
default:
break;
}
return null;
}
/// <summary> Read a <c>Type</c> value from the stream. </summary>
internal static Type ReadSpecifiedTypeHeader<TReader>(this TReader @this, SerializationManager serializationManager) where TReader : IBinaryTokenStreamReader
{
// Assumes that the SpecifiedType token has already been read
var token = @this.ReadToken();
switch (token)
{
case SerializationTokenType.Boolean:
return typeof(bool);
case SerializationTokenType.Int:
return typeof(int);
case SerializationTokenType.Short:
return typeof(short);
case SerializationTokenType.Long:
return typeof(long);
case SerializationTokenType.Sbyte:
return typeof(sbyte);
case SerializationTokenType.Uint:
return typeof(uint);
case SerializationTokenType.Ushort:
return typeof(ushort);
case SerializationTokenType.Ulong:
return typeof(ulong);
case SerializationTokenType.Byte:
return typeof(byte);
case SerializationTokenType.Float:
return typeof(float);
case SerializationTokenType.Double:
return typeof(double);
case SerializationTokenType.Decimal:
return typeof(decimal);
case SerializationTokenType.String:
return typeof(string);
case SerializationTokenType.Character:
return typeof(char);
case SerializationTokenType.Guid:
return typeof(Guid);
case SerializationTokenType.Date:
return typeof(DateTime);
case SerializationTokenType.TimeSpan:
return typeof(TimeSpan);
case SerializationTokenType.IpAddress:
return typeof(IPAddress);
case SerializationTokenType.IpEndPoint:
return typeof(IPEndPoint);
case SerializationTokenType.GrainId:
return typeof(GrainId);
case SerializationTokenType.ActivationId:
return typeof(ActivationId);
case SerializationTokenType.SiloAddress:
return typeof(SiloAddress);
case SerializationTokenType.ActivationAddress:
return typeof(ActivationAddress);
case SerializationTokenType.CorrelationId:
return typeof(CorrelationId);
case SerializationTokenType.Request:
return typeof(InvokeMethodRequest);
case SerializationTokenType.Response:
return typeof(Response);
case SerializationTokenType.StringObjDict:
return typeof(Dictionary<string, object>);
case SerializationTokenType.Object:
return typeof(Object);
case SerializationTokenType.Tuple + 1:
return typeof(Tuple<>).MakeGenericType(@this.ReadGenericArguments(serializationManager, 1));
case SerializationTokenType.Tuple + 2:
return typeof(Tuple<,>).MakeGenericType(@this.ReadGenericArguments(serializationManager, 2));
case SerializationTokenType.Tuple + 3:
return typeof(Tuple<,,>).MakeGenericType(@this.ReadGenericArguments(serializationManager, 3));
case SerializationTokenType.Tuple + 4:
return typeof(Tuple<,,,>).MakeGenericType(@this.ReadGenericArguments(serializationManager, 4));
case SerializationTokenType.Tuple + 5:
return typeof(Tuple<,,,,>).MakeGenericType(@this.ReadGenericArguments(serializationManager, 5));
case SerializationTokenType.Tuple + 6:
return typeof(Tuple<,,,,,>).MakeGenericType(@this.ReadGenericArguments(serializationManager, 6));
case SerializationTokenType.Tuple + 7:
return typeof(Tuple<,,,,,,>).MakeGenericType(@this.ReadGenericArguments(serializationManager, 7));
case SerializationTokenType.Array + 1:
var et1 = @this.ReadFullTypeHeader(serializationManager);
return et1.MakeArrayType();
case SerializationTokenType.Array + 2:
var et2 = @this.ReadFullTypeHeader(serializationManager);
return et2.MakeArrayType(2);
case SerializationTokenType.Array + 3:
var et3 = @this.ReadFullTypeHeader(serializationManager);
return et3.MakeArrayType(3);
case SerializationTokenType.Array + 4:
var et4 = @this.ReadFullTypeHeader(serializationManager);
return et4.MakeArrayType(4);
case SerializationTokenType.Array + 5:
var et5 = @this.ReadFullTypeHeader(serializationManager);
return et5.MakeArrayType(5);
case SerializationTokenType.Array + 6:
var et6 = @this.ReadFullTypeHeader(serializationManager);
return et6.MakeArrayType(6);
case SerializationTokenType.Array + 7:
var et7 = @this.ReadFullTypeHeader(serializationManager);
return et7.MakeArrayType(7);
case SerializationTokenType.Array + 8:
var et8 = @this.ReadFullTypeHeader(serializationManager);
return et8.MakeArrayType(8);
case SerializationTokenType.List:
return typeof(List<>).MakeGenericType(@this.ReadGenericArguments(serializationManager, 1));
case SerializationTokenType.Dictionary:
return typeof(Dictionary<,>).MakeGenericType(@this.ReadGenericArguments(serializationManager, 2));
case SerializationTokenType.KeyValuePair:
return typeof(KeyValuePair<,>).MakeGenericType(@this.ReadGenericArguments(serializationManager, 2));
case SerializationTokenType.Set:
return typeof(HashSet<>).MakeGenericType(@this.ReadGenericArguments(serializationManager, 1));
case SerializationTokenType.SortedList:
return typeof(SortedList<,>).MakeGenericType(@this.ReadGenericArguments(serializationManager, 2));
case SerializationTokenType.SortedSet:
return typeof(SortedSet<>).MakeGenericType(@this.ReadGenericArguments(serializationManager, 1));
case SerializationTokenType.Stack:
return typeof(Stack<>).MakeGenericType(@this.ReadGenericArguments(serializationManager, 1));
case SerializationTokenType.Queue:
return typeof(Queue<>).MakeGenericType(@this.ReadGenericArguments(serializationManager, 1));
case SerializationTokenType.LinkedList:
return typeof(LinkedList<>).MakeGenericType(@this.ReadGenericArguments(serializationManager, 1));
case SerializationTokenType.Nullable:
return typeof(Nullable<>).MakeGenericType(@this.ReadGenericArguments(serializationManager, 1));
case SerializationTokenType.ByteArray:
return typeof(byte[]);
case SerializationTokenType.ShortArray:
return typeof(short[]);
case SerializationTokenType.IntArray:
return typeof(int[]);
case SerializationTokenType.LongArray:
return typeof(long[]);
case SerializationTokenType.UShortArray:
return typeof(ushort[]);
case SerializationTokenType.UIntArray:
return typeof(uint[]);
case SerializationTokenType.ULongArray:
return typeof(ulong[]);
case SerializationTokenType.FloatArray:
return typeof(float[]);
case SerializationTokenType.DoubleArray:
return typeof(double[]);
case SerializationTokenType.CharArray:
return typeof(char[]);
case SerializationTokenType.BoolArray:
return typeof(bool[]);
case SerializationTokenType.SByteArray:
return typeof(sbyte[]);
case SerializationTokenType.NamedType:
var typeName = @this.ReadString();
try
{
var type = serializationManager.ResolveTypeName(typeName);
return type;
}
catch (TypeAccessException ex)
{
throw new TypeAccessException("Named type \"" + typeName + "\" is invalid: " + ex.Message);
}
default:
break;
}
throw new SerializationException("Unexpected '" + token + "' found when expecting a type reference");
}
/// <summary> Read a <c>Type</c> value from the stream. </summary>
/// <param name="this">The IBinaryTokenStreamReader to read from</param>
/// <param name="serializationManager">The serialization manager used to resolve type names.</param>
/// <param name="expected">Expected Type, if known.</param>
/// <returns>Data from current position in stream, converted to the appropriate output type.</returns>
private static Type ReadFullTypeHeader<TReader>(this TReader @this, SerializationManager serializationManager, Type expected = null) where TReader: IBinaryTokenStreamReader
{
var token = @this.ReadToken();
if (token == SerializationTokenType.ExpectedType)
{
return expected;
}
var t = CheckSpecialTypeCode(token);
if (t != null)
{
return t;
}
if (token == SerializationTokenType.SpecifiedType)
{
#if TRACE_SERIALIZATION
var tt = ReadSpecifiedTypeHeader();
Trace("--Read specified type header for type {0}", tt);
return tt;
#else
return @this.ReadSpecifiedTypeHeader(serializationManager);
#endif
}
throw new SerializationException("Invalid '" + token + "'token in input stream where full type header is expected");
}
private static Type[] ReadGenericArguments(this IBinaryTokenStreamReader @this, SerializationManager serializationManager, int n)
{
var args = new Type[n];
for (var i = 0; i < n; i++)
{
args[i] = @this.ReadFullTypeHeader(serializationManager);
}
return args;
}
}
/// <summary>
/// Reader for Orleans binary token streams
/// </summary>
public class BinaryTokenStreamReader : IBinaryTokenStreamReader
{
private IList<ArraySegment<byte>> buffers;
private int buffersCount;
private int currentSegmentIndex;
private ArraySegment<byte> currentSegment;
private byte[] currentBuffer;
private int currentOffset;
private int currentSegmentOffset;
private int currentSegmentCount;
private int totalProcessedBytes;
private int currentSegmentOffsetPlusCount;
private int totalLength;
private static readonly ArraySegment<byte> emptySegment = new ArraySegment<byte>(new byte[0]);
private static readonly byte[] emptyByteArray = new byte[0];
/// <summary>
/// Create a new BinaryTokenStreamReader to read from the specified input byte array.
/// </summary>
/// <param name="input">Input binary data to be tokenized.</param>
public BinaryTokenStreamReader(byte[] input)
: this(new List<ArraySegment<byte>> { new ArraySegment<byte>(input) })
{
}
/// <summary>
/// Create a new BinaryTokenStreamReader to read from the specified input buffers.
/// </summary>
/// <param name="buffs">The list of ArraySegments to use for the data.</param>
public BinaryTokenStreamReader(IList<ArraySegment<byte>> buffs)
{
this.Reset(buffs);
Trace("Starting new stream reader");
}
/// <summary>
/// Resets this instance with the provided data.
/// </summary>
/// <param name="buffs">The underlying buffers.</param>
public void Reset(IList<ArraySegment<byte>> buffs)
{
buffers = buffs;
totalProcessedBytes = 0;
currentSegmentIndex = 0;
InitializeCurrentSegment(0);
totalLength = buffs.Sum(b => b.Count);
buffersCount = buffs.Count;
}
private void InitializeCurrentSegment(int segmentIndex)
{
currentSegment = buffers[segmentIndex];
currentBuffer = currentSegment.Array;
currentOffset = currentSegment.Offset;
currentSegmentOffset = currentOffset;
currentSegmentCount = currentSegment.Count;
currentSegmentOffsetPlusCount = currentSegmentOffset + currentSegmentCount;
}
/// <summary>
/// Create a new BinaryTokenStreamReader to read from the specified input buffer.
/// </summary>
/// <param name="buff">ArraySegment to use for the data.</param>
public BinaryTokenStreamReader(ArraySegment<byte> buff)
: this(new[] { buff })
{
}
/// <summary> Current read position in the stream. </summary>
public int CurrentPosition => currentOffset + totalProcessedBytes - currentSegmentOffset;
/// <summary>
/// Gets the total length.
/// </summary>
public long Length => this.totalLength;
/// <summary>
/// Creates a copy of the current stream reader.
/// </summary>
/// <returns>The new copy</returns>
public IBinaryTokenStreamReader Copy()
{
return new BinaryTokenStreamReader(this.buffers);
}
private void StartNextSegment()
{
totalProcessedBytes += currentSegment.Count;
currentSegmentIndex++;
if (currentSegmentIndex < buffersCount)
{
InitializeCurrentSegment(currentSegmentIndex);
}
else
{
currentSegment = emptySegment;
currentBuffer = null;
currentOffset = 0;
currentSegmentOffset = 0;
currentSegmentOffsetPlusCount = currentSegmentOffset + currentSegmentCount;
}
}
private byte[] CheckLength(int n, out int offset)
{
bool ignore;
byte[] res;
if (TryCheckLengthFast(n, out res, out offset, out ignore))
{
return res;
}
return CheckLength(n, out offset, out ignore);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private bool TryCheckLengthFast(int n, out byte[] res, out int offset, out bool safeToUse)
{
safeToUse = false;
res = null;
offset = 0;
var nextOffset = currentOffset + n;
if (nextOffset <= currentSegmentOffsetPlusCount)
{
offset = currentOffset;
currentOffset = nextOffset;
res = currentBuffer;
return true;
}
return false;
}
private byte[] CheckLength(int n, out int offset, out bool safeToUse)
{
safeToUse = false;
offset = 0;
if (currentOffset == currentSegmentOffsetPlusCount)
{
StartNextSegment();
}
byte[] res;
if (TryCheckLengthFast(n, out res, out offset, out safeToUse))
{
return res;
}
if ((CurrentPosition + n > totalLength))
{
throw new SerializationException(
String.Format("Attempt to read past the end of the input stream: CurrentPosition={0}, n={1}, totalLength={2}",
CurrentPosition, n, totalLength));
}
var temp = new byte[n];
var i = 0;
while (i < n)
{
var segmentOffsetPlusCount = currentSegmentOffsetPlusCount;
var bytesFromThisBuffer = Math.Min(segmentOffsetPlusCount - currentOffset, n - i);
Buffer.BlockCopy(currentBuffer, currentOffset, temp, i, bytesFromThisBuffer);
i += bytesFromThisBuffer;
currentOffset += bytesFromThisBuffer;
if (currentOffset >= segmentOffsetPlusCount)
{
if (currentSegmentIndex >= buffersCount)
{
throw new SerializationException(
String.Format("Attempt to read past buffers.Count: currentSegmentIndex={0}, buffers.Count={1}.", currentSegmentIndex, buffers.Count));
}
StartNextSegment();
}
}
safeToUse = true;
offset = 0;
return temp;
}
/// <summary> Read a <c>bool</c> value from the stream. </summary>
/// <returns>Data from current position in stream, converted to the appropriate output type.</returns>
public bool ReadBoolean()
{
return this.ReadToken() == SerializationTokenType.True;
}
/// <summary> Read an <c>Int32</c> value from the stream. </summary>
/// <returns>Data from current position in stream, converted to the appropriate output type.</returns>
public int ReadInt()
{
int offset;
var buff = CheckLength(sizeof(int), out offset);
var val = BitConverter.ToInt32(buff, offset);
Trace("--Read int {0}", val);
return val;
}
/// <summary> Read an <c>UInt32</c> value from the stream. </summary>
/// <returns>Data from current position in stream, converted to the appropriate output type.</returns>
public uint ReadUInt()
{
int offset;
var buff = CheckLength(sizeof(uint), out offset);
var val = BitConverter.ToUInt32(buff, offset);
Trace("--Read uint {0}", val);
return val;
}
/// <summary> Read an <c>Int16</c> value from the stream. </summary>
/// <returns>Data from current position in stream, converted to the appropriate output type.</returns>
public short ReadShort()
{
int offset;
var buff = CheckLength(sizeof(short), out offset);
var val = BitConverter.ToInt16(buff, offset);
Trace("--Read short {0}", val);
return val;
}
/// <summary> Read an <c>UInt16</c> value from the stream. </summary>
/// <returns>Data from current position in stream, converted to the appropriate output type.</returns>
public ushort ReadUShort()
{
int offset;
var buff = CheckLength(sizeof(ushort), out offset);
var val = BitConverter.ToUInt16(buff, offset);
Trace("--Read ushort {0}", val);
return val;
}
/// <summary> Read an <c>Int64</c> value from the stream. </summary>
/// <returns>Data from current position in stream, converted to the appropriate output type.</returns>
public long ReadLong()
{
int offset;
var buff = CheckLength(sizeof(long), out offset);
var val = BitConverter.ToInt64(buff, offset);
Trace("--Read long {0}", val);
return val;
}
/// <summary> Read an <c>UInt64</c> value from the stream. </summary>
/// <returns>Data from current position in stream, converted to the appropriate output type.</returns>
public ulong ReadULong()
{
int offset;
var buff = CheckLength(sizeof(ulong), out offset);
var val = BitConverter.ToUInt64(buff, offset);
Trace("--Read ulong {0}", val);
return val;
}
/// <summary> Read an <c>float</c> value from the stream. </summary>
/// <returns>Data from current position in stream, converted to the appropriate output type.</returns>
public float ReadFloat()
{
int offset;
var buff = CheckLength(sizeof(float), out offset);
var val = BitConverter.ToSingle(buff, offset);
Trace("--Read float {0}", val);
return val;
}
/// <summary> Read an <c>double</c> value from the stream. </summary>
/// <returns>Data from current position in stream, converted to the appropriate output type.</returns>
public double ReadDouble()
{
int offset;
var buff = CheckLength(sizeof(double), out offset);
var val = BitConverter.ToDouble(buff, offset);
Trace("--Read double {0}", val);
return val;
}
/// <summary> Read an <c>decimal</c> value from the stream. </summary>
/// <returns>Data from current position in stream, converted to the appropriate output type.</returns>
public decimal ReadDecimal()
{
int offset;
var buff = CheckLength(4 * sizeof(int), out offset);
var raw = new int[4];
Trace("--Read decimal");
var n = offset;
for (var i = 0; i < 4; i++)
{
raw[i] = BitConverter.ToInt32(buff, n);
n += sizeof(int);
}
return new decimal(raw);
}
public DateTime ReadDateTime()
{
var n = ReadLong();
return n == 0 ? default(DateTime) : DateTime.FromBinary(n);
}
/// <summary> Read an <c>string</c> value from the stream. </summary>
/// <returns>Data from current position in stream, converted to the appropriate output type.</returns>
public string ReadString()
{
var n = ReadInt();
if (n == 0)
{
Trace("--Read empty string");
return String.Empty;
}
string s = null;
// a length of -1 indicates that the string is null.
if (-1 != n)
{
int offset;
var buff = CheckLength(n, out offset);
s = Encoding.UTF8.GetString(buff, offset, n);
}
Trace("--Read string '{0}'", s);
return s;
}
/// <summary> Read the next bytes from the stream. </summary>
/// <param name="count">Number of bytes to read.</param>
/// <returns>Data from current position in stream, converted to the appropriate output type.</returns>
public byte[] ReadBytes(int count)
{
if (count == 0)
{
return emptyByteArray;
}
bool safeToUse;
int offset;
byte[] buff;
if (!TryCheckLengthFast(count, out buff, out offset, out safeToUse))
{
buff = CheckLength(count, out offset, out safeToUse);
}
Trace("--Read byte array of length {0}", count);
if (!safeToUse)
{
var result = new byte[count];
Array.Copy(buff, offset, result, 0, count);
return result;
}
else
{
return buff;
}
}
/// <summary> Read the next bytes from the stream. </summary>
/// <param name="destination">Output array to store the returned data in.</param>
/// <param name="offset">Offset into the destination array to write to.</param>
/// <param name="count">Number of bytes to read.</param>
public void ReadByteArray(byte[] destination, int offset, int count)
{
if (offset + count > destination.Length)
{
throw new ArgumentOutOfRangeException("count", "Reading into an array that is too small");
}
var buffOffset = 0;
var buff = count == 0 ? emptyByteArray : CheckLength(count, out buffOffset);
Buffer.BlockCopy(buff, buffOffset, destination, offset, count);
}
/// <summary> Read an <c>char</c> value from the stream. </summary>
/// <returns>Data from current position in stream, converted to the appropriate output type.</returns>
public char ReadChar()
{
Trace("--Read char");
return Convert.ToChar(ReadShort());
}
/// <summary> Read an <c>byte</c> value from the stream. </summary>
/// <returns>Data from current position in stream, converted to the appropriate output type.</returns>
public byte ReadByte()
{
int offset;
var buff = CheckLength(1, out offset);
Trace("--Read byte");
return buff[offset];
}
public byte PeekByte()
{
if (currentOffset == currentSegment.Count + currentSegment.Offset)
StartNextSegment();
return currentBuffer[currentOffset];
}
/// <summary> Read an <c>sbyte</c> value from the stream. </summary>
/// <returns>Data from current position in stream, converted to the appropriate output type.</returns>
public sbyte ReadSByte()
{
int offset;
var buff = CheckLength(1, out offset);
Trace("--Read sbyte");
return unchecked((sbyte)(buff[offset]));
}
/// <summary> Read an <c>IPAddress</c> value from the stream. </summary>
/// <returns>Data from current position in stream, converted to the appropriate output type.</returns>
public IPAddress ReadIPAddress()
{
int offset;
var buff = CheckLength(16, out offset);
bool v4 = true;
for (var i = 0; i < 12; i++)
{
if (buff[offset + i] != 0)
{
v4 = false;
break;
}
}
if (v4)
{
var v4Bytes = new byte[4];
for (var i = 0; i < 4; i++)
{
v4Bytes[i] = buff[offset + 12 + i];
}
return new IPAddress(v4Bytes);
}
else
{
var v6Bytes = new byte[16];
for (var i = 0; i < 16; i++)
{
v6Bytes[i] = buff[offset + i];
}
return new IPAddress(v6Bytes);
}
}
public Guid ReadGuid()
{
byte[] bytes = ReadBytes(16);
return new Guid(bytes);
}
/// <summary> Read an <c>IPEndPoint</c> value from the stream. </summary>
/// <returns>Data from current position in stream, converted to the appropriate output type.</returns>
public IPEndPoint ReadIPEndPoint()
{
var addr = ReadIPAddress();
var port = ReadInt();
return new IPEndPoint(addr, port);
}
/// <summary> Read an <c>SiloAddress</c> value from the stream. </summary>
/// <returns>Data from current position in stream, converted to the appropriate output type.</returns>
public SiloAddress ReadSiloAddress()
{
var ep = ReadIPEndPoint();
var gen = ReadInt();
return SiloAddress.New(ep, gen);
}
public TimeSpan ReadTimeSpan()
{
return new TimeSpan(ReadLong());
}
/// <summary>
/// Read a block of data into the specified output <c>Array</c>.
/// </summary>
/// <param name="array">Array to output the data to.</param>
/// <param name="n">Number of bytes to read.</param>
public void ReadBlockInto(Array array, int n)
{
int offset;
var buff = CheckLength(n, out offset);
Buffer.BlockCopy(buff, offset, array, 0, n);
Trace("--Read block of {0} bytes", n);
}
private StreamWriter trace;
[Conditional("TRACE_SERIALIZATION")]
private void Trace(string format, params object[] args)
{
if (trace == null)
{
var path = String.Format("d:\\Trace-{0}.{1}.{2}.txt", DateTime.UtcNow.Hour, DateTime.UtcNow.Minute, DateTime.UtcNow.Ticks);
Console.WriteLine("Opening trace file at '{0}'", path);
trace = File.CreateText(path);
}
trace.Write(format, args);
trace.WriteLine(" at offset {0}", CurrentPosition);
trace.Flush();
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Text;
namespace System.Management.Automation
{
internal class MergedCommandParameterMetadata
{
/// <summary>
/// Replaces any existing metadata in this object with the metadata specified.
///
/// Note that this method should NOT be called after a MergedCommandParameterMetadata
/// instance is made read only by calling MakeReadOnly(). This is because MakeReadOnly()
/// will turn 'bindableParameters', 'aliasedParameters' and 'parameterSetMap' into
/// ReadOnlyDictionary and ReadOnlyCollection.
/// </summary>
/// <param name="metadata">
/// The metadata to replace in this object.
/// </param>
/// <returns>
/// A list of the merged parameter metadata that was added.
/// </returns>
internal List<MergedCompiledCommandParameter> ReplaceMetadata(MergedCommandParameterMetadata metadata)
{
var result = new List<MergedCompiledCommandParameter>();
// Replace bindable parameters
_bindableParameters.Clear();
foreach (KeyValuePair<string, MergedCompiledCommandParameter> entry in metadata.BindableParameters)
{
_bindableParameters.Add(entry.Key, entry.Value);
result.Add(entry.Value);
}
_aliasedParameters.Clear();
foreach (KeyValuePair<string, MergedCompiledCommandParameter> entry in metadata.AliasedParameters)
{
_aliasedParameters.Add(entry.Key, entry.Value);
}
// Replace additional meta info
_defaultParameterSetName = metadata._defaultParameterSetName;
_nextAvailableParameterSetIndex = metadata._nextAvailableParameterSetIndex;
_parameterSetMap.Clear();
var parameterSetMapInList = (List<string>)_parameterSetMap;
parameterSetMapInList.AddRange(metadata._parameterSetMap);
Diagnostics.Assert(ParameterSetCount == _nextAvailableParameterSetIndex,
"After replacement with the metadata of the new parameters, ParameterSetCount should be equal to nextAvailableParameterSetIndex");
return result;
}
/// <summary>
/// Merges the specified metadata with the other metadata already defined
/// in this object.
/// </summary>
/// <param name="parameterMetadata">
/// The compiled metadata for the type to be merged.
/// </param>
/// <param name="binderAssociation">
/// The type of binder that the CommandProcessor will use to bind
/// the parameters for <paramref name="parameterMetadata"/>
/// </param>
/// <returns>
/// A collection of the merged parameter metadata that was added.
/// </returns>
/// <exception cref="MetadataException">
/// If a parameter name or alias described in the <paramref name="parameterMetadata"/> already
/// exists.
/// </exception>
internal Collection<MergedCompiledCommandParameter> AddMetadataForBinder(
InternalParameterMetadata parameterMetadata,
ParameterBinderAssociation binderAssociation)
{
if (parameterMetadata == null)
{
throw PSTraceSource.NewArgumentNullException("parameterMetadata");
}
Collection<MergedCompiledCommandParameter> result =
new Collection<MergedCompiledCommandParameter>();
// Merge in the bindable parameters
foreach (KeyValuePair<string, CompiledCommandParameter> bindableParameter in parameterMetadata.BindableParameters)
{
if (_bindableParameters.ContainsKey(bindableParameter.Key))
{
MetadataException exception =
new MetadataException(
"ParameterNameAlreadyExistsForCommand",
null,
Metadata.ParameterNameAlreadyExistsForCommand,
bindableParameter.Key);
throw exception;
}
// NTRAID#Windows Out Of Band Releases-926371-2005/12/27-JonN
if (_aliasedParameters.ContainsKey(bindableParameter.Key))
{
MetadataException exception =
new MetadataException(
"ParameterNameConflictsWithAlias",
null,
Metadata.ParameterNameConflictsWithAlias,
bindableParameter.Key,
RetrieveParameterNameForAlias(bindableParameter.Key, _aliasedParameters));
throw exception;
}
MergedCompiledCommandParameter mergedParameter =
new MergedCompiledCommandParameter(bindableParameter.Value, binderAssociation);
_bindableParameters.Add(bindableParameter.Key, mergedParameter);
result.Add(mergedParameter);
// Merge in the aliases
foreach (string aliasName in bindableParameter.Value.Aliases)
{
if (_aliasedParameters.ContainsKey(aliasName))
{
MetadataException exception =
new MetadataException(
"AliasParameterNameAlreadyExistsForCommand",
null,
Metadata.AliasParameterNameAlreadyExistsForCommand,
aliasName);
throw exception;
}
// NTRAID#Windows Out Of Band Releases-926371-2005/12/27-JonN
if (_bindableParameters.ContainsKey(aliasName))
{
MetadataException exception =
new MetadataException(
"ParameterNameConflictsWithAlias",
null,
Metadata.ParameterNameConflictsWithAlias,
RetrieveParameterNameForAlias(aliasName, _bindableParameters),
bindableParameter.Value.Name);
throw exception;
}
_aliasedParameters.Add(aliasName, mergedParameter);
}
}
return result;
}
/// <summary>
/// The next available parameter set bit. This number increments but the parameter
/// set bit is really 1 shifted left this number of times. This number also acts
/// as the index for the parameter set map.
/// </summary>
private uint _nextAvailableParameterSetIndex;
/// <summary>
/// Gets the number of parameter sets that were declared for the command.
/// </summary>
internal int ParameterSetCount
{
get
{
return _parameterSetMap.Count;
}
}
/// <summary>
/// Gets a bit-field representing all valid parameter sets.
/// </summary>
internal uint AllParameterSetFlags
{
get
{
return (1u << ParameterSetCount) - 1;
}
}
/// <summary>
/// This is the parameter set map. The index is the number of times 1 gets shifted
/// left to specify the bit field marker for the parameter set.
/// The value is the parameter set name.
/// New parameter sets are added at the nextAvailableParameterSetIndex.
/// </summary>
private IList<string> _parameterSetMap = new List<string>();
/// <summary>
/// The name of the default parameter set.
/// </summary>
private string _defaultParameterSetName;
/// <summary>
/// Adds the parameter set name to the parameter set map and returns the
/// index. If the parameter set name was already in the map, the index to
/// the existing parameter set name is returned.
/// </summary>
/// <param name="parameterSetName">
/// The name of the parameter set to add.
/// </param>
/// <returns>
/// The index of the parameter set name. If the name didn't already exist the
/// name gets added and the new index is returned. If the name already exists
/// the index of the existing name is returned.
/// </returns>
/// <remarks>
/// The nextAvailableParameterSetIndex is incremented if the parameter set name
/// is added.
/// </remarks>
/// <exception cref="ParsingMetadataException">
/// If more than uint.MaxValue parameter-sets are defined for the command.
/// </exception>
private int AddParameterSetToMap(string parameterSetName)
{
int index = -1;
if (!string.IsNullOrEmpty(parameterSetName))
{
index = _parameterSetMap.IndexOf(parameterSetName);
// A parameter set name should only be added once
if (index == -1)
{
if (_nextAvailableParameterSetIndex == uint.MaxValue)
{
// Don't let the parameter set index overflow
ParsingMetadataException parsingException =
new ParsingMetadataException(
"ParsingTooManyParameterSets",
null,
Metadata.ParsingTooManyParameterSets);
throw parsingException;
}
_parameterSetMap.Add(parameterSetName);
index = _parameterSetMap.IndexOf(parameterSetName);
Diagnostics.Assert(
index == _nextAvailableParameterSetIndex,
"AddParameterSetToMap should always add the parameter set name to the map at the nextAvailableParameterSetIndex");
_nextAvailableParameterSetIndex++;
}
}
return index;
}
/// <summary>
/// Loops through all the parameters and retrieves the parameter set names. In the process
/// it generates a mapping of parameter set names to the bits in the bit-field and sets
/// the parameter set flags for the parameter.
/// </summary>
/// <param name="defaultParameterSetName">
/// The default parameter set name.
/// </param>
/// <returns>
/// The bit flag for the default parameter set.
/// </returns>
/// <exception cref="ParsingMetadataException">
/// If more than uint.MaxValue parameter-sets are defined for the command.
/// </exception>
internal uint GenerateParameterSetMappingFromMetadata(string defaultParameterSetName)
{
// First clear the parameter set map
_parameterSetMap.Clear();
_nextAvailableParameterSetIndex = 0;
uint defaultParameterSetFlag = 0;
if (!string.IsNullOrEmpty(defaultParameterSetName))
{
_defaultParameterSetName = defaultParameterSetName;
// Add the default parameter set to the parameter set map
int index = AddParameterSetToMap(defaultParameterSetName);
defaultParameterSetFlag = (uint)1 << index;
}
// Loop through all the parameters and then each parameter set for each parameter
foreach (MergedCompiledCommandParameter parameter in BindableParameters.Values)
{
// For each parameter we need to generate a bit-field for the parameter sets
// that the parameter is a part of.
uint parameterSetBitField = 0;
foreach (var keyValuePair in parameter.Parameter.ParameterSetData)
{
var parameterSetName = keyValuePair.Key;
var parameterSetData = keyValuePair.Value;
if (string.Equals(parameterSetName, ParameterAttribute.AllParameterSets, StringComparison.OrdinalIgnoreCase))
{
// Don't add the parameter set name but assign the bit field zero and then mark the bool
parameterSetData.ParameterSetFlag = 0;
parameterSetData.IsInAllSets = true;
parameter.Parameter.IsInAllSets = true;
}
else
{
// Add the parameter set name and/or get the index in the map
int index = AddParameterSetToMap(parameterSetName);
Diagnostics.Assert(
index >= 0,
"AddParameterSetToMap should always be able to add the parameter set name, if not it should throw");
// Calculate the bit for this parameter set
uint parameterSetBit = (uint)1 << index;
// Add the bit to the bit-field
parameterSetBitField |= parameterSetBit;
// Add the bit to the parameter set specific data
parameterSetData.ParameterSetFlag = parameterSetBit;
}
}
// Set the bit field in the parameter
parameter.Parameter.ParameterSetFlags = parameterSetBitField;
}
return defaultParameterSetFlag;
}
/// <summary>
/// Gets the parameter set name for the specified parameter set.
/// </summary>
/// <param name="parameterSet">
/// The parameter set to get the name for.
/// </param>
/// <returns>
/// The name of the specified parameter set.
/// </returns>
internal string GetParameterSetName(uint parameterSet)
{
string result = _defaultParameterSetName;
if (string.IsNullOrEmpty(result))
{
result = ParameterAttribute.AllParameterSets;
}
if (parameterSet != uint.MaxValue && parameterSet != 0)
{
// Count the number of right shifts it takes to hit the parameter set
// This is the index into the parameter set map.
int index = 0;
while (((parameterSet >> index) & 0x1) == 0)
{
++index;
}
// Now check to see if there are any remaining sets passed this bit.
// If so return string.Empty
if (((parameterSet >> (index + 1)) & 0x1) == 0)
{
// Ensure that the bit found was within the map, if not return an empty string
if (index < _parameterSetMap.Count)
{
result = _parameterSetMap[index];
}
else
{
result = string.Empty;
}
}
else
{
result = string.Empty;
}
}
return result;
}
/// <summary>
/// Helper function to retrieve the name of the parameter
/// which defined an alias.
/// </summary>
/// <param name="key"></param>
/// <param name="dict"></param>
/// <returns></returns>
private static string RetrieveParameterNameForAlias(
string key,
IDictionary<string, MergedCompiledCommandParameter> dict)
{
MergedCompiledCommandParameter mergedParam = dict[key];
if (mergedParam != null)
{
CompiledCommandParameter compiledParam = mergedParam.Parameter;
if (compiledParam != null)
{
if (!string.IsNullOrEmpty(compiledParam.Name))
return compiledParam.Name;
}
}
return string.Empty;
}
/// <summary>
/// Gets the parameters by matching its name.
/// </summary>
/// <param name="name">
/// The name of the parameter.
/// </param>
/// <param name="throwOnParameterNotFound">
/// If true and a matching parameter is not found, an exception will be
/// throw. If false and a matching parameter is not found, null is returned.
/// </param>
/// <param name="tryExactMatching">
/// If true we do exact matching, otherwise we do not.
/// </param>
/// <param name="invocationInfo">
/// The invocation information about the code being run.
/// </param>
/// <returns>
/// The a collection of the metadata associated with the parameters that
/// match the specified name. If no matches were found, an empty collection
/// is returned.
/// </returns>
/// <exception cref="ArgumentException">
/// If <paramref name="name"/> is null or empty.
/// </exception>
internal MergedCompiledCommandParameter GetMatchingParameter(
string name,
bool throwOnParameterNotFound,
bool tryExactMatching,
InvocationInfo invocationInfo)
{
if (string.IsNullOrEmpty(name))
{
throw PSTraceSource.NewArgumentException("name");
}
Collection<MergedCompiledCommandParameter> matchingParameters =
new Collection<MergedCompiledCommandParameter>();
// Skip the leading '-' if present
if (name.Length > 0 && SpecialCharacters.IsDash(name[0]))
{
name = name.Substring(1);
}
// First try to match the bindable parameters
foreach (string parameterName in _bindableParameters.Keys)
{
if (CultureInfo.InvariantCulture.CompareInfo.IsPrefix(parameterName, name, CompareOptions.IgnoreCase))
{
// If it is an exact match then only return the exact match
// as the result
if (tryExactMatching && string.Equals(parameterName, name, StringComparison.OrdinalIgnoreCase))
{
return _bindableParameters[parameterName];
}
else
{
matchingParameters.Add(_bindableParameters[parameterName]);
}
}
}
// Now check the aliases
foreach (string parameterName in _aliasedParameters.Keys)
{
if (CultureInfo.InvariantCulture.CompareInfo.IsPrefix(parameterName, name, CompareOptions.IgnoreCase))
{
// If it is an exact match then only return the exact match
// as the result
if (tryExactMatching && string.Equals(parameterName, name, StringComparison.OrdinalIgnoreCase))
{
return _aliasedParameters[parameterName];
}
else
{
if (!matchingParameters.Contains(_aliasedParameters[parameterName]))
{
matchingParameters.Add(_aliasedParameters[parameterName]);
}
}
}
}
if (matchingParameters.Count > 1)
{
// Prefer parameters in the cmdlet over common parameters
Collection<MergedCompiledCommandParameter> filteredParameters =
new Collection<MergedCompiledCommandParameter>();
foreach (MergedCompiledCommandParameter matchingParameter in matchingParameters)
{
if ((matchingParameter.BinderAssociation == ParameterBinderAssociation.DeclaredFormalParameters) ||
(matchingParameter.BinderAssociation == ParameterBinderAssociation.DynamicParameters))
{
filteredParameters.Add(matchingParameter);
}
}
if (filteredParameters.Count == 1)
{
matchingParameters = filteredParameters;
}
else
{
StringBuilder possibleMatches = new StringBuilder();
foreach (MergedCompiledCommandParameter matchingParameter in matchingParameters)
{
possibleMatches.Append(" -");
possibleMatches.Append(matchingParameter.Parameter.Name);
}
ParameterBindingException exception =
new ParameterBindingException(
ErrorCategory.InvalidArgument,
invocationInfo,
null,
name,
null,
null,
ParameterBinderStrings.AmbiguousParameter,
"AmbiguousParameter",
possibleMatches);
throw exception;
}
}
else if (matchingParameters.Count == 0)
{
if (throwOnParameterNotFound)
{
ParameterBindingException exception =
new ParameterBindingException(
ErrorCategory.InvalidArgument,
invocationInfo,
null,
name,
null,
null,
ParameterBinderStrings.NamedParameterNotFound,
"NamedParameterNotFound");
throw exception;
}
}
MergedCompiledCommandParameter result = null;
if (matchingParameters.Count > 0)
{
result = matchingParameters[0];
}
return result;
}
/// <summary>
/// Gets a collection of all the parameters that are allowed in the parameter set.
/// </summary>
/// <param name="parameterSetFlag">
/// The bit representing the parameter set from which the parameters should be retrieved.
/// </param>
/// <returns>
/// A collection of all the parameters in the specified parameter set.
/// </returns>
internal Collection<MergedCompiledCommandParameter> GetParametersInParameterSet(uint parameterSetFlag)
{
Collection<MergedCompiledCommandParameter> result =
new Collection<MergedCompiledCommandParameter>();
foreach (MergedCompiledCommandParameter parameter in BindableParameters.Values)
{
if ((parameterSetFlag & parameter.Parameter.ParameterSetFlags) != 0 ||
parameter.Parameter.IsInAllSets)
{
result.Add(parameter);
}
}
return result;
}
/// <summary>
/// Gets a dictionary of the compiled parameter metadata for this Type.
/// The dictionary keys are the names of the parameters and
/// the values are the compiled parameter metadata.
/// </summary>
internal IDictionary<string, MergedCompiledCommandParameter> BindableParameters { get { return _bindableParameters; } }
private IDictionary<string, MergedCompiledCommandParameter> _bindableParameters =
new Dictionary<string, MergedCompiledCommandParameter>(StringComparer.OrdinalIgnoreCase);
/// <summary>
/// Gets a dictionary of the parameters that have been aliased to other names. The key is
/// the alias name and the value is the MergedCompiledCommandParameter metadata.
/// </summary>
internal IDictionary<string, MergedCompiledCommandParameter> AliasedParameters { get { return _aliasedParameters; } }
private IDictionary<string, MergedCompiledCommandParameter> _aliasedParameters =
new Dictionary<string, MergedCompiledCommandParameter>(StringComparer.OrdinalIgnoreCase);
internal void MakeReadOnly()
{
_bindableParameters = new ReadOnlyDictionary<string, MergedCompiledCommandParameter>(_bindableParameters);
_aliasedParameters = new ReadOnlyDictionary<string, MergedCompiledCommandParameter>(_aliasedParameters);
_parameterSetMap = new ReadOnlyCollection<string>(_parameterSetMap);
}
internal void ResetReadOnly()
{
_bindableParameters = new Dictionary<string, MergedCompiledCommandParameter>(_bindableParameters, StringComparer.OrdinalIgnoreCase);
_aliasedParameters = new Dictionary<string, MergedCompiledCommandParameter>(_aliasedParameters, StringComparer.OrdinalIgnoreCase);
}
}
/// <summary>
/// Makes an association between a CompiledCommandParameter and the type
/// of the parameter binder used to bind the parameter.
/// </summary>
internal class MergedCompiledCommandParameter
{
/// <summary>
/// Constructs an association between the CompiledCommandParameter and the
/// binder that should be used to bind it.
/// </summary>
/// <param name="parameter">
/// The metadata for a parameter.
/// </param>
/// <param name="binderAssociation">
/// The type of binder that should be used to bind the parameter.
/// </param>
internal MergedCompiledCommandParameter(
CompiledCommandParameter parameter,
ParameterBinderAssociation binderAssociation)
{
Diagnostics.Assert(parameter != null, "caller to verify parameter is not null");
this.Parameter = parameter;
this.BinderAssociation = binderAssociation;
}
/// <summary>
/// Gets the compiled command parameter for the association.
/// </summary>
internal CompiledCommandParameter Parameter { get; private set; }
/// <summary>
/// Gets the type of binder that the compiled command parameter should be bound with.
/// </summary>
internal ParameterBinderAssociation BinderAssociation { get; private set; }
public override string ToString()
{
return Parameter.ToString();
}
}
/// <summary>
/// This enum is used in the MergedCompiledCommandParameter class
/// to associate a particular CompiledCommandParameter with the
/// appropriate ParameterBinder.
/// </summary>
internal enum ParameterBinderAssociation
{
/// <summary>
/// The parameter was declared as a formal parameter in the command type.
/// </summary>
DeclaredFormalParameters,
/// <summary>
/// The parameter was declared as a dynamic parameter for the command.
/// </summary>
DynamicParameters,
/// <summary>
/// The parameter is a common parameter found in the CommonParameters class.
/// </summary>
CommonParameters,
/// <summary>
/// The parameter is a ShouldProcess parameter found in the ShouldProcessParameters class.
/// </summary>
ShouldProcessParameters,
/// <summary>
/// The parameter is a transactions parameter found in the TransactionParameters class.
/// </summary>
TransactionParameters,
/// <summary>
/// The parameter is a Paging parameter found in the PagingParameters class.
/// </summary>
PagingParameters,
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="TrayIcon.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Windows.Forms {
using System.Runtime.Remoting;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Diagnostics;
using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using System.Windows.Forms.Design;
using Microsoft.Win32;
using System.Drawing;
using System.Globalization;
/// <include file='doc\TrayIcon.uex' path='docs/doc[@for="NotifyIcon"]/*' />
/// <devdoc>
/// <para>
/// Specifies a component that creates
/// an icon in the Windows System Tray. This class cannot be inherited.
/// </para>
/// </devdoc>
[
DefaultProperty("Text"),
DefaultEvent("MouseDoubleClick"),
Designer("System.Windows.Forms.Design.NotifyIconDesigner, " + AssemblyRef.SystemDesign),
ToolboxItemFilter("System.Windows.Forms"),
SRDescription(SR.DescriptionNotifyIcon)
]
public sealed class NotifyIcon : Component {
private static readonly object EVENT_MOUSEDOWN = new object();
private static readonly object EVENT_MOUSEMOVE = new object();
private static readonly object EVENT_MOUSEUP = new object();
private static readonly object EVENT_CLICK = new object();
private static readonly object EVENT_DOUBLECLICK = new object();
private static readonly object EVENT_MOUSECLICK = new object();
private static readonly object EVENT_MOUSEDOUBLECLICK = new object();
private static readonly object EVENT_BALLOONTIPSHOWN = new object();
private static readonly object EVENT_BALLOONTIPCLICKED = new object();
private static readonly object EVENT_BALLOONTIPCLOSED = new object();
private const int WM_TRAYMOUSEMESSAGE = NativeMethods.WM_USER + 1024;
private static int WM_TASKBARCREATED = SafeNativeMethods.RegisterWindowMessage("TaskbarCreated");
private object syncObj = new object();
private Icon icon = null;
private string text = "";
private int id = 0;
private bool added = false;
private NotifyIconNativeWindow window = null;
private ContextMenu contextMenu = null;
private ContextMenuStrip contextMenuStrip = null;
private ToolTipIcon balloonTipIcon;
private string balloonTipText = "";
private string balloonTipTitle = "";
private static int nextId = 0;
private object userData;
private bool doubleClick = false; // checks if doubleclick is fired
// Visible defaults to false, but the NotifyIconDesigner makes it seem like the default is
// true. We do this because while visible is the more common case, if it was a true default,
// there would be no way to create a hidden NotifyIcon without being visible for a moment.
private bool visible = false;
/// <include file='doc\TrayIcon.uex' path='docs/doc[@for="NotifyIcon.NotifyIcon"]/*' />
/// <devdoc>
/// <para>
/// Initializes a new instance of the <see cref='System.Windows.Forms.NotifyIcon'/> class.
/// </para>
/// </devdoc>
public NotifyIcon() {
id = ++nextId;
window = new NotifyIconNativeWindow(this);
UpdateIcon(visible);
}
/// <include file='doc\TrayIcon.uex' path='docs/doc[@for="NotifyIcon.NotifyIcon1"]/*' />
/// <devdoc>
/// <para>
/// Initializes a new instance of the <see cref='System.Windows.Forms.NotifyIcon'/> class.
/// </para>
/// </devdoc>
public NotifyIcon(IContainer container) : this() {
if (container == null) {
throw new ArgumentNullException("container");
}
container.Add(this);
}
/// <include file='doc\TrayIcon.uex' path='docs/doc[@for="NotifyIcon.BalloonTipText"]/*' />
/// <devdoc>
/// <para>
/// Gets or sets the BalloonTip text displayed when
/// the mouse hovers over a system tray icon.
/// </para>
/// </devdoc>
[
SRCategory(SR.CatAppearance),
Localizable(true),
DefaultValue(""),
SRDescription(SR.NotifyIconBalloonTipTextDescr),
Editor("System.ComponentModel.Design.MultilineStringEditor, " + AssemblyRef.SystemDesign, typeof(System.Drawing.Design.UITypeEditor))
]
public string BalloonTipText {
get {
return balloonTipText;
}
set {
if (value != balloonTipText) {
balloonTipText = value;
}
}
}
/// <include file='doc\TrayIcon.uex' path='docs/doc[@for="NotifyIcon.BalloonTipIcon"]/*' />
/// <devdoc>
/// <para>
/// Gets or sets the BalloonTip icon displayed when
/// the mouse hovers over a system tray icon.
/// </para>
/// </devdoc>
[
SRCategory(SR.CatAppearance),
DefaultValue(ToolTipIcon.None),
SRDescription(SR.NotifyIconBalloonTipIconDescr)
]
public ToolTipIcon BalloonTipIcon {
get {
return balloonTipIcon;
}
set {
//valid values are 0x0 to 0x3
if (!ClientUtils.IsEnumValid(value, (int)value, (int)ToolTipIcon.None, (int)ToolTipIcon.Error)){
throw new InvalidEnumArgumentException("value", (int)value, typeof(ToolTipIcon));
}
if (value != balloonTipIcon) {
balloonTipIcon = value;
}
}
}
/// <include file='doc\TrayIcon.uex' path='docs/doc[@for="NotifyIcon.BalloonTipTitle"]/*' />
/// <devdoc>
/// <para>
/// Gets or sets the BalloonTip title displayed when
/// the mouse hovers over a system tray icon.
/// </para>
/// </devdoc>
[
SRCategory(SR.CatAppearance),
Localizable(true),
DefaultValue(""),
SRDescription(SR.NotifyIconBalloonTipTitleDescr)
]
public string BalloonTipTitle {
get {
return balloonTipTitle;
}
set {
if (value != balloonTipTitle) {
balloonTipTitle = value;
}
}
}
/// <include file='doc\NotifyIcon.uex' path='docs/doc[@for="NotifyIcon.BalloonTipClicked"]/*' />
/// <devdoc>
/// <para>[This event is raised on the NIN_BALLOONUSERCLICK message.]</para>
/// </devdoc>
[SRCategory(SR.CatAction), SRDescription(SR.NotifyIconOnBalloonTipClickedDescr)]
public event EventHandler BalloonTipClicked {
add {
Events.AddHandler(EVENT_BALLOONTIPCLICKED, value);
}
remove {
Events.RemoveHandler(EVENT_BALLOONTIPCLICKED, value);
}
}
/// <include file='doc\NotifyIcon.uex' path='docs/doc[@for="NotifyIcon.BalloonTipClosed"]/*' />
/// <devdoc>
/// <para>[This event is raised on the NIN_BALLOONTIMEOUT message.]</para>
/// </devdoc>
[SRCategory(SR.CatAction), SRDescription(SR.NotifyIconOnBalloonTipClosedDescr)]
public event EventHandler BalloonTipClosed {
add {
Events.AddHandler(EVENT_BALLOONTIPCLOSED, value);
}
remove {
Events.RemoveHandler(EVENT_BALLOONTIPCLOSED, value);
}
}
/// <include file='doc\NotifyIcon.uex' path='docs/doc[@for="NotifyIcon.BalloonTipShown"]/*' />
/// <devdoc>
/// <para>[This event is raised on the NIN_BALLOONSHOW or NIN_BALLOONHIDE message.]</para>
/// </devdoc>
[SRCategory(SR.CatAction), SRDescription(SR.NotifyIconOnBalloonTipShownDescr)]
public event EventHandler BalloonTipShown {
add {
Events.AddHandler(EVENT_BALLOONTIPSHOWN, value);
}
remove {
Events.RemoveHandler(EVENT_BALLOONTIPSHOWN, value);
}
}
/// <include file='doc\TrayIcon.uex' path='docs/doc[@for="NotifyIcon.ContextMenu"]/*' />
/// <devdoc>
/// <para>
/// Gets or sets context menu
/// for the tray icon.
/// </para>
/// </devdoc>
[
Browsable(false),
DefaultValue(null),
SRCategory(SR.CatBehavior),
SRDescription(SR.NotifyIconMenuDescr)
]
public ContextMenu ContextMenu {
get {
return contextMenu;
}
set {
this.contextMenu = value;
}
}
[
DefaultValue(null),
SRCategory(SR.CatBehavior),
SRDescription(SR.NotifyIconMenuDescr)
]
public ContextMenuStrip ContextMenuStrip {
get {
return contextMenuStrip;
}
set {
this.contextMenuStrip = value;
}
}
/// <include file='doc\TrayIcon.uex' path='docs/doc[@for="NotifyIcon.Icon"]/*' />
/// <devdoc>
/// <para>
/// Gets or sets the current
/// icon.
/// </para>
/// </devdoc>
[
SRCategory(SR.CatAppearance),
Localizable(true),
DefaultValue(null),
SRDescription(SR.NotifyIconIconDescr)
]
public Icon Icon {
get {
return icon;
}
set {
if (icon != value) {
this.icon = value;
UpdateIcon(visible);
}
}
}
/// <include file='doc\TrayIcon.uex' path='docs/doc[@for="NotifyIcon.Text"]/*' />
/// <devdoc>
/// <para>
/// Gets or sets the ToolTip text displayed when
/// the mouse hovers over a system tray icon.
/// </para>
/// </devdoc>
[
SRCategory(SR.CatAppearance),
Localizable(true),
DefaultValue(""),
SRDescription(SR.NotifyIconTextDescr),
Editor("System.ComponentModel.Design.MultilineStringEditor, " + AssemblyRef.SystemDesign, typeof(System.Drawing.Design.UITypeEditor))
]
public string Text {
get {
return text;
}
set {
if (value == null) value = "";
if (value != null && !value.Equals(this.text)) {
if (value != null && value.Length > 63) {
throw new ArgumentOutOfRangeException("Text", value, SR.GetString(SR.TrayIcon_TextTooLong));
}
this.text = value;
if (added) {
UpdateIcon(true);
}
}
}
}
/// <include file='doc\TrayIcon.uex' path='docs/doc[@for="NotifyIcon.Visible"]/*' />
/// <devdoc>
/// <para>
/// Gets or sets a value indicating whether the icon is visible in the Windows System Tray.
/// </para>
/// </devdoc>
[
SRCategory(SR.CatBehavior),
Localizable(true),
DefaultValue(false),
SRDescription(SR.NotifyIconVisDescr)
]
public bool Visible {
get {
return visible;
}
set {
if (visible != value) {
UpdateIcon(value);
visible = value;
}
}
}
/// <include file='doc\TrayIcon.uex' path='docs/doc[@for="TrayIcon.Tag"]/*' />
[
SRCategory(SR.CatData),
Localizable(false),
Bindable(true),
SRDescription(SR.ControlTagDescr),
DefaultValue(null),
TypeConverter(typeof(StringConverter)),
]
public object Tag {
get {
return userData;
}
set {
userData = value;
}
}
/// <include file='doc\TrayIcon.uex' path='docs/doc[@for="NotifyIcon.Click"]/*' />
/// <devdoc>
/// Occurs when the user clicks the icon in the system tray.
/// </devdoc>
[SRCategory(SR.CatAction), SRDescription(SR.ControlOnClickDescr)]
public event EventHandler Click {
add {
Events.AddHandler(EVENT_CLICK, value);
}
remove {
Events.RemoveHandler(EVENT_CLICK, value);
}
}
/// <include file='doc\TrayIcon.uex' path='docs/doc[@for="NotifyIcon.DoubleClick"]/*' />
/// <devdoc>
/// Occurs when the user double-clicks the icon in the system tray.
/// </devdoc>
[SRCategory(SR.CatAction), SRDescription(SR.ControlOnDoubleClickDescr)]
public event EventHandler DoubleClick {
add {
Events.AddHandler(EVENT_DOUBLECLICK, value);
}
remove {
Events.RemoveHandler(EVENT_DOUBLECLICK, value);
}
}
/// <include file='doc\TrayIcon.uex' path='docs/doc[@for="NotifyIcon.MouseClick"]/*' />
/// <devdoc>
/// Occurs when the user clicks the icon in the system tray.
/// </devdoc>
[SRCategory(SR.CatAction), SRDescription(SR.NotifyIconMouseClickDescr)]
public event MouseEventHandler MouseClick {
add {
Events.AddHandler(EVENT_MOUSECLICK, value);
}
remove {
Events.RemoveHandler(EVENT_MOUSECLICK, value);
}
}
/// <include file='doc\TrayIcon.uex' path='docs/doc[@for="NotifyIcon.MouseDoubleClick"]/*' />
/// <devdoc>
/// Occurs when the user mouse double clicks the icon in the system tray.
/// </devdoc>
[SRCategory(SR.CatAction), SRDescription(SR.NotifyIconMouseDoubleClickDescr)]
public event MouseEventHandler MouseDoubleClick {
add {
Events.AddHandler(EVENT_MOUSEDOUBLECLICK, value);
}
remove {
Events.RemoveHandler(EVENT_MOUSEDOUBLECLICK, value);
}
}
/// <include file='doc\TrayIcon.uex' path='docs/doc[@for="NotifyIcon.MouseDown"]/*' />
/// <devdoc>
/// <para>
/// Occurs when the
/// user presses a mouse button while the pointer is over the icon in the system tray.
/// </para>
/// </devdoc>
[SRCategory(SR.CatMouse), SRDescription(SR.ControlOnMouseDownDescr)]
public event MouseEventHandler MouseDown {
add {
Events.AddHandler(EVENT_MOUSEDOWN, value);
}
remove {
Events.RemoveHandler(EVENT_MOUSEDOWN, value);
}
}
/// <include file='doc\TrayIcon.uex' path='docs/doc[@for="NotifyIcon.MouseMove"]/*' />
/// <devdoc>
/// <para>
/// Occurs
/// when the user moves the mouse pointer over the icon in the system tray.
/// </para>
/// </devdoc>
[SRCategory(SR.CatMouse), SRDescription(SR.ControlOnMouseMoveDescr)]
public event MouseEventHandler MouseMove {
add {
Events.AddHandler(EVENT_MOUSEMOVE, value);
}
remove {
Events.RemoveHandler(EVENT_MOUSEMOVE, value);
}
}
/// <include file='doc\TrayIcon.uex' path='docs/doc[@for="NotifyIcon.MouseUp"]/*' />
/// <devdoc>
/// <para>
/// Occurs when the
/// user releases the mouse button while the pointer
/// is over the icon in the system tray.
/// </para>
/// </devdoc>
[SRCategory(SR.CatMouse), SRDescription(SR.ControlOnMouseUpDescr)]
public event MouseEventHandler MouseUp {
add {
Events.AddHandler(EVENT_MOUSEUP, value);
}
remove {
Events.RemoveHandler(EVENT_MOUSEUP, value);
}
}
/// <include file='doc\TrayIcon.uex' path='docs/doc[@for="NotifyIcon.Dispose"]/*' />
/// <devdoc>
/// <para>
/// Disposes of the resources (other than memory) used by the
/// <see cref='System.Windows.Forms.NotifyIcon'/>.
/// </para>
/// </devdoc>
protected override void Dispose(bool disposing) {
if (disposing) {
if (window != null) {
this.icon = null;
this.Text = String.Empty;
UpdateIcon(false);
window.DestroyHandle();
window = null;
contextMenu = null;
contextMenuStrip = null;
}
}
else {
// This same post is done in ControlNativeWindow's finalize method, so if you change
// it, change it there too.
//
if (window != null && window.Handle != IntPtr.Zero) {
UnsafeNativeMethods.PostMessage(new HandleRef(window, window.Handle), NativeMethods.WM_CLOSE, 0, 0);
window.ReleaseHandle();
}
}
base.Dispose(disposing);
}
/// <include file='doc\TrayIcon.uex' path='docs/doc[@for="NotifyIcon.BalloonTipClicked"]/*' />
/// <devdoc>
/// <para>
/// This method raised the BalloonTipClicked event.
/// </para>
/// </devdoc>
private void OnBalloonTipClicked() {
EventHandler handler = (EventHandler)Events[EVENT_BALLOONTIPCLICKED];
if (handler != null) {
handler(this, EventArgs.Empty);
}
}
/// <include file='doc\TrayIcon.uex' path='docs/doc[@for="NotifyIcon.OnBalloonTipClosed"]/*' />
/// <devdoc>
/// <para>
/// This method raised the BalloonTipClosed event.
/// </para>
/// </devdoc>
private void OnBalloonTipClosed() {
EventHandler handler = (EventHandler)Events[EVENT_BALLOONTIPCLOSED];
if (handler != null) {
handler(this, EventArgs.Empty);
}
}
/// <include file='doc\TrayIcon.uex' path='docs/doc[@for="NotifyIcon.OnBalloonTipShown"]/*' />
/// <devdoc>
/// <para>
/// This method raised the BalloonTipShown event.
/// </para>
/// </devdoc>
private void OnBalloonTipShown() {
EventHandler handler = (EventHandler)Events[EVENT_BALLOONTIPSHOWN];
if (handler != null) {
handler(this, EventArgs.Empty);
}
}
/// <include file='doc\TrayIcon.uex' path='docs/doc[@for="NotifyIcon.OnClick"]/*' />
/// <devdoc>
/// <para>
/// This method actually raises the Click event. Inheriting classes should
/// override this if they wish to be notified of a Click event. (This is far
/// preferable to actually adding an event handler.) They should not,
/// however, forget to call base.onClick(e); before exiting, to ensure that
/// other recipients do actually get the event.
/// </para>
/// </devdoc>
private void OnClick(EventArgs e) {
EventHandler handler = (EventHandler) Events[ EVENT_CLICK ];
if (handler != null)
handler( this, e );
}
/// <include file='doc\TrayIcon.uex' path='docs/doc[@for="NotifyIcon.OnDoubleClick"]/*' />
/// <devdoc>
/// Inheriting classes should override this method to handle this event.
/// Call base.onDoubleClick to send this event to any registered event listeners.
/// </devdoc>
private void OnDoubleClick(EventArgs e) {
EventHandler handler = (EventHandler) Events[ EVENT_DOUBLECLICK ];
if (handler != null)
handler( this, e );
}
/// <include file='doc\TrayIcon.uex' path='docs/doc[@for="NotifyIcon.OnMouseClick"]/*' />
/// <devdoc>
/// Inheriting classes should override this method to handle this event.
/// Call base.OnMouseClick to send this event to any registered event listeners.
/// </devdoc>
private void OnMouseClick(MouseEventArgs mea) {
MouseEventHandler handler = (MouseEventHandler) Events[ EVENT_MOUSECLICK ];
if (handler != null)
handler( this, mea );
}
/// <include file='doc\TrayIcon.uex' path='docs/doc[@for="NotifyIcon.OnMouseDoubleClick"]/*' />
/// <devdoc>
/// Inheriting classes should override this method to handle this event.
/// Call base.OnMouseDoubleClick to send this event to any registered event listeners.
/// </devdoc>
private void OnMouseDoubleClick(MouseEventArgs mea) {
MouseEventHandler handler = (MouseEventHandler) Events[ EVENT_MOUSEDOUBLECLICK ];
if (handler != null)
handler( this, mea );
}
/// <include file='doc\TrayIcon.uex' path='docs/doc[@for="NotifyIcon.OnMouseDown"]/*' />
/// <devdoc>
/// <para>
/// Raises the <see cref='System.Windows.Forms.NotifyIcon.MouseDown'/> event.
/// Inheriting classes should override this method to handle this event.
/// Call base.onMouseDown to send this event to any registered event listeners.
///
/// </para>
/// </devdoc>
private void OnMouseDown(MouseEventArgs e) {
MouseEventHandler handler = (MouseEventHandler)Events[EVENT_MOUSEDOWN];
if (handler != null)
handler(this, e);
}
/// <include file='doc\TrayIcon.uex' path='docs/doc[@for="NotifyIcon.OnMouseMove"]/*' />
/// <devdoc>
/// <para>
/// Inheriting classes should override this method to handle this event.
/// Call base.onMouseMove to send this event to any registered event listeners.
///
/// </para>
/// </devdoc>
private void OnMouseMove(MouseEventArgs e) {
MouseEventHandler handler = (MouseEventHandler)Events[EVENT_MOUSEMOVE];
if (handler != null)
handler(this, e);
}
/// <include file='doc\TrayIcon.uex' path='docs/doc[@for="NotifyIcon.OnMouseUp"]/*' />
/// <devdoc>
/// <para>
/// Inheriting classes should override this method to handle this event.
/// Call base.onMouseUp to send this event to any registered event listeners.
/// </para>
/// </devdoc>
private void OnMouseUp(MouseEventArgs e) {
MouseEventHandler handler = (MouseEventHandler)Events[EVENT_MOUSEUP];
if (handler != null)
handler(this, e);
}
/// <include file='doc\TrayIcon.uex' path='docs/doc[@for="NotifyIcon.ShowBalloonTip"]/*' />
/// <devdoc>
/// <para>
/// Displays a balloon tooltip in the taskbar.
///
/// The system enforces minimum and maximum timeout values. Timeout
/// values that are too large are set to the maximum value and values
/// that are too small default to the minimum value. The operating system's
/// default minimum and maximum timeout values are 10 seconds and 30 seconds,
/// respectively.
///
/// No more than one balloon ToolTip at at time is displayed for the taskbar.
/// If an application attempts to display a ToolTip when one is already being displayed,
/// the ToolTip will not appear until the existing balloon ToolTip has been visible for at
/// least the system minimum timeout value. For example, a balloon ToolTip with timeout
/// set to 30 seconds has been visible for seven seconds when another application attempts
/// to display a balloon ToolTip. If the system minimum timeout is ten seconds, the first
/// ToolTip displays for an additional three seconds before being replaced by the second ToolTip.
/// </para>
/// </devdoc>
public void ShowBalloonTip(int timeout) {
ShowBalloonTip(timeout, this.balloonTipTitle, this.balloonTipText, this.balloonTipIcon);
}
/// <include file='doc\TrayIcon.uex' path='docs/doc[@for="NotifyIcon.ShowBalloonTip"]/*' />
/// <devdoc>
/// <para>
/// Displays a balloon tooltip in the taskbar with the specified title,
/// text, and icon for a duration of the specified timeout value.
///
/// The system enforces minimum and maximum timeout values. Timeout
/// values that are too large are set to the maximum value and values
/// that are too small default to the minimum value. The operating system's
/// default minimum and maximum timeout values are 10 seconds and 30 seconds,
/// respectively.
///
/// No more than one balloon ToolTip at at time is displayed for the taskbar.
/// If an application attempts to display a ToolTip when one is already being displayed,
/// the ToolTip will not appear until the existing balloon ToolTip has been visible for at
/// least the system minimum timeout value. For example, a balloon ToolTip with timeout
/// set to 30 seconds has been visible for seven seconds when another application attempts
/// to display a balloon ToolTip. If the system minimum timeout is ten seconds, the first
/// ToolTip displays for an additional three seconds before being replaced by the second ToolTip.
/// </para>
/// </devdoc>
public void ShowBalloonTip(int timeout, string tipTitle, string tipText, ToolTipIcon tipIcon) {
if (timeout < 0) {
throw new ArgumentOutOfRangeException("timeout", SR.GetString(SR.InvalidArgument, "timeout", (timeout).ToString(CultureInfo.CurrentCulture)));
}
if (string.IsNullOrEmpty(tipText))
{
throw new ArgumentException(SR.GetString(SR.NotifyIconEmptyOrNullTipText));
}
//valid values are 0x0 to 0x3
if (!ClientUtils.IsEnumValid(tipIcon, (int)tipIcon, (int)ToolTipIcon.None, (int)ToolTipIcon.Error)){
throw new InvalidEnumArgumentException("tipIcon", (int)tipIcon, typeof(ToolTipIcon));
}
if (added ) {
// Bail if in design mode...
if (DesignMode) {
return;
}
IntSecurity.UnrestrictedWindows.Demand();
NativeMethods.NOTIFYICONDATA data = new NativeMethods.NOTIFYICONDATA();
if (window.Handle == IntPtr.Zero) {
window.CreateHandle(new CreateParams());
}
data.hWnd = window.Handle;
data.uID = id;
data.uFlags = NativeMethods.NIF_INFO;
data.uTimeoutOrVersion = timeout;
data.szInfoTitle = tipTitle;
data.szInfo = tipText;
switch (tipIcon) {
case ToolTipIcon.Info: data.dwInfoFlags = NativeMethods.NIIF_INFO; break;
case ToolTipIcon.Warning: data.dwInfoFlags = NativeMethods.NIIF_WARNING; break;
case ToolTipIcon.Error: data.dwInfoFlags = NativeMethods.NIIF_ERROR; break;
case ToolTipIcon.None: data.dwInfoFlags = NativeMethods.NIIF_NONE; break;
}
UnsafeNativeMethods.Shell_NotifyIcon(NativeMethods.NIM_MODIFY, data);
}
}
/// <include file='doc\TrayIcon.uex' path='docs/doc[@for="NotifyIcon.ShowContextMenu"]/*' />
/// <devdoc>
/// Shows the context menu for the tray icon.
/// </devdoc>
/// <internalonly/>
private void ShowContextMenu() {
if (contextMenu != null || contextMenuStrip != null) {
NativeMethods.POINT pt = new NativeMethods.POINT();
UnsafeNativeMethods.GetCursorPos(pt);
// VS7 #38994
// The solution to this problem was found in MSDN Article ID: Q135788.
// Summary: the current window must be made the foreground window
// before calling TrackPopupMenuEx, and a task switch must be
// forced after the call.
UnsafeNativeMethods.SetForegroundWindow(new HandleRef(window, window.Handle));
if (contextMenu != null) {
contextMenu.OnPopup( EventArgs.Empty );
SafeNativeMethods.TrackPopupMenuEx(new HandleRef(contextMenu, contextMenu.Handle),
NativeMethods.TPM_VERTICAL | NativeMethods.TPM_RIGHTALIGN,
pt.x,
pt.y,
new HandleRef(window, window.Handle),
null);
// Force task switch (see above)
UnsafeNativeMethods.PostMessage(new HandleRef(window, window.Handle), NativeMethods.WM_NULL, IntPtr.Zero, IntPtr.Zero);
}
else if (contextMenuStrip != null) {
// this will set the context menu strip to be toplevel
// and will allow us to overlap the system tray
contextMenuStrip.ShowInTaskbar(pt.x, pt.y);
}
}
}
/// <include file='doc\TrayIcon.uex' path='docs/doc[@for="NotifyIcon.UpdateIcon"]/*' />
/// <devdoc>
/// Updates the icon in the system tray.
/// </devdoc>
/// <internalonly/>
private void UpdateIcon(bool showIconInTray) {
lock(syncObj) {
// Bail if in design mode...
//
if (DesignMode) {
return;
}
IntSecurity.UnrestrictedWindows.Demand();
window.LockReference(showIconInTray);
NativeMethods.NOTIFYICONDATA data = new NativeMethods.NOTIFYICONDATA();
data.uCallbackMessage = WM_TRAYMOUSEMESSAGE;
data.uFlags = NativeMethods.NIF_MESSAGE;
if (showIconInTray) {
if (window.Handle == IntPtr.Zero) {
window.CreateHandle(new CreateParams());
}
}
data.hWnd = window.Handle;
data.uID = id;
data.hIcon = IntPtr.Zero;
data.szTip = null;
if (icon != null) {
data.uFlags |= NativeMethods.NIF_ICON;
data.hIcon = icon.Handle;
}
data.uFlags |= NativeMethods.NIF_TIP;
data.szTip = text;
if (showIconInTray && icon != null) {
if (!added) {
UnsafeNativeMethods.Shell_NotifyIcon(NativeMethods.NIM_ADD, data);
added = true;
}
else {
UnsafeNativeMethods.Shell_NotifyIcon(NativeMethods.NIM_MODIFY, data);
}
}
else if (added) {
UnsafeNativeMethods.Shell_NotifyIcon(NativeMethods.NIM_DELETE, data);
added = false;
}
}
}
/// <include file='doc\TrayIcon.uex' path='docs/doc[@for="NotifyIcon.WmMouseDown"]/*' />
/// <devdoc>
/// Handles the mouse-down event
/// </devdoc>
/// <internalonly/>
private void WmMouseDown(ref Message m, MouseButtons button, int clicks) {
if (clicks == 2) {
OnDoubleClick(new MouseEventArgs(button, 2, 0, 0, 0));
OnMouseDoubleClick(new MouseEventArgs(button, 2, 0, 0, 0));
doubleClick = true;
}
OnMouseDown(new MouseEventArgs(button, clicks, 0, 0, 0));
}
/// <include file='doc\TrayIcon.uex' path='docs/doc[@for="NotifyIcon.WmMouseMove"]/*' />
/// <devdoc>
/// Handles the mouse-move event
/// </devdoc>
/// <internalonly/>
private void WmMouseMove(ref Message m) {
OnMouseMove(new MouseEventArgs(Control.MouseButtons, 0, 0, 0, 0));
}
/// <include file='doc\TrayIcon.uex' path='docs/doc[@for="NotifyIcon.WmMouseUp"]/*' />
/// <devdoc>
/// Handles the mouse-up event
/// </devdoc>
/// <internalonly/>
private void WmMouseUp(ref Message m, MouseButtons button) {
OnMouseUp(new MouseEventArgs(button, 0, 0, 0, 0));
//subhag
if(!doubleClick) {
OnClick(new MouseEventArgs(button, 0, 0, 0, 0));
OnMouseClick(new MouseEventArgs(button, 0, 0, 0, 0));
}
doubleClick = false;
}
private void WmTaskbarCreated(ref Message m) {
added = false;
UpdateIcon(visible);
}
private void WndProc(ref Message msg) {
switch (msg.Msg) {
case WM_TRAYMOUSEMESSAGE:
switch ((int)msg.LParam) {
case NativeMethods.WM_LBUTTONDBLCLK:
WmMouseDown(ref msg, MouseButtons.Left, 2);
break;
case NativeMethods.WM_LBUTTONDOWN:
WmMouseDown(ref msg, MouseButtons.Left, 1);
break;
case NativeMethods.WM_LBUTTONUP:
WmMouseUp(ref msg, MouseButtons.Left);
break;
case NativeMethods.WM_MBUTTONDBLCLK:
WmMouseDown(ref msg, MouseButtons.Middle, 2);
break;
case NativeMethods.WM_MBUTTONDOWN:
WmMouseDown(ref msg, MouseButtons.Middle, 1);
break;
case NativeMethods.WM_MBUTTONUP:
WmMouseUp(ref msg, MouseButtons.Middle);
break;
case NativeMethods.WM_MOUSEMOVE:
WmMouseMove(ref msg);
break;
case NativeMethods.WM_RBUTTONDBLCLK:
WmMouseDown(ref msg, MouseButtons.Right, 2);
break;
case NativeMethods.WM_RBUTTONDOWN:
WmMouseDown(ref msg, MouseButtons.Right, 1);
break;
case NativeMethods.WM_RBUTTONUP:
if (contextMenu != null || contextMenuStrip != null) {
ShowContextMenu();
}
WmMouseUp(ref msg, MouseButtons.Right);
break;
case NativeMethods.NIN_BALLOONSHOW:
OnBalloonTipShown();
break;
case NativeMethods.NIN_BALLOONHIDE:
OnBalloonTipClosed();
break;
case NativeMethods.NIN_BALLOONTIMEOUT:
OnBalloonTipClosed();
break;
case NativeMethods.NIN_BALLOONUSERCLICK:
OnBalloonTipClicked();
break;
}
break;
case NativeMethods.WM_COMMAND:
if (IntPtr.Zero == msg.LParam) {
if (Command.DispatchID((int)msg.WParam & 0xFFFF)) return;
}
else {
window.DefWndProc(ref msg);
}
break;
case NativeMethods.WM_DRAWITEM:
// If the wparam is zero, then the message was sent by a menu.
// See WM_DRAWITEM in MSDN.
if (msg.WParam == IntPtr.Zero) {
WmDrawItemMenuItem(ref msg);
}
break;
case NativeMethods.WM_MEASUREITEM:
// If the wparam is zero, then the message was sent by a menu.
if (msg.WParam == IntPtr.Zero) {
WmMeasureMenuItem(ref msg);
}
break;
case NativeMethods.WM_INITMENUPOPUP:
WmInitMenuPopup(ref msg);
break;
case NativeMethods.WM_DESTROY:
// Remove the icon from the taskbar
UpdateIcon(false);
break;
default:
if (msg.Msg == WM_TASKBARCREATED) {
WmTaskbarCreated(ref msg);
}
window.DefWndProc(ref msg);
break;
}
}
private void WmInitMenuPopup(ref Message m) {
if (contextMenu != null) {
if (contextMenu.ProcessInitMenuPopup(m.WParam)) {
return;
}
}
window.DefWndProc(ref m);
}
private void WmMeasureMenuItem(ref Message m) {
// Obtain the menu item object
NativeMethods.MEASUREITEMSTRUCT mis = (NativeMethods.MEASUREITEMSTRUCT)m.GetLParam(typeof(NativeMethods.MEASUREITEMSTRUCT));
Debug.Assert(m.LParam != IntPtr.Zero, "m.lparam is null");
// A pointer to the correct MenuItem is stored in the measure item
// information sent with the message.
// (See MenuItem.CreateMenuItemInfo)
MenuItem menuItem = MenuItem.GetMenuItemFromItemData(mis.itemData);
Debug.Assert(menuItem != null, "UniqueID is not associated with a menu item");
// Delegate this message to the menu item
if (menuItem != null) {
menuItem.WmMeasureItem(ref m);
}
}
private void WmDrawItemMenuItem(ref Message m) {
// Obtain the menu item object
NativeMethods.DRAWITEMSTRUCT dis = (NativeMethods.DRAWITEMSTRUCT)m.GetLParam(typeof(NativeMethods.DRAWITEMSTRUCT));
// A pointer to the correct MenuItem is stored in the draw item
// information sent with the message.
// (See MenuItem.CreateMenuItemInfo)
MenuItem menuItem = MenuItem.GetMenuItemFromItemData(dis.itemData);
// Delegate this message to the menu item
if (menuItem != null) {
menuItem.WmDrawItem(ref m);
}
}
/// <include file='doc\TrayIcon.uex' path='docs/doc[@for="NotifyIcon.NotifyIconNativeWindow"]/*' />
/// <devdoc>
/// Defines a placeholder window that the NotifyIcon is attached to.
/// </devdoc>
/// <internalonly/>
private class NotifyIconNativeWindow : NativeWindow {
internal NotifyIcon reference;
private GCHandle rootRef; // We will root the control when we do not want to be elligible for garbage collection.
/// <include file='doc\TrayIcon.uex' path='docs/doc[@for="NotifyIcon.NotifyIconNativeWindow.NotifyIconNativeWindow"]/*' />
/// <devdoc>
/// Create a new NotifyIcon, and bind the window to the NotifyIcon component.
/// </devdoc>
/// <internalonly/>
internal NotifyIconNativeWindow(NotifyIcon component) {
reference = component;
}
~NotifyIconNativeWindow() {
// This same post is done in Control's Dispose method, so if you change
// it, change it there too.
//
if (Handle != IntPtr.Zero) {
UnsafeNativeMethods.PostMessage(new HandleRef(this, Handle), NativeMethods.WM_CLOSE, 0, 0);
}
// This releases the handle from our window proc, re-routing it back to
// the system.
}
public void LockReference(bool locked) {
if (locked) {
if (!rootRef.IsAllocated) {
rootRef = GCHandle.Alloc(reference, GCHandleType.Normal);
}
}
else {
if (rootRef.IsAllocated) {
rootRef.Free();
}
}
}
protected override void OnThreadException(Exception e) {
Application.OnThreadException(e);
}
/// <include file='doc\TrayIcon.uex' path='docs/doc[@for="NotifyIcon.NotifyIconNativeWindow.WndProc"]/*' />
/// <devdoc>
/// Pass messages on to the NotifyIcon object's wndproc handler.
/// </devdoc>
/// <internalonly/>
protected override void WndProc(ref Message m) {
Debug.Assert(reference != null, "NotifyIcon was garbage collected while it was still visible. How did we let that happen?");
reference.WndProc(ref m);
}
}
}
}
| |
/* ====================================================================
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 NPOI.HPSF
{
using System;
using System.IO;
using System.Text;
using System.Collections;
using NPOI.Util;
using NPOI.HPSF.Wellknown;
/// <summary>
/// Represents a section in a {@link PropertySet}.
/// @author Rainer Klute
/// <a href="mailto:klute@rainer-klute.de"><klute@rainer-klute.de></a>
/// @author Drew Varner (Drew.Varner allUpIn sc.edu)
/// @since 2002-02-09
/// </summary>
internal class Section
{
/**
* Maps property IDs To section-private PID strings. These
* strings can be found in the property with ID 0.
*/
protected IDictionary dictionary;
/**
* The section's format ID, {@link #GetFormatID}.
*/
protected ClassID formatID;
/// <summary>
/// Returns the format ID. The format ID is the "type" of the
/// section. For example, if the format ID of the first {@link
/// Section} Contains the bytes specified by
/// <c>org.apache.poi.hpsf.wellknown.SectionIDMap.SUMMARY_INFORMATION_ID</c>
/// the section (and thus the property Set) is a SummaryInformation.
/// </summary>
/// <value>The format ID.</value>
public ClassID FormatID
{
get { return formatID; }
}
protected long offset;
/// <summary>
/// Gets the offset of the section in the stream.
/// </summary>
/// <value>The offset of the section in the stream</value>
public long OffSet
{
get { return offset; }
}
protected int size;
/// <summary>
/// Returns the section's size in bytes.
/// </summary>
/// <value>The section's size in bytes.</value>
public virtual int Size
{
get { return size; }
}
/// <summary>
/// Returns the number of properties in this section.
/// </summary>
/// <value>The number of properties in this section.</value>
public virtual int PropertyCount
{
get { return properties.Length; }
}
protected Property[] properties;
/// <summary>
/// Returns this section's properties.
/// </summary>
/// <value>This section's properties.</value>
public virtual Property[] Properties
{
get { return properties; }
}
/// <summary>
/// Creates an empty and uninitialized {@link Section}.
/// </summary>
protected Section()
{ }
/// <summary>
/// Creates a {@link Section} instance from a byte array.
/// </summary>
/// <param name="src">Contains the complete property Set stream.</param>
/// <param name="offset">The position in the stream that points To the
/// section's format ID.</param>
public Section(byte[] src, int offset)
{
int o1 = offset;
/*
* Read the format ID.
*/
formatID = new ClassID(src, o1);
o1 += ClassID.LENGTH;
/*
* Read the offset from the stream's start and positions To
* the section header.
*/
this.offset = LittleEndian.GetUInt(src, o1);
o1 = (int)this.offset;
/*
* Read the section Length.
*/
size = (int)LittleEndian.GetUInt(src, o1);
o1 += LittleEndianConsts.INT_SIZE;
/*
* Read the number of properties.
*/
int propertyCount = (int)LittleEndian.GetUInt(src, o1);
o1 += LittleEndianConsts.INT_SIZE;
/*
* Read the properties. The offset is positioned at the first
* entry of the property list. There are two problems:
*
* 1. For each property we have To Find out its Length. In the
* property list we Find each property's ID and its offset relative
* To the section's beginning. Unfortunately the properties in the
* property list need not To be in ascending order, so it is not
* possible To calculate the Length as
* (offset of property(i+1) - offset of property(i)). Before we can
* that we first have To sort the property list by ascending offsets.
*
* 2. We have To Read the property with ID 1 before we Read other
* properties, at least before other properties containing strings.
* The reason is that property 1 specifies the codepage. If it Is
* 1200, all strings are in Unicode. In other words: Before we can
* Read any strings we have To know whether they are in Unicode or
* not. Unfortunately property 1 is not guaranteed To be the first in
* a section.
*
* The algorithm below Reads the properties in two passes: The first
* one looks for property ID 1 and extracts the codepage number. The
* seconds pass Reads the other properties.
*/
properties = new Property[propertyCount];
/* Pass 1: Read the property list. */
int pass1OffSet = o1;
ArrayList propertyList = new ArrayList(propertyCount);
PropertyListEntry ple;
for (int i = 0; i < properties.Length; i++)
{
ple = new PropertyListEntry();
/* Read the property ID. */
ple.id = (int)LittleEndian.GetUInt(src, pass1OffSet);
pass1OffSet += LittleEndianConsts.INT_SIZE;
/* OffSet from the section's start. */
ple.offset = (int)LittleEndian.GetUInt(src, pass1OffSet);
pass1OffSet += LittleEndianConsts.INT_SIZE;
/* Add the entry To the property list. */
propertyList.Add(ple);
}
/* Sort the property list by ascending offsets: */
propertyList.Sort();
/* Calculate the properties' Lengths. */
for (int i = 0; i < propertyCount - 1; i++)
{
PropertyListEntry ple1 =
(PropertyListEntry)propertyList[i];
PropertyListEntry ple2 =
(PropertyListEntry)propertyList[i + 1];
ple1.Length = ple2.offset - ple1.offset;
}
if (propertyCount > 0)
{
ple = (PropertyListEntry)propertyList[propertyCount - 1];
ple.Length = size - ple.offset;
//if (ple.Length <= 0)
//{
// StringBuilder b = new StringBuilder();
// b.Append("The property Set claims To have a size of ");
// b.Append(size);
// b.Append(" bytes. However, it exceeds ");
// b.Append(ple.offset);
// b.Append(" bytes.");
// throw new IllegalPropertySetDataException(b.ToString());
//}
}
/* Look for the codepage. */
int codepage = -1;
for (IEnumerator i = propertyList.GetEnumerator();
codepage == -1 && i.MoveNext(); )
{
ple = (PropertyListEntry)i.Current;
/* Read the codepage if the property ID is 1. */
if (ple.id == PropertyIDMap.PID_CODEPAGE)
{
/* Read the property's value type. It must be
* VT_I2. */
int o = (int)(this.offset + ple.offset);
long type = LittleEndian.GetUInt(src, o);
o += LittleEndianConsts.INT_SIZE;
if (type != Variant.VT_I2)
throw new HPSFRuntimeException
("Value type of property ID 1 is not VT_I2 but " +
type + ".");
/* Read the codepage number. */
codepage = LittleEndian.GetUShort(src, o);
}
}
/* Pass 2: Read all properties - including the codepage property,
* if available. */
int i1 = 0;
for (IEnumerator i = propertyList.GetEnumerator(); i.MoveNext(); )
{
ple = (PropertyListEntry)i.Current;
Property p = new Property(ple.id, src,
this.offset + ple.offset,
ple.Length, codepage);
if (p.ID == PropertyIDMap.PID_CODEPAGE)
p = new Property(p.ID, p.Type, codepage);
properties[i1++] = p;
}
/*
* Extract the dictionary (if available).
* Tony changed the logic
*/
this.dictionary = (IDictionary)GetProperty(0);
}
/**
* Represents an entry in the property list and holds a property's ID and
* its offset from the section's beginning.
*/
class PropertyListEntry : IComparable
{
public int id;
public int offset;
public int Length;
/**
* Compares this {@link PropertyListEntry} with another one by their
* offsets. A {@link PropertyListEntry} is "smaller" than another one if
* its offset from the section's begin is smaller.
*
* @see Comparable#CompareTo(java.lang.Object)
*/
public int CompareTo(Object o)
{
if (!(o is PropertyListEntry))
throw new InvalidCastException(o.ToString());
int otherOffSet = ((PropertyListEntry)o).offset;
if (offset < otherOffSet)
return -1;
else if (offset == otherOffSet)
return 0;
else
return 1;
}
public override String ToString()
{
StringBuilder b = new StringBuilder();
b.Append(GetType().Name);
b.Append("[id=");
b.Append(id);
b.Append(", offset=");
b.Append(offset);
b.Append(", Length=");
b.Append(Length);
b.Append(']');
return b.ToString();
}
}
/**
* Returns the value of the property with the specified ID. If
* the property is not available, <c>null</c> is returned
* and a subsequent call To {@link #wasNull} will return
* <c>true</c>.
*
* @param id The property's ID
*
* @return The property's value
*/
public virtual Object GetProperty(long id)
{
wasNull = false;
for (int i = 0; i < properties.Length; i++)
if (id == properties[i].ID)
return properties[i].Value;
wasNull = true;
return null;
}
/**
* Returns the value of the numeric property with the specified
* ID. If the property is not available, 0 is returned. A
* subsequent call To {@link #wasNull} will return
* <c>true</c> To let the caller distinguish that case from
* a real property value of 0.
*
* @param id The property's ID
*
* @return The property's value
*/
public virtual int GetPropertyIntValue(long id)
{
Object o = GetProperty(id);
if (o == null)
return 0;
if (!(o is long || o is int))
throw new HPSFRuntimeException
("This property is not an integer type, but " +
o.GetType().Name + ".");
return (int)o;
}
/**
* Returns the value of the bool property with the specified
* ID. If the property is not available, <c>false</c> Is
* returned. A subsequent call To {@link #wasNull} will return
* <c>true</c> To let the caller distinguish that case from
* a real property value of <c>false</c>.
*
* @param id The property's ID
*
* @return The property's value
*/
public virtual bool GetPropertyBooleanValue(int id)
{
object tmp = GetProperty(id);
if (tmp != null)
{
return (bool)GetProperty(id);
}
else
{
return false;
}
}
/**
* This member is <c>true</c> if the last call To {@link
* #GetPropertyIntValue} or {@link #GetProperty} tried To access a
* property that was not available, else <c>false</c>.
*/
private bool wasNull;
/// <summary>
/// Checks whether the property which the last call To {@link
/// #GetPropertyIntValue} or {@link #GetProperty} tried To access
/// was available or not. This information might be important for
/// callers of {@link #GetPropertyIntValue} since the latter
/// returns 0 if the property does not exist. Using {@link
/// #wasNull} the caller can distiguish this case from a property's
/// real value of 0.
/// </summary>
/// <value><c>true</c> if the last call To {@link
/// #GetPropertyIntValue} or {@link #GetProperty} tried To access a
/// property that was not available; otherwise, <c>false</c>.</value>
public virtual bool WasNull
{
get { return wasNull; }
}
/// <summary>
/// Returns the PID string associated with a property ID. The ID
/// is first looked up in the {@link Section}'s private
/// dictionary. If it is not found there, the method calls {@link
/// SectionIDMap#GetPIDString}.
/// </summary>
/// <param name="pid">The property ID.</param>
/// <returns>The property ID's string value</returns>
public String GetPIDString(long pid)
{
String s = null;
if (dictionary != null)
s = (String)dictionary[pid];
if (s == null)
s = SectionIDMap.GetPIDString(FormatID.Bytes, pid);
if (s == null)
s = SectionIDMap.UNDEFINED;
return s;
}
/**
* Checks whether this section is equal To another object. The result Is
* <c>false</c> if one of the the following conditions holds:
*
* <ul>
*
* <li>The other object is not a {@link Section}.</li>
*
* <li>The format IDs of the two sections are not equal.</li>
*
* <li>The sections have a different number of properties. However,
* properties with ID 1 (codepage) are not counted.</li>
*
* <li>The other object is not a {@link Section}.</li>
*
* <li>The properties have different values. The order of the properties
* is irrelevant.</li>
*
* </ul>
*
* @param o The object To Compare this section with
* @return <c>true</c> if the objects are equal, <c>false</c> if
* not
*/
public override bool Equals(Object o)
{
if (o == null || !(o is Section))
return false;
Section s = (Section)o;
if (!s.FormatID.Equals(FormatID))
return false;
/* Compare all properties except 0 and 1 as they must be handled
* specially. */
Property[] pa1 = new Property[Properties.Length];
Property[] pa2 = new Property[s.Properties.Length];
Array.Copy(Properties, 0, pa1, 0, pa1.Length);
Array.Copy(s.Properties, 0, pa2, 0, pa2.Length);
/* Extract properties 0 and 1 and Remove them from the copy of the
* arrays. */
Property p10 = null;
Property p20 = null;
for (int i = 0; i < pa1.Length; i++)
{
long id = pa1[i].ID;
if (id == 0)
{
p10 = pa1[i];
pa1 = Remove(pa1, i);
i--;
}
if (id == 1)
{
// p11 = pa1[i];
pa1 = Remove(pa1, i);
i--;
}
}
for (int i = 0; i < pa2.Length; i++)
{
long id = pa2[i].ID;
if (id == 0)
{
p20 = pa2[i];
pa2 = Remove(pa2, i);
i--;
}
if (id == 1)
{
// p21 = pa2[i];
pa2 = Remove(pa2, i);
i--;
}
}
/* If the number of properties (not counting property 1) is unequal the
* sections are unequal. */
if (pa1.Length != pa2.Length)
return false;
/* If the dictionaries are unequal the sections are unequal. */
bool dictionaryEqual = true;
if (p10 != null && p20 != null)
{
//tony qu fixed this issue
Hashtable a=(Hashtable)p10.Value;
Hashtable b = (Hashtable)p20.Value;
dictionaryEqual = a.Count==b.Count;
}
else if (p10 != null || p20 != null)
{
dictionaryEqual = false;
}
if (!dictionaryEqual)
return false;
else
return Util.AreEqual(pa1, pa2);
}
/// <summary>
/// Removes a field from a property array. The resulting array Is
/// compactified and returned.
/// </summary>
/// <param name="pa">The property array.</param>
/// <param name="i">The index of the field To be Removed.</param>
/// <returns>the compactified array.</returns>
private Property[] Remove(Property[] pa, int i)
{
Property[] h = new Property[pa.Length - 1];
if (i > 0)
Array.Copy(pa, 0, h, 0, i);
Array.Copy(pa, i + 1, h, i, h.Length - i);
return h;
}
/// <summary>
/// Serves as a hash function for a particular type.
/// </summary>
/// <returns>
/// A hash code for the current <see cref="T:System.Object"/>.
/// </returns>
public override int GetHashCode()
{
long GetHashCode = 0;
GetHashCode += FormatID.GetHashCode();
Property[] pa = Properties;
for (int i = 0; i < pa.Length; i++)
GetHashCode += pa[i].GetHashCode();
int returnHashCode = (int)(GetHashCode & 0x0ffffffffL);
return returnHashCode;
}
/// <summary>
/// Returns a <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>.
/// </summary>
/// <returns>
/// A <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>.
/// </returns>
public override String ToString()
{
StringBuilder b = new StringBuilder();
Property[] pa = Properties;
b.Append(GetType().Name);
b.Append('[');
b.Append("formatID: ");
b.Append(FormatID);
b.Append(", offset: ");
b.Append(OffSet);
b.Append(", propertyCount: ");
b.Append(PropertyCount);
b.Append(", size: ");
b.Append(Size);
b.Append(", properties: [\n");
for (int i = 0; i < pa.Length; i++)
{
b.Append(pa[i].ToString());
b.Append(",\n");
}
b.Append(']');
b.Append(']');
return b.ToString();
}
/// <summary>
/// Gets the section's dictionary. A dictionary allows an application To
/// use human-Readable property names instead of numeric property IDs. It
/// Contains mappings from property IDs To their associated string
/// values. The dictionary is stored as the property with ID 0. The codepage
/// for the strings in the dictionary is defined by property with ID 1.
/// </summary>
/// <value>the dictionary or null
/// if the section does not have
/// a dictionary.</value>
public virtual IDictionary Dictionary
{
get {
if (dictionary == null)
dictionary = new Hashtable();
return dictionary;
}
set {
dictionary = value;
}
}
/// <summary>
/// Gets the section's codepage, if any.
/// </summary>
/// <value>The section's codepage if one is defined, else -1.</value>
public int Codepage
{
get
{
if (GetProperty(PropertyIDMap.PID_CODEPAGE) == null)
return -1;
int codepage =
(int)GetProperty(PropertyIDMap.PID_CODEPAGE);
return codepage;
}
}
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Caching.Memory;
using Newtonsoft.Json.Linq;
using OrchardCore.ContentManagement.Metadata;
using OrchardCore.ContentManagement.Metadata.Models;
using OrchardCore.ContentManagement.Metadata.Records;
using OrchardCore.Data.Documents;
namespace OrchardCore.ContentManagement
{
public class ContentDefinitionManager : IContentDefinitionManager
{
private const string CacheKey = nameof(ContentDefinitionManager);
private readonly IContentDefinitionStore _contentDefinitionStore;
private readonly IMemoryCache _memoryCache;
private readonly ConcurrentDictionary<string, ContentTypeDefinition> _cachedTypeDefinitions;
private readonly ConcurrentDictionary<string, ContentPartDefinition> _cachedPartDefinitions;
private readonly Dictionary<string, ContentTypeDefinition> _scopedTypeDefinitions = new Dictionary<string, ContentTypeDefinition>();
private readonly Dictionary<string, ContentPartDefinition> _scopedPartDefinitions = new Dictionary<string, ContentPartDefinition>();
public ContentDefinitionManager(
IContentDefinitionStore contentDefinitionStore,
IMemoryCache memoryCache)
{
_contentDefinitionStore = contentDefinitionStore;
_memoryCache = memoryCache;
_cachedTypeDefinitions = _memoryCache.GetOrCreate("TypeDefinitions", entry => new ConcurrentDictionary<string, ContentTypeDefinition>());
_cachedPartDefinitions = _memoryCache.GetOrCreate("PartDefinitions", entry => new ConcurrentDictionary<string, ContentPartDefinition>());
}
public async Task<string> GetIdentifierAsync() => (await _contentDefinitionStore.GetContentDefinitionAsync()).Identifier;
public ContentTypeDefinition LoadTypeDefinition(string name)
{
if (string.IsNullOrEmpty(name))
{
throw new ArgumentException("Argument cannot be null or empty", nameof(name));
}
if (!_scopedTypeDefinitions.TryGetValue(name, out var typeDefinition))
{
var contentTypeDefinitionRecord = LoadContentDefinitionRecord()
.ContentTypeDefinitionRecords
.FirstOrDefault(x => x.Name == name);
_scopedTypeDefinitions[name] = typeDefinition = Build(contentTypeDefinitionRecord, LoadContentDefinitionRecord().ContentPartDefinitionRecords);
};
return typeDefinition;
}
public ContentTypeDefinition GetTypeDefinition(string name)
{
if (string.IsNullOrEmpty(name))
{
throw new ArgumentException("Argument cannot be null or empty", nameof(name));
}
var document = GetContentDefinitionRecord();
CheckDocumentIdentifier(document);
return _cachedTypeDefinitions.GetOrAdd(name, n =>
{
var contentTypeDefinitionRecord = document
.ContentTypeDefinitionRecords
.FirstOrDefault(x => x.Name == name);
return Build(contentTypeDefinitionRecord, GetContentDefinitionRecord().ContentPartDefinitionRecords);
});
}
public ContentPartDefinition LoadPartDefinition(string name)
{
if (!_scopedPartDefinitions.TryGetValue(name, out var partDefinition))
{
_scopedPartDefinitions[name] = partDefinition = Build(LoadContentDefinitionRecord()
.ContentPartDefinitionRecords
.FirstOrDefault(x => x.Name == name));
};
return partDefinition;
}
public ContentPartDefinition GetPartDefinition(string name)
{
var document = GetContentDefinitionRecord();
CheckDocumentIdentifier(document);
return _cachedPartDefinitions.GetOrAdd(name, n =>
{
return Build(document
.ContentPartDefinitionRecords
.FirstOrDefault(x => x.Name == name));
});
}
public IEnumerable<ContentTypeDefinition> LoadTypeDefinitions()
{
return LoadContentDefinitionRecord().ContentTypeDefinitionRecords.Select(x => LoadTypeDefinition(x.Name)).ToList();
}
public IEnumerable<ContentTypeDefinition> ListTypeDefinitions()
{
return GetContentDefinitionRecord().ContentTypeDefinitionRecords.Select(x => GetTypeDefinition(x.Name)).ToList();
}
public IEnumerable<ContentPartDefinition> LoadPartDefinitions()
{
return LoadContentDefinitionRecord().ContentPartDefinitionRecords.Select(x => LoadPartDefinition(x.Name)).ToList();
}
public IEnumerable<ContentPartDefinition> ListPartDefinitions()
{
return GetContentDefinitionRecord().ContentPartDefinitionRecords.Select(x => GetPartDefinition(x.Name)).ToList();
}
public void StoreTypeDefinition(ContentTypeDefinition contentTypeDefinition)
{
Apply(contentTypeDefinition, Acquire(contentTypeDefinition));
UpdateContentDefinitionRecord();
}
public void StorePartDefinition(ContentPartDefinition contentPartDefinition)
{
Apply(contentPartDefinition, Acquire(contentPartDefinition));
UpdateContentDefinitionRecord();
}
public void DeleteTypeDefinition(string name)
{
var record = LoadContentDefinitionRecord().ContentTypeDefinitionRecords.FirstOrDefault(x => x.Name == name);
// deletes the content type record associated
if (record != null)
{
LoadContentDefinitionRecord().ContentTypeDefinitionRecords.Remove(record);
UpdateContentDefinitionRecord();
}
}
public void DeletePartDefinition(string name)
{
// remove parts from current types
var typesWithPart = LoadTypeDefinitions().Where(typeDefinition => typeDefinition.Parts.Any(part => part.PartDefinition.Name == name));
foreach (var typeDefinition in typesWithPart)
{
this.AlterTypeDefinition(typeDefinition.Name, builder => builder.RemovePart(name));
}
// delete part
var record = LoadContentDefinitionRecord().ContentPartDefinitionRecords.FirstOrDefault(x => x.Name == name);
if (record != null)
{
LoadContentDefinitionRecord().ContentPartDefinitionRecords.Remove(record);
UpdateContentDefinitionRecord();
}
}
private ContentTypeDefinitionRecord Acquire(ContentTypeDefinition contentTypeDefinition)
{
var result = LoadContentDefinitionRecord().ContentTypeDefinitionRecords.FirstOrDefault(x => x.Name == contentTypeDefinition.Name);
if (result == null)
{
result = new ContentTypeDefinitionRecord { Name = contentTypeDefinition.Name, DisplayName = contentTypeDefinition.DisplayName };
LoadContentDefinitionRecord().ContentTypeDefinitionRecords.Add(result);
}
return result;
}
private ContentPartDefinitionRecord Acquire(ContentPartDefinition contentPartDefinition)
{
var result = LoadContentDefinitionRecord().ContentPartDefinitionRecords.FirstOrDefault(x => x.Name == contentPartDefinition.Name);
if (result == null)
{
result = new ContentPartDefinitionRecord { Name = contentPartDefinition.Name, };
LoadContentDefinitionRecord().ContentPartDefinitionRecords.Add(result);
}
return result;
}
private void Apply(ContentTypeDefinition model, ContentTypeDefinitionRecord record)
{
record.DisplayName = model.DisplayName;
record.Settings = model.Settings;
var toRemove = record.ContentTypePartDefinitionRecords
.Where(typePartDefinitionRecord => !model.Parts.Any(part => typePartDefinitionRecord.Name == part.Name))
.ToList();
foreach (var remove in toRemove)
{
record.ContentTypePartDefinitionRecords.Remove(remove);
}
foreach (var part in model.Parts)
{
var typePartRecord = record.ContentTypePartDefinitionRecords.FirstOrDefault(r => r.Name == part.Name);
if (typePartRecord == null)
{
typePartRecord = new ContentTypePartDefinitionRecord
{
PartName = part.PartDefinition.Name,
Name = part.Name,
Settings = part.Settings
};
record.ContentTypePartDefinitionRecords.Add(typePartRecord);
}
Apply(part, typePartRecord);
}
}
private void Apply(ContentTypePartDefinition model, ContentTypePartDefinitionRecord record)
{
record.Settings = model.Settings;
}
private void Apply(ContentPartDefinition model, ContentPartDefinitionRecord record)
{
record.Settings = model.Settings;
var toRemove = record.ContentPartFieldDefinitionRecords
.Where(partFieldDefinitionRecord => !model.Fields.Any(partField => partFieldDefinitionRecord.Name == partField.Name))
.ToList();
foreach (var remove in toRemove)
{
record.ContentPartFieldDefinitionRecords.Remove(remove);
}
foreach (var field in model.Fields)
{
var fieldName = field.Name;
var partFieldRecord = record.ContentPartFieldDefinitionRecords.FirstOrDefault(r => r.Name == fieldName);
if (partFieldRecord == null)
{
partFieldRecord = new ContentPartFieldDefinitionRecord
{
FieldName = field.FieldDefinition.Name,
Name = field.Name
};
record.ContentPartFieldDefinitionRecords.Add(partFieldRecord);
}
Apply(field, partFieldRecord);
}
}
private void Apply(ContentPartFieldDefinition model, ContentPartFieldDefinitionRecord record)
{
record.Settings = model.Settings;
}
private ContentTypeDefinition Build(ContentTypeDefinitionRecord source, IList<ContentPartDefinitionRecord> partDefinitionRecords)
{
if (source == null)
{
return null;
}
var contentTypeDefinition = new ContentTypeDefinition(
source.Name,
source.DisplayName,
source.ContentTypePartDefinitionRecords.Select(tp => Build(tp, partDefinitionRecords.FirstOrDefault(p => p.Name == tp.PartName))),
source.Settings);
return contentTypeDefinition;
}
private ContentTypePartDefinition Build(ContentTypePartDefinitionRecord source, ContentPartDefinitionRecord partDefinitionRecord)
{
return source == null ? null : new ContentTypePartDefinition(
source.Name,
Build(partDefinitionRecord) ?? new ContentPartDefinition(source.PartName, Enumerable.Empty<ContentPartFieldDefinition>(), new JObject()),
source.Settings);
}
private ContentPartDefinition Build(ContentPartDefinitionRecord source)
{
return source == null ? null : new ContentPartDefinition(
source.Name,
source.ContentPartFieldDefinitionRecords.Select(Build),
source.Settings);
}
private ContentPartFieldDefinition Build(ContentPartFieldDefinitionRecord source)
{
return source == null ? null : new ContentPartFieldDefinition(
Build(new ContentFieldDefinitionRecord { Name = source.FieldName }),
source.Name,
source.Settings
);
}
private ContentFieldDefinition Build(ContentFieldDefinitionRecord source)
{
return source == null ? null : new ContentFieldDefinition(source.Name);
}
/// <summary>
/// Loads the document from the store for updating and that should not be cached.
/// </summary>
private ContentDefinitionRecord LoadContentDefinitionRecord() => _contentDefinitionStore.LoadContentDefinitionAsync().GetAwaiter().GetResult();
/// <summary>
/// Gets the document from the cache for sharing and that should not be updated.
/// </summary>
private ContentDefinitionRecord GetContentDefinitionRecord() => _contentDefinitionStore.GetContentDefinitionAsync().GetAwaiter().GetResult();
private void UpdateContentDefinitionRecord()
{
var contentDefinitionRecord = LoadContentDefinitionRecord();
_contentDefinitionStore.SaveContentDefinitionAsync(contentDefinitionRecord).GetAwaiter().GetResult();
// If multiple updates in the same scope, types and parts may need to be rebuilt.
_scopedTypeDefinitions.Clear();
_scopedPartDefinitions.Clear();
}
/// <summary>
/// Checks the document identifier and then clears the cached built definitions if it has changed.
/// </summary>
private void CheckDocumentIdentifier(ContentDefinitionRecord document)
{
if (!_memoryCache.TryGetValue<Document>(CacheKey, out var cacheEntry) || cacheEntry.Identifier != document.Identifier)
{
cacheEntry = new Document()
{
Identifier = document.Identifier,
};
_cachedTypeDefinitions.Clear();
_cachedPartDefinitions.Clear();
_memoryCache.Set(CacheKey, cacheEntry);
}
}
}
}
| |
namespace MSBuild.AutoILMerge
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Reflection;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using System.Dynamic;
using System.Text;
/// <summary>
/// The MSBuild task wrapping (in)famous ILMerge utility.
/// The recommended way of embedding dependencies into the executable is now <b>Costura.Fody</b>,
/// but <b>ILMerge is still unavoidable for some tasks, e.g. creation of database-stored MS CRM plug-ins.</b>
/// Also, calling ILMerge from a batch file is sometimes hindered by the limitation on the total length of the command line...
/// </summary>
/// <remarks>
/// See http://sedodream.com/PermaLink,guid,020fd1af-fb17-4fc9-8336-877c157eb2b4.aspx
/// why we don't really know the project directory so you better make sure all paths are absolute.
/// </remarks>
public class Task : Microsoft.Build.Utilities.Task
{
/// <summary>
/// Initializes a new instance of the <see cref="Task"/> class.
/// </summary>
public Task()
{
this.LibraryPath = new ITaskItem[0];
this.InputAssemblies = new ITaskItem[0];
}
#region public properties
#region Files and directories
/// <summary>
/// Gets or sets the item list containing the input assemblies.
/// The first element of the list is considered to be the primary assembly.
/// </summary>
/// <remarks>Translates to ILMerge.SetInputAssemblies().</remarks>
[Required]
public virtual ITaskItem[] InputAssemblies { get; set; }
/// <summary>
/// Gets or sets the item list containing the library assemblies
/// that are not to be included in the merge. They are used to determine the
/// <see cref="LibraryPath"/> for the lack of a better method.
/// With NuGet we can have hundreds potential library directories even if we filter them by platform
/// (nontrivial task by itself).
/// </summary>
/// <remarks>Translates to ILMerge.SetSearchDirectories() eventually with a higher priority then <see cref="LibraryPath"/>.
/// TODO: copy to temp dir (use symlinks?), add dthis dir to the lib path.</remarks>
public virtual ITaskItem[] LibraryAssemblies { get; set; }
/// <summary>
/// Gets or sets the item list containing the directories to be used to search for input assemblies.
/// </summary>
/// <remarks>Translates to ILMerge.SetSearchDirectories().</remarks>
public virtual ITaskItem[] LibraryPath { get; set; }
/// <summary>
/// Gets or sets the directory path to be considered an anchor point
/// for library (usually packaged) assemblies. used to determine the default merge order.
/// </summary>
public virtual string PackagesDir { get; set; }
/// <summary>
/// Gets or sets the path and name of the file containing the merge order list.
/// Assemblies (or, in the future, packages) are listed one per line;
/// all names given before a line containing "..." are popped to the top of the merge order,
/// all names after that line are pushed to the bottom. Assemblies not mentioned there stay where they were
/// (most often the initial order was quite random).
/// </summary>
public virtual string MergeOrderFile { get; set; }
/// <summary>
/// Gets or sets the path and name of the output file with the successfully merged result assembly.
/// </summary>
[Required]
public virtual string OutputFile { get; set; }
/// <summary>
/// Gets or sets the path and name of the log file.
/// </summary>
public virtual string LogFile { get; set; }
/// <summary>
/// Gets or sets the path name of the file that will be used to identify types that are not to have their visibility modified.
/// Used together with <see cref="Internalize"/> flag. For details, see ILMerge documentation.
/// </summary>
public virtual string InternalizeExcludeFile { get; set; }
/// <summary>
/// Gets or sets the path and name of the attribute assembly,
/// an assembly that will be used to get all of the assembly-level attributes such as Culture, Version, etc.
/// It will also be used to get the Win32 Resources from. It is mutually exclusive with the <see cref="CopyAttributes"/> property
/// For details, see ILMerge documentation.
/// </summary>
public virtual string AttributeFile { get; set; }
/// <summary>
/// Gets or sets the path and name of the .snk file.
/// The target assembly will be signed with its contents and will then have a strong name.
/// It can be used with the <see langword="DelaySign"/> property to have the target assembly delay signed.
/// This can be done even if the primary assembly was fully signed.
/// </summary>
public virtual string KeyFile { get; set; }
#endregion
#region flags and options
/// <summary>
/// Gets or sets of the type names that are allowed to be in duplicate.
/// For details, see ILMerge documentation.
/// </summary>
public virtual string AllowDuplicateType { get; set; }
/// <summary>
/// Gets or sets a value indicating whether, if the <see cref="CopyAttributes"/> is also set,
/// any assembly-level attributes names that have the same type are copied over into the target directory
/// as long as the definition of the attribute type specifies that <b>AllowMultiple</b> is true.
/// </summary>
public virtual bool AllowMultipleAssemblyLevelAttributes { get; set; }
/// <summary>
/// Gets or sets a value indicating whether, if an assembly's PeKind flag
/// (this is the value of the field listed as .corflags in the Manifest) is zero
/// it will be treated as if it was ILonly.
/// For details, see ILMerge documentation.
/// </summary>
public virtual bool AllowZeroPeKind { get; set; }
/// <summary>
/// Gets or sets a value indicating whether any wild cards in file names are expanded and all matching files will be used as input.
/// Usually it is already done by MSBuild, but left here for completeness. For details, see ILMerge documentation.
/// </summary>
public bool AllowWildCards { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the "transitive closure"
/// of the input assemblies is computed and added to the list of input assemblies.
/// For details, see ILMerge documentation.
/// </summary>
public virtual bool Closed { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the assembly level attributes of each input assembly are copied over into the target assembly.
/// For details, see ILMerge documentation.
/// </summary>
public virtual bool CopyAttributes { get; set; }
/// <summary>
/// Gets or sets a value indicating whether ILMerge creates a .pdb file for the output assembly
/// and merges into it any .pdb files found for input assemblies.
/// </summary>
public virtual bool DebugInfo { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the target assembly will be delay signed.
/// Only used together with <see cref="KeyFile"/> option.
/// </summary>
public virtual bool DelaySign { get; set; }
/// <summary>
/// Gets or sets the file alignment used for the target assembly.
/// The setter sets the value to the largest power of two that is no larger than the supplied argument, and is at least 512.
/// </summary>
public virtual int FileAlignment { get; set; }
/// <summary>
/// Gets or sets a value indicating whether types in assemblies other than the primary assembly have their visibility modified.
/// For details, see ILMerge documentation.
/// </summary>
public virtual bool Internalize { get; set; }
/// <summary>
/// Gets or sets a value indicating whether XML documentation files are merged
/// to produce an XML documentation file for the target assembly.
/// </summary>
public virtual bool XmlDocumentation { get; set; }
/// <summary>
/// Gets or sets a value indicating whether external assembly references in the manifest of the target assembly
/// will use full public keys (false) or public key tokens (true). Default is <see langword="true"/>.
/// </summary>
public virtual bool PublicKeyTokens { get; set; }
/// <summary>
/// Gets or sets a value indicating whether log messages are written. It is used in conjunction with the <see cref="LogFile"/> property.
/// </summary>
public virtual bool ShouldLog { get; set; }
/// <summary>
/// Gets the value indicating whether after the merge the primary assembly had a strong name,
/// but the target assembly does not. This can occur when an .snk file is not specified,
/// or if something goes wrong trying to read its contents.
/// </summary>
[Output]
public virtual bool StrongNameLost { get; private set; }
/// <summary>
/// Gets or sets the kind of the target assembly (a library, a console application or a Windows application).
/// The possible values are (Dll, Exe, WinExe).
/// </summary>
public virtual string TargetKind { get; set; }
/// <summary>
/// Gets or sets the version of the target framework. Default is "40".
/// </summary>
public virtual string TargetPlatform { get; set; }
/// <summary>
/// Gets or sets a value indicating whether types with the same name are all merged into a single type in the target assembly.
/// For details, see ILMerge documentation.
/// </summary>
public virtual bool UnionMerge { get; set; }
/// <summary>
/// Gets or sets the version number of the assembly in "6.2.1.3" format. Default is "1.0.0.0".
/// </summary>
public virtual string Version { get; set; }
#endregion
#endregion
#region public methods
/// <summary>
/// The one and only.
/// </summary>
/// <returns>Success or failure.</returns>
/// <remarks>use Dynamic. Segregate executable search in a separate class.</remarks>
public override bool Execute()
{
var targetPlatform = ConvertTargetPlatform(this.TargetPlatform);
var targetPlatformDir = this.GetTargetPlatformDirectory(this.TargetPlatform);
var inputAssemblies = this.ReshuffleInputAssemblies();
var searchDirs = this.CollectAllLibraryPaths();
if (this.DebugInfo || this.ShouldLog)
{
ListItems("Running ILMerge executable",
new string[] {
"AllowMultipleAssemblyLevelAttributes = " + this.AllowMultipleAssemblyLevelAttributes,
"AllowWildCards = " + this.AllowWildCards,
"AllowZeroPeKind = " + this.AllowZeroPeKind,
"AttributeFile = " + this.BuildPath(this.AttributeFile),
"Closed = " + this.Closed,
"CopyAttributes = " + this.CopyAttributes,
"DebugInfo = " + this.DebugInfo,
"DelaySign = " + this.DelaySign,
"ExcludeFile = " + this.BuildPath(this.InternalizeExcludeFile),
"FileAlignment = " + (this.FileAlignment > 0 ? this.FileAlignment : 512),
"Internalize = " + this.Internalize,
"KeyFile = " + this.BuildPath(this.KeyFile),
"Log = " + this.ShouldLog,
"LogFile = " + this.BuildPath(this.LogFile),
"OutputFile = " + this.BuildPath(this.OutputFile),
"PublicKeyTokens = " + this.PublicKeyTokens,
"TargetKind = " + ConvertTargetKind(this.TargetKind),
"UnionMerge = " + this.UnionMerge,
"Version = " + this.Version,
"XmlDocumentation = " + this.XmlDocumentation,
"AllowDuplicateType = "+ this.AllowDuplicateType,
"TargetPlatform = " + targetPlatform + ";" + targetPlatformDir,
"InputAssemblies = " + string.Join("; ", inputAssemblies),
"SearchDirectories = " + string.Join("; ", searchDirs)
});
}
Assembly ilmergeExe = this.LoadILMerge();
Type ilmergeType = ilmergeExe.GetType("ILMerging.ILMerge", true, true);
if (ilmergeType == null)
throw new InvalidOperationException("Cannot find 'ILMerging.ILMerge' in executable.");
dynamic merger = Activator.CreateInstance(ilmergeType);
merger.AllowMultipleAssemblyLevelAttributes = this.AllowMultipleAssemblyLevelAttributes;
merger.AllowWildCards = this.AllowWildCards;
merger.AllowZeroPeKind = this.AllowZeroPeKind;
merger.AttributeFile = this.BuildPath(this.AttributeFile);
merger.Closed = this.Closed;
merger.CopyAttributes = this.CopyAttributes;
merger.DebugInfo = this.DebugInfo;
merger.DelaySign = this.DelaySign;
merger.ExcludeFile = this.BuildPath(this.InternalizeExcludeFile);
merger.FileAlignment = this.FileAlignment > 0 ? this.FileAlignment : 512;
merger.Internalize = this.Internalize;
if (!string.IsNullOrEmpty(this.KeyFile))
merger.KeyFile = this.BuildPath(this.KeyFile);
merger.Log = this.ShouldLog;
merger.LogFile = this.BuildPath(this.LogFile);
merger.OutputFile = this.BuildPath(this.OutputFile);
merger.PublicKeyTokens = this.PublicKeyTokens;
merger.TargetKind = (dynamic)Enum.Parse(merger.TargetKind.GetType(), ConvertTargetKind(this.TargetKind).ToString());
merger.UnionMerge = this.UnionMerge;
merger.XmlDocumentation = this.XmlDocumentation;
if (!string.IsNullOrEmpty(this.Version))
{
merger.Version = new Version(this.Version);
}
if (!string.IsNullOrEmpty(this.AllowDuplicateType))
{
if (this.AllowDuplicateType == "*")
{
merger.AllowDuplicateType(null);
}
else
{
foreach (string typeName in this.AllowDuplicateType.Split(','))
{
merger.AllowDuplicateType(typeName);
}
}
}
merger.SetTargetPlatform(targetPlatform, targetPlatformDir);
merger.SetInputAssemblies(inputAssemblies);
merger.SetSearchDirectories(searchDirs);
try
{
Log.LogMessage(
MessageImportance.Normal,
"Merging {0} assembl{1} to '{2}'.",
this.InputAssemblies.Length,
(this.InputAssemblies.Length != 1) ? "ies" : "y",
this.BuildPath(this.OutputFile));
merger.Merge();
this.StrongNameLost = merger.StrongNameLost;
if (this.StrongNameLost)
Log.LogMessage(MessageImportance.High, "StrongNameLost = true");
}
catch (Exception exception)
{
Log.LogErrorFromException(exception);
return false;
}
return true;
}
#endregion
#region private methods
private void ListItems(string message, IEnumerable<string> items)
{
Log.LogMessage(MessageImportance.Low, message);
foreach (var item in items)
Log.LogMessage(MessageImportance.Low, " " + item);
}
/// <summary>
/// Reshuffles the input assembly list according to the file source and specified lead order (if any).
/// In any case, project assemblies are loaded before library assemblies (library assemblies are all that lives
/// under <see cref="PackagesDir"/>).
/// </summary>
/// <returns>The reordered list of input assemblies. The master assembly will remain the first one.</returns>
/// <remarks>TODO: use http://stackoverflow.com/questions/6653715/view-nuget-package-dependency-hierarchy
/// to flatten package dependency graph.</remarks>
private string[] ReshuffleInputAssemblies()
{
var result = new List<string>();
var projectFiles = new List<string>();
var libraryFiles = new List<string>();
result.Add(this.BuildPath(this.InputAssemblies[0].ItemSpec));
for (var i = 1; i < this.InputAssemblies.Length; i++)
{
var fileName = this.BuildPath(this.InputAssemblies[i].ItemSpec);
if (!string.IsNullOrWhiteSpace(this.PackagesDir))
{
var pathInPackages = GetRelativePath(this.PackagesDir, fileName);
if (!Path.IsPathRooted(pathInPackages))
{
libraryFiles.Add(fileName);
continue;
}
}
projectFiles.Add(fileName);
}
if (this.DebugInfo)
{
ListItems("Project assemblies to merge (original order)", projectFiles);
ListItems("Library assemblies to merge (original order)", libraryFiles);
}
var mergeOrderHigh = new List<string>();
var mergeOrderLow = new List<string>();
var isHigh = true;
foreach (var orderItem in this.ReadMergeOrder())
{
if (orderItem == "...")
isHigh = false;
else if (isHigh)
mergeOrderHigh.Add(orderItem);
else
mergeOrderLow.Add(orderItem);
}
if (this.DebugInfo && mergeOrderHigh.Count > 0)
ListItems("Assemblies to bubble up in the merge order", mergeOrderHigh);
if (this.DebugInfo && mergeOrderLow.Count > 0)
ListItems("Assemblies to push down in the merge order", mergeOrderLow);
result.AddRange(SortAssemblies(projectFiles, mergeOrderHigh, mergeOrderLow));
result.AddRange(SortAssemblies(libraryFiles, mergeOrderHigh, mergeOrderLow));
var filenames = result.Select(s => Path.GetFileName(s)).ToArray();
if (this.DebugInfo && filenames.Length > 0)
ListItems("Final assemblies merge order", filenames);
var tempOrdrFileName = Path.ChangeExtension(result[0], ".ilmerge");
WriteMergeOrder(tempOrdrFileName, filenames);
return result.Where(s => !string.IsNullOrEmpty(s)).ToArray();
}
private string AsDirectory(string path)
{
if (string.IsNullOrEmpty(path))
return null;
try
{
FileAttributes attr = File.GetAttributes(path);
return (attr & FileAttributes.Directory) == FileAttributes.Directory
? path
: Path.GetDirectoryName(path);
}
catch (System.Exception ex)
{
// fake directories etc can have funny names
return null;
}
}
private string[] CollectAllLibraryPaths()
{
var result = new List<string>();
if (this.LibraryAssemblies != null)
{
result.AddRange(this.LibraryAssemblies
.Where(iti => iti != null)
.Select(iti => AsDirectory(this.BuildPath(iti.ItemSpec))));
}
if (this.LibraryPath != null)
{
result.AddRange(this.LibraryPath
.Where(iti => iti != null)
.Select(iti => AsDirectory(this.BuildPath(iti.ItemSpec))));
}
result = result.Where(s => !string.IsNullOrEmpty(s) && !s.StartsWith("{"))
.Distinct()
.ToList();
if (this.DebugInfo && result.Count > 0)
ListItems("Library paths", result);
return result.ToArray();
}
private static string GetRelativePath(string rootPath, string fullPath)
{
// TODO: normalize both anchor and filename
var relPath = fullPath;
if (!String.IsNullOrEmpty(rootPath))
{
if (rootPath.Equals(fullPath, StringComparison.OrdinalIgnoreCase))
{
relPath = string.Empty;
}
else if (fullPath.StartsWith(rootPath + "\\", StringComparison.OrdinalIgnoreCase))
{
relPath = fullPath.Substring(rootPath.Length + 1);
}
}
return relPath;
}
private string[] ReadMergeOrder()
{
if (string.IsNullOrWhiteSpace(this.MergeOrderFile))
return new string[0];
if (!File.Exists((this.MergeOrderFile)))
{
Log.LogError("Specified merge order file '{0}' doesn't exist.", this.MergeOrderFile);
return new string[0];
}
var items = File.ReadAllLines(this.MergeOrderFile)
.Select(s => Regex.Replace(s, @"\s+", ""))
.Where(s => !(string.IsNullOrEmpty(s) || s.StartsWith("#") || s.StartsWith("//")))
.ToArray();
if (this.DebugInfo && items.Length > 0)
ListItems("Merge order is read from '" + this.MergeOrderFile + "' as", items);
return items;
}
private void WriteMergeOrder(string fileName, string[] items)
{
try
{
Log.LogMessage("Writing assembly merge order to '{0}'.", fileName);
File.WriteAllLines(fileName, items);
}
catch (System.Exception ex)
{
Log.LogWarning("Could not write merge order file '{0}' failed: {1}", fileName, ex.Message);
}
}
private List<string> SortAssemblies(List<string> files, List<string> mergeOrderHigh, List<string> mergeOrderLow)
{
files = SortAssembliesDown(files, mergeOrderLow);
return SortAssembliesUp(files, mergeOrderHigh);
}
private List<string> SortAssembliesUp(List<string> files, IEnumerable<string> mergeOrder)
{
////ListItems("in order up", mergeOrder);
////ListItems("before", files);
var result = new List<string>();
foreach (string pattern in mergeOrder)
{
for (var i = 0; i < files.Count; i++)
{
if (IsThatFile(files[i], pattern))
{
result.Add(files[i]);
files.RemoveAt(i);
}
}
}
////ListItems("shifted", result);
////ListItems("leftovers", files);
result.AddRange(files);
////ListItems("after", result);
return result;
}
private List<string> SortAssembliesDown(List<string> files, IEnumerable<string> mergeOrder)
{
////ListItems("in order down", mergeOrder);
////ListItems("before", files);
var result = new List<string>();
foreach (string pattern in mergeOrder.Reverse())
{
for (var i = files.Count - 1; i >= 0; i--)
{
if (IsThatFile(files[i], pattern))
{
result.Insert(0, files[i]);
files.RemoveAt(i);
}
}
}
////ListItems("shifted", result);
////ListItems("leftovers", files);
result.InsertRange(0, files);
////ListItems("after", result);
return result;
}
private string NormalizeFileName(string fileName)
{
fileName = Path.GetFileName(fileName).ToLowerInvariant();
string ext = Path.GetExtension(fileName);
if (ext == ".dll" || ext == ".exe")
fileName = Path.ChangeExtension(fileName, string.Empty);
return fileName;
}
private bool IsThatFile(string fileName, string pattern)
{
var fileNameParts = NormalizeFileName(fileName).Split('.');
var patternParts = NormalizeFileName(pattern).Split('.');
for (int i = 0; i < patternParts.Length; i++)
{
var p = patternParts[i];
var wild = p == "*";
if (i >= fileNameParts.Length)
return (i == patternParts.Length && wild);
var f = fileNameParts[i];
if (f != p && !wild)
return false;
}
////Log.LogMessage("{0} fit {1}", fileName, pattern);
return true;
}
private string BuildPath(string iti)
{
// see http://sedodream.com/PermaLink,guid,020fd1af-fb17-4fc9-8336-877c157eb2b4.aspx
// why we don't really know the project directory
// so you better make sure all paths are absolute
return iti;
////return string.IsNullOrEmpty(iti)
//// ? null
//// : Path.IsPathRooted(iti)
//// ? iti
//// : Path.Combine(base.BuildEngine.ProjectFileOfTaskNode, iti);
}
private enum ILMergeKind
{
Dll = 0,
Exe = 1,
WinExe = 2,
SameAsPrimaryAssembly = 3,
}
private ILMergeKind ConvertTargetKind(string value)
{
if (string.IsNullOrEmpty(value))
return ILMergeKind.SameAsPrimaryAssembly;
if (Enum.IsDefined(typeof(ILMergeKind), value))
{
return (ILMergeKind)Enum.Parse(typeof(ILMergeKind), value);
}
else
{
Log.LogWarning("Unrecognized target kind '{0}' - should be [Exe|Dll|WinExe|SameAsPrimaryAssembly]; set to SameAsPrimaryAssembly", value);
return ILMergeKind.SameAsPrimaryAssembly;
}
}
private TargetDotNetFrameworkVersion GetTargetPlatform(string value)
{
if (string.IsNullOrWhiteSpace(value))
return TargetDotNetFrameworkVersion.VersionLatest;
value = Regex.Replace(value, "[^.0-9]", string.Empty);
int n;
if (int.TryParse(value, out n))
{
if (n == 1 || n == 10 || n == 11)
return TargetDotNetFrameworkVersion.Version11;
if (n == 2 || n == 20)
return TargetDotNetFrameworkVersion.Version20;
if (n == 3 || n == 30)
return TargetDotNetFrameworkVersion.Version30;
if (n == 35)
return TargetDotNetFrameworkVersion.Version35;
if (n == 4 || n == 40 || n == 45)
return TargetDotNetFrameworkVersion.VersionLatest;
}
Log.LogWarning("Unrecognized target platform '{0}', set to v4", new object[0]);
return TargetDotNetFrameworkVersion.VersionLatest;
}
private string ConvertTargetPlatform(string value)
{
switch (this.GetTargetPlatform(this.TargetPlatform))
{
case TargetDotNetFrameworkVersion.Version11: return "v1.1";
case TargetDotNetFrameworkVersion.Version20: return "v2";
case TargetDotNetFrameworkVersion.Version30: return "v2";
case TargetDotNetFrameworkVersion.Version35: return "v2";
default: return "v4";
}
}
private string GetTargetPlatformDirectory(string value)
{
return ToolLocationHelper.GetPathToDotNetFramework(this.GetTargetPlatform(this.TargetPlatform));
}
#region everyone looking for ILMerge...
private Assembly LoadILMerge()
{
var ilmerge = this.FindILMergeExecutable();
if (ilmerge == null)
throw new FileNotFoundException("Cannot find ILMerge executable.");
Log.LogMessage("Loading ILMerge from '{0}'.", ilmerge);
return Assembly.LoadFrom(ilmerge);
}
private string FindILMergeExecutable()
{
string iamhere = Path.GetDirectoryName(this.GetType().Assembly.Location);
string ilmergePath = null;
// in the same directory as the task dll and 6 times up (in case we are package)
if (LookForILMergeUp(iamhere, out ilmergePath))
return ilmergePath;
// somewhere in the parent chain of the project (in case we are not but they are)
if (LookForILMergeUp(Path.GetDirectoryName(this.OutputFile), out ilmergePath))
return ilmergePath;
return null;
}
private bool LookForILMergeUp(string path, out string ilmergePath)
{
ilmergePath = null;
for (var i = 6; i >= 0 && !string.IsNullOrEmpty(Path.GetFileName(path)); i--)
{
if (LookForILMergeInDirectory(path, out ilmergePath))
return true;
path = Path.GetDirectoryName(path);
}
return false;
}
// ugly bit of blindly grouping around...
private bool LookForILMergeInDirectory(string pathToTry, out string ilmergePath)
{
if (IsILMergeThere(pathToTry, out ilmergePath))
return true;
// NB: we ignore pre-release part, assuming that ILMerge will never be made public in pre-release state
// just get the latest
var ilmergeDir = Directory.EnumerateDirectories(pathToTry, "ilmerge.*", SearchOption.TopDirectoryOnly)
.Where(s =>
{
s = Path.GetFileName(s);
// ignore all package like ILMerge.Bla.Bla.Bla.1.2.3.4
string[] parts = s.Split('.');
int n;
return parts.Length == 1 || int.TryParse(parts[1], out n);
})
.OrderByDescending(s => s)
.FirstOrDefault();
if (ilmergeDir != null)
return IsILMergeThere(ilmergeDir, out ilmergePath);
var packagesDir = Path.Combine(pathToTry, "packages");
if (Directory.Exists(packagesDir))
return LookForILMergeInDirectory(packagesDir, out ilmergePath);
return false;
}
private bool IsILMergeThere(string pathToTry, out string ilmergePath)
{
ilmergePath = Path.Combine(pathToTry, @"ILMerge.exe");
//Log.LogMessage("looking for " + ilmergePath);
if (File.Exists(ilmergePath))
return true;
// 1.0.3: see issue "Does not work with ILMerge 2.14.1208"
ilmergePath = Path.Combine(Path.Combine(pathToTry, "tools"), @"ILMerge.exe");
//Log.LogMessage("looking for " + ilmergePath);
if (File.Exists(ilmergePath))
return true;
ilmergePath = null;
return false;
}
#endregion
#endregion
}
}
| |
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System.Collections.Generic;
using UMA;
namespace UMA.Examples
{
public class UMACharacterCustomization : MonoBehaviour
{
public UMAData umaData;
private UMADnaHumanoid umaDna;
private UMACrowd crowdHandle;
private Slider[] sliderControlList;
private Slider[] sliderControlList2;
private Slider[] sliderControlList3;
private byte bodyArea = 0;
private Transform myCamera;
private Transform bodyGO;
private Transform topHeadGO;
private Transform lowHeadGO;
/*private Color[] skinColors;
private Color[] eyeColors;
private Color[] hairColors;
private string[] femaleHairStyles;
private string[] maleHairStyles;
private string[,] facialHairStyles;*/
//private byte hairColor = 0;
private Transform panel;
private Vector3 lastPos = new Vector3(0, 1.2f, -2.4f);
private Quaternion lastRot;
private void Start()
{
panel = GameObject.Find("Canvas/Panel").transform;
bodyGO = panel.FindChild("Body");
topHeadGO = panel.FindChild("UpperHead");
lowHeadGO = panel.FindChild("LowerHead");
/*skinColors = new Color[]{
Color.white,
new Color32(233, 233, 233, 255),
new Color32(211, 211, 211, 255),
new Color32(189, 189, 189, 255),
new Color32(167, 167, 167, 255),
new Color32(145, 145, 145, 255),
new Color32(123, 123, 123, 255),
new Color32(101, 101, 101, 255),
new Color32(079, 079, 079, 255),
new Color32(057, 057, 057, 255),
};
eyeColors = new Color[]{
new Color32(165, 188, 255, 255),
new Color32(111, 147, 255, 255),
new Color32(122, 088, 045, 255),
new Color32(054, 135, 011, 255),
new Color32(127, 152, 79, 255),
};
hairColors = new Color[]{
Color.white,
new Color32(255, 246, 172, 255),
new Color32(255, 211, 103, 255),
new Color32(255, 204, 094, 255),
new Color32(191, 061, 039, 255),
new Color32(109, 031, 018, 255),
new Color32(159, 109, 000, 255),
new Color32(086, 048, 000, 255),
new Color32(039, 022, 000, 255),
Color.black,
};
femaleHairStyles = new string[]{
"FemaleShortHair01",
"FemaleLongHair01",
};
maleHairStyles = new string[]{
"MaleHair01",
"MaleHair02",
};
facialHairStyles = new string[,]{
{"",""},
{"MaleBeard01",""},
{"MaleBeard02",""},
{"MaleBeard03",""},
{"MaleBeard01","MaleBeard02"},
{"MaleBeard02","MaleBeard03"},
{"MaleBeard03","MaleBeard01"},
};*/
myCamera = GameObject.Find("NormalCamera").transform;
crowdHandle = GameObject.Find("UMACrowd").GetComponent<UMACrowd>();
sliderControlList = new Slider[19];
sliderControlList2 = new Slider[18];
sliderControlList3 = new Slider[14];
InitSliders();
int randomResult = Random.Range(0, 2);
GameObject myUma = crowdHandle.GenerateOneUMA(randomResult);
myUma.transform.localRotation = Quaternion.Euler(new Vector3(0, 180, 0));
GetUMAData(myUma);
}
private void GetUMAData(GameObject myUma)
{
UMAData tempUMA = myUma.GetComponent<UMAData>();
if (tempUMA)
{
umaData = tempUMA;
umaDna = umaData.umaRecipe.GetDna<UMADnaHumanoid>();
ReceiveValues();
}
}
private void Update()
{
if (Input.GetKey(KeyCode.E))
{
myCamera.transform.RotateAround(Vector3.zero, Vector3.up, -70 * Time.deltaTime);
}
if (Input.GetKey(KeyCode.Q))
{
myCamera.transform.RotateAround(Vector3.zero, Vector3.up, 70 * Time.deltaTime);
}
}
public void ButtonMale()
{
Destroy(GameObject.Find("UMACrowd").transform.GetChild(0).gameObject);
crowdHandle.ResetSpawnPos();
GameObject myUma = crowdHandle.GenerateOneUMA(0);
myUma.transform.localRotation = Quaternion.Euler(new Vector3(0, 180, 0));
GetUMAData(myUma);
if (bodyArea != 0)
{
float yPos = GameObject.Find("NoseMiddle").transform.position.y;
myCamera.transform.position = new Vector3(0, yPos + 0.05f, -0.62f);
if (bodyArea == 2)
panel.FindChild("LowerHead/FacialHair").gameObject.SetActive(true);
}
}
public void ButtonFemale()
{
Destroy(GameObject.Find("UMACrowd").transform.GetChild(0).gameObject);
crowdHandle.ResetSpawnPos();
GameObject myUma = crowdHandle.GenerateOneUMA(1);
myUma.transform.localRotation = Quaternion.Euler(new Vector3(0, 180, 0));
GetUMAData(myUma);
if (bodyArea != 0)
{
float yPos = GameObject.Find("NoseMiddle").transform.position.y;
myCamera.transform.position = new Vector3(0, yPos + 0.05f, -0.62f);
if (bodyArea == 2)
panel.FindChild("LowerHead/FacialHair").gameObject.SetActive(false);
}
}
public void ButtonBody()
{
if (bodyArea != 0)
{
bodyArea = 0;
bodyGO.gameObject.SetActive(true);
topHeadGO.gameObject.SetActive(false);
lowHeadGO.gameObject.SetActive(false);
ReceiveValues();
myCamera.position = lastPos;
myCamera.rotation = lastRot;
}
}
public void ButtonHead()
{
float yPos = GameObject.Find("NoseMiddle").transform.position.y;
lastPos = myCamera.position;
lastRot = myCamera.rotation;
myCamera.position = new Vector3(0, yPos + 0.05f, -0.62f);
myCamera.rotation = Quaternion.Euler(new Vector3(0, 0, 0));
if (bodyArea == 0)
{
bodyArea = 1;
bodyGO.gameObject.SetActive(false);
topHeadGO.gameObject.SetActive(true);
ReceiveValues();
}
}
public void ButtonHeadUpper()
{
if (bodyArea != 1)
{
bodyArea = 1;
topHeadGO.gameObject.SetActive(true);
lowHeadGO.gameObject.SetActive(false);
ReceiveValues();
}
}
public void ButtonHeadLower()
{
if (bodyArea != 2)
{
bodyArea = 2;
topHeadGO.gameObject.SetActive(false);
lowHeadGO.gameObject.SetActive(true);
ReceiveValues();
if (umaData.umaRecipe.raceData.raceName == "umaDnaMale")
panel.FindChild("LowerHead/FacialHair").gameObject.SetActive(true);
else
panel.FindChild("LowerHead/FacialHair").gameObject.SetActive(false);
}
}
private void InitSliders()
{
sliderControlList[0] = bodyGO.FindChild("Height").GetComponent<Slider>();
sliderControlList[1] = bodyGO.FindChild("HeadSize").GetComponent<Slider>();
sliderControlList[2] = bodyGO.FindChild("UpperMuscle").GetComponent<Slider>();
sliderControlList[3] = bodyGO.FindChild("LowerMuscle").GetComponent<Slider>();
sliderControlList[4] = bodyGO.FindChild("UpperWeight").GetComponent<Slider>();
sliderControlList[5] = bodyGO.FindChild("LowerWeight").GetComponent<Slider>();
sliderControlList[6] = bodyGO.FindChild("ArmLength").GetComponent<Slider>();
sliderControlList[7] = bodyGO.FindChild("ArmWidth").GetComponent<Slider>();
sliderControlList[8] = bodyGO.FindChild("ForearmLength").GetComponent<Slider>();
sliderControlList[9] = bodyGO.FindChild("ForearmWidth").GetComponent<Slider>();
sliderControlList[10] = bodyGO.FindChild("HandSize").GetComponent<Slider>();
sliderControlList[11] = bodyGO.FindChild("FeetSize").GetComponent<Slider>();
sliderControlList[12] = bodyGO.FindChild("LegSeparation").GetComponent<Slider>();
sliderControlList[13] = bodyGO.FindChild("LegSize").GetComponent<Slider>();
sliderControlList[14] = bodyGO.FindChild("BumSize").GetComponent<Slider>();
sliderControlList[15] = bodyGO.FindChild("BreastSize").GetComponent<Slider>();
sliderControlList[16] = bodyGO.FindChild("Belly").GetComponent<Slider>();
sliderControlList[17] = bodyGO.FindChild("Waist").GetComponent<Slider>();
//sliderControlList[18] = bodyGO.FindChild("SkinColor").GetComponent<Slider>();
//sliderControlList[18].maxValue = skinColors.Length - 1;
sliderControlList2[0] = topHeadGO.FindChild("HeadWidth").GetComponent<Slider>();
sliderControlList2[1] = topHeadGO.FindChild("ForeheadSize").GetComponent<Slider>();
sliderControlList2[2] = topHeadGO.FindChild("ForeheadPosition").GetComponent<Slider>();
sliderControlList2[3] = topHeadGO.FindChild("EarSize").GetComponent<Slider>();
sliderControlList2[4] = topHeadGO.FindChild("EarPosition").GetComponent<Slider>();
sliderControlList2[5] = topHeadGO.FindChild("EarRotation").GetComponent<Slider>();
sliderControlList2[6] = topHeadGO.FindChild("NoseSize").GetComponent<Slider>();
sliderControlList2[7] = topHeadGO.FindChild("NoseCurve").GetComponent<Slider>();
sliderControlList2[8] = topHeadGO.FindChild("NoseWidth").GetComponent<Slider>();
sliderControlList2[9] = topHeadGO.FindChild("NoseInclination").GetComponent<Slider>();
sliderControlList2[10] = topHeadGO.FindChild("NosePosition").GetComponent<Slider>();
sliderControlList2[11] = topHeadGO.FindChild("NoseFlatten").GetComponent<Slider>();
sliderControlList2[12] = topHeadGO.FindChild("NosePronounce").GetComponent<Slider>();
sliderControlList2[13] = topHeadGO.FindChild("EyeSize").GetComponent<Slider>();
sliderControlList2[14] = topHeadGO.FindChild("EyeRotation").GetComponent<Slider>();
//sliderControlList2[15] = topHeadGO.FindChild("HairColor").GetComponent<Slider>();
//sliderControlList2[15].maxValue = hairColors.Length - 1;
//sliderControlList2[16] = topHeadGO.FindChild("EyeColor").GetComponent<Slider>();
//sliderControlList2[16].maxValue = eyeColors.Length - 1;
//sliderControlList2[17] = topHeadGO.FindChild("HairType").GetComponent<Slider>();
//sliderControlList2[17].maxValue = femaleHairStyles.Length - 1;
topHeadGO.gameObject.SetActive(false);
sliderControlList3[0] = lowHeadGO.FindChild("CheekSize").GetComponent<Slider>();
sliderControlList3[1] = lowHeadGO.FindChild("CheekPosition").GetComponent<Slider>();
sliderControlList3[2] = lowHeadGO.FindChild("LowCheekPosition").GetComponent<Slider>();
sliderControlList3[3] = lowHeadGO.FindChild("LowCheekPronounce").GetComponent<Slider>();
sliderControlList3[4] = lowHeadGO.FindChild("LipSize").GetComponent<Slider>();
sliderControlList3[5] = lowHeadGO.FindChild("MouthSize").GetComponent<Slider>();
sliderControlList3[6] = lowHeadGO.FindChild("JawLength").GetComponent<Slider>();
sliderControlList3[7] = lowHeadGO.FindChild("JawWidth").GetComponent<Slider>();
sliderControlList3[8] = lowHeadGO.FindChild("JawPosition").GetComponent<Slider>();
sliderControlList3[9] = lowHeadGO.FindChild("Neck").GetComponent<Slider>();
sliderControlList3[10] = lowHeadGO.FindChild("ChinSize").GetComponent<Slider>();
sliderControlList3[11] = lowHeadGO.FindChild("ChinPronounce").GetComponent<Slider>();
sliderControlList3[12] = lowHeadGO.FindChild("ChinPosition").GetComponent<Slider>();
//sliderControlList3[13] = lowHeadGO.FindChild("FacialHair").GetComponent<Slider>();
//sliderControlList3[13].maxValue = facialHairStyles.Length - 1;
lowHeadGO.gameObject.SetActive(false);
}
public void UpdateUMAAtlas()
{
umaData.isTextureDirty = true;
umaData.Dirty();
}
public void UpdateUMAShape()
{
umaData.isShapeDirty = true;
umaData.Dirty();
}
private void ReceiveValues()
{
if (umaDna != null)
{
if (bodyArea == 0)
{
sliderControlList[0].value = umaDna.height;
sliderControlList[1].value = umaDna.headSize;
sliderControlList[2].value = umaDna.upperMuscle;
sliderControlList[3].value = umaDna.lowerMuscle;
sliderControlList[4].value = umaDna.upperWeight;
sliderControlList[5].value = umaDna.lowerWeight;
sliderControlList[6].value = umaDna.armLength;
sliderControlList[7].value = umaDna.armWidth;
sliderControlList[8].value = umaDna.forearmLength;
sliderControlList[9].value = umaDna.forearmWidth;
sliderControlList[10].value = umaDna.handsSize;
sliderControlList[11].value = umaDna.feetSize;
sliderControlList[12].value = umaDna.legSeparation;
sliderControlList[13].value = umaDna.legsSize;
sliderControlList[14].value = umaDna.gluteusSize;
sliderControlList[15].value = umaDna.breastSize;
sliderControlList[16].value = umaDna.belly;
sliderControlList[17].value = umaDna.waist;
//sliderControlList[18].value = (float)umaDna.Body[(int)Positions.BuildSlots.Body_Torso].colors[0] - 1;
}
else if (bodyArea == 1)
{
sliderControlList2[0].value = umaDna.headWidth;
sliderControlList2[1].value = umaDna.foreheadSize;
sliderControlList2[2].value = umaDna.foreheadPosition;
sliderControlList2[3].value = umaDna.earsSize;
sliderControlList2[4].value = umaDna.earsPosition;
sliderControlList2[5].value = umaDna.earsRotation;
sliderControlList2[6].value = umaDna.noseSize;
sliderControlList2[7].value = umaDna.noseCurve;
sliderControlList2[8].value = umaDna.noseWidth;
sliderControlList2[9].value = umaDna.noseInclination;
sliderControlList2[10].value = umaDna.nosePosition;
sliderControlList2[11].value = umaDna.nosePronounced;
sliderControlList2[12].value = umaDna.noseFlatten;
sliderControlList2[13].value = umaDna.eyeSize;
sliderControlList2[14].value = umaDna.eyeRotation;
/*if(umaDna.gender == 'F')
{
for(int i = 0; i < femaleHairStyles.Length; i++)
{
if(umaDna.Body[(int)Positions.BuildSlots.Body_Hair].element.Name == femaleHairStyles[i])
{
sliderControlList2[17].value = i;
break;
}
}
}
else
{
for(int i = 0; i < maleHairStyles.Length; i++)
{
if(umaDna.Body[(int)Positions.BuildSlots.Body_Hair].element.Name == maleHairStyles[i])
{
sliderControlList2[17].value = i;
break;
}
}
}*/
//sliderControlList2[15].value = (float)umaDna.Body[(int)Positions.BuildSlots.Body_Hair].colors[0] - 12;
//sliderControlList2[16].value = (float)umaDna.Body[(int)Positions.BuildSlots.Body_HeadEyes].colors[0] - 22;
}
else
{
sliderControlList3[0].value = umaDna.cheekSize;
sliderControlList3[1].value = umaDna.cheekPosition;
sliderControlList3[2].value = umaDna.lowCheekPronounced;
sliderControlList3[3].value = umaDna.lowCheekPosition;
sliderControlList3[4].value = umaDna.lipsSize;
sliderControlList3[5].value = umaDna.mouthSize;
sliderControlList3[6].value = umaDna.mandibleSize;
sliderControlList3[7].value = umaDna.jawsSize;
sliderControlList3[8].value = umaDna.jawsPosition;
sliderControlList3[9].value = umaDna.neckThickness;
sliderControlList3[10].value = umaDna.chinSize;
sliderControlList3[11].value = umaDna.chinPronounced;
sliderControlList3[12].value = umaDna.chinPosition;
/*if(umaDna.gender == 'M')
{
for(int i = 0; i < facialHairStyles.Length; i++)
{
if(umaDna.Body[(int)Positions.BuildSlots.Body_Beard].element.Name == facialHairStyles[i])
{
sliderControlList3[17].value = i;
break;
}
}
}*/
}
}
}
// Slider callbacks
public void OnHeightChange()
{
umaDna.height = sliderControlList[0].value;
UpdateUMAShape();
}
public void OnUpperMuscleChange()
{
umaDna.upperMuscle = sliderControlList[2].value;
UpdateUMAShape();
}
public void OnUpperWeightChange()
{
umaDna.upperWeight = sliderControlList[4].value;
UpdateUMAShape();
}
public void OnLowerMuscleChange()
{
umaDna.lowerMuscle = sliderControlList[3].value;
UpdateUMAShape();
}
public void OnLowerWeightChange()
{
umaDna.lowerWeight = sliderControlList[5].value;
UpdateUMAShape();
}
public void OnArmLengthChange()
{
umaDna.armLength = sliderControlList[6].value;
UpdateUMAShape();
}
public void OnForearmLengthChange()
{
umaDna.forearmLength = sliderControlList[8].value;
UpdateUMAShape();
}
public void OnLegSeparationChange()
{
umaDna.legSeparation = sliderControlList[12].value;
UpdateUMAShape();
}
public void OnHandSizeChange()
{
umaDna.handsSize = sliderControlList[10].value;
UpdateUMAShape();
}
public void OnFootSizeChange()
{
umaDna.feetSize = sliderControlList[11].value;
UpdateUMAShape();
}
public void OnLegSizeChange()
{
umaDna.legsSize = sliderControlList[13].value;
UpdateUMAShape();
}
public void OnArmWidthChange()
{
umaDna.armWidth = sliderControlList[7].value;
UpdateUMAShape();
}
public void OnForearmWidthChange()
{
umaDna.forearmWidth = sliderControlList[9].value;
UpdateUMAShape();
}
public void OnBreastSizeChange()
{
umaDna.breastSize = sliderControlList[15].value;
UpdateUMAShape();
}
public void OnBellySizeChange()
{
umaDna.belly = sliderControlList[16].value;
UpdateUMAShape();
}
public void OnWaistSizeChange()
{
umaDna.waist = sliderControlList[17].value;
UpdateUMAShape();
}
public void OnGluteusSizeChange()
{
umaDna.gluteusSize = sliderControlList[14].value;
UpdateUMAShape();
}
public void OnHeadSizeChange()
{
umaDna.headSize = sliderControlList[1].value;
UpdateUMAShape();
}
public void OnHeadWidthChange()
{
umaDna.headWidth = sliderControlList2[0].value;
UpdateUMAShape();
}
public void OnNeckThicknessChange()
{
umaDna.neckThickness = sliderControlList3[9].value;
UpdateUMAShape();
}
public void OnEarSizeChange()
{
umaDna.earsSize = sliderControlList2[3].value;
UpdateUMAShape();
}
public void OnEarPositionChange()
{
umaDna.earsPosition = sliderControlList2[4].value;
UpdateUMAShape();
}
public void OnEarRotationChange()
{
umaDna.earsRotation = sliderControlList2[5].value;
UpdateUMAShape();
}
public void OnNoseSizeChange()
{
umaDna.noseSize = sliderControlList2[6].value;
UpdateUMAShape();
}
public void OnNoseCurveChange()
{
umaDna.noseCurve = sliderControlList2[7].value;
UpdateUMAShape();
}
public void OnNoseWidthChange()
{
umaDna.noseWidth = sliderControlList2[8].value;
UpdateUMAShape();
}
public void OnNoseInclinationChange()
{
umaDna.noseInclination = sliderControlList2[9].value;
UpdateUMAShape();
}
public void OnNosePositionChange()
{
umaDna.nosePosition = sliderControlList2[10].value;
UpdateUMAShape();
}
public void OnNosePronouncedChange()
{
umaDna.nosePronounced = sliderControlList2[11].value;
UpdateUMAShape();
}
public void OnNoseFlattenChange()
{
umaDna.noseFlatten = sliderControlList2[12].value;
UpdateUMAShape();
}
public void OnChinSizeChange()
{
umaDna.chinSize = sliderControlList3[10].value;
UpdateUMAShape();
}
public void OnChinPronouncedChange()
{
umaDna.chinPronounced = sliderControlList3[11].value;
UpdateUMAShape();
}
public void OnChinPositionChange()
{
umaDna.chinPosition = sliderControlList3[12].value;
UpdateUMAShape();
}
public void OnMandibleSizeChange()
{
umaDna.mandibleSize = sliderControlList3[6].value;
UpdateUMAShape();
}
public void OnJawSizeChange()
{
umaDna.jawsSize = sliderControlList3[7].value;
UpdateUMAShape();
}
public void OnJawPositionChange()
{
umaDna.jawsPosition = sliderControlList3[8].value;
UpdateUMAShape();
}
public void OnCheekSizeChange()
{
umaDna.cheekSize = sliderControlList3[0].value;
UpdateUMAShape();
}
public void OnCheekPositionChange()
{
umaDna.cheekPosition = sliderControlList3[1].value;
UpdateUMAShape();
}
public void OnCheekLowPronouncedChange()
{
umaDna.lowCheekPronounced = sliderControlList3[2].value;
UpdateUMAShape();
}
public void OnForeheadSizeChange()
{
umaDna.foreheadSize = sliderControlList2[1].value;
UpdateUMAShape();
}
public void OnForeheadPositionChange()
{
umaDna.foreheadPosition = sliderControlList2[2].value;
UpdateUMAShape();
}
public void OnLipSizeChange()
{
umaDna.lipsSize = sliderControlList3[4].value;
UpdateUMAShape();
}
public void OnMouthSizeChange()
{
umaDna.mouthSize = sliderControlList3[5].value;
UpdateUMAShape();
}
public void OnEyeSizechange()
{
umaDna.eyeSize = sliderControlList2[13].value;
UpdateUMAShape();
}
public void OnEyeRotationChange()
{
umaDna.eyeRotation = sliderControlList2[14].value;
UpdateUMAShape();
}
public void OnLowCheekPositionChange()
{
umaDna.lowCheekPosition = sliderControlList3[3].value;
UpdateUMAShape();
}
/*private void TransferValues()
{
if(umaDna != null)
{
if(bodyArea == 0)
{
//byte skinColor = (byte)(sliderControlList[18].value);
//AddParts(umaDna.gender, skinColors[skinColor]);
}
else if(bodyArea == 1)
{
//hairColor = (byte)(sliderControlList2[15].value);
//byte hairStyle = (byte)(sliderControlList2[17].value);
//byte eyeColor = (byte)(sliderControlList2[16].value);
if(umaDna.gender == 'F')
{
umaDnaoidStructure.BodyAdd(umaDna, "umaDna Female HeadEyes 01", eyeColors[eyeColor]);
umaDnaoidStructure.BodyAdd(umaDna, femaleHairStyles[hairStyle], hairColors[hairColor]);
}
else
{
umaDnaoidStructure.BodyAdd(umaDna, "umaDna Male HeadEyes 01", eyeColors[eyeColor]);
umaDnaoidStructure.BodyAdd(umaDna, maleHairStyles[hairStyle], hairColors[hairColor]);
}
}
else
{
if(umaData.umaRecipe.raceData.raceName == "umaDnaMale")
{
byte beardStyle = (byte)(sliderControlList3[13].value);
if(facialHairStyles[beardStyle] != "")
umaDnaoidStructure.BodyAdd(umaDna, facialHairStyles[beardStyle], hairColors[hairColor]);
else
umaDnaoidStructure.BodyRemove(umaDna, (int)Positions.BuildSlots.Body_Beard);
}
}
}
}*/
}
}
| |
#region File Description
//-----------------------------------------------------------------------------
// MenuEntry.cs
//
// XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#endregion
#region Using Statements
using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
#endregion
namespace MahjongXNA
{
/// <summary>
/// Helper class represents a single entry in a MenuScreen. By default this
/// just draws the entry text string, but it can be customized to display menu
/// entries in different ways. This also provides an event that will be raised
/// when the menu entry is selected.
/// </summary>
class MenuEntry
{
#region Fields
/// <summary>
/// The text rendered for this entry.
/// </summary>
string text;
/// <summary>
/// Tracks a fading selection effect on the entry.
/// </summary>
/// <remarks>
/// The entries transition out of the selection effect when they are deselected.
/// </remarks>
float selectionFade;
/// <summary>
/// The position at which the entry is drawn. This is set by the MenuScreen
/// each frame in Update.
/// </summary>
Vector2 position;
#endregion
#region Properties
/// <summary>
/// Gets or sets the text of this menu entry.
/// </summary>
public virtual string Text
{
get { return text; }
set { text = value; }
}
/// <summary>
/// Gets or sets the position at which to draw this menu entry.
/// </summary>
public Vector2 Position
{
get { return position; }
set { position = value; }
}
#endregion
#region Events
/// <summary>
/// Event raised when the menu entry is selected.
/// </summary>
public event EventHandler<PlayerIndexEventArgs> Selected;
public event EventHandler<PlayerIndexEventArgs> SelectedLeftwards;
/// <summary>
/// Method for raising the Selected event.
/// </summary>
protected internal virtual void OnSelectEntry(PlayerIndex playerIndex)
{
if (Selected != null)
Selected(this, new PlayerIndexEventArgs(playerIndex));
}
protected internal virtual void OnSelectEntryLeftwards(PlayerIndex playerIndex)
{
if (SelectedLeftwards != null)
SelectedLeftwards(this, new PlayerIndexEventArgs(playerIndex));
}
#endregion
#region Initialization
/// <summary>
/// Constructs a new menu entry with the specified text.
/// </summary>
public MenuEntry(string text)
{
this.text = text;
this.SelectedColor = Color.Yellow;
this.UnselectedColor = Color.White;
}
#endregion
#region Update and Draw
/// <summary>
/// Updates the menu entry.
/// </summary>
public virtual void Update(MenuScreen screen, bool isSelected, GameTime gameTime)
{
// there is no such thing as a selected item on Windows Phone, so we always
// force isSelected to be false
#if WINDOWS_PHONE
isSelected = false;
#endif
// When the menu selection changes, entries gradually fade between
// their selected and deselected appearance, rather than instantly
// popping to the new state.
float fadeSpeed = (float)gameTime.ElapsedGameTime.TotalSeconds * 4;
if (isSelected)
selectionFade = Math.Min(selectionFade + fadeSpeed, 1);
else
selectionFade = Math.Max(selectionFade - fadeSpeed, 0);
}
public Color SelectedColor { get; set; }
public Color UnselectedColor { get; set; }
/// <summary>
/// Draws the menu entry. This can be overridden to customize the appearance.
/// </summary>
public virtual void Draw(MenuScreen screen, bool isSelected, GameTime gameTime)
{
// there is no such thing as a selected item on Windows Phone, so we always
// force isSelected to be false
#if WINDOWS_PHONE
isSelected = false;
#endif
// Draw the selected entry in yellow, otherwise white.
Color color = isSelected ? SelectedColor : UnselectedColor;
// Pulsate the size of the selected menu entry.
double time = gameTime.TotalGameTime.TotalSeconds;
float pulsate = (float)Math.Sin(time * 6) + 1;
float scale = 1 + pulsate * 0.05f * selectionFade;
// Modify the alpha to fade text out during transitions.
color *= screen.TransitionAlpha;
// Draw text, centered on the middle of each line.
ScreenManager screenManager = screen.ScreenManager;
SpriteBatch spriteBatch = screenManager.SpriteBatch;
SpriteFont font = screenManager.Font;
Vector2 origin = new Vector2(0, font.LineSpacing / 2);
spriteBatch.DrawString(font, Text, position, color, 0,
origin, scale, SpriteEffects.None, 0);
}
/// <summary>
/// Queries how much space this menu entry requires.
/// </summary>
public virtual int GetHeight(MenuScreen screen)
{
return screen.ScreenManager.Font.LineSpacing;
}
/// <summary>
/// Queries how wide the entry is, used for centering on the screen.
/// </summary>
public virtual int GetWidth(MenuScreen screen)
{
return (int)screen.ScreenManager.Font.MeasureString(Text).X;
}
#endregion
}
}
| |
using DotBPE.Gateway.Internal;
using DotBPE.Rpc;
using DotBPE.Rpc.Client;
using Microsoft.AspNetCore.Routing;
using Microsoft.AspNetCore.Routing.Patterns;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
namespace DotBPE.Gateway
{
internal class HttpApiProviderServiceBinder<TService> where TService : class
{
private readonly RpcGatewayOption _gatewayOption;
private readonly RpcServiceMethodProviderContext<TService> _context;
private readonly IClientProxy _clientProxy;
private readonly IJsonParser _jsonParser;
private readonly ILoggerFactory _loggerFactory;
private readonly ILogger _logger;
private readonly Type _serviceType;
private readonly MethodInfo _dynamicCreateGenericMethod;
private readonly MethodInfo _dynamicAddGenericMethod;
public HttpApiProviderServiceBinder(
RpcServiceMethodProviderContext<TService> context,
RpcGatewayOption gatewayOption,
IClientProxy clientProxy,
IJsonParser jsonParser,
ILoggerFactory loggerFactory
)
{
_serviceType = typeof(TService);
_gatewayOption = gatewayOption;
_context = context;
_clientProxy = clientProxy;
_jsonParser = jsonParser;
_loggerFactory = loggerFactory;
_logger = loggerFactory.CreateLogger<HttpApiProviderServiceBinder<TService>>();
_dynamicCreateGenericMethod = this.GetType().GetMethod("CreateMethod", BindingFlags.NonPublic | BindingFlags.Instance);
_dynamicAddGenericMethod = this.GetType().GetMethod("AddMethod", BindingFlags.NonPublic | BindingFlags.Instance);
}
public void BindAll()
{
if (!_serviceType.IsInterface)
return;
//this._logger.LogInformation(type.FullName);
var sAttr = _serviceType.GetCustomAttribute<RpcServiceAttribute>();
if (sAttr == null)
return;
AddRpcService( sAttr, new string[] {});
}
private void AddRpcService(RpcServiceAttribute sAttr, params string[] categories)
{
var methods = _serviceType.GetMethods();
foreach (var m in methods)
{
var mAttr = m.GetCustomAttribute<RpcMethodAttribute>();
if (mAttr == null)
continue;
var rAttr = m.GetCustomAttribute<RouterAttribute>();
if (rAttr == null)
continue;
Type returnType = m.ReturnType;
Type requestType = m.GetParameters()[0].ParameterType;
if (!returnType.IsGenericType && returnType.GenericTypeArguments.Length !=1)
{
//TODO:WARNING~
continue;
}
var returnGenericTypes = returnType.GenericTypeArguments[0]; //RpcReslut<>
if(!returnGenericTypes.IsGenericType || returnGenericTypes.GetGenericTypeDefinition() != typeof(RpcResult<>))
{
//TODO:WARNING~
continue;
}
var responseType = returnGenericTypes.GetGenericArguments()[0];
if ((categories != null && categories.Any() && categories.Contains(rAttr.Category))
|| "default".Equals(rAttr.Category, StringComparison.OrdinalIgnoreCase)
)
{
DynamicAddMethod(m, sAttr, mAttr, rAttr, requestType, responseType);
}
}
}
private void DynamicAddMethod(MethodInfo m, RpcServiceAttribute sAttr, RpcMethodAttribute mAttr, RouterAttribute rAttr, Type requestType, Type responseType)
{
var dynamicCreateMethodInvoker = _dynamicCreateGenericMethod.MakeGenericMethod(requestType, responseType);
var dynamicAddMethodInvoker = _dynamicAddGenericMethod.MakeGenericMethod(requestType, responseType);
object method = dynamicCreateMethodInvoker.Invoke(this, new object[] { _serviceType.Name, m });
dynamicAddMethodInvoker.Invoke(this, new object[] { method, sAttr, mAttr, rAttr });
}
private Method<TRequest,TResponse> CreateMethod<TRequest, TResponse>(string serviceName,MethodInfo hanlder)
where TRequest : class
where TResponse : class
{
return new Method<TRequest, TResponse>(serviceName, hanlder);
}
private void AddMethod<TRequest, TResponse>(Method<TRequest, TResponse> method, RpcServiceAttribute sAttr, RpcMethodAttribute mAttr, RouterAttribute rAttr)
where TRequest : class
where TResponse : class
{
if(rAttr.AcceptVerb== RestfulVerb.Any)
{
var anyVerbs = new RestfulVerb[] { RestfulVerb.Get, RestfulVerb.Post };
foreach(var verb in anyVerbs)
{
var httpApiOptions = new HttpApiOptions()
{
AcceptVerb = verb,
Category = rAttr.Category,
Pattern = rAttr.Path,
PluginName = rAttr.PluginName,
Version = rAttr.Version
};
AddMethodCore(method, httpApiOptions);
}
}
else
{
var httpApiOptions = new HttpApiOptions()
{
AcceptVerb = rAttr.AcceptVerb,
Category = rAttr.Category,
Pattern = rAttr.Path,
PluginName = rAttr.PluginName,
Version = rAttr.Version
};
AddMethodCore(method, httpApiOptions);
}
}
private void AddMethodCore<TRequest, TResponse>(Method<TRequest, TResponse> method, HttpApiOptions httpApiOptions)
where TRequest : class
where TResponse : class
{
try
{
var pattern = httpApiOptions.Pattern;
if (!pattern.StartsWith('/'))
{
// This validation is consistent with rpc-gateway code generation.
// We should match their validation to be a good member of the eco-system.
throw new InvalidOperationException($"Path template must start with /: {pattern}");
}
var methodContext = MethodOptions.Create();
var routePattern = RoutePatternFactory.Parse(pattern);
var parameters = method.HandlerMethod.GetParameters();
if (parameters.Length == 1)
{
var (invoker, metadata) = CreateModelCore<RpcServiceMethod<TService, TRequest, TResponse>, TRequest, TResponse>(method,httpApiOptions);
var methodInvoker = new RpcServiceMethodInvoker<TService, TRequest, TResponse>(invoker,null,0, method, methodContext, _clientProxy);
var unaryServerCallHandler = new RpcServiceCallHandler<TService, TRequest, TResponse>(_gatewayOption, methodInvoker, _jsonParser, httpApiOptions, _loggerFactory);
_context.AddMethod<TRequest, TResponse>(method, routePattern, metadata, unaryServerCallHandler.HandleCallAsync);
}
else //has timeout
{
var (invokerWithTimeout, metadata) = CreateModelCore<RpcServiceMethodWithTimeout<TService, TRequest, TResponse>, TRequest, TResponse>(method, httpApiOptions);
var methodInvoker = new RpcServiceMethodInvoker<TService, TRequest, TResponse>(null, invokerWithTimeout, (int)parameters[1].DefaultValue, method, methodContext, _clientProxy);
var unaryServerCallHandler = new RpcServiceCallHandler<TService, TRequest, TResponse>(_gatewayOption, methodInvoker, _jsonParser, httpApiOptions, _loggerFactory);
_context.AddMethod<TRequest, TResponse>(method, routePattern, metadata, unaryServerCallHandler.HandleCallAsync);
}
}
catch (Exception ex)
{
throw new InvalidOperationException($"Error binding {method.Name} on {typeof(TService).Name} to HTTP API.", ex);
}
}
private (TDelegate invoker, List<object> metadata) CreateModelCore<TDelegate, TRequest, TResponse>(
Method<TRequest, TResponse> method,
HttpApiOptions httpApiOptions
)
where TDelegate : Delegate
where TRequest : class
where TResponse : class
{
var invoker = (TDelegate)Delegate.CreateDelegate(typeof(TDelegate), method.HandlerMethod);
var metadata = new List<object>();
// Add type metadata first so it has a lower priority
//metadata.AddRange(typeof(TService).GetCustomAttributes(inherit: true));
// Add method metadata last so it has a higher priority
//metadata.AddRange(handlerMethod.GetCustomAttributes(inherit: true));
metadata.Add(new HttpMethodMetadata(new[] { httpApiOptions.AcceptVerb.ToString().ToUpper() }));
// Add service method descriptor.
// Is used by swagger generation to identify HTTP APIs.
metadata.Add(new RpcHttpMetadata(method.HandlerMethod, httpApiOptions,typeof(TRequest),typeof(TResponse)));
return (invoker, metadata);
}
}
}
| |
// 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.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Threading;
using Microsoft.Win32.SafeHandles;
using System.Diagnostics;
namespace System.Net.Sockets
{
internal partial class SafeCloseSocket :
#if DEBUG
DebugSafeHandleMinusOneIsInvalid
#else
SafeHandleMinusOneIsInvalid
#endif
{
private int _receiveTimeout = -1;
private int _sendTimeout = -1;
private bool _nonBlocking;
private SocketAsyncContext _asyncContext;
public SocketAsyncContext AsyncContext
{
get
{
if (Volatile.Read(ref _asyncContext) == null)
{
Interlocked.CompareExchange(ref _asyncContext, new SocketAsyncContext(this), null);
}
return _asyncContext;
}
}
public bool IsNonBlocking
{
get
{
return _nonBlocking;
}
set
{
_nonBlocking = value;
//
// If transitioning to non-blocking, we need to set the native socket to non-blocking mode.
// If we ever transition back to blocking, we keep the native socket in non-blocking mode, and emulate
// blocking. This avoids problems with switching to native blocking while there are pending async
// operations.
//
if (value)
{
AsyncContext.SetNonBlocking();
}
}
}
public int ReceiveTimeout
{
get
{
return _receiveTimeout;
}
set
{
Debug.Assert(value == -1 || value > 0);
_receiveTimeout = value;;
}
}
public int SendTimeout
{
get
{
return _sendTimeout;
}
set
{
Debug.Assert(value == -1 || value > 0);
_sendTimeout = value;
}
}
public unsafe static SafeCloseSocket CreateSocket(int fileDescriptor)
{
return CreateSocket(InnerSafeCloseSocket.CreateSocket(fileDescriptor));
}
public unsafe static SocketError CreateSocket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType, out SafeCloseSocket socket)
{
SocketError errorCode;
socket = CreateSocket(InnerSafeCloseSocket.CreateSocket(addressFamily, socketType, protocolType, out errorCode));
return errorCode;
}
public unsafe static SocketError Accept(SafeCloseSocket socketHandle, byte[] socketAddress, ref int socketAddressSize, out SafeCloseSocket socket)
{
SocketError errorCode;
socket = CreateSocket(InnerSafeCloseSocket.Accept(socketHandle, socketAddress, ref socketAddressSize, out errorCode));
return errorCode;
}
private void InnerReleaseHandle()
{
if (_asyncContext != null)
{
_asyncContext.Close();
}
}
internal sealed partial class InnerSafeCloseSocket : SafeHandleMinusOneIsInvalid
{
private unsafe SocketError InnerReleaseHandle()
{
int errorCode;
// If _blockable was set in BlockingRelease, it's safe to block here, which means
// we can honor the linger options set on the socket. It also means closesocket() might return WSAEWOULDBLOCK, in which
// case we need to do some recovery.
if (_blockable)
{
if (GlobalLog.IsEnabled)
{
GlobalLog.Print("SafeCloseSocket::ReleaseHandle(handle:" + handle.ToString("x") + ") Following 'blockable' branch.");
}
errorCode = Interop.Sys.Close(handle);
if (errorCode == -1)
{
errorCode = (int)Interop.Sys.GetLastError();
}
if (GlobalLog.IsEnabled)
{
GlobalLog.Print("SafeCloseSocket::ReleaseHandle(handle:" + handle.ToString("x") + ") close()#1:" + errorCode.ToString());
}
#if DEBUG
_closeSocketHandle = handle;
_closeSocketResult = SocketPal.GetSocketErrorForErrorCode((Interop.Error)errorCode);
#endif
// If it's not EWOULDBLOCK, there's no more recourse - we either succeeded or failed.
if (errorCode != (int)Interop.Error.EWOULDBLOCK)
{
return SocketPal.GetSocketErrorForErrorCode((Interop.Error)errorCode);
}
// The socket must be non-blocking with a linger timeout set.
// We have to set the socket to blocking.
errorCode = Interop.Sys.Fcntl.DangerousSetIsNonBlocking(handle, 0);
if (errorCode == 0)
{
// The socket successfully made blocking; retry the close().
errorCode = Interop.Sys.Close(handle);
if (GlobalLog.IsEnabled)
{
GlobalLog.Print("SafeCloseSocket::ReleaseHandle(handle:" + handle.ToString("x") + ") close()#2:" + errorCode.ToString());
}
#if DEBUG
_closeSocketHandle = handle;
_closeSocketResult = SocketPal.GetSocketErrorForErrorCode((Interop.Error)errorCode);
#endif
return SocketPal.GetSocketErrorForErrorCode((Interop.Error)errorCode);
}
// The socket could not be made blocking; fall through to the regular abortive close.
}
// By default or if CloseAsIs() path failed, set linger timeout to zero to get an abortive close (RST).
var linger = new Interop.Sys.LingerOption {
OnOff = 1,
Seconds = 0
};
errorCode = (int)Interop.Sys.DangerousSetLingerOption((int)handle, &linger);
#if DEBUG
_closeSocketLinger = SocketPal.GetSocketErrorForErrorCode((Interop.Error)errorCode);
#endif
if (GlobalLog.IsEnabled)
{
GlobalLog.Print("SafeCloseSocket::ReleaseHandle(handle:" + handle.ToString("x") + ") setsockopt():" + errorCode.ToString());
}
if (errorCode != 0 && errorCode != (int)Interop.Error.EINVAL && errorCode != (int)Interop.Error.ENOPROTOOPT)
{
// Too dangerous to try closesocket() - it might block!
return SocketPal.GetSocketErrorForErrorCode((Interop.Error)errorCode);
}
errorCode = Interop.Sys.Close(handle);
#if DEBUG
_closeSocketHandle = handle;
_closeSocketResult = SocketPal.GetSocketErrorForErrorCode((Interop.Error)errorCode);
#endif
if (GlobalLog.IsEnabled)
{
GlobalLog.Print("SafeCloseSocket::ReleaseHandle(handle:" + handle.ToString("x") + ") close#3():" + (errorCode == -1 ? (int)Interop.Sys.GetLastError() : errorCode).ToString());
}
return SocketPal.GetSocketErrorForErrorCode((Interop.Error)errorCode);
}
public static InnerSafeCloseSocket CreateSocket(int fileDescriptor)
{
var res = new InnerSafeCloseSocket();
res.SetHandle((IntPtr)fileDescriptor);
return res;
}
public static unsafe InnerSafeCloseSocket CreateSocket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType, out SocketError errorCode)
{
int fd;
Interop.Error error = Interop.Sys.Socket(addressFamily, socketType, protocolType, &fd);
if (error == Interop.Error.SUCCESS)
{
Debug.Assert(fd != -1);
errorCode = SocketError.Success;
// The socket was created successfully; enable IPV6_V6ONLY by default for AF_INET6 sockets.
if (addressFamily == AddressFamily.InterNetworkV6)
{
int on = 1;
error = Interop.Sys.DangerousSetSockOpt(fd, SocketOptionLevel.IPv6, SocketOptionName.IPv6Only, (byte*)&on, sizeof(int));
if (error != Interop.Error.SUCCESS)
{
Interop.Sys.Close((IntPtr)fd);
fd = -1;
errorCode = SocketPal.GetSocketErrorForErrorCode(error);
}
}
}
else
{
Debug.Assert(fd == -1);
errorCode = SocketPal.GetSocketErrorForErrorCode(error);
}
var res = new InnerSafeCloseSocket();
res.SetHandle((IntPtr)fd);
return res;
}
public static unsafe InnerSafeCloseSocket Accept(SafeCloseSocket socketHandle, byte[] socketAddress, ref int socketAddressLen, out SocketError errorCode)
{
int acceptedFd;
if (!socketHandle.IsNonBlocking)
{
errorCode = socketHandle.AsyncContext.Accept(socketAddress, ref socketAddressLen, -1, out acceptedFd);
}
else
{
SocketPal.TryCompleteAccept(socketHandle, socketAddress, ref socketAddressLen, out acceptedFd, out errorCode);
}
var res = new InnerSafeCloseSocket();
res.SetHandle((IntPtr)acceptedFd);
return res;
}
}
}
}
| |
//
// Options.cs
//
// Authors:
// Jonathan Pryor <jpryor@novell.com>
//
// Copyright (C) 2008 Novell (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// Compile With:
// gmcs -debug+ -r:System.Core Options.cs -o:NDesk.Options.dll
// gmcs -debug+ -d:LINQ -r:System.Core Options.cs -o:NDesk.Options.dll
//
// The LINQ version just changes the implementation of
// OptionSet.Parse(IEnumerable<string>), and confers no semantic changes.
//
// A Getopt::Long-inspired option parsing library for C#.
//
// NDesk.Options.OptionSet is built upon a key/value table, where the
// key is a option format string and the value is a delegate that is
// invoked when the format string is matched.
//
// Option format strings:
// Regex-like BNF Grammar:
// name: .+
// type: [=:]
// sep: ( [^{}]+ | '{' .+ '}' )?
// aliases: ( name type sep ) ( '|' name type sep )*
//
// Each '|'-delimited name is an alias for the associated action. If the
// format string ends in a '=', it has a required value. If the format
// string ends in a ':', it has an optional value. If neither '=' or ':'
// is present, no value is supported. `=' or `:' need only be defined on one
// alias, but if they are provided on more than one they must be consistent.
//
// Each alias portion may also end with a "key/value separator", which is used
// to split option values if the option accepts > 1 value. If not specified,
// it defaults to '=' and ':'. If specified, it can be any character except
// '{' and '}' OR the *string* between '{' and '}'. If no separator should be
// used (i.e. the separate values should be distinct arguments), then "{}"
// should be used as the separator.
//
// Options are extracted either from the current option by looking for
// the option name followed by an '=' or ':', or is taken from the
// following option IFF:
// - The current option does not contain a '=' or a ':'
// - The current option requires a value (i.e. not a Option type of ':')
//
// The `name' used in the option format string does NOT include any leading
// option indicator, such as '-', '--', or '/'. All three of these are
// permitted/required on any named option.
//
// Option bundling is permitted so long as:
// - '-' is used to start the option group
// - all of the bundled options are a single character
// - at most one of the bundled options accepts a value, and the value
// provided starts from the next character to the end of the string.
//
// This allows specifying '-a -b -c' as '-abc', and specifying '-D name=value'
// as '-Dname=value'.
//
// Option processing is disabled by specifying "--". All options after "--"
// are returned by OptionSet.Parse() unchanged and unprocessed.
//
// Unprocessed options are returned from OptionSet.Parse().
//
// Examples:
// int verbose = 0;
// OptionSet p = new OptionSet ()
// .Add ("v", v => ++verbose)
// .Add ("name=|value=", v => Console.WriteLine (v));
// p.Parse (new string[]{"-v", "--v", "/v", "-name=A", "/name", "B", "extra"});
//
// The above would parse the argument string array, and would invoke the
// lambda expression three times, setting `verbose' to 3 when complete.
// It would also print out "A" and "B" to standard output.
// The returned array would contain the string "extra".
//
// C# 3.0 collection initializers are supported and encouraged:
// var p = new OptionSet () {
// { "h|?|help", v => ShowHelp () },
// };
//
// System.ComponentModel.TypeConverter is also supported, allowing the use of
// custom data types in the callback type; TypeConverter.ConvertFromString()
// is used to convert the value option to an instance of the specified
// type:
//
// var p = new OptionSet () {
// { "foo=", (Foo f) => Console.WriteLine (f.ToString ()) },
// };
//
// Random other tidbits:
// - Boolean options (those w/o '=' or ':' in the option format string)
// are explicitly enabled if they are followed with '+', and explicitly
// disabled if they are followed with '-':
// string a = null;
// var p = new OptionSet () {
// { "a", s => a = s },
// };
// p.Parse (new string[]{"-a"}); // sets v != null
// p.Parse (new string[]{"-a+"}); // sets v != null
// p.Parse (new string[]{"-a-"}); // sets v == null
//
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.Runtime.Serialization;
using System.Security.Permissions;
using System.Text;
using System.Text.RegularExpressions;
using System.Linq;
namespace NDesk.Options {
public class OptionValueCollection : IList, IList<string> {
List<string> values = new List<string> ();
OptionContext c;
internal OptionValueCollection (OptionContext c)
{
this.c = c;
}
#region ICollection
void ICollection.CopyTo (Array array, int index) {(values as ICollection).CopyTo (array, index);}
bool ICollection.IsSynchronized {get {return (values as ICollection).IsSynchronized;}}
object ICollection.SyncRoot {get {return (values as ICollection).SyncRoot;}}
#endregion
#region ICollection<T>
public void Add (string item) {values.Add (item);}
public void Clear () {values.Clear ();}
public bool Contains (string item) {return values.Contains (item);}
public void CopyTo (string[] array, int arrayIndex) {values.CopyTo (array, arrayIndex);}
public bool Remove (string item) {return values.Remove (item);}
public int Count {get {return values.Count;}}
public bool IsReadOnly {get {return false;}}
#endregion
#region IEnumerable
IEnumerator IEnumerable.GetEnumerator () {return values.GetEnumerator ();}
#endregion
#region IEnumerable<T>
public IEnumerator<string> GetEnumerator () {return values.GetEnumerator ();}
#endregion
#region IList
int IList.Add (object value) {return (values as IList).Add (value);}
bool IList.Contains (object value) {return (values as IList).Contains (value);}
int IList.IndexOf (object value) {return (values as IList).IndexOf (value);}
void IList.Insert (int index, object value) {(values as IList).Insert (index, value);}
void IList.Remove (object value) {(values as IList).Remove (value);}
void IList.RemoveAt (int index) {(values as IList).RemoveAt (index);}
bool IList.IsFixedSize {get {return false;}}
object IList.this [int index] {get {return this [index];} set {(values as IList)[index] = value;}}
#endregion
#region IList<T>
public int IndexOf (string item) {return values.IndexOf (item);}
public void Insert (int index, string item) {values.Insert (index, item);}
public void RemoveAt (int index) {values.RemoveAt (index);}
private void AssertValid (int index)
{
if (c.Option == null)
throw new InvalidOperationException ("OptionContext.Option is null.");
if (index >= c.Option.MaxValueCount)
throw new ArgumentOutOfRangeException ("index");
if (c.Option.OptionValueType == OptionValueType.Required &&
index >= values.Count)
throw new OptionException (string.Format (
c.OptionSet.MessageLocalizer ("Missing required value for option '{0}'."), c.OptionName),
c.OptionName);
}
public string this [int index] {
get {
AssertValid (index);
return index >= values.Count ? null : values [index];
}
set {
values [index] = value;
}
}
#endregion
public List<string> ToList ()
{
return new List<string> (values);
}
public string[] ToArray ()
{
return values.ToArray ();
}
public override string ToString ()
{
return string.Join (", ", values.ToArray ());
}
}
public class OptionContext {
private Option option;
private string name;
private int index;
private OptionSet set;
private OptionValueCollection c;
public OptionContext (OptionSet set)
{
this.set = set;
this.c = new OptionValueCollection (this);
}
public Option Option {
get {return option;}
set {option = value;}
}
public string OptionName {
get {return name;}
set {name = value;}
}
public int OptionIndex {
get {return index;}
set {index = value;}
}
public OptionSet OptionSet {
get {return set;}
}
public OptionValueCollection OptionValues {
get {return c;}
}
}
public enum OptionValueType {
None,
Optional,
Required,
}
public abstract class Option {
string prototype, description;
string[] names;
OptionValueType type;
int count;
string[] separators;
protected Option (string prototype, string description)
: this (prototype, description, 1)
{
}
protected Option (string prototype, string description, int maxValueCount)
{
if (prototype == null)
throw new ArgumentNullException ("prototype");
if (prototype.Length == 0)
throw new ArgumentException ("Cannot be the empty string.", "prototype");
if (maxValueCount < 0)
throw new ArgumentOutOfRangeException ("maxValueCount");
this.prototype = prototype;
this.names = prototype.Split ('|');
this.description = description;
this.count = maxValueCount;
this.type = ParsePrototype ();
if (this.count == 0 && type != OptionValueType.None)
throw new ArgumentException (
"Cannot provide maxValueCount of 0 for OptionValueType.Required or " +
"OptionValueType.Optional.",
"maxValueCount");
if (this.type == OptionValueType.None && maxValueCount > 1)
throw new ArgumentException (
string.Format ("Cannot provide maxValueCount of {0} for OptionValueType.None.", maxValueCount),
"maxValueCount");
if (Array.IndexOf (names, "<>") >= 0 &&
((names.Length == 1 && this.type != OptionValueType.None) ||
(names.Length > 1 && this.MaxValueCount > 1)))
throw new ArgumentException (
"The default option handler '<>' cannot require values.",
"prototype");
}
public string Prototype {get {return prototype;}}
public string Description {get {return description;}}
public OptionValueType OptionValueType {get {return type;}}
public int MaxValueCount {get {return count;}}
public string[] GetNames ()
{
return (string[]) names.Clone ();
}
public string[] GetValueSeparators ()
{
if (separators == null)
return new string [0];
return (string[]) separators.Clone ();
}
protected static T Parse<T> (string value, OptionContext c)
{
TypeConverter conv = TypeDescriptor.GetConverter (typeof (T));
T t = default (T);
try {
if (value != null)
t = (T) conv.ConvertFromString (value);
}
catch (Exception e) {
throw new OptionException (
string.Format (
c.OptionSet.MessageLocalizer ("Could not convert string `{0}' to type {1} for option `{2}'."),
value, typeof (T).Name, c.OptionName),
c.OptionName, e);
}
return t;
}
internal string[] Names {get {return names;}}
internal string[] ValueSeparators {get {return separators;}}
static readonly char[] NameTerminator = new char[]{'=', ':'};
private OptionValueType ParsePrototype ()
{
char type = '\0';
List<string> seps = new List<string> ();
for (int i = 0; i < names.Length; ++i) {
string name = names [i];
if (name.Length == 0)
throw new ArgumentException ("Empty option names are not supported.", "prototype");
int end = name.IndexOfAny (NameTerminator);
if (end == -1)
continue;
names [i] = name.Substring (0, end);
if (type == '\0' || type == name [end])
type = name [end];
else
throw new ArgumentException (
string.Format ("Conflicting option types: '{0}' vs. '{1}'.", type, name [end]),
"prototype");
AddSeparators (name, end, seps);
}
if (type == '\0')
return OptionValueType.None;
if (count <= 1 && seps.Count != 0)
throw new ArgumentException (
string.Format ("Cannot provide key/value separators for Options taking {0} value(s).", count),
"prototype");
if (count > 1) {
if (seps.Count == 0)
this.separators = new string[]{":", "="};
else if (seps.Count == 1 && seps [0].Length == 0)
this.separators = null;
else
this.separators = seps.ToArray ();
}
return type == '=' ? OptionValueType.Required : OptionValueType.Optional;
}
private static void AddSeparators (string name, int end, ICollection<string> seps)
{
int start = -1;
for (int i = end+1; i < name.Length; ++i) {
switch (name [i]) {
case '{':
if (start != -1)
throw new ArgumentException (
string.Format ("Ill-formed name/value separator found in \"{0}\".", name),
"prototype");
start = i+1;
break;
case '}':
if (start == -1)
throw new ArgumentException (
string.Format ("Ill-formed name/value separator found in \"{0}\".", name),
"prototype");
seps.Add (name.Substring (start, i-start));
start = -1;
break;
default:
if (start == -1)
seps.Add (name [i].ToString ());
break;
}
}
if (start != -1)
throw new ArgumentException (
string.Format ("Ill-formed name/value separator found in \"{0}\".", name),
"prototype");
}
public void Invoke (OptionContext c)
{
OnParseComplete (c);
c.OptionName = null;
c.Option = null;
c.OptionValues.Clear ();
}
protected abstract void OnParseComplete (OptionContext c);
public override string ToString ()
{
return Prototype;
}
}
[Serializable]
public class OptionException : Exception {
private string option;
public OptionException ()
{
}
public OptionException (string message, string optionName)
: base (message)
{
this.option = optionName;
}
public OptionException (string message, string optionName, Exception innerException)
: base (message, innerException)
{
this.option = optionName;
}
protected OptionException (SerializationInfo info, StreamingContext context)
: base (info, context)
{
this.option = info.GetString ("OptionName");
}
public string OptionName {
get {return this.option;}
}
[SecurityPermission (SecurityAction.LinkDemand, SerializationFormatter = true)]
public override void GetObjectData (SerializationInfo info, StreamingContext context)
{
base.GetObjectData (info, context);
info.AddValue ("OptionName", option);
}
}
public delegate void OptionAction<TKey, TValue> (TKey key, TValue value);
public class OptionSet : KeyedCollection<string, Option>
{
public OptionSet ()
: this (delegate (string f) {return f;})
{
}
public OptionSet (Converter<string, string> localizer)
{
this.localizer = localizer;
}
Converter<string, string> localizer;
public Converter<string, string> MessageLocalizer {
get {return localizer;}
}
protected override string GetKeyForItem (Option item)
{
if (item == null)
throw new ArgumentNullException ("option");
if (item.Names != null && item.Names.Length > 0)
return item.Names [0];
// This should never happen, as it's invalid for Option to be
// constructed w/o any names.
throw new InvalidOperationException ("Option has no names!");
}
[Obsolete ("Use KeyedCollection.this[string]")]
protected Option GetOptionForName (string option)
{
if (option == null)
throw new ArgumentNullException ("option");
try {
return base [option];
}
catch (KeyNotFoundException) {
return null;
}
}
protected override void InsertItem (int index, Option item)
{
base.InsertItem (index, item);
AddImpl (item);
}
protected override void RemoveItem (int index)
{
base.RemoveItem (index);
Option p = Items [index];
// KeyedCollection.RemoveItem() handles the 0th item
for (int i = 1; i < p.Names.Length; ++i) {
Dictionary.Remove (p.Names [i]);
}
}
protected override void SetItem (int index, Option item)
{
base.SetItem (index, item);
RemoveItem (index);
AddImpl (item);
}
private void AddImpl (Option option)
{
if (option == null)
throw new ArgumentNullException ("option");
List<string> added = new List<string> (option.Names.Length);
try {
// KeyedCollection.InsertItem/SetItem handle the 0th name.
for (int i = 1; i < option.Names.Length; ++i) {
Dictionary.Add (option.Names [i], option);
added.Add (option.Names [i]);
}
}
catch (Exception) {
foreach (string name in added)
Dictionary.Remove (name);
throw;
}
}
public new OptionSet Add (Option option)
{
base.Add (option);
return this;
}
sealed class ActionOption : Option {
Action<OptionValueCollection> action;
public ActionOption (string prototype, string description, int count, Action<OptionValueCollection> action)
: base (prototype, description, count)
{
if (action == null)
throw new ArgumentNullException ("action");
this.action = action;
}
protected override void OnParseComplete (OptionContext c)
{
action (c.OptionValues);
}
}
public OptionSet Add (string prototype, Action<string> action)
{
return Add (prototype, null, action);
}
public OptionSet Add (string prototype, string description, Action<string> action)
{
if (action == null)
throw new ArgumentNullException ("action");
Option p = new ActionOption (prototype, description, 1,
delegate (OptionValueCollection v) { action (v [0]); });
base.Add (p);
return this;
}
public OptionSet Add (string prototype, OptionAction<string, string> action)
{
return Add (prototype, null, action);
}
public OptionSet Add (string prototype, string description, OptionAction<string, string> action)
{
if (action == null)
throw new ArgumentNullException ("action");
Option p = new ActionOption (prototype, description, 2,
delegate (OptionValueCollection v) {action (v [0], v [1]);});
base.Add (p);
return this;
}
sealed class ActionOption<T> : Option {
Action<T> action;
public ActionOption (string prototype, string description, Action<T> action)
: base (prototype, description, 1)
{
if (action == null)
throw new ArgumentNullException ("action");
this.action = action;
}
protected override void OnParseComplete (OptionContext c)
{
action (Parse<T> (c.OptionValues [0], c));
}
}
sealed class ActionOption<TKey, TValue> : Option {
OptionAction<TKey, TValue> action;
public ActionOption (string prototype, string description, OptionAction<TKey, TValue> action)
: base (prototype, description, 2)
{
if (action == null)
throw new ArgumentNullException ("action");
this.action = action;
}
protected override void OnParseComplete (OptionContext c)
{
action (
Parse<TKey> (c.OptionValues [0], c),
Parse<TValue> (c.OptionValues [1], c));
}
}
public OptionSet Add<T> (string prototype, Action<T> action)
{
return Add (prototype, null, action);
}
public OptionSet Add<T> (string prototype, string description, Action<T> action)
{
return Add (new ActionOption<T> (prototype, description, action));
}
public OptionSet Add<TKey, TValue> (string prototype, OptionAction<TKey, TValue> action)
{
return Add (prototype, null, action);
}
public OptionSet Add<TKey, TValue> (string prototype, string description, OptionAction<TKey, TValue> action)
{
return Add (new ActionOption<TKey, TValue> (prototype, description, action));
}
protected virtual OptionContext CreateOptionContext ()
{
return new OptionContext (this);
}
#if LINQ
public List<string> Parse (IEnumerable<string> arguments)
{
bool process = true;
OptionContext c = CreateOptionContext ();
c.OptionIndex = -1;
var def = GetOptionForName ("<>");
var unprocessed =
from argument in arguments
where ++c.OptionIndex >= 0 && (process || def != null)
? process
? argument == "--"
? (process = false)
: !Parse (argument, c)
? def != null
? Unprocessed (null, def, c, argument)
: true
: false
: def != null
? Unprocessed (null, def, c, argument)
: true
: true
select argument;
List<string> r = unprocessed.ToList ();
if (c.Option != null)
c.Option.Invoke (c);
return r;
}
#else
public List<string> Parse (IEnumerable<string> arguments)
{
OptionContext c = CreateOptionContext ();
c.OptionIndex = -1;
bool process = true;
List<string> unprocessed = new List<string> ();
Option def = Contains ("<>") ? this ["<>"] : null;
foreach (string argument in arguments) {
++c.OptionIndex;
if (argument == "--") {
process = false;
continue;
}
if (!process) {
Unprocessed (unprocessed, def, c, argument);
continue;
}
if (!Parse (argument, c))
Unprocessed (unprocessed, def, c, argument);
}
if (c.Option != null)
c.Option.Invoke (c);
return unprocessed;
}
#endif
private static bool Unprocessed (ICollection<string> extra, Option def, OptionContext c, string argument)
{
if (def == null) {
extra.Add (argument);
return false;
}
c.OptionValues.Add (argument);
c.Option = def;
c.Option.Invoke (c);
return false;
}
private readonly Regex ValueOption = new Regex (
@"^(?<flag>--|-|/)(?<name>[^:=]+)((?<sep>[:=])(?<value>.*))?$");
protected bool GetOptionParts (string argument, out string flag, out string name, out string sep, out string value)
{
if (argument == null)
throw new ArgumentNullException ("argument");
flag = name = sep = value = null;
Match m = ValueOption.Match (argument);
if (!m.Success) {
return false;
}
flag = m.Groups ["flag"].Value;
name = m.Groups ["name"].Value;
if (m.Groups ["sep"].Success && m.Groups ["value"].Success) {
sep = m.Groups ["sep"].Value;
value = m.Groups ["value"].Value;
}
return true;
}
protected virtual bool Parse (string argument, OptionContext c)
{
if (c.Option != null) {
ParseValue (argument, c);
return true;
}
string f, n, s, v;
if (!GetOptionParts (argument, out f, out n, out s, out v))
return false;
Option p;
if (Contains (n)) {
p = this [n];
c.OptionName = f + n;
c.Option = p;
switch (p.OptionValueType) {
case OptionValueType.None:
c.OptionValues.Add (n);
c.Option.Invoke (c);
break;
case OptionValueType.Optional:
case OptionValueType.Required:
ParseValue (v, c);
break;
}
return true;
}
// no match; is it a bool option?
if (ParseBool (argument, n, c))
return true;
// is it a bundled option?
if (ParseBundledValue (f, string.Concat (n + s + v), c))
return true;
return false;
}
private void ParseValue (string option, OptionContext c)
{
if (option != null)
foreach (string o in c.Option.ValueSeparators != null
? option.Split (c.Option.ValueSeparators, StringSplitOptions.None)
: new string[]{option}) {
c.OptionValues.Add (o);
}
if (c.OptionValues.Count == c.Option.MaxValueCount ||
c.Option.OptionValueType == OptionValueType.Optional)
c.Option.Invoke (c);
else if (c.OptionValues.Count > c.Option.MaxValueCount) {
throw new OptionException (localizer (string.Format (
"Error: Found {0} option values when expecting {1}.",
c.OptionValues.Count, c.Option.MaxValueCount)),
c.OptionName);
}
}
private bool ParseBool (string option, string n, OptionContext c)
{
Option p;
string rn;
if (n.Length >= 1 && (n [n.Length-1] == '+' || n [n.Length-1] == '-') &&
Contains ((rn = n.Substring (0, n.Length-1)))) {
p = this [rn];
string v = n [n.Length-1] == '+' ? option : null;
c.OptionName = option;
c.Option = p;
c.OptionValues.Add (v);
p.Invoke (c);
return true;
}
return false;
}
private bool ParseBundledValue (string f, string n, OptionContext c)
{
if (f != "-")
return false;
for (int i = 0; i < n.Length; ++i) {
Option p;
string opt = f + n [i].ToString ();
string rn = n [i].ToString ();
if (!Contains (rn)) {
if (i == 0)
return false;
throw new OptionException (string.Format (localizer (
"Cannot bundle unregistered option '{0}'."), opt), opt);
}
p = this [rn];
switch (p.OptionValueType) {
case OptionValueType.None:
Invoke (c, opt, n, p);
break;
case OptionValueType.Optional:
case OptionValueType.Required: {
string v = n.Substring (i+1);
c.Option = p;
c.OptionName = opt;
ParseValue (v.Length != 0 ? v : null, c);
return true;
}
default:
throw new InvalidOperationException ("Unknown OptionValueType: " + p.OptionValueType);
}
}
return true;
}
private static void Invoke (OptionContext c, string name, string value, Option option)
{
c.OptionName = name;
c.Option = option;
c.OptionValues.Add (value);
option.Invoke (c);
}
private const int OptionWidth = 29;
public void WriteOptionDescriptions (TextWriter o)
{
foreach (Option p in this) {
int written = 0;
if (!WriteOptionPrototype (o, p, ref written))
continue;
if (written < OptionWidth)
o.Write (new string (' ', OptionWidth - written));
else {
o.WriteLine ();
o.Write (new string (' ', OptionWidth));
}
List<string> lines = GetLines (localizer (GetDescription (p.Description)));
o.WriteLine (lines [0]);
string prefix = new string (' ', OptionWidth+2);
for (int i = 1; i < lines.Count; ++i) {
o.Write (prefix);
o.WriteLine (lines [i]);
}
}
}
bool WriteOptionPrototype (TextWriter o, Option p, ref int written)
{
string[] names = p.Names;
int i = GetNextOptionIndex (names, 0);
if (i == names.Length)
return false;
if (names [i].Length == 1) {
Write (o, ref written, " -");
Write (o, ref written, names [0]);
}
else {
Write (o, ref written, " --");
Write (o, ref written, names [0]);
}
for ( i = GetNextOptionIndex (names, i+1);
i < names.Length; i = GetNextOptionIndex (names, i+1)) {
Write (o, ref written, ", ");
Write (o, ref written, names [i].Length == 1 ? "-" : "--");
Write (o, ref written, names [i]);
}
if (p.OptionValueType == OptionValueType.Optional ||
p.OptionValueType == OptionValueType.Required) {
if (p.OptionValueType == OptionValueType.Optional) {
Write (o, ref written, localizer ("["));
}
Write (o, ref written, localizer ("=" + GetArgumentName (0, p.MaxValueCount, p.Description)));
string sep = p.ValueSeparators != null && p.ValueSeparators.Length > 0
? p.ValueSeparators [0]
: " ";
for (int c = 1; c < p.MaxValueCount; ++c) {
Write (o, ref written, localizer (sep + GetArgumentName (c, p.MaxValueCount, p.Description)));
}
if (p.OptionValueType == OptionValueType.Optional) {
Write (o, ref written, localizer ("]"));
}
}
return true;
}
static int GetNextOptionIndex (string[] names, int i)
{
while (i < names.Length && names [i] == "<>") {
++i;
}
return i;
}
static void Write (TextWriter o, ref int n, string s)
{
n += s.Length;
o.Write (s);
}
private static string GetArgumentName (int index, int maxIndex, string description)
{
if (description == null)
return maxIndex == 1 ? "VALUE" : "VALUE" + (index + 1);
string[] nameStart;
if (maxIndex == 1)
nameStart = new string[]{"{0:", "{"};
else
nameStart = new string[]{"{" + index + ":"};
for (int i = 0; i < nameStart.Length; ++i) {
int start, j = 0;
do {
start = description.IndexOf (nameStart [i], j);
} while (start >= 0 && j != 0 ? description [j++ - 1] == '{' : false);
if (start == -1)
continue;
int end = description.IndexOf ("}", start);
if (end == -1)
continue;
return description.Substring (start + nameStart [i].Length, end - start - nameStart [i].Length);
}
return maxIndex == 1 ? "VALUE" : "VALUE" + (index + 1);
}
private static string GetDescription (string description)
{
if (description == null)
return string.Empty;
StringBuilder sb = new StringBuilder (description.Length);
int start = -1;
for (int i = 0; i < description.Length; ++i) {
switch (description [i]) {
case '{':
if (i == start) {
sb.Append ('{');
start = -1;
}
else if (start < 0)
start = i + 1;
break;
case '}':
if (start < 0) {
if ((i+1) == description.Length || description [i+1] != '}')
throw new InvalidOperationException ("Invalid option description: " + description);
++i;
sb.Append ("}");
}
else {
sb.Append (description.Substring (start, i - start));
start = -1;
}
break;
case ':':
if (start < 0)
goto default;
start = i + 1;
break;
default:
if (start < 0)
sb.Append (description [i]);
break;
}
}
return sb.ToString ();
}
private static List<string> GetLines (string description)
{
List<string> lines = new List<string> ();
if (string.IsNullOrEmpty (description)) {
lines.Add (string.Empty);
return lines;
}
int length = 80 - OptionWidth - 2;
int start = 0, end;
do {
end = GetLineEnd (start, length, description);
bool cont = false;
if (end < description.Length) {
char c = description [end];
if (c == '-' || (char.IsWhiteSpace (c) && c != '\n'))
++end;
else if (c != '\n') {
cont = true;
--end;
}
}
lines.Add (description.Substring (start, end - start));
if (cont) {
lines [lines.Count-1] += "-";
}
start = end;
if (start < description.Length && description [start] == '\n')
++start;
} while (end < description.Length);
return lines;
}
private static int GetLineEnd (int start, int length, string description)
{
int end = Math.Min (start + length, description.Length);
int sep = -1;
for (int i = start; i < end; ++i) {
switch (description [i]) {
case ' ':
case '\t':
case '\v':
case '-':
case ',':
case '.':
case ';':
sep = i;
break;
case '\n':
return i;
}
}
if (sep == -1 || end == description.Length)
return end;
return sep;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections;
using System.Collections.ObjectModel;
using System.Collections.Generic;
using Xunit;
namespace System.Linq.Expressions.Tests
{
public static class NewArrayListTests
{
#region Tests
[Fact]
public static void CheckBoolArrayListTest()
{
bool[][] array = new bool[][]
{
new bool[] { },
new bool[] { true },
new bool[] { true, false }
};
Expression[][] exprs = new Expression[array.Length][];
for (int i = 0; i < array.Length; i++)
{
exprs[i] = new Expression[array[i].Length];
for (int j = 0; j < array[i].Length; j++)
{
bool val = array[i][j];
exprs[i][j] = Expression.Constant(val, typeof(bool));
}
}
for (int i = 0; i < array.Length; i++)
{
VerifyBoolArrayList(array[i], exprs[i]);
}
}
[Fact]
public static void CheckByteArrayListTest()
{
byte[][] array = new byte[][]
{
new byte[] { },
new byte[] { 0 },
new byte[] { 0, 1, byte.MaxValue }
};
Expression[][] exprs = new Expression[array.Length][];
for (int i = 0; i < array.Length; i++)
{
exprs[i] = new Expression[array[i].Length];
for (int j = 0; j < array[i].Length; j++)
{
byte val = array[i][j];
exprs[i][j] = Expression.Constant(val, typeof(byte));
}
}
for (int i = 0; i < array.Length; i++)
{
VerifyByteArrayList(array[i], exprs[i]);
}
}
[Fact]
public static void CheckCustomArrayListTest()
{
C[][] array = new C[][]
{
new C[] { },
new C[] { null },
new C[] { new C(), new D(), new D(0), new D(5) }
};
Expression[][] exprs = new Expression[array.Length][];
for (int i = 0; i < array.Length; i++)
{
exprs[i] = new Expression[array[i].Length];
for (int j = 0; j < array[i].Length; j++)
{
C val = array[i][j];
exprs[i][j] = Expression.Constant(val, typeof(C));
}
}
for (int i = 0; i < array.Length; i++)
{
VerifyCustomArrayList(array[i], exprs[i]);
}
}
[Fact]
public static void CheckCharArrayListTest()
{
char[][] array = new char[][]
{
new char[] { },
new char[] { '\0' },
new char[] { '\0', '\b', 'A', '\uffff' }
};
Expression[][] exprs = new Expression[array.Length][];
for (int i = 0; i < array.Length; i++)
{
exprs[i] = new Expression[array[i].Length];
for (int j = 0; j < array[i].Length; j++)
{
char val = array[i][j];
exprs[i][j] = Expression.Constant(val, typeof(char));
}
}
for (int i = 0; i < array.Length; i++)
{
VerifyCharArrayList(array[i], exprs[i]);
}
}
[Fact]
public static void CheckCustom2ArrayListTest()
{
D[][] array = new D[][]
{
new D[] { },
new D[] { null },
new D[] { null, new D(), new D(0), new D(5) }
};
Expression[][] exprs = new Expression[array.Length][];
for (int i = 0; i < array.Length; i++)
{
exprs[i] = new Expression[array[i].Length];
for (int j = 0; j < array[i].Length; j++)
{
D val = array[i][j];
exprs[i][j] = Expression.Constant(val, typeof(D));
}
}
for (int i = 0; i < array.Length; i++)
{
VerifyCustom2ArrayList(array[i], exprs[i]);
}
}
[Fact]
public static void CheckDecimalArrayListTest()
{
decimal[][] array = new decimal[][]
{
new decimal[] { },
new decimal[] { decimal.Zero },
new decimal[] { decimal.Zero, decimal.One, decimal.MinusOne, decimal.MinValue, decimal.MaxValue }
};
Expression[][] exprs = new Expression[array.Length][];
for (int i = 0; i < array.Length; i++)
{
exprs[i] = new Expression[array[i].Length];
for (int j = 0; j < array[i].Length; j++)
{
decimal val = array[i][j];
exprs[i][j] = Expression.Constant(val, typeof(decimal));
}
}
for (int i = 0; i < array.Length; i++)
{
VerifyDecimalArrayList(array[i], exprs[i]);
}
}
[Fact]
public static void CheckDelegateArrayListTest()
{
Delegate[][] array = new Delegate[][]
{
new Delegate[] { },
new Delegate[] { null },
new Delegate[] { null, (Func<object>) delegate() { return null; }, (Func<int, int>) delegate(int i) { return i+1; }, (Action<object>) delegate { } }
};
Expression[][] exprs = new Expression[array.Length][];
for (int i = 0; i < array.Length; i++)
{
exprs[i] = new Expression[array[i].Length];
for (int j = 0; j < array[i].Length; j++)
{
Delegate val = array[i][j];
exprs[i][j] = Expression.Constant(val, typeof(Delegate));
}
}
for (int i = 0; i < array.Length; i++)
{
VerifyDelegateArrayList(array[i], exprs[i]);
}
}
[Fact]
public static void CheckDoubleArrayListTest()
{
double[][] array = new double[][]
{
new double[] { },
new double[] { 0 },
new double[] { 0, 1, -1, double.MinValue, double.MaxValue, double.Epsilon, double.NegativeInfinity, double.PositiveInfinity, double.NaN }
};
Expression[][] exprs = new Expression[array.Length][];
for (int i = 0; i < array.Length; i++)
{
exprs[i] = new Expression[array[i].Length];
for (int j = 0; j < array[i].Length; j++)
{
double val = array[i][j];
exprs[i][j] = Expression.Constant(val, typeof(double));
}
}
for (int i = 0; i < array.Length; i++)
{
VerifyDoubleArrayList(array[i], exprs[i]);
}
}
[Fact]
public static void CheckEnumArrayListTest()
{
E[][] array = new E[][]
{
new E[] { },
new E[] { (E) 0 },
new E[] { (E) 0, E.A, E.B, (E) int.MaxValue, (E) int.MinValue }
};
Expression[][] exprs = new Expression[array.Length][];
for (int i = 0; i < array.Length; i++)
{
exprs[i] = new Expression[array[i].Length];
for (int j = 0; j < array[i].Length; j++)
{
E val = array[i][j];
exprs[i][j] = Expression.Constant(val, typeof(E));
}
}
for (int i = 0; i < array.Length; i++)
{
VerifyEnumArrayList(array[i], exprs[i]);
}
}
[Fact]
public static void CheckEnumLongArrayListTest()
{
El[][] array = new El[][]
{
new El[] { },
new El[] { (El) 0 },
new El[] { (El) 0, El.A, El.B, (El) long.MaxValue, (El) long.MinValue }
};
Expression[][] exprs = new Expression[array.Length][];
for (int i = 0; i < array.Length; i++)
{
exprs[i] = new Expression[array[i].Length];
for (int j = 0; j < array[i].Length; j++)
{
El val = array[i][j];
exprs[i][j] = Expression.Constant(val, typeof(El));
}
}
for (int i = 0; i < array.Length; i++)
{
VerifyEnumLongArrayList(array[i], exprs[i]);
}
}
[Fact]
public static void CheckFloatArrayListTest()
{
float[][] array = new float[][]
{
new float[] { },
new float[] { 0 },
new float[] { 0, 1, -1, float.MinValue, float.MaxValue, float.Epsilon, float.NegativeInfinity, float.PositiveInfinity, float.NaN }
};
Expression[][] exprs = new Expression[array.Length][];
for (int i = 0; i < array.Length; i++)
{
exprs[i] = new Expression[array[i].Length];
for (int j = 0; j < array[i].Length; j++)
{
float val = array[i][j];
exprs[i][j] = Expression.Constant(val, typeof(float));
}
}
for (int i = 0; i < array.Length; i++)
{
VerifyFloatArrayList(array[i], exprs[i]);
}
}
[Fact]
public static void CheckFuncArrayListTest()
{
Func<object>[][] array = new Func<object>[][]
{
new Func<object>[] { },
new Func<object>[] { null },
new Func<object>[] { null, (Func<object>) delegate() { return null; } }
};
Expression[][] exprs = new Expression[array.Length][];
for (int i = 0; i < array.Length; i++)
{
exprs[i] = new Expression[array[i].Length];
for (int j = 0; j < array[i].Length; j++)
{
Func<object> val = array[i][j];
exprs[i][j] = Expression.Constant(val, typeof(Func<object>));
}
}
for (int i = 0; i < array.Length; i++)
{
VerifyFuncArrayList(array[i], exprs[i]);
}
}
[Fact]
public static void CheckInterfaceArrayListTest()
{
I[][] array = new I[][]
{
new I[] { },
new I[] { null },
new I[] { null, new C(), new D(), new D(0), new D(5) }
};
Expression[][] exprs = new Expression[array.Length][];
for (int i = 0; i < array.Length; i++)
{
exprs[i] = new Expression[array[i].Length];
for (int j = 0; j < array[i].Length; j++)
{
I val = array[i][j];
exprs[i][j] = Expression.Constant(val, typeof(I));
}
}
for (int i = 0; i < array.Length; i++)
{
VerifyInterfaceArrayList(array[i], exprs[i]);
}
}
[Fact]
public static void CheckIEquatableCustomArrayListTest()
{
IEquatable<C>[][] array = new IEquatable<C>[][]
{
new IEquatable<C>[] { },
new IEquatable<C>[] { null },
new IEquatable<C>[] { null, new C(), new D(), new D(0), new D(5) }
};
Expression[][] exprs = new Expression[array.Length][];
for (int i = 0; i < array.Length; i++)
{
exprs[i] = new Expression[array[i].Length];
for (int j = 0; j < array[i].Length; j++)
{
IEquatable<C> val = array[i][j];
exprs[i][j] = Expression.Constant(val, typeof(IEquatable<C>));
}
}
for (int i = 0; i < array.Length; i++)
{
VerifyIEquatableCustomArrayList(array[i], exprs[i]);
}
}
[Fact]
public static void CheckIEquatableCustom2ArrayListTest()
{
IEquatable<D>[][] array = new IEquatable<D>[][]
{
new IEquatable<D>[] { },
new IEquatable<D>[] { null },
new IEquatable<D>[] { null, new D(), new D(0), new D(5) }
};
Expression[][] exprs = new Expression[array.Length][];
for (int i = 0; i < array.Length; i++)
{
exprs[i] = new Expression[array[i].Length];
for (int j = 0; j < array[i].Length; j++)
{
IEquatable<D> val = array[i][j];
exprs[i][j] = Expression.Constant(val, typeof(IEquatable<D>));
}
}
for (int i = 0; i < array.Length; i++)
{
VerifyIEquatableCustom2ArrayList(array[i], exprs[i]);
}
}
[Fact]
public static void CheckIntArrayListTest()
{
int[][] array = new int[][]
{
new int[] { },
new int[] { 0 },
new int[] { 0, 1, -1, int.MinValue, int.MaxValue }
};
Expression[][] exprs = new Expression[array.Length][];
for (int i = 0; i < array.Length; i++)
{
exprs[i] = new Expression[array[i].Length];
for (int j = 0; j < array[i].Length; j++)
{
int val = array[i][j];
exprs[i][j] = Expression.Constant(val, typeof(int));
}
}
for (int i = 0; i < array.Length; i++)
{
VerifyIntArrayList(array[i], exprs[i]);
}
}
[Fact]
public static void CheckLongArrayListTest()
{
long[][] array = new long[][]
{
new long[] { },
new long[] { 0 },
new long[] { 0, 1, -1, long.MinValue, long.MaxValue }
};
Expression[][] exprs = new Expression[array.Length][];
for (int i = 0; i < array.Length; i++)
{
exprs[i] = new Expression[array[i].Length];
for (int j = 0; j < array[i].Length; j++)
{
long val = array[i][j];
exprs[i][j] = Expression.Constant(val, typeof(long));
}
}
for (int i = 0; i < array.Length; i++)
{
VerifyLongArrayList(array[i], exprs[i]);
}
}
[Fact]
public static void CheckObjectArrayListTest()
{
object[][] array = new object[][]
{
new object[] { },
new object[] { null },
new object[] { null, new object(), new C(), new D(3) }
};
Expression[][] exprs = new Expression[array.Length][];
for (int i = 0; i < array.Length; i++)
{
exprs[i] = new Expression[array[i].Length];
for (int j = 0; j < array[i].Length; j++)
{
object val = array[i][j];
exprs[i][j] = Expression.Constant(val, typeof(object));
}
}
for (int i = 0; i < array.Length; i++)
{
VerifyObjectArrayList(array[i], exprs[i]);
}
}
[Fact]
public static void CheckStructArrayListTest()
{
S[][] array = new S[][]
{
new S[] { },
new S[] { default(S) },
new S[] { default(S), new S() }
};
Expression[][] exprs = new Expression[array.Length][];
for (int i = 0; i < array.Length; i++)
{
exprs[i] = new Expression[array[i].Length];
for (int j = 0; j < array[i].Length; j++)
{
S val = array[i][j];
exprs[i][j] = Expression.Constant(val, typeof(S));
}
}
for (int i = 0; i < array.Length; i++)
{
VerifyStructArrayList(array[i], exprs[i]);
}
}
[Fact]
public static void CheckSByteArrayListTest()
{
sbyte[][] array = new sbyte[][]
{
new sbyte[] { },
new sbyte[] { 0 },
new sbyte[] { 0, 1, -1, sbyte.MinValue, sbyte.MaxValue }
};
Expression[][] exprs = new Expression[array.Length][];
for (int i = 0; i < array.Length; i++)
{
exprs[i] = new Expression[array[i].Length];
for (int j = 0; j < array[i].Length; j++)
{
sbyte val = array[i][j];
exprs[i][j] = Expression.Constant(val, typeof(sbyte));
}
}
for (int i = 0; i < array.Length; i++)
{
VerifySByteArrayList(array[i], exprs[i]);
}
}
[Fact]
public static void CheckStructWithStringArrayListTest()
{
Sc[][] array = new Sc[][]
{
new Sc[] { },
new Sc[] { default(Sc) },
new Sc[] { default(Sc), new Sc(), new Sc(null) }
};
Expression[][] exprs = new Expression[array.Length][];
for (int i = 0; i < array.Length; i++)
{
exprs[i] = new Expression[array[i].Length];
for (int j = 0; j < array[i].Length; j++)
{
Sc val = array[i][j];
exprs[i][j] = Expression.Constant(val, typeof(Sc));
}
}
for (int i = 0; i < array.Length; i++)
{
VerifyStructWithStringArrayList(array[i], exprs[i]);
}
}
[Fact]
public static void CheckStructWithStringAndFieldArrayListTest()
{
Scs[][] array = new Scs[][]
{
new Scs[] { },
new Scs[] { default(Scs) },
new Scs[] { default(Scs), new Scs(), new Scs(null,new S()) }
};
Expression[][] exprs = new Expression[array.Length][];
for (int i = 0; i < array.Length; i++)
{
exprs[i] = new Expression[array[i].Length];
for (int j = 0; j < array[i].Length; j++)
{
Scs val = array[i][j];
exprs[i][j] = Expression.Constant(val, typeof(Scs));
}
}
for (int i = 0; i < array.Length; i++)
{
VerifyStructWithStringAndFieldArrayList(array[i], exprs[i]);
}
}
[Fact]
public static void CheckShortArrayListTest()
{
short[][] array = new short[][]
{
new short[] { },
new short[] { 0 },
new short[] { 0, 1, -1, short.MinValue, short.MaxValue }
};
Expression[][] exprs = new Expression[array.Length][];
for (int i = 0; i < array.Length; i++)
{
exprs[i] = new Expression[array[i].Length];
for (int j = 0; j < array[i].Length; j++)
{
short val = array[i][j];
exprs[i][j] = Expression.Constant(val, typeof(short));
}
}
for (int i = 0; i < array.Length; i++)
{
VerifyShortArrayList(array[i], exprs[i]);
}
}
[Fact]
public static void CheckStructWithTwoValuesArrayListTest()
{
Sp[][] array = new Sp[][]
{
new Sp[] { },
new Sp[] { default(Sp) },
new Sp[] { default(Sp), new Sp(), new Sp(5,5.0) }
};
Expression[][] exprs = new Expression[array.Length][];
for (int i = 0; i < array.Length; i++)
{
exprs[i] = new Expression[array[i].Length];
for (int j = 0; j < array[i].Length; j++)
{
Sp val = array[i][j];
exprs[i][j] = Expression.Constant(val, typeof(Sp));
}
}
for (int i = 0; i < array.Length; i++)
{
VerifyStructWithTwoValuesArrayList(array[i], exprs[i]);
}
}
[Fact]
public static void CheckStructWithValueArrayListTest()
{
Ss[][] array = new Ss[][]
{
new Ss[] { },
new Ss[] { default(Ss) },
new Ss[] { default(Ss), new Ss(), new Ss(new S()) }
};
Expression[][] exprs = new Expression[array.Length][];
for (int i = 0; i < array.Length; i++)
{
exprs[i] = new Expression[array[i].Length];
for (int j = 0; j < array[i].Length; j++)
{
Ss val = array[i][j];
exprs[i][j] = Expression.Constant(val, typeof(Ss));
}
}
for (int i = 0; i < array.Length; i++)
{
VerifyStructWithValueArrayList(array[i], exprs[i]);
}
}
[Fact]
public static void CheckStringArrayListTest()
{
string[][] array = new string[][]
{
new string[] { },
new string[] { null },
new string[] { null, "", "a", "foo" }
};
Expression[][] exprs = new Expression[array.Length][];
for (int i = 0; i < array.Length; i++)
{
exprs[i] = new Expression[array[i].Length];
for (int j = 0; j < array[i].Length; j++)
{
string val = array[i][j];
exprs[i][j] = Expression.Constant(val, typeof(string));
}
}
for (int i = 0; i < array.Length; i++)
{
VerifyStringArrayList(array[i], exprs[i]);
}
}
[Fact]
public static void CheckUIntArrayListTest()
{
uint[][] array = new uint[][]
{
new uint[] { },
new uint[] { 0 },
new uint[] { 0, 1, uint.MaxValue }
};
Expression[][] exprs = new Expression[array.Length][];
for (int i = 0; i < array.Length; i++)
{
exprs[i] = new Expression[array[i].Length];
for (int j = 0; j < array[i].Length; j++)
{
uint val = array[i][j];
exprs[i][j] = Expression.Constant(val, typeof(uint));
}
}
for (int i = 0; i < array.Length; i++)
{
VerifyUIntArrayList(array[i], exprs[i]);
}
}
[Fact]
public static void CheckULongArrayListTest()
{
ulong[][] array = new ulong[][]
{
new ulong[] { },
new ulong[] { 0 },
new ulong[] { 0, 1, ulong.MaxValue }
};
Expression[][] exprs = new Expression[array.Length][];
for (int i = 0; i < array.Length; i++)
{
exprs[i] = new Expression[array[i].Length];
for (int j = 0; j < array[i].Length; j++)
{
ulong val = array[i][j];
exprs[i][j] = Expression.Constant(val, typeof(ulong));
}
}
for (int i = 0; i < array.Length; i++)
{
VerifyULongArrayList(array[i], exprs[i]);
}
}
[Fact]
public static void CheckUShortArrayListTest()
{
ushort[][] array = new ushort[][]
{
new ushort[] { },
new ushort[] { 0 },
new ushort[] { 0, 1, ushort.MaxValue }
};
Expression[][] exprs = new Expression[array.Length][];
for (int i = 0; i < array.Length; i++)
{
exprs[i] = new Expression[array[i].Length];
for (int j = 0; j < array[i].Length; j++)
{
ushort val = array[i][j];
exprs[i][j] = Expression.Constant(val, typeof(ushort));
}
}
for (int i = 0; i < array.Length; i++)
{
VerifyUShortArrayList(array[i], exprs[i]);
}
}
[Fact]
public static void CheckGenericCustomArrayListTest()
{
CheckGenericArrayListHelper<C>();
}
[Fact]
public static void CheckGenericEnumArrayListTest()
{
CheckGenericArrayListHelper<E>();
}
[Fact]
public static void CheckGenericObjectArrayListTest()
{
CheckGenericArrayListHelper<object>();
}
[Fact]
public static void CheckGenericStructArrayListTest()
{
CheckGenericArrayListHelper<S>();
}
[Fact]
public static void CheckGenericStructWithStringAndFieldArrayListTest()
{
CheckGenericArrayListHelper<Scs>();
}
[Fact]
public static void CheckGenericCustomWithClassRestrictionArrayListTest()
{
CheckGenericWithClassRestrictionArrayListHelper<C>();
}
[Fact]
public static void CheckGenericObjectWithClassRestrictionArrayListTest()
{
CheckGenericWithClassRestrictionArrayListHelper<object>();
}
[Fact]
public static void CheckGenericCustomWithSubClassRestrictionArrayListTest()
{
CheckGenericWithSubClassRestrictionArrayListHelper<C>();
}
[Fact]
public static void CheckGenericCustomWithClassAndNewRestrictionArrayListTest()
{
CheckGenericWithClassAndNewRestrictionArrayListHelper<C>();
}
[Fact]
public static void CheckGenericObjectWithClassAndNewRestrictionArrayListTest()
{
CheckGenericWithClassAndNewRestrictionArrayListHelper<object>();
}
[Fact]
public static void CheckGenericCustomWithSubClassAndNewRestrictionArrayListTest()
{
CheckGenericWithSubClassAndNewRestrictionArrayListHelper<C>();
}
[Fact]
public static void CheckGenericEnumWithStructRestrictionArrayListTest()
{
CheckGenericWithStructRestrictionArrayListHelper<E>();
}
[Fact]
public static void CheckGenericStructWithStructRestrictionArrayListTest()
{
CheckGenericWithStructRestrictionArrayListHelper<S>();
}
[Fact]
public static void CheckGenericStructWithStringAndFieldWithStructRestrictionArrayListTest()
{
CheckGenericWithStructRestrictionArrayListHelper<Scs>();
}
[Fact]
public static void ThrowOnNegativeSizedCollection()
{
// This is an obscure case, and it doesn't much matter what is thrown, as long as is thrown before such
// an edge case could cause more obscure damage. A class derived from ReadOnlyCollection is used to catch
// assumptions that such a type is safe.
Assert.ThrowsAny<Exception>(() => Expression.NewArrayInit(typeof(int), new BogusReadOnlyCollection<Expression>()));
}
#endregion
#region Helper methods
private class BogusCollection<T> : IList<T>
{
public T this[int index]
{
get { return default(T); }
set { throw new NotSupportedException(); }
}
public int Count
{
get { return -1; }
}
public bool IsReadOnly
{
get { return true; }
}
public void Add(T item)
{
throw new NotSupportedException();
}
public void Clear()
{
throw new NotSupportedException();
}
public bool Contains(T item)
{
return false;
}
public void CopyTo(T[] array, int arrayIndex)
{
}
public IEnumerator<T> GetEnumerator()
{
return Enumerable.Empty<T>().GetEnumerator();
}
public int IndexOf(T item)
{
return -1;
}
public void Insert(int index, T item)
{
throw new NotSupportedException();
}
public bool Remove(T item)
{
throw new NotSupportedException();
}
public void RemoveAt(int index)
{
throw new NotSupportedException();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
private class BogusReadOnlyCollection<T> : ReadOnlyCollection<T>
{
public BogusReadOnlyCollection()
:base(new BogusCollection<T>())
{
}
}
private static void CheckGenericArrayListHelper<T>()
{
T[][] array = new T[][]
{
new T[] { },
new T[] { default(T) },
new T[] { default(T) }
};
Expression[][] exprs = new Expression[array.Length][];
for (int i = 0; i < array.Length; i++)
{
exprs[i] = new Expression[array[i].Length];
for (int j = 0; j < array[i].Length; j++)
{
T val = array[i][j];
exprs[i][j] = Expression.Constant(val, typeof(T));
}
}
for (int i = 0; i < array.Length; i++)
{
VerifyGenericArrayList<T>(array[i], exprs[i]);
}
}
private static void CheckGenericWithClassRestrictionArrayListHelper<Tc>() where Tc : class
{
Tc[][] array = new Tc[][]
{
new Tc[] { },
new Tc[] { default(Tc) },
new Tc[] { default(Tc) }
};
Expression[][] exprs = new Expression[array.Length][];
for (int i = 0; i < array.Length; i++)
{
exprs[i] = new Expression[array[i].Length];
for (int j = 0; j < array[i].Length; j++)
{
Tc val = array[i][j];
exprs[i][j] = Expression.Constant(val, typeof(Tc));
}
}
for (int i = 0; i < array.Length; i++)
{
VerifyGenericWithClassRestrictionArrayList<Tc>(array[i], exprs[i]);
}
}
private static void CheckGenericWithSubClassRestrictionArrayListHelper<TC>() where TC : C
{
TC[][] array = new TC[][]
{
new TC[] { },
new TC[] { default(TC) },
new TC[] { default(TC) }
};
Expression[][] exprs = new Expression[array.Length][];
for (int i = 0; i < array.Length; i++)
{
exprs[i] = new Expression[array[i].Length];
for (int j = 0; j < array[i].Length; j++)
{
TC val = array[i][j];
exprs[i][j] = Expression.Constant(val, typeof(TC));
}
}
for (int i = 0; i < array.Length; i++)
{
VerifyGenericWithSubClassRestrictionArrayList<TC>(array[i], exprs[i]);
}
}
private static void CheckGenericWithClassAndNewRestrictionArrayListHelper<Tcn>() where Tcn : class, new()
{
Tcn[][] array = new Tcn[][]
{
new Tcn[] { },
new Tcn[] { default(Tcn) },
new Tcn[] { default(Tcn) }
};
Expression[][] exprs = new Expression[array.Length][];
for (int i = 0; i < array.Length; i++)
{
exprs[i] = new Expression[array[i].Length];
for (int j = 0; j < array[i].Length; j++)
{
Tcn val = array[i][j];
exprs[i][j] = Expression.Constant(val, typeof(Tcn));
}
}
for (int i = 0; i < array.Length; i++)
{
VerifyGenericWithClassAndNewRestrictionArrayList<Tcn>(array[i], exprs[i]);
}
}
private static void CheckGenericWithSubClassAndNewRestrictionArrayListHelper<TCn>() where TCn : C, new()
{
TCn[][] array = new TCn[][]
{
new TCn[] { },
new TCn[] { default(TCn) },
new TCn[] { default(TCn) }
};
Expression[][] exprs = new Expression[array.Length][];
for (int i = 0; i < array.Length; i++)
{
exprs[i] = new Expression[array[i].Length];
for (int j = 0; j < array[i].Length; j++)
{
TCn val = array[i][j];
exprs[i][j] = Expression.Constant(val, typeof(TCn));
}
}
for (int i = 0; i < array.Length; i++)
{
VerifyGenericWithSubClassAndNewRestrictionArrayList<TCn>(array[i], exprs[i]);
}
}
private static void CheckGenericWithStructRestrictionArrayListHelper<Ts>() where Ts : struct
{
Ts[][] array = new Ts[][]
{
new Ts[] { },
new Ts[] { default(Ts) },
new Ts[] { default(Ts) }
};
Expression[][] exprs = new Expression[array.Length][];
for (int i = 0; i < array.Length; i++)
{
exprs[i] = new Expression[array[i].Length];
for (int j = 0; j < array[i].Length; j++)
{
Ts val = array[i][j];
exprs[i][j] = Expression.Constant(val, typeof(Ts));
}
}
for (int i = 0; i < array.Length; i++)
{
VerifyGenericWithStructRestrictionArrayList<Ts>(array[i], exprs[i]);
}
}
#endregion
#region verifiers
private static void VerifyBoolArrayList(bool[] val, Expression[] exprs)
{
Expression<Func<bool[]>> e =
Expression.Lambda<Func<bool[]>>(
Expression.NewArrayInit(typeof(bool), exprs),
Enumerable.Empty<ParameterExpression>());
Func<bool[]> f = e.Compile();
bool[] result = f();
Assert.Equal(val.Length, result.Length);
for (int i = 0; i < result.Length; i++)
{
Assert.Equal(val[i], result[i]);
}
}
private static void VerifyByteArrayList(byte[] val, Expression[] exprs)
{
Expression<Func<byte[]>> e =
Expression.Lambda<Func<byte[]>>(
Expression.NewArrayInit(typeof(byte), exprs),
Enumerable.Empty<ParameterExpression>());
Func<byte[]> f = e.Compile();
byte[] result = f();
Assert.Equal(val.Length, result.Length);
for (int i = 0; i < result.Length; i++)
{
Assert.Equal(val[i], result[i]);
}
}
private static void VerifyCustomArrayList(C[] val, Expression[] exprs)
{
Expression<Func<C[]>> e =
Expression.Lambda<Func<C[]>>(
Expression.NewArrayInit(typeof(C), exprs),
Enumerable.Empty<ParameterExpression>());
Func<C[]> f = e.Compile();
C[] result = f();
Assert.Equal(val.Length, result.Length);
for (int i = 0; i < result.Length; i++)
{
Assert.Equal(val[i], result[i]);
}
}
private static void VerifyCharArrayList(char[] val, Expression[] exprs)
{
Expression<Func<char[]>> e =
Expression.Lambda<Func<char[]>>(
Expression.NewArrayInit(typeof(char), exprs),
Enumerable.Empty<ParameterExpression>());
Func<char[]> f = e.Compile();
char[] result = f();
Assert.Equal(val.Length, result.Length);
for (int i = 0; i < result.Length; i++)
{
Assert.Equal(val[i], result[i]);
}
}
private static void VerifyCustom2ArrayList(D[] val, Expression[] exprs)
{
Expression<Func<D[]>> e =
Expression.Lambda<Func<D[]>>(
Expression.NewArrayInit(typeof(D), exprs),
Enumerable.Empty<ParameterExpression>());
Func<D[]> f = e.Compile();
D[] result = f();
Assert.Equal(val.Length, result.Length);
for (int i = 0; i < result.Length; i++)
{
Assert.Equal(val[i], result[i]);
}
}
private static void VerifyDecimalArrayList(decimal[] val, Expression[] exprs)
{
Expression<Func<decimal[]>> e =
Expression.Lambda<Func<decimal[]>>(
Expression.NewArrayInit(typeof(decimal), exprs),
Enumerable.Empty<ParameterExpression>());
Func<decimal[]> f = e.Compile();
decimal[] result = f();
Assert.Equal(val.Length, result.Length);
for (int i = 0; i < result.Length; i++)
{
Assert.Equal(val[i], result[i]);
}
}
private static void VerifyDelegateArrayList(Delegate[] val, Expression[] exprs)
{
Expression<Func<Delegate[]>> e =
Expression.Lambda<Func<Delegate[]>>(
Expression.NewArrayInit(typeof(Delegate), exprs),
Enumerable.Empty<ParameterExpression>());
Func<Delegate[]> f = e.Compile();
Delegate[] result = f();
Assert.Equal(val.Length, result.Length);
for (int i = 0; i < result.Length; i++)
{
Assert.Equal(val[i], result[i]);
}
}
private static void VerifyDoubleArrayList(double[] val, Expression[] exprs)
{
Expression<Func<double[]>> e =
Expression.Lambda<Func<double[]>>(
Expression.NewArrayInit(typeof(double), exprs),
Enumerable.Empty<ParameterExpression>());
Func<double[]> f = e.Compile();
double[] result = f();
Assert.Equal(val.Length, result.Length);
for (int i = 0; i < result.Length; i++)
{
Assert.Equal(val[i], result[i]);
}
}
private static void VerifyEnumArrayList(E[] val, Expression[] exprs)
{
Expression<Func<E[]>> e =
Expression.Lambda<Func<E[]>>(
Expression.NewArrayInit(typeof(E), exprs),
Enumerable.Empty<ParameterExpression>());
Func<E[]> f = e.Compile();
E[] result = f();
Assert.Equal(val.Length, result.Length);
for (int i = 0; i < result.Length; i++)
{
Assert.Equal(val[i], result[i]);
}
}
private static void VerifyEnumLongArrayList(El[] val, Expression[] exprs)
{
Expression<Func<El[]>> e =
Expression.Lambda<Func<El[]>>(
Expression.NewArrayInit(typeof(El), exprs),
Enumerable.Empty<ParameterExpression>());
Func<El[]> f = e.Compile();
El[] result = f();
Assert.Equal(val.Length, result.Length);
for (int i = 0; i < result.Length; i++)
{
Assert.Equal(val[i], result[i]);
}
}
private static void VerifyFloatArrayList(float[] val, Expression[] exprs)
{
Expression<Func<float[]>> e =
Expression.Lambda<Func<float[]>>(
Expression.NewArrayInit(typeof(float), exprs),
Enumerable.Empty<ParameterExpression>());
Func<float[]> f = e.Compile();
float[] result = f();
Assert.Equal(val.Length, result.Length);
for (int i = 0; i < result.Length; i++)
{
Assert.Equal(val[i], result[i]);
}
}
private static void VerifyFuncArrayList(Func<object>[] val, Expression[] exprs)
{
Expression<Func<Func<object>[]>> e =
Expression.Lambda<Func<Func<object>[]>>(
Expression.NewArrayInit(typeof(Func<object>), exprs),
Enumerable.Empty<ParameterExpression>());
Func<Func<object>[]> f = e.Compile();
Func<object>[] result = f();
Assert.Equal(val.Length, result.Length);
for (int i = 0; i < result.Length; i++)
{
Assert.Equal(val[i], result[i]);
}
}
private static void VerifyInterfaceArrayList(I[] val, Expression[] exprs)
{
Expression<Func<I[]>> e =
Expression.Lambda<Func<I[]>>(
Expression.NewArrayInit(typeof(I), exprs),
Enumerable.Empty<ParameterExpression>());
Func<I[]> f = e.Compile();
I[] result = f();
Assert.Equal(val.Length, result.Length);
for (int i = 0; i < result.Length; i++)
{
Assert.Equal(val[i], result[i]);
}
}
private static void VerifyIEquatableCustomArrayList(IEquatable<C>[] val, Expression[] exprs)
{
Expression<Func<IEquatable<C>[]>> e =
Expression.Lambda<Func<IEquatable<C>[]>>(
Expression.NewArrayInit(typeof(IEquatable<C>), exprs),
Enumerable.Empty<ParameterExpression>());
Func<IEquatable<C>[]> f = e.Compile();
IEquatable<C>[] result = f();
Assert.Equal(val.Length, result.Length);
for (int i = 0; i < result.Length; i++)
{
Assert.Equal(val[i], result[i]);
}
}
private static void VerifyIEquatableCustom2ArrayList(IEquatable<D>[] val, Expression[] exprs)
{
Expression<Func<IEquatable<D>[]>> e =
Expression.Lambda<Func<IEquatable<D>[]>>(
Expression.NewArrayInit(typeof(IEquatable<D>), exprs),
Enumerable.Empty<ParameterExpression>());
Func<IEquatable<D>[]> f = e.Compile();
IEquatable<D>[] result = f();
Assert.Equal(val.Length, result.Length);
for (int i = 0; i < result.Length; i++)
{
Assert.Equal(val[i], result[i]);
}
}
private static void VerifyIntArrayList(int[] val, Expression[] exprs)
{
Expression<Func<int[]>> e =
Expression.Lambda<Func<int[]>>(
Expression.NewArrayInit(typeof(int), exprs),
Enumerable.Empty<ParameterExpression>());
Func<int[]> f = e.Compile();
int[] result = f();
Assert.Equal(val.Length, result.Length);
for (int i = 0; i < result.Length; i++)
{
Assert.Equal(val[i], result[i]);
}
}
private static void VerifyLongArrayList(long[] val, Expression[] exprs)
{
Expression<Func<long[]>> e =
Expression.Lambda<Func<long[]>>(
Expression.NewArrayInit(typeof(long), exprs),
Enumerable.Empty<ParameterExpression>());
Func<long[]> f = e.Compile();
long[] result = f();
Assert.Equal(val.Length, result.Length);
for (int i = 0; i < result.Length; i++)
{
Assert.Equal(val[i], result[i]);
}
}
private static void VerifyObjectArrayList(object[] val, Expression[] exprs)
{
Expression<Func<object[]>> e =
Expression.Lambda<Func<object[]>>(
Expression.NewArrayInit(typeof(object), exprs),
Enumerable.Empty<ParameterExpression>());
Func<object[]> f = e.Compile();
object[] result = f();
Assert.Equal(val.Length, result.Length);
for (int i = 0; i < result.Length; i++)
{
Assert.Equal(val[i], result[i]);
}
}
private static void VerifyStructArrayList(S[] val, Expression[] exprs)
{
Expression<Func<S[]>> e =
Expression.Lambda<Func<S[]>>(
Expression.NewArrayInit(typeof(S), exprs),
Enumerable.Empty<ParameterExpression>());
Func<S[]> f = e.Compile();
S[] result = f();
Assert.Equal(val.Length, result.Length);
for (int i = 0; i < result.Length; i++)
{
Assert.Equal(val[i], result[i]);
}
}
private static void VerifySByteArrayList(sbyte[] val, Expression[] exprs)
{
Expression<Func<sbyte[]>> e =
Expression.Lambda<Func<sbyte[]>>(
Expression.NewArrayInit(typeof(sbyte), exprs),
Enumerable.Empty<ParameterExpression>());
Func<sbyte[]> f = e.Compile();
sbyte[] result = f();
Assert.Equal(val.Length, result.Length);
for (int i = 0; i < result.Length; i++)
{
Assert.Equal(val[i], result[i]);
}
}
private static void VerifyStructWithStringArrayList(Sc[] val, Expression[] exprs)
{
Expression<Func<Sc[]>> e =
Expression.Lambda<Func<Sc[]>>(
Expression.NewArrayInit(typeof(Sc), exprs),
Enumerable.Empty<ParameterExpression>());
Func<Sc[]> f = e.Compile();
Sc[] result = f();
Assert.Equal(val.Length, result.Length);
for (int i = 0; i < result.Length; i++)
{
Assert.Equal(val[i], result[i]);
}
}
private static void VerifyStructWithStringAndFieldArrayList(Scs[] val, Expression[] exprs)
{
Expression<Func<Scs[]>> e =
Expression.Lambda<Func<Scs[]>>(
Expression.NewArrayInit(typeof(Scs), exprs),
Enumerable.Empty<ParameterExpression>());
Func<Scs[]> f = e.Compile();
Scs[] result = f();
Assert.Equal(val.Length, result.Length);
for (int i = 0; i < result.Length; i++)
{
Assert.Equal(val[i], result[i]);
}
}
private static void VerifyShortArrayList(short[] val, Expression[] exprs)
{
Expression<Func<short[]>> e =
Expression.Lambda<Func<short[]>>(
Expression.NewArrayInit(typeof(short), exprs),
Enumerable.Empty<ParameterExpression>());
Func<short[]> f = e.Compile();
short[] result = f();
Assert.Equal(val.Length, result.Length);
for (int i = 0; i < result.Length; i++)
{
Assert.Equal(val[i], result[i]);
}
}
private static void VerifyStructWithTwoValuesArrayList(Sp[] val, Expression[] exprs)
{
Expression<Func<Sp[]>> e =
Expression.Lambda<Func<Sp[]>>(
Expression.NewArrayInit(typeof(Sp), exprs),
Enumerable.Empty<ParameterExpression>());
Func<Sp[]> f = e.Compile();
Sp[] result = f();
Assert.Equal(val.Length, result.Length);
for (int i = 0; i < result.Length; i++)
{
Assert.Equal(val[i], result[i]);
}
}
private static void VerifyStructWithValueArrayList(Ss[] val, Expression[] exprs)
{
Expression<Func<Ss[]>> e =
Expression.Lambda<Func<Ss[]>>(
Expression.NewArrayInit(typeof(Ss), exprs),
Enumerable.Empty<ParameterExpression>());
Func<Ss[]> f = e.Compile();
Ss[] result = f();
Assert.Equal(val.Length, result.Length);
for (int i = 0; i < result.Length; i++)
{
Assert.Equal(val[i], result[i]);
}
}
private static void VerifyStringArrayList(string[] val, Expression[] exprs)
{
Expression<Func<string[]>> e =
Expression.Lambda<Func<string[]>>(
Expression.NewArrayInit(typeof(string), exprs),
Enumerable.Empty<ParameterExpression>());
Func<string[]> f = e.Compile();
string[] result = f();
Assert.Equal(val.Length, result.Length);
for (int i = 0; i < result.Length; i++)
{
Assert.Equal(val[i], result[i]);
}
}
private static void VerifyUIntArrayList(uint[] val, Expression[] exprs)
{
Expression<Func<uint[]>> e =
Expression.Lambda<Func<uint[]>>(
Expression.NewArrayInit(typeof(uint), exprs),
Enumerable.Empty<ParameterExpression>());
Func<uint[]> f = e.Compile();
uint[] result = f();
Assert.Equal(val.Length, result.Length);
for (int i = 0; i < result.Length; i++)
{
Assert.Equal(val[i], result[i]);
}
}
private static void VerifyULongArrayList(ulong[] val, Expression[] exprs)
{
Expression<Func<ulong[]>> e =
Expression.Lambda<Func<ulong[]>>(
Expression.NewArrayInit(typeof(ulong), exprs),
Enumerable.Empty<ParameterExpression>());
Func<ulong[]> f = e.Compile();
ulong[] result = f();
Assert.Equal(val.Length, result.Length);
for (int i = 0; i < result.Length; i++)
{
Assert.Equal(val[i], result[i]);
}
}
private static void VerifyUShortArrayList(ushort[] val, Expression[] exprs)
{
Expression<Func<ushort[]>> e =
Expression.Lambda<Func<ushort[]>>(
Expression.NewArrayInit(typeof(ushort), exprs),
Enumerable.Empty<ParameterExpression>());
Func<ushort[]> f = e.Compile();
ushort[] result = f();
Assert.Equal(val.Length, result.Length);
for (int i = 0; i < result.Length; i++)
{
Assert.Equal(val[i], result[i]);
}
}
private static void VerifyGenericArrayList<T>(T[] val, Expression[] exprs)
{
Expression<Func<T[]>> e =
Expression.Lambda<Func<T[]>>(
Expression.NewArrayInit(typeof(T), exprs),
Enumerable.Empty<ParameterExpression>());
Func<T[]> f = e.Compile();
T[] result = f();
Assert.Equal(val.Length, result.Length);
for (int i = 0; i < result.Length; i++)
{
Assert.Equal(val[i], result[i]);
}
}
private static void VerifyGenericWithClassRestrictionArrayList<Tc>(Tc[] val, Expression[] exprs) where Tc : class
{
Expression<Func<Tc[]>> e =
Expression.Lambda<Func<Tc[]>>(
Expression.NewArrayInit(typeof(Tc), exprs),
Enumerable.Empty<ParameterExpression>());
Func<Tc[]> f = e.Compile();
Tc[] result = f();
Assert.Equal(val.Length, result.Length);
for (int i = 0; i < result.Length; i++)
{
Assert.Equal(val[i], result[i]);
}
}
private static void VerifyGenericWithSubClassRestrictionArrayList<TC>(TC[] val, Expression[] exprs) where TC : C
{
Expression<Func<TC[]>> e =
Expression.Lambda<Func<TC[]>>(
Expression.NewArrayInit(typeof(TC), exprs),
Enumerable.Empty<ParameterExpression>());
Func<TC[]> f = e.Compile();
TC[] result = f();
Assert.Equal(val.Length, result.Length);
for (int i = 0; i < result.Length; i++)
{
Assert.Equal(val[i], result[i]);
}
}
private static void VerifyGenericWithClassAndNewRestrictionArrayList<Tcn>(Tcn[] val, Expression[] exprs) where Tcn : class, new()
{
Expression<Func<Tcn[]>> e =
Expression.Lambda<Func<Tcn[]>>(
Expression.NewArrayInit(typeof(Tcn), exprs),
Enumerable.Empty<ParameterExpression>());
Func<Tcn[]> f = e.Compile();
Tcn[] result = f();
Assert.Equal(val.Length, result.Length);
for (int i = 0; i < result.Length; i++)
{
Assert.Equal(val[i], result[i]);
}
}
private static void VerifyGenericWithSubClassAndNewRestrictionArrayList<TCn>(TCn[] val, Expression[] exprs) where TCn : C, new()
{
Expression<Func<TCn[]>> e =
Expression.Lambda<Func<TCn[]>>(
Expression.NewArrayInit(typeof(TCn), exprs),
Enumerable.Empty<ParameterExpression>());
Func<TCn[]> f = e.Compile();
TCn[] result = f();
Assert.Equal(val.Length, result.Length);
for (int i = 0; i < result.Length; i++)
{
Assert.Equal(val[i], result[i]);
}
}
private static void VerifyGenericWithStructRestrictionArrayList<Ts>(Ts[] val, Expression[] exprs) where Ts : struct
{
Expression<Func<Ts[]>> e =
Expression.Lambda<Func<Ts[]>>(
Expression.NewArrayInit(typeof(Ts), exprs),
Enumerable.Empty<ParameterExpression>());
Func<Ts[]> f = e.Compile();
Ts[] result = f();
Assert.Equal(val.Length, result.Length);
for (int i = 0; i < result.Length; i++)
{
Assert.Equal(val[i], result[i]);
}
}
#endregion
}
}
| |
using System;
using System.Data;
using PrimerProObjects;
using GenLib;
namespace PrimerProSearch
{
/// <summary>
///
/// </summary>
public class ContextChartTable : DataTable
{
private DataColumn m_DataColumn;
private DataRow m_DataRow;
private DataSet m_DataSet;
private string m_ID;
public const string kWordInit = "WI";
public const string kWordMedial = "WM";
public const string kWordFinal = "WF";
public const string kSyllInit = "SI";
public const string kSyllMedial = "SM";
public const string kSyllFinal = "SF";
public const string kInitSyll = "IS";
public const string kMedialSyll = "MS";
public const string kFinalSyll = "FS";
public const string kInRoots = "IR";
public const string kInAffxs = "IA";
public const string kOpenSyll = "OS";
public const string kClosdSyll = "CS";
public const string kFirstRootC = "FRC";
public const string kSecndRootC = "SRC";
public const string kFirstRootV = "FRV";
public const string kSecndRootV = "SRV";
public ContextChartTable(ContextChartSearch search)
{
m_ID = "ID";
//ID column
m_DataColumn = new DataColumn();
m_DataColumn.DataType = System.Type.GetType("System.String");
m_DataColumn.ColumnName = m_ID;
m_DataColumn.AutoIncrement = false;
m_DataColumn.ReadOnly = false;
m_DataColumn.Unique = true;
this.Columns.Add(m_DataColumn);
// Columns
if (search.WordInit)
this.AddColumn(ContextChartTable.kWordInit, "Word Init");
if (search.WordMedial)
this.AddColumn(ContextChartTable.kWordMedial, "Word Med");
if (search.WordFinal)
this.AddColumn(ContextChartTable.kWordFinal, "Word Fina");
if (search.SyllableInit)
this.AddColumn(ContextChartTable.kSyllInit, "Syll Init");
if (search.SyllableMedial)
this.AddColumn(ContextChartTable.kSyllMedial, "Syll Med");
if (search.SyllableFinal)
this.AddColumn(ContextChartTable.kSyllFinal, "Syll Fina");
if (search.InitSyllable)
this.AddColumn(ContextChartTable.kInitSyll, "Init Syll");
if (search.MedialSyllable)
this.AddColumn(ContextChartTable.kMedialSyll, "Med Syll");
if (search.FinalSyllable)
this.AddColumn(ContextChartTable.kFinalSyll, "Fina Syll");
if (search.InRoots)
this.AddColumn(ContextChartTable.kInRoots, "In Roots");
if (search.InAffixes)
this.AddColumn(ContextChartTable.kInAffxs, "In Affxs");
if (search.OpenSyllables)
this.AddColumn(ContextChartTable.kOpenSyll, "Open Syll");
if (search.ClosedSyllables)
this.AddColumn(ContextChartTable.kClosdSyll, "Clos Syll");
if (search.FirstRootC)
this.AddColumn(ContextChartTable.kFirstRootC, "1st RootC");
if (search.SecondRootC)
this.AddColumn(ContextChartTable.kSecndRootC, "2nd RootC");
if (search.FirstRootV)
this.AddColumn(ContextChartTable.kFirstRootV, "1st RootV");
if (search.SecondRootV)
this.AddColumn(ContextChartTable.kSecndRootV, "2nd RootV");
//Rows
if (search.IsConsonantChart())
{
Consonant cns = null;
for (int i = 0; i < search.GI.ConsonantCount(); i++)
{
cns = search.GI.GetConsonant(i);
if (cns.MatchesFeatures(search.CFeatures))
{
m_DataRow = this.NewRow();
m_DataRow[m_ID] = cns.Symbol;
this.Rows.Add(m_DataRow);
}
}
}
if (search.IsVowelChart())
{
Vowel vwl = null;
for (int i = 0; i < search.GI.VowelCount(); i++)
{
vwl = search.GI.GetVowel(i);
if (vwl.MatchesFeatures(search.VFeatures))
{
m_DataRow = this.NewRow();
m_DataRow[m_ID] = vwl.Symbol;
this.Rows.Add(m_DataRow);
}
}
}
// Make the ID column the primary key column.
DataColumn[] dcPrimaryKey = new DataColumn[1];
dcPrimaryKey[0] = this.Columns[m_ID];
this.PrimaryKey = dcPrimaryKey;
// Add the new DataTable to the DataSet.
m_DataSet = new DataSet();
m_DataSet.Tables.Add(this);
}
public DataSet GetDataSet()
{
return m_DataSet;
}
public DataRow GetDataRow(int n)
{
if (n < this.Rows.Count)
return this.Rows[n];
else return null;
}
public DataColumn GetDataColumn(int n)
{
if (n < this.Columns.Count)
return this.Columns[n];
else return null;
}
public string GetID()
{
return m_ID;
}
public int GetRowIndex(string strId)
{
int num = 0;
bool found = false;
DataRow dr = null;
for (int i = 0; i < this.Rows.Count; i++)
{
dr = this.GetDataRow(i);
if ((string) dr[m_ID] == strId)
{
num = i;
found = true;
break;
}
}
if (!found) //Row does not exist yet, so add it
{
m_DataRow = this.NewRow();
m_DataRow[m_ID] = strId;
this.Rows.Add(m_DataRow);
num = this.Rows.Count - 1;
}
return num;
}
public int GetColumnIndex(string strColName)
{
return this.Columns.IndexOf(strColName);
}
public string GetColumnHeaders()
{
string strHdrs = "";
string strHdrs1 = "";
string strHdrs2 = "";
string strTab = Constants.Tab;
char chSpace = Constants.Space;
int ndx;
foreach (DataColumn dc in this.Columns)
{
if (dc.ColumnName != this.GetID())
{
ndx = dc.Caption.IndexOf(chSpace);
strHdrs1 += strTab + dc.Caption.Substring(0, ndx).Trim();
strHdrs2 += strTab + dc.Caption.Substring(ndx+1).Trim();
}
strHdrs = strHdrs1 + strTab + Environment.NewLine;
strHdrs += strHdrs2 + strTab + Environment.NewLine;
strHdrs = Constants.kHCOn + strHdrs + Constants.kHCOff;
}
return strHdrs;
}
public string GetRows()
{
string strRow = "";
WordList wl = null;
int nSize = 0;
foreach (DataRow dr in this.Rows)
{
nSize = dr.ItemArray.Length;
strRow += Constants.kHCOn + dr[this.GetID()].ToString()
+ Constants.Tab + Constants.kHCOff;
for (int i = 1; i < nSize; i++)
{
if (dr.ItemArray[i].ToString() != "")
{
wl = (WordList)dr.ItemArray[i];
strRow += wl.WordCount().ToString().PadLeft(5) + Constants.Tab;
}
else strRow += Constants.Space.ToString().PadLeft(5) + Constants.Tab;
;
}
strRow += Environment.NewLine;
}
return strRow;
}
public WordList GetWordList(int row, int col)
{
WordList wl = null;
DataRow dr = this.Rows[row];
if (dr.ItemArray[col].ToString() != "")
wl = (WordList)dr.ItemArray[col];
return wl;
}
public void UpdateChartCell(int row, int col, Word wrd)
{
int num = 0;
object obj = null;
WordList wl = null;
DataRow dr = null;
num = this.Rows.Count;
dr = this.Rows[row];
object[] ia = dr.ItemArray;
if (ia.GetValue(col).ToString() != "")
{
obj = ia.GetValue(col);
if (obj == null)
wl = new WordList();
else wl = (WordList)obj;
wl.AddWord(wrd);
obj = (object)wl;
}
else
{
wl = new WordList();
wl.AddWord(wrd);
obj = (object)wl;
}
ia.SetValue(obj, col);
this.AcceptChanges();
this.BeginLoadData();
dr = this.LoadDataRow(ia, false);
this.EndLoadData();
}
private void AddColumn(string strName, string strCaption)
{
m_DataColumn = new DataColumn();
//m_DataColumn.DataType = System.Type.GetType("System.String");
//m_DataColumn.DataType = System.Type.GetType("PrimerProObjects.WordList");
m_DataColumn.DataType = typeof(PrimerProObjects.WordList);
m_DataColumn.ColumnName = strName;
m_DataColumn.Caption = strCaption;
m_DataColumn.AutoIncrement = false;
m_DataColumn.ReadOnly = false;
m_DataColumn.Unique = false;
this.Columns.Add(m_DataColumn);
}
}
}
| |
namespace Microsoft.Protocols.TestSuites.MS_OXWSFOLD
{
using System.Xml;
using Microsoft.Protocols.TestSuites.Common;
using Microsoft.Protocols.TestTools;
using Microsoft.VisualStudio.TestTools.UnitTesting;
/// <summary>
/// This scenario is designed to verify GetFolder operation.
/// </summary>
[TestClass]
public class S04_GetFolder : TestSuiteBase
{
#region Class initialize and clean up
/// <summary>
/// Initialize the test class.
/// </summary>
/// <param name="testContext">Context to initialize.</param>
[ClassInitialize]
public static void ClassInitialize(TestContext testContext)
{
TestClassBase.Initialize(testContext);
}
/// <summary>
/// Clean up the test class.
/// </summary>
[ClassCleanup]
public static void ClassCleanup()
{
TestClassBase.Cleanup();
}
#endregion
#region Test cases
/// <summary>
/// This test case verifies requirements related to getting calendar folder.
/// </summary>
[TestCategory("MSOXWSFOLD"), TestMethod()]
public void MSOXWSFOLD_S04_TC01_GetCalendarFolder()
{
#region Get the Calendar folder.
DistinguishedFolderIdType folder = new DistinguishedFolderIdType();
folder.Id = (DistinguishedFolderIdNameType)DistinguishedFolderIdNameType.calendar;
// GetFolder request.
GetFolderType getCalendarFolderRequest = this.GetGetFolderRequest(DefaultShapeNamesType.IdOnly, folder);
// Set to get additional property : folder class
getCalendarFolderRequest.FolderShape.AdditionalProperties = new BasePathToElementType[]
{
new PathToUnindexedFieldType()
{
FieldURI = UnindexedFieldURIType.folderFolderClass
},
new PathToUnindexedFieldType()
{
FieldURI = UnindexedFieldURIType.folderEffectiveRights
}
};
// Get the Calendar folder.
GetFolderResponseType getCalendarFolderResponse = this.FOLDAdapter.GetFolder(getCalendarFolderRequest);
// Check the response.
Common.CheckOperationSuccess(getCalendarFolderResponse, 1, this.Site);
// Variable to save the folder.
FolderInfoResponseMessageType foldersResponseInfo = (FolderInfoResponseMessageType)getCalendarFolderResponse.ResponseMessages.Items[0];
// Add the debug information
this.Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXWSFOLD_R29");
// Verify MS-OXWSFOLD requirement: MS-OXWSFOLD_R29
this.Site.CaptureRequirementIfIsInstanceOfType(
foldersResponseInfo.Folders[0],
typeof(CalendarFolderType),
29,
@"[In t:ArrayOfFoldersType Complex Type]The type of element CalendarFolder is t:CalendarFolderType ([MS-OXWSMTGS] section 2.2.4.5).");
// Add the debug information
this.Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXWSFOLD_R2901");
// Verify MS-OXWSFOLD requirement: MS-OXWSFOLD_R2901
this.Site.CaptureRequirementIfIsInstanceOfType(
foldersResponseInfo.Folders[0],
typeof(CalendarFolderType),
2901,
@"[In t:ArrayOfFoldersType Complex Type]CalendarFolder represents a Calendar folder in a mailbox.");
CalendarFolderType folderInfo = (CalendarFolderType)foldersResponseInfo.Folders[0];
// Add the debug information
this.Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXWSFOLD_R81");
// Verify MS-OXWSFOLD requirement: MS-OXWSFOLD_R81
// Since the schema has been validate and this element is not null, this requirement will be captured.
this.Site.CaptureRequirementIfIsNotNull(
folderInfo.EffectiveRights,
81,
@"[In t:BaseFolderType Complex Type]The type of element EffectiveRights is t:EffectiveRightsType ([MS-OXWSCDATA] section 2.2.4.29).");
// Add the debug information
this.Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXWSFOLD_R5934");
// Verify MS-OXWSFOLD requirement: MS-OXWSFOLD_R5934
// Effective rights is returned in response and schema is verified in adapter so this requirement can be captured.
this.Site.CaptureRequirementIfIsNotNull(
folderInfo.EffectiveRights,
5934,
@"[In t:BaseFolderType Complex Type]This property[EffectiveRights] is returned in a response.");
// Add the debug information.
Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXWSFOLD_R70.");
// Verify MS-OXWSFOLD_R70.
Site.CaptureRequirementIfAreEqual<string>(
"IPF.Appointment",
folderInfo.FolderClass,
70,
@"[In t:BaseFolderType Complex Type]This value[FolderClass] MUST be ""IPF.Appointment"" for Calendar folders.");
// Add the debug information
this.Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXWSFOLD_R42104");
// Verify MS-OXWSFOLD requirement: MS-OXWSFOLD_R42104
// Additional property folder class is returned from server and schema is verified in adapter, so this requirement can be captured.
this.Site.CaptureRequirementIfIsNotNull(
folderInfo.FolderClass,
42104,
@"[In t:FolderResponseShapeType Complex Type]The element [AdditionalProperties] with type [t:NonEmptyArrayOfPathsToElementType] specifies the identity of additional properties to be returned in a response.");
// Add the debug information
this.Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXWSFOLD_R42105");
// Verify MS-OXWSFOLD requirement: MS-OXWSFOLD_R42105
// Additional property folder class is returned from server and schema is verified in adapter, so this requirement can be captured.
this.Site.CaptureRequirementIfIsNotNull(
folderInfo.FolderClass,
42105,
@"[In t:FolderResponseShapeType Complex Type][In t:NonEmptyArrayOfPathsToElementType Complex Type] The element [t:Path] with type [t:Path] specifies a property to be returned in a response.");
// Add the debug information
this.Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXWSFOLD_R3864");
// Verify MS-OXWSFOLD requirement: MS-OXWSFOLD_R3864
this.Site.CaptureRequirementIfAreEqual<ResponseClassType>(
ResponseClassType.Success,
getCalendarFolderResponse.ResponseMessages.Items[0].ResponseClass,
3864,
@"[In GetFolder Operation]A successful GetFolder operation request returns a GetFolderResponse element with the ResponseClass attribute of the GetFolderResponseMessage element set to ""Success"".");
// Add the debug information
this.Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXWSFOLD_R38644");
// Verify MS-OXWSFOLD requirement: MS-OXWSFOLD_R38644
this.Site.CaptureRequirementIfAreEqual<ResponseCodeType>(
ResponseCodeType.NoError,
getCalendarFolderResponse.ResponseMessages.Items[0].ResponseCode,
38644,
@"[In GetFolder Operation]A successful GetFolder operation request returns a GetFolderResponse element with the ResponseCode element of the GetFolderResponse element set to ""NoError"".");
// Add the debug information
this.Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXWSFOLD_R575");
// Verify MS-OXWSFOLD requirement: MS-OXWSFOLD_R575
// Folder information is returned from server and schema has verified in adapter, so this requirement can be covered.
this.Site.CaptureRequirementIfIsNotNull(
foldersResponseInfo,
575,
@"[In m:GetFolderType Complex Type]The GetFolderType complex type specifies a request message to get a folder in a server database.");
// Add the debug information
this.Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXWSFOLD_R428");
// GetFolder operation in this test case gets a distinguished folder : Calendar folder.
this.Site.CaptureRequirement(
428,
@"[In t:NonEmptyArrayOfBaseFolderIdsType Complex Type]DistinguishedFolderId specifies a distinguished folder identifier.");
// Add the debug information
this.Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXWSFOLD_R8402");
// GetFolder operation in this test case gets a distinguished folder : Calendar folder.
this.Site.CaptureRequirement(
8402,
@"[In t:BaseFolderType Complex Type]DistinguishedFolderId specifies an identifier for a folder that can be referenced by name.");
// Add the debug information
this.Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXWSFOLD_R96");
// Verify MS-OXWSFOLD requirement: MS-OXWSFOLD_R96
// Folder information is returned from server and schema has verified in adapter, so this requirement can be covered.
this.Site.CaptureRequirementIfIsNotNull(
foldersResponseInfo,
96,
@"[In m:FolderInfoResponseMessageType Complex Type]The type of element Folders is t:ArrayOfFoldersType (section 2.2.4.2).");
// Add the debug information
this.Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXWSFOLD_R9602");
// Verify MS-OXWSFOLD requirement: MS-OXWSFOLD_R9602
// Folder information is returned from server and schema has verified in adapter, so this requirement can be covered.
this.Site.CaptureRequirementIfIsNotNull(
foldersResponseInfo,
9602,
@"[In m:FolderInfoResponseMessageType Complex Type][Folders] Represents the folders that are returned with the response message.");
// Add the debug information
this.Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXWSFOLD_R8401");
// Verify MS-OXWSFOLD requirement: MS-OXWSFOLD_R8401
// Distinguished folder id is set in request and schema is verified in adapter, so if folder information is returned successfully this can be covered.
this.Site.CaptureRequirementIfAreEqual<ResponseClassType>(
ResponseClassType.Success,
getCalendarFolderResponse.ResponseMessages.Items[0].ResponseClass,
8401,
@"[In t:BaseFolderType Complex Type]The type of element DistinguishedFolderId is t:DistinguishedFolderIdNameType ([MS-OXWSCDATA] section 2.2.5.10).");
#endregion
}
/// <summary>
/// This test case verifies requirements related to getting contacts folder.
/// </summary>
[TestCategory("MSOXWSFOLD"), TestMethod()]
public void MSOXWSFOLD_S04_TC02_GetContactsFolder()
{
#region Get the contacts folder.
DistinguishedFolderIdType folder = new DistinguishedFolderIdType();
folder.Id = DistinguishedFolderIdNameType.contacts;
// GetFolder request.
GetFolderType getContactsFolderRequest = this.GetGetFolderRequest(DefaultShapeNamesType.AllProperties, folder);
// Get the Contacts folder.
GetFolderResponseType getContactsFolderResponse = this.FOLDAdapter.GetFolder(getContactsFolderRequest);
// Check the response.
Common.CheckOperationSuccess(getContactsFolderResponse, 1, this.Site);
// Variable to save the folder.
FolderInfoResponseMessageType allFolders = (FolderInfoResponseMessageType)getContactsFolderResponse.ResponseMessages.Items[0];
#endregion
// Add the debug information
this.Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXWSFOLD_R31");
// Verify MS-OXWSFOLD requirement: MS-OXWSFOLD_R31
this.Site.CaptureRequirementIfIsInstanceOfType(
allFolders.Folders[0],
typeof(ContactsFolderType),
31,
@"[In t:ArrayOfFoldersType Complex Type]The type of element ContactsFolder is t:ContactsFolderType ([MS-OXWSCONT] section 3.1.4.1.1.6).");
// Add the debug information
this.Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXWSFOLD_R3301");
// Verify MS-OXWSFOLD requirement: MS-OXWSFOLD_R3301
this.Site.CaptureRequirementIfIsInstanceOfType(
allFolders.Folders[0],
typeof(ContactsFolderType),
3301,
@"[In t:ArrayOfFoldersType Complex Type]ContactsFolder represents a Contacts folder in a mailbox.");
ContactsFolderType folderInfo = (ContactsFolderType)allFolders.Folders[0];
// Add the debug information
this.Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXWSFOLD_R69");
// Verify MS-OXWSFOLD requirement: MS-OXWSFOLD_R69
// Folder class value is returned from server and schema has verified in adapter, so this requirement can be covered.
this.Site.CaptureRequirementIfIsNotNull(
folderInfo.FolderClass,
69,
@"[In t:BaseFolderType Complex Type]The type of element FolderClass is xs:string [XMLSCHEMA2].");
// Add the debug information.
Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXWSFOLD_R585.");
// Verify MS-OXWSFOLD_R585.
Site.CaptureRequirementIfAreEqual<string>(
"IPF.Contact",
folderInfo.FolderClass,
585,
@"[In t:BaseFolderType Complex Type]This value[FolderClass] MUST be ""IPF.Contact"" for Contacts folders.");
// Add the debug information
this.Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXWSFOLD_R7101");
// Verify MS-OXWSFOLD requirement: MS-OXWSFOLD_R7101
this.Site.CaptureRequirementIfAreEqual<string>(
"Contacts",
folderInfo.DisplayName,
7101,
@"[In t:BaseFolderType Complex Type]DisplayName specifies the display name of the folder.");
// Add the debug information
this.Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXWSFOLD_R71");
// Verify MS-OXWSFOLD requirement: MS-OXWSFOLD_R71
// Folder display name is returned from server and schema has verified in adapter, so this requirement can be covered.
this.Site.CaptureRequirementIfIsNotNull(
folderInfo.DisplayName,
71,
@"[In t:BaseFolderType Complex Type]The type of element DisplayName is xs:string.");
// Add the debug information
this.Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXWSFOLD_R66");
// Verify MS-OXWSFOLD requirement: MS-OXWSFOLD_R66
// Folder id is returned from server and schema has verified in adapter, so this requirement can be covered.
this.Site.CaptureRequirementIfIsNotNull(
folderInfo.FolderId,
66,
@"[In t:BaseFolderType Complex Type]The type of element FolderId is t:FolderIdType ([MS-OXWSCDATA] section 2.2.4.36).");
// Add the debug information
this.Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXWSFOLD_R6602");
// Verify MS-OXWSFOLD requirement: MS-OXWSFOLD_R6602
// Folder id is returned from server and schema is verified in adapter so this requirement can be covered.
this.Site.CaptureRequirementIfIsNotNull(
folderInfo.FolderId,
6602,
@"[In t:BaseFolderType Complex Type]FolderId specifies the folder identifier and change key.");
}
/// <summary>
/// This test case verifies requirements related to getting journal folder.
/// </summary>
[TestCategory("MSOXWSFOLD"), TestMethod()]
public void MSOXWSFOLD_S04_TC03_GetJournalFolder()
{
#region Get the Journal folder.
DistinguishedFolderIdType folder = new DistinguishedFolderIdType();
folder.Id = DistinguishedFolderIdNameType.journal;
// GetFolder request.
GetFolderType getJournalFolderRequest = this.GetGetFolderRequest(DefaultShapeNamesType.AllProperties, folder);
// Get the journal folder.
GetFolderResponseType getJournalFolderResponse = this.FOLDAdapter.GetFolder(getJournalFolderRequest);
// Check the response.
Common.CheckOperationSuccess(getJournalFolderResponse, 1, this.Site);
// Variable to save the folder.
FolderInfoResponseMessageType allFolders = (FolderInfoResponseMessageType)getJournalFolderResponse.ResponseMessages.Items[0];
BaseFolderType folderInfo = (BaseFolderType)allFolders.Folders[0];
#endregion
// Add the debug information.
Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXWSFOLD_R586.");
// Verify MS-OXWSFOLD_R586.
Site.CaptureRequirementIfAreEqual<string>(
"IPF.Journal",
folderInfo.FolderClass,
586,
@"[In t:BaseFolderType Complex Type]This value[FolderClass] MUST be ""IPF.Journal"" for journal folders.");
}
/// <summary>
/// This test case verifies requirements related to getting inbox folder.
/// </summary>
[TestCategory("MSOXWSFOLD"), TestMethod()]
public void MSOXWSFOLD_S04_TC04_GetInboxFolder()
{
#region Get the Inbox folder.
DistinguishedFolderIdType folder = new DistinguishedFolderIdType();
folder.Id = DistinguishedFolderIdNameType.inbox;
// GetFolder request.
GetFolderType getInboxFolderRequest = this.GetGetFolderRequest(DefaultShapeNamesType.AllProperties, folder);
// Get the inbox folder.
GetFolderResponseType getInboxFolderResponse = this.FOLDAdapter.GetFolder(getInboxFolderRequest);
// Check the response.
Common.CheckOperationSuccess(getInboxFolderResponse, 1, this.Site);
// Variable to save the folder.
FolderInfoResponseMessageType allFolders = (FolderInfoResponseMessageType)getInboxFolderResponse.ResponseMessages.Items[0];
BaseFolderType folderInfo = (BaseFolderType)allFolders.Folders[0];
#endregion
// Add the debug information.
Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXWSFOLD_R587.");
// Verify MS-OXWSFOLD_R587.
Site.CaptureRequirementIfAreEqual<string>(
"IPF.Note",
folderInfo.FolderClass,
587,
@"[In t:BaseFolderType Complex Type]This value[FolderClass] MUST be ""IPF.Note"" for mail folders.");
}
/// <summary>
/// This test case verifies requirements related to getting notes folder.
/// </summary>
[TestCategory("MSOXWSFOLD"), TestMethod()]
public void MSOXWSFOLD_S04_TC05_GetNotesFolder()
{
#region Get the notes folder.
DistinguishedFolderIdType folder = new DistinguishedFolderIdType();
folder.Id = DistinguishedFolderIdNameType.notes;
// GetFolder request.
GetFolderType getNotesFolderRequest = this.GetGetFolderRequest(DefaultShapeNamesType.AllProperties, folder);
// Get the notes folder.
GetFolderResponseType getNotesFolderResponse = this.FOLDAdapter.GetFolder(getNotesFolderRequest);
// Check the response.
Common.CheckOperationSuccess(getNotesFolderResponse, 1, this.Site);
// Variable to save the folder.
FolderInfoResponseMessageType allFolders = (FolderInfoResponseMessageType)getNotesFolderResponse.ResponseMessages.Items[0];
BaseFolderType folderInfo = (BaseFolderType)allFolders.Folders[0];
#endregion
// Add the debug information.
Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXWSFOLD_R588.");
// Verify MS-OXWSFOLD_R588.
Site.CaptureRequirementIfAreEqual<string>(
"IPF.StickyNote",
folderInfo.FolderClass,
588,
@"[In t:BaseFolderType Complex Type]This value[FolderClass] MUST be ""IPF.StickyNote"" for note folders.");
}
/// <summary>
/// This test case verifies requirements related to getting tasks folder.
/// </summary>
[TestCategory("MSOXWSFOLD"), TestMethod()]
public void MSOXWSFOLD_S04_TC06_GetTasksFolder()
{
#region Get the tasks folder.
DistinguishedFolderIdType folder = new DistinguishedFolderIdType();
folder.Id = DistinguishedFolderIdNameType.tasks;
// GetFolder request.
GetFolderType getTasksFolderRequest = this.GetGetFolderRequest(DefaultShapeNamesType.AllProperties, folder);
// Get the tasks folder.
GetFolderResponseType getTasksFolderResponse = this.FOLDAdapter.GetFolder(getTasksFolderRequest);
// Check the response.
Common.CheckOperationSuccess(getTasksFolderResponse, 1, this.Site);
// Variable to save the folder.
FolderInfoResponseMessageType allFolders = (FolderInfoResponseMessageType)getTasksFolderResponse.ResponseMessages.Items[0];
// Add the debug information
this.Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXWSFOLD_R35");
// Verify MS-OXWSFOLD requirement: MS-OXWSFOLD_R35
this.Site.CaptureRequirementIfIsInstanceOfType(
allFolders.Folders[0],
typeof(TasksFolderType),
35,
@"[In t:ArrayOfFoldersType Complex Type]The type of element TasksFolder is t:TasksFolderType ([MS-OXWSTASK] section 2.2.4.5).");
// Add the debug information
this.Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXWSFOLD_R3501");
// Verify MS-OXWSFOLD requirement: MS-OXWSFOLD_R3501
this.Site.CaptureRequirementIfIsInstanceOfType(
allFolders.Folders[0],
typeof(TasksFolderType),
3501,
@"[In t:ArrayOfFoldersType Complex Type]TasksFolder represents a Tasks folder that is contained in a mailbox.");
TasksFolderType folderInfo = (TasksFolderType)allFolders.Folders[0];
#endregion
// Add the debug information.
Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXWSFOLD_R589.");
// Verify MS-OXWSFOLD_R589.
Site.CaptureRequirementIfAreEqual<string>(
"IPF.Task",
folderInfo.FolderClass,
589,
@"[In t:BaseFolderType Complex Type]This value[FolderClass] MUST be ""IPF.Task"" for Tasks folders.");
}
/// <summary>
/// This test case verifies the requirements related to UnreadCount property of folder via checking the property of Inbox before and after sending a mail.
/// </summary>
[TestCategory("MSOXWSFOLD"), TestMethod()]
public void MSOXWSFOLD_S04_TC07_UnReadCount()
{
#region Get the Inbox folder
DistinguishedFolderIdType folder = new DistinguishedFolderIdType();
folder.Id = DistinguishedFolderIdNameType.inbox;
// GetFolder request.
GetFolderType getInboxRequest = this.GetGetFolderRequest(DefaultShapeNamesType.AllProperties, folder);
// Get the Inbox folder.
GetFolderResponseType getInboxResponse = this.FOLDAdapter.GetFolder(getInboxRequest);
// Check the response.
Common.CheckOperationSuccess(getInboxResponse, 1, this.Site);
// Variable to save the folder.
FolderInfoResponseMessageType allFolders = (FolderInfoResponseMessageType)getInboxResponse.ResponseMessages.Items[0];
BaseFolderType folderInfo = (BaseFolderType)allFolders.Folders[0];
// Variable to save the count of unread messages before sent mail to the specific account.
// Save the unread message count.
int count = ((FolderType)folderInfo).UnreadCount;
#endregion
#region Create an unread message.
string itemName = Common.GenerateResourceName(this.Site, "Test Mail");
// Send a mail to User1
ItemIdType itemId = this.CreateItem(Common.GetConfigurationPropertyValue("User1Name", this.Site) + "@" + Common.GetConfigurationPropertyValue("Domain", this.Site), DistinguishedFolderIdNameType.inbox.ToString(), itemName);
this.NewCreatedItemIds.Add(itemId);
#endregion
#region Get the Inbox folder
// Set the request's folderId field.
folder.Id = DistinguishedFolderIdNameType.inbox;
// GetFolder request.
GetFolderType getInboxAfterMailReceivedRequest = this.GetGetFolderRequest(DefaultShapeNamesType.AllProperties, folder);
// Get the Inbox folder.
GetFolderResponseType getInboxAfterMailReceivedResponse = this.FOLDAdapter.GetFolder(getInboxAfterMailReceivedRequest);
// Check the response.
Common.CheckOperationSuccess(getInboxAfterMailReceivedResponse, 1, this.Site);
// Variable to save the folder.
allFolders = (FolderInfoResponseMessageType)getInboxAfterMailReceivedResponse.ResponseMessages.Items[0];
folderInfo = (BaseFolderType)allFolders.Folders[0];
FolderType folderType = (FolderType)folderInfo;
#endregion
// Add the debug information
this.Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXWSFOLD_R99");
// Verify MS-OXWSFOLD requirement: MS-OXWSFOLD_R99
// Unread count value is returned from server, and schema is verified in adapter so this requirement can be covered.
this.Site.CaptureRequirementIfIsNotNull(
folderType.UnreadCount,
99,
@"[In t:FolderType Complex Type]The type of element UnreadCount is xs:int [XMLSCHEMA2].");
// Add the debug information
this.Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXWSFOLD_R10010");
// Verify MS-OXWSFOLD requirement: MS-OXWSFOLD_R10010
// After sending a new message to mail box, the number of unread messages should be (count + 1).
this.Site.CaptureRequirementIfAreEqual<int>(
1 + count,
folderType.UnreadCount,
10010,
@"[In t:FolderType Complex Type]This element[UnreadCount] MUST exist in responses.");
// Add the debug information
this.Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXWSFOLD_R9901");
// Verify MS-OXWSFOLD requirement: MS-OXWSFOLD_R9901
this.Site.CaptureRequirementIfAreEqual<int>(
1 + count,
folderType.UnreadCount,
9901,
@"[In t:FolderType Complex Type]UnreadCount specifies the number of unread items in a folder.");
// Add the debug information
this.Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXWSFOLD_R10011");
// Since R9901 and R100 are captured successfully, this requirement will be captured.
this.Site.CaptureRequirement(
10011,
@"[In t:FolderType Complex Type]This element[UnreadCount] MUST equal the sum of all MessageType complex types ([MS-OXWSMSG] section 2.2.4.3) and PostItemType complex types ([MS-OXWSPOST] section 2.2.4.1) that have the IsRead property set to ""false"".");
}
/// <summary>
/// This test case verifies the requirements related to extended property of folder.
/// </summary>
[TestCategory("MSOXWSFOLD"), TestMethod()]
public void MSOXWSFOLD_S04_TC08_GetExtendedProperty()
{
#region Create a new folder in the inbox folder
// CreateFolder request.
CreateFolderType createFolderRequest = this.GetCreateFolderRequest(DistinguishedFolderIdNameType.inbox.ToString(), new string[] { "Custom Folder" }, new string[] { "IPF.MyCustomFolderClass" }, null);
// Set folder class to null.
createFolderRequest.Folders[0].FolderClass = null;
// Set folder extended property and its value.
PathToExtendedFieldType publishInAddressBook = new PathToExtendedFieldType();
// Set extended property Id and type.
publishInAddressBook.PropertyTag = "0x671E";
publishInAddressBook.PropertyType = MapiPropertyTypeType.Boolean;
ExtendedPropertyType pubAddressbook = new ExtendedPropertyType();
pubAddressbook.ExtendedFieldURI = publishInAddressBook;
// Set extended property value.
pubAddressbook.Item = "1";
ExtendedPropertyType[] extendedProperties = new ExtendedPropertyType[1];
extendedProperties[0] = pubAddressbook;
createFolderRequest.Folders[0].ExtendedProperty = extendedProperties;
// Create a new folder.
CreateFolderResponseType createFolderResponse = this.FOLDAdapter.CreateFolder(createFolderRequest);
// Check the response.
Common.CheckOperationSuccess(createFolderResponse, 1, this.Site);
// Save the new created folder's folder id.
FolderIdType newFolderId = ((FolderInfoResponseMessageType)createFolderResponse.ResponseMessages.Items[0]).Folders[0].FolderId;
this.NewCreatedFolderIds.Add(newFolderId);
#endregion
// Add the debug information
this.Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXWSFOLD_R7801");
// Verify MS-OXWSFOLD requirement: MS-OXWSFOLD_R7801
// Folder created successfully with extended property this requirement can be captured.
this.Site.CaptureRequirementIfAreEqual<ResponseCodeType>(
ResponseCodeType.NoError,
createFolderResponse.ResponseMessages.Items[0].ResponseCode,
7801,
@"[In t:BaseFolderType Complex Type]This element [ExtendedProperty] is present, server responses NO_ERROR.");
// Add the debug information
this.Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXWSFOLD_R980302");
// Verify MS-OXWSFOLD requirement: MS-OXWSFOLD_R980302
// Folder created successfully without permission set so this requirement can be covered.
this.Site.CaptureRequirementIfAreEqual<ResponseCodeType>(
ResponseCodeType.NoError,
createFolderResponse.ResponseMessages.Items[0].ResponseCode,
980302,
@"[In t:FolderType Complex Type]This element [PermissionSet] is not present, server responses NO_ERROR.");
// Add the debug information
this.Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXWSFOLD_R589202");
// Verify MS-OXWSFOLD requirement: MS-OXWSFOLD_R589202
this.Site.CaptureRequirementIfAreEqual<ResponseCodeType>(
ResponseCodeType.NoError,
createFolderResponse.ResponseMessages.Items[0].ResponseCode,
589202,
@"[In t:BaseFolderType Complex Type]This element [FolderClass] is not present, server responses NO_ERROR.");
#region Get the new created folder
// GetFolder request.
GetFolderType getNewFolderRequest = this.GetGetFolderRequest(DefaultShapeNamesType.AllProperties, newFolderId);
getNewFolderRequest.FolderShape.AdditionalProperties = new BasePathToElementType[1];
getNewFolderRequest.FolderShape.AdditionalProperties[0] = publishInAddressBook;
// Get the new created folder.
GetFolderResponseType getFolderResponse = this.FOLDAdapter.GetFolder(getNewFolderRequest);
// Check the response.
Common.CheckOperationSuccess(getFolderResponse, 1, this.Site);
FolderInfoResponseMessageType allFolders = (FolderInfoResponseMessageType)getFolderResponse.ResponseMessages.Items[0];
FolderType folderInfo = (FolderType)allFolders.Folders[0];
#endregion
// Add the debug information
this.Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXWSFOLD_R423");
// Folder ids is set in request and response is returned from server so this requirement can be captured.
this.Site.CaptureRequirement(
423,
@"[In m:GetFolderType Complex Type]FolderIds is an array of one or more folder identifiers.");
// Add the debug information
this.Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXWSFOLD_R426");
// Folder id that contains id and change key value is set in request and response is returned from server so this requirement can be captured.
this.Site.CaptureRequirement(
426,
@"[In t:NonEmptyArrayOfBaseFolderIdsType Complex Type]FolderId specifies the folder identifier and change key. ");
// Add the debug information
this.Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXWSFOLD_R77");
// Verify MS-OXWSFOLD requirement: MS-OXWSFOLD_R77
// Extended property value is returned from server, and schema is verified in adapter so this requirement can be covered.
this.Site.CaptureRequirementIfIsNotNull(
folderInfo.ExtendedProperty,
77,
@"[In t:BaseFolderType Complex Type]The type of element ExtendedProperty is t:ExtendedPropertyType ([MS-OXWSXPROP] section 2.1.5).");
// Add the debug information
this.Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXWSFOLD_R7701");
// Verify MS-OXWSFOLD requirement: MS-OXWSFOLD_R7701
// In create operation this property value is set to 1 and type to Boolean this means the value is "true" in string type.
this.Site.CaptureRequirementIfAreEqual<string>(
"true",
((ExtendedPropertyType)folderInfo.ExtendedProperty.GetValue(0)).Item.ToString(),
7701,
@"[In t:BaseFolderType Complex Type]ExtendedProperty specifies the set of extended properties on a folder.");
}
/// <summary>
/// This test case verifies requirements related to getting folder with the base folder shape set to IdOnly.
/// </summary>
[TestCategory("MSOXWSFOLD"), TestMethod()]
public void MSOXWSFOLD_S04_TC09_GetFolderIdOnly()
{
#region Get the contacts folder.
DistinguishedFolderIdType folder = new DistinguishedFolderIdType();
folder.Id = DistinguishedFolderIdNameType.contacts;
// GetFolder request.
GetFolderType getContactsFolderRequest = this.GetGetFolderRequest(DefaultShapeNamesType.IdOnly, folder);
// Get the Contacts folder.
GetFolderResponseType getContactsFolderResponse = this.FOLDAdapter.GetFolder(getContactsFolderRequest);
// Check the response.
Common.CheckOperationSuccess(getContactsFolderResponse, 1, this.Site);
#endregion
// Add the debug information
this.Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXWSFOLD_R42103");
// Verify MS-OXWSFOLD requirement: MS-OXWSFOLD_R42103
bool isVerifiedR42103 = Common.IsIdOnly((XmlElement)this.FOLDAdapter.LastRawResponseXml, "t:ContactsFolder", "t:FolderId");
this.Site.CaptureRequirementIfIsTrue(
isVerifiedR42103,
42103,
@"[In t:DefaultShapeNamesType Simple Type] A value of ""IdOnly"" [in DefaultShapeNamesType] specifies only the item or folder ID. include in the response.");
}
#endregion
}
}
| |
namespace CustomControlUsingPalettes
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1));
this.kryptonManager = new ComponentFactory.Krypton.Toolkit.KryptonManager(this.components);
this.buttonSparkle = new ComponentFactory.Krypton.Toolkit.KryptonCheckButton();
this.buttonSystem = new ComponentFactory.Krypton.Toolkit.KryptonCheckButton();
this.kryptonCheckSet = new ComponentFactory.Krypton.Toolkit.KryptonCheckSet(this.components);
this.buttonCustom = new ComponentFactory.Krypton.Toolkit.KryptonCheckButton();
this.buttonOffice2010Blue = new ComponentFactory.Krypton.Toolkit.KryptonCheckButton();
this.buttonOffice2007Blue = new ComponentFactory.Krypton.Toolkit.KryptonCheckButton();
this.groupBoxPalettes = new System.Windows.Forms.GroupBox();
this.groupBoxCustomControl = new System.Windows.Forms.GroupBox();
this.checkBoxEnabled = new System.Windows.Forms.CheckBox();
this.myUserControl1 = new CustomControlUsingPalettes.MyUserControl();
this.groupBoxDescription = new System.Windows.Forms.GroupBox();
this.textBox1 = new System.Windows.Forms.TextBox();
this.buttonClose = new System.Windows.Forms.Button();
this.kryptonPaletteCustom = new ComponentFactory.Krypton.Toolkit.KryptonPalette(this.components);
((System.ComponentModel.ISupportInitialize)(this.kryptonCheckSet)).BeginInit();
this.groupBoxPalettes.SuspendLayout();
this.groupBoxCustomControl.SuspendLayout();
this.groupBoxDescription.SuspendLayout();
this.SuspendLayout();
//
// kryptonManager
//
this.kryptonManager.GlobalPaletteMode = ComponentFactory.Krypton.Toolkit.PaletteModeManager.Office2007Blue;
//
// buttonSparkle
//
this.buttonSparkle.AutoSize = true;
this.buttonSparkle.Location = new System.Drawing.Point(20, 98);
this.buttonSparkle.Name = "buttonSparkle";
this.buttonSparkle.Size = new System.Drawing.Size(127, 27);
this.buttonSparkle.TabIndex = 2;
this.buttonSparkle.Values.Text = "Sparkle - Blue";
//
// buttonSystem
//
this.buttonSystem.AutoSize = true;
this.buttonSystem.Location = new System.Drawing.Point(20, 131);
this.buttonSystem.Name = "buttonSystem";
this.buttonSystem.Size = new System.Drawing.Size(127, 27);
this.buttonSystem.TabIndex = 3;
this.buttonSystem.Values.Text = "System";
//
// kryptonCheckSet
//
this.kryptonCheckSet.CheckButtons.Add(this.buttonSparkle);
this.kryptonCheckSet.CheckButtons.Add(this.buttonSystem);
this.kryptonCheckSet.CheckButtons.Add(this.buttonCustom);
this.kryptonCheckSet.CheckButtons.Add(this.buttonOffice2010Blue);
this.kryptonCheckSet.CheckButtons.Add(this.buttonOffice2007Blue);
this.kryptonCheckSet.CheckedButton = this.buttonOffice2010Blue;
this.kryptonCheckSet.CheckedButtonChanged += new System.EventHandler(this.kryptonCheckSet_CheckedButtonChanged);
//
// buttonCustom
//
this.buttonCustom.AutoSize = true;
this.buttonCustom.Location = new System.Drawing.Point(20, 164);
this.buttonCustom.Name = "buttonCustom";
this.buttonCustom.Size = new System.Drawing.Size(127, 27);
this.buttonCustom.TabIndex = 4;
this.buttonCustom.Values.Text = "Custom";
//
// buttonOffice2010Blue
//
this.buttonOffice2010Blue.AutoSize = true;
this.buttonOffice2010Blue.Checked = true;
this.buttonOffice2010Blue.Location = new System.Drawing.Point(20, 32);
this.buttonOffice2010Blue.Name = "buttonOffice2010Blue";
this.buttonOffice2010Blue.Size = new System.Drawing.Size(127, 27);
this.buttonOffice2010Blue.TabIndex = 0;
this.buttonOffice2010Blue.Values.Text = "Office 2010 - Blue";
//
// buttonOffice2007Blue
//
this.buttonOffice2007Blue.AutoSize = true;
this.buttonOffice2007Blue.Location = new System.Drawing.Point(20, 65);
this.buttonOffice2007Blue.Name = "buttonOffice2007Blue";
this.buttonOffice2007Blue.Size = new System.Drawing.Size(127, 27);
this.buttonOffice2007Blue.TabIndex = 1;
this.buttonOffice2007Blue.Values.Text = "Office 2007 - Blue";
//
// groupBoxPalettes
//
this.groupBoxPalettes.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)));
this.groupBoxPalettes.Controls.Add(this.buttonOffice2010Blue);
this.groupBoxPalettes.Controls.Add(this.buttonSystem);
this.groupBoxPalettes.Controls.Add(this.buttonOffice2007Blue);
this.groupBoxPalettes.Controls.Add(this.buttonCustom);
this.groupBoxPalettes.Controls.Add(this.buttonSparkle);
this.groupBoxPalettes.Location = new System.Drawing.Point(12, 12);
this.groupBoxPalettes.Name = "groupBoxPalettes";
this.groupBoxPalettes.Size = new System.Drawing.Size(170, 222);
this.groupBoxPalettes.TabIndex = 0;
this.groupBoxPalettes.TabStop = false;
this.groupBoxPalettes.Text = "Palettes";
//
// groupBoxCustomControl
//
this.groupBoxCustomControl.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.groupBoxCustomControl.Controls.Add(this.checkBoxEnabled);
this.groupBoxCustomControl.Controls.Add(this.myUserControl1);
this.groupBoxCustomControl.Location = new System.Drawing.Point(188, 13);
this.groupBoxCustomControl.Name = "groupBoxCustomControl";
this.groupBoxCustomControl.Size = new System.Drawing.Size(262, 221);
this.groupBoxCustomControl.TabIndex = 1;
this.groupBoxCustomControl.TabStop = false;
this.groupBoxCustomControl.Text = "MyCustomControl Instance";
//
// checkBoxEnabled
//
this.checkBoxEnabled.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.checkBoxEnabled.AutoSize = true;
this.checkBoxEnabled.Checked = true;
this.checkBoxEnabled.CheckState = System.Windows.Forms.CheckState.Checked;
this.checkBoxEnabled.Location = new System.Drawing.Point(15, 190);
this.checkBoxEnabled.Name = "checkBoxEnabled";
this.checkBoxEnabled.Size = new System.Drawing.Size(64, 17);
this.checkBoxEnabled.TabIndex = 1;
this.checkBoxEnabled.Text = "Enabled";
this.checkBoxEnabled.UseVisualStyleBackColor = true;
this.checkBoxEnabled.CheckedChanged += new System.EventHandler(this.checkBoxEnabled_CheckedChanged);
//
// myUserControl1
//
this.myUserControl1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.myUserControl1.Location = new System.Drawing.Point(15, 31);
this.myUserControl1.Name = "myUserControl1";
this.myUserControl1.Size = new System.Drawing.Size(228, 148);
this.myUserControl1.TabIndex = 0;
//
// groupBoxDescription
//
this.groupBoxDescription.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.groupBoxDescription.Controls.Add(this.textBox1);
this.groupBoxDescription.Location = new System.Drawing.Point(12, 241);
this.groupBoxDescription.Name = "groupBoxDescription";
this.groupBoxDescription.Padding = new System.Windows.Forms.Padding(5);
this.groupBoxDescription.Size = new System.Drawing.Size(438, 156);
this.groupBoxDescription.TabIndex = 2;
this.groupBoxDescription.TabStop = false;
this.groupBoxDescription.Text = "Description";
//
// textBox1
//
this.textBox1.BackColor = System.Drawing.SystemColors.Control;
this.textBox1.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.textBox1.Dock = System.Windows.Forms.DockStyle.Fill;
this.textBox1.Location = new System.Drawing.Point(5, 19);
this.textBox1.Multiline = true;
this.textBox1.Name = "textBox1";
this.textBox1.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
this.textBox1.Size = new System.Drawing.Size(428, 132);
this.textBox1.TabIndex = 0;
this.textBox1.Text = resources.GetString("textBox1.Text");
//
// buttonClose
//
this.buttonClose.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonClose.Location = new System.Drawing.Point(375, 403);
this.buttonClose.Name = "buttonClose";
this.buttonClose.Size = new System.Drawing.Size(75, 23);
this.buttonClose.TabIndex = 3;
this.buttonClose.Text = "Close";
this.buttonClose.UseVisualStyleBackColor = true;
this.buttonClose.Click += new System.EventHandler(this.buttonClose_Click);
//
// kryptonPaletteCustom
//
this.kryptonPaletteCustom.BasePaletteMode = ComponentFactory.Krypton.Toolkit.PaletteMode.Office2007Blue;
this.kryptonPaletteCustom.ButtonStyles.ButtonStandalone.StateCheckedNormal.Back.Color1 = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(128)))), ((int)(((byte)(255)))));
this.kryptonPaletteCustom.ButtonStyles.ButtonStandalone.StateCheckedNormal.Back.Color2 = System.Drawing.Color.Fuchsia;
this.kryptonPaletteCustom.ButtonStyles.ButtonStandalone.StateCheckedNormal.Border.Color1 = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(192)))), ((int)(((byte)(255)))));
this.kryptonPaletteCustom.ButtonStyles.ButtonStandalone.StateCheckedNormal.Border.DrawBorders = ((ComponentFactory.Krypton.Toolkit.PaletteDrawBorders)((((ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Top | ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Bottom)
| ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Left)
| ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Right)));
this.kryptonPaletteCustom.ButtonStyles.ButtonStandalone.StateCheckedNormal.Content.ShortText.Color1 = System.Drawing.Color.White;
this.kryptonPaletteCustom.ButtonStyles.ButtonStandalone.StateCheckedNormal.Content.ShortText.Font = new System.Drawing.Font("Berlin Sans FB", 9F, System.Drawing.FontStyle.Italic, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.kryptonPaletteCustom.ButtonStyles.ButtonStandalone.StateCheckedPressed.Back.Color1 = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(128)))), ((int)(((byte)(255)))));
this.kryptonPaletteCustom.ButtonStyles.ButtonStandalone.StateCheckedPressed.Back.Color2 = System.Drawing.Color.Fuchsia;
this.kryptonPaletteCustom.ButtonStyles.ButtonStandalone.StateCheckedPressed.Border.Color1 = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(192)))), ((int)(((byte)(255)))));
this.kryptonPaletteCustom.ButtonStyles.ButtonStandalone.StateCheckedPressed.Border.DrawBorders = ((ComponentFactory.Krypton.Toolkit.PaletteDrawBorders)((((ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Top | ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Bottom)
| ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Left)
| ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Right)));
this.kryptonPaletteCustom.ButtonStyles.ButtonStandalone.StateCheckedPressed.Content.ShortText.Color1 = System.Drawing.Color.White;
this.kryptonPaletteCustom.ButtonStyles.ButtonStandalone.StateCheckedPressed.Content.ShortText.Font = new System.Drawing.Font("Berlin Sans FB", 9F, System.Drawing.FontStyle.Italic, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.kryptonPaletteCustom.ButtonStyles.ButtonStandalone.StateCheckedTracking.Back.Color1 = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(128)))), ((int)(((byte)(255)))));
this.kryptonPaletteCustom.ButtonStyles.ButtonStandalone.StateCheckedTracking.Back.Color2 = System.Drawing.Color.Fuchsia;
this.kryptonPaletteCustom.ButtonStyles.ButtonStandalone.StateCheckedTracking.Border.Color1 = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(192)))), ((int)(((byte)(255)))));
this.kryptonPaletteCustom.ButtonStyles.ButtonStandalone.StateCheckedTracking.Border.DrawBorders = ((ComponentFactory.Krypton.Toolkit.PaletteDrawBorders)((((ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Top | ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Bottom)
| ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Left)
| ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Right)));
this.kryptonPaletteCustom.ButtonStyles.ButtonStandalone.StateCheckedTracking.Content.ShortText.Color1 = System.Drawing.Color.White;
this.kryptonPaletteCustom.ButtonStyles.ButtonStandalone.StateCheckedTracking.Content.ShortText.Font = new System.Drawing.Font("Berlin Sans FB", 9F, System.Drawing.FontStyle.Italic, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.kryptonPaletteCustom.ButtonStyles.ButtonStandalone.StateCommon.Back.ColorAngle = 60F;
this.kryptonPaletteCustom.ButtonStyles.ButtonStandalone.StateDisabled.Back.Color1 = System.Drawing.Color.Gray;
this.kryptonPaletteCustom.ButtonStyles.ButtonStandalone.StateDisabled.Back.Color2 = System.Drawing.Color.Black;
this.kryptonPaletteCustom.ButtonStyles.ButtonStandalone.StateDisabled.Border.Color1 = System.Drawing.Color.Black;
this.kryptonPaletteCustom.ButtonStyles.ButtonStandalone.StateDisabled.Border.DrawBorders = ((ComponentFactory.Krypton.Toolkit.PaletteDrawBorders)((((ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Top | ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Bottom)
| ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Left)
| ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Right)));
this.kryptonPaletteCustom.ButtonStyles.ButtonStandalone.StateDisabled.Content.ShortText.Color1 = System.Drawing.Color.Gainsboro;
this.kryptonPaletteCustom.ButtonStyles.ButtonStandalone.StateNormal.Back.Color1 = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(128)))));
this.kryptonPaletteCustom.ButtonStyles.ButtonStandalone.StateNormal.Back.Color2 = System.Drawing.Color.Yellow;
this.kryptonPaletteCustom.ButtonStyles.ButtonStandalone.StateNormal.Border.Color1 = System.Drawing.Color.Olive;
this.kryptonPaletteCustom.ButtonStyles.ButtonStandalone.StateNormal.Border.DrawBorders = ((ComponentFactory.Krypton.Toolkit.PaletteDrawBorders)((((ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Top | ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Bottom)
| ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Left)
| ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Right)));
this.kryptonPaletteCustom.ButtonStyles.ButtonStandalone.StateNormal.Content.ShortText.Font = new System.Drawing.Font("Berlin Sans FB", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.kryptonPaletteCustom.ButtonStyles.ButtonStandalone.StatePressed.Back.Color1 = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(128)))), ((int)(((byte)(128)))));
this.kryptonPaletteCustom.ButtonStyles.ButtonStandalone.StatePressed.Back.Color2 = System.Drawing.Color.Red;
this.kryptonPaletteCustom.ButtonStyles.ButtonStandalone.StatePressed.Border.Color1 = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(0)))), ((int)(((byte)(0)))));
this.kryptonPaletteCustom.ButtonStyles.ButtonStandalone.StatePressed.Border.DrawBorders = ((ComponentFactory.Krypton.Toolkit.PaletteDrawBorders)((((ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Top | ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Bottom)
| ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Left)
| ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Right)));
this.kryptonPaletteCustom.ButtonStyles.ButtonStandalone.StatePressed.Content.ShortText.Color1 = System.Drawing.Color.White;
this.kryptonPaletteCustom.ButtonStyles.ButtonStandalone.StatePressed.Content.ShortText.Font = new System.Drawing.Font("Berlin Sans FB", 9F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.kryptonPaletteCustom.ButtonStyles.ButtonStandalone.StateTracking.Back.Color1 = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(192)))), ((int)(((byte)(128)))));
this.kryptonPaletteCustom.ButtonStyles.ButtonStandalone.StateTracking.Back.Color2 = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(128)))), ((int)(((byte)(0)))));
this.kryptonPaletteCustom.ButtonStyles.ButtonStandalone.StateTracking.Border.Color1 = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(64)))), ((int)(((byte)(0)))));
this.kryptonPaletteCustom.ButtonStyles.ButtonStandalone.StateTracking.Border.DrawBorders = ((ComponentFactory.Krypton.Toolkit.PaletteDrawBorders)((((ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Top | ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Bottom)
| ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Left)
| ComponentFactory.Krypton.Toolkit.PaletteDrawBorders.Right)));
this.kryptonPaletteCustom.ButtonStyles.ButtonStandalone.StateTracking.Content.ShortText.Font = new System.Drawing.Font("Berlin Sans FB", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.kryptonPaletteCustom.PanelStyles.PanelAlternate.StateDisabled.Color1 = System.Drawing.Color.FromArgb(((int)(((byte)(224)))), ((int)(((byte)(224)))), ((int)(((byte)(224)))));
this.kryptonPaletteCustom.PanelStyles.PanelAlternate.StateDisabled.Color2 = System.Drawing.Color.FromArgb(((int)(((byte)(224)))), ((int)(((byte)(224)))), ((int)(((byte)(224)))));
this.kryptonPaletteCustom.PanelStyles.PanelAlternate.StateNormal.Color1 = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(192)))), ((int)(((byte)(0)))));
this.kryptonPaletteCustom.PanelStyles.PanelAlternate.StateNormal.Color2 = System.Drawing.Color.GreenYellow;
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(462, 432);
this.Controls.Add(this.buttonClose);
this.Controls.Add(this.groupBoxDescription);
this.Controls.Add(this.groupBoxCustomControl);
this.Controls.Add(this.groupBoxPalettes);
this.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.MaximizeBox = false;
this.MinimizeBox = false;
this.MinimumSize = new System.Drawing.Size(432, 466);
this.Name = "Form1";
this.Text = "Custom Control using Palettes";
((System.ComponentModel.ISupportInitialize)(this.kryptonCheckSet)).EndInit();
this.groupBoxPalettes.ResumeLayout(false);
this.groupBoxPalettes.PerformLayout();
this.groupBoxCustomControl.ResumeLayout(false);
this.groupBoxCustomControl.PerformLayout();
this.groupBoxDescription.ResumeLayout(false);
this.groupBoxDescription.PerformLayout();
this.ResumeLayout(false);
}
#endregion
private MyUserControl myUserControl1;
private ComponentFactory.Krypton.Toolkit.KryptonManager kryptonManager;
private ComponentFactory.Krypton.Toolkit.KryptonCheckButton buttonSparkle;
private ComponentFactory.Krypton.Toolkit.KryptonCheckButton buttonSystem;
private ComponentFactory.Krypton.Toolkit.KryptonCheckSet kryptonCheckSet;
private System.Windows.Forms.GroupBox groupBoxPalettes;
private System.Windows.Forms.GroupBox groupBoxCustomControl;
private System.Windows.Forms.GroupBox groupBoxDescription;
private System.Windows.Forms.Button buttonClose;
private System.Windows.Forms.CheckBox checkBoxEnabled;
private ComponentFactory.Krypton.Toolkit.KryptonPalette kryptonPaletteCustom;
private ComponentFactory.Krypton.Toolkit.KryptonCheckButton buttonCustom;
private System.Windows.Forms.TextBox textBox1;
private ComponentFactory.Krypton.Toolkit.KryptonCheckButton buttonOffice2010Blue;
private ComponentFactory.Krypton.Toolkit.KryptonCheckButton buttonOffice2007Blue;
}
}
| |
// 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.Net.Test.Common;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
using Xunit.Abstractions;
namespace System.Net.WebSockets.Client.Tests
{
public class CloseTest : ClientWebSocketTestBase
{
public CloseTest(ITestOutputHelper output) : base(output) { }
[ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoServers))]
public async Task CloseAsync_ServerInitiatedClose_Success(Uri server)
{
const string closeWebSocketMetaCommand = ".close";
using (ClientWebSocket cws = await WebSocketHelper.GetConnectedWebSocket(server, TimeOutMilliseconds, _output))
{
var cts = new CancellationTokenSource(TimeOutMilliseconds);
_output.WriteLine("SendAsync starting.");
await cws.SendAsync(
WebSocketData.GetBufferFromText(closeWebSocketMetaCommand),
WebSocketMessageType.Text,
true,
cts.Token);
_output.WriteLine("SendAsync done.");
var recvBuffer = new byte[256];
_output.WriteLine("ReceiveAsync starting.");
WebSocketReceiveResult recvResult = await cws.ReceiveAsync(new ArraySegment<byte>(recvBuffer), cts.Token);
_output.WriteLine("ReceiveAsync done.");
// Verify received server-initiated close message.
Assert.Equal(WebSocketCloseStatus.NormalClosure, recvResult.CloseStatus);
Assert.Equal(closeWebSocketMetaCommand, recvResult.CloseStatusDescription);
// Verify current websocket state as CloseReceived which indicates only partial close.
Assert.Equal(WebSocketState.CloseReceived, cws.State);
Assert.Equal(WebSocketCloseStatus.NormalClosure, cws.CloseStatus);
Assert.Equal(closeWebSocketMetaCommand, cws.CloseStatusDescription);
// Send back close message to acknowledge server-initiated close.
_output.WriteLine("CloseAsync starting.");
await cws.CloseAsync(WebSocketCloseStatus.InvalidMessageType, string.Empty, cts.Token);
_output.WriteLine("CloseAsync done.");
Assert.Equal(WebSocketState.Closed, cws.State);
// Verify that there is no follow-up echo close message back from the server by
// making sure the close code and message are the same as from the first server close message.
Assert.Equal(WebSocketCloseStatus.NormalClosure, cws.CloseStatus);
Assert.Equal(closeWebSocketMetaCommand, cws.CloseStatusDescription);
}
}
[ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoServers))]
public async Task CloseAsync_ClientInitiatedClose_Success(Uri server)
{
using (ClientWebSocket cws = await WebSocketHelper.GetConnectedWebSocket(server, TimeOutMilliseconds, _output))
{
var cts = new CancellationTokenSource(TimeOutMilliseconds);
Assert.Equal(WebSocketState.Open, cws.State);
var closeStatus = WebSocketCloseStatus.InvalidMessageType;
string closeDescription = "CloseAsync_InvalidMessageType";
await cws.CloseAsync(closeStatus, closeDescription, cts.Token);
Assert.Equal(WebSocketState.Closed, cws.State);
Assert.Equal(closeStatus, cws.CloseStatus);
Assert.Equal(closeDescription, cws.CloseStatusDescription);
}
}
[ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoServers))]
public async Task CloseAsync_CloseDescriptionIsMaxLength_Success(Uri server)
{
string closeDescription = new string('C', CloseDescriptionMaxLength);
using (ClientWebSocket cws = await WebSocketHelper.GetConnectedWebSocket(server, TimeOutMilliseconds, _output))
{
var cts = new CancellationTokenSource(TimeOutMilliseconds);
await cws.CloseAsync(WebSocketCloseStatus.NormalClosure, closeDescription, cts.Token);
}
}
[ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoServers))]
public async Task CloseAsync_CloseDescriptionIsMaxLengthPlusOne_ThrowsArgumentException(Uri server)
{
string closeDescription = new string('C', CloseDescriptionMaxLength + 1);
using (ClientWebSocket cws = await WebSocketHelper.GetConnectedWebSocket(server, TimeOutMilliseconds, _output))
{
var cts = new CancellationTokenSource(TimeOutMilliseconds);
string expectedInnerMessage = ResourceHelper.GetExceptionMessage(
"net_WebSockets_InvalidCloseStatusDescription",
closeDescription,
CloseDescriptionMaxLength);
var expectedException = new ArgumentException(expectedInnerMessage, "statusDescription");
string expectedMessage = expectedException.Message;
Assert.Throws<ArgumentException>(() =>
{ Task t = cws.CloseAsync(WebSocketCloseStatus.NormalClosure, closeDescription, cts.Token); });
Assert.Equal(WebSocketState.Open, cws.State);
}
}
[ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoServers))]
public async Task CloseAsync_CloseDescriptionHasUnicode_Success(Uri server)
{
using (ClientWebSocket cws = await WebSocketHelper.GetConnectedWebSocket(server, TimeOutMilliseconds, _output))
{
var cts = new CancellationTokenSource(TimeOutMilliseconds);
var closeStatus = WebSocketCloseStatus.InvalidMessageType;
string closeDescription = "CloseAsync_Containing\u016Cnicode.";
await cws.CloseAsync(closeStatus, closeDescription, cts.Token);
Assert.Equal(closeStatus, cws.CloseStatus);
Assert.Equal(closeDescription, cws.CloseStatusDescription);
}
}
[ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoServers))]
public async Task CloseAsync_CloseDescriptionIsNull_Success(Uri server)
{
using (ClientWebSocket cws = await WebSocketHelper.GetConnectedWebSocket(server, TimeOutMilliseconds, _output))
{
var cts = new CancellationTokenSource(TimeOutMilliseconds);
var closeStatus = WebSocketCloseStatus.NormalClosure;
string closeDescription = null;
await cws.CloseAsync(closeStatus, closeDescription, cts.Token);
Assert.Equal(closeStatus, cws.CloseStatus);
Assert.Equal(true, String.IsNullOrEmpty(cws.CloseStatusDescription));
}
}
[ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoServers))]
public async Task CloseOutputAsync_ClientInitiated_CanReceive_CanClose(Uri server)
{
string message = "Hello WebSockets!";
using (ClientWebSocket cws = await WebSocketHelper.GetConnectedWebSocket(server, TimeOutMilliseconds, _output))
{
var cts = new CancellationTokenSource(TimeOutMilliseconds);
var closeStatus = WebSocketCloseStatus.InvalidPayloadData;
string closeDescription = "CloseOutputAsync_Client_InvalidPayloadData";
await cws.SendAsync(WebSocketData.GetBufferFromText(message), WebSocketMessageType.Text, true, cts.Token);
// Need a short delay as per WebSocket rfc6455 section 5.5.1 there isn't a requirement to receive any
// data fragments after a close has been sent. The delay allows the received data fragment to be
// available before calling close. The WinRT MessageWebSocket implementation doesn't allow receiving
// after a call to Close.
await Task.Delay(100);
await cws.CloseOutputAsync(closeStatus, closeDescription, cts.Token);
// Should be able to receive the message echoed by the server.
var recvBuffer = new byte[100];
var segmentRecv = new ArraySegment<byte>(recvBuffer);
WebSocketReceiveResult recvResult = await cws.ReceiveAsync(segmentRecv, cts.Token);
Assert.Equal(message.Length, recvResult.Count);
segmentRecv = new ArraySegment<byte>(segmentRecv.Array, 0, recvResult.Count);
Assert.Equal(message, WebSocketData.GetTextFromBuffer(segmentRecv));
Assert.Equal(null, recvResult.CloseStatus);
Assert.Equal(null, recvResult.CloseStatusDescription);
await cws.CloseAsync(closeStatus, closeDescription, cts.Token);
Assert.Equal(closeStatus, cws.CloseStatus);
Assert.Equal(closeDescription, cws.CloseStatusDescription);
}
}
[ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoServers))]
public async Task CloseOutputAsync_ServerInitiated_CanSend(Uri server)
{
string message = "Hello WebSockets!";
var expectedCloseStatus = WebSocketCloseStatus.NormalClosure;
var expectedCloseDescription = ".shutdown";
using (ClientWebSocket cws = await WebSocketHelper.GetConnectedWebSocket(server, TimeOutMilliseconds, _output))
{
var cts = new CancellationTokenSource(TimeOutMilliseconds);
await cws.SendAsync(
WebSocketData.GetBufferFromText(".shutdown"),
WebSocketMessageType.Text,
true,
cts.Token);
// Should be able to receive a shutdown message.
var recvBuffer = new byte[100];
var segmentRecv = new ArraySegment<byte>(recvBuffer);
WebSocketReceiveResult recvResult = await cws.ReceiveAsync(segmentRecv, cts.Token);
Assert.Equal(0, recvResult.Count);
Assert.Equal(expectedCloseStatus, recvResult.CloseStatus);
Assert.Equal(expectedCloseDescription, recvResult.CloseStatusDescription);
// Verify WebSocket state
Assert.Equal(expectedCloseStatus, cws.CloseStatus);
Assert.Equal(expectedCloseDescription, cws.CloseStatusDescription);
Assert.Equal(WebSocketState.CloseReceived, cws.State);
// Should be able to send.
await cws.SendAsync(WebSocketData.GetBufferFromText(message), WebSocketMessageType.Text, true, cts.Token);
// Cannot change the close status/description with the final close.
var closeStatus = WebSocketCloseStatus.InvalidPayloadData;
var closeDescription = "CloseOutputAsync_Client_Description";
await cws.CloseAsync(closeStatus, closeDescription, cts.Token);
Assert.Equal(expectedCloseStatus, cws.CloseStatus);
Assert.Equal(expectedCloseDescription, cws.CloseStatusDescription);
Assert.Equal(WebSocketState.Closed, cws.State);
}
}
[ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoServers))]
public async Task CloseOutputAsync_CloseDescriptionIsNull_Success(Uri server)
{
using (ClientWebSocket cws = await WebSocketHelper.GetConnectedWebSocket(server, TimeOutMilliseconds, _output))
{
var cts = new CancellationTokenSource(TimeOutMilliseconds);
var closeStatus = WebSocketCloseStatus.NormalClosure;
string closeDescription = null;
await cws.CloseOutputAsync(closeStatus, closeDescription, cts.Token);
}
}
}
}
| |
// HtmlAgilityPack V1.0 - Simon Mourier <simon underscore mourier at hotmail dot com>
using System;
using System.Collections;
using System.Text;
namespace HtmlAgilityPack
{
/// <summary>
/// A utility class to replace special characters by entities and vice-versa.
/// Follows HTML 4.0 specification found at http://www.w3.org/TR/html4/sgml/entities.html
/// </summary>
public class HtmlEntity
{
private static Hashtable _entityName;
private static Hashtable _entityValue;
private static readonly int _maxEntitySize;
private HtmlEntity()
{
}
static HtmlEntity()
{
_entityName = new Hashtable();
_entityValue = new Hashtable();
#region Entities Definition
_entityValue.Add("nbsp", 160); // no-break space = non-breaking space, U+00A0 ISOnum
_entityName.Add(160, "nbsp");
_entityValue.Add("iexcl", 161); // inverted exclamation mark, U+00A1 ISOnum
_entityName.Add(161, "iexcl");
_entityValue.Add("cent", 162); // cent sign, U+00A2 ISOnum
_entityName.Add(162, "cent");
_entityValue.Add("pound", 163); // pound sign, U+00A3 ISOnum
_entityName.Add(163, "pound");
_entityValue.Add("curren", 164); // currency sign, U+00A4 ISOnum
_entityName.Add(164, "curren");
_entityValue.Add("yen", 165); // yen sign = yuan sign, U+00A5 ISOnum
_entityName.Add(165, "yen");
_entityValue.Add("brvbar", 166); // broken bar = broken vertical bar, U+00A6 ISOnum
_entityName.Add(166, "brvbar");
_entityValue.Add("sect", 167); // section sign, U+00A7 ISOnum
_entityName.Add(167, "sect");
_entityValue.Add("uml", 168); // diaeresis = spacing diaeresis, U+00A8 ISOdia
_entityName.Add(168, "uml");
_entityValue.Add("copy", 169); // copyright sign, U+00A9 ISOnum
_entityName.Add(169, "copy");
_entityValue.Add("ordf", 170); // feminine ordinal indicator, U+00AA ISOnum
_entityName.Add(170, "ordf");
_entityValue.Add("laquo", 171); // left-pointing double angle quotation mark = left pointing guillemet, U+00AB ISOnum
_entityName.Add(171, "laquo");
_entityValue.Add("not", 172); // not sign, U+00AC ISOnum
_entityName.Add(172, "not");
_entityValue.Add("shy", 173); // soft hyphen = discretionary hyphen, U+00AD ISOnum
_entityName.Add(173, "shy");
_entityValue.Add("reg", 174); // registered sign = registered trade mark sign, U+00AE ISOnum
_entityName.Add(174, "reg");
_entityValue.Add("macr", 175); // macron = spacing macron = overline = APL overbar, U+00AF ISOdia
_entityName.Add(175, "macr");
_entityValue.Add("deg", 176); // degree sign, U+00B0 ISOnum
_entityName.Add(176, "deg");
_entityValue.Add("plusmn", 177); // plus-minus sign = plus-or-minus sign, U+00B1 ISOnum
_entityName.Add(177, "plusmn");
_entityValue.Add("sup2", 178); // superscript two = superscript digit two = squared, U+00B2 ISOnum
_entityName.Add(178, "sup2");
_entityValue.Add("sup3", 179); // superscript three = superscript digit three = cubed, U+00B3 ISOnum
_entityName.Add(179, "sup3");
_entityValue.Add("acute", 180); // acute accent = spacing acute, U+00B4 ISOdia
_entityName.Add(180, "acute");
_entityValue.Add("micro", 181); // micro sign, U+00B5 ISOnum
_entityName.Add(181, "micro");
_entityValue.Add("para", 182); // pilcrow sign = paragraph sign, U+00B6 ISOnum
_entityName.Add(182, "para");
_entityValue.Add("middot", 183); // middle dot = Georgian comma = Greek middle dot, U+00B7 ISOnum
_entityName.Add(183, "middot");
_entityValue.Add("cedil", 184); // cedilla = spacing cedilla, U+00B8 ISOdia
_entityName.Add(184, "cedil");
_entityValue.Add("sup1", 185); // superscript one = superscript digit one, U+00B9 ISOnum
_entityName.Add(185, "sup1");
_entityValue.Add("ordm", 186); // masculine ordinal indicator, U+00BA ISOnum
_entityName.Add(186, "ordm");
_entityValue.Add("raquo", 187); // right-pointing double angle quotation mark = right pointing guillemet, U+00BB ISOnum
_entityName.Add(187, "raquo");
_entityValue.Add("frac14", 188); // vulgar fraction one quarter = fraction one quarter, U+00BC ISOnum
_entityName.Add(188, "frac14");
_entityValue.Add("frac12", 189); // vulgar fraction one half = fraction one half, U+00BD ISOnum
_entityName.Add(189, "frac12");
_entityValue.Add("frac34", 190); // vulgar fraction three quarters = fraction three quarters, U+00BE ISOnum
_entityName.Add(190, "frac34");
_entityValue.Add("iquest", 191); // inverted question mark = turned question mark, U+00BF ISOnum
_entityName.Add(191, "iquest");
_entityValue.Add("Agrave", 192); // latin capital letter A with grave = latin capital letter A grave, U+00C0 ISOlat1
_entityName.Add(192, "Agrave");
_entityValue.Add("Aacute", 193); // latin capital letter A with acute, U+00C1 ISOlat1
_entityName.Add(193, "Aacute");
_entityValue.Add("Acirc", 194); // latin capital letter A with circumflex, U+00C2 ISOlat1
_entityName.Add(194, "Acirc");
_entityValue.Add("Atilde", 195); // latin capital letter A with tilde, U+00C3 ISOlat1
_entityName.Add(195, "Atilde");
_entityValue.Add("Auml", 196); // latin capital letter A with diaeresis, U+00C4 ISOlat1
_entityName.Add(196, "Auml");
_entityValue.Add("Aring", 197); // latin capital letter A with ring above = latin capital letter A ring, U+00C5 ISOlat1
_entityName.Add(197, "Aring");
_entityValue.Add("AElig", 198); // latin capital letter AE = latin capital ligature AE, U+00C6 ISOlat1
_entityName.Add(198, "AElig");
_entityValue.Add("Ccedil", 199); // latin capital letter C with cedilla, U+00C7 ISOlat1
_entityName.Add(199, "Ccedil");
_entityValue.Add("Egrave", 200); // latin capital letter E with grave, U+00C8 ISOlat1
_entityName.Add(200, "Egrave");
_entityValue.Add("Eacute", 201); // latin capital letter E with acute, U+00C9 ISOlat1
_entityName.Add(201, "Eacute");
_entityValue.Add("Ecirc", 202); // latin capital letter E with circumflex, U+00CA ISOlat1
_entityName.Add(202, "Ecirc");
_entityValue.Add("Euml", 203); // latin capital letter E with diaeresis, U+00CB ISOlat1
_entityName.Add(203, "Euml");
_entityValue.Add("Igrave", 204); // latin capital letter I with grave, U+00CC ISOlat1
_entityName.Add(204, "Igrave");
_entityValue.Add("Iacute", 205); // latin capital letter I with acute, U+00CD ISOlat1
_entityName.Add(205, "Iacute");
_entityValue.Add("Icirc", 206); // latin capital letter I with circumflex, U+00CE ISOlat1
_entityName.Add(206, "Icirc");
_entityValue.Add("Iuml", 207); // latin capital letter I with diaeresis, U+00CF ISOlat1
_entityName.Add(207, "Iuml");
_entityValue.Add("ETH", 208); // latin capital letter ETH, U+00D0 ISOlat1
_entityName.Add(208, "ETH");
_entityValue.Add("Ntilde", 209); // latin capital letter N with tilde, U+00D1 ISOlat1
_entityName.Add(209, "Ntilde");
_entityValue.Add("Ograve", 210); // latin capital letter O with grave, U+00D2 ISOlat1
_entityName.Add(210, "Ograve");
_entityValue.Add("Oacute", 211); // latin capital letter O with acute, U+00D3 ISOlat1
_entityName.Add(211, "Oacute");
_entityValue.Add("Ocirc", 212); // latin capital letter O with circumflex, U+00D4 ISOlat1
_entityName.Add(212, "Ocirc");
_entityValue.Add("Otilde", 213); // latin capital letter O with tilde, U+00D5 ISOlat1
_entityName.Add(213, "Otilde");
_entityValue.Add("Ouml", 214); // latin capital letter O with diaeresis, U+00D6 ISOlat1
_entityName.Add(214, "Ouml");
_entityValue.Add("times", 215); // multiplication sign, U+00D7 ISOnum
_entityName.Add(215, "times");
_entityValue.Add("Oslash", 216); // latin capital letter O with stroke = latin capital letter O slash, U+00D8 ISOlat1
_entityName.Add(216, "Oslash");
_entityValue.Add("Ugrave", 217); // latin capital letter U with grave, U+00D9 ISOlat1
_entityName.Add(217, "Ugrave");
_entityValue.Add("Uacute", 218); // latin capital letter U with acute, U+00DA ISOlat1
_entityName.Add(218, "Uacute");
_entityValue.Add("Ucirc", 219); // latin capital letter U with circumflex, U+00DB ISOlat1
_entityName.Add(219, "Ucirc");
_entityValue.Add("Uuml", 220); // latin capital letter U with diaeresis, U+00DC ISOlat1
_entityName.Add(220, "Uuml");
_entityValue.Add("Yacute", 221); // latin capital letter Y with acute, U+00DD ISOlat1
_entityName.Add(221, "Yacute");
_entityValue.Add("THORN", 222); // latin capital letter THORN, U+00DE ISOlat1
_entityName.Add(222, "THORN");
_entityValue.Add("szlig", 223); // latin small letter sharp s = ess-zed, U+00DF ISOlat1
_entityName.Add(223, "szlig");
_entityValue.Add("agrave", 224); // latin small letter a with grave = latin small letter a grave, U+00E0 ISOlat1
_entityName.Add(224, "agrave");
_entityValue.Add("aacute", 225); // latin small letter a with acute, U+00E1 ISOlat1
_entityName.Add(225, "aacute");
_entityValue.Add("acirc", 226); // latin small letter a with circumflex, U+00E2 ISOlat1
_entityName.Add(226, "acirc");
_entityValue.Add("atilde", 227); // latin small letter a with tilde, U+00E3 ISOlat1
_entityName.Add(227, "atilde");
_entityValue.Add("auml", 228); // latin small letter a with diaeresis, U+00E4 ISOlat1
_entityName.Add(228, "auml");
_entityValue.Add("aring", 229); // latin small letter a with ring above = latin small letter a ring, U+00E5 ISOlat1
_entityName.Add(229, "aring");
_entityValue.Add("aelig", 230); // latin small letter ae = latin small ligature ae, U+00E6 ISOlat1
_entityName.Add(230, "aelig");
_entityValue.Add("ccedil", 231); // latin small letter c with cedilla, U+00E7 ISOlat1
_entityName.Add(231, "ccedil");
_entityValue.Add("egrave", 232); // latin small letter e with grave, U+00E8 ISOlat1
_entityName.Add(232, "egrave");
_entityValue.Add("eacute", 233); // latin small letter e with acute, U+00E9 ISOlat1
_entityName.Add(233, "eacute");
_entityValue.Add("ecirc", 234); // latin small letter e with circumflex, U+00EA ISOlat1
_entityName.Add(234, "ecirc");
_entityValue.Add("euml", 235); // latin small letter e with diaeresis, U+00EB ISOlat1
_entityName.Add(235, "euml");
_entityValue.Add("igrave", 236); // latin small letter i with grave, U+00EC ISOlat1
_entityName.Add(236, "igrave");
_entityValue.Add("iacute", 237); // latin small letter i with acute, U+00ED ISOlat1
_entityName.Add(237, "iacute");
_entityValue.Add("icirc", 238); // latin small letter i with circumflex, U+00EE ISOlat1
_entityName.Add(238, "icirc");
_entityValue.Add("iuml", 239); // latin small letter i with diaeresis, U+00EF ISOlat1
_entityName.Add(239, "iuml");
_entityValue.Add("eth", 240); // latin small letter eth, U+00F0 ISOlat1
_entityName.Add(240, "eth");
_entityValue.Add("ntilde", 241); // latin small letter n with tilde, U+00F1 ISOlat1
_entityName.Add(241, "ntilde");
_entityValue.Add("ograve", 242); // latin small letter o with grave, U+00F2 ISOlat1
_entityName.Add(242, "ograve");
_entityValue.Add("oacute", 243); // latin small letter o with acute, U+00F3 ISOlat1
_entityName.Add(243, "oacute");
_entityValue.Add("ocirc", 244); // latin small letter o with circumflex, U+00F4 ISOlat1
_entityName.Add(244, "ocirc");
_entityValue.Add("otilde", 245); // latin small letter o with tilde, U+00F5 ISOlat1
_entityName.Add(245, "otilde");
_entityValue.Add("ouml", 246); // latin small letter o with diaeresis, U+00F6 ISOlat1
_entityName.Add(246, "ouml");
_entityValue.Add("divide", 247); // division sign, U+00F7 ISOnum
_entityName.Add(247, "divide");
_entityValue.Add("oslash", 248); // latin small letter o with stroke, = latin small letter o slash, U+00F8 ISOlat1
_entityName.Add(248, "oslash");
_entityValue.Add("ugrave", 249); // latin small letter u with grave, U+00F9 ISOlat1
_entityName.Add(249, "ugrave");
_entityValue.Add("uacute", 250); // latin small letter u with acute, U+00FA ISOlat1
_entityName.Add(250, "uacute");
_entityValue.Add("ucirc", 251); // latin small letter u with circumflex, U+00FB ISOlat1
_entityName.Add(251, "ucirc");
_entityValue.Add("uuml", 252); // latin small letter u with diaeresis, U+00FC ISOlat1
_entityName.Add(252, "uuml");
_entityValue.Add("yacute", 253); // latin small letter y with acute, U+00FD ISOlat1
_entityName.Add(253, "yacute");
_entityValue.Add("thorn", 254); // latin small letter thorn, U+00FE ISOlat1
_entityName.Add(254, "thorn");
_entityValue.Add("yuml", 255); // latin small letter y with diaeresis, U+00FF ISOlat1
_entityName.Add(255, "yuml");
_entityValue.Add("fnof", 402); // latin small f with hook = function = florin, U+0192 ISOtech
_entityName.Add(402, "fnof");
_entityValue.Add("Alpha", 913); // greek capital letter alpha, U+0391
_entityName.Add(913, "Alpha");
_entityValue.Add("Beta", 914); // greek capital letter beta, U+0392
_entityName.Add(914, "Beta");
_entityValue.Add("Gamma", 915); // greek capital letter gamma, U+0393 ISOgrk3
_entityName.Add(915, "Gamma");
_entityValue.Add("Delta", 916); // greek capital letter delta, U+0394 ISOgrk3
_entityName.Add(916, "Delta");
_entityValue.Add("Epsilon", 917); // greek capital letter epsilon, U+0395
_entityName.Add(917, "Epsilon");
_entityValue.Add("Zeta", 918); // greek capital letter zeta, U+0396
_entityName.Add(918, "Zeta");
_entityValue.Add("Eta", 919); // greek capital letter eta, U+0397
_entityName.Add(919, "Eta");
_entityValue.Add("Theta", 920); // greek capital letter theta, U+0398 ISOgrk3
_entityName.Add(920, "Theta");
_entityValue.Add("Iota", 921); // greek capital letter iota, U+0399
_entityName.Add(921, "Iota");
_entityValue.Add("Kappa", 922); // greek capital letter kappa, U+039A
_entityName.Add(922, "Kappa");
_entityValue.Add("Lambda", 923); // greek capital letter lambda, U+039B ISOgrk3
_entityName.Add(923, "Lambda");
_entityValue.Add("Mu", 924); // greek capital letter mu, U+039C
_entityName.Add(924, "Mu");
_entityValue.Add("Nu", 925); // greek capital letter nu, U+039D
_entityName.Add(925, "Nu");
_entityValue.Add("Xi", 926); // greek capital letter xi, U+039E ISOgrk3
_entityName.Add(926, "Xi");
_entityValue.Add("Omicron", 927); // greek capital letter omicron, U+039F
_entityName.Add(927, "Omicron");
_entityValue.Add("Pi", 928); // greek capital letter pi, U+03A0 ISOgrk3
_entityName.Add(928, "Pi");
_entityValue.Add("Rho", 929); // greek capital letter rho, U+03A1
_entityName.Add(929, "Rho");
_entityValue.Add("Sigma", 931); // greek capital letter sigma, U+03A3 ISOgrk3
_entityName.Add(931, "Sigma");
_entityValue.Add("Tau", 932); // greek capital letter tau, U+03A4
_entityName.Add(932, "Tau");
_entityValue.Add("Upsilon", 933); // greek capital letter upsilon, U+03A5 ISOgrk3
_entityName.Add(933, "Upsilon");
_entityValue.Add("Phi", 934); // greek capital letter phi, U+03A6 ISOgrk3
_entityName.Add(934, "Phi");
_entityValue.Add("Chi", 935); // greek capital letter chi, U+03A7
_entityName.Add(935, "Chi");
_entityValue.Add("Psi", 936); // greek capital letter psi, U+03A8 ISOgrk3
_entityName.Add(936, "Psi");
_entityValue.Add("Omega", 937); // greek capital letter omega, U+03A9 ISOgrk3
_entityName.Add(937, "Omega");
_entityValue.Add("alpha", 945); // greek small letter alpha, U+03B1 ISOgrk3
_entityName.Add(945, "alpha");
_entityValue.Add("beta", 946); // greek small letter beta, U+03B2 ISOgrk3
_entityName.Add(946, "beta");
_entityValue.Add("gamma", 947); // greek small letter gamma, U+03B3 ISOgrk3
_entityName.Add(947, "gamma");
_entityValue.Add("delta", 948); // greek small letter delta, U+03B4 ISOgrk3
_entityName.Add(948, "delta");
_entityValue.Add("epsilon", 949); // greek small letter epsilon, U+03B5 ISOgrk3
_entityName.Add(949, "epsilon");
_entityValue.Add("zeta", 950); // greek small letter zeta, U+03B6 ISOgrk3
_entityName.Add(950, "zeta");
_entityValue.Add("eta", 951); // greek small letter eta, U+03B7 ISOgrk3
_entityName.Add(951, "eta");
_entityValue.Add("theta", 952); // greek small letter theta, U+03B8 ISOgrk3
_entityName.Add(952, "theta");
_entityValue.Add("iota", 953); // greek small letter iota, U+03B9 ISOgrk3
_entityName.Add(953, "iota");
_entityValue.Add("kappa", 954); // greek small letter kappa, U+03BA ISOgrk3
_entityName.Add(954, "kappa");
_entityValue.Add("lambda", 955); // greek small letter lambda, U+03BB ISOgrk3
_entityName.Add(955, "lambda");
_entityValue.Add("mu", 956); // greek small letter mu, U+03BC ISOgrk3
_entityName.Add(956, "mu");
_entityValue.Add("nu", 957); // greek small letter nu, U+03BD ISOgrk3
_entityName.Add(957, "nu");
_entityValue.Add("xi", 958); // greek small letter xi, U+03BE ISOgrk3
_entityName.Add(958, "xi");
_entityValue.Add("omicron", 959); // greek small letter omicron, U+03BF NEW
_entityName.Add(959, "omicron");
_entityValue.Add("pi", 960); // greek small letter pi, U+03C0 ISOgrk3
_entityName.Add(960, "pi");
_entityValue.Add("rho", 961); // greek small letter rho, U+03C1 ISOgrk3
_entityName.Add(961, "rho");
_entityValue.Add("sigmaf", 962); // greek small letter final sigma, U+03C2 ISOgrk3
_entityName.Add(962, "sigmaf");
_entityValue.Add("sigma", 963); // greek small letter sigma, U+03C3 ISOgrk3
_entityName.Add(963, "sigma");
_entityValue.Add("tau", 964); // greek small letter tau, U+03C4 ISOgrk3
_entityName.Add(964, "tau");
_entityValue.Add("upsilon", 965); // greek small letter upsilon, U+03C5 ISOgrk3
_entityName.Add(965, "upsilon");
_entityValue.Add("phi", 966); // greek small letter phi, U+03C6 ISOgrk3
_entityName.Add(966, "phi");
_entityValue.Add("chi", 967); // greek small letter chi, U+03C7 ISOgrk3
_entityName.Add(967, "chi");
_entityValue.Add("psi", 968); // greek small letter psi, U+03C8 ISOgrk3
_entityName.Add(968, "psi");
_entityValue.Add("omega", 969); // greek small letter omega, U+03C9 ISOgrk3
_entityName.Add(969, "omega");
_entityValue.Add("thetasym", 977); // greek small letter theta symbol, U+03D1 NEW
_entityName.Add(977, "thetasym");
_entityValue.Add("upsih", 978); // greek upsilon with hook symbol, U+03D2 NEW
_entityName.Add(978, "upsih");
_entityValue.Add("piv", 982); // greek pi symbol, U+03D6 ISOgrk3
_entityName.Add(982, "piv");
_entityValue.Add("bull", 8226); // bullet = black small circle, U+2022 ISOpub
_entityName.Add(8226, "bull");
_entityValue.Add("hellip", 8230); // horizontal ellipsis = three dot leader, U+2026 ISOpub
_entityName.Add(8230, "hellip");
_entityValue.Add("prime", 8242); // prime = minutes = feet, U+2032 ISOtech
_entityName.Add(8242, "prime");
_entityValue.Add("Prime", 8243); // double prime = seconds = inches, U+2033 ISOtech
_entityName.Add(8243, "Prime");
_entityValue.Add("oline", 8254); // overline = spacing overscore, U+203E NEW
_entityName.Add(8254, "oline");
_entityValue.Add("frasl", 8260); // fraction slash, U+2044 NEW
_entityName.Add(8260, "frasl");
_entityValue.Add("weierp", 8472); // script capital P = power set = Weierstrass p, U+2118 ISOamso
_entityName.Add(8472, "weierp");
_entityValue.Add("image", 8465); // blackletter capital I = imaginary part, U+2111 ISOamso
_entityName.Add(8465, "image");
_entityValue.Add("real", 8476); // blackletter capital R = real part symbol, U+211C ISOamso
_entityName.Add(8476, "real");
_entityValue.Add("trade", 8482); // trade mark sign, U+2122 ISOnum
_entityName.Add(8482, "trade");
_entityValue.Add("alefsym", 8501); // alef symbol = first transfinite cardinal, U+2135 NEW
_entityName.Add(8501, "alefsym");
_entityValue.Add("larr", 8592); // leftwards arrow, U+2190 ISOnum
_entityName.Add(8592, "larr");
_entityValue.Add("uarr", 8593); // upwards arrow, U+2191 ISOnum
_entityName.Add(8593, "uarr");
_entityValue.Add("rarr", 8594); // rightwards arrow, U+2192 ISOnum
_entityName.Add(8594, "rarr");
_entityValue.Add("darr", 8595); // downwards arrow, U+2193 ISOnum
_entityName.Add(8595, "darr");
_entityValue.Add("harr", 8596); // left right arrow, U+2194 ISOamsa
_entityName.Add(8596, "harr");
_entityValue.Add("crarr", 8629); // downwards arrow with corner leftwards = carriage return, U+21B5 NEW
_entityName.Add(8629, "crarr");
_entityValue.Add("lArr", 8656); // leftwards double arrow, U+21D0 ISOtech
_entityName.Add(8656, "lArr");
_entityValue.Add("uArr", 8657); // upwards double arrow, U+21D1 ISOamsa
_entityName.Add(8657, "uArr");
_entityValue.Add("rArr", 8658); // rightwards double arrow, U+21D2 ISOtech
_entityName.Add(8658, "rArr");
_entityValue.Add("dArr", 8659); // downwards double arrow, U+21D3 ISOamsa
_entityName.Add(8659, "dArr");
_entityValue.Add("hArr", 8660); // left right double arrow, U+21D4 ISOamsa
_entityName.Add(8660, "hArr");
_entityValue.Add("forall", 8704); // for all, U+2200 ISOtech
_entityName.Add(8704, "forall");
_entityValue.Add("part", 8706); // partial differential, U+2202 ISOtech
_entityName.Add(8706, "part");
_entityValue.Add("exist", 8707); // there exists, U+2203 ISOtech
_entityName.Add(8707, "exist");
_entityValue.Add("empty", 8709); // empty set = null set = diameter, U+2205 ISOamso
_entityName.Add(8709, "empty");
_entityValue.Add("nabla", 8711); // nabla = backward difference, U+2207 ISOtech
_entityName.Add(8711, "nabla");
_entityValue.Add("isin", 8712); // element of, U+2208 ISOtech
_entityName.Add(8712, "isin");
_entityValue.Add("notin", 8713); // not an element of, U+2209 ISOtech
_entityName.Add(8713, "notin");
_entityValue.Add("ni", 8715); // contains as member, U+220B ISOtech
_entityName.Add(8715, "ni");
_entityValue.Add("prod", 8719); // n-ary product = product sign, U+220F ISOamsb
_entityName.Add(8719, "prod");
_entityValue.Add("sum", 8721); // n-ary sumation, U+2211 ISOamsb
_entityName.Add(8721, "sum");
_entityValue.Add("minus", 8722); // minus sign, U+2212 ISOtech
_entityName.Add(8722, "minus");
_entityValue.Add("lowast", 8727); // asterisk operator, U+2217 ISOtech
_entityName.Add(8727, "lowast");
_entityValue.Add("radic", 8730); // square root = radical sign, U+221A ISOtech
_entityName.Add(8730, "radic");
_entityValue.Add("prop", 8733); // proportional to, U+221D ISOtech
_entityName.Add(8733, "prop");
_entityValue.Add("infin", 8734); // infinity, U+221E ISOtech
_entityName.Add(8734, "infin");
_entityValue.Add("ang", 8736); // angle, U+2220 ISOamso
_entityName.Add(8736, "ang");
_entityValue.Add("and", 8743); // logical and = wedge, U+2227 ISOtech
_entityName.Add(8743, "and");
_entityValue.Add("or", 8744); // logical or = vee, U+2228 ISOtech
_entityName.Add(8744, "or");
_entityValue.Add("cap", 8745); // intersection = cap, U+2229 ISOtech
_entityName.Add(8745, "cap");
_entityValue.Add("cup", 8746); // union = cup, U+222A ISOtech
_entityName.Add(8746, "cup");
_entityValue.Add("int", 8747); // integral, U+222B ISOtech
_entityName.Add(8747, "int");
_entityValue.Add("there4", 8756); // therefore, U+2234 ISOtech
_entityName.Add(8756, "there4");
_entityValue.Add("sim", 8764); // tilde operator = varies with = similar to, U+223C ISOtech
_entityName.Add(8764, "sim");
_entityValue.Add("cong", 8773); // approximately equal to, U+2245 ISOtech
_entityName.Add(8773, "cong");
_entityValue.Add("asymp", 8776); // almost equal to = asymptotic to, U+2248 ISOamsr
_entityName.Add(8776, "asymp");
_entityValue.Add("ne", 8800); // not equal to, U+2260 ISOtech
_entityName.Add(8800, "ne");
_entityValue.Add("equiv", 8801); // identical to, U+2261 ISOtech
_entityName.Add(8801, "equiv");
_entityValue.Add("le", 8804); // less-than or equal to, U+2264 ISOtech
_entityName.Add(8804, "le");
_entityValue.Add("ge", 8805); // greater-than or equal to, U+2265 ISOtech
_entityName.Add(8805, "ge");
_entityValue.Add("sub", 8834); // subset of, U+2282 ISOtech
_entityName.Add(8834, "sub");
_entityValue.Add("sup", 8835); // superset of, U+2283 ISOtech
_entityName.Add(8835, "sup");
_entityValue.Add("nsub", 8836); // not a subset of, U+2284 ISOamsn
_entityName.Add(8836, "nsub");
_entityValue.Add("sube", 8838); // subset of or equal to, U+2286 ISOtech
_entityName.Add(8838, "sube");
_entityValue.Add("supe", 8839); // superset of or equal to, U+2287 ISOtech
_entityName.Add(8839, "supe");
_entityValue.Add("oplus", 8853); // circled plus = direct sum, U+2295 ISOamsb
_entityName.Add(8853, "oplus");
_entityValue.Add("otimes", 8855); // circled times = vector product, U+2297 ISOamsb
_entityName.Add(8855, "otimes");
_entityValue.Add("perp", 8869); // up tack = orthogonal to = perpendicular, U+22A5 ISOtech
_entityName.Add(8869, "perp");
_entityValue.Add("sdot", 8901); // dot operator, U+22C5 ISOamsb
_entityName.Add(8901, "sdot");
_entityValue.Add("lceil", 8968); // left ceiling = apl upstile, U+2308 ISOamsc
_entityName.Add(8968, "lceil");
_entityValue.Add("rceil", 8969); // right ceiling, U+2309 ISOamsc
_entityName.Add(8969, "rceil");
_entityValue.Add("lfloor", 8970); // left floor = apl downstile, U+230A ISOamsc
_entityName.Add(8970, "lfloor");
_entityValue.Add("rfloor", 8971); // right floor, U+230B ISOamsc
_entityName.Add(8971, "rfloor");
_entityValue.Add("lang", 9001); // left-pointing angle bracket = bra, U+2329 ISOtech
_entityName.Add(9001, "lang");
_entityValue.Add("rang", 9002); // right-pointing angle bracket = ket, U+232A ISOtech
_entityName.Add(9002, "rang");
_entityValue.Add("loz", 9674); // lozenge, U+25CA ISOpub
_entityName.Add(9674, "loz");
_entityValue.Add("spades", 9824); // black spade suit, U+2660 ISOpub
_entityName.Add(9824, "spades");
_entityValue.Add("clubs", 9827); // black club suit = shamrock, U+2663 ISOpub
_entityName.Add(9827, "clubs");
_entityValue.Add("hearts", 9829); // black heart suit = valentine, U+2665 ISOpub
_entityName.Add(9829, "hearts");
_entityValue.Add("diams", 9830); // black diamond suit, U+2666 ISOpub
_entityName.Add(9830, "diams");
_entityValue.Add("quot", 34); // quotation mark = APL quote, U+0022 ISOnum
_entityName.Add(34, "quot");
_entityValue.Add("amp", 38); // ampersand, U+0026 ISOnum
_entityName.Add(38, "amp");
_entityValue.Add("lt", 60); // less-than sign, U+003C ISOnum
_entityName.Add(60, "lt");
_entityValue.Add("gt", 62); // greater-than sign, U+003E ISOnum
_entityName.Add(62, "gt");
_entityValue.Add("OElig", 338); // latin capital ligature OE, U+0152 ISOlat2
_entityName.Add(338, "OElig");
_entityValue.Add("oelig", 339); // latin small ligature oe, U+0153 ISOlat2
_entityName.Add(339, "oelig");
_entityValue.Add("Scaron", 352); // latin capital letter S with caron, U+0160 ISOlat2
_entityName.Add(352, "Scaron");
_entityValue.Add("scaron", 353); // latin small letter s with caron, U+0161 ISOlat2
_entityName.Add(353, "scaron");
_entityValue.Add("Yuml", 376); // latin capital letter Y with diaeresis, U+0178 ISOlat2
_entityName.Add(376, "Yuml");
_entityValue.Add("circ", 710); // modifier letter circumflex accent, U+02C6 ISOpub
_entityName.Add(710, "circ");
_entityValue.Add("tilde", 732); // small tilde, U+02DC ISOdia
_entityName.Add(732, "tilde");
_entityValue.Add("ensp", 8194); // en space, U+2002 ISOpub
_entityName.Add(8194, "ensp");
_entityValue.Add("emsp", 8195); // em space, U+2003 ISOpub
_entityName.Add(8195, "emsp");
_entityValue.Add("thinsp", 8201); // thin space, U+2009 ISOpub
_entityName.Add(8201, "thinsp");
_entityValue.Add("zwnj", 8204); // zero width non-joiner, U+200C NEW RFC 2070
_entityName.Add(8204, "zwnj");
_entityValue.Add("zwj", 8205); // zero width joiner, U+200D NEW RFC 2070
_entityName.Add(8205, "zwj");
_entityValue.Add("lrm", 8206); // left-to-right mark, U+200E NEW RFC 2070
_entityName.Add(8206, "lrm");
_entityValue.Add("rlm", 8207); // right-to-left mark, U+200F NEW RFC 2070
_entityName.Add(8207, "rlm");
_entityValue.Add("ndash", 8211); // en dash, U+2013 ISOpub
_entityName.Add(8211, "ndash");
_entityValue.Add("mdash", 8212); // em dash, U+2014 ISOpub
_entityName.Add(8212, "mdash");
_entityValue.Add("lsquo", 8216); // left single quotation mark, U+2018 ISOnum
_entityName.Add(8216, "lsquo");
_entityValue.Add("rsquo", 8217); // right single quotation mark, U+2019 ISOnum
_entityName.Add(8217, "rsquo");
_entityValue.Add("sbquo", 8218); // single low-9 quotation mark, U+201A NEW
_entityName.Add(8218, "sbquo");
_entityValue.Add("ldquo", 8220); // left double quotation mark, U+201C ISOnum
_entityName.Add(8220, "ldquo");
_entityValue.Add("rdquo", 8221); // right double quotation mark, U+201D ISOnum
_entityName.Add(8221, "rdquo");
_entityValue.Add("bdquo", 8222); // double low-9 quotation mark, U+201E NEW
_entityName.Add(8222, "bdquo");
_entityValue.Add("dagger", 8224); // dagger, U+2020 ISOpub
_entityName.Add(8224, "dagger");
_entityValue.Add("Dagger", 8225); // double dagger, U+2021 ISOpub
_entityName.Add(8225, "Dagger");
_entityValue.Add("permil", 8240); // per mille sign, U+2030 ISOtech
_entityName.Add(8240, "permil");
_entityValue.Add("lsaquo", 8249); // single left-pointing angle quotation mark, U+2039 ISO proposed
_entityName.Add(8249, "lsaquo");
_entityValue.Add("rsaquo", 8250); // single right-pointing angle quotation mark, U+203A ISO proposed
_entityName.Add(8250, "rsaquo");
_entityValue.Add("euro", 8364); // euro sign, U+20AC NEW
_entityName.Add(8364, "euro");
_maxEntitySize = 8 + 1; // we add the # char
#endregion
}
/// <summary>
/// A collection of entities indexed by name.
/// </summary>
public static Hashtable EntityName
{
get
{
return _entityName;
}
}
/// <summary>
/// A collection of entities indexed by value.
/// </summary>
public static Hashtable EntityValue
{
get
{
return _entityValue;
}
}
/// <summary>
/// Clone and entitize an HtmlNode. This will affect attribute values and nodes' text. It will also entitize all child nodes.
/// </summary>
/// <param name="node">The node to entitize.</param>
/// <returns>An entitized cloned node.</returns>
public static HtmlNode Entitize(HtmlNode node)
{
if (node == null)
{
throw new ArgumentNullException("node");
}
HtmlNode result = node.CloneNode(true);
if (result.HasAttributes)
Entitize(result.Attributes);
if (result.HasChildNodes)
{
Entitize(result.ChildNodes);
}
else
{
if (result.NodeType == HtmlNodeType.Text)
{
((HtmlTextNode)result).Text = Entitize(((HtmlTextNode)result).Text, true, true);
}
}
return result;
}
private static void Entitize(HtmlAttributeCollection collection)
{
foreach(HtmlAttribute at in collection)
{
at.Value = Entitize(at.Value);
}
}
private static void Entitize(HtmlNodeCollection collection)
{
foreach(HtmlNode node in collection)
{
if (node.HasAttributes)
Entitize(node.Attributes);
if (node.HasChildNodes)
{
Entitize(node.ChildNodes);
}
else
{
if (node.NodeType == HtmlNodeType.Text)
{
((HtmlTextNode)node).Text = Entitize(((HtmlTextNode)node).Text, true, true);
}
}
}
}
/// <summary>
/// Replace characters above 127 by entities.
/// </summary>
/// <param name="text">The source text.</param>
/// <returns>The result text.</returns>
public static string Entitize(string text)
{
return Entitize(text, true);
}
/// <summary>
/// Replace characters above 127 by entities.
/// </summary>
/// <param name="text">The source text.</param>
/// <param name="useNames">If set to false, the function will not use known entities name. Default is true.</param>
/// <returns>The result text.</returns>
public static string Entitize(string text, bool useNames)
{
return Entitize( text, useNames, false);
}
/// <summary>
/// Replace characters above 127 by entities.
/// </summary>
/// <param name="text">The source text.</param>
/// <param name="useNames">If set to false, the function will not use known entities name. Default is true.</param>
/// <param name="entitizeQuotAmpAndLtGt">If set to true, the [quote], [ampersand], [lower than] and [greather than] characters will be entitized.</param>
/// <returns>The result text</returns>
public static string Entitize(string text, bool useNames, bool entitizeQuotAmpAndLtGt)
// _entityValue.Add("quot", 34); // quotation mark = APL quote, U+0022 ISOnum
// _entityName.Add(34, "quot");
// _entityValue.Add("amp", 38); // ampersand, U+0026 ISOnum
// _entityName.Add(38, "amp");
// _entityValue.Add("lt", 60); // less-than sign, U+003C ISOnum
// _entityName.Add(60, "lt");
// _entityValue.Add("gt", 62); // greater-than sign, U+003E ISOnum
// _entityName.Add(62, "gt");
{
if (text == null)
return null;
if (text.Length == 0)
return text;
StringBuilder sb = new StringBuilder(text.Length);
for(int i=0;i<text.Length;i++)
{
int code = (int)text[i];
if ((code>127) || (entitizeQuotAmpAndLtGt && ((code == 34) || (code == 38) || (code == 60) || (code == 62))))
{
string entity = _entityName[code] as string;
if ((entity == null) || (!useNames))
{
sb.Append("&#" + code + ";");
}
else
{
sb.Append("&" + entity + ";");
}
}
else
{
sb.Append(text[i]);
}
}
return sb.ToString();
}
/// <summary>
/// Replace known entities by characters.
/// </summary>
/// <param name="text">The source text.</param>
/// <returns>The result text.</returns>
public static string DeEntitize(string text)
{
if (text == null)
return null;
if (text.Length == 0)
return text;
StringBuilder sb = new StringBuilder(text.Length);
ParseState state = ParseState.Text;
StringBuilder entity = new StringBuilder(10);
for(int i=0;i<text.Length;i++)
{
switch(state)
{
case ParseState.Text:
switch(text[i])
{
case '&':
state = ParseState.EntityStart;
break;
default:
sb.Append(text[i]);
break;
}
break;
case ParseState.EntityStart:
switch(text[i])
{
case ';':
if (entity.Length == 0)
{
sb.Append("&;");
}
else
{
if (entity[0] == '#')
{
string e = entity.ToString();
try
{
int code = Convert.ToInt32(e.Substring(1, e.Length-1));
sb.Append(Convert.ToChar(code));
}
catch
{
sb.Append("&#" + e + ";");
}
}
else
{
// named entity?
int code;
object o = _entityValue[entity.ToString()];
if (o == null)
{
// nope
sb.Append("&" + entity + ";");
}
else
{
// we found one
code = (int)o;
sb.Append(Convert.ToChar(code));
}
}
entity.Remove(0, entity.Length);
}
state = ParseState.Text;
break;
case '&':
// new entity start without end, it was not an entity...
sb.Append("&" + entity);
entity.Remove(0, entity.Length);
break;
default:
entity.Append(text[i]);
if (entity.Length>_maxEntitySize)
{
// unknown stuff, just don't touch it
state = ParseState.Text;
sb.Append("&" + entity);
entity.Remove(0, entity.Length);
}
break;
}
break;
}
}
// finish the work
if (state == ParseState.EntityStart)
{
sb.Append("&" + entity);
}
return sb.ToString();
}
private enum ParseState
{
Text,
EntityStart
}
}
}
| |
// 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.Globalization;
using Xunit;
namespace System.Globalization.CalendarTests
{
// GregorianCalendar.GetMonth(DateTime)
public class GregorianCalendarGetMonth
{
private const int c_DAYS_IN_LEAP_YEAR = 366;
private const int c_DAYS_IN_COMMON_YEAR = 365;
#region Positive tests
// PosTest1: the speicified time is in leap year, February
[Fact]
public void PosTest1()
{
System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish);
DateTime time;
int year, month;
int expectedMonth, actualMonth;
year = GetALeapYear(myCalendar);
month = 2;
time = myCalendar.ToDateTime(year, month, 29, 10, 30, 12, 0);
expectedMonth = month;
actualMonth = myCalendar.GetMonth(time);
Assert.Equal(expectedMonth, actualMonth);
}
// PosTest2: the speicified time is in leap year, any month other than February
[Fact]
public void PosTest2()
{
System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish);
int year, month;
DateTime time;
int expectedMonth, actualMonth;
year = GetALeapYear(myCalendar);
//Get a random value beween 1 and 12 not including 2.
do
{
month = TestLibrary.Generator.GetInt32(-55) % 12 + 1;
} while (2 == month);
time = myCalendar.ToDateTime(year, month, 28, 10, 30, 20, 0);
expectedMonth = month;
actualMonth = myCalendar.GetMonth(time);
Assert.Equal(expectedMonth, actualMonth);
}
// PosTest3: the speicified time is in common year, February
[Fact]
public void PosTest3()
{
System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish);
int year, month;
DateTime time;
int expectedMonth, actualMonth;
year = GetACommonYear(myCalendar);
month = 2;
time = myCalendar.ToDateTime(year, month, 28, 10, 20, 30, 0);
expectedMonth = month;
actualMonth = myCalendar.GetMonth(time);
Assert.Equal(expectedMonth, actualMonth);
}
// PosTest4: the speicified time is in common year, any month other than February
[Fact]
public void PosTest4()
{
System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish);
int year, month;
DateTime time;
int expectedMonth, actualMonth;
year = GetACommonYear(myCalendar);
//Get a random value beween 1 and 12 not including 2.
do
{
month = TestLibrary.Generator.GetInt32(-55) % 12 + 1;
} while (2 == month);
time = myCalendar.ToDateTime(year, month, 28, 10, 30, 20, 0);
expectedMonth = month;
actualMonth = myCalendar.GetMonth(time);
Assert.Equal(expectedMonth, actualMonth);
}
// PosTest5: the speicified time is in minimum supported year, any month
[Fact]
public void PosTest5()
{
System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish);
int year, month;
DateTime time;
int expectedMonth, actualMonth;
year = myCalendar.MinSupportedDateTime.Year;
month = TestLibrary.Generator.GetInt32(-55) % 12 + 1;
time = myCalendar.ToDateTime(year, month, 20, 8, 20, 30, 0);
expectedMonth = month;
actualMonth = myCalendar.GetMonth(time);
Assert.Equal(expectedMonth, actualMonth);
}
// PosTest6: the speicified time is in maximum supported year, any month
[Fact]
public void PosTest6()
{
System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish);
int year, month;
DateTime time;
int expectedMonth, actualMonth;
year = myCalendar.MaxSupportedDateTime.Year;
month = TestLibrary.Generator.GetInt32(-55) % 12 + 1;
time = myCalendar.ToDateTime(year, month, 20, 8, 20, 30, 0);
expectedMonth = month;
actualMonth = myCalendar.GetMonth(time);
Assert.Equal(expectedMonth, actualMonth);
}
// PosTest7: the speicified time is in any year, minimum month
[Fact]
public void PosTest7()
{
System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish);
int year, month;
DateTime time;
int expectedMonth, actualMonth;
year = myCalendar.MinSupportedDateTime.Year;
month = 1;
time = myCalendar.ToDateTime(year, month, 20, 8, 20, 30, 0);
expectedMonth = month;
actualMonth = myCalendar.GetMonth(time);
Assert.Equal(expectedMonth, actualMonth);
}
// PosTest8: the speicified time is in any year, maximum month
[Fact]
public void PosTest8()
{
System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish);
int year, month;
DateTime time;
int expectedMonth, actualMonth;
year = myCalendar.MaxSupportedDateTime.Year;
month = 12;
time = myCalendar.ToDateTime(year, month, 20, 8, 20, 30, 0);
expectedMonth = month;
actualMonth = myCalendar.GetMonth(time);
Assert.Equal(expectedMonth, actualMonth);
}
// PosTest9: the speicified time is in any year, any month
[Fact]
public void PosTest9()
{
System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish);
int year, month;
DateTime time;
int expectedMonth, actualMonth;
year = GetAYear(myCalendar);
month = TestLibrary.Generator.GetInt32(-55) % 12 + 1;
time = myCalendar.ToDateTime(year, month, 20, 8, 20, 30, 0);
expectedMonth = month;
actualMonth = myCalendar.GetMonth(time);
Assert.Equal(expectedMonth, actualMonth);
}
#endregion
#region Helper methods for all the tests
//Indicate whether the specified year is leap year or not
private bool IsLeapYear(int year)
{
if (0 == year % 400 || (0 != year % 100 && 0 == (year & 0x3)))
{
return true;
}
return false;
}
//Get a random year beween minmum supported year and maximum supported year of the specified calendar
private int GetAYear(Calendar calendar)
{
int retVal;
int maxYear, minYear;
maxYear = calendar.MaxSupportedDateTime.Year;
minYear = calendar.MinSupportedDateTime.Year;
retVal = minYear + TestLibrary.Generator.GetInt32(-55) % (maxYear + 1 - minYear);
return retVal;
}
//Get a leap year of the specified calendar
private int GetALeapYear(Calendar calendar)
{
int retVal;
// A leap year is any year divisible by 4 except for centennial years(those ending in 00)
// which are only leap years if they are divisible by 400.
retVal = ~(~GetAYear(calendar) | 0x3); // retVal will be divisible by 4 since the 2 least significant bits will be 0
retVal = (0 != retVal % 100) ? retVal : (retVal - retVal % 400); // if retVal is divisible by 100 subtract years from it to make it divisible by 400
// if retVal was 100, 200, or 300 the above logic will result in 0
if (0 == retVal)
{
retVal = 400;
}
return retVal;
}
//Get a common year of the specified calendar
private int GetACommonYear(Calendar calendar)
{
int retVal;
do
{
retVal = GetAYear(calendar);
}
while ((0 == (retVal & 0x3) && 0 != retVal % 100) || 0 == retVal % 400);
return retVal;
}
//Get text represntation of the input parmeters
private string GetParamsInfo(int year)
{
string str;
str = string.Format("\nThe specified year is {0:04}(yyyy).", year);
return str;
}
//Get text represntation of the input parmeters
private string GetParamsInfo(DateTime time)
{
string str;
str = string.Format("\nThe specified time is ({0}).", time);
return str;
}
#endregion
}
}
| |
using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using System.Text;
using Epi.Analysis;
using Epi.Windows.Dialogs;
using Epi.Windows.Analysis;
namespace Epi.Windows.Analysis.Dialogs
{
/// <summary>
/// Dialog for Complex Sample Tables command (TABLES or MATCH).
/// </summary>
public partial class ComplexSampleTablesDialog : CommandDesignDialog
{
#region Constructor
/// <summary>
/// Default constructor - NOT TO BE USED FOR INSTANTIATION
/// </summary>
[Obsolete("Use of default constructor not allowed", true)]
public ComplexSampleTablesDialog()
{
InitializeComponent();
Construct();
}
/// <summary>
/// TablesDialog constructor
/// </summary>
/// <param name="frm"></param>
public ComplexSampleTablesDialog(Epi.Windows.Analysis.Forms.AnalysisMainForm frm)
: base(frm)
{
InitializeComponent();
Construct();
}
#endregion Constructors
#region Private Properties
string txtExposure = String.Empty;
string txtWeight = String.Empty;
string txtStratifyBy = String.Empty;
string txtPSU = String.Empty;
string txtOutcome = String.Empty;
#endregion Private Properties
#region Private Methods
protected void Construct()
{
if (!this.DesignMode)
{
this.btnOK.Click += new System.EventHandler(this.btnOK_Click);
this.btnSaveOnly.Click += new System.EventHandler(this.btnSaveOnly_Click);
}
}
/// <summary>
/// Loads the Complex Sample Tables dialog.
/// </summary>
private void TablesDialog_Load(object sender, EventArgs e)
{
VariableType scopeWord = VariableType.DataSource | VariableType.DataSourceRedefined |
VariableType.Standard;
FillVariableCombo( cmbExposure, scopeWord );
cmbExposure.Items.Insert( 0, "*" );
cmbExposure.SelectedIndex = -1;
FillVariableCombo( cmbOutcome, scopeWord );
FillVariableCombo( cmbStratifyBy, scopeWord );
cmbStratifyBy.SelectedIndex = -1;
FillVariableCombo(cmbWeight, scopeWord);
FillVariableCombo(cmbPSU, scopeWord);
cmbWeight.SelectedIndex = -1;
cmbPSU.SelectedIndex = -1;
}
#endregion Private Methods
#region Public Methods
/// <summary>
/// Sets enabled property of OK and Save Only
/// </summary>
public override void CheckForInputSufficiency()
{
bool inputValid = ValidateInput();
btnOK.Enabled = inputValid;
btnSaveOnly.Enabled = inputValid;
}
#endregion Public Methods
#region Protected Methods
/// <summary>
/// Generates the command text
/// </summary>
protected override void GenerateCommand()
{
StringBuilder sb = new StringBuilder();
if (cbxMatch.Checked)
{
sb.Append(CommandNames.MATCH);
}
else
{
sb.Append(CommandNames.TABLES);
}
sb.Append(StringLiterals.SPACE);
sb.Append(cmbExposure.Text);
sb.Append(StringLiterals.SPACE);
sb.Append(cmbOutcome.Text );
sb.Append(StringLiterals.SPACE);
if (cbxMatch.Checked)
{
sb.Append(CommandNames.MATCHVAR);
sb.Append(StringLiterals.EQUAL);
sb.Append(cmbStratifyBy.Text);
//foreach (string s in this.lbxStratifyBy.Items)
//{
// sb.Append(s);
// sb.Append(StringLiterals.SPACE);
//}
}
//else if (lbxStratifyBy.Items.Count > 0 )
else if (cmbStratifyBy.SelectedIndex >= 0 )
{
sb.Append(CommandNames.STRATAVAR);
sb.Append(StringLiterals.EQUAL);
sb.Append(cmbStratifyBy.Text);
//foreach (string s in this.lbxStratifyBy.Items)
//{
// sb.Append(s);
// sb.Append(StringLiterals.SPACE);
//}
}
if (cmbWeight.SelectedIndex >= 0)
{
sb.Append(StringLiterals.SPACE);
sb.Append(CommandNames.WEIGHTVAR);
sb.Append(StringLiterals.EQUAL);
sb.Append(cmbWeight.Text);
}
sb.Append(StringLiterals.SPACE);
sb.Append(CommandNames.PSUVAR);
sb.Append(StringLiterals.EQUAL);
sb.Append(cmbPSU.Text);
if (txtOutput.TextLength > 0)
{
sb.Append(StringLiterals.SPACE);
sb.Append(CommandNames.OUTTABLE);
sb.Append(StringLiterals.EQUAL);
sb.Append(txtOutput.Text);
}
if (txtNumCol.TextLength > 0)
{
sb.Append(StringLiterals.SPACE);
sb.Append(CommandNames.COLUMNSIZE);
sb.Append(StringLiterals.EQUAL);
sb.Append(txtNumCol.Text);
}
if (cbxNoLineWrap.Checked)
{
sb.Append(StringLiterals.SPACE);
sb.Append(CommandNames.NOWRAP);
}
CommandText = sb.ToString();
}
/// <summary>
/// Validates user input
/// </summary>
/// <returns>true if there is no error; else false</returns>
protected override bool ValidateInput()
{
base.ValidateInput();
if (cmbExposure.SelectedIndex == -1)
{
ErrorMessages.Add( SharedStrings.MUST_SELECT_EXPOSURE );
}
if (cmbOutcome.SelectedIndex == -1)
{
ErrorMessages.Add( SharedStrings.MUST_SELECT_OUTCOME );
}
if (cmbPSU.SelectedIndex == -1)
{
ErrorMessages.Add(SharedStrings.MUST_SELECT_PSU);
}
// cmbStratifyby doubles as cmbMatchVar (which doesn't exist)
//if (cbxMatch.Checked && (lbxStratifyBy.Items.Count < 1))
if (cbxMatch.Checked && (cmbStratifyBy.SelectedIndex < 0))
{
ErrorMessages.Add( SharedStrings.NO_MATCHVAR);
}
return (ErrorMessages.Count == 0);
}
#endregion Protected Methods
#region Event Handlers
/// <summary>
/// Handles the btnClear Click event
/// </summary>
/// <param name="sender">Object that fired the event.</param>
/// <param name="e">.NET supplied event args.</param>
private void btnClear_Click(object sender, System.EventArgs e)
{
cmbOutcome.Items.Clear();
cmbStratifyBy.Items.Clear();
cmbWeight.Items.Clear();
cmbPSU.Text = string.Empty;
txtOutput.Text = string.Empty;
//lbxStratifyBy.Items.Clear();
TablesDialog_Load(this, null);
}
/// <summary>
/// Handles the lbxStratifyBy SelectedIndexChanged event.
/// </summary>
/// <remarks>Removes item from StratifyBy listbox; Adds it back to the other comboboxes.</remarks>
/// <param name="sender">Object that fired the event.</param>
/// <param name="e">.NET supplied event args.</param>
private void lbxStratifyBy_SelectedIndexChanged(object sender, EventArgs e)
{
if (lbxStratifyBy.SelectedIndex >= 0) // prevent the remove below from re-entering
{
string s = this.lbxStratifyBy.SelectedItem.ToString();
cmbExposure.Items.Add(s);
cmbWeight.Items.Add(s);
cmbPSU.Items.Add(s);
cmbOutcome.Items.Add(s);
cmbStratifyBy.Items.Add(s);
lbxStratifyBy.Items.Remove(s);
}
CheckForInputSufficiency();
}
/// <summary>
/// Handles the cmbStratifyBy SelectedIndexChanged event.
/// </summary>
/// <remarks>Removes item from other comboboxes; Inserts item into StratifyBy listbox.</remarks>
/// <param name="sender">Object that fired the event.</param>
/// <param name="e">.NET supplied event args.</param>
private void cmbStratifyBy_SelectedIndexChanged(object sender, EventArgs e)
{
//Get the old variable chosen that was saved to the txt string.
string strOld = txtStratifyBy;
string strNew = cmbStratifyBy.Text;
//make sure it isn't "" or the same as the new variable picked.
if ((strOld.Length > 0) && (strOld != strNew))
{
cmbExposure.Items.Add(strOld);
cmbWeight.Items.Add(strOld);
cmbPSU.Items.Add(strOld);
cmbOutcome.Items.Add(strOld);
//cmbStratifyBy.Items.Add(strOld);
}
if (cmbStratifyBy.SelectedIndex >= 0)
{
cmbExposure.Items.Remove(strNew);
cmbWeight.Items.Remove(strNew);
cmbPSU.Items.Remove(strNew);
cmbOutcome.Items.Remove(strNew);
//cmbStratifyBy.Items.Remove(strNew);
this.txtStratifyBy = strNew;
}
CheckForInputSufficiency();
}
/// <summary>
/// Handles the cmbOutcome SelectedIndexChanged event
/// </summary>
/// <remarks>Removes item from other comboboxes</remarks>
/// <param name="sender">Object that fired the event.</param>
/// <param name="e">.NET supplied event args.</param>
private void cmbOutcome_SelectedIndexChanged(object sender, EventArgs e)
{
//Get the old variable chosen that was saved to the txt string.
string strOld = txtOutcome;
string strNew = cmbOutcome.Text;
//make sure it isn't "" or the same as the new variable picked.
if ((strOld.Length > 0) && (strOld != strNew))
{
cmbExposure.Items.Add(strOld);
cmbWeight.Items.Add(strOld);
cmbPSU.Items.Add(strOld);
//cmbOutcome.Items.Add(strOld);
cmbStratifyBy.Items.Add(strOld);
}
if (cmbOutcome.SelectedIndex >= 0)
{
cmbExposure.Items.Remove(strNew);
cmbWeight.Items.Remove(strNew);
cmbPSU.Items.Remove(strNew);
//cmbOutcome.Items.Remove(strNew);
cmbStratifyBy.Items.Remove(strNew);
this.txtExposure = strNew;
}
CheckForInputSufficiency();
}
/// <summary>
/// Handles the cmbExposure SelectedIndexChanged event
/// </summary>
/// <remarks>Removes item from other comboboxes</remarks>
/// <param name="sender">Object that fired the event.</param>
/// <param name="e">.NET supplied event args.</param>
private void cmbExposure_SelectedIndexChanged(object sender, EventArgs e)
{
//Get the old variable chosen that was saved to the txt string.
string strOld = txtExposure;
string strNew = cmbExposure.Text;
//make sure it isn't "" or the same as the new variable picked.
if ((strOld.Length > 0) && (strOld != strNew))
{
//cmbExposure.Items.Add(strOld);
cmbWeight.Items.Add(strOld);
cmbPSU.Items.Add(strOld);
cmbOutcome.Items.Add(strOld);
cmbStratifyBy.Items.Add(strOld);
}
if (cmbExposure.SelectedIndex >= 0)
{
//cmbExposure.Items.Remove(strNew);
cmbWeight.Items.Remove(strNew);
cmbPSU.Items.Remove(strNew);
cmbOutcome.Items.Remove(strNew);
cmbStratifyBy.Items.Remove(strNew);
this.txtExposure = strNew;
}
CheckForInputSufficiency();
}
/// <summary>
/// Handles the KeyDown event for cmbWeight.
/// Allows to delete the optional value for Weight.
/// </summary>
/// <param name="sender">Object that fired the event.</param>
/// <param name="e">.NET supplied event args.</param>
private void cmbWeight_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Delete)
{
//SelectedIndexChanged will add the var back to the other DDLs
cmbWeight.Text = "";
cmbWeight.SelectedIndex = -1;
}
}
/// <summary>
/// Handles the Click event for cmbExposure.
/// Saves the content of the text to the temp storage or resets.
/// </summary>
/// <param name="sender">Object that fired the event.</param>
/// <param name="e">.NET supplied event args.</param>
private void cmbExposure_Click(object sender, EventArgs e)
{
txtExposure = (cmbExposure.SelectedIndex >= 0) ? cmbExposure.Text : "";
}
/// <summary>
/// Handles the Click event for cmbOutcome.
/// Saves the content of the text to the temp storage or resets.
/// </summary>
/// <param name="sender">Object that fired the event.</param>
/// <param name="e">.NET supplied event args.</param>
private void cmbOutcome_Click(object sender, EventArgs e)
{
txtOutcome = (cmbOutcome.SelectedIndex >= 0) ? cmbOutcome.Text : "";
}
/// <summary>
/// Handles the Click event for cmbPSU.
/// Saves the content of the text to the temp storage or resets.
/// </summary>
/// <param name="sender">Object that fired the event.</param>
/// <param name="e">.NET supplied event args.</param>
private void cmbPSU_Click(object sender, EventArgs e)
{
txtPSU = (cmbPSU.SelectedIndex >= 0) ? cmbPSU.Text : "";
}
/// <summary>
/// Handles the Click event for cmbWeight.
/// Saves the content of the text to the temp storage or resets.
/// </summary>
/// <param name="sender">Object that fired the event.</param>
/// <param name="e">.NET supplied event args.</param>
private void cmbWeight_Click(object sender, EventArgs e)
{
txtWeight = (cmbWeight.SelectedIndex >= 0) ? cmbWeight.Text : "";
}
/// <summary>
/// Handles the cmbWeight SelectedIndexChanged event
/// </summary>
/// <remarks>Removes item from other comboboxes</remarks>
/// <param name="sender">Object that fired the event.</param>
/// <param name="e">.NET supplied event args.</param>
private void cmbWeight_SelectedIndexChanged(object sender, EventArgs e)
{
//Get the old variable chosen that was saved to the txt string.
string strOld = txtWeight;
string strNew = cmbWeight.Text;
//make sure it isn't "" or the same as the new variable picked.
if ((strOld.Length > 0) && (strOld != strNew))
{
cmbExposure.Items.Add(strOld);
//cmbWeight.Items.Add(strOld);
cmbPSU.Items.Add(strOld);
cmbOutcome.Items.Add(strOld);
cmbStratifyBy.Items.Add(strOld);
}
if (cmbWeight.SelectedIndex >= 0)
{
cmbExposure.Items.Remove(strNew);
//cmbWeight.Items.Remove(strNew);
cmbPSU.Items.Remove(strNew);
cmbOutcome.Items.Remove(strNew);
cmbStratifyBy.Items.Remove(strNew);
this.txtWeight = strNew;
}
}
/// <summary>
/// Handles the cmbPSU SelectedIndexChanged event
/// </summary>
/// <remarks>Removes item from other comboboxes</remarks>
/// <param name="sender">Object that fired the event.</param>
/// <param name="e">.NET supplied event args.</param>
private void cmbPSU_SelectedIndexChanged(object sender, EventArgs e)
{
//Get the old variable chosen that was saved to the txt string.
string strOld = txtPSU;
string strNew = cmbPSU.Text;
//make sure it isn't "" or the same as the new variable picked.
if ((strOld.Length > 0) && (strOld != strNew))
{
cmbExposure.Items.Add(strOld);
cmbWeight.Items.Add(strOld);
//cmbPSU.Items.Add(strOld);
cmbOutcome.Items.Add(strOld);
cmbStratifyBy.Items.Add(strOld);
}
if (cmbPSU.SelectedIndex >= 0)
{
cmbExposure.Items.Remove(strNew);
cmbWeight.Items.Remove(strNew);
//cmbPSU.Items.Remove(strNew);
cmbOutcome.Items.Remove(strNew);
cmbStratifyBy.Items.Remove(strNew);
this.txtExposure = strNew;
}
CheckForInputSufficiency();
}
/// <summary>
/// Handles the KeyPress event for txtNumCol.
/// Allows only digits, delete, and backspace strokes; Limits to two digits length.
/// </summary>
/// <param name="sender">Object that fired the event.</param>
/// <param name="e">.NET supplied event args.</param>
private void txtNumCol_KeyPress(object sender, KeyPressEventArgs e)
{
string keyInput = e.KeyChar.ToString();
if (e.KeyChar.ToString().Equals("\b"))
{
// Backspace key is OK
}
else if (e.KeyChar.Equals(Keys.Delete))
{
// Delete key is OK
}
else if (e.KeyChar.ToString().Equals("0"))
{
if (txtNumCol.TextLength == 0) e.Handled = true;
}
else if ((txtNumCol.TextLength <= 1) && (Char.IsDigit(e.KeyChar)))
{
// Digits are OK
}
else
{
e.Handled = true;
}
}
/// <summary>
/// Opens a process to show the related help topic
/// </summary>
/// <param name="sender">Object that fired the event.</param>
/// <param name="e">.NET supplied event args.</param>
protected override void btnHelp_Click(object sender, System.EventArgs e)
{
System.Diagnostics.Process.Start("http://www.cdc.gov/epiinfo/user-guide/command-reference/analysis-commands-tables.html");
}
#endregion Event Handlers
/// <summary>
/// Handles the Click event for Match checkbox.
/// <remarks>Sets lblStratifyBy font to bold indicating items are required.</remarks>
/// </summary>
/// <param name="sender">Object that fired the event.</param>
/// <param name="e">.NET supplied event args.</param>
private void cbxMatch_Click(object sender, EventArgs e)
{
if (cbxMatch.Checked)
{
lblStratifyBy.Text = "Match Variables";
lblStratifyBy.Font = new Font(lblStratifyBy.Font, FontStyle.Bold);
}
else
{
lblStratifyBy.Text = "Stratify By";
lblStratifyBy.Font = new Font(lblStratifyBy.Font, FontStyle.Regular);
}
CheckForInputSufficiency();
}
/// <summary>
/// Handles the Leave event for Number of Columns textbox.
/// <remarks>Clears the textbox if only a 0 exists.</remarks>
/// </summary>
/// <param name="sender">Object that fired the event.</param>
/// <param name="e">.NET supplied event args.</param>
private void txtNumCol_Leave(object sender, EventArgs e)
{
if (txtNumCol.Text.Equals("0")) txtNumCol.Text = "";
}
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Common.Logging;
using Lucene.Net.Index;
using Lucene.Net.Linq;
using Lucene.Net.Search;
using Ninject;
namespace NuGet.Server.Infrastructure.Lucene
{
public class PackageIndexer : IPackageIndexer, IInitializable, IDisposable
{
public static ILog Log = LogManager.GetLogger<PackageIndexer>();
private enum UpdateType { Add, Remove, RemoveByPath, Increment }
private class Update
{
private readonly LucenePackage package;
private readonly UpdateType updateType;
private readonly TaskCompletionSource<object> signal = new TaskCompletionSource<object>();
public Update(LucenePackage package, UpdateType updateType)
{
this.package = package;
this.updateType = updateType;
}
public LucenePackage Package
{
get { return package; }
}
public UpdateType UpdateType
{
get { return updateType; }
}
public Task Task
{
get
{
return signal.Task;
}
}
public void SetComplete()
{
signal.SetResult(null);
}
}
private readonly IList<IndexingStatus> indexingStatus = new List<IndexingStatus> { new IndexingStatus { State = IndexingState.Idle } };
private readonly BlockingCollection<Update> pendingUpdates = new BlockingCollection<Update>();
private Task indexUpdaterTask;
[Inject]
public IFileSystem FileSystem { get; set; }
[Inject]
public IndexWriter Writer { get; set; }
[Inject]
public LuceneDataProvider Provider { get; set; }
[Inject]
public ILucenePackageRepository PackageRepository { get; set; }
public void Initialize()
{
Action<Task> cb = task =>
{
if (task.Exception != null)
{
Log.Error(task.Exception);
}
};
// Sync lucene index with filesystem whenever the web app starts.
SynchronizeIndexWithFileSystem().ContinueWith(cb);
indexUpdaterTask = Task.Factory.StartNew(IndexUpdateLoop, TaskCreationOptions.LongRunning);
}
public void Dispose()
{
pendingUpdates.CompleteAdding();
indexUpdaterTask.Wait();
}
/// <summary>
/// Gets status of index building activity.
/// </summary>
public IndexingStatus GetIndexingStatus()
{
IndexingStatus current;
lock (indexingStatus)
{
current = indexingStatus.Last();
}
using (var reader = Writer.GetReader())
{
return new IndexingStatus
{
State = current.State,
CompletedPackages = current.CompletedPackages,
PackagesToIndex = current.PackagesToIndex,
CurrentPackagePath = current.CurrentPackagePath,
TotalPackages = reader.NumDocs(),
PendingDeletes = reader.NumDeletedDocs,
IsOptimized = reader.IsOptimized(),
LastModification = DateTimeUtils.FromJava(reader.IndexCommit.Timestamp)
};
}
}
public void Optimize()
{
using (UpdateStatus(IndexingState.Optimizing))
{
Writer.Optimize();
}
}
public Task SynchronizeIndexWithFileSystem()
{
IndexDifferences differences = null;
Action findDifferences = () =>
{
using (UpdateStatus(IndexingState.Scanning))
{
using (var session = OpenSession())
{
differences = IndexDifferenceCalculator.FindDifferences(FileSystem, session.Query());
}
}
};
return Task.Run(findDifferences).ContinueWith(task => SynchronizeIndexWithFileSystem(differences), TaskContinuationOptions.NotOnFaulted);
}
public Task AddPackage(LucenePackage package)
{
var update = new Update(package, UpdateType.Add);
pendingUpdates.Add(update);
return update.Task;
}
public Task RemovePackage(IPackage package)
{
if (!(package is LucenePackage)) throw new ArgumentException("Package of type " + package.GetType() + " not supported.");
var update = new Update((LucenePackage)package, UpdateType.Remove);
pendingUpdates.Add(update);
return update.Task;
}
public Task IncrementDownloadCount(IPackage package)
{
if (!(package is LucenePackage)) throw new ArgumentException("Package of type " + package.GetType() + " not supported.");
if (string.IsNullOrWhiteSpace(package.Id))
{
throw new InvalidOperationException("Package Id must be specified.");
}
if (package.Version == null)
{
throw new InvalidOperationException("Package Version must be specified.");
}
var update = new Update((LucenePackage) package, UpdateType.Increment);
pendingUpdates.Add(update);
return update.Task;
}
internal void SynchronizeIndexWithFileSystem(IndexDifferences diff)
{
if (diff.IsEmpty) return;
var tasks = new ConcurrentQueue<Task>();
Log.Info(string.Format("Updates to process: {0} packages added, {1} packages updated, {2} packages removed.", diff.NewPackages.Count(), diff.ModifiedPackages.Count(), diff.MissingPackages.Count()));
foreach (var path in diff.MissingPackages)
{
var package = new LucenePackage(FileSystem) { Path = path };
var update = new Update(package, UpdateType.RemoveByPath);
pendingUpdates.Add(update);
tasks.Enqueue(update.Task);
}
var pathsToIndex = diff.NewPackages.Union(diff.ModifiedPackages).OrderBy(p => p).ToArray();
var i = 0;
Parallel.ForEach(pathsToIndex, new ParallelOptions { MaxDegreeOfParallelism = 5 }, (p, s) =>
{
using(UpdateStatus(IndexingState.Building, completedPackages: Interlocked.Increment(ref i), packagesToIndex: pathsToIndex.Length, currentPackagePath: p))
{
tasks.Enqueue(SynchronizePackage(p));
}
});
Task.WaitAll(tasks.ToArray());
}
private Task SynchronizePackage(string path)
{
try
{
var package = PackageRepository.LoadFromFileSystem(path);
return AddPackage(package);
}
catch (Exception ex)
{
Log.Error("Failed to index package path: " + path, ex);
return Task.FromResult(ex);
}
}
private void IndexUpdateLoop()
{
while (!pendingUpdates.IsCompleted)
{
var items = pendingUpdates.TakeAvailable(Timeout.InfiniteTimeSpan).ToList();
if (items.Any())
{
ApplyUpdates(items);
}
items.ForEach(i => i.SetComplete());
}
}
private void ApplyUpdates(IList<Update> items)
{
Log.Trace(m => m("Processing {0} updates.", items.Count()));
using (var session = OpenSession())
{
using (UpdateStatus(IndexingState.Building))
{
var removals =
items.Where(i => i.UpdateType == UpdateType.Remove).Select(i => i.Package).ToList();
removals.ForEach(pkg => RemovePackageInternal(pkg, session));
var removalsByPath =
items.Where(i => i.UpdateType == UpdateType.RemoveByPath).Select(i => i.Package.Path).ToList();
var deleteQueries = removalsByPath.Select(p => (Query)new TermQuery(new Term("Path", p))).ToArray();
session.Delete(deleteQueries);
var additions = items.Where(i => i.UpdateType == UpdateType.Add).Select(i => i.Package).ToList();
ApplyPendingAdditions(additions, session);
var downloadUpdates =
items.Where(i => i.UpdateType == UpdateType.Increment).Select(i => i.Package).ToList();
ApplyPendingDownloadIncrements(downloadUpdates, session);
}
using (UpdateStatus(IndexingState.Commit))
{
session.Commit();
}
}
}
private void ApplyPendingAdditions(IEnumerable<LucenePackage> additions, ISession<LucenePackage> session)
{
foreach (var grouping in additions.GroupBy(pkg => pkg.Id))
{
AddPackagesInternal(grouping.Key, grouping.ToList(), session);
}
}
private void AddPackagesInternal(string packageId, IEnumerable<LucenePackage> packages, ISession<LucenePackage> session)
{
var currentPackages = (from p in session.Query()
where p.Id == packageId
orderby p.Version descending
select p).ToList();
var newest = currentPackages.FirstOrDefault();
var versionDownloadCount = newest != null ? newest.VersionDownloadCount : 0;
foreach (var package in packages)
{
var packageToReplace = currentPackages.Find(p => p.Version == package.Version);
package.VersionDownloadCount = versionDownloadCount;
package.DownloadCount = packageToReplace != null ? packageToReplace.DownloadCount : 0;
currentPackages.Remove(packageToReplace);
currentPackages.Add(package);
session.Add(package);
}
UpdatePackageVersionFlags(currentPackages.OrderByDescending(p => p.Version));
}
private void RemovePackageInternal(LucenePackage package, ISession<LucenePackage> session)
{
session.Delete(package);
var remainingPackages = from p in session.Query()
where p.Id == package.Id
orderby p.Version descending
select p;
UpdatePackageVersionFlags(remainingPackages);
}
private void UpdatePackageVersionFlags(IEnumerable<LucenePackage> packages)
{
var first = true;
foreach (var p in packages)
{
p.IsLatestVersion = first;
p.IsAbsoluteLatestVersion = first;
if (first)
{
first = false;
}
}
}
//public IList<IPackage> PendingDownloadIncrements
//{
// get { return new List<IPackage>(pendingUpdates); }
//}
public void ApplyPendingDownloadIncrements(IList<LucenePackage> increments, ISession<LucenePackage> session)
{
if (increments.Count == 0) return;
var byId = increments.ToLookup(p => p.Id);
foreach (var grouping in byId)
{
var packageId = grouping.Key;
var packages = from p in session.Query() where p.Id == packageId select p;
var byVersion = grouping.ToLookup(p => p.Version);
foreach (var lucenePackage in packages)
{
lucenePackage.DownloadCount += grouping.Count();
lucenePackage.VersionDownloadCount += byVersion[lucenePackage.Version].Count();
}
}
}
protected internal virtual ISession<LucenePackage> OpenSession()
{
return Provider.OpenSession(() => new LucenePackage(FileSystem));
}
private IDisposable UpdateStatus(IndexingState state, int completedPackages = 0, int packagesToIndex = 0, string currentPackagePath = null)
{
var status = new IndexingStatus
{
State = state,
CompletedPackages = completedPackages,
PackagesToIndex = packagesToIndex,
CurrentPackagePath = currentPackagePath
};
lock (indexingStatus)
{
indexingStatus.Add(status);
}
return new DisposableAction(() =>
{
lock (indexingStatus)
{
indexingStatus.Remove(status);
}
});
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Orleans;
namespace UnitTests.GrainInterfaces
{
public interface IGenericGrainWithGenericState<TFirstTypeParam, TStateType, TLastTypeParam> : IGrainWithGuidKey
{
Task<Type> GetStateType();
}
public class GenericGrainWithGenericState<TFirstTypeParam, TStateType, TLastTypeParam> : Grain<TStateType>,
IGenericGrainWithGenericState<TFirstTypeParam, TStateType, TLastTypeParam> where TStateType : new()
{
public Task<Type> GetStateType() => Task.FromResult(this.State.GetType());
}
public interface IGenericGrain<T, U> : IGrainWithIntegerKey
{
Task SetT(T a);
Task<U> MapT2U();
}
public interface ISimpleGenericGrain1<T> : IGrainWithIntegerKey
{
Task<T> GetA();
Task<string> GetAxB();
Task<string> GetAxB(T a, T b);
Task SetA(T a);
Task SetB(T b);
}
/// <summary>
/// Long named grain type, which can cause issues in AzureTableStorage
/// </summary>
/// <typeparam name="T"></typeparam>
public interface ISimpleGenericGrainUsingAzureTableStorage<T> : IGrainWithGuidKey
{
Task<T> EchoAsync(T entity);
Task ClearState();
}
/// <summary>
/// Short named grain type, which shouldn't cause issues in AzureTableStorage
/// </summary>
/// <typeparam name="T"></typeparam>
public interface ITinyNameGrain<T> : IGrainWithGuidKey
{
Task<T> EchoAsync(T entity);
Task ClearState();
}
public interface ISimpleGenericGrainU<U> : IGrainWithIntegerKey
{
Task<U> GetA();
Task<string> GetAxB();
Task<string> GetAxB(U a, U b);
Task SetA(U a);
Task SetB(U b);
}
public interface ISimpleGenericGrain2<T, in U> : IGrainWithIntegerKey
{
Task<T> GetA();
Task<string> GetAxB();
Task<string> GetAxB(T a, U b);
Task SetA(T a);
Task SetB(U b);
}
public interface IGenericGrainWithNoProperties<in T> : IGrainWithIntegerKey
{
Task<string> GetAxB(T a, T b);
}
public interface IGrainWithNoProperties : IGrainWithIntegerKey
{
Task<string> GetAxB(int a, int b);
}
public interface IGrainWithListFields : IGrainWithIntegerKey
{
Task AddItem(string item);
Task<IList<string>> GetItems();
}
public interface IGenericGrainWithListFields<T> : IGrainWithIntegerKey
{
Task AddItem(T item);
Task<IList<T>> GetItems();
}
public interface IGenericReader1<T> : IGrainWithIntegerKey
{
Task<T> GetValue();
}
public interface IGenericWriter1<in T> : IGrainWithIntegerKey
{
Task SetValue(T value);
}
public interface IGenericReaderWriterGrain1<T> : IGenericWriter1<T>, IGenericReader1<T>
{
}
public interface IGenericReader2<TOne, TTwo> : IGrainWithIntegerKey
{
Task<TOne> GetValue1();
Task<TTwo> GetValue2();
}
public interface IGenericWriter2<in TOne, in TTwo> : IGrainWithIntegerKey
{
Task SetValue1(TOne value);
Task SetValue2(TTwo value);
}
public interface IGenericReaderWriterGrain2<TOne, TTwo> : IGenericWriter2<TOne, TTwo>, IGenericReader2<TOne, TTwo>
{
}
public interface IGenericReader3<TOne, TTwo, TThree> : IGenericReader2<TOne, TTwo>
{
Task<TThree> GetValue3();
}
public interface IGenericWriter3<in TOne, in TTwo, in TThree> : IGenericWriter2<TOne, TTwo>
{
Task SetValue3(TThree value);
}
public interface IGenericReaderWriterGrain3<TOne, TTwo, TThree> : IGenericWriter3<TOne, TTwo, TThree>, IGenericReader3<TOne, TTwo, TThree>
{
}
public interface IBasicGenericGrain<T, U> : IGrainWithIntegerKey
{
Task<T> GetA();
Task<string> GetAxB();
Task<string> GetAxB(T a, U b);
Task SetA(T a);
Task SetB(U b);
}
public interface IHubGrain<TKey, T1, T2> : IGrainWithIntegerKey
{
Task Bar(TKey key, T1 message1, T2 message2);
}
public interface IEchoHubGrain<TKey, TMessage> : IHubGrain<TKey, TMessage, TMessage>
{
Task Foo(TKey key, TMessage message, int x);
Task<int> GetX();
}
public interface IEchoGenericChainGrain<T> : IGrainWithIntegerKey
{
Task<T> Echo(T item);
Task<T> Echo2(T item);
Task<T> Echo3(T item);
Task<T> Echo4(T item);
Task<T> Echo5(T item);
Task<T> Echo6(T item);
}
public interface INonGenericBase : IGrainWithGuidKey
{
Task Ping();
}
public interface IGeneric1Argument<T> : IGrainWithGuidKey
{
Task<T> Ping(T t);
}
public interface IGeneric2Arguments<T, U> : IGrainWithIntegerKey
{
Task<Tuple<T, U>> Ping(T t, U u);
}
public interface IDbGrain<T> : IGrainWithIntegerKey
{
Task SetValue(T value);
Task<T> GetValue();
}
public interface IGenericPingSelf<T> : IGrainWithGuidKey
{
Task<T> Ping(T t);
Task<T> PingSelf(T t);
Task<T> PingOther(IGenericPingSelf<T> target, T t);
Task<T> PingSelfThroughOther(IGenericPingSelf<T> target, T t);
Task<T> GetLastValue();
Task ScheduleDelayedPing(IGenericPingSelf<T> target, T t, TimeSpan delay);
Task ScheduleDelayedPingToSelfAndDeactivate(IGenericPingSelf<T> target, T t, TimeSpan delay);
}
public interface ILongRunningTaskGrain<T> : IGrainWithGuidKey
{
Task<string> GetRuntimeInstanceId();
Task LongWait(GrainCancellationToken tc, TimeSpan delay);
Task<T> LongRunningTask(T t, TimeSpan delay);
Task<T> CallOtherLongRunningTask(ILongRunningTaskGrain<T> target, T t, TimeSpan delay);
Task CallOtherLongRunningTask(ILongRunningTaskGrain<T> target, GrainCancellationToken tc, TimeSpan delay);
Task CallOtherLongRunningTaskWithLocalToken(ILongRunningTaskGrain<T> target, TimeSpan delay,
TimeSpan delayBeforeCancel);
Task<bool> CancellationTokenCallbackResolve(GrainCancellationToken tc);
Task<bool> CallOtherCancellationTokenCallbackResolve(ILongRunningTaskGrain<T> target);
Task CancellationTokenCallbackThrow(GrainCancellationToken tc);
}
public interface IGenericGrainWithConstraints<A, B, C> : IGrainWithStringKey
where A : ICollection<B>, new() where B : struct where C : class
{
Task<int> GetCount();
Task Add(B item);
Task<C> RoundTrip(C value);
}
public interface INonGenericCastableGrain : IGrainWithGuidKey
{
Task DoSomething();
}
public interface IGenericCastableGrain<T> : IGrainWithGuidKey
{ }
public interface IGrainSayingHello : IGrainWithGuidKey
{
Task<string> Hello();
}
public interface ISomeGenericGrain<T> : IGrainSayingHello
{ }
public interface INonGenericCastGrain : IGrainSayingHello
{ }
public interface IIndependentlyConcretizedGrain : ISomeGenericGrain<string>
{ }
public interface IIndependentlyConcretizedGenericGrain<T> : ISomeGenericGrain<T>
{ }
namespace Generic.EdgeCases
{
public interface IBasicGrain : IGrainWithGuidKey
{
Task<string> Hello();
Task<string[]> ConcreteGenArgTypeNames();
}
public interface IGrainWithTwoGenArgs<T1, T2> : IBasicGrain
{ }
public interface IGrainWithThreeGenArgs<T1, T2, T3> : IBasicGrain
{ }
public interface IGrainReceivingRepeatedGenArgs<T1, T2> : IBasicGrain
{ }
public interface IPartiallySpecifyingInterface<T> : IGrainWithTwoGenArgs<T, int>
{ }
public interface IReceivingRepeatedGenArgsAmongstOthers<T1, T2, T3> : IBasicGrain
{ }
public interface IReceivingRepeatedGenArgsFromOtherInterface<T1, T2, T3> : IBasicGrain
{ }
public interface ISpecifyingGenArgsRepeatedlyToParentInterface<T> : IReceivingRepeatedGenArgsFromOtherInterface<T, T, T>
{ }
public interface IReceivingRearrangedGenArgs<T1, T2> : IBasicGrain
{ }
public interface IReceivingRearrangedGenArgsViaCast<T1, T2> : IBasicGrain
{ }
public interface ISpecifyingRearrangedGenArgsToParentInterface<T1, T2> : IReceivingRearrangedGenArgsViaCast<T2, T1>
{ }
public interface IArbitraryInterface<T1, T2> : IBasicGrain
{ }
public interface IInterfaceUnrelatedToConcreteGenArgs<T> : IBasicGrain
{ }
public interface IInterfaceTakingFurtherSpecializedGenArg<T> : IBasicGrain
{ }
public interface IAnotherReceivingFurtherSpecializedGenArg<T> : IBasicGrain
{ }
public interface IYetOneMoreReceivingFurtherSpecializedGenArg<T> : IBasicGrain
{ }
}
}
| |
using System.Collections;
using Anycmd.Xacml.Policy.TargetItems;
using pol = Anycmd.Xacml.Policy;
namespace Anycmd.Xacml.ControlCenter.CustomControls
{
/// <summary>
/// Summary description for PolicySet.
/// </summary>
public class TargetItem : BaseControl
{
private TargetItemBaseReadWrite _targetItem;
private System.Windows.Forms.ListBox lstMatch;
private System.Windows.Forms.Button btnDown;
private System.Windows.Forms.Button btnUp;
private System.Windows.Forms.Button btnRemove;
private System.Windows.Forms.Button btnAdd;
private System.Windows.Forms.GroupBox grpTargetItems;
private System.Windows.Forms.Panel mainPanel;
private Hashtable _list = new Hashtable();
private System.Windows.Forms.Button btnApply;
private int index = -1;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
/// <summary>
///
/// </summary>
/// <param name="targetItem"></param>
public TargetItem(TargetItemBaseReadWrite targetItem)
{
// This call is required by the Windows.Forms Form Designer.
InitializeComponent();
LoadingData = true;
_targetItem = targetItem;
lstMatch.DisplayMember = "MatchId";
foreach (TargetMatchBaseReadWrite match in targetItem.Match)
{
lstMatch.Items.Add(match);
}
if (lstMatch.Items.Count != 0)
{
lstMatch.SelectedIndex = 0;
}
LoadingData = false;
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.lstMatch = new System.Windows.Forms.ListBox();
this.btnDown = new System.Windows.Forms.Button();
this.btnUp = new System.Windows.Forms.Button();
this.btnRemove = new System.Windows.Forms.Button();
this.btnAdd = new System.Windows.Forms.Button();
this.grpTargetItems = new System.Windows.Forms.GroupBox();
this.mainPanel = new System.Windows.Forms.Panel();
this.btnApply = new System.Windows.Forms.Button();
this.grpTargetItems.SuspendLayout();
this.SuspendLayout();
//
// lstMatch
//
this.lstMatch.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.lstMatch.Location = new System.Drawing.Point(8, 16);
this.lstMatch.Name = "lstMatch";
this.lstMatch.Size = new System.Drawing.Size(472, 134);
this.lstMatch.TabIndex = 5;
this.lstMatch.SelectedIndexChanged += new System.EventHandler(this.lstMatch_SelectedIndexChanged);
//
// btnDown
//
this.btnDown.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.btnDown.Location = new System.Drawing.Point(488, 112);
this.btnDown.Name = "btnDown";
this.btnDown.TabIndex = 4;
this.btnDown.Text = "Down";
//
// btnUp
//
this.btnUp.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.btnUp.Location = new System.Drawing.Point(488, 80);
this.btnUp.Name = "btnUp";
this.btnUp.TabIndex = 3;
this.btnUp.Text = "Up";
//
// btnRemove
//
this.btnRemove.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.btnRemove.Location = new System.Drawing.Point(488, 48);
this.btnRemove.Name = "btnRemove";
this.btnRemove.TabIndex = 2;
this.btnRemove.Text = "Remove";
this.btnRemove.Click += new System.EventHandler(this.btnRemove_Click);
//
// btnAdd
//
this.btnAdd.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.btnAdd.Location = new System.Drawing.Point(488, 16);
this.btnAdd.Name = "btnAdd";
this.btnAdd.TabIndex = 1;
this.btnAdd.Text = "Add";
this.btnAdd.Click += new System.EventHandler(this.btnAdd_Click);
//
// grpTargetItems
//
this.grpTargetItems.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.grpTargetItems.Controls.Add(this.lstMatch);
this.grpTargetItems.Controls.Add(this.btnDown);
this.grpTargetItems.Controls.Add(this.btnUp);
this.grpTargetItems.Controls.Add(this.btnRemove);
this.grpTargetItems.Controls.Add(this.btnAdd);
this.grpTargetItems.Location = new System.Drawing.Point(8, 8);
this.grpTargetItems.Name = "grpTargetItems";
this.grpTargetItems.Size = new System.Drawing.Size(576, 160);
this.grpTargetItems.TabIndex = 2;
this.grpTargetItems.TabStop = false;
this.grpTargetItems.Text = "Matches";
//
// mainPanel
//
this.mainPanel.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.mainPanel.Location = new System.Drawing.Point(8, 176);
this.mainPanel.Name = "mainPanel";
this.mainPanel.Size = new System.Drawing.Size(576, 352);
this.mainPanel.TabIndex = 3;
//
// button1
//
this.btnApply.Location = new System.Drawing.Point(264, 552);
this.btnApply.Name = "btnApply";
this.btnApply.TabIndex = 4;
this.btnApply.Text = "Apply";
this.btnApply.Click += new System.EventHandler(this.button1_Click);
//
// TargetItem
//
this.Controls.Add(this.btnApply);
this.Controls.Add(this.mainPanel);
this.Controls.Add(this.grpTargetItems);
this.Name = "TargetItem";
this.Size = new System.Drawing.Size(592, 584);
this.grpTargetItems.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void lstMatch_SelectedIndexChanged(object sender, System.EventArgs e)
{
if (lstMatch.SelectedItem != null)
{
if (index != -1 && index != lstMatch.SelectedIndex)
{
TargetMatchBaseReadWrite indexMatch = lstMatch.Items[index] as TargetMatchBaseReadWrite;
lstMatch.Items.RemoveAt(index);
lstMatch.Items.Insert(index, indexMatch);
}
TargetMatchBaseReadWrite match = lstMatch.SelectedItem as TargetMatchBaseReadWrite;
index = lstMatch.SelectedIndex;
try
{
LoadingData = true;
Match matchControl = _list[lstMatch.SelectedIndex] as Match;
if (matchControl == null)
{
matchControl = new Match(_targetItem, match, lstMatch.SelectedIndex);
_list[lstMatch.SelectedIndex] = matchControl;
}
mainPanel.Controls.Clear();
mainPanel.Controls.Add(matchControl);
}
finally
{
LoadingData = false;
}
}
}
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnAdd_Click(object sender, System.EventArgs e)
{
TargetMatchBaseReadWrite targetMatch = null;
if (_targetItem is ActionElementReadWrite)
targetMatch = new ActionMatchElementReadWrite(
Consts.Schema1.InternalFunctions.StringEqual,
new pol.AttributeValueElementReadWrite(Consts.Schema1.InternalDataTypes.XsdString, "Somebody", Xacml.XacmlVersion.Version11), //TODO: check version
new ActionAttributeDesignatorElement(Consts.Schema1.InternalDataTypes.XsdString, false, "", "", Xacml.XacmlVersion.Version11), //TODO: check version
Xacml.XacmlVersion.Version11);
else if (_targetItem is EnvironmentElementReadWrite)
targetMatch = new EnvironmentMatchElementReadWrite(
Consts.Schema1.InternalFunctions.StringEqual,
new pol.AttributeValueElementReadWrite(Consts.Schema1.InternalDataTypes.XsdString, "Somebody", Xacml.XacmlVersion.Version11), //TODO: check version
new EnvironmentAttributeDesignatorElement(Consts.Schema1.InternalDataTypes.XsdString, false, "", "", Xacml.XacmlVersion.Version11), //TODO: check version
Xacml.XacmlVersion.Version11);
else if (_targetItem is ResourceElementReadWrite)
targetMatch = new ResourceMatchElementReadWrite(
Consts.Schema1.InternalFunctions.StringEqual,
new pol.AttributeValueElementReadWrite(Consts.Schema1.InternalDataTypes.XsdString, "Somebody", Xacml.XacmlVersion.Version11), //TODO: check version
new ResourceAttributeDesignatorElement(Consts.Schema1.InternalDataTypes.XsdString, false, "", "", Xacml.XacmlVersion.Version11), //TODO: check version
Xacml.XacmlVersion.Version11);
else if (_targetItem is SubjectElementReadWrite)
targetMatch = new SubjectMatchElementReadWrite(
Consts.Schema1.InternalFunctions.StringEqual,
new pol.AttributeValueElementReadWrite(Consts.Schema1.InternalDataTypes.XsdString, "Somebody", Xacml.XacmlVersion.Version11), //TODO: check version
new SubjectAttributeDesignatorElement(Consts.Schema1.InternalDataTypes.XsdString, false, "", "", "", Xacml.XacmlVersion.Version11), //TODO: check version
Xacml.XacmlVersion.Version11);
_targetItem.Match.Add(targetMatch); //TODO: check version
try
{
LoadingData = true;
Match matchControl = new Match(_targetItem, targetMatch, lstMatch.Items.Count);
_list[lstMatch.Items.Count] = matchControl;
}
finally
{
LoadingData = false;
}
index = -1;
lstMatch.Items.Clear();
foreach (TargetMatchBaseReadWrite match in _targetItem.Match)
{
lstMatch.Items.Add(match);
}
}
private void button1_Click(object sender, System.EventArgs e)
{
LoadingData = true;
for (int index = 0; index < _list.Count; index++)
{
_targetItem.Match[index] = ((CustomControls.Match)_list[index]).MatchElement;
}
LoadingData = false;
ModifiedValue = false;
lstMatch.Items.Clear();
foreach (TargetMatchBaseReadWrite match in _targetItem.Match)
{
lstMatch.Items.Add(match);
}
mainPanel.Controls.Clear();
}
private void btnRemove_Click(object sender, System.EventArgs e)
{
LoadingData = true;
_list.Remove(lstMatch.SelectedIndex);
_targetItem.Match.RemoveAt(lstMatch.SelectedIndex);
lstMatch.Items.RemoveAt(lstMatch.SelectedIndex);
mainPanel.Controls.Clear();
LoadingData = false;
index = -1;
}
/// <summary>
///
/// </summary>
public TargetItemBaseReadWrite TargetItemBaseElement
{
get
{
if (index != -1)
{
TargetMatchBaseReadWrite indexMatch = lstMatch.Items[index] as TargetMatchBaseReadWrite;
lstMatch.Items.RemoveAt(index);
lstMatch.Items.Insert(index, indexMatch);
}
return _targetItem;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
using Windows.ApplicationModel;
using Windows.Storage;
using Windows.Storage.Streams;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
namespace ParsePushSample.Common
{
/// <summary>
/// SuspensionManager captures global session state to simplify process lifetime management
/// for an application. Note that session state will be automatically cleared under a variety
/// of conditions and should only be used to store information that would be convenient to
/// carry across sessions, but that should be discarded when an application crashes or is
/// upgraded.
/// </summary>
internal sealed class SuspensionManager
{
private static Dictionary<string, object> _sessionState = new Dictionary<string, object>();
private static List<Type> _knownTypes = new List<Type>();
private const string sessionStateFilename = "_sessionState.xml";
/// <summary>
/// Provides access to global session state for the current session. This state is
/// serialized by <see cref="SaveAsync"/> and restored by
/// <see cref="RestoreAsync"/>, so values must be serializable by
/// <see cref="DataContractSerializer"/> and should be as compact as possible. Strings
/// and other self-contained data types are strongly recommended.
/// </summary>
public static Dictionary<string, object> SessionState
{
get { return _sessionState; }
}
/// <summary>
/// List of custom types provided to the <see cref="DataContractSerializer"/> when
/// reading and writing session state. Initially empty, additional types may be
/// added to customize the serialization process.
/// </summary>
public static List<Type> KnownTypes
{
get { return _knownTypes; }
}
/// <summary>
/// Save the current <see cref="SessionState"/>. Any <see cref="Frame"/> instances
/// registered with <see cref="RegisterFrame"/> will also preserve their current
/// navigation stack, which in turn gives their active <see cref="Page"/> an opportunity
/// to save its state.
/// </summary>
/// <returns>An asynchronous task that reflects when session state has been saved.</returns>
public static async Task SaveAsync()
{
try
{
// Save the navigation state for all registered frames
foreach (var weakFrameReference in _registeredFrames)
{
Frame frame;
if (weakFrameReference.TryGetTarget(out frame))
{
SaveFrameNavigationState(frame);
}
}
// Serialize the session state synchronously to avoid asynchronous access to shared
// state
MemoryStream sessionData = new MemoryStream();
DataContractSerializer serializer = new DataContractSerializer(typeof(Dictionary<string, object>), _knownTypes);
serializer.WriteObject(sessionData, _sessionState);
// Get an output stream for the SessionState file and write the state asynchronously
StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync(sessionStateFilename, CreationCollisionOption.ReplaceExisting);
using (Stream fileStream = await file.OpenStreamForWriteAsync())
{
sessionData.Seek(0, SeekOrigin.Begin);
await sessionData.CopyToAsync(fileStream);
await fileStream.FlushAsync();
}
}
catch (Exception e)
{
throw new SuspensionManagerException(e);
}
}
/// <summary>
/// Restores previously saved <see cref="SessionState"/>. Any <see cref="Frame"/> instances
/// registered with <see cref="RegisterFrame"/> will also restore their prior navigation
/// state, which in turn gives their active <see cref="Page"/> an opportunity restore its
/// state.
/// </summary>
/// <returns>An asynchronous task that reflects when session state has been read. The
/// content of <see cref="SessionState"/> should not be relied upon until this task
/// completes.</returns>
public static async Task RestoreAsync()
{
_sessionState = new Dictionary<String, Object>();
try
{
// Get the input stream for the SessionState file
StorageFile file = await ApplicationData.Current.LocalFolder.GetFileAsync(sessionStateFilename);
using (IInputStream inStream = await file.OpenSequentialReadAsync())
{
// Deserialize the Session State
DataContractSerializer serializer = new DataContractSerializer(typeof(Dictionary<string, object>), _knownTypes);
_sessionState = (Dictionary<string, object>)serializer.ReadObject(inStream.AsStreamForRead());
}
// Restore any registered frames to their saved state
foreach (var weakFrameReference in _registeredFrames)
{
Frame frame;
if (weakFrameReference.TryGetTarget(out frame))
{
frame.ClearValue(FrameSessionStateProperty);
RestoreFrameNavigationState(frame);
}
}
}
catch (Exception e)
{
throw new SuspensionManagerException(e);
}
}
private static DependencyProperty FrameSessionStateKeyProperty =
DependencyProperty.RegisterAttached("_FrameSessionStateKey", typeof(String), typeof(SuspensionManager), null);
private static DependencyProperty FrameSessionStateProperty =
DependencyProperty.RegisterAttached("_FrameSessionState", typeof(Dictionary<String, Object>), typeof(SuspensionManager), null);
private static List<WeakReference<Frame>> _registeredFrames = new List<WeakReference<Frame>>();
/// <summary>
/// Registers a <see cref="Frame"/> instance to allow its navigation history to be saved to
/// and restored from <see cref="SessionState"/>. Frames should be registered once
/// immediately after creation if they will participate in session state management. Upon
/// registration if state has already been restored for the specified key
/// the navigation history will immediately be restored. Subsequent invocations of
/// <see cref="RestoreAsync"/> will also restore navigation history.
/// </summary>
/// <param name="frame">An instance whose navigation history should be managed by
/// <see cref="SuspensionManager"/></param>
/// <param name="sessionStateKey">A unique key into <see cref="SessionState"/> used to
/// store navigation-related information.</param>
public static void RegisterFrame(Frame frame, String sessionStateKey)
{
if (frame.GetValue(FrameSessionStateKeyProperty) != null)
{
throw new InvalidOperationException("Frames can only be registered to one session state key");
}
if (frame.GetValue(FrameSessionStateProperty) != null)
{
throw new InvalidOperationException("Frames must be either be registered before accessing frame session state, or not registered at all");
}
// Use a dependency property to associate the session key with a frame, and keep a list of frames whose
// navigation state should be managed
frame.SetValue(FrameSessionStateKeyProperty, sessionStateKey);
_registeredFrames.Add(new WeakReference<Frame>(frame));
// Check to see if navigation state can be restored
RestoreFrameNavigationState(frame);
}
/// <summary>
/// Disassociates a <see cref="Frame"/> previously registered by <see cref="RegisterFrame"/>
/// from <see cref="SessionState"/>. Any navigation state previously captured will be
/// removed.
/// </summary>
/// <param name="frame">An instance whose navigation history should no longer be
/// managed.</param>
public static void UnregisterFrame(Frame frame)
{
// Remove session state and remove the frame from the list of frames whose navigation
// state will be saved (along with any weak references that are no longer reachable)
SessionState.Remove((String)frame.GetValue(FrameSessionStateKeyProperty));
_registeredFrames.RemoveAll((weakFrameReference) =>
{
Frame testFrame;
return !weakFrameReference.TryGetTarget(out testFrame) || testFrame == frame;
});
}
/// <summary>
/// Provides storage for session state associated with the specified <see cref="Frame"/>.
/// Frames that have been previously registered with <see cref="RegisterFrame"/> have
/// their session state saved and restored automatically as a part of the global
/// <see cref="SessionState"/>. Frames that are not registered have transient state
/// that can still be useful when restoring pages that have been discarded from the
/// navigation cache.
/// </summary>
/// <remarks>Apps may choose to rely on <see cref="LayoutAwarePage"/> to manage
/// page-specific state instead of working with frame session state directly.</remarks>
/// <param name="frame">The instance for which session state is desired.</param>
/// <returns>A collection of state subject to the same serialization mechanism as
/// <see cref="SessionState"/>.</returns>
public static Dictionary<String, Object> SessionStateForFrame(Frame frame)
{
var frameState = (Dictionary<String, Object>)frame.GetValue(FrameSessionStateProperty);
if (frameState == null)
{
var frameSessionKey = (String)frame.GetValue(FrameSessionStateKeyProperty);
if (frameSessionKey != null)
{
// Registered frames reflect the corresponding session state
if (!_sessionState.ContainsKey(frameSessionKey))
{
_sessionState[frameSessionKey] = new Dictionary<String, Object>();
}
frameState = (Dictionary<String, Object>)_sessionState[frameSessionKey];
}
else
{
// Frames that aren't registered have transient state
frameState = new Dictionary<String, Object>();
}
frame.SetValue(FrameSessionStateProperty, frameState);
}
return frameState;
}
private static void RestoreFrameNavigationState(Frame frame)
{
var frameState = SessionStateForFrame(frame);
if (frameState.ContainsKey("Navigation"))
{
frame.SetNavigationState((String)frameState["Navigation"]);
}
}
private static void SaveFrameNavigationState(Frame frame)
{
var frameState = SessionStateForFrame(frame);
frameState["Navigation"] = frame.GetNavigationState();
}
}
public class SuspensionManagerException : Exception
{
public SuspensionManagerException()
{
}
public SuspensionManagerException(Exception e) : base("SuspensionManager failed", e)
{
}
}
}
| |
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
#pragma warning disable 618
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Tests.TestObjects;
using Newtonsoft.Json.Tests.TestObjects.Organization;
using Newtonsoft.Json.Utilities;
#if DNXCORE50
using Xunit;
using Test = Xunit.FactAttribute;
using Assert = Newtonsoft.Json.Tests.XUnitAssert;
#else
using NUnit.Framework;
#endif
using Newtonsoft.Json.Schema;
using System.IO;
using Newtonsoft.Json.Linq;
using System.Text;
using Extensions = Newtonsoft.Json.Schema.Extensions;
#if NET20
using Newtonsoft.Json.Utilities.LinqBridge;
#else
using System.Linq;
#endif
using Newtonsoft.Json.Tests.Serialization;
namespace Newtonsoft.Json.Tests.Schema
{
[TestFixture]
public class JsonSchemaGeneratorTests : TestFixtureBase
{
[Test]
public void Generate_GenericDictionary()
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
JsonSchema schema = generator.Generate(typeof(Dictionary<string, List<string>>));
string json = schema.ToString();
StringAssert.AreEqual(@"{
""type"": ""object"",
""additionalProperties"": {
""type"": [
""array"",
""null""
],
""items"": {
""type"": [
""string"",
""null""
]
}
}
}", json);
Dictionary<string, List<string>> value = new Dictionary<string, List<string>>
{
{ "HasValue", new List<string>() { "first", "second", null } },
{ "NoValue", null }
};
string valueJson = JsonConvert.SerializeObject(value, Formatting.Indented);
JObject o = JObject.Parse(valueJson);
Assert.IsTrue(o.IsValid(schema));
}
#if !(PORTABLE || DNXCORE50 || PORTABLE40)
[Test]
public void Generate_DefaultValueAttributeTestClass()
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
JsonSchema schema = generator.Generate(typeof(DefaultValueAttributeTestClass));
string json = schema.ToString();
StringAssert.AreEqual(@"{
""description"": ""DefaultValueAttributeTestClass description!"",
""type"": ""object"",
""additionalProperties"": false,
""properties"": {
""TestField1"": {
""required"": true,
""type"": ""integer"",
""default"": 21
},
""TestProperty1"": {
""required"": true,
""type"": [
""string"",
""null""
],
""default"": ""TestProperty1Value""
}
}
}", json);
}
#endif
[Test]
public void Generate_Person()
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
JsonSchema schema = generator.Generate(typeof(Person));
string json = schema.ToString();
StringAssert.AreEqual(@"{
""id"": ""Person"",
""title"": ""Title!"",
""description"": ""JsonObjectAttribute description!"",
""type"": ""object"",
""properties"": {
""Name"": {
""required"": true,
""type"": [
""string"",
""null""
]
},
""BirthDate"": {
""required"": true,
""type"": ""string""
},
""LastModified"": {
""required"": true,
""type"": ""string""
}
}
}", json);
}
[Test]
public void Generate_UserNullable()
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
JsonSchema schema = generator.Generate(typeof(UserNullable));
string json = schema.ToString();
StringAssert.AreEqual(@"{
""type"": ""object"",
""properties"": {
""Id"": {
""required"": true,
""type"": ""string""
},
""FName"": {
""required"": true,
""type"": [
""string"",
""null""
]
},
""LName"": {
""required"": true,
""type"": [
""string"",
""null""
]
},
""RoleId"": {
""required"": true,
""type"": ""integer""
},
""NullableRoleId"": {
""required"": true,
""type"": [
""integer"",
""null""
]
},
""NullRoleId"": {
""required"": true,
""type"": [
""integer"",
""null""
]
},
""Active"": {
""required"": true,
""type"": [
""boolean"",
""null""
]
}
}
}", json);
}
[Test]
public void Generate_RequiredMembersClass()
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
JsonSchema schema = generator.Generate(typeof(RequiredMembersClass));
Assert.AreEqual(JsonSchemaType.String, schema.Properties["FirstName"].Type);
Assert.AreEqual(JsonSchemaType.String | JsonSchemaType.Null, schema.Properties["MiddleName"].Type);
Assert.AreEqual(JsonSchemaType.String | JsonSchemaType.Null, schema.Properties["LastName"].Type);
Assert.AreEqual(JsonSchemaType.String, schema.Properties["BirthDate"].Type);
}
[Test]
public void Generate_Store()
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
JsonSchema schema = generator.Generate(typeof(Store));
Assert.AreEqual(11, schema.Properties.Count);
JsonSchema productArraySchema = schema.Properties["product"];
JsonSchema productSchema = productArraySchema.Items[0];
Assert.AreEqual(4, productSchema.Properties.Count);
}
[Test]
public void MissingSchemaIdHandlingTest()
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
JsonSchema schema = generator.Generate(typeof(Store));
Assert.AreEqual(null, schema.Id);
generator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseTypeName;
schema = generator.Generate(typeof(Store));
Assert.AreEqual(typeof(Store).FullName, schema.Id);
generator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseAssemblyQualifiedName;
schema = generator.Generate(typeof(Store));
Assert.AreEqual(typeof(Store).AssemblyQualifiedName, schema.Id);
}
[Test]
public void CircularReferenceError()
{
ExceptionAssert.Throws<Exception>(() =>
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
generator.Generate(typeof(CircularReferenceClass));
}, @"Unresolved circular reference for type 'Newtonsoft.Json.Tests.TestObjects.CircularReferenceClass'. Explicitly define an Id for the type using a JsonObject/JsonArray attribute or automatically generate a type Id using the UndefinedSchemaIdHandling property.");
}
[Test]
public void CircularReferenceWithTypeNameId()
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
generator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseTypeName;
JsonSchema schema = generator.Generate(typeof(CircularReferenceClass), true);
Assert.AreEqual(JsonSchemaType.String, schema.Properties["Name"].Type);
Assert.AreEqual(typeof(CircularReferenceClass).FullName, schema.Id);
Assert.AreEqual(JsonSchemaType.Object | JsonSchemaType.Null, schema.Properties["Child"].Type);
Assert.AreEqual(schema, schema.Properties["Child"]);
}
[Test]
public void CircularReferenceWithExplicitId()
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
JsonSchema schema = generator.Generate(typeof(CircularReferenceWithIdClass));
Assert.AreEqual(JsonSchemaType.String | JsonSchemaType.Null, schema.Properties["Name"].Type);
Assert.AreEqual("MyExplicitId", schema.Id);
Assert.AreEqual(JsonSchemaType.Object | JsonSchemaType.Null, schema.Properties["Child"].Type);
Assert.AreEqual(schema, schema.Properties["Child"]);
}
[Test]
public void GenerateSchemaForType()
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
generator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseTypeName;
JsonSchema schema = generator.Generate(typeof(Type));
Assert.AreEqual(JsonSchemaType.String, schema.Type);
string json = JsonConvert.SerializeObject(typeof(Version), Formatting.Indented);
JValue v = new JValue(json);
Assert.IsTrue(v.IsValid(schema));
}
#if !(PORTABLE || DNXCORE50 || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0
[Test]
public void GenerateSchemaForISerializable()
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
generator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseTypeName;
JsonSchema schema = generator.Generate(typeof(ISerializableTestObject));
Assert.AreEqual(JsonSchemaType.Object, schema.Type);
Assert.AreEqual(true, schema.AllowAdditionalProperties);
Assert.AreEqual(null, schema.Properties);
}
#endif
#if !(PORTABLE || DNXCORE50 || PORTABLE40)
[Test]
public void GenerateSchemaForDBNull()
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
generator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseTypeName;
JsonSchema schema = generator.Generate(typeof(DBNull));
Assert.AreEqual(JsonSchemaType.Null, schema.Type);
}
#endif
#if !(PORTABLE || DNXCORE50 || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0
public class CustomDirectoryInfoMapper : DefaultContractResolver
{
public CustomDirectoryInfoMapper()
{
}
protected override JsonContract CreateContract(Type objectType)
{
if (objectType == typeof(DirectoryInfo))
{
return base.CreateObjectContract(objectType);
}
return base.CreateContract(objectType);
}
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
IList<JsonProperty> properties = base.CreateProperties(type, memberSerialization);
JsonPropertyCollection c = new JsonPropertyCollection(type);
c.AddRange(properties.Where(m => m.PropertyName != "Root"));
return c;
}
}
#endif
[Test]
public void GenerateSchemaCamelCase()
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
generator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseTypeName;
generator.ContractResolver = new CamelCasePropertyNamesContractResolver()
{
#if !(PORTABLE || DNXCORE50 || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0
IgnoreSerializableAttribute = true
#endif
};
JsonSchema schema = generator.Generate(typeof(Version), true);
string json = schema.ToString();
StringAssert.AreEqual(@"{
""id"": ""System.Version"",
""type"": [
""object"",
""null""
],
""additionalProperties"": false,
""properties"": {
""major"": {
""required"": true,
""type"": ""integer""
},
""minor"": {
""required"": true,
""type"": ""integer""
},
""build"": {
""required"": true,
""type"": ""integer""
},
""revision"": {
""required"": true,
""type"": ""integer""
},
""majorRevision"": {
""required"": true,
""type"": ""integer""
},
""minorRevision"": {
""required"": true,
""type"": ""integer""
}
}
}", json);
}
#if !(PORTABLE || DNXCORE50 || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0
[Test]
public void GenerateSchemaSerializable()
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
DefaultContractResolver contractResolver = new DefaultContractResolver
{
IgnoreSerializableAttribute = false
};
generator.ContractResolver = contractResolver;
generator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseTypeName;
JsonSchema schema = generator.Generate(typeof(SerializableTestObject), true);
string json = schema.ToString();
StringAssert.AreEqual(@"{
""id"": ""Newtonsoft.Json.Tests.Schema.SerializableTestObject"",
""type"": [
""object"",
""null""
],
""additionalProperties"": false,
""properties"": {
""_name"": {
""required"": true,
""type"": [
""string"",
""null""
]
}
}
}", json);
JTokenWriter jsonWriter = new JTokenWriter();
JsonSerializer serializer = new JsonSerializer();
serializer.ContractResolver = contractResolver;
serializer.Serialize(jsonWriter, new SerializableTestObject
{
Name = "Name!"
});
List<string> errors = new List<string>();
jsonWriter.Token.Validate(schema, (sender, args) => errors.Add(args.Message));
Assert.AreEqual(0, errors.Count);
StringAssert.AreEqual(@"{
""_name"": ""Name!""
}", jsonWriter.Token.ToString());
SerializableTestObject c = jsonWriter.Token.ToObject<SerializableTestObject>(serializer);
Assert.AreEqual("Name!", c.Name);
}
#endif
public enum SortTypeFlag
{
No = 0,
Asc = 1,
Desc = -1
}
public class X
{
public SortTypeFlag x;
}
[Test]
public void GenerateSchemaWithNegativeEnum()
{
JsonSchemaGenerator jsonSchemaGenerator = new JsonSchemaGenerator();
JsonSchema schema = jsonSchemaGenerator.Generate(typeof(X));
string json = schema.ToString();
StringAssert.AreEqual(@"{
""type"": ""object"",
""properties"": {
""x"": {
""required"": true,
""type"": ""integer"",
""enum"": [
0,
1,
-1
]
}
}
}", json);
}
[Test]
public void CircularCollectionReferences()
{
Type type = typeof(Workspace);
JsonSchemaGenerator jsonSchemaGenerator = new JsonSchemaGenerator();
jsonSchemaGenerator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseTypeName;
JsonSchema jsonSchema = jsonSchemaGenerator.Generate(type);
// should succeed
Assert.IsNotNull(jsonSchema);
}
[Test]
public void CircularReferenceWithMixedRequires()
{
JsonSchemaGenerator jsonSchemaGenerator = new JsonSchemaGenerator();
jsonSchemaGenerator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseTypeName;
JsonSchema jsonSchema = jsonSchemaGenerator.Generate(typeof(CircularReferenceClass));
string json = jsonSchema.ToString();
StringAssert.AreEqual(@"{
""id"": ""Newtonsoft.Json.Tests.TestObjects.CircularReferenceClass"",
""type"": [
""object"",
""null""
],
""properties"": {
""Name"": {
""required"": true,
""type"": ""string""
},
""Child"": {
""$ref"": ""Newtonsoft.Json.Tests.TestObjects.CircularReferenceClass""
}
}
}", json);
}
[Test]
public void JsonPropertyWithHandlingValues()
{
JsonSchemaGenerator jsonSchemaGenerator = new JsonSchemaGenerator();
jsonSchemaGenerator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseTypeName;
JsonSchema jsonSchema = jsonSchemaGenerator.Generate(typeof(JsonPropertyWithHandlingValues));
string json = jsonSchema.ToString();
StringAssert.AreEqual(@"{
""id"": ""Newtonsoft.Json.Tests.TestObjects.JsonPropertyWithHandlingValues"",
""required"": true,
""type"": [
""object"",
""null""
],
""properties"": {
""DefaultValueHandlingIgnoreProperty"": {
""type"": [
""string"",
""null""
],
""default"": ""Default!""
},
""DefaultValueHandlingIncludeProperty"": {
""required"": true,
""type"": [
""string"",
""null""
],
""default"": ""Default!""
},
""DefaultValueHandlingPopulateProperty"": {
""required"": true,
""type"": [
""string"",
""null""
],
""default"": ""Default!""
},
""DefaultValueHandlingIgnoreAndPopulateProperty"": {
""type"": [
""string"",
""null""
],
""default"": ""Default!""
},
""NullValueHandlingIgnoreProperty"": {
""type"": [
""string"",
""null""
]
},
""NullValueHandlingIncludeProperty"": {
""required"": true,
""type"": [
""string"",
""null""
]
},
""ReferenceLoopHandlingErrorProperty"": {
""$ref"": ""Newtonsoft.Json.Tests.TestObjects.JsonPropertyWithHandlingValues""
},
""ReferenceLoopHandlingIgnoreProperty"": {
""$ref"": ""Newtonsoft.Json.Tests.TestObjects.JsonPropertyWithHandlingValues""
},
""ReferenceLoopHandlingSerializeProperty"": {
""$ref"": ""Newtonsoft.Json.Tests.TestObjects.JsonPropertyWithHandlingValues""
}
}
}", json);
}
[Test]
public void GenerateForNullableInt32()
{
JsonSchemaGenerator jsonSchemaGenerator = new JsonSchemaGenerator();
JsonSchema jsonSchema = jsonSchemaGenerator.Generate(typeof(NullableInt32TestClass));
string json = jsonSchema.ToString();
StringAssert.AreEqual(@"{
""type"": ""object"",
""properties"": {
""Value"": {
""required"": true,
""type"": [
""integer"",
""null""
]
}
}
}", json);
}
[JsonConverter(typeof(StringEnumConverter))]
public enum SortTypeFlagAsString
{
No = 0,
Asc = 1,
Desc = -1
}
public class Y
{
public SortTypeFlagAsString y;
}
}
public class NullableInt32TestClass
{
public int? Value { get; set; }
}
public class DMDSLBase
{
public String Comment;
}
public class Workspace : DMDSLBase
{
public ControlFlowItemCollection Jobs = new ControlFlowItemCollection();
}
public class ControlFlowItemBase : DMDSLBase
{
public String Name;
}
public class ControlFlowItem : ControlFlowItemBase //A Job
{
public TaskCollection Tasks = new TaskCollection();
public ContainerCollection Containers = new ContainerCollection();
}
public class ControlFlowItemCollection : List<ControlFlowItem>
{
}
public class Task : ControlFlowItemBase
{
public DataFlowTaskCollection DataFlowTasks = new DataFlowTaskCollection();
public BulkInsertTaskCollection BulkInsertTask = new BulkInsertTaskCollection();
}
public class TaskCollection : List<Task>
{
}
public class Container : ControlFlowItemBase
{
public ControlFlowItemCollection ContainerJobs = new ControlFlowItemCollection();
}
public class ContainerCollection : List<Container>
{
}
public class DataFlowTask_DSL : ControlFlowItemBase
{
}
public class DataFlowTaskCollection : List<DataFlowTask_DSL>
{
}
public class SequenceContainer_DSL : Container
{
}
public class BulkInsertTaskCollection : List<BulkInsertTask_DSL>
{
}
public class BulkInsertTask_DSL
{
}
#if !(PORTABLE || DNXCORE50 || PORTABLE40) || NETSTANDARD1_3 || NETSTANDARD2_0
[Serializable]
public sealed class SerializableTestObject
{
private string _name;
public string Name
{
get { return _name; }
set { _name = value; }
}
}
#endif
}
#pragma warning restore 618
| |
// Copyright (c) 2012, Miron Brezuleanu
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Collections.Generic;
using System.IO;
using Shovel.Vm.Types;
using System.Text;
using System.Linq;
namespace Shovel.Serialization
{
internal class VmStateSerializer
{
#region Inner Types
enum Types
{
ShortString,
String,
ShortInteger,
Integer,
LongInteger,
Double,
ShortComposite,
Composite,
}
enum ObjectTypes
{
ShovelValueList,
StringArray,
ShovelValueArray,
//List,
Hash,
Callable,
ReturnAddress,
NamedBlock,
Environment,
EnvFrame,
Struct,
StructInstance
}
class Composite
{
internal ObjectTypes Kind { get; set; }
internal int[] Elements { get; set; }
}
#endregion
#region Private Storage
Dictionary<object, int> hash;
List<object> array;
#endregion
#region Public API
internal VmStateSerializer ()
{
this.hash = new Dictionary<object, int> ();
this.array = new List<object> ();
}
internal void WriteToStream (Stream s)
{
var bs = new BinaryWriter (s);
bs.Write ((int)this.array.Count);
foreach (var obj in this.array) {
if (obj is string) {
WriteString (bs, (string)obj);
} else if (obj is long) {
WriteLong (bs, (long)obj);
} else if (obj is int) {
WriteLong (bs, (int)obj);
} else if (obj is Double) {
WriteDouble (bs, (double)obj);
} else if (obj is Composite) {
WriteComposite (bs, (Composite)obj);
} else {
Shovel.Utils.Panic ();
}
}
bs.Flush ();
}
internal int Serialize (object obj)
{
if (obj == null) {
return SerializeNull ();
} else if (this.hash.ContainsKey (obj)) {
return this.hash [obj];
} else if (obj is Value) {
return SerializeShovelValue ((Value)obj, obj);
} else if (obj is string[]) {
return SerializeStringArray ((string[])obj);
} else if (obj is Value[]) {
return SerializeShovelValueArray ((Value[])obj);
} else if (obj is VmEnvironment) {
return SerializeEnvironment ((VmEnvironment)obj, obj);
} else if (obj is VmEnvFrame) {
return SerializeEnvFrame ((VmEnvFrame)obj, obj);
} else if (obj is Struct) {
return SerializeStruct ((Struct)obj, obj);
} else if (obj is StructInstance) {
return SerializeStructInstance ((StructInstance)obj, obj);
}
Shovel.Utils.Panic ();
throw new InvalidOperationException ();
}
internal static MemoryStream SerializeVmState (Vm.Vm vm)
{
return Utils.SerializeWithMd5CheckSum (str => {
vm.SerializeState (str);
});
}
internal void Deserialize (Stream s, int version, Action<Func<int, object>> action)
{
var length = Utils.ReadInt (s);
var serArray = new object[length];
var objects = new object[length];
var br = new BinaryReader(s);
for (var i = 0; i < length; i++) {
serArray [i] = ReadValue (br);
}
Func<int, object> reader = null;
reader = (index) => {
if (index < 0) {
if (index == -1) {
return null;
} else if (index == -2) {
return true;
} else if (index == -3) {
return false;
} else {
Shovel.Utils.Panic ();
throw new InvalidOperationException ();
}
}
if (objects [index] == null) {
if (serArray [index] is string || serArray [index] is long || serArray [index] is double) {
objects [index] = serArray [index];
} else if (serArray [index] is Composite) {
RebuildFromComposite (objects, index, (Composite)serArray [index], reader, version);
} else {
Shovel.Utils.Panic ();
throw new NotImplementedException ();
}
}
return objects [index];
};
action (reader);
}
#endregion
#region Private Helper Functions - Deserializer
object ReadShortString (BinaryReader br)
{
var length = br.ReadByte ();
AdjustBigBuf(length);
br.Read (bigBuf, 0, length);
return Encoding.UTF8.GetString (bigBuf, 0, length);
}
object ReadString (BinaryReader br)
{
var length = ReadInteger (br);
AdjustBigBuf(length);
br.Read (bigBuf, 0, length);
return Encoding.UTF8.GetString (bigBuf, 0, length);
}
byte[] bigBuf = new byte[1024];
short ReadShortInteger (BinaryReader br)
{
return br.ReadInt16();
}
int ReadInteger (BinaryReader br)
{
return br.ReadInt32();
}
long ReadLongInteger (BinaryReader br)
{
return br.ReadInt64();
}
double ReadDouble (BinaryReader br)
{
return br.ReadDouble();
}
void AdjustBigBuf (int lengthInBytes)
{
if (bigBuf.Length < lengthInBytes) {
bigBuf = new byte[lengthInBytes];
}
}
Composite ReadCompositeImpl (BinaryReader br, int length)
{
var result = new Composite ();
result.Kind = (ObjectTypes)br.ReadByte ();
var lengthInBytes = 4 * length;
AdjustBigBuf (lengthInBytes);
br.Read (bigBuf, 0, lengthInBytes);
result.Elements = new int[length];
Buffer.BlockCopy (bigBuf, 0, result.Elements, 0, lengthInBytes);
return result;
}
Composite ReadShortComposite (BinaryReader br)
{
var length = br.ReadByte ();
return ReadCompositeImpl (br, length);
}
Composite ReadComposite (BinaryReader br)
{
var length = ReadInteger (br);
return ReadCompositeImpl (br, length);
}
object ReadValue (BinaryReader br)
{
var type = (Types)br.ReadByte ();
switch (type) {
case Types.ShortString:
return ReadShortString (br);
case Types.String:
return ReadString (br);
case Types.ShortInteger:
return (long)ReadShortInteger (br);
case Types.Integer:
return (long)ReadInteger (br);
case Types.LongInteger:
return (long)ReadLongInteger (br);
case Types.Double:
return ReadDouble (br);
case Types.ShortComposite:
return ReadShortComposite (br);
case Types.Composite:
return ReadComposite (br);
default:
Shovel.Utils.Panic ();
throw new InvalidOperationException ();
}
}
Value RebuildShovelValue (object par)
{
if (par is long) {
return Value.MakeInt ((long)par);
} else if (par is string) {
return Value.Make ((string)par);
} else if (par is double) {
return Value.MakeFloat ((double)par);
} else if (par == null) {
return Value.Make ();
} else if (par is bool) {
return Value.Make ((bool)par);
} else if (par is ArrayInstance) {
return Value.Make ((ArrayInstance)par);
} else if (par is HashInstance) {
return Value.Make ((HashInstance)par);
} else if (par is Callable) {
return Value.Make ((Callable)par);
} else if (par is ReturnAddress) {
return Value.Make ((ReturnAddress)par);
} else if (par is NamedBlock) {
return Value.Make ((NamedBlock)par);
} else if (par is Struct) {
return Value.Make ((Struct)par);
} else if (par is StructInstance) {
return Value.Make ((StructInstance)par);
} else {
Shovel.Utils.Panic ();
throw new InvalidOperationException ();
}
}
ArrayInstance RebuildShovelValueList (
object[] objects, int index, Composite composite, Func<int, object> reader, int version)
{
var result = new ArrayInstance ();
objects [index] = result;
var length = composite.Elements.Length;
if (version > 4)
{
length -= 2;
}
for (var i = 0; i < length; i++) {
result.Add (RebuildShovelValue (reader (composite.Elements [i])));
}
if (version > 4)
{
// The indirect get/set are stored as the last elements of the array.
result.IndirectGet = RebuildShovelValue(reader(composite.Elements[length]));
result.IndirectSet = RebuildShovelValue(reader(composite.Elements[length + 1]));
}
return result;
}
string[] RebuildStringArray (
object[] objects, int index, Composite composite, Func<int, object> reader)
{
var result = new string[composite.Elements.Length];
objects [index] = result;
for (var i = 0; i < composite.Elements.Length; i++) {
result [i] = (string)reader (composite.Elements [i]);
}
return result;
}
Value[] RebuildShovelValueArray (
object[] objects, int index, Composite composite, Func<int, object> reader)
{
var result = new Value[composite.Elements.Length];
objects [index] = result;
for (var i = 0; i < composite.Elements.Length; i++) {
result [i] = RebuildShovelValue (reader (composite.Elements [i]));
}
return result;
}
HashInstance RebuildHash (
object[] objects, int index, Composite composite, Func<int, object> reader, int version)
{
var result = new HashInstance ();
objects [index] = result;
var length = composite.Elements.Length;
if (version > 4)
{
length -= 2;
}
for (var i = 0; i < length; i+=2) {
var key = RebuildShovelValue (reader (composite.Elements [i]));
var value = RebuildShovelValue (reader (composite.Elements [i + 1]));
result [key] = value;
}
if (version > 4)
{
// The indirect get/set are stored as the last elements of the hash.
result.IndirectGet = RebuildShovelValue(reader(composite.Elements[length]));
result.IndirectSet = RebuildShovelValue(reader(composite.Elements[length + 1]));
}
return result;
}
Callable RebuildCallable (
object[] objects, int index, Composite composite, Func<int, object> reader)
{
var result = new Callable ();
objects [index] = result;
result.UdpName = (string)reader (composite.Elements [0]);
result.Prim0Name = (string)reader (composite.Elements [1]);
result.Arity = (int?)(long?)reader (composite.Elements [2]);
result.ProgramCounter = (int?)(long?)reader (composite.Elements [3]);
result.Environment = (VmEnvironment)reader (composite.Elements [4]);
return result;
}
ReturnAddress RebuildReturnAddress (
object[] objects, int index, Composite composite, Func<int, object> reader)
{
var result = new ReturnAddress ();
objects [index] = result;
result.Environment = (VmEnvironment)reader (composite.Elements [0]);
result.ProgramCounter = (int)(long)reader (composite.Elements [1]);
return result;
}
NamedBlock RebuildNamedBlock (
object[] objects, int index, Composite composite, Func<int, object> reader)
{
var result = new NamedBlock ();
objects [index] = result;
result.Name = (string)reader (composite.Elements [0]);
result.BlockEnd = (int)(long)reader (composite.Elements [1]);
result.Environment = (VmEnvironment)reader (composite.Elements [2]);
return result;
}
VmEnvironment RebuildEnvironment (
object[] objects, int index, Composite composite, Func<int, object> reader)
{
var result = new VmEnvironment ();
objects [index] = result;
result.Frame = (VmEnvFrame)reader (composite.Elements [0]);
result.Next = (VmEnvironment)reader (composite.Elements [1]);
return result;
}
VmEnvFrame RebuildEnvFrame (
object[] objects, int index, Composite composite, Func<int, object> reader)
{
var result = new VmEnvFrame ();
objects [index] = result;
result.VarNames = (string[])reader (composite.Elements [0]);
result.Values = (Value[])reader (composite.Elements [1]);
result.IntroducedAtProgramCounter = (int)(long)reader (composite.Elements [2]);
return result;
}
Struct RebuildStruct (object[] objects, int index, Composite composite, Func<int, object> reader)
{
var result = new Struct ();
objects [index] = result;
result.Fields = (string[])reader (composite.Elements [0]);
return result;
}
StructInstance RebuildStructInstance (
object[] objects, int index, Composite composite, Func<int, object> reader)
{
var result = new StructInstance ();
objects [index] = result;
result.Struct = (Struct)reader (composite.Elements [0]);
result.Values = (Value[])reader (composite.Elements [1]);
return result;
}
void RebuildFromComposite (
object[] objects, int index, Composite composite, Func<int, object> reader, int version)
{
switch (composite.Kind) {
case ObjectTypes.ShovelValueList:
RebuildShovelValueList (objects, index, composite, reader, version);
break;
case ObjectTypes.StringArray:
RebuildStringArray (objects, index, composite, reader);
break;
case ObjectTypes.ShovelValueArray:
RebuildShovelValueArray (objects, index, composite, reader);
break;
case ObjectTypes.Hash:
RebuildHash (objects, index, composite, reader, version);
break;
case ObjectTypes.Callable:
RebuildCallable (objects, index, composite, reader);
break;
case ObjectTypes.ReturnAddress:
RebuildReturnAddress (objects, index, composite, reader);
break;
case ObjectTypes.NamedBlock:
RebuildNamedBlock (objects, index, composite, reader);
break;
case ObjectTypes.Environment:
RebuildEnvironment (objects, index, composite, reader);
break;
case ObjectTypes.EnvFrame:
RebuildEnvFrame (objects, index, composite, reader);
break;
case ObjectTypes.Struct:
RebuildStruct (objects, index, composite, reader);
break;
case ObjectTypes.StructInstance:
RebuildStructInstance (objects, index, composite, reader);
break;
default:
Shovel.Utils.Panic ();
break;
}
}
#endregion
#region Private Helper Functions - Serializer
int SerializeNull ()
{
return -1;
}
int SerializeBool (bool b)
{
if (b) {
return -2;
} else {
return -3;
}
}
int SerializeOne (object obj)
{
if (obj == null) {
return SerializeNull ();
}
this.array.Add (obj);
return this.array.Count - 1;
}
int SerializeOneHashed (object obj, object storeAs = null)
{
if (storeAs == null) {
storeAs = obj;
}
if (storeAs == null) {
return SerializeNull ();
}
if (this.hash.ContainsKey (storeAs)) {
return this.hash [storeAs];
}
var result = SerializeOne (obj);
this.hash [storeAs] = result;
return result;
}
int SerializeShovelValueArray (Value[] array)
{
var composite = new Composite {
Kind = ObjectTypes.ShovelValueArray,
Elements = new int[array.Length]
};
var result = SerializeOneHashed (composite, array);
for (var i = 0; i < array.Length; i++) {
composite.Elements [i] = Serialize (array [i]);
}
return result;
}
int SerializeStringArray (string[] array)
{
var composite = new Composite {
Kind = ObjectTypes.StringArray,
Elements = new int[array.Length]
};
var result = SerializeOneHashed (composite, array);
for (var i = 0; i < array.Length; i++) {
composite.Elements [i] = SerializeOneHashed (array [i]);
}
return result;
}
int SerializeHash (HashInstance dict, object obj)
{
var composite = new Composite {
Kind = ObjectTypes.Hash,
Elements = new int[dict.Count * 2 + 2]
};
var result = SerializeOneHashed (composite, obj);
var cursor = 0;
foreach (var kv in dict) {
composite.Elements [cursor] = Serialize (kv.Key);
composite.Elements [cursor + 1] = Serialize (kv.Value);
cursor += 2;
}
composite.Elements[cursor] = Serialize(dict.IndirectGet);
cursor++;
composite.Elements[cursor] = Serialize(dict.IndirectSet);
cursor++;
return result;
}
int SerializeList (ArrayInstance list, object obj)
{
var composite = new Composite {
Kind = ObjectTypes.ShovelValueList,
Elements = new int[list.Count + 2]
};
var result = SerializeOneHashed (composite, obj);
var i = 0;
for (i = 0; i < list.Count; i++) {
composite.Elements [i] = Serialize (list [i]);
}
composite.Elements[i] = Serialize(list.IndirectGet);
i++;
composite.Elements[i] = Serialize(list.IndirectSet);
i++;
return result;
}
int SerializeCallable (Callable callable, object obj)
{
var composite = new Composite {
Kind = ObjectTypes.Callable,
Elements = new int[5]
};
var result = SerializeOneHashed (composite, obj);
composite.Elements [0] = SerializeOneHashed (callable.UdpName);
composite.Elements [1] = SerializeOneHashed (callable.Prim0Name);
composite.Elements [2] = SerializeOne (callable.Arity);
composite.Elements [3] = SerializeOne (callable.ProgramCounter);
composite.Elements [4] = Serialize (callable.Environment);
return result;
}
int SerializeReturnAddress (ReturnAddress returnAddress, object obj)
{
var composite = new Composite {
Kind = ObjectTypes.ReturnAddress,
Elements = new int[2]
};
var result = SerializeOneHashed (composite, obj);
composite.Elements [0] = Serialize (returnAddress.Environment);
composite.Elements [1] = SerializeOne (returnAddress.ProgramCounter);
return result;
}
int SerializeNamedBlock (NamedBlock namedBlock, object obj)
{
var composite = new Composite {
Kind = ObjectTypes.NamedBlock,
Elements = new int[3]
};
var result = SerializeOneHashed (composite, obj);
composite.Elements [0] = SerializeOneHashed (namedBlock.Name);
composite.Elements [1] = SerializeOne (namedBlock.BlockEnd);
composite.Elements [2] = Serialize (namedBlock.Environment);
return result;
}
int SerializeEnvironment (VmEnvironment env, object obj)
{
var composite = new Composite {
Kind = ObjectTypes.Environment,
Elements = new int[2]
};
var result = SerializeOneHashed (composite, obj);
composite.Elements [0] = Serialize (env.Frame);
composite.Elements [1] = Serialize (env.Next);
return result;
}
int SerializeEnvFrame (VmEnvFrame frame, object obj)
{
var composite = new Composite {
Kind = ObjectTypes.EnvFrame,
Elements = new int[3]
};
var result = SerializeOneHashed (composite, obj);
composite.Elements [0] = Serialize (frame.VarNames);
composite.Elements [1] = Serialize (frame.Values);
composite.Elements [2] = SerializeOne (frame.IntroducedAtProgramCounter);
return result;
}
int SerializeStruct (Struct ztruct, object obj)
{
var composite = new Composite {
Kind = ObjectTypes.Struct,
Elements = new int[1]
};
var result = SerializeOneHashed (composite, obj);
composite.Elements [0] = SerializeStringArray (ztruct.Fields);
return result;
}
int SerializeStructInstance (StructInstance structInstance, object obj)
{
var composite = new Composite {
Kind = ObjectTypes.StructInstance,
Elements = new int[2]
};
var result = SerializeOneHashed (composite, obj);
composite.Elements [0] = Serialize (structInstance.Struct);
composite.Elements [1] = SerializeShovelValueArray (structInstance.Values);
return result;
}
int SerializeShovelValue (Value sv, object obj)
{
switch (sv.Kind) {
case Value.Kinds.Null:
return SerializeNull ();
case Value.Kinds.Bool:
return SerializeBool (sv.boolValue);
case Value.Kinds.String:
return SerializeOne (sv.stringValue);
case Value.Kinds.Integer:
return SerializeOne (sv.integerValue);
case Value.Kinds.Double:
return SerializeOne (sv.doubleValue);
case Value.Kinds.Array:
return SerializeList (sv.arrayValue, obj);
case Value.Kinds.Hash:
return SerializeHash (sv.hashValue, obj);
case Value.Kinds.Callable:
return SerializeCallable (sv.CallableValue, obj);
case Value.Kinds.ReturnAddress:
return SerializeReturnAddress (sv.ReturnAddressValue, obj);
case Value.Kinds.NamedBlock:
return SerializeNamedBlock (sv.NamedBlockValue, obj);
case Value.Kinds.Struct:
return SerializeStruct (sv.StructValue, obj);
case Value.Kinds.StructInstance:
return SerializeStructInstance (sv.structInstanceValue, obj);
default:
Shovel.Utils.Panic ();
throw new InvalidOperationException ();
}
}
void WriteString (BinaryWriter bs, string str)
{
byte[] bytes = Encoding.UTF8.GetBytes (str);
if (bytes.Length <= 255) {
bs.Write ((byte)Types.ShortString);
bs.Write ((byte)bytes.Length);
} else {
bs.Write ((byte)Types.String);
bs.Write (bytes.Length);
}
bs.Write (bytes);
}
void WriteLong (BinaryWriter bs, long li)
{
if (li <= Int16.MaxValue && li >= Int16.MinValue) {
bs.Write ((byte)Types.ShortInteger);
bs.Write ((ushort)li);
} else if (li <= Int32.MaxValue && li >= Int32.MinValue) {
bs.Write ((byte)Types.Integer);
bs.Write ((int)li);
} else {
bs.Write ((byte)Types.LongInteger);
bs.Write (li);
}
}
void WriteDouble (BinaryWriter bs, double d)
{
bs.Write ((byte)Types.Double);
bs.Write (d);
}
void WriteComposite (BinaryWriter bs, Composite composite)
{
int length = composite.Elements.Length;
if (length < 255) {
bs.Write ((byte)Types.ShortComposite);
bs.Write ((byte)length);
} else {
bs.Write ((byte)Types.Composite);
bs.Write (length);
}
bs.Write ((byte)composite.Kind);
var lengthInBytes = 4 * composite.Elements.Length;
AdjustBigBuf (lengthInBytes);
Buffer.BlockCopy (composite.Elements, 0, bigBuf, 0, lengthInBytes);
bs.Write (bigBuf, 0, lengthInBytes);
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;
using System.Threading;
using Xunit;
using Xunit.NetCore.Extensions;
namespace System.Diagnostics.Tests
{
public partial class ProcessTests : ProcessTestBase
{
private class FinalizingProcess : Process
{
public static volatile bool WasFinalized;
public static void CreateAndRelease()
{
new FinalizingProcess();
}
protected override void Dispose(bool disposing)
{
if (!disposing)
{
WasFinalized = true;
}
base.Dispose(disposing);
}
}
private void SetAndCheckBasePriority(ProcessPriorityClass exPriorityClass, int priority)
{
_process.PriorityClass = exPriorityClass;
_process.Refresh();
Assert.Equal(priority, _process.BasePriority);
}
private void AssertNonZeroWindowsZeroUnix(long value)
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
Assert.NotEqual(0, value);
}
else
{
Assert.Equal(0, value);
}
}
[ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
[PlatformSpecific(TestPlatforms.Windows)] // Expected behavior varies on Windows and Unix
public void TestBasePriorityOnWindows()
{
CreateDefaultProcess();
ProcessPriorityClass originalPriority = _process.PriorityClass;
Assert.Equal(ProcessPriorityClass.Normal, originalPriority);
try
{
// We are not checking for RealTime case here, as RealTime priority process can
// preempt the threads of all other processes, including operating system processes
// performing important tasks, which may cause the machine to be unresponsive.
//SetAndCheckBasePriority(ProcessPriorityClass.RealTime, 24);
SetAndCheckBasePriority(ProcessPriorityClass.High, 13);
SetAndCheckBasePriority(ProcessPriorityClass.Idle, 4);
SetAndCheckBasePriority(ProcessPriorityClass.Normal, 8);
}
finally
{
_process.PriorityClass = originalPriority;
}
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Expected behavior varies on Windows and Unix
[OuterLoop]
[Trait(XunitConstants.Category, XunitConstants.RequiresElevation)]
public void TestBasePriorityOnUnix()
{
CreateDefaultProcess();
ProcessPriorityClass originalPriority = _process.PriorityClass;
Assert.Equal(ProcessPriorityClass.Normal, originalPriority);
try
{
SetAndCheckBasePriority(ProcessPriorityClass.High, -11);
SetAndCheckBasePriority(ProcessPriorityClass.Idle, 19);
SetAndCheckBasePriority(ProcessPriorityClass.Normal, 0);
}
finally
{
_process.PriorityClass = originalPriority;
}
}
[Theory]
[InlineData(true)]
[InlineData(false)]
[InlineData(null)]
public void TestEnableRaiseEvents(bool? enable)
{
bool exitedInvoked = false;
Process p = CreateProcessLong();
if (enable.HasValue)
{
p.EnableRaisingEvents = enable.Value;
}
p.Exited += delegate { exitedInvoked = true; };
StartSleepKillWait(p);
if (enable.GetValueOrDefault())
{
// There's no guarantee that the Exited callback will be invoked by
// the time Process.WaitForExit completes, though it's extremely likely.
// There could be a race condition where WaitForExit is returning from
// its wait and sees that the callback is already running asynchronously,
// at which point it returns to the caller even if the callback hasn't
// entirely completed. As such, we spin until the value is set.
Assert.True(SpinWait.SpinUntil(() => exitedInvoked, WaitInMS));
}
else
{
Assert.False(exitedInvoked);
}
}
[Fact]
public void TestExitCode()
{
{
Process p = CreateProcess();
p.Start();
Assert.True(p.WaitForExit(WaitInMS));
Assert.Equal(SuccessExitCode, p.ExitCode);
}
{
Process p = CreateProcessLong();
StartSleepKillWait(p);
Assert.NotEqual(0, p.ExitCode);
}
}
[PlatformSpecific(TestPlatforms.AnyUnix)] // Tests UseShellExecute with ProcessStartInfo
[Fact]
public void TestUseShellExecute_Unix_Succeeds()
{
using (var p = Process.Start(new ProcessStartInfo { UseShellExecute = true, FileName = "exit", Arguments = "42" }))
{
Assert.True(p.WaitForExit(WaitInMS));
Assert.Equal(42, p.ExitCode);
}
}
[Fact]
public void TestExitTime()
{
// ExitTime resolution on some platforms is less accurate than our DateTime.UtcNow resolution, so
// we subtract ms from the begin time to account for it.
DateTime timeBeforeProcessStart = DateTime.UtcNow.AddMilliseconds(-25);
Process p = CreateProcessLong();
p.Start();
Assert.Throws<InvalidOperationException>(() => p.ExitTime);
p.Kill();
Assert.True(p.WaitForExit(WaitInMS));
Assert.True(p.ExitTime.ToUniversalTime() >= timeBeforeProcessStart,
$@"TestExitTime is incorrect. " +
$@"TimeBeforeStart {timeBeforeProcessStart} Ticks={timeBeforeProcessStart.Ticks}, " +
$@"ExitTime={p.ExitTime}, Ticks={p.ExitTime.Ticks}, " +
$@"ExitTimeUniversal {p.ExitTime.ToUniversalTime()} Ticks={p.ExitTime.ToUniversalTime().Ticks}, " +
$@"NowUniversal {DateTime.Now.ToUniversalTime()} Ticks={DateTime.Now.Ticks}");
}
[Fact]
public void StartTime_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.StartTime);
}
[Fact]
public void TestId()
{
CreateDefaultProcess();
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
Assert.Equal(_process.Id, Interop.GetProcessId(_process.SafeHandle));
}
else
{
IEnumerable<int> testProcessIds = Process.GetProcessesByName(HostRunnerName).Select(p => p.Id);
Assert.Contains(_process.Id, testProcessIds);
}
}
[Fact]
public void TestHasExited()
{
{
Process p = CreateProcess();
p.Start();
Assert.True(p.WaitForExit(WaitInMS));
Assert.True(p.HasExited, "TestHasExited001 failed");
}
{
Process p = CreateProcessLong();
p.Start();
try
{
Assert.False(p.HasExited, "TestHasExited002 failed");
}
finally
{
p.Kill();
Assert.True(p.WaitForExit(WaitInMS));
}
Assert.True(p.HasExited, "TestHasExited003 failed");
}
}
[Fact]
public void HasExited_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.HasExited);
}
[Fact]
public void Kill_NotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.Kill());
}
[Fact]
public void TestMachineName()
{
CreateDefaultProcess();
// Checking that the MachineName returns some value.
Assert.NotNull(_process.MachineName);
}
[Fact]
public void MachineName_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.MachineName);
}
[Fact]
public void TestMainModuleOnNonOSX()
{
Process p = Process.GetCurrentProcess();
Assert.True(p.Modules.Count > 0);
Assert.Equal(HostRunnerName, p.MainModule.ModuleName);
Assert.EndsWith(HostRunnerName, p.MainModule.FileName);
Assert.Equal(string.Format("System.Diagnostics.ProcessModule ({0})", HostRunnerName), p.MainModule.ToString());
}
[Fact]
public void TestMaxWorkingSet()
{
CreateDefaultProcess();
using (Process p = Process.GetCurrentProcess())
{
Assert.True((long)p.MaxWorkingSet > 0);
Assert.True((long)p.MinWorkingSet >= 0);
}
if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
return; // doesn't support getting/setting working set for other processes
long curValue = (long)_process.MaxWorkingSet;
Assert.True(curValue >= 0);
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
try
{
_process.MaxWorkingSet = (IntPtr)((int)curValue + 1024);
IntPtr min, max;
uint flags;
Interop.GetProcessWorkingSetSizeEx(_process.SafeHandle, out min, out max, out flags);
curValue = (int)max;
_process.Refresh();
Assert.Equal(curValue, (int)_process.MaxWorkingSet);
}
finally
{
_process.MaxWorkingSet = (IntPtr)curValue;
}
}
}
[Fact]
[PlatformSpecific(~TestPlatforms.OSX)] // Getting MaxWorkingSet is not supported on OSX.
public void MaxWorkingSet_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.MaxWorkingSet);
}
[Fact]
[PlatformSpecific(TestPlatforms.OSX)]
public void MaxValueWorkingSet_GetSetMacos_ThrowsPlatformSupportedException()
{
var process = new Process();
Assert.Throws<PlatformNotSupportedException>(() => process.MaxWorkingSet);
Assert.Throws<PlatformNotSupportedException>(() => process.MaxWorkingSet = (IntPtr)1);
}
[Fact]
public void TestMinWorkingSet()
{
CreateDefaultProcess();
using (Process p = Process.GetCurrentProcess())
{
Assert.True((long)p.MaxWorkingSet > 0);
Assert.True((long)p.MinWorkingSet >= 0);
}
if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
return; // doesn't support getting/setting working set for other processes
long curValue = (long)_process.MinWorkingSet;
Assert.True(curValue >= 0);
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
try
{
_process.MinWorkingSet = (IntPtr)((int)curValue - 1024);
IntPtr min, max;
uint flags;
Interop.GetProcessWorkingSetSizeEx(_process.SafeHandle, out min, out max, out flags);
curValue = (int)min;
_process.Refresh();
Assert.Equal(curValue, (int)_process.MinWorkingSet);
}
finally
{
_process.MinWorkingSet = (IntPtr)curValue;
}
}
}
[Fact]
[PlatformSpecific(~TestPlatforms.OSX)] // Getting MinWorkingSet is not supported on OSX.
public void MinWorkingSet_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.MinWorkingSet);
}
[Fact]
[PlatformSpecific(TestPlatforms.OSX)]
public void MinWorkingSet_GetMacos_ThrowsPlatformSupportedException()
{
var process = new Process();
Assert.Throws<PlatformNotSupportedException>(() => process.MinWorkingSet);
}
[Fact]
public void TestModules()
{
ProcessModuleCollection moduleCollection = Process.GetCurrentProcess().Modules;
foreach (ProcessModule pModule in moduleCollection)
{
// Validated that we can get a value for each of the following.
Assert.NotNull(pModule);
Assert.NotNull(pModule.FileName);
Assert.NotNull(pModule.ModuleName);
// Just make sure these don't throw
IntPtr baseAddr = pModule.BaseAddress;
IntPtr entryAddr = pModule.EntryPointAddress;
int memSize = pModule.ModuleMemorySize;
}
}
[Fact]
public void TestNonpagedSystemMemorySize64()
{
CreateDefaultProcess();
AssertNonZeroWindowsZeroUnix(_process.NonpagedSystemMemorySize64);
}
[Fact]
public void NonpagedSystemMemorySize64_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.NonpagedSystemMemorySize64);
}
[Fact]
public void TestPagedMemorySize64()
{
CreateDefaultProcess();
AssertNonZeroWindowsZeroUnix(_process.PagedMemorySize64);
}
[Fact]
public void PagedMemorySize64_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.PagedMemorySize64);
}
[Fact]
public void TestPagedSystemMemorySize64()
{
CreateDefaultProcess();
AssertNonZeroWindowsZeroUnix(_process.PagedSystemMemorySize64);
}
[Fact]
public void PagedSystemMemorySize64_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.PagedSystemMemorySize64);
}
[Fact]
public void TestPeakPagedMemorySize64()
{
CreateDefaultProcess();
AssertNonZeroWindowsZeroUnix(_process.PeakPagedMemorySize64);
}
[Fact]
public void PeakPagedMemorySize64_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.PeakPagedMemorySize64);
}
[Fact]
public void TestPeakVirtualMemorySize64()
{
CreateDefaultProcess();
AssertNonZeroWindowsZeroUnix(_process.PeakVirtualMemorySize64);
}
[Fact]
public void PeakVirtualMemorySize64_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.PeakVirtualMemorySize64);
}
[Fact]
public void TestPeakWorkingSet64()
{
CreateDefaultProcess();
AssertNonZeroWindowsZeroUnix(_process.PeakWorkingSet64);
}
[Fact]
public void PeakWorkingSet64_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.PeakWorkingSet64);
}
[Fact]
public void TestPrivateMemorySize64()
{
CreateDefaultProcess();
AssertNonZeroWindowsZeroUnix(_process.PrivateMemorySize64);
}
[Fact]
public void PrivateMemorySize64_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.PrivateMemorySize64);
}
[Fact]
public void TestVirtualMemorySize64()
{
CreateDefaultProcess();
Assert.True(_process.VirtualMemorySize64 > 0);
}
[Fact]
public void VirtualMemorySize64_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.VirtualMemorySize64);
}
[Fact]
public void TestWorkingSet64()
{
CreateDefaultProcess();
if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
// resident memory can be 0 on OSX.
Assert.True(_process.WorkingSet64 >= 0);
return;
}
Assert.True(_process.WorkingSet64 > 0);
}
[Fact]
public void WorkingSet64_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.WorkingSet64);
}
[Fact]
public void TestProcessorTime()
{
CreateDefaultProcess();
Assert.True(_process.UserProcessorTime.TotalSeconds >= 0);
Assert.True(_process.PrivilegedProcessorTime.TotalSeconds >= 0);
double processorTimeBeforeSpin = Process.GetCurrentProcess().TotalProcessorTime.TotalSeconds;
double processorTimeAtHalfSpin = 0;
// Perform loop to occupy cpu, takes less than a second.
int i = int.MaxValue / 16;
while (i > 0)
{
i--;
if (i == int.MaxValue / 32)
processorTimeAtHalfSpin = Process.GetCurrentProcess().TotalProcessorTime.TotalSeconds;
}
Assert.InRange(processorTimeAtHalfSpin, processorTimeBeforeSpin, Process.GetCurrentProcess().TotalProcessorTime.TotalSeconds);
}
[Fact]
public void UserProcessorTime_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.UserProcessorTime);
}
[Fact]
public void PriviledgedProcessorTime_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.PrivilegedProcessorTime);
}
[Fact]
public void TotalProcessorTime_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.TotalProcessorTime);
}
[ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/974
public void TestProcessStartTime()
{
TimeSpan allowedWindow = TimeSpan.FromSeconds(3);
DateTime testStartTime = DateTime.UtcNow;
using (var remote = RemoteInvoke(() => { Console.Write(Process.GetCurrentProcess().StartTime.ToUniversalTime()); return SuccessExitCode; },
new RemoteInvokeOptions { StartInfo = new ProcessStartInfo { RedirectStandardOutput = true } }))
{
Assert.Equal(remote.Process.StartTime, remote.Process.StartTime);
DateTime remoteStartTime = DateTime.Parse(remote.Process.StandardOutput.ReadToEnd());
DateTime curTime = DateTime.UtcNow;
Assert.InRange(remoteStartTime, testStartTime - allowedWindow, curTime + allowedWindow);
}
}
[Fact]
public void ExitTime_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.ExitTime);
}
[ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/968
[PlatformSpecific(~TestPlatforms.OSX)] // getting/setting affinity not supported on OSX
public void TestProcessorAffinity()
{
CreateDefaultProcess();
IntPtr curProcessorAffinity = _process.ProcessorAffinity;
try
{
_process.ProcessorAffinity = new IntPtr(0x1);
Assert.Equal(new IntPtr(0x1), _process.ProcessorAffinity);
}
finally
{
_process.ProcessorAffinity = curProcessorAffinity;
Assert.Equal(curProcessorAffinity, _process.ProcessorAffinity);
}
}
[Fact]
public void TestPriorityBoostEnabled()
{
CreateDefaultProcess();
bool isPriorityBoostEnabled = _process.PriorityBoostEnabled;
try
{
_process.PriorityBoostEnabled = true;
Assert.True(_process.PriorityBoostEnabled, "TestPriorityBoostEnabled001 failed");
_process.PriorityBoostEnabled = false;
Assert.False(_process.PriorityBoostEnabled, "TestPriorityBoostEnabled002 failed");
}
finally
{
_process.PriorityBoostEnabled = isPriorityBoostEnabled;
}
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // PriorityBoostEnabled is a no-op on Unix.
public void PriorityBoostEnabled_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.PriorityBoostEnabled);
Assert.Throws<InvalidOperationException>(() => process.PriorityBoostEnabled = true);
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Expected behavior varies on Windows and Unix
[OuterLoop]
[Trait(XunitConstants.Category, XunitConstants.RequiresElevation)]
public void TestPriorityClassUnix()
{
CreateDefaultProcess();
ProcessPriorityClass priorityClass = _process.PriorityClass;
try
{
_process.PriorityClass = ProcessPriorityClass.High;
Assert.Equal(_process.PriorityClass, ProcessPriorityClass.High);
_process.PriorityClass = ProcessPriorityClass.Normal;
Assert.Equal(_process.PriorityClass, ProcessPriorityClass.Normal);
}
finally
{
_process.PriorityClass = priorityClass;
}
}
[Fact, PlatformSpecific(TestPlatforms.Windows)] // Expected behavior varies on Windows and Unix
public void TestPriorityClassWindows()
{
CreateDefaultProcess();
ProcessPriorityClass priorityClass = _process.PriorityClass;
try
{
_process.PriorityClass = ProcessPriorityClass.High;
Assert.Equal(_process.PriorityClass, ProcessPriorityClass.High);
_process.PriorityClass = ProcessPriorityClass.Normal;
Assert.Equal(_process.PriorityClass, ProcessPriorityClass.Normal);
}
finally
{
_process.PriorityClass = priorityClass;
}
}
[Theory]
[InlineData((ProcessPriorityClass)0)]
[InlineData(ProcessPriorityClass.Normal | ProcessPriorityClass.Idle)]
public void TestInvalidPriorityClass(ProcessPriorityClass priorityClass)
{
var process = new Process();
Assert.Throws<InvalidEnumArgumentException>(() => process.PriorityClass = priorityClass);
}
[Fact]
public void PriorityClass_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.PriorityClass);
}
[Fact]
public void TestProcessName()
{
CreateDefaultProcess();
// Processes are not hosted by dotnet in the full .NET Framework.
string expected = PlatformDetection.IsFullFramework ? TestConsoleApp : HostRunner;
Assert.Equal(Path.GetFileNameWithoutExtension(_process.ProcessName), Path.GetFileNameWithoutExtension(expected), StringComparer.OrdinalIgnoreCase);
}
[Fact]
public void ProcessName_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.ProcessName);
}
[Fact]
public void TestSafeHandle()
{
CreateDefaultProcess();
Assert.False(_process.SafeHandle.IsInvalid);
}
[Fact]
public void SafeHandle_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.SafeHandle);
}
[Fact]
public void TestSessionId()
{
CreateDefaultProcess();
uint sessionId;
#if TargetsWindows
Interop.ProcessIdToSessionId((uint)_process.Id, out sessionId);
#else
sessionId = (uint)Interop.getsid(_process.Id);
#endif
Assert.Equal(sessionId, (uint)_process.SessionId);
}
[Fact]
public void SessionId_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.SessionId);
}
[Fact]
public void TestGetCurrentProcess()
{
Process current = Process.GetCurrentProcess();
Assert.NotNull(current);
int currentProcessId =
#if TargetsWindows
Interop.GetCurrentProcessId();
#else
Interop.getpid();
#endif
Assert.Equal(currentProcessId, current.Id);
}
[Fact]
public void TestGetProcessById()
{
CreateDefaultProcess();
Process p = Process.GetProcessById(_process.Id);
Assert.Equal(_process.Id, p.Id);
Assert.Equal(_process.ProcessName, p.ProcessName);
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Uses P/Invokes to get process Id
public void TestRootGetProcessById()
{
Process p = Process.GetProcessById(1);
Assert.Equal(1, p.Id);
}
[Fact]
public void TestGetProcesses()
{
Process currentProcess = Process.GetCurrentProcess();
// Get all the processes running on the machine, and check if the current process is one of them.
var foundCurrentProcess = (from p in Process.GetProcesses()
where (p.Id == currentProcess.Id) && (p.ProcessName.Equals(currentProcess.ProcessName))
select p).Any();
Assert.True(foundCurrentProcess, "TestGetProcesses001 failed");
foundCurrentProcess = (from p in Process.GetProcesses(currentProcess.MachineName)
where (p.Id == currentProcess.Id) && (p.ProcessName.Equals(currentProcess.ProcessName))
select p).Any();
Assert.True(foundCurrentProcess, "TestGetProcesses002 failed");
}
[Fact]
public void GetProcesseses_NullMachineName_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("machineName", () => Process.GetProcesses(null));
}
[Fact]
public void GetProcesses_EmptyMachineName_ThrowsArgumentException()
{
Assert.Throws<ArgumentException>(null, () => Process.GetProcesses(""));
}
[Fact]
public void GetProcessesByName_ProcessName_ReturnsExpected()
{
// Get the current process using its name
Process currentProcess = Process.GetCurrentProcess();
Process[] processes = Process.GetProcessesByName(currentProcess.ProcessName);
Assert.NotEmpty(processes);
Assert.All(processes, process => Assert.Equal(".", process.MachineName));
}
public static IEnumerable<object[]> MachineName_TestData()
{
string currentProcessName = Process.GetCurrentProcess().MachineName;
yield return new object[] { currentProcessName };
yield return new object[] { "." };
yield return new object[] { Dns.GetHostName() };
}
public static IEnumerable<object[]> MachineName_Remote_TestData()
{
yield return new object[] { Guid.NewGuid().ToString("N") };
yield return new object[] { "\\" + Guid.NewGuid().ToString("N") };
}
[Theory]
[MemberData(nameof(MachineName_TestData))]
public void GetProcessesByName_ProcessNameMachineName_ReturnsExpected(string machineName)
{
Process currentProcess = Process.GetCurrentProcess();
Process[] processes = Process.GetProcessesByName(currentProcess.ProcessName, machineName);
Assert.NotEmpty(processes);
Assert.All(processes, process => Assert.Equal(machineName, process.MachineName));
}
[MemberData(nameof(MachineName_Remote_TestData))]
[PlatformSpecific(TestPlatforms.Windows)] // Accessing processes on remote machines is only supported on Windows.
public void GetProcessesByName_RemoteMachineNameWindows_ReturnsExpected(string machineName)
{
try
{
GetProcessesByName_ProcessNameMachineName_ReturnsExpected(machineName);
}
catch (InvalidOperationException)
{
// As we can't detect reliably if performance counters are enabled
// we let possible InvalidOperationExceptions pass silently.
}
}
[Theory]
[MemberData(nameof(MachineName_Remote_TestData))]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Accessing processes on remote machines is not supported on Unix.
public void GetProcessesByName_RemoteMachineNameUnix_ThrowsPlatformNotSupportedException(string machineName)
{
Process currentProcess = Process.GetCurrentProcess();
Assert.Throws<PlatformNotSupportedException>(() => Process.GetProcessesByName(currentProcess.ProcessName, machineName));
}
[Fact]
public void GetProcessesByName_NoSuchProcess_ReturnsEmpty()
{
string processName = Guid.NewGuid().ToString("N");
Assert.Empty(Process.GetProcessesByName(processName));
}
[Fact]
public void GetProcessesByName_NullMachineName_ThrowsArgumentNullException()
{
Process currentProcess = Process.GetCurrentProcess();
AssertExtensions.Throws<ArgumentNullException>("machineName", () => Process.GetProcessesByName(currentProcess.ProcessName, null));
}
[Fact]
public void GetProcessesByName_EmptyMachineName_ThrowsArgumentException()
{
Process currentProcess = Process.GetCurrentProcess();
Assert.Throws<ArgumentException>(null, () => Process.GetProcessesByName(currentProcess.ProcessName, ""));
}
[PlatformSpecific(TestPlatforms.Windows)] // Behavior differs on Windows and Unix
[SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "https://github.com/dotnet/corefx/issues/18212")]
public void TestProcessOnRemoteMachineWindows()
{
Process currentProccess = Process.GetCurrentProcess();
void TestRemoteProccess(Process remoteProcess)
{
Assert.Equal(currentProccess.Id, remoteProcess.Id);
Assert.Equal(currentProccess.BasePriority, remoteProcess.BasePriority);
Assert.Equal(currentProccess.EnableRaisingEvents, remoteProcess.EnableRaisingEvents);
Assert.Equal("127.0.0.1", remoteProcess.MachineName);
// This property throws exception only on remote processes.
Assert.Throws<NotSupportedException>(() => remoteProcess.MainModule);
}
try
{
TestRemoteProccess(Process.GetProcessById(currentProccess.Id, "127.0.0.1"));
TestRemoteProccess(Process.GetProcessesByName(currentProccess.ProcessName, "127.0.0.1").Where(p => p.Id == currentProccess.Id).Single());
}
catch (InvalidOperationException)
{
// As we can't detect reliably if performance counters are enabled
// we let possible InvalidOperationExceptions pass silently.
}
}
[Fact, PlatformSpecific(TestPlatforms.AnyUnix)] // Behavior differs on Windows and Unix
public void TestProcessOnRemoteMachineUnix()
{
Process currentProcess = Process.GetCurrentProcess();
Assert.Throws<PlatformNotSupportedException>(() => Process.GetProcessesByName(currentProcess.ProcessName, "127.0.0.1"));
Assert.Throws<PlatformNotSupportedException>(() => Process.GetProcessById(currentProcess.Id, "127.0.0.1"));
}
[Fact]
public void StartInfo_GetFileName_ReturnsExpected()
{
Process process = CreateProcessLong();
process.Start();
// Processes are not hosted by dotnet in the full .NET Framework.
string expectedFileName = PlatformDetection.IsFullFramework ? TestConsoleApp : HostRunner;
Assert.Equal(expectedFileName, process.StartInfo.FileName);
process.Kill();
Assert.True(process.WaitForExit(WaitInMS));
}
[Fact]
public void StartInfo_SetOnRunningProcess_ThrowsInvalidOperationException()
{
Process process = CreateProcessLong();
process.Start();
// .NET Core fixes a bug where Process.StartInfo for a unrelated process would
// return information about the current process, not the unrelated process.
// See https://github.com/dotnet/corefx/issues/1100.
if (PlatformDetection.IsFullFramework)
{
var startInfo = new ProcessStartInfo();
process.StartInfo = startInfo;
Assert.Equal(startInfo, process.StartInfo);
}
else
{
Assert.Throws<InvalidOperationException>(() => process.StartInfo = new ProcessStartInfo());
}
process.Kill();
Assert.True(process.WaitForExit(WaitInMS));
}
[Fact]
public void StartInfo_SetGet_ReturnsExpected()
{
var process = new Process() { StartInfo = new ProcessStartInfo(TestConsoleApp) };
Assert.Equal(TestConsoleApp, process.StartInfo.FileName);
}
[Fact]
public void StartInfo_SetNull_ThrowsArgumentNullException()
{
var process = new Process();
Assert.Throws<ArgumentNullException>("value", () => process.StartInfo = null);
}
[Fact]
public void StartInfo_GetOnRunningProcess_ThrowsInvalidOperationException()
{
Process process = Process.GetCurrentProcess();
// .NET Core fixes a bug where Process.StartInfo for an unrelated process would
// return information about the current process, not the unrelated process.
// See https://github.com/dotnet/corefx/issues/1100.
if (PlatformDetection.IsFullFramework)
{
Assert.NotNull(process.StartInfo);
}
else
{
Assert.Throws<InvalidOperationException>(() => process.StartInfo);
}
}
[Theory]
[InlineData(@"""abc"" d e", @"abc,d,e")]
[InlineData(@"""abc"" d e", @"abc,d,e")]
[InlineData("\"abc\"\t\td\te", @"abc,d,e")]
[InlineData(@"a\\b d""e f""g h", @"a\\b,de fg,h")]
[InlineData(@"\ \\ \\\", @"\,\\,\\\")]
[InlineData(@"a\\\""b c d", @"a\""b,c,d")]
[InlineData(@"a\\\\""b c"" d e", @"a\\b c,d,e")]
[InlineData(@"a""b c""d e""f g""h i""j k""l", @"ab cd,ef gh,ij kl")]
[InlineData(@"a b c""def", @"a,b,cdef")]
[InlineData(@"""\a\"" \\""\\\ b c", @"\a"" \\\\,b,c")]
public void TestArgumentParsing(string inputArguments, string expectedArgv)
{
using (var handle = RemoteInvokeRaw((Func<string, string, string, int>)ConcatThreeArguments,
inputArguments,
new RemoteInvokeOptions { Start = true, StartInfo = new ProcessStartInfo { RedirectStandardOutput = true } }))
{
Assert.Equal(expectedArgv, handle.Process.StandardOutput.ReadToEnd());
}
}
[Fact]
public void StandardInput_GetNotRedirected_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.StandardInput);
}
private static int ConcatThreeArguments(string one, string two, string three)
{
Console.Write(string.Join(",", one, two, three));
return SuccessExitCode;
}
// [Fact] // uncomment for diagnostic purposes to list processes to console
public void TestDiagnosticsWithConsoleWriteLine()
{
foreach (var p in Process.GetProcesses().OrderBy(p => p.Id))
{
Console.WriteLine("{0} : \"{1}\" (Threads: {2})", p.Id, p.ProcessName, p.Threads.Count);
p.Dispose();
}
}
[Fact]
public void CanBeFinalized()
{
FinalizingProcess.CreateAndRelease();
GC.Collect();
GC.WaitForPendingFinalizers();
Assert.True(FinalizingProcess.WasFinalized);
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void TestStartWithMissingFile(bool fullPath)
{
string path = Guid.NewGuid().ToString("N");
if (fullPath)
{
path = Path.GetFullPath(path);
Assert.True(Path.IsPathRooted(path));
}
else
{
Assert.False(Path.IsPathRooted(path));
}
Assert.False(File.Exists(path));
Win32Exception e = Assert.Throws<Win32Exception>(() => Process.Start(path));
Assert.NotEqual(0, e.NativeErrorCode);
}
[PlatformSpecific(TestPlatforms.Windows)] // Needs permissions on Unix
// NativeErrorCode not 193 on Windows Nano for ERROR_BAD_EXE_FORMAT, issue #10290
[ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
public void TestStartOnWindowsWithBadFileFormat()
{
string path = GetTestFilePath();
File.Create(path).Dispose();
Win32Exception e = Assert.Throws<Win32Exception>(() => Process.Start(path));
Assert.NotEqual(0, e.NativeErrorCode);
}
[Fact]
public void Start_NullStartInfo_ThrowsArgumentNullExceptionException()
{
AssertExtensions.Throws<ArgumentNullException>("startInfo", () => Process.Start((ProcessStartInfo)null));
}
[Fact]
public void Start_EmptyFileName_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.Start());
}
[Fact]
public void Start_HasStandardOutputEncodingNonRedirected_ThrowsInvalidOperationException()
{
var process = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = "FileName",
RedirectStandardOutput = false,
StandardOutputEncoding = Encoding.UTF8
}
};
Assert.Throws<InvalidOperationException>(() => process.Start());
}
[Fact]
public void Start_HasStandardErrorEncodingNonRedirected_ThrowsInvalidOperationException()
{
var process = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = "FileName",
RedirectStandardError = false,
StandardErrorEncoding = Encoding.UTF8
}
};
Assert.Throws<InvalidOperationException>(() => process.Start());
}
[Fact]
public void Start_Disposed_ThrowsObjectDisposedException()
{
var process = new Process();
process.StartInfo.FileName = "Nothing";
process.Dispose();
Assert.Throws<ObjectDisposedException>(() => process.Start());
}
[Fact]
[PlatformSpecific(TestPlatforms.Linux | TestPlatforms.Windows)] // Expected process HandleCounts differs on OSX
public void TestHandleCount()
{
using (Process p = Process.GetCurrentProcess())
{
Assert.True(p.HandleCount > 0);
}
}
[Fact]
[PlatformSpecific(TestPlatforms.OSX)] // Expected process HandleCounts differs on OSX
public void TestHandleCount_OSX()
{
using (Process p = Process.GetCurrentProcess())
{
Assert.Equal(0, p.HandleCount);
}
}
[Fact]
[PlatformSpecific(TestPlatforms.Linux | TestPlatforms.Windows)] // Expected process HandleCounts differs on OSX
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Handle count change is not reliable, but seems less robust on NETFX")]
public void HandleCountChanges()
{
RemoteInvoke(() =>
{
Process p = Process.GetCurrentProcess();
int handleCount = p.HandleCount;
using (var fs1 = File.Open(GetTestFilePath(), FileMode.OpenOrCreate))
using (var fs2 = File.Open(GetTestFilePath(), FileMode.OpenOrCreate))
using (var fs3 = File.Open(GetTestFilePath(), FileMode.OpenOrCreate))
{
p.Refresh();
int secondHandleCount = p.HandleCount;
Assert.True(handleCount < secondHandleCount);
handleCount = secondHandleCount;
}
p.Refresh();
int thirdHandleCount = p.HandleCount;
Assert.True(thirdHandleCount < handleCount);
return SuccessExitCode;
}).Dispose();
}
[Fact]
public void HandleCount_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.HandleCount);
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // MainWindowHandle is not supported on Unix.
public void MainWindowHandle_NoWindow_ReturnsEmptyHandle()
{
CreateDefaultProcess();
Assert.Equal(IntPtr.Zero, _process.MainWindowHandle);
Assert.Equal(_process.MainWindowHandle, _process.MainWindowHandle);
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // MainWindowHandle is not supported on Unix.
public void MainWindowHandle_GetUnix_ThrowsPlatformNotSupportedException()
{
CreateDefaultProcess();
Assert.Throws<PlatformNotSupportedException>(() => _process.MainWindowHandle);
}
[Fact]
public void MainWindowHandle_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.MainWindowHandle);
}
[Fact]
public void MainWindowTitle_NoWindow_ReturnsEmpty()
{
CreateDefaultProcess();
Assert.Empty(_process.MainWindowTitle);
Assert.Same(_process.MainWindowTitle, _process.MainWindowTitle);
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // MainWindowTitle is a no-op and always returns string.Empty on Unix.
public void MainWindowTitle_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.MainWindowTitle);
}
[Fact]
public void CloseMainWindow_NoWindow_ReturnsFalse()
{
CreateDefaultProcess();
Assert.False(_process.CloseMainWindow());
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // CloseMainWindow is a no-op and always returns false on Unix.
public void CloseMainWindow_NotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.CloseMainWindow());
}
[PlatformSpecific(TestPlatforms.Windows)] // Needs to get the process Id from OS
[Fact]
public void TestRespondingWindows()
{
using (Process p = Process.GetCurrentProcess())
{
Assert.True(p.Responding);
}
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Responding always returns true on Unix.
public void Responding_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.Responding);
}
[PlatformSpecific(TestPlatforms.AnyUnix)] // Needs to get the process Id from OS
[Fact]
private void TestWindowApisUnix()
{
// This tests the hardcoded implementations of these APIs on Unix.
using (Process p = Process.GetCurrentProcess())
{
Assert.True(p.Responding);
Assert.Equal(string.Empty, p.MainWindowTitle);
Assert.False(p.CloseMainWindow());
Assert.Throws<InvalidOperationException>(()=>p.WaitForInputIdle());
}
}
[Fact]
public void TestNonpagedSystemMemorySize()
{
CreateDefaultProcess();
#pragma warning disable 0618
AssertNonZeroWindowsZeroUnix(_process.NonpagedSystemMemorySize);
#pragma warning restore 0618
}
[Fact]
public void NonpagedSystemMemorySize_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
#pragma warning disable 0618
Assert.Throws<InvalidOperationException>(() => process.NonpagedSystemMemorySize);
#pragma warning restore 0618
}
[Fact]
public void TestPagedMemorySize()
{
CreateDefaultProcess();
#pragma warning disable 0618
AssertNonZeroWindowsZeroUnix(_process.PagedMemorySize);
#pragma warning restore 0618
}
[Fact]
public void PagedMemorySize_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
#pragma warning disable 0618
Assert.Throws<InvalidOperationException>(() => process.PagedMemorySize);
#pragma warning restore 0618
}
[Fact]
public void TestPagedSystemMemorySize()
{
CreateDefaultProcess();
#pragma warning disable 0618
AssertNonZeroWindowsZeroUnix(_process.PagedSystemMemorySize);
#pragma warning restore 0618
}
[Fact]
public void PagedSystemMemorySize_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
#pragma warning disable 0618
Assert.Throws<InvalidOperationException>(() => process.PagedSystemMemorySize);
#pragma warning restore 0618
}
[Fact]
public void TestPeakPagedMemorySize()
{
CreateDefaultProcess();
#pragma warning disable 0618
AssertNonZeroWindowsZeroUnix(_process.PeakPagedMemorySize);
#pragma warning restore 0618
}
[Fact]
public void PeakPagedMemorySize_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
#pragma warning disable 0618
Assert.Throws<InvalidOperationException>(() => process.PeakPagedMemorySize);
#pragma warning restore 0618
}
[Fact]
public void TestPeakVirtualMemorySize()
{
CreateDefaultProcess();
#pragma warning disable 0618
AssertNonZeroWindowsZeroUnix(_process.PeakVirtualMemorySize);
#pragma warning restore 0618
}
[Fact]
public void PeakVirtualMemorySize_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
#pragma warning disable 0618
Assert.Throws<InvalidOperationException>(() => process.PeakVirtualMemorySize);
#pragma warning restore 0618
}
[Fact]
public void TestPeakWorkingSet()
{
CreateDefaultProcess();
#pragma warning disable 0618
AssertNonZeroWindowsZeroUnix(_process.PeakWorkingSet);
#pragma warning restore 0618
}
[Fact]
public void PeakWorkingSet_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
#pragma warning disable 0618
Assert.Throws<InvalidOperationException>(() => process.PeakWorkingSet);
#pragma warning restore 0618
}
[Fact]
public void TestPrivateMemorySize()
{
CreateDefaultProcess();
#pragma warning disable 0618
AssertNonZeroWindowsZeroUnix(_process.PrivateMemorySize);
#pragma warning restore 0618
}
[Fact]
public void PrivateMemorySize_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
#pragma warning disable 0618
Assert.Throws<InvalidOperationException>(() => process.PrivateMemorySize);
#pragma warning restore 0618
}
[Fact]
public void TestVirtualMemorySize()
{
CreateDefaultProcess();
#pragma warning disable 0618
Assert.Equal(unchecked((int)_process.VirtualMemorySize64), _process.VirtualMemorySize);
#pragma warning restore 0618
}
[Fact]
public void VirtualMemorySize_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
#pragma warning disable 0618
Assert.Throws<InvalidOperationException>(() => process.VirtualMemorySize);
#pragma warning restore 0618
}
[Fact]
public void TestWorkingSet()
{
CreateDefaultProcess();
if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
// resident memory can be 0 on OSX.
#pragma warning disable 0618
Assert.True(_process.WorkingSet >= 0);
#pragma warning restore 0618
return;
}
#pragma warning disable 0618
Assert.True(_process.WorkingSet > 0);
#pragma warning restore 0618
}
[Fact]
public void WorkingSet_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
#pragma warning disable 0618
Assert.Throws<InvalidOperationException>(() => process.WorkingSet);
#pragma warning restore 0618
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Starting process with authentication not supported on Unix
public void Process_StartInvalidNamesTest()
{
Assert.Throws<InvalidOperationException>(() => Process.Start(null, "userName", new SecureString(), "thisDomain"));
Assert.Throws<InvalidOperationException>(() => Process.Start(string.Empty, "userName", new SecureString(), "thisDomain"));
Assert.Throws<Win32Exception>(() => Process.Start("exe", string.Empty, new SecureString(), "thisDomain"));
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Starting process with authentication not supported on Unix
public void Process_StartWithInvalidUserNamePassword()
{
SecureString password = AsSecureString("Value");
Assert.Throws<Win32Exception>(() => Process.Start(GetCurrentProcessName(), "userName", password, "thisDomain"));
Assert.Throws<Win32Exception>(() => Process.Start(GetCurrentProcessName(), Environment.UserName, password, Environment.UserDomainName));
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Starting process with authentication not supported on Unix
public void Process_StartTest()
{
string currentProcessName = GetCurrentProcessName();
string userName = string.Empty;
string domain = "thisDomain";
SecureString password = AsSecureString("Value");
Process p = Process.Start(currentProcessName, userName, password, domain);
Assert.NotNull(p);
Assert.Equal(currentProcessName, p.StartInfo.FileName);
Assert.Equal(userName, p.StartInfo.UserName);
Assert.Same(password, p.StartInfo.Password);
Assert.Equal(domain, p.StartInfo.Domain);
Assert.True(p.WaitForExit(WaitInMS));
password.Dispose();
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Starting process with authentication not supported on Unix
public void Process_StartWithArgumentsTest()
{
string currentProcessName = GetCurrentProcessName();
string userName = string.Empty;
string domain = Environment.UserDomainName;
string arguments = "-xml testResults.xml";
SecureString password = AsSecureString("Value");
Process p = Process.Start(currentProcessName, arguments, userName, password, domain);
Assert.NotNull(p);
Assert.Equal(currentProcessName, p.StartInfo.FileName);
Assert.Equal(arguments, p.StartInfo.Arguments);
Assert.Equal(userName, p.StartInfo.UserName);
Assert.Same(password, p.StartInfo.Password);
Assert.Equal(domain, p.StartInfo.Domain);
p.Kill();
password.Dispose();
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Starting process with authentication not supported on Unix
public void Process_StartWithDuplicatePassword()
{
var startInfo = new ProcessStartInfo()
{
FileName = "exe",
UserName = "dummyUser",
PasswordInClearText = "Value",
Password = AsSecureString("Value"),
UseShellExecute = false
};
var process = new Process() { StartInfo = startInfo };
Assert.Throws<ArgumentException>(null, () => process.Start());
}
private string GetCurrentProcessName()
{
return $"{Process.GetCurrentProcess().ProcessName}.exe";
}
private SecureString AsSecureString(string str)
{
SecureString secureString = new SecureString();
foreach (var ch in str)
{
secureString.AppendChar(ch);
}
return secureString;
}
}
}
| |
/*
* Naiad ver. 0.5
* Copyright (c) Microsoft Corporation
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT
* LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR
* A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT.
*
* See the Apache Version 2.0 License for specific language governing
* permissions and limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Research.Naiad.Serialization;
using Microsoft.Research.Naiad.DataStructures;
namespace Microsoft.Research.Naiad.Frameworks.DifferentialDataflow.CollectionTrace
{
internal class CollectionTraceWithoutHeap<S> : CollectionTraceCheckpointable<S>
where S : IEquatable<S>
{
VariableLengthHeap<CollectionTraceWithoutHeapIncrement> increments; // stores regions of increments, each corresponding to a time
Func<int, int, bool> TimeLessThan; // wraps the "less than" partial order on time indices
Func<int, int> UpdateTime; // wraps the reachability-based time advancement
OffsetLength cachedIncrementOffset;
Int64 cachedWeight;
int cachedTimeIndex;
public void ReleaseCache()
{
if (!cachedIncrementOffset.IsEmpty)
{
cachedWeight = 0;
cachedIncrementOffset = new OffsetLength();
cachedTimeIndex = 0;
}
}
public void Introduce(ref int offsetLength, S element, Int64 weight, int timeIndex)
{
var ol = new OffsetLength(offsetLength);
Introduce(ref ol, element, weight, timeIndex);
offsetLength = ol.offsetLength;
ReleaseCache();
}
void Introduce(ref OffsetLength offsetLength, S element, Int64 weight, int timeIndex)
{
if (weight != 0)
{
var handle = EnsureTime(ref offsetLength, timeIndex);
var position = 0;
while (handle.Array[handle.Offset + position].TimeIndex != timeIndex)
position++;
handle.Array[handle.Offset + position].Weight += weight;
// if the introduction results in an empty region, we need to clean up
if (handle.Array[handle.Offset + position].IsEmpty)
{
// drag everything after it down one
for (int i = position + 1; i < handle.Length; i++)
handle.Array[handle.Offset + i - 1] = handle.Array[handle.Offset + i];
handle.Array[handle.Offset + handle.Length - 1] = new CollectionTraceWithoutHeapIncrement();
// if the root element is empty, the list must be empty
if (handle.Array[handle.Offset].IsEmpty)
increments.Release(ref offsetLength);
}
}
}
void Introduce(ref OffsetLength thisOffsetLength, OffsetLength thatOffsetLength, int scale)
{
var handle = increments.Dereference(thatOffsetLength);
for (int i = 0; i < handle.Length && !handle.Array[handle.Offset + i].IsEmpty; i++)
Introduce(ref thisOffsetLength, default(S), scale * handle.Array[handle.Offset + i].Weight, handle.Array[handle.Offset + i].TimeIndex);
}
Handle<CollectionTraceWithoutHeapIncrement> EnsureTime(ref OffsetLength offsetLength, int timeIndex)
{
var handle = increments.Dereference(offsetLength);
for (int i = 0; i < handle.Length; i++)
{
// if we found the time, it is ensured and we can return
if (handle.Array[handle.Offset + i].TimeIndex == timeIndex)
return handle;
// if we found an empty slot, new it up and return
if (handle.Array[handle.Offset + i].IsEmpty)
{
handle.Array[handle.Offset + i] = new CollectionTraceWithoutHeapIncrement(timeIndex);
return handle;
}
}
// if we didn't find it, and no empty space for it
var oldLength = handle.Length;
handle = increments.EnsureAllocation(ref offsetLength, handle.Length + 1);
handle.Array[handle.Offset + oldLength] = new CollectionTraceWithoutHeapIncrement(timeIndex);
return handle;
}
public void IntroduceFrom(ref int thisKeyIndex, ref int thatKeyIndex, bool delete = true)
{
var ol1 = new OffsetLength(thisKeyIndex);
var ol2 = new OffsetLength(thatKeyIndex);
if (!ol2.IsEmpty)
{
Introduce(ref ol1, ol2, 1);
thisKeyIndex = ol1.offsetLength;
if (delete)
ZeroState(ref thatKeyIndex);
ReleaseCache();
}
}
public void SubtractStrictlyPriorDifferences(ref int keyIndex, int timeIndex)
{
var ol = new OffsetLength(keyIndex);
// if there aren't any strictly prior differences we can just return
if (ol.IsEmpty)
return;
var handle = EnsureTime(ref ol, timeIndex);
var position = 0;
while (handle.Array[handle.Offset + position].TimeIndex != timeIndex)
position++;
// if the destination time is empty, we can swap in the accumulation (negated)
if (!handle.Array[handle.Offset + position].IsEmpty)
{
// swap the accumulation in, and zero out the accumulation (the new correct accumulation for this key).
handle.Array[handle.Offset + position] = new CollectionTraceWithoutHeapIncrement(-1 * UpdateAccumulation(ref ol, timeIndex), timeIndex);
// we may have ended up with a null acculumation, must clean up
if (handle.Array[handle.Offset + position].Weight == 0)
{
for (int i = position + 1; i < handle.Length; i++)
handle.Array[handle.Offset + i - 1] = handle.Array[handle.Offset + i];
handle.Array[handle.Offset + handle.Length - 1] = new CollectionTraceWithoutHeapIncrement();
if (handle.Array[handle.Offset].Weight == 0)
increments.Release(ref ol);
}
// important to update the cached accumulation to reflect the emptiness
// only do this if the cached accumulation is what we are working with
if (cachedIncrementOffset.offsetLength == ol.offsetLength)
{
cachedWeight = 0;
cachedIncrementOffset = ol;
cachedTimeIndex = timeIndex;
}
}
else
throw new Exception("Attemping subtraction from non-empty time; something wrong in Operator logic");
keyIndex = ol.offsetLength;
}
public void EnumerateCollectionAt(int offsetLength, int timeIndex, NaiadList<Weighted<S>> toFill)
{
if (toFill.Count == 0)
{
var temp = new OffsetLength(offsetLength);
var weight = UpdateAccumulation(ref temp, timeIndex);
if (weight != 0)
toFill.Add(new Weighted<S>(default(S), weight));
}
else
{
var temp = new OffsetLength(offsetLength);
var weight = UpdateAccumulation(ref temp, timeIndex);
toFill.Array[0].weight += weight;
if (toFill.Array[0].weight == 0)
toFill.Clear();
}
//throw new NotImplementedException();
}
// no caching at the moment; should do, but need to figure out how...
Int64 UpdateAccumulation(ref OffsetLength ol, int timeIndex)
{
#if true
if (ol.IsEmpty)
return 0;
var handle = increments.Dereference(ol);
// special-case single element accumulations to avoid unprocessed accumulation dropping processed accumulation
if (handle.Length == 1)
{
if (TimeLessThan(handle.Array[handle.Offset].TimeIndex, timeIndex))
return handle.Array[handle.Offset].Weight;
else
return 0;
}
else
#else
var handle = increments.Dereference(ol);
#endif
{
// if we have a hit on the cache ...
if (ol.offsetLength == cachedIncrementOffset.offsetLength)
{
for (int i = 0; i < handle.Length && !handle.Array[handle.Offset + i].IsEmpty; i++)
{
if (!handle.Array[handle.Offset + i].IsEmpty)
{
var inNew = TimeLessThan(handle.Array[handle.Offset + i].TimeIndex, timeIndex);
var inOld = TimeLessThan(handle.Array[handle.Offset + i].TimeIndex, cachedTimeIndex);
if (inOld != inNew)
cachedWeight += (inOld ? -1 : +1) * handle.Array[handle.Offset + i].Weight;
}
}
cachedTimeIndex = timeIndex;
}
else
{
ReleaseCache(); // blow cache away and start over
for (int i = 0; i < handle.Length && !handle.Array[handle.Offset + i].IsEmpty; i++)
if (TimeLessThan(handle.Array[handle.Offset + i].TimeIndex, timeIndex))
cachedWeight += handle.Array[handle.Offset + i].Weight;
cachedIncrementOffset = ol;
cachedTimeIndex = timeIndex;
}
return cachedWeight;
}
}
public void EnumerateDifferenceAt(int offsetLength, int timeIndex, NaiadList<Weighted<S>> toFill)
{
if (toFill.Count == 0)
{
var temp = new OffsetLength(offsetLength);
var weight = 0L;
var handle = increments.Dereference(temp);
for (int i = 0; i < handle.Length && !handle.Array[handle.Offset + i].IsEmpty; i++)
if (handle.Array[handle.Offset + i].TimeIndex == timeIndex)
weight += handle.Array[handle.Offset + i].Weight;
if (weight != 0)
toFill.Add(new Weighted<S>(default(S), weight));
}
else
{
var temp = new OffsetLength(offsetLength);
var weight = 0L;
var handle = increments.Dereference(temp);
for (int i = 0; i < handle.Length && !handle.Array[handle.Offset + i].IsEmpty; i++)
if (handle.Array[handle.Offset + i].TimeIndex == timeIndex)
weight += handle.Array[handle.Offset + i].Weight;
if (weight != 0)
toFill.Array[0].weight += weight;
if (toFill.Array[0].weight == 0)
toFill.Clear();
}
}
HashSet<int> hashSet = new HashSet<int>();
public void EnumerateTimes(int keyIndex, NaiadList<int> timelist)
{
var ol = new OffsetLength(keyIndex);
if (timelist.Count == 0)
{
var handle = increments.Dereference(ol);
for (int i = 0; i < handle.Length && !handle.Array[handle.Offset + i].IsEmpty; i++)
timelist.Add(handle.Array[handle.Offset + i].TimeIndex);
}
else
{
hashSet.Clear();
for (int i = 0; i < timelist.Count; i++)
hashSet.Add(timelist.Array[i]);
var handle = increments.Dereference(ol);
for (int i = 0; i < handle.Length && !handle.Array[handle.Offset + i].IsEmpty; i++)
{
var time = handle.Array[handle.Offset + i].TimeIndex;
if (!hashSet.Contains(time))
{
timelist.Add(time);
hashSet.Add(time);
}
}
}
}
public int AllocateState() { throw new NotImplementedException(); }
public void ReleaseState(ref int keyIndex)
{
var temp = new OffsetLength(keyIndex);
if (!temp.IsEmpty)
{
increments.Release(ref temp);
keyIndex = temp.offsetLength;
}
ReleaseCache();
}
public void ZeroState(ref int keyIndex)
{
ReleaseState(ref keyIndex);
}
public bool IsZero(ref int keyIndex) { return keyIndex == 0; }
public void EnsureStateIsCurrentWRTAdvancedTimes(ref int offsetLength)
{
var ol = new OffsetLength(offsetLength);
if (!ol.IsEmpty)
{
var handle = increments.Dereference(ol);
for (int i = 0; i < handle.Length; i++)
{
if (handle.Array[handle.Offset + i].Weight != 0)
{
handle.Array[handle.Offset + i].TimeIndex = UpdateTime(handle.Array[handle.Offset + i].TimeIndex);
for (int j = 0; j < i && !handle.Array[handle.Offset + i].IsEmpty; j++)
{
if (handle.Array[handle.Offset + j].TimeIndex == handle.Array[handle.Offset + i].TimeIndex)
{
handle.Array[handle.Offset + j].Weight += handle.Array[handle.Offset + i].Weight;
handle.Array[handle.Offset + i] = new CollectionTraceWithoutHeapIncrement();
}
}
}
}
var position = 0;
for (int i = 0; i < handle.Length; i++)
if (!handle.Array[handle.Offset + i].IsEmpty)
{
var temp = handle.Array[handle.Offset + i];
handle.Array[handle.Offset + i] = new CollectionTraceWithoutHeapIncrement();
handle.Array[handle.Offset + (position++)] = temp;
}
if (handle.Array[handle.Offset].IsEmpty)
increments.Release(ref ol);
offsetLength = ol.offsetLength;
}
}
public void Release() { }
public void Compact() { }
public void Checkpoint(NaiadWriter writer)
{
this.increments.Checkpoint(writer);
}
public void Restore(NaiadReader reader)
{
this.ReleaseCache();
this.increments.Restore(reader);
}
public bool Stateful { get { return true; } }
public CollectionTraceWithoutHeap(Func<int, int, bool> tCompare, Func<int, int> update)
{
TimeLessThan = tCompare;
UpdateTime = update;
increments = new VariableLengthHeap<CollectionTraceWithoutHeapIncrement>(32);
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace DotNetty.Buffers
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using DotNetty.Common.Internal;
using DotNetty.Common.Utilities;
enum SizeClass
{
Tiny,
Small,
Normal
}
abstract class PoolArena<T> : IPoolArenaMetric
{
internal const int NumTinySubpagePools = 512 >> 4;
internal readonly PooledByteBufferAllocator Parent;
readonly int maxOrder;
internal readonly int PageSize;
internal readonly int PageShifts;
internal readonly int ChunkSize;
internal readonly int SubpageOverflowMask;
internal readonly int NumSmallSubpagePools;
readonly PoolSubpage<T>[] tinySubpagePools;
readonly PoolSubpage<T>[] smallSubpagePools;
readonly PoolChunkList<T> q050;
readonly PoolChunkList<T> q025;
readonly PoolChunkList<T> q000;
readonly PoolChunkList<T> qInit;
readonly PoolChunkList<T> q075;
readonly PoolChunkList<T> q100;
readonly IReadOnlyList<IPoolChunkListMetric> chunkListMetrics;
// Metrics for allocations and deallocations
long allocationsNormal;
// We need to use the LongCounter here as this is not guarded via synchronized block.
long allocationsTiny;
long allocationsSmall;
long allocationsHuge;
long activeBytesHuge;
long deallocationsTiny;
long deallocationsSmall;
long deallocationsNormal;
// We need to use the LongCounter here as this is not guarded via synchronized block.
long deallocationsHuge;
// Number of thread caches backed by this arena.
int numThreadCaches;
// TODO: Test if adding padding helps under contention
//private long pad0, pad1, pad2, pad3, pad4, pad5, pad6, pad7;
protected PoolArena(
PooledByteBufferAllocator parent,
int pageSize,
int maxOrder,
int pageShifts,
int chunkSize)
{
this.Parent = parent;
this.PageSize = pageSize;
this.maxOrder = maxOrder;
this.PageShifts = pageShifts;
this.ChunkSize = chunkSize;
this.SubpageOverflowMask = ~(pageSize - 1);
this.tinySubpagePools = this.NewSubpagePoolArray(NumTinySubpagePools);
for (int i = 0; i < this.tinySubpagePools.Length; i++)
{
this.tinySubpagePools[i] = this.NewSubpagePoolHead(pageSize);
}
this.NumSmallSubpagePools = pageShifts - 9;
this.smallSubpagePools = this.NewSubpagePoolArray(this.NumSmallSubpagePools);
for (int i = 0; i < this.smallSubpagePools.Length; i++)
{
this.smallSubpagePools[i] = this.NewSubpagePoolHead(pageSize);
}
this.q100 = new PoolChunkList<T>(this, null, 100, int.MaxValue, chunkSize);
this.q075 = new PoolChunkList<T>(this, this.q100, 75, 100, chunkSize);
this.q050 = new PoolChunkList<T>(this, this.q075, 50, 100, chunkSize);
this.q025 = new PoolChunkList<T>(this, this.q050, 25, 75, chunkSize);
this.q000 = new PoolChunkList<T>(this, this.q025, 1, 50, chunkSize);
this.qInit = new PoolChunkList<T>(this, this.q000, int.MinValue, 25, chunkSize);
this.q100.PrevList(this.q075);
this.q075.PrevList(this.q050);
this.q050.PrevList(this.q025);
this.q025.PrevList(this.q000);
this.q000.PrevList(null);
this.qInit.PrevList(this.qInit);
var metrics = new List<IPoolChunkListMetric>(6);
metrics.Add(this.qInit);
metrics.Add(this.q000);
metrics.Add(this.q025);
metrics.Add(this.q050);
metrics.Add(this.q075);
metrics.Add(this.q100);
this.chunkListMetrics = metrics;
}
PoolSubpage<T> NewSubpagePoolHead(int pageSize)
{
var head = new PoolSubpage<T>(pageSize);
head.Prev = head;
head.Next = head;
return head;
}
PoolSubpage<T>[] NewSubpagePoolArray(int size) => new PoolSubpage<T>[size];
internal abstract bool IsDirect { get; }
internal PooledByteBuffer<T> Allocate(PoolThreadCache<T> cache, int reqCapacity, int maxCapacity)
{
PooledByteBuffer<T> buf = this.NewByteBuf(maxCapacity);
this.Allocate(cache, buf, reqCapacity);
return buf;
}
internal static int TinyIdx(int normCapacity) => normCapacity.RightUShift(4);
internal static int SmallIdx(int normCapacity)
{
int tableIdx = 0;
int i = normCapacity.RightUShift(10);
while (i != 0)
{
i = i.RightUShift(1);
tableIdx++;
}
return tableIdx;
}
// capacity < pageSize
internal bool IsTinyOrSmall(int normCapacity) => (normCapacity & this.SubpageOverflowMask) == 0;
// normCapacity < 512
internal static bool IsTiny(int normCapacity) => (normCapacity & 0xFFFFFE00) == 0;
void Allocate(PoolThreadCache<T> cache, PooledByteBuffer<T> buf, int reqCapacity)
{
int normCapacity = this.NormalizeCapacity(reqCapacity);
if (this.IsTinyOrSmall(normCapacity))
{
// capacity < pageSize
int tableIdx;
PoolSubpage<T>[] table;
bool tiny = IsTiny(normCapacity);
if (tiny)
{
// < 512
if (cache.AllocateTiny(this, buf, reqCapacity, normCapacity))
{
// was able to allocate out of the cache so move on
return;
}
tableIdx = TinyIdx(normCapacity);
table = this.tinySubpagePools;
}
else
{
if (cache.AllocateSmall(this, buf, reqCapacity, normCapacity))
{
// was able to allocate out of the cache so move on
return;
}
tableIdx = SmallIdx(normCapacity);
table = this.smallSubpagePools;
}
PoolSubpage<T> head = table[tableIdx];
//
// Synchronize on the head. This is needed as {@link PoolSubpage#allocate()} and
// {@link PoolSubpage#free(int)} may modify the doubly linked list as well.
//
lock (head)
{
PoolSubpage<T> s = head.Next;
if (s != head)
{
Debug.Assert(s.DoNotDestroy && s.ElemSize == normCapacity);
long handle = s.Allocate();
Debug.Assert(handle >= 0);
s.Chunk.InitBufWithSubpage(buf, handle, reqCapacity);
this.IncTinySmallAllocation(tiny);
return;
}
}
lock (this)
{
this.AllocateNormal(buf, reqCapacity, normCapacity);
}
this.IncTinySmallAllocation(tiny);
return;
}
if (normCapacity <= this.ChunkSize)
{
if (cache.AllocateNormal(this, buf, reqCapacity, normCapacity))
{
// was able to allocate out of the cache so move on
return;
}
lock (this)
{
this.AllocateNormal(buf, reqCapacity, normCapacity);
this.allocationsNormal++;
}
}
else
{
// Huge allocations are never served via the cache so just call allocateHuge
this.AllocateHuge(buf, reqCapacity);
}
}
void AllocateNormal(PooledByteBuffer<T> buf, int reqCapacity, int normCapacity)
{
if (this.q050.Allocate(buf, reqCapacity, normCapacity) || this.q025.Allocate(buf, reqCapacity, normCapacity)
|| this.q000.Allocate(buf, reqCapacity, normCapacity) || this.qInit.Allocate(buf, reqCapacity, normCapacity)
|| this.q075.Allocate(buf, reqCapacity, normCapacity))
{
return;
}
// Add a new chunk.
PoolChunk<T> c = this.NewChunk(this.PageSize, this.maxOrder, this.PageShifts, this.ChunkSize);
long handle = c.Allocate(normCapacity);
Debug.Assert(handle > 0);
c.InitBuf(buf, handle, reqCapacity);
this.qInit.Add(c);
}
void IncTinySmallAllocation(bool tiny)
{
if (tiny)
{
Interlocked.Increment(ref this.allocationsTiny);
}
else
{
Interlocked.Increment(ref this.allocationsSmall);
}
}
void AllocateHuge(PooledByteBuffer<T> buf, int reqCapacity)
{
PoolChunk<T> chunk = this.NewUnpooledChunk(reqCapacity);
Interlocked.Add(ref this.activeBytesHuge, chunk.ChunkSize);
buf.InitUnpooled(chunk, reqCapacity);
Interlocked.Increment(ref this.allocationsHuge);
}
internal void Free(PoolChunk<T> chunk, long handle, int normCapacity, PoolThreadCache<T> cache)
{
if (chunk.Unpooled)
{
int size = chunk.ChunkSize;
this.DestroyChunk(chunk);
Interlocked.Add(ref this.activeBytesHuge, -size);
Interlocked.Increment(ref this.deallocationsHuge);
}
else
{
SizeClass sizeClass = this.SizeClass(normCapacity);
if (cache != null && cache.Add(this, chunk, handle, normCapacity, sizeClass))
{
// cached so not free it.
return;
}
this.FreeChunk(chunk, handle, sizeClass);
}
}
SizeClass SizeClass(int normCapacity)
{
if (!this.IsTinyOrSmall(normCapacity))
{
return Buffers.SizeClass.Normal;
}
return IsTiny(normCapacity) ? Buffers.SizeClass.Tiny : Buffers.SizeClass.Small;
}
internal void FreeChunk(PoolChunk<T> chunk, long handle, SizeClass sizeClass)
{
bool destroyChunk;
lock (this)
{
switch (sizeClass)
{
case Buffers.SizeClass.Normal:
++this.deallocationsNormal;
break;
case Buffers.SizeClass.Small:
++this.deallocationsSmall;
break;
case Buffers.SizeClass.Tiny:
++this.deallocationsTiny;
break;
default:
throw new ArgumentOutOfRangeException();
}
destroyChunk = !chunk.Parent.Free(chunk, handle);
}
if (destroyChunk)
{
// destroyChunk not need to be called while holding the synchronized lock.
this.DestroyChunk(chunk);
}
}
internal PoolSubpage<T> FindSubpagePoolHead(int elemSize)
{
int tableIdx;
PoolSubpage<T>[] table;
if (IsTiny(elemSize))
{
// < 512
tableIdx = elemSize.RightUShift(4);
table = this.tinySubpagePools;
}
else
{
tableIdx = 0;
elemSize = elemSize.RightUShift(10);
while (elemSize != 0)
{
elemSize = elemSize.RightUShift(1);
tableIdx++;
}
table = this.smallSubpagePools;
}
return table[tableIdx];
}
internal int NormalizeCapacity(int reqCapacity)
{
Contract.Requires(reqCapacity >= 0 && reqCapacity >= this.ChunkSize);
if (reqCapacity >= this.ChunkSize)
{
return reqCapacity;
}
if (!IsTiny(reqCapacity))
{
// >= 512
// Doubled
int normalizedCapacity = reqCapacity;
normalizedCapacity--;
normalizedCapacity |= normalizedCapacity.RightUShift(1);
normalizedCapacity |= normalizedCapacity.RightUShift(2);
normalizedCapacity |= normalizedCapacity.RightUShift(4);
normalizedCapacity |= normalizedCapacity.RightUShift(8);
normalizedCapacity |= normalizedCapacity.RightUShift(16);
normalizedCapacity++;
if (normalizedCapacity < 0)
{
normalizedCapacity = normalizedCapacity.RightUShift(1);
}
return normalizedCapacity;
}
// Quantum-spaced
if ((reqCapacity & 15) == 0)
{
return reqCapacity;
}
return (reqCapacity & ~15) + 16;
}
internal void Reallocate(PooledByteBuffer<T> buf, int newCapacity, bool freeOldMemory)
{
Contract.Requires(newCapacity >= 0 && newCapacity <= buf.MaxCapacity);
int oldCapacity = buf.Length;
if (oldCapacity == newCapacity)
{
return;
}
PoolChunk<T> oldChunk = buf.Chunk;
long oldHandle = buf.Handle;
T oldMemory = buf.Memory;
int oldOffset = buf.Offset;
int oldMaxLength = buf.MaxLength;
int readerIndex = buf.ReaderIndex;
int writerIndex = buf.WriterIndex;
this.Allocate(this.Parent.ThreadCache<T>(), buf, newCapacity);
if (newCapacity > oldCapacity)
{
this.MemoryCopy(
oldMemory, oldOffset,
buf.Memory, buf.Offset, oldCapacity);
}
else if (newCapacity < oldCapacity)
{
if (readerIndex < newCapacity)
{
if (writerIndex > newCapacity)
{
writerIndex = newCapacity;
}
this.MemoryCopy(
oldMemory, oldOffset + readerIndex,
buf.Memory, buf.Offset + readerIndex, writerIndex - readerIndex);
}
else
{
readerIndex = writerIndex = newCapacity;
}
}
buf.SetIndex(readerIndex, writerIndex);
if (freeOldMemory)
{
this.Free(oldChunk, oldHandle, oldMaxLength, buf.Cache);
}
}
internal void IncrementNumThreadCaches() => Interlocked.Increment(ref this.numThreadCaches);
internal void DecrementNumThreadCaches() => Interlocked.Decrement(ref this.numThreadCaches);
public int NumThreadCaches => Volatile.Read(ref this.numThreadCaches);
public int NumTinySubpages => this.tinySubpagePools.Length;
public int NumSmallSubpages => this.smallSubpagePools.Length;
public int NumChunkLists => this.chunkListMetrics.Count;
public IReadOnlyList<IPoolSubpageMetric> TinySubpages => SubPageMetricList(this.tinySubpagePools);
public IReadOnlyList<IPoolSubpageMetric> SmallSubpages => SubPageMetricList(this.smallSubpagePools);
public IReadOnlyList<IPoolChunkListMetric> ChunkLists => this.chunkListMetrics;
static List<IPoolSubpageMetric> SubPageMetricList(PoolSubpage<T>[] pages)
{
var metrics = new List<IPoolSubpageMetric>();
foreach (PoolSubpage<T> head in pages)
{
if (head.Next == head)
{
continue;
}
PoolSubpage<T> s = head.Next;
for (; ; )
{
metrics.Add(s);
s = s.Next;
if (s == head)
{
break;
}
}
}
return metrics;
}
public long NumAllocations
{
get
{
long allocsNormal;
lock (this)
{
allocsNormal = this.allocationsNormal;
}
return this.NumTinyAllocations + this.NumSmallAllocations + allocsNormal + this.NumHugeAllocations;
}
}
public long NumTinyAllocations => Volatile.Read(ref this.allocationsTiny);
public long NumSmallAllocations => Volatile.Read(ref this.allocationsSmall);
public long NumNormalAllocations => Volatile.Read(ref this.allocationsNormal);
public long NumDeallocations
{
get
{
long deallocs;
lock (this)
{
deallocs = this.deallocationsTiny + this.deallocationsSmall + this.deallocationsNormal;
}
return deallocs + this.NumHugeDeallocations;
}
}
public long NumTinyDeallocations => Volatile.Read(ref this.deallocationsTiny);
public long NumSmallDeallocations => Volatile.Read(ref this.deallocationsSmall);
public long NumNormalDeallocations => Volatile.Read(ref this.deallocationsNormal);
public long NumHugeAllocations => Volatile.Read(ref this.allocationsHuge);
public long NumHugeDeallocations => Volatile.Read(ref this.deallocationsHuge);
public long NumActiveAllocations
{
get
{
long val = this.NumTinyAllocations + this.NumSmallAllocations + this.NumHugeAllocations
- this.NumHugeDeallocations;
lock (this)
{
val += this.allocationsNormal - (this.deallocationsTiny + this.deallocationsSmall + this.deallocationsNormal);
}
return Math.Max(val, 0);
}
}
public long NumActiveTinyAllocations => Math.Max(this.NumTinyAllocations - this.NumTinyDeallocations, 0);
public long NumActiveSmallAllocations => Math.Max(this.NumSmallAllocations - this.NumSmallDeallocations, 0);
public long NumActiveNormalAllocations
{
get
{
long val;
lock (this)
{
val = this.allocationsNormal - this.deallocationsNormal;
}
return Math.Max(val, 0);
}
}
public long NumActiveHugeAllocations => Math.Max(this.NumHugeAllocations - this.NumHugeDeallocations, 0);
public long NumActiveBytes
{
get
{
long val = Volatile.Read(ref this.activeBytesHuge);
lock (this)
{
foreach (IPoolChunkListMetric t in this.chunkListMetrics)
{
foreach (IPoolChunkMetric m in t)
{
val += m.ChunkSize;
}
}
}
return Math.Max(0, val);
}
}
protected abstract PoolChunk<T> NewChunk(int pageSize, int maxOrder, int pageShifts, int chunkSize);
protected abstract PoolChunk<T> NewUnpooledChunk(int capacity);
protected abstract PooledByteBuffer<T> NewByteBuf(int maxCapacity);
protected abstract void MemoryCopy(T src, int srcOffset, T dst, int dstOffset, int length);
protected internal abstract void DestroyChunk(PoolChunk<T> chunk);
public override string ToString()
{
StringBuilder buf = new StringBuilder()
.Append("Chunk(s) at 0~25%:")
.Append(StringUtil.Newline)
.Append(this.qInit)
.Append(StringUtil.Newline)
.Append("Chunk(s) at 0~50%:")
.Append(StringUtil.Newline)
.Append(this.q000)
.Append(StringUtil.Newline)
.Append("Chunk(s) at 25~75%:")
.Append(StringUtil.Newline)
.Append(this.q025)
.Append(StringUtil.Newline)
.Append("Chunk(s) at 50~100%:")
.Append(StringUtil.Newline)
.Append(this.q050)
.Append(StringUtil.Newline)
.Append("Chunk(s) at 75~100%:")
.Append(StringUtil.Newline)
.Append(this.q075)
.Append(StringUtil.Newline)
.Append("Chunk(s) at 100%:")
.Append(StringUtil.Newline)
.Append(this.q100)
.Append(StringUtil.Newline)
.Append("tiny subpages:");
AppendPoolSubPages(buf, this.tinySubpagePools);
buf.Append(StringUtil.Newline)
.Append("small subpages:");
AppendPoolSubPages(buf, this.smallSubpagePools);
buf.Append(StringUtil.Newline);
return buf.ToString();
}
static void AppendPoolSubPages(StringBuilder buf, PoolSubpage<T>[] subpages)
{
for (int i = 0; i < subpages.Length; i++)
{
PoolSubpage<T> head = subpages[i];
if (head.Next == head)
{
continue;
}
buf.Append(StringUtil.Newline)
.Append(i)
.Append(": ");
PoolSubpage<T> s = head.Next;
for (; ;)
{
buf.Append(s);
s = s.Next;
if (s == head)
{
break;
}
}
}
}
~PoolArena()
{
DestroyPoolSubPages(this.smallSubpagePools);
DestroyPoolSubPages(this.tinySubpagePools);
this.DestroyPoolChunkLists(this.qInit, this.q000, this.q025, this.q050, this.q075, this.q100);
}
static void DestroyPoolSubPages(PoolSubpage<T>[] pages)
{
foreach (PoolSubpage<T> page in pages)
{
page.Destroy();
}
}
void DestroyPoolChunkLists(params PoolChunkList<T>[] chunkLists)
{
foreach (PoolChunkList<T> chunkList in chunkLists)
{
chunkList.Destroy(this);
}
}
}
sealed class HeapArena : PoolArena<byte[]>
{
public HeapArena(PooledByteBufferAllocator parent, int pageSize, int maxOrder, int pageShifts, int chunkSize)
: base(parent, pageSize, maxOrder, pageShifts, chunkSize)
{
}
static byte[] NewByteArray(int size) => new byte[size];
internal override bool IsDirect => false;
protected override PoolChunk<byte[]> NewChunk(int pageSize, int maxOrder, int pageShifts, int chunkSize) =>
new PoolChunk<byte[]>(this, NewByteArray(chunkSize), pageSize, maxOrder, pageShifts, chunkSize, 0);
protected override PoolChunk<byte[]> NewUnpooledChunk(int capacity) =>
new PoolChunk<byte[]>(this, NewByteArray(capacity), capacity, 0);
protected internal override void DestroyChunk(PoolChunk<byte[]> chunk)
{
// Rely on GC.
}
protected override PooledByteBuffer<byte[]> NewByteBuf(int maxCapacity) =>
PooledHeapByteBuffer.NewInstance(maxCapacity);
protected override void MemoryCopy(byte[] src, int srcOffset, byte[] dst, int dstOffset, int length)
{
if (length == 0)
{
return;
}
PlatformDependent.CopyMemory(src, srcOffset, dst, dstOffset, length);
}
}
//TODO: Maybe use Memory or OwnedMemory as direct arena/byte buffer type parameter in NETStandard 2.0
sealed class DirectArena : PoolArena<byte[]>
{
readonly List<MemoryChunk> memoryChunks;
public DirectArena(PooledByteBufferAllocator parent, int pageSize, int maxOrder, int pageShifts, int chunkSize)
: base(parent, pageSize, maxOrder, pageShifts, chunkSize)
{
this.memoryChunks = new List<MemoryChunk>();
}
static MemoryChunk NewMemoryChunk(int size) => new MemoryChunk(size);
internal override bool IsDirect => true;
protected override PoolChunk<byte[]> NewChunk(int pageSize, int maxOrder, int pageShifts, int chunkSize)
{
MemoryChunk memoryChunk = NewMemoryChunk(chunkSize);
this.memoryChunks.Add(memoryChunk);
var chunk = new PoolChunk<byte[]>(this, memoryChunk.Bytes, pageSize, maxOrder, pageShifts, chunkSize, 0);
return chunk;
}
protected override PoolChunk<byte[]> NewUnpooledChunk(int capacity)
{
MemoryChunk memoryChunk = NewMemoryChunk(capacity);
this.memoryChunks.Add(memoryChunk);
var chunk = new PoolChunk<byte[]>(this, memoryChunk.Bytes, capacity, 0);
return chunk;
}
protected override PooledByteBuffer<byte[]> NewByteBuf(int maxCapacity) =>
PooledUnsafeDirectByteBuffer.NewInstance(maxCapacity);
protected override unsafe void MemoryCopy(byte[] src, int srcOffset, byte[] dst, int dstOffset, int length) =>
PlatformDependent.CopyMemory((byte*)Unsafe.AsPointer(ref src[srcOffset]), (byte*)Unsafe.AsPointer(ref dst[dstOffset]), length);
protected internal override void DestroyChunk(PoolChunk<byte[]> chunk)
{
for (int i = 0; i < this.memoryChunks.Count; i++)
{
MemoryChunk memoryChunk = this.memoryChunks[i];
if (ReferenceEquals(chunk.Memory, memoryChunk.Bytes))
{
this.memoryChunks.Remove(memoryChunk);
memoryChunk.Dispose();
break;
}
}
}
sealed class MemoryChunk : IDisposable
{
internal byte[] Bytes;
GCHandle handle;
internal MemoryChunk(int size)
{
this.Bytes = new byte[size];
this.handle = GCHandle.Alloc(this.Bytes, GCHandleType.Pinned);
}
void Release()
{
if (this.handle.IsAllocated)
{
try
{
this.handle.Free();
}
catch (InvalidOperationException)
{
// Free is not thread safe
}
}
this.Bytes = null;
}
public void Dispose()
{
this.Release();
GC.SuppressFinalize(this);
}
~MemoryChunk()
{
this.Release();
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
namespace Lucene.Net.Index
{
using Lucene.Net.Support;
using InfoStream = Lucene.Net.Util.InfoStream;
/*
* 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 ThreadState = Lucene.Net.Index.DocumentsWriterPerThreadPool.ThreadState;
/// <summary>
/// this class controls <seealso cref="DocumentsWriterPerThread"/> flushing during
/// indexing. It tracks the memory consumption per
/// <seealso cref="DocumentsWriterPerThread"/> and uses a configured <seealso cref="FlushPolicy"/> to
/// decide if a <seealso cref="DocumentsWriterPerThread"/> must flush.
/// <p>
/// In addition to the <seealso cref="FlushPolicy"/> the flush control might set certain
/// <seealso cref="DocumentsWriterPerThread"/> as flush pending iff a
/// <seealso cref="DocumentsWriterPerThread"/> exceeds the
/// <seealso cref="IndexWriterConfig#getRAMPerThreadHardLimitMB()"/> to prevent address
/// space exhaustion.
/// </summary>
public sealed class DocumentsWriterFlushControl
{
private readonly long HardMaxBytesPerDWPT;
private long ActiveBytes_Renamed = 0;
private long FlushBytes_Renamed = 0;
private volatile int NumPending = 0;
private int NumDocsSinceStalled = 0; // only with assert
internal readonly AtomicBoolean FlushDeletes = new AtomicBoolean(false);
private bool FullFlush_Renamed = false;
private readonly Queue<DocumentsWriterPerThread> FlushQueue = new Queue<DocumentsWriterPerThread>();
// only for safety reasons if a DWPT is close to the RAM limit
private readonly LinkedList<BlockedFlush> BlockedFlushes = new LinkedList<BlockedFlush>();
private readonly IdentityHashMap<DocumentsWriterPerThread, long?> FlushingWriters = new IdentityHashMap<DocumentsWriterPerThread, long?>();
internal double MaxConfiguredRamBuffer = 0;
internal long PeakActiveBytes = 0; // only with assert
internal long PeakFlushBytes = 0; // only with assert
internal long PeakNetBytes = 0; // only with assert
internal long PeakDelta = 0; // only with assert
internal readonly DocumentsWriterStallControl StallControl;
private readonly DocumentsWriterPerThreadPool PerThreadPool;
private readonly FlushPolicy FlushPolicy;
private bool Closed = false;
private readonly DocumentsWriter DocumentsWriter;
private readonly LiveIndexWriterConfig Config;
private readonly BufferedUpdatesStream BufferedUpdatesStream;
private readonly InfoStream InfoStream_Renamed;
internal DocumentsWriterFlushControl(DocumentsWriter documentsWriter, LiveIndexWriterConfig config, BufferedUpdatesStream bufferedUpdatesStream)
{
this.InfoStream_Renamed = config.InfoStream;
this.StallControl = new DocumentsWriterStallControl();
this.PerThreadPool = documentsWriter.PerThreadPool;
this.FlushPolicy = documentsWriter.FlushPolicy;
this.Config = config;
this.HardMaxBytesPerDWPT = config.RAMPerThreadHardLimitMB * 1024 * 1024;
this.DocumentsWriter = documentsWriter;
this.BufferedUpdatesStream = bufferedUpdatesStream;
}
public long ActiveBytes()
{
lock (this)
{
return ActiveBytes_Renamed;
}
}
public long FlushBytes()
{
lock (this)
{
return FlushBytes_Renamed;
}
}
public long NetBytes()
{
lock (this)
{
return FlushBytes_Renamed + ActiveBytes_Renamed;
}
}
private long StallLimitBytes()
{
double maxRamMB = Config.RAMBufferSizeMB;
return maxRamMB != IndexWriterConfig.DISABLE_AUTO_FLUSH ? (long)(2 * (maxRamMB * 1024 * 1024)) : long.MaxValue;
}
private bool AssertMemory()
{
double maxRamMB = Config.RAMBufferSizeMB;
if (maxRamMB != IndexWriterConfig.DISABLE_AUTO_FLUSH)
{
// for this assert we must be tolerant to ram buffer changes!
MaxConfiguredRamBuffer = Math.Max(maxRamMB, MaxConfiguredRamBuffer);
long ram = FlushBytes_Renamed + ActiveBytes_Renamed;
long ramBufferBytes = (long)(MaxConfiguredRamBuffer * 1024 * 1024);
// take peakDelta into account - worst case is that all flushing, pending and blocked DWPT had maxMem and the last doc had the peakDelta
// 2 * ramBufferBytes -> before we stall we need to cross the 2xRAM Buffer border this is still a valid limit
// (numPending + numFlushingDWPT() + numBlockedFlushes()) * peakDelta) -> those are the total number of DWPT that are not active but not yet fully fluhsed
// all of them could theoretically be taken out of the loop once they crossed the RAM buffer and the last document was the peak delta
// (numDocsSinceStalled * peakDelta) -> at any given time there could be n threads in flight that crossed the stall control before we reached the limit and each of them could hold a peak document
long expected = (2 * (ramBufferBytes)) + ((NumPending + NumFlushingDWPT() + NumBlockedFlushes()) * PeakDelta) + (NumDocsSinceStalled * PeakDelta);
// the expected ram consumption is an upper bound at this point and not really the expected consumption
if (PeakDelta < (ramBufferBytes >> 1))
{
/*
* if we are indexing with very low maxRamBuffer like 0.1MB memory can
* easily overflow if we check out some DWPT based on docCount and have
* several DWPT in flight indexing large documents (compared to the ram
* buffer). this means that those DWPT and their threads will not hit
* the stall control before asserting the memory which would in turn
* fail. To prevent this we only assert if the the largest document seen
* is smaller than the 1/2 of the maxRamBufferMB
*/
Debug.Assert(ram <= expected, "actual mem: " + ram + " byte, expected mem: " + expected + " byte, flush mem: " + FlushBytes_Renamed + ", active mem: " + ActiveBytes_Renamed + ", pending DWPT: " + NumPending + ", flushing DWPT: " + NumFlushingDWPT() + ", blocked DWPT: " + NumBlockedFlushes() + ", peakDelta mem: " + PeakDelta + " byte");
}
}
return true;
}
private void CommitPerThreadBytes(ThreadState perThread)
{
long delta = perThread.Dwpt.BytesUsed() - perThread.BytesUsed;
perThread.BytesUsed += delta;
/*
* We need to differentiate here if we are pending since setFlushPending
* moves the perThread memory to the flushBytes and we could be set to
* pending during a delete
*/
if (perThread.FlushPending_Renamed)
{
FlushBytes_Renamed += delta;
}
else
{
ActiveBytes_Renamed += delta;
}
Debug.Assert(UpdatePeaks(delta));
}
// only for asserts
private bool UpdatePeaks(long delta)
{
PeakActiveBytes = Math.Max(PeakActiveBytes, ActiveBytes_Renamed);
PeakFlushBytes = Math.Max(PeakFlushBytes, FlushBytes_Renamed);
PeakNetBytes = Math.Max(PeakNetBytes, NetBytes());
PeakDelta = Math.Max(PeakDelta, delta);
return true;
}
internal DocumentsWriterPerThread DoAfterDocument(ThreadState perThread, bool isUpdate)
{
lock (this)
{
try
{
CommitPerThreadBytes(perThread);
if (!perThread.FlushPending_Renamed)
{
if (isUpdate)
{
FlushPolicy.OnUpdate(this, perThread);
}
else
{
FlushPolicy.OnInsert(this, perThread);
}
if (!perThread.FlushPending_Renamed && perThread.BytesUsed > HardMaxBytesPerDWPT)
{
// Safety check to prevent a single DWPT exceeding its RAM limit. this
// is super important since we can not address more than 2048 MB per DWPT
FlushPending = perThread;
}
}
DocumentsWriterPerThread flushingDWPT;
if (FullFlush_Renamed)
{
if (perThread.FlushPending_Renamed)
{
CheckoutAndBlock(perThread);
flushingDWPT = NextPendingFlush();
}
else
{
flushingDWPT = null;
}
}
else
{
flushingDWPT = TryCheckoutForFlush(perThread);
}
return flushingDWPT;
}
finally
{
bool stalled = UpdateStallState();
Debug.Assert(AssertNumDocsSinceStalled(stalled) && AssertMemory());
}
}
}
private bool AssertNumDocsSinceStalled(bool stalled)
{
/*
* updates the number of documents "finished" while we are in a stalled state.
* this is important for asserting memory upper bounds since it corresponds
* to the number of threads that are in-flight and crossed the stall control
* check before we actually stalled.
* see #assertMemory()
*/
if (stalled)
{
NumDocsSinceStalled++;
}
else
{
NumDocsSinceStalled = 0;
}
return true;
}
internal void DoAfterFlush(DocumentsWriterPerThread dwpt)
{
lock (this)
{
Debug.Assert(FlushingWriters.ContainsKey(dwpt));
try
{
long? bytes = FlushingWriters[dwpt];
FlushingWriters.Remove(dwpt);
FlushBytes_Renamed -= (long)bytes;
PerThreadPool.Recycle(dwpt);
Debug.Assert(AssertMemory());
}
finally
{
try
{
UpdateStallState();
}
finally
{
Monitor.PulseAll(this);
}
}
}
}
private bool UpdateStallState()
{
//Debug.Assert(Thread.holdsLock(this));
long limit = StallLimitBytes();
/*
* we block indexing threads if net byte grows due to slow flushes
* yet, for small ram buffers and large documents we can easily
* reach the limit without any ongoing flushes. we need to ensure
* that we don't stall/block if an ongoing or pending flush can
* not free up enough memory to release the stall lock.
*/
bool stall = ((ActiveBytes_Renamed + FlushBytes_Renamed) > limit) && (ActiveBytes_Renamed < limit) && !Closed;
StallControl.UpdateStalled(stall);
return stall;
}
public void WaitForFlush()
{
lock (this)
{
while (FlushingWriters.Count != 0)
{
try
{
Monitor.Wait(this);
}
catch (ThreadInterruptedException e)
{
throw new ThreadInterruptedException("Thread Interrupted Exception", e);
}
}
}
}
/// <summary>
/// Sets flush pending state on the given <seealso cref="ThreadState"/>. The
/// <seealso cref="ThreadState"/> must have indexed at least on Document and must not be
/// already pending.
/// </summary>
public ThreadState FlushPending
{
set
{
lock (this)
{
Debug.Assert(!value.FlushPending_Renamed);
if (value.Dwpt.NumDocsInRAM > 0)
{
value.FlushPending_Renamed = true; // write access synced
long bytes = value.BytesUsed;
FlushBytes_Renamed += bytes;
ActiveBytes_Renamed -= bytes;
NumPending++; // write access synced
Debug.Assert(AssertMemory());
} // don't assert on numDocs since we could hit an abort excp. while selecting that dwpt for flushing
}
}
}
internal void DoOnAbort(ThreadState state)
{
lock (this)
{
try
{
if (state.FlushPending_Renamed)
{
FlushBytes_Renamed -= state.BytesUsed;
}
else
{
ActiveBytes_Renamed -= state.BytesUsed;
}
Debug.Assert(AssertMemory());
// Take it out of the loop this DWPT is stale
PerThreadPool.Reset(state, Closed);
}
finally
{
UpdateStallState();
}
}
}
internal DocumentsWriterPerThread TryCheckoutForFlush(ThreadState perThread)
{
lock (this)
{
return perThread.FlushPending_Renamed ? InternalTryCheckOutForFlush(perThread) : null;
}
}
private void CheckoutAndBlock(ThreadState perThread)
{
perThread.@Lock();
try
{
Debug.Assert(perThread.FlushPending_Renamed, "can not block non-pending threadstate");
Debug.Assert(FullFlush_Renamed, "can not block if fullFlush == false");
DocumentsWriterPerThread dwpt;
long bytes = perThread.BytesUsed;
dwpt = PerThreadPool.Reset(perThread, Closed);
NumPending--;
BlockedFlushes.AddLast(new BlockedFlush(dwpt, bytes));
}
finally
{
perThread.Unlock();
}
}
private DocumentsWriterPerThread InternalTryCheckOutForFlush(ThreadState perThread)
{
//Debug.Assert(Thread.HoldsLock(this));
Debug.Assert(perThread.FlushPending_Renamed);
try
{
// We are pending so all memory is already moved to flushBytes
if (perThread.TryLock())
{
try
{
if (perThread.Initialized)
{
//Debug.Assert(perThread.HeldByCurrentThread);
DocumentsWriterPerThread dwpt;
long bytes = perThread.BytesUsed; // do that before
// replace!
dwpt = PerThreadPool.Reset(perThread, Closed);
Debug.Assert(!FlushingWriters.ContainsKey(dwpt), "DWPT is already flushing");
// Record the flushing DWPT to reduce flushBytes in doAfterFlush
FlushingWriters[dwpt] = Convert.ToInt64(bytes);
NumPending--; // write access synced
return dwpt;
}
}
finally
{
perThread.Unlock();
}
}
return null;
}
finally
{
UpdateStallState();
}
}
public override string ToString()
{
return "DocumentsWriterFlushControl [activeBytes=" + ActiveBytes_Renamed + ", flushBytes=" + FlushBytes_Renamed + "]";
}
internal DocumentsWriterPerThread NextPendingFlush()
{
int numPending;
bool fullFlush;
lock (this)
{
DocumentsWriterPerThread poll;
if (FlushQueue.Count > 0 && (poll = FlushQueue.Dequeue()) != null)
{
UpdateStallState();
return poll;
}
fullFlush = this.FullFlush_Renamed;
numPending = this.NumPending;
}
if (numPending > 0 && !fullFlush) // don't check if we are doing a full flush
{
int limit = PerThreadPool.ActiveThreadState;
for (int i = 0; i < limit && numPending > 0; i++)
{
ThreadState next = PerThreadPool.GetThreadState(i);
if (next.FlushPending_Renamed)
{
DocumentsWriterPerThread dwpt = TryCheckoutForFlush(next);
if (dwpt != null)
{
return dwpt;
}
}
}
}
return null;
}
internal void SetClosed()
{
lock (this)
{
// set by DW to signal that we should not release new DWPT after close
if (!Closed)
{
this.Closed = true;
PerThreadPool.DeactivateUnreleasedStates();
}
}
}
/// <summary>
/// Returns an iterator that provides access to all currently active <seealso cref="ThreadState"/>s
/// </summary>
public IEnumerator<ThreadState> AllActiveThreadStates()
{
return GetPerThreadsIterator(PerThreadPool.ActiveThreadState);
}
private IEnumerator<ThreadState> GetPerThreadsIterator(int upto)
{
return new IteratorAnonymousInnerClassHelper(this, upto);
}
private class IteratorAnonymousInnerClassHelper : IEnumerator<ThreadState>
{
private readonly DocumentsWriterFlushControl OuterInstance;
private ThreadState current;
private int Upto;
private int i;
public IteratorAnonymousInnerClassHelper(DocumentsWriterFlushControl outerInstance, int upto)
{
this.OuterInstance = outerInstance;
this.Upto = upto;
i = 0;
}
public ThreadState Current
{
get { return current; }
}
public void Dispose()
{
}
object System.Collections.IEnumerator.Current
{
get { return Current; }
}
public bool MoveNext()
{
if (i < Upto)
{
current = OuterInstance.PerThreadPool.GetThreadState(i++);
return true;
}
return false;
}
public void Reset()
{
throw new NotImplementedException();
}
}
internal void DoOnDelete()
{
lock (this)
{
// pass null this is a global delete no update
FlushPolicy.OnDelete(this, null);
}
}
/// <summary>
/// Returns the number of delete terms in the global pool
/// </summary>
public int NumGlobalTermDeletes
{
get
{
return DocumentsWriter.DeleteQueue.NumGlobalTermDeletes() + BufferedUpdatesStream.NumTerms();
}
}
public long DeleteBytesUsed
{
get
{
return DocumentsWriter.DeleteQueue.BytesUsed() + BufferedUpdatesStream.BytesUsed();
}
}
internal int NumFlushingDWPT()
{
lock (this)
{
return FlushingWriters.Count;
}
}
public bool AndResetApplyAllDeletes
{
get
{
return FlushDeletes.GetAndSet(false);
}
}
public void SetApplyAllDeletes()
{
FlushDeletes.Set(true);
}
internal int NumActiveDWPT()
{
return this.PerThreadPool.ActiveThreadState;
}
internal ThreadState ObtainAndLock()
{
ThreadState perThread = PerThreadPool.GetAndLock(Thread.CurrentThread, DocumentsWriter);
bool success = false;
try
{
if (perThread.Initialized && perThread.Dwpt.DeleteQueue != DocumentsWriter.DeleteQueue)
{
// There is a flush-all in process and this DWPT is
// now stale -- enroll it for flush and try for
// another DWPT:
AddFlushableState(perThread);
}
success = true;
// simply return the ThreadState even in a flush all case sine we already hold the lock
return perThread;
}
finally
{
if (!success) // make sure we unlock if this fails
{
perThread.Unlock();
}
}
}
internal void MarkForFullFlush()
{
DocumentsWriterDeleteQueue flushingQueue;
lock (this)
{
Debug.Assert(!FullFlush_Renamed, "called DWFC#markForFullFlush() while full flush is still running");
Debug.Assert(FullFlushBuffer.Count == 0, "full flush buffer should be empty: " + FullFlushBuffer);
FullFlush_Renamed = true;
flushingQueue = DocumentsWriter.DeleteQueue;
// Set a new delete queue - all subsequent DWPT will use this queue until
// we do another full flush
DocumentsWriterDeleteQueue newQueue = new DocumentsWriterDeleteQueue(flushingQueue.Generation + 1);
DocumentsWriter.DeleteQueue = newQueue;
}
int limit = PerThreadPool.ActiveThreadState;
for (int i = 0; i < limit; i++)
{
ThreadState next = PerThreadPool.GetThreadState(i);
next.@Lock();
try
{
if (!next.Initialized)
{
if (Closed && next.Active)
{
PerThreadPool.DeactivateThreadState(next);
}
continue;
}
Debug.Assert(next.Dwpt.DeleteQueue == flushingQueue || next.Dwpt.DeleteQueue == DocumentsWriter.DeleteQueue, " flushingQueue: " + flushingQueue + " currentqueue: " + DocumentsWriter.DeleteQueue + " perThread queue: " + next.Dwpt.DeleteQueue + " numDocsInRam: " + next.Dwpt.NumDocsInRAM);
if (next.Dwpt.DeleteQueue != flushingQueue)
{
// this one is already a new DWPT
continue;
}
AddFlushableState(next);
}
finally
{
next.Unlock();
}
}
lock (this)
{
/* make sure we move all DWPT that are where concurrently marked as
* pending and moved to blocked are moved over to the flushQueue. There is
* a chance that this happens since we marking DWPT for full flush without
* blocking indexing.*/
PruneBlockedQueue(flushingQueue);
Debug.Assert(AssertBlockedFlushes(DocumentsWriter.DeleteQueue));
//FlushQueue.AddAll(FullFlushBuffer);
foreach (var dwpt in FullFlushBuffer)
{
FlushQueue.Enqueue(dwpt);
}
FullFlushBuffer.Clear();
UpdateStallState();
}
Debug.Assert(AssertActiveDeleteQueue(DocumentsWriter.DeleteQueue));
}
private bool AssertActiveDeleteQueue(DocumentsWriterDeleteQueue queue)
{
int limit = PerThreadPool.ActiveThreadState;
for (int i = 0; i < limit; i++)
{
ThreadState next = PerThreadPool.GetThreadState(i);
next.@Lock();
try
{
Debug.Assert(!next.Initialized || next.Dwpt.DeleteQueue == queue, "isInitialized: " + next.Initialized + " numDocs: " + (next.Initialized ? next.Dwpt.NumDocsInRAM : 0));
}
finally
{
next.Unlock();
}
}
return true;
}
private readonly IList<DocumentsWriterPerThread> FullFlushBuffer = new List<DocumentsWriterPerThread>();
internal void AddFlushableState(ThreadState perThread)
{
if (InfoStream_Renamed.IsEnabled("DWFC"))
{
InfoStream_Renamed.Message("DWFC", "addFlushableState " + perThread.Dwpt);
}
DocumentsWriterPerThread dwpt = perThread.Dwpt;
//Debug.Assert(perThread.HeldByCurrentThread);
Debug.Assert(perThread.Initialized);
Debug.Assert(FullFlush_Renamed);
Debug.Assert(dwpt.DeleteQueue != DocumentsWriter.DeleteQueue);
if (dwpt.NumDocsInRAM > 0)
{
lock (this)
{
if (!perThread.FlushPending_Renamed)
{
FlushPending = perThread;
}
DocumentsWriterPerThread flushingDWPT = InternalTryCheckOutForFlush(perThread);
Debug.Assert(flushingDWPT != null, "DWPT must never be null here since we hold the lock and it holds documents");
Debug.Assert(dwpt == flushingDWPT, "flushControl returned different DWPT");
FullFlushBuffer.Add(flushingDWPT);
}
}
else
{
PerThreadPool.Reset(perThread, Closed); // make this state inactive
}
}
/// <summary>
/// Prunes the blockedQueue by removing all DWPT that are associated with the given flush queue.
/// </summary>
private void PruneBlockedQueue(DocumentsWriterDeleteQueue flushingQueue)
{
var node = BlockedFlushes.First;
while (node != null)
{
var nextNode = node.Next;
BlockedFlush blockedFlush = node.Value;
if (blockedFlush.Dwpt.DeleteQueue == flushingQueue)
{
BlockedFlushes.Remove(node);
Debug.Assert(!FlushingWriters.ContainsKey(blockedFlush.Dwpt), "DWPT is already flushing");
// Record the flushing DWPT to reduce flushBytes in doAfterFlush
FlushingWriters[blockedFlush.Dwpt] = Convert.ToInt64(blockedFlush.Bytes);
// don't decr pending here - its already done when DWPT is blocked
FlushQueue.Enqueue(blockedFlush.Dwpt);
}
node = nextNode;
}
}
internal void FinishFullFlush()
{
lock (this)
{
Debug.Assert(FullFlush_Renamed);
Debug.Assert(FlushQueue.Count == 0);
Debug.Assert(FlushingWriters.Count == 0);
try
{
if (BlockedFlushes.Count > 0)
{
Debug.Assert(AssertBlockedFlushes(DocumentsWriter.DeleteQueue));
PruneBlockedQueue(DocumentsWriter.DeleteQueue);
Debug.Assert(BlockedFlushes.Count == 0);
}
}
finally
{
FullFlush_Renamed = false;
UpdateStallState();
}
}
}
internal bool AssertBlockedFlushes(DocumentsWriterDeleteQueue flushingQueue)
{
foreach (BlockedFlush blockedFlush in BlockedFlushes)
{
Debug.Assert(blockedFlush.Dwpt.DeleteQueue == flushingQueue);
}
return true;
}
internal void AbortFullFlushes(ISet<string> newFiles)
{
lock (this)
{
try
{
AbortPendingFlushes(newFiles);
}
finally
{
FullFlush_Renamed = false;
}
}
}
internal void AbortPendingFlushes(ISet<string> newFiles)
{
lock (this)
{
try
{
foreach (DocumentsWriterPerThread dwpt in FlushQueue)
{
try
{
DocumentsWriter.SubtractFlushedNumDocs(dwpt.NumDocsInRAM);
dwpt.Abort(newFiles);
}
catch (Exception)
{
// ignore - keep on aborting the flush queue
}
finally
{
DoAfterFlush(dwpt);
}
}
foreach (BlockedFlush blockedFlush in BlockedFlushes)
{
try
{
FlushingWriters[blockedFlush.Dwpt] = Convert.ToInt64(blockedFlush.Bytes);
DocumentsWriter.SubtractFlushedNumDocs(blockedFlush.Dwpt.NumDocsInRAM);
blockedFlush.Dwpt.Abort(newFiles);
}
catch (Exception)
{
// ignore - keep on aborting the blocked queue
}
finally
{
DoAfterFlush(blockedFlush.Dwpt);
}
}
}
finally
{
FlushQueue.Clear();
BlockedFlushes.Clear();
UpdateStallState();
}
}
}
/// <summary>
/// Returns <code>true</code> if a full flush is currently running
/// </summary>
internal bool FullFlush
{
get
{
lock (this)
{
return FullFlush_Renamed;
}
}
}
/// <summary>
/// Returns the number of flushes that are already checked out but not yet
/// actively flushing
/// </summary>
internal int NumQueuedFlushes()
{
lock (this)
{
return FlushQueue.Count;
}
}
/// <summary>
/// Returns the number of flushes that are checked out but not yet available
/// for flushing. this only applies during a full flush if a DWPT needs
/// flushing but must not be flushed until the full flush has finished.
/// </summary>
internal int NumBlockedFlushes()
{
lock (this)
{
return BlockedFlushes.Count;
}
}
private class BlockedFlush
{
internal readonly DocumentsWriterPerThread Dwpt;
internal readonly long Bytes;
internal BlockedFlush(DocumentsWriterPerThread dwpt, long bytes)
: base()
{
this.Dwpt = dwpt;
this.Bytes = bytes;
}
}
/// <summary>
/// this method will block if too many DWPT are currently flushing and no
/// checked out DWPT are available
/// </summary>
internal void WaitIfStalled()
{
if (InfoStream_Renamed.IsEnabled("DWFC"))
{
InfoStream_Renamed.Message("DWFC", "waitIfStalled: numFlushesPending: " + FlushQueue.Count + " netBytes: " + NetBytes() + " flushBytes: " + FlushBytes() + " fullFlush: " + FullFlush_Renamed);
}
StallControl.WaitIfStalled();
}
/// <summary>
/// Returns <code>true</code> iff stalled
/// </summary>
internal bool AnyStalledThreads()
{
return StallControl.AnyStalledThreads();
}
/// <summary>
/// Returns the <seealso cref="IndexWriter"/> <seealso cref="InfoStream"/>
/// </summary>
public InfoStream InfoStream
{
get
{
return InfoStream_Renamed;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text.RegularExpressions;
namespace AWSAppender.Core.Services
{
public abstract class EventMessageParserBase<TDatum> : IEventMessageParser<TDatum>
{
protected bool DefaultsOverridePattern;
private List<AppenderValue> _values;
protected EventMessageParserBase(bool useOverrides)
{
DefaultsOverridePattern = useOverrides;
}
protected bool ConfigOverrides { get { return DefaultsOverridePattern; } set { DefaultsOverridePattern = value; } }
protected abstract void ApplyDefaults();
protected abstract void NewDatum();
protected abstract bool FillName(AppenderValue value);
protected virtual void ParseTokens(ref List<Match>.Enumerator enumerator, string renderedMessage)
{
string name, sNum = string.Empty, rest = "";
int? jsonDepth = 0, ignoreBelow = null, includeAt = null;
var collectedTokens = new List<int>();
AppenderValue currentValue = null;
var matches = new List<Match>();
while (enumerator.MoveNext())
matches.Add(enumerator.Current);
var tokens = matches.GetEnumerator();
tokens.MoveNext();
while (tokens.Current != null)
{
if (!string.IsNullOrEmpty(tokens.Current.Groups["lbrace"].Value))
{
jsonDepth++;
tokens.MoveNext();
if (currentValue != null && includeAt == null)
includeAt = jsonDepth;
continue;
}
if (!string.IsNullOrEmpty(tokens.Current.Groups["rbrace"].Value))
{
jsonDepth--;
tokens.MoveNext();
if (currentValue != null && jsonDepth < includeAt)
{
includeAt = null;
_values.Add(currentValue);
currentValue = null;
}
continue;
}
if (ignoreBelow != null && jsonDepth > ignoreBelow)
{
tokens.MoveNext();
continue;
}
if (!string.IsNullOrEmpty(name = tokens.Current.Groups["name"].Value))
{
if (!IsSupportedName(name))
{
tokens.MoveNext();
ignoreBelow = jsonDepth;
continue;
}
collectedTokens.Add(tokens.Current.Index);
ignoreBelow = null;
if (currentValue != null && includeAt == null)
currentValue = null;
if (currentValue == null)
{
currentValue = NewAppenderValue();
currentValue.Name = name;
}
if (includeAt != null && (IsSupportedValueField(name) || name.Equals("value", StringComparison.OrdinalIgnoreCase)))
{
tokens.MoveNext();
sNum = string.IsNullOrEmpty(tokens.Current.Groups["float"].Value)
? tokens.Current.Groups["int"].Value
: tokens.Current.Groups["float"].Value;
var sValue = tokens.Current.Groups["word"].Value;
if (string.IsNullOrEmpty(sNum) && string.IsNullOrEmpty(sValue))
{
tokens.MoveNext();
continue;
}
double d;
if (!Double.TryParse(sNum, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out d))
{
if (string.IsNullOrEmpty(sValue))
{
tokens.MoveNext();
continue;
}
Double.TryParse(sValue.Trim("\" ".ToCharArray()), NumberStyles.AllowDecimalPoint,
CultureInfo.InvariantCulture, out d);
}
if (name.Equals("value", StringComparison.OrdinalIgnoreCase))
{
currentValue.dValue = d;
currentValue.sValue = string.IsNullOrEmpty(sValue) ? sNum : sValue;
collectedTokens.Add(tokens.Current.Index);
PostElementParse(ref tokens, currentValue);
continue;
}
AssignValueField(currentValue, name, d, sNum, sValue);
collectedTokens.Add(tokens.Current.Index);
tokens.MoveNext();
continue;
}
if (ShouldLocalParse(name))
{
LocalParse(ref tokens);
}
else if (name.StartsWith("Timestamp", StringComparison.InvariantCultureIgnoreCase))
{
DateTimeOffset time;
int length;
var start = tokens.Current.Index + name.Length+1;
if (ExtractTime(renderedMessage.Substring(start), out time, out length))
{
_values.Add(new AppenderValue
{
Name = "Timestamp",
Time = time
});
collectedTokens.Add(tokens.Current.Index);
tokens.MoveNext();
do
{
if (tokens.Current != null)
collectedTokens.Add(tokens.Current.Index);
} while (tokens.MoveNext() && tokens.Current.Index < start + length);
}
tokens.MoveNext();
}
else
{
if (!tokens.MoveNext())
continue;
if (!string.IsNullOrEmpty(tokens.Current.Groups["lbrace"].Value))
continue;
sNum = string.IsNullOrEmpty(tokens.Current.Groups["float"].Value)
? tokens.Current.Groups["int"].Value
: tokens.Current.Groups["float"].Value;
var sValue = tokens.Current.Groups["word"].Value;
var strings = sValue.Split(' ');
if (strings.Count() > 1 && string.IsNullOrEmpty(sNum))
sNum = strings[0];
if (string.IsNullOrEmpty(sNum) && string.IsNullOrEmpty(sValue))
{
tokens.MoveNext();
continue;
}
double d;
if (!Double.TryParse(sNum, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out d))
{
if (string.IsNullOrEmpty(sValue))
{
tokens.MoveNext();
continue;
}
Double.TryParse(sValue.Trim('"'), NumberStyles.AllowDecimalPoint,
CultureInfo.InvariantCulture, out d);
}
currentValue.dValue = d;
currentValue.sValue = string.IsNullOrEmpty(sValue) ? sNum : sValue;
var aggregate = strings.Skip(1).Aggregate("", (a, b) => a + b);
if (tokens.Current != null)
collectedTokens.Add(tokens.Current.Index);
PostElementParse(ref tokens, currentValue, aggregate);
AddValue(currentValue);
currentValue = null;
}
}
else
{
tokens.MoveNext();
}
}
collectedTokens = collectedTokens.Distinct().ToList();
tokens = matches.GetEnumerator();
int? startRest = 0;
var rest2 = "";
while (tokens.MoveNext())
{
if (!collectedTokens.Contains(tokens.Current.Index))
startRest = startRest ?? tokens.Current.Index;
else
{
if (startRest != null)
rest2 += renderedMessage.Substring(startRest.Value, tokens.Current.Index - startRest.Value);
startRest = null;
}
}
if (startRest != null)
rest2 += renderedMessage.Substring(startRest.Value, renderedMessage.Length - startRest.Value);
rest2 = rest2.Replace(" {} ", " ").Replace("{}", "");
rest = rest2;
AddValue(new AppenderValue { Name = "__cav_rest", sValue = rest.Trim() });
}
protected void AddValue(AppenderValue currentValue)
{
_values.Add(currentValue);
}
protected virtual void AssignValueField(AppenderValue currentValue, string fieldName, double d, string sNum, string sValue)
{
}
protected virtual AppenderValue NewAppenderValue()
{
var v = new AppenderValue();
return v;
}
protected virtual void PostElementParse(ref List<Match>.Enumerator tokens, AppenderValue appenderValue, string aggregate = null)
{
tokens.MoveNext();
}
protected virtual bool ShouldLocalParse(string t0) { return false; }
protected abstract bool IsSupportedName(string t0);
protected abstract bool IsSupportedValueField(string t0);
private bool ExtractTime(string s, out DateTimeOffset time, out int length)
{
var success = false;
length = 0;
time = DateTimeOffset.UtcNow;
var added = s.Length;
s = s.TrimStart();
s = s.TrimStart(":\" ".ToCharArray());
added -= s.Length;
s = s.TrimEnd();
s = s.TrimEnd(":\" ".ToCharArray());
for (int i = 1; i <= s.Length; i++)
{
DateTimeOffset lastTriedTime;
if (DateTimeOffset.TryParse(s.Substring(0, i), null, DateTimeStyles.AssumeUniversal, out lastTriedTime))
{
success = true;
time = lastTriedTime;
length = i;
}
}
length += added;
return success;
}
protected virtual void LocalParse(ref List<Match>.Enumerator tokens) { }
protected abstract IEnumerable<TDatum> GetParsedData();
public IEnumerable<TDatum> Parse(string renderedMessage)
{
Init();
if (!string.IsNullOrEmpty(renderedMessage))
{
var tokens =
Regex.Matches(renderedMessage,
@"(?<lbrace>{)|(?<rbrace>})|(?<float>(\d+\.\d+))|(?<int>\d+)|""(?<name>\w+)"":|(?<name>\w+):|\((?<word>[\w/ ]+)\)|""(?<word>.*?)""|(?<word>[^()}{"", ]+)|(?<lparen>\()|(?<rparen>\))")
.Cast<Match>()
.ToList()
.GetEnumerator();
ParseTokens(ref tokens, renderedMessage);
}
NewDatum();
foreach (var p in _values)
{
try
{
if (!FillName(p))
{
NewDatum();
FillName(p);
}
}
catch (DatumFilledException)
{
NewDatum();
FillName(p);
}
}
ApplyDefaults();
return GetParsedData();
}
protected virtual void Init()
{
_values = new List<AppenderValue>();
}
}
}
| |
using System;
using System.Collections.Specialized;
using System.Text;
using System.Web;
using NGM.CasClient.Client.Factories;
using NGM.CasClient.Models;
using Orchard;
using Orchard.ContentManagement;
using Orchard.Settings;
using Orchard.Validation;
namespace NGM.CasClient.Client.Utils {
public interface IUrlUtil : IDependency {
/// <summary>
/// Constructs the URL to use for redirection to the CAS server for login
/// </summary>
/// <remarks>
/// The server name is not parsed from the request for security reasons, which
/// is why the service and server name configuration parameters exist.
/// </remarks>
/// <returns>The redirection URL to use</returns>
string ConstructLoginRedirectUrl(bool gateway, bool renew, bool gatewayCheck);
/// <summary>
/// Constructs a service URL using configured values in the following order:
/// 1. if not empty, the value configured for Service is used
/// - otherwise -
/// 2. the value configured for ServerName is used together with HttpRequest
/// data
/// </summary>
/// <remarks>
/// The server name is not parsed from the request for security reasons, which
/// is why the service and server name configuration parameters exist, per Jasig
/// website.
/// </remarks>
/// <returns>the service URL to use, not encoded</returns>
string ConstructServiceUrl(bool gateway);
/// <summary>
/// Constructs a URL used to check the validitiy of a service ticket, with or without a proxy
/// callback URL, and with or without requiring renewed credentials.
/// </summary>
/// <remarks>See CAS Protocol specification, section 2.5</remarks>
/// <param name="serviceTicket">The service ticket to validate.</param>
/// <param name="renew">
/// Whether or not renewed credentials are required. If True, ticket validation
/// will fail for Single Sign On credentials.
/// </param>
/// <param name="gateway">
/// whether or not to include gatewayResponse=true in the request (client specific).
/// </param>
/// <param name="customParameters">custom parameters to add to the validation URL</param>
/// <returns>The service ticket validation URL to use</returns>
string ConstructValidateUrl(string serviceTicket, bool gateway, bool renew, NameValueCollection customParameters);
/// <summary>
/// Constructs a proxy callback URL containing a ProxyCallbackParameter
/// (proxyResponse by default). This URL is sent to the CAS server during a proxy
/// ticket request and is then connected to by the CAS server. If the CAS server
/// cannot successfully connect (generally due to SSL configuration issues), the
/// CAS server will refuse to send a proxy ticket.
/// </summary>
/// <remarks>
/// This is a .NET implementation specific method used to eliminate the need for
/// a special HTTP Handler. Essentially, if the client detects an incoming request
/// with the ProxyCallbackParameter in the URL (i.e., proxyResponse), that request
/// is treated specially and behaves as if it were handled by an HTTP Handler. In
/// other words, this behavior may or may not short circuit the request event
/// processing and will not allow the underlying page to execute and transmit back to
/// the client. If your application does coincidentally make use of the key
/// 'proxyResponse' as a URL parameter, you will need to configure a custom
/// proxyCallbackParameter value which does not conflict with the URL parameters in
/// your application.
/// </remarks>
/// <returns>the proxy callback URL to use</returns>
string ConstructProxyCallbackUrl();
/// <summary>
/// Constructs a proxy ticket request URL containing both a proxy granting
/// ticket and a URL Encoded targetServiceUrl. The URL returned will generally only
/// be executed by the CAS client as a part of a proxy redirection in
/// CasAuthentication.ProxyRedirect(...) or CasAuthentication.GetProxyTicketIdFor(...)
/// but may also be used by applications which require low-level access to the proxy
/// ticket request functionality.
/// </summary>
/// <param name="proxyGrantingTicketId">
/// The proxy granting ticket used to authorize the request for a proxy ticket on the
/// CAS server
/// </param>
/// <param name="targetService">
/// The target service URL to request a proxy ticket request URL for
/// </param>
/// <returns>The URL to use to request a proxy ticket for the targetService specified</returns>
string ConstructProxyTicketRequestUrl(string proxyGrantingTicketId, string targetService);
/// <summary>
/// Attempts to request a proxy ticket for the targetService specified and
/// returns a URL appropriate for redirection to the targetService containing
/// a ticket.
/// </summary>
/// <param name="targetService">The target service for proxy authentication</param>
/// <returns>The URL of the target service with a proxy ticket included</returns>
string GetProxyRedirectUrl(string targetService, Func<string, string> getProxyTicket);
/// <summary>
/// Attempts to request a proxy ticket for the targetService specified and
/// returns a URL appropriate for redirection to the targetService containing
/// a ticket.
/// </summary>
/// <param name="targetService">The target service for proxy authentication</param>
/// <param name="proxyTicketUrlParameter">
/// The name of the ticket URL parameter expected by the target service (ticket by
/// default)
/// </param>
/// <returns>The URL of the target service with a proxy ticket included</returns>
string GetProxyRedirectUrl(string targetService, string proxyTicketUrlParameter, Func<string, string> getProxyTicket);
/// <summary>
/// Constructs the URL to use for redirection to the CAS server for single
/// signout. The CAS server will invalidate the ticket granting ticket and
/// redirect back to the current page. The web application must then call
/// ClearAuthCookie and revoke the ticket from the ServiceTicketManager to sign
/// the client out.
/// </summary>
/// <returns>the redirection URL to use, not encoded</returns>
string ConstructSingleSignOutRedirectUrl();
/// <summary>
/// Returns a copy of the URL supplied modified to remove CAS protocol-specific
/// URL parameters.
/// </summary>
/// <param name="url">The URL to remove CAS artifacts from</param>
/// <returns>The URL supplied without CAS artifacts</returns>
string RemoveCasArtifactsFromUrl(string url);
/// <summary>
/// Resolves a relative ~/Url to a Url that is meaningful to the
/// client.
/// <remarks>
/// Derived from: http://weblogs.asp.net/palermo4/archive/2004/06/18/getting-the-absolute-path-in-asp-net-part-2.aspx
/// </remarks>
/// </summary>
/// <author>J. Michael Palermo IV</author>
/// <author>Scott Holodak</author>
/// <param name="url">The Url to resolve</param>
/// <returns>The fullly resolved Url</returns>
string ResolveUrl(string url);
}
/// <summary>
/// An internal class used to generate and modify URLs
/// as needed for redirection and external communication.
/// </summary>
/// <remarks>
/// See https://wiki.jasig.org/display/CASC/UrlUtil+Methods for additional
/// information including sample output of each method.
/// </remarks>
/// <author>Scott Holodak</author>
public class UrlUtil : IUrlUtil {
private readonly IOrchardServices _orchardServices;
private readonly Lazy<ITicketValidatorFactory> _ticketValidatorFactory;
public UrlUtil(IOrchardServices orchardServices,
Lazy<ITicketValidatorFactory> ticketValidatorFactory) {
_orchardServices = orchardServices;
_ticketValidatorFactory = ticketValidatorFactory;
}
private CASSettingsPart Settings {
get { return _orchardServices.WorkContext.CurrentSite.As<CASSettingsPart>(); }
}
private ISite SiteSettings {
get { return _orchardServices.WorkContext.CurrentSite; }
}
/// <summary>
/// Constructs the URL to use for redirection to the CAS server for login
/// </summary>
/// <remarks>
/// The server name is not parsed from the request for security reasons, which
/// is why the service and server name configuration parameters exist.
/// </remarks>
/// <returns>The redirection URL to use</returns>
public string ConstructLoginRedirectUrl(bool gateway, bool renew, bool gatewayCheck)
{
if (gateway && renew) {
throw new ArgumentException("Gateway and Renew parameters are mutually exclusive and cannot both be True");
}
EnhancedUriBuilder ub = new EnhancedUriBuilder(Settings.FormsLoginUrl);
ub.QueryItems.Set(_ticketValidatorFactory.Value.TicketValidator.ServiceParameterName, HttpUtility.UrlEncode(ConstructServiceUrl(gateway)));
if (renew) {
ub.QueryItems.Add("renew", "true");
}
else if (gatewayCheck)
{
ub.QueryItems.Add("gateway", "true");
}
string url = ub.Uri.AbsoluteUri;
return url;
}
/// <summary>
/// Constructs a service URL using configured values in the following order:
/// 1. if not empty, the value configured for Service is used
/// - otherwise -
/// 2. the value configured for ServerName is used together with HttpRequest
/// data
/// </summary>
/// <remarks>
/// The server name is not parsed from the request for security reasons, which
/// is why the service and server name configuration parameters exist, per Jasig
/// website.
/// </remarks>
/// <returns>the service URL to use, not encoded</returns>
public string ConstructServiceUrl(bool gateway) {
HttpContext context = HttpContext.Current;
HttpRequest request = context.Request;
StringBuilder buffer = new StringBuilder();
if (!(SiteSettings.BaseUrl.StartsWith("https://") || SiteSettings.BaseUrl.StartsWith("http://"))) {
buffer.Append(request.IsSecureConnection ? "https://" : "http://");
}
buffer.Append(SiteSettings.BaseUrl);
EnhancedUriBuilder ub = new EnhancedUriBuilder(buffer.ToString());
ub.Path = request.Url.AbsolutePath;
ub.QueryItems.Add(request.QueryString);
ub.QueryItems.Remove(_ticketValidatorFactory.Value.TicketValidator.ServiceParameterName);
ub.QueryItems.Remove(_ticketValidatorFactory.Value.TicketValidator.ArtifactParameterName);
if (gateway) {
ub.QueryItems.Set(Settings.GatewayParameterName, "true");
}
else {
ub.QueryItems.Remove(Settings.GatewayParameterName);
}
return ub.Uri.AbsoluteUri;
}
/// <summary>
/// Constructs a URL used to check the validitiy of a service ticket, with or without a proxy
/// callback URL, and with or without requiring renewed credentials.
/// </summary>
/// <remarks>See CAS Protocol specification, section 2.5</remarks>
/// <param name="serviceTicket">The service ticket to validate.</param>
/// <param name="renew">
/// Whether or not renewed credentials are required. If True, ticket validation
/// will fail for Single Sign On credentials.
/// </param>
/// <param name="gateway">
/// whether or not to include gatewayResponse=true in the request (client specific).
/// </param>
/// <param name="customParameters">custom parameters to add to the validation URL</param>
/// <returns>The service ticket validation URL to use</returns>
public string ConstructValidateUrl(string serviceTicket, bool gateway, bool renew, NameValueCollection customParameters) {
if (gateway && renew) {
throw new ArgumentException("Gateway and Renew parameters are mutually exclusive and cannot both be True");
}
EnhancedUriBuilder ub = new EnhancedUriBuilder(EnhancedUriBuilder.Combine(Settings.CasServerUrlPrefix, _ticketValidatorFactory.Value.TicketValidator.UrlSuffix));
ub.QueryItems.Add(_ticketValidatorFactory.Value.TicketValidator.ServiceParameterName, HttpUtility.UrlEncode(ConstructServiceUrl(gateway)));
ub.QueryItems.Add(_ticketValidatorFactory.Value.TicketValidator.ArtifactParameterName, HttpUtility.UrlEncode(serviceTicket));
if (renew) {
ub.QueryItems.Set("renew", "true");
}
if (customParameters != null) {
for (int i = 0; i < customParameters.Count; i++) {
string key = customParameters.AllKeys[i];
string value = customParameters[i];
ub.QueryItems.Add(key, value);
}
}
return ub.Uri.AbsoluteUri;
}
/// <summary>
/// Constructs a proxy callback URL containing a ProxyCallbackParameter
/// (proxyResponse by default). This URL is sent to the CAS server during a proxy
/// ticket request and is then connected to by the CAS server. If the CAS server
/// cannot successfully connect (generally due to SSL configuration issues), the
/// CAS server will refuse to send a proxy ticket.
/// </summary>
/// <remarks>
/// This is a .NET implementation specific method used to eliminate the need for
/// a special HTTP Handler. Essentially, if the client detects an incoming request
/// with the ProxyCallbackParameter in the URL (i.e., proxyResponse), that request
/// is treated specially and behaves as if it were handled by an HTTP Handler. In
/// other words, this behavior may or may not short circuit the request event
/// processing and will not allow the underlying page to execute and transmit back to
/// the client. If your application does coincidentally make use of the key
/// 'proxyResponse' as a URL parameter, you will need to configure a custom
/// proxyCallbackParameter value which does not conflict with the URL parameters in
/// your application.
/// </remarks>
/// <returns>the proxy callback URL to use</returns>
public string ConstructProxyCallbackUrl() {
EnhancedUriBuilder ub = new EnhancedUriBuilder(ConstructServiceUrl(false));
ub.QueryItems.Set(Settings.ProxyCallbackParameterName, "true");
return ub.Uri.AbsoluteUri;
}
/// <summary>
/// Constructs a proxy ticket request URL containing both a proxy granting
/// ticket and a URL Encoded targetServiceUrl. The URL returned will generally only
/// be executed by the CAS client as a part of a proxy redirection in
/// CasAuthentication.ProxyRedirect(...) or CasAuthentication.GetProxyTicketIdFor(...)
/// but may also be used by applications which require low-level access to the proxy
/// ticket request functionality.
/// </summary>
/// <param name="proxyGrantingTicketId">
/// The proxy granting ticket used to authorize the request for a proxy ticket on the
/// CAS server
/// </param>
/// <param name="targetService">
/// The target service URL to request a proxy ticket request URL for
/// </param>
/// <returns>The URL to use to request a proxy ticket for the targetService specified</returns>
public string ConstructProxyTicketRequestUrl(string proxyGrantingTicketId, string targetService) {
// TODO: Make "proxy" configurable.
EnhancedUriBuilder ub = new EnhancedUriBuilder(EnhancedUriBuilder.Combine(Settings.CasServerUrlPrefix, "proxy"));
ub.QueryItems.Add("pgt", proxyGrantingTicketId);
ub.QueryItems.Add("targetService", HttpUtility.UrlEncode(targetService));
return ub.Uri.AbsoluteUri;
}
/// <summary>
/// Attempts to request a proxy ticket for the targetService specified and
/// returns a URL appropriate for redirection to the targetService containing
/// a ticket.
/// </summary>
/// <param name="targetService">The target service for proxy authentication</param>
/// <returns>The URL of the target service with a proxy ticket included</returns>
public string GetProxyRedirectUrl(string targetService, Func<string, string> getProxyTicket) {
return GetProxyRedirectUrl(targetService, _ticketValidatorFactory.Value.TicketValidator.ArtifactParameterName, getProxyTicket);
}
/// <summary>
/// Attempts to request a proxy ticket for the targetService specified and
/// returns a URL appropriate for redirection to the targetService containing
/// a ticket.
/// </summary>
/// <param name="targetService">The target service for proxy authentication</param>
/// <param name="proxyTicketUrlParameter">
/// The name of the ticket URL parameter expected by the target service (ticket by
/// default)
/// </param>
/// <returns>The URL of the target service with a proxy ticket included</returns>
public string GetProxyRedirectUrl(string targetService, string proxyTicketUrlParameter, Func<string, string> getProxyTicket) {
// Todo: Is ResolveUrl(...) appropriate/necessary? If the URL starts with ~, it shouldn't require proxy authentication
string resolvedUrl = ResolveUrl(targetService);
string proxyTicket = getProxyTicket(resolvedUrl);
EnhancedUriBuilder ub = new EnhancedUriBuilder(resolvedUrl);
ub.QueryItems[proxyTicketUrlParameter] = proxyTicket;
return ub.Uri.AbsoluteUri;
}
/// <summary>
/// Constructs the URL to use for redirection to the CAS server for single
/// signout. The CAS server will invalidate the ticket granting ticket and
/// redirect back to the current page. The web application must then call
/// ClearAuthCookie and revoke the ticket from the ServiceTicketManager to sign
/// the client out.
/// </summary>
/// <returns>the redirection URL to use, not encoded</returns>
public string ConstructSingleSignOutRedirectUrl() {
// TODO: Make "logout" configurable
EnhancedUriBuilder ub = new EnhancedUriBuilder(EnhancedUriBuilder.Combine(Settings.CasServerUrlPrefix, "logout"));
ub.QueryItems.Set(_ticketValidatorFactory.Value.TicketValidator.ServiceParameterName, HttpUtility.UrlEncode(ConstructServiceUrl(false)));
return ub.Uri.AbsoluteUri;
}
/// <summary>
/// Returns a copy of the URL supplied modified to remove CAS protocol-specific
/// URL parameters.
/// </summary>
/// <param name="url">The URL to remove CAS artifacts from</param>
/// <returns>The URL supplied without CAS artifacts</returns>
public string RemoveCasArtifactsFromUrl(string url) {
Argument.ThrowIfNullOrEmpty(url, "url", "url parameter can not be null or empty.");
EnhancedUriBuilder ub = new EnhancedUriBuilder(url);
ub.QueryItems.Remove(_ticketValidatorFactory.Value.TicketValidator.ArtifactParameterName);
ub.QueryItems.Remove(_ticketValidatorFactory.Value.TicketValidator.ServiceParameterName);
ub.QueryItems.Remove(Settings.GatewayParameterName);
ub.QueryItems.Remove(Settings.ProxyCallbackParameterName);
// ++ NETC-28
Uri uriServerName;
if (SiteSettings.BaseUrl.StartsWith("http://", StringComparison.InvariantCultureIgnoreCase) ||
SiteSettings.BaseUrl.StartsWith("https://", StringComparison.InvariantCultureIgnoreCase)) {
uriServerName = new Uri(SiteSettings.BaseUrl);
}
else {
// .NET URIs require scheme
uriServerName = new Uri("https://" + SiteSettings.BaseUrl);
}
ub.Scheme = uriServerName.Scheme;
ub.Host = uriServerName.Host;
ub.Port = uriServerName.Port;
return ub.Uri.AbsoluteUri;
}
/// <summary>
/// Resolves a relative ~/Url to a Url that is meaningful to the
/// client.
/// <remarks>
/// Derived from: http://weblogs.asp.net/palermo4/archive/2004/06/18/getting-the-absolute-path-in-asp-net-part-2.aspx
/// </remarks>
/// </summary>
/// <author>J. Michael Palermo IV</author>
/// <author>Scott Holodak</author>
/// <param name="url">The Url to resolve</param>
/// <returns>The fullly resolved Url</returns>
public string ResolveUrl(string url) {
Argument.ThrowIfNullOrEmpty(url, "url", "url parameter can not be null or empty.");
if (url[0] != '~') return url;
string applicationPath = HttpContext.Current.Request.ApplicationPath;
if (url.Length == 1) return applicationPath;
// assume url looks like ~somePage
int indexOfUrl = 1;
// determine the middle character
string midPath = ((applicationPath ?? string.Empty).Length > 1) ? "/" : string.Empty;
// if url looks like ~/ or ~\ change the indexOfUrl to 2
if (url[1] == '/' || url[1] == '\\') indexOfUrl = 2;
return applicationPath + midPath + url.Substring(indexOfUrl);
}
}
}
| |
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Microsoft Corporation
*
* -=- Robust Distributed System Nucleus (rDSN) -=-
*
* 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.
*/
/*
* Description:
* What is this file about?
*
* Revision history:
* Feb., 2016, @imzhenyu (Zhenyu Guo), done in Tron project and copied here
* xxxx-xx-xx, author, fix bug about xxx
*/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using rDSN.Tron.Contract;
using rDSN.Tron.Utility;
namespace rDSN.Tron.Compiler
{
public class QueryContext : ExpressionVisitor<object, int>
{
public static HashSet<string> KnownLibs = new HashSet<string>
{
"System.dll",
"System.Core.dll",
"rDSN.Tron.Utility.dll",
"rDSN.Tron.Compiler.dll",
"rDSN.Tron.Contract.dll",
"rDSN.Tron.Runtime.dll"
};
public Dictionary<Type, string> RewrittenTypes = new Dictionary<Type,string>(); // see TypeRewriter
public Dictionary<string, string> ResourceLibraries = new Dictionary<string,string>(); // AllLibs - KnownLibs
public Dictionary<string, string> AllLibraries = new Dictionary<string, string>(); //
public HashSet<Type> Types = new HashSet<Type>();
public HashSet<MethodInfo> Methods = new HashSet<MethodInfo>();
public Dictionary<MethodCallExpression, Service> ServiceCalls = new Dictionary<MethodCallExpression, Service>();
public Dictionary<Expression, object> ExternalObjects = new Dictionary<Expression, object>();
public Dictionary<ConstantExpression, ISymbol> InputSymbols = new Dictionary<ConstantExpression, ISymbol>();
public Dictionary<ConstantExpression, object> InputConstants = new Dictionary<ConstantExpression, object>();
public Dictionary<MemberExpression, Service> Services = new Dictionary<MemberExpression, Service>();
public Dictionary<Expression, string> TempSymbols = new Dictionary<Expression, string>(); // var xyz = expression;
public Dictionary<string, Expression> TempSymbolsByAlias = new Dictionary<string, Expression>();
public Dictionary<MethodInfo, MethodCallExpression> ExternalComposedSerivce = new Dictionary<MethodInfo, MethodCallExpression>();
public Type InputType { get; private set; }
public Type OutputType { get; private set; }
public MethodCallExpression RootExpression { get; private set; }
public string Name { get; private set; }
public object ComposedServiceObject { get; private set; }
public QueryContext(object serviceObject, MethodCallExpression exp, string name = "Invoke")
{
ComposedServiceObject = serviceObject;
RootExpression = exp;
Name = name;
}
public void Collect()
{
Visit(RootExpression, 0);
ExtractInputOutputTypes();
ExtractAllAnonymousOrPrivateTypes();
ExtractAllResources();
}
private void ExtractInputOutputTypes()
{
Trace.Assert(InputSymbols.Count >= 1);
InputType = InputSymbols.First().Key.Type;
OutputType = RootExpression.Type;
}
private void ExtractAllAnonymousOrPrivateTypes()
{
Types.Where(t => t.IsAnonymous()).Select(t => {
RewrittenTypes.Add(t, "Anonymous_" + t.GetHashCode());
return 0;
}).Count();
Types.Where(t => !t.IsAnonymous() && t.IsNotPublic).Select(t => {
RewrittenTypes.Add(t, "NonPublic_" + t.Name + "_" + t.GetHashCode());
return 0;
}).Count();
}
private void ExtractAllResources()
{
Methods.Select(m =>
{
if (m.IsPublic == false)
{
throw new Exception("Method call " + m.DeclaringType.FullName + "." + m.Name + " is not public therefore cannot be used in the query");
}
return 0;
}).Count();
var types = Types.Union(Methods.Select(mi => mi.DeclaringType))
.Except(RewrittenTypes.Select(rt => rt.Key))
.Where(t => !t.FullName.StartsWith("System."))
.Distinct()
.ToArray();
var allModules = types
.Select(t => t.Module)
.Distinct()
.ToArray()
;
foreach (var m in allModules)
{
AllLibraries.Add(m.Name, m.FullyQualifiedName);
}
foreach (var m in allModules.Where(m => !KnownLibs.Contains(m.Name)))
{
ResourceLibraries.Add(m.Name, m.FullyQualifiedName);
}
}
public override object VisitMethodCall(MethodCallExpression m, int nil)
{
var attrs = m.Method.GetCustomAttributes(typeof(Primitive), false).Cast<Primitive>().ToArray();
if (attrs.Length > 0 && attrs[0].Analyzer != null)
{
attrs[0].Analyzer.Analysis(m, this);
return null;
}
if (attrs.Length == 0 && (m.Type.IsSymbol() || m.Type.IsSymbols()))
{
var paramemters = new List<object>();
var i = 0;
foreach (var p in m.Method.GetParameters())
{
i++;
if (p.ParameterType.IsSymbols())
{
var rp = p.ParameterType.GetConstructor(new Type[] { }).Invoke(new object[] { });
paramemters.Add(rp);
}
else
{
Trace.Assert(p.ParameterType.IsSymbol());
var rp = p.ParameterType.GetConstructor(new[] { typeof(string) }).Invoke(new object[] { "p_" + i });
(rp as ISymbol).Name = "p_" + i;
paramemters.Add(rp);
}
}
var r = m.Method.Invoke(ComposedServiceObject, paramemters.ToArray());
Trace.Assert(r.GetType().IsInheritedTypeOf(typeof(ISymbol)));
ExternalComposedSerivce.Add(m.Method, (r as ISymbol).Expression as MethodCallExpression);
//Visit(kexpr, 0);
}
if (!Methods.Contains(m.Method))
Methods.Add(m.Method);
if (m.Object == null || !m.Object.Type.IsInheritedTypeOf(typeof (Service)))
return base.VisitMethodCall(m, nil);
if (!ServiceCalls.ContainsKey(m))
{
ServiceCalls.Add(m, GetValue(m.Object) as Service);
}
return base.VisitMethodCall(m, nil);
}
public override object VisitConstant(ConstantExpression node, int nil)
{
object v;
var r = GetValue(node, out v);
if (!r)
{
if (node.Type.IsGenericType && node.Type.BaseType == typeof(ISymbol))
{
InputSymbols.Add(node, node.Value as ISymbol);
}
else
{
throw new Exception("cannot resolve external constant expression '" + node + "'");
}
}
else
{
if (node.Type.IsGenericType && node.Type.BaseType == typeof(ISymbol))
{
InputSymbols.Add(node, node.Value as ISymbol);
}
else
{
InputConstants.Add(node, true);
}
}
return null;
}
public override object VisitMemberAccess(MemberExpression node, int nil)
{
object value;
if (ExternalObjects.ContainsKey(node))
{
return null;
}
if (GetValue(node, out value))
{
ExternalObjects[node] = value;
if (node.Type.IsInheritedTypeOf(typeof(Service)))
{
// TODO: multiple instances of the same type
var t1 = Services.Keys.Select(k => k.Type.ToString()).Any(p => p == node.Type.ToString());
if (!t1)
{
Services.Add(node, value as Service);
}
return null;
}
if (node.Type.IsInheritedTypeOf(typeof(Expression)))
{
return null;
}
if (node.Type.IsSymbol() || node.Type.IsSymbols())
{
if (value == null)
{
Trace.Assert(TempSymbolsByAlias.ContainsKey(node.Member.Name), "a symbol must be first defined (e.g., using Alias operator)");
}
else
{
var kexpr = (value as ISymbol).Expression;
if (kexpr.NodeType == ExpressionType.Constant) return null;
if (!TempSymbols.ContainsKey(kexpr))
{
TempSymbols.Add(kexpr, node.Member.Name);
}
}
return null;
}
string s;
var r = LocalTypeHelper.ConstantValue2String(ExternalObjects[node], out s);
if (r)
{
return null;
}
throw new Exception("cannot resolve external constant expression '" + node + "'");
}
if (node.Expression != null)
{
Visit(node.Expression, nil);
}
return null;
}
public override object VisitNew(NewExpression nex, int param)
{
VisitExpressionList(nex.Arguments, param);
Types.Add(nex.Type);
return null;
}
public override object VisitNewArray(NewArrayExpression na, int param)
{
VisitExpressionList(na.Expressions, param);
Types.Add(na.Type);
return null;
}
public override object VisitInvocation(InvocationExpression iv, int param)
{
VisitExpressionList(iv.Arguments, param);
Visit(iv.Expression, param);
Types.Add(iv.Type);
return null;
}
}
}
| |
using System.IO.Compression;
namespace Protobuild.Tests
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
public abstract class ProtobuildTest
{
private string m_TestName;
private string m_TestLocation;
protected void SetupTest(string name, bool isPackTest = false)
{
// This is used to ensure Protobuild.exe is referenced.
Console.WriteLine(typeof(Protobuild.Bootstrap.Program).FullName);
this.m_TestName = name;
var location = new FileInfo(Assembly.GetExecutingAssembly().Location).Directory.FullName;
var dataLocation = Path.Combine(location, "..", "..", "..", "..", "TestData", this.m_TestName);
var protobuildLocation =
AppDomain.CurrentDomain.GetAssemblies().First(x => x.GetName().Name == "Protobuild").Location;
this.m_TestLocation = dataLocation;
this.DeployProtobuildToTestFolder(dataLocation, protobuildLocation, isPackTest);
}
private void PurgeSolutionsAndProjects(string dataLocation)
{
var dir = new DirectoryInfo(dataLocation);
foreach (var solution in dir.GetFiles("*.sln"))
{
solution.Delete();
}
foreach (var project in dir.GetFiles("*.csproj"))
{
project.Delete();
}
foreach (var sub in dir.GetDirectories())
{
this.PurgeSolutionsAndProjects(sub.FullName);
}
}
private void DeployProtobuildToTestFolder(string dataLocation, string protobuildLocation, bool isPackTest)
{
File.Copy(protobuildLocation, Path.Combine(dataLocation, "Protobuild.exe"), true);
if (!isPackTest)
{
foreach (var dir in new DirectoryInfo(dataLocation).GetDirectories())
{
if (dir.GetDirectories().Any(x => x.Name == "Build"))
{
this.DeployProtobuildToTestFolder(dir.FullName, protobuildLocation, isPackTest);
}
}
}
}
protected Tuple<string, string> Generate(string platform = null, string args = null, bool expectFailure = false, bool capture = false)
{
return this.OtherMode("generate", (platform ?? "Windows") + " " + args, expectFailure, capture: capture);
}
protected Tuple<string, string> OtherMode(string mode, string args = null, bool expectFailure = false, bool purge = true, bool capture = false, string workingSubdirectory = null)
{
if (purge)
{
this.PurgeSolutionsAndProjects(this.m_TestLocation);
}
var stdout = string.Empty;
var stderr = string.Empty;
var pi = new ProcessStartInfo
{
FileName = Path.Combine(this.m_TestLocation, "Protobuild.exe"),
Arguments = "--" + mode + " " + (args ?? string.Empty),
WorkingDirectory = workingSubdirectory != null ? Path.Combine(this.m_TestLocation, workingSubdirectory) : this.m_TestLocation,
CreateNoWindow = true,
UseShellExecute = false,
RedirectStandardError = true,
RedirectStandardOutput = true,
};
var p = new Process { StartInfo = pi };
p.OutputDataReceived += (sender, eventArgs) =>
{
if (!string.IsNullOrEmpty(eventArgs.Data))
{
if (capture)
{
stdout += eventArgs.Data + "\n";
}
else
{
Console.WriteLine(eventArgs.Data);
}
}
};
p.ErrorDataReceived += (sender, eventArgs) =>
{
if (!string.IsNullOrEmpty(eventArgs.Data))
{
if (capture)
{
stderr += eventArgs.Data + "\n";
}
else
{
Console.WriteLine(eventArgs.Data);
}
}
};
p.Start();
p.BeginOutputReadLine();
p.BeginErrorReadLine();
p.WaitForExit();
if (p.ExitCode == 134)
{
// SIGSEGV due to Mono bugs, try again.
return this.OtherMode(mode, args, expectFailure, purge, capture);
}
if (expectFailure)
{
Xunit.Assert.True(1 == p.ExitCode, "Expected command '" + pi.FileName + " " + pi.Arguments + "' to fail, but got successful exit code.");
}
else
{
Xunit.Assert.True(0 == p.ExitCode, "Expected command '" + pi.FileName + " " + pi.Arguments + "' to succeed, but got failure exit code.");
}
return new Tuple<string, string>(stdout, stderr);
}
protected string ReadFile(string path)
{
path = path.Replace('\\', Path.DirectorySeparatorChar);
using (var reader = new StreamReader(Path.Combine(this.m_TestLocation, path)))
{
return reader.ReadToEnd();
}
}
protected string GetPath(string path)
{
path = path.Replace('\\', Path.DirectorySeparatorChar);
return Path.Combine(this.m_TestLocation, path);
}
protected Dictionary<string, byte[]> LoadPackage(string path)
{
var results = new Dictionary<string, byte[]>();
if (path.EndsWith(".tar.lzma"))
{
using (var lzma = new FileStream(Path.Combine(m_TestLocation, path), FileMode.Open, FileAccess.Read, FileShare.None))
{
using (var decompress = new MemoryStream())
{
LZMA.LzmaHelper.Decompress(lzma, decompress);
decompress.Seek(0, SeekOrigin.Begin);
var archive = new tar_cs.TarReader(decompress);
var deduplicator = new Reduplicator();
return deduplicator.UnpackTarToMemory(archive);
}
}
}
else if (path.EndsWith(".tar.gz"))
{
using (var file = new FileStream(Path.Combine(m_TestLocation, path), FileMode.Open, FileAccess.Read, FileShare.None))
{
using (var gzip = new GZipStream(file, CompressionMode.Decompress))
{
var archive = new tar_cs.TarReader(gzip);
var deduplicator = new Reduplicator();
return deduplicator.UnpackTarToMemory(archive);
}
}
}
else
{
throw new NotSupportedException();
}
return results;
}
protected string SetupSrcPackage()
{
var protobuildLocation =
AppDomain.CurrentDomain.GetAssemblies().First(x => x.GetName().Name == "Protobuild").Location;
var location = new FileInfo(Assembly.GetExecutingAssembly().Location).Directory.FullName;
var dataLocation = Path.Combine(location, "..", "..", "..", "..", "TestData", "SrcPackage");
var tempLocation = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
CopyDirectory(dataLocation, tempLocation);
File.Copy(protobuildLocation, Path.Combine(tempLocation, "Protobuild.exe"), true);
RunGitAndCapture(tempLocation, "init");
RunGitAndCapture(tempLocation, "add -f .");
RunGitAndCapture(tempLocation, "commit -a -m 'temp'");
return tempLocation;
}
protected string SetupSrcTemplate()
{
var location = new FileInfo(Assembly.GetExecutingAssembly().Location).Directory.FullName;
var dataLocation = Path.Combine(location, "..", "..", "..", "..", "TestData", "SrcTemplate");
var tempLocation = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
CopyDirectory(dataLocation, tempLocation);
RunGitAndCapture(tempLocation, "init");
RunGitAndCapture(tempLocation, "add -f .");
RunGitAndCapture(tempLocation, "commit -a -m 'temp'");
return tempLocation;
}
private static void CopyDirectory(string source, string dest)
{
var dir = new DirectoryInfo(source);
if (!Directory.Exists(dest))
{
Directory.CreateDirectory(dest);
}
foreach (var file in dir.GetFiles())
{
var temppath = Path.Combine(dest, file.Name);
file.CopyTo(temppath, true);
}
foreach (var subdir in dir.GetDirectories())
{
var temppath = Path.Combine(dest, subdir.Name);
CopyDirectory(subdir.FullName, temppath);
}
}
private static string RunGitAndCapture(string folder, string str)
{
var processStartInfo = new ProcessStartInfo
{
FileName = "git",
Arguments = str,
WorkingDirectory = folder,
RedirectStandardOutput = true,
CreateNoWindow = true,
UseShellExecute = false,
};
var process = Process.Start(processStartInfo);
var result = process.StandardOutput.ReadToEnd();
process.WaitForExit();
if (process.ExitCode != 0)
{
throw new InvalidOperationException("Got an unexpected exit code of " + process.ExitCode + " from Git");
}
return result;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using GlmSharp.Swizzle;
// ReSharper disable InconsistentNaming
namespace GlmSharp.Swizzle
{
/// <summary>
/// Temporary vector of type bool with 2 components, used for implementing swizzling for bvec2.
/// </summary>
[Serializable]
[StructLayout(LayoutKind.Sequential)]
public struct swizzle_bvec2
{
#region Fields
/// <summary>
/// x-component
/// </summary>
internal readonly bool x;
/// <summary>
/// y-component
/// </summary>
internal readonly bool y;
#endregion
#region Constructors
/// <summary>
/// Constructor for swizzle_bvec2.
/// </summary>
internal swizzle_bvec2(bool x, bool y)
{
this.x = x;
this.y = y;
}
#endregion
#region Properties
/// <summary>
/// Returns bvec2.xx swizzling.
/// </summary>
public bvec2 xx => new bvec2(x, x);
/// <summary>
/// Returns bvec2.rr swizzling (equivalent to bvec2.xx).
/// </summary>
public bvec2 rr => new bvec2(x, x);
/// <summary>
/// Returns bvec2.xxx swizzling.
/// </summary>
public bvec3 xxx => new bvec3(x, x, x);
/// <summary>
/// Returns bvec2.rrr swizzling (equivalent to bvec2.xxx).
/// </summary>
public bvec3 rrr => new bvec3(x, x, x);
/// <summary>
/// Returns bvec2.xxxx swizzling.
/// </summary>
public bvec4 xxxx => new bvec4(x, x, x, x);
/// <summary>
/// Returns bvec2.rrrr swizzling (equivalent to bvec2.xxxx).
/// </summary>
public bvec4 rrrr => new bvec4(x, x, x, x);
/// <summary>
/// Returns bvec2.xxxy swizzling.
/// </summary>
public bvec4 xxxy => new bvec4(x, x, x, y);
/// <summary>
/// Returns bvec2.rrrg swizzling (equivalent to bvec2.xxxy).
/// </summary>
public bvec4 rrrg => new bvec4(x, x, x, y);
/// <summary>
/// Returns bvec2.xxy swizzling.
/// </summary>
public bvec3 xxy => new bvec3(x, x, y);
/// <summary>
/// Returns bvec2.rrg swizzling (equivalent to bvec2.xxy).
/// </summary>
public bvec3 rrg => new bvec3(x, x, y);
/// <summary>
/// Returns bvec2.xxyx swizzling.
/// </summary>
public bvec4 xxyx => new bvec4(x, x, y, x);
/// <summary>
/// Returns bvec2.rrgr swizzling (equivalent to bvec2.xxyx).
/// </summary>
public bvec4 rrgr => new bvec4(x, x, y, x);
/// <summary>
/// Returns bvec2.xxyy swizzling.
/// </summary>
public bvec4 xxyy => new bvec4(x, x, y, y);
/// <summary>
/// Returns bvec2.rrgg swizzling (equivalent to bvec2.xxyy).
/// </summary>
public bvec4 rrgg => new bvec4(x, x, y, y);
/// <summary>
/// Returns bvec2.xy swizzling.
/// </summary>
public bvec2 xy => new bvec2(x, y);
/// <summary>
/// Returns bvec2.rg swizzling (equivalent to bvec2.xy).
/// </summary>
public bvec2 rg => new bvec2(x, y);
/// <summary>
/// Returns bvec2.xyx swizzling.
/// </summary>
public bvec3 xyx => new bvec3(x, y, x);
/// <summary>
/// Returns bvec2.rgr swizzling (equivalent to bvec2.xyx).
/// </summary>
public bvec3 rgr => new bvec3(x, y, x);
/// <summary>
/// Returns bvec2.xyxx swizzling.
/// </summary>
public bvec4 xyxx => new bvec4(x, y, x, x);
/// <summary>
/// Returns bvec2.rgrr swizzling (equivalent to bvec2.xyxx).
/// </summary>
public bvec4 rgrr => new bvec4(x, y, x, x);
/// <summary>
/// Returns bvec2.xyxy swizzling.
/// </summary>
public bvec4 xyxy => new bvec4(x, y, x, y);
/// <summary>
/// Returns bvec2.rgrg swizzling (equivalent to bvec2.xyxy).
/// </summary>
public bvec4 rgrg => new bvec4(x, y, x, y);
/// <summary>
/// Returns bvec2.xyy swizzling.
/// </summary>
public bvec3 xyy => new bvec3(x, y, y);
/// <summary>
/// Returns bvec2.rgg swizzling (equivalent to bvec2.xyy).
/// </summary>
public bvec3 rgg => new bvec3(x, y, y);
/// <summary>
/// Returns bvec2.xyyx swizzling.
/// </summary>
public bvec4 xyyx => new bvec4(x, y, y, x);
/// <summary>
/// Returns bvec2.rggr swizzling (equivalent to bvec2.xyyx).
/// </summary>
public bvec4 rggr => new bvec4(x, y, y, x);
/// <summary>
/// Returns bvec2.xyyy swizzling.
/// </summary>
public bvec4 xyyy => new bvec4(x, y, y, y);
/// <summary>
/// Returns bvec2.rggg swizzling (equivalent to bvec2.xyyy).
/// </summary>
public bvec4 rggg => new bvec4(x, y, y, y);
/// <summary>
/// Returns bvec2.yx swizzling.
/// </summary>
public bvec2 yx => new bvec2(y, x);
/// <summary>
/// Returns bvec2.gr swizzling (equivalent to bvec2.yx).
/// </summary>
public bvec2 gr => new bvec2(y, x);
/// <summary>
/// Returns bvec2.yxx swizzling.
/// </summary>
public bvec3 yxx => new bvec3(y, x, x);
/// <summary>
/// Returns bvec2.grr swizzling (equivalent to bvec2.yxx).
/// </summary>
public bvec3 grr => new bvec3(y, x, x);
/// <summary>
/// Returns bvec2.yxxx swizzling.
/// </summary>
public bvec4 yxxx => new bvec4(y, x, x, x);
/// <summary>
/// Returns bvec2.grrr swizzling (equivalent to bvec2.yxxx).
/// </summary>
public bvec4 grrr => new bvec4(y, x, x, x);
/// <summary>
/// Returns bvec2.yxxy swizzling.
/// </summary>
public bvec4 yxxy => new bvec4(y, x, x, y);
/// <summary>
/// Returns bvec2.grrg swizzling (equivalent to bvec2.yxxy).
/// </summary>
public bvec4 grrg => new bvec4(y, x, x, y);
/// <summary>
/// Returns bvec2.yxy swizzling.
/// </summary>
public bvec3 yxy => new bvec3(y, x, y);
/// <summary>
/// Returns bvec2.grg swizzling (equivalent to bvec2.yxy).
/// </summary>
public bvec3 grg => new bvec3(y, x, y);
/// <summary>
/// Returns bvec2.yxyx swizzling.
/// </summary>
public bvec4 yxyx => new bvec4(y, x, y, x);
/// <summary>
/// Returns bvec2.grgr swizzling (equivalent to bvec2.yxyx).
/// </summary>
public bvec4 grgr => new bvec4(y, x, y, x);
/// <summary>
/// Returns bvec2.yxyy swizzling.
/// </summary>
public bvec4 yxyy => new bvec4(y, x, y, y);
/// <summary>
/// Returns bvec2.grgg swizzling (equivalent to bvec2.yxyy).
/// </summary>
public bvec4 grgg => new bvec4(y, x, y, y);
/// <summary>
/// Returns bvec2.yy swizzling.
/// </summary>
public bvec2 yy => new bvec2(y, y);
/// <summary>
/// Returns bvec2.gg swizzling (equivalent to bvec2.yy).
/// </summary>
public bvec2 gg => new bvec2(y, y);
/// <summary>
/// Returns bvec2.yyx swizzling.
/// </summary>
public bvec3 yyx => new bvec3(y, y, x);
/// <summary>
/// Returns bvec2.ggr swizzling (equivalent to bvec2.yyx).
/// </summary>
public bvec3 ggr => new bvec3(y, y, x);
/// <summary>
/// Returns bvec2.yyxx swizzling.
/// </summary>
public bvec4 yyxx => new bvec4(y, y, x, x);
/// <summary>
/// Returns bvec2.ggrr swizzling (equivalent to bvec2.yyxx).
/// </summary>
public bvec4 ggrr => new bvec4(y, y, x, x);
/// <summary>
/// Returns bvec2.yyxy swizzling.
/// </summary>
public bvec4 yyxy => new bvec4(y, y, x, y);
/// <summary>
/// Returns bvec2.ggrg swizzling (equivalent to bvec2.yyxy).
/// </summary>
public bvec4 ggrg => new bvec4(y, y, x, y);
/// <summary>
/// Returns bvec2.yyy swizzling.
/// </summary>
public bvec3 yyy => new bvec3(y, y, y);
/// <summary>
/// Returns bvec2.ggg swizzling (equivalent to bvec2.yyy).
/// </summary>
public bvec3 ggg => new bvec3(y, y, y);
/// <summary>
/// Returns bvec2.yyyx swizzling.
/// </summary>
public bvec4 yyyx => new bvec4(y, y, y, x);
/// <summary>
/// Returns bvec2.gggr swizzling (equivalent to bvec2.yyyx).
/// </summary>
public bvec4 gggr => new bvec4(y, y, y, x);
/// <summary>
/// Returns bvec2.yyyy swizzling.
/// </summary>
public bvec4 yyyy => new bvec4(y, y, y, y);
/// <summary>
/// Returns bvec2.gggg swizzling (equivalent to bvec2.yyyy).
/// </summary>
public bvec4 gggg => new bvec4(y, y, y, y);
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
#if ES_BUILD_STANDALONE
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security;
namespace Microsoft.Diagnostics.Tracing.Internal
#else
namespace System.Diagnostics.Tracing.Internal
#endif
{
#if ES_BUILD_AGAINST_DOTNET_V35
using Microsoft.Internal;
#endif
using Microsoft.Reflection;
using System.Reflection;
internal static class Environment
{
public static readonly string NewLine = System.Environment.NewLine;
public static int TickCount
{ get { return System.Environment.TickCount; } }
public static string GetResourceString(string key, params object[] args)
{
string fmt = rm.GetString(key);
if (fmt != null)
return string.Format(fmt, args);
string sargs = string.Empty;
foreach(var arg in args)
{
if (sargs != string.Empty)
sargs += ", ";
sargs += arg.ToString();
}
return key + " (" + sargs + ")";
}
public static string GetRuntimeResourceString(string key, params object[] args)
{
return GetResourceString(key, args);
}
private static System.Resources.ResourceManager rm = new System.Resources.ResourceManager("Microsoft.Diagnostics.Tracing.Messages", typeof(Environment).Assembly());
}
#if ES_BUILD_STANDALONE
internal static class BitOperations
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static uint RotateLeft(uint value, int offset)
=> (value << offset) | (value >> (32 - offset));
public static int PopCount(uint value)
{
const uint c1 = 0x_55555555u;
const uint c2 = 0x_33333333u;
const uint c3 = 0x_0F0F0F0Fu;
const uint c4 = 0x_01010101u;
value = value - ((value >> 1) & c1);
value = (value & c2) + ((value >> 2) & c2);
value = (((value + (value >> 4)) & c3) * c4) >> 24;
return (int)value;
}
public static int TrailingZeroCount(uint value)
{
if (value == 0)
return 32;
int count = 0;
while ((value & 1) == 0)
{
value >>= 1;
count++;
}
return count;
}
}
#endif
}
#if ES_BUILD_AGAINST_DOTNET_V35
namespace Microsoft.Internal
{
using System.Text;
internal static class Tuple
{
public static Tuple<T1> Create<T1>(T1 item1)
{
return new Tuple<T1>(item1);
}
public static Tuple<T1, T2> Create<T1, T2>(T1 item1, T2 item2)
{
return new Tuple<T1, T2>(item1, item2);
}
}
[Serializable]
internal class Tuple<T1>
{
private readonly T1 m_Item1;
public T1 Item1 { get { return m_Item1; } }
public Tuple(T1 item1)
{
m_Item1 = item1;
}
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.Append("(");
sb.Append(m_Item1);
sb.Append(")");
return sb.ToString();
}
int Size
{
get
{
return 1;
}
}
}
[Serializable]
public class Tuple<T1, T2>
{
private readonly T1 m_Item1;
private readonly T2 m_Item2;
public T1 Item1 { get { return m_Item1; } }
public T2 Item2 { get { return m_Item2; } }
public Tuple(T1 item1, T2 item2)
{
m_Item1 = item1;
m_Item2 = item2;
}
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.Append("(");
sb.Append(m_Item1);
sb.Append(", ");
sb.Append(m_Item2);
sb.Append(")");
return sb.ToString();
}
int Size
{
get
{
return 2;
}
}
}
}
#endif
namespace Microsoft.Reflection
{
using System.Reflection;
#if ES_BUILD_PCL
[Flags]
public enum BindingFlags
{
DeclaredOnly = 0x02, // Only look at the members declared on the Type
Instance = 0x04, // Include Instance members in search
Static = 0x08, // Include Static members in search
Public = 0x10, // Include Public members in search
NonPublic = 0x20, // Include Non-Public members in search
}
public enum TypeCode {
Empty = 0, // Null reference
Object = 1, // Instance that isn't a value
DBNull = 2, // Database null value
Boolean = 3, // Boolean
Char = 4, // Unicode character
SByte = 5, // Signed 8-bit integer
Byte = 6, // Unsigned 8-bit integer
Int16 = 7, // Signed 16-bit integer
UInt16 = 8, // Unsigned 16-bit integer
Int32 = 9, // Signed 32-bit integer
UInt32 = 10, // Unsigned 32-bit integer
Int64 = 11, // Signed 64-bit integer
UInt64 = 12, // Unsigned 64-bit integer
Single = 13, // IEEE 32-bit float
Double = 14, // IEEE 64-bit double
Decimal = 15, // Decimal
DateTime = 16, // DateTime
String = 18, // Unicode character string
}
#endif
static class ReflectionExtensions
{
#if (!ES_BUILD_PCL && !ES_BUILD_PN)
//
// Type extension methods
//
public static bool IsEnum(this Type type) { return type.IsEnum; }
public static bool IsAbstract(this Type type) { return type.IsAbstract; }
public static bool IsSealed(this Type type) { return type.IsSealed; }
public static bool IsValueType(this Type type) { return type.IsValueType; }
public static bool IsGenericType(this Type type) { return type.IsGenericType; }
public static Type BaseType(this Type type) { return type.BaseType; }
public static Assembly Assembly(this Type type) { return type.Assembly; }
public static TypeCode GetTypeCode(this Type type) { return Type.GetTypeCode(type); }
public static bool ReflectionOnly(this Assembly assm) { return assm.ReflectionOnly; }
#else // ES_BUILD_PCL
//
// Type extension methods
//
public static bool IsEnum(this Type type) { return type.GetTypeInfo().IsEnum; }
public static bool IsAbstract(this Type type) { return type.GetTypeInfo().IsAbstract; }
public static bool IsSealed(this Type type) { return type.GetTypeInfo().IsSealed; }
public static bool IsValueType(this Type type) { return type.GetTypeInfo().IsValueType; }
public static bool IsGenericType(this Type type) { return type.IsConstructedGenericType; }
public static Type BaseType(this Type type) { return type.GetTypeInfo().BaseType; }
public static Assembly Assembly(this Type type) { return type.GetTypeInfo().Assembly; }
public static IEnumerable<PropertyInfo> GetProperties(this Type type)
{
#if ES_BUILD_PN
return type.GetProperties();
#else
return type.GetRuntimeProperties();
#endif
}
public static MethodInfo GetGetMethod(this PropertyInfo propInfo) { return propInfo.GetMethod; }
public static Type[] GetGenericArguments(this Type type) { return type.GenericTypeArguments; }
public static MethodInfo[] GetMethods(this Type type, BindingFlags flags)
{
// Minimal implementation to cover only the cases we need
System.Diagnostics.Debug.Assert((flags & BindingFlags.DeclaredOnly) != 0);
System.Diagnostics.Debug.Assert((flags & ~(BindingFlags.DeclaredOnly|BindingFlags.Instance|BindingFlags.Static|BindingFlags.Public|BindingFlags.NonPublic)) == 0);
Func<MethodInfo, bool> visFilter;
Func<MethodInfo, bool> instFilter;
switch (flags & (BindingFlags.Public | BindingFlags.NonPublic))
{
case 0: visFilter = mi => false; break;
case BindingFlags.Public: visFilter = mi => mi.IsPublic; break;
case BindingFlags.NonPublic: visFilter = mi => !mi.IsPublic; break;
default: visFilter = mi => true; break;
}
switch (flags & (BindingFlags.Instance | BindingFlags.Static))
{
case 0: instFilter = mi => false; break;
case BindingFlags.Instance: instFilter = mi => !mi.IsStatic; break;
case BindingFlags.Static: instFilter = mi => mi.IsStatic; break;
default: instFilter = mi => true; break;
}
List<MethodInfo> methodInfos = new List<MethodInfo>();
foreach (var declaredMethod in type.GetTypeInfo().DeclaredMethods)
{
if (visFilter(declaredMethod) && instFilter(declaredMethod))
methodInfos.Add(declaredMethod);
}
return methodInfos.ToArray();
}
public static FieldInfo[] GetFields(this Type type, BindingFlags flags)
{
// Minimal implementation to cover only the cases we need
System.Diagnostics.Debug.Assert((flags & BindingFlags.DeclaredOnly) != 0);
System.Diagnostics.Debug.Assert((flags & ~(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)) == 0);
Func<FieldInfo, bool> visFilter;
Func<FieldInfo, bool> instFilter;
switch (flags & (BindingFlags.Public | BindingFlags.NonPublic))
{
case 0: visFilter = fi => false; break;
case BindingFlags.Public: visFilter = fi => fi.IsPublic; break;
case BindingFlags.NonPublic: visFilter = fi => !fi.IsPublic; break;
default: visFilter = fi => true; break;
}
switch (flags & (BindingFlags.Instance | BindingFlags.Static))
{
case 0: instFilter = fi => false; break;
case BindingFlags.Instance: instFilter = fi => !fi.IsStatic; break;
case BindingFlags.Static: instFilter = fi => fi.IsStatic; break;
default: instFilter = fi => true; break;
}
List<FieldInfo> fieldInfos = new List<FieldInfo>();
foreach (var declaredField in type.GetTypeInfo().DeclaredFields)
{
if (visFilter(declaredField) && instFilter(declaredField))
fieldInfos.Add(declaredField);
}
return fieldInfos.ToArray();
}
public static Type GetNestedType(this Type type, string nestedTypeName)
{
TypeInfo ti = null;
foreach(var nt in type.GetTypeInfo().DeclaredNestedTypes)
{
if (nt.Name == nestedTypeName)
{
ti = nt;
break;
}
}
return ti == null ? null : ti.AsType();
}
public static TypeCode GetTypeCode(this Type type)
{
if (type == typeof(bool)) return TypeCode.Boolean;
else if (type == typeof(byte)) return TypeCode.Byte;
else if (type == typeof(char)) return TypeCode.Char;
else if (type == typeof(ushort)) return TypeCode.UInt16;
else if (type == typeof(uint)) return TypeCode.UInt32;
else if (type == typeof(ulong)) return TypeCode.UInt64;
else if (type == typeof(sbyte)) return TypeCode.SByte;
else if (type == typeof(short)) return TypeCode.Int16;
else if (type == typeof(int)) return TypeCode.Int32;
else if (type == typeof(long)) return TypeCode.Int64;
else if (type == typeof(string)) return TypeCode.String;
else if (type == typeof(float)) return TypeCode.Single;
else if (type == typeof(double)) return TypeCode.Double;
else if (type == typeof(DateTime)) return TypeCode.DateTime;
else if (type == (typeof(decimal))) return TypeCode.Decimal;
else return TypeCode.Object;
}
//
// FieldInfo extension methods
//
public static object GetRawConstantValue(this FieldInfo fi)
{ return fi.GetValue(null); }
//
// Assembly extension methods
//
public static bool ReflectionOnly(this Assembly assm)
{
// In PCL we can't load in reflection-only context
return false;
}
#endif
}
}
#if ES_BUILD_STANDALONE
internal static partial class Interop
{
[SuppressUnmanagedCodeSecurityAttribute()]
internal static partial class Kernel32
{
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
internal static extern int GetCurrentThreadId();
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
internal static extern uint GetCurrentProcessId();
}
}
#endif
| |
// ****************************************************************
// Copyright 2007, Charlie Poole
// This is free software licensed under the NUnit license. You may
// obtain a copy of the license at http://nunit.org
// ****************************************************************
using System;
using System.Collections;
using System.Reflection;
using System.Text;
#if CLR_2_0 || CLR_4_0
using System.Collections.Generic;
#endif
using ArrayList = System.Collections.Generic.List<object>;
namespace NUnit.Framework.Constraints
{
#region CollectionConstraint
/// <summary>
/// CollectionConstraint is the abstract base class for
/// constraints that operate on collections.
/// </summary>
public abstract class CollectionConstraint : Constraint
{
/// <summary>
/// Construct an empty CollectionConstraint
/// </summary>
public CollectionConstraint() { }
/// <summary>
/// Construct a CollectionConstraint
/// </summary>
/// <param name="arg"></param>
public CollectionConstraint(object arg) : base(arg) { }
/// <summary>
/// Determines whether the specified enumerable is empty.
/// </summary>
/// <param name="enumerable">The enumerable.</param>
/// <returns>
/// <c>true</c> if the specified enumerable is empty; otherwise, <c>false</c>.
/// </returns>
protected static bool IsEmpty( IEnumerable enumerable )
{
ICollection collection = enumerable as ICollection;
if ( collection != null )
return collection.Count == 0;
foreach (object o in enumerable)
return false;
return true;
}
/// <summary>
/// Test whether the constraint is satisfied by a given value
/// </summary>
/// <param name="actual">The value to be tested</param>
/// <returns>True for success, false for failure</returns>
public override bool Matches(object actual)
{
this.actual = actual;
IEnumerable enumerable = actual as IEnumerable;
if ( enumerable == null )
throw new ArgumentException( "The actual value must be an IEnumerable", "actual" );
return doMatch( enumerable );
}
/// <summary>
/// Protected method to be implemented by derived classes
/// </summary>
/// <param name="collection"></param>
/// <returns></returns>
protected abstract bool doMatch(IEnumerable collection);
}
#endregion
#region CollectionItemsEqualConstraint
/// <summary>
/// CollectionItemsEqualConstraint is the abstract base class for all
/// collection constraints that apply some notion of item equality
/// as a part of their operation.
/// </summary>
public abstract class CollectionItemsEqualConstraint : CollectionConstraint
{
// This is internal so that ContainsConstraint can set it
// TODO: Figure out a way to avoid this indirection
internal NUnitEqualityComparer comparer = NUnitEqualityComparer.Default;
/// <summary>
/// Construct an empty CollectionConstraint
/// </summary>
public CollectionItemsEqualConstraint() { }
/// <summary>
/// Construct a CollectionConstraint
/// </summary>
/// <param name="arg"></param>
public CollectionItemsEqualConstraint(object arg) : base(arg) { }
#region Modifiers
/// <summary>
/// Flag the constraint to ignore case and return self.
/// </summary>
public CollectionItemsEqualConstraint IgnoreCase
{
get
{
comparer.IgnoreCase = true;
return this;
}
}
/// <summary>
/// Flag the constraint to use the supplied IComparer object.
/// </summary>
/// <param name="comparer">The IComparer object to use.</param>
/// <returns>Self.</returns>
public CollectionItemsEqualConstraint Using(IComparer comparer)
{
this.comparer.ExternalComparers.Add(EqualityAdapter.For(comparer));
return this;
}
#if CLR_2_0 || CLR_4_0
/// <summary>
/// Flag the constraint to use the supplied IComparer object.
/// </summary>
/// <param name="comparer">The IComparer object to use.</param>
/// <returns>Self.</returns>
public CollectionItemsEqualConstraint Using<T>(IComparer<T> comparer)
{
this.comparer.ExternalComparers.Add(EqualityAdapter.For(comparer));
return this;
}
/// <summary>
/// Flag the constraint to use the supplied Comparison object.
/// </summary>
/// <param name="comparer">The IComparer object to use.</param>
/// <returns>Self.</returns>
public CollectionItemsEqualConstraint Using<T>(Comparison<T> comparer)
{
this.comparer.ExternalComparers.Add(EqualityAdapter.For(comparer));
return this;
}
/// <summary>
/// Flag the constraint to use the supplied IEqualityComparer object.
/// </summary>
/// <param name="comparer">The IComparer object to use.</param>
/// <returns>Self.</returns>
public CollectionItemsEqualConstraint Using(IEqualityComparer comparer)
{
this.comparer.ExternalComparers.Add(EqualityAdapter.For(comparer));
return this;
}
/// <summary>
/// Flag the constraint to use the supplied IEqualityComparer object.
/// </summary>
/// <param name="comparer">The IComparer object to use.</param>
/// <returns>Self.</returns>
public CollectionItemsEqualConstraint Using<T>(IEqualityComparer<T> comparer)
{
this.comparer.ExternalComparers.Add(EqualityAdapter.For(comparer));
return this;
}
#endif
#endregion
/// <summary>
/// Compares two collection members for equality
/// </summary>
protected bool ItemsEqual(object x, object y)
{
Tolerance tolerance = Tolerance.Zero;
return comparer.AreEqual(x, y, ref tolerance);
}
/// <summary>
/// Return a new CollectionTally for use in making tests
/// </summary>
/// <param name="c">The collection to be included in the tally</param>
protected CollectionTally Tally(IEnumerable c)
{
return new CollectionTally(comparer, c);
}
}
#endregion
#region EmptyCollectionConstraint
/// <summary>
/// EmptyCollectionConstraint tests whether a collection is empty.
/// </summary>
public class EmptyCollectionConstraint : CollectionConstraint
{
/// <summary>
/// Check that the collection is empty
/// </summary>
/// <param name="collection"></param>
/// <returns></returns>
protected override bool doMatch(IEnumerable collection)
{
return IsEmpty( collection );
}
/// <summary>
/// Write the constraint description to a MessageWriter
/// </summary>
/// <param name="writer"></param>
public override void WriteDescriptionTo(MessageWriter writer)
{
writer.Write( "<empty>" );
}
}
#endregion
#region UniqueItemsConstraint
/// <summary>
/// UniqueItemsConstraint tests whether all the items in a
/// collection are unique.
/// </summary>
public class UniqueItemsConstraint : CollectionItemsEqualConstraint
{
/// <summary>
/// Check that all items are unique.
/// </summary>
/// <param name="actual"></param>
/// <returns></returns>
protected override bool doMatch(IEnumerable actual)
{
ArrayList list = new ArrayList();
foreach (object o1 in actual)
{
foreach( object o2 in list )
if ( ItemsEqual(o1, o2) )
return false;
list.Add(o1);
}
return true;
}
/// <summary>
/// Write a description of this constraint to a MessageWriter
/// </summary>
/// <param name="writer"></param>
public override void WriteDescriptionTo(MessageWriter writer)
{
writer.Write("all items unique");
}
}
#endregion
#region CollectionContainsConstraint
/// <summary>
/// CollectionContainsConstraint is used to test whether a collection
/// contains an expected object as a member.
/// </summary>
public class CollectionContainsConstraint : CollectionItemsEqualConstraint
{
private object expected;
/// <summary>
/// Construct a CollectionContainsConstraint
/// </summary>
/// <param name="expected"></param>
public CollectionContainsConstraint(object expected)
: base(expected)
{
this.expected = expected;
this.DisplayName = "contains";
}
/// <summary>
/// Test whether the expected item is contained in the collection
/// </summary>
/// <param name="actual"></param>
/// <returns></returns>
protected override bool doMatch(IEnumerable actual)
{
foreach (object obj in actual)
if (ItemsEqual(obj, expected))
return true;
return false;
}
/// <summary>
/// Write a descripton of the constraint to a MessageWriter
/// </summary>
/// <param name="writer"></param>
public override void WriteDescriptionTo(MessageWriter writer)
{
writer.WritePredicate("collection containing");
writer.WriteExpectedValue(expected);
}
}
#endregion
#region CollectionEquivalentConstraint
/// <summary>
/// CollectionEquivalentCOnstraint is used to determine whether two
/// collections are equivalent.
/// </summary>
public class CollectionEquivalentConstraint : CollectionItemsEqualConstraint
{
private IEnumerable expected;
/// <summary>
/// Construct a CollectionEquivalentConstraint
/// </summary>
/// <param name="expected"></param>
public CollectionEquivalentConstraint(IEnumerable expected) : base(expected)
{
this.expected = expected;
this.DisplayName = "equivalent";
}
/// <summary>
/// Test whether two collections are equivalent
/// </summary>
/// <param name="actual"></param>
/// <returns></returns>
protected override bool doMatch(IEnumerable actual)
{
// This is just an optimization
if( expected is ICollection && actual is ICollection )
if( ((ICollection)actual).Count != ((ICollection)expected).Count )
return false;
CollectionTally tally = Tally(expected);
return tally.TryRemove(actual) && tally.Count == 0;
}
/// <summary>
/// Write a description of this constraint to a MessageWriter
/// </summary>
/// <param name="writer"></param>
public override void WriteDescriptionTo(MessageWriter writer)
{
writer.WritePredicate("equivalent to");
writer.WriteExpectedValue(expected);
}
}
#endregion
#region CollectionSubsetConstraint
/// <summary>
/// CollectionSubsetConstraint is used to determine whether
/// one collection is a subset of another
/// </summary>
public class CollectionSubsetConstraint : CollectionItemsEqualConstraint
{
private IEnumerable expected;
/// <summary>
/// Construct a CollectionSubsetConstraint
/// </summary>
/// <param name="expected">The collection that the actual value is expected to be a subset of</param>
public CollectionSubsetConstraint(IEnumerable expected) : base(expected)
{
this.expected = expected;
this.DisplayName = "subsetof";
}
/// <summary>
/// Test whether the actual collection is a subset of
/// the expected collection provided.
/// </summary>
/// <param name="actual"></param>
/// <returns></returns>
protected override bool doMatch(IEnumerable actual)
{
return Tally(expected).TryRemove( actual );
}
/// <summary>
/// Write a description of this constraint to a MessageWriter
/// </summary>
/// <param name="writer"></param>
public override void WriteDescriptionTo(MessageWriter writer)
{
writer.WritePredicate( "subset of" );
writer.WriteExpectedValue(expected);
}
}
#endregion
#region CollectionOrderedConstraint
/// <summary>
/// CollectionOrderedConstraint is used to test whether a collection is ordered.
/// </summary>
public class CollectionOrderedConstraint : CollectionConstraint
{
private ComparisonAdapter comparer = ComparisonAdapter.Default;
private string comparerName;
private string propertyName;
private bool descending;
/// <summary>
/// Construct a CollectionOrderedConstraint
/// </summary>
public CollectionOrderedConstraint()
{
this.DisplayName = "ordered";
}
///<summary>
/// If used performs a reverse comparison
///</summary>
public CollectionOrderedConstraint Descending
{
get
{
descending = true;
return this;
}
}
/// <summary>
/// Modifies the constraint to use an IComparer and returns self.
/// </summary>
public CollectionOrderedConstraint Using(IComparer comparer)
{
this.comparer = ComparisonAdapter.For( comparer );
this.comparerName = comparer.GetType().FullName;
return this;
}
#if CLR_2_0 || CLR_4_0
/// <summary>
/// Modifies the constraint to use an IComparer<T> and returns self.
/// </summary>
public CollectionOrderedConstraint Using<T>(IComparer<T> comparer)
{
this.comparer = ComparisonAdapter.For(comparer);
this.comparerName = comparer.GetType().FullName;
return this;
}
/// <summary>
/// Modifies the constraint to use a Comparison<T> and returns self.
/// </summary>
public CollectionOrderedConstraint Using<T>(Comparison<T> comparer)
{
this.comparer = ComparisonAdapter.For(comparer);
this.comparerName = comparer.GetType().FullName;
return this;
}
#endif
/// <summary>
/// Modifies the constraint to test ordering by the value of
/// a specified property and returns self.
/// </summary>
public CollectionOrderedConstraint By(string propertyName)
{
this.propertyName = propertyName;
return this;
}
/// <summary>
/// Test whether the collection is ordered
/// </summary>
/// <param name="actual"></param>
/// <returns></returns>
protected override bool doMatch(IEnumerable actual)
{
object previous = null;
int index = 0;
foreach(object obj in actual)
{
object objToCompare = obj;
if (obj == null)
throw new ArgumentNullException("actual", "Null value at index " + index.ToString());
if (this.propertyName != null)
{
PropertyInfo prop = obj.GetType().GetProperty(propertyName);
objToCompare = prop.GetValue(obj, null);
if (objToCompare == null)
throw new ArgumentNullException("actual", "Null property value at index " + index.ToString());
}
if (previous != null)
{
//int comparisonResult = comparer.Compare(al[i], al[i + 1]);
int comparisonResult = comparer.Compare(previous, objToCompare);
if (descending && comparisonResult < 0)
return false;
if (!descending && comparisonResult > 0)
return false;
}
previous = objToCompare;
index++;
}
return true;
}
/// <summary>
/// Write a description of the constraint to a MessageWriter
/// </summary>
/// <param name="writer"></param>
public override void WriteDescriptionTo(MessageWriter writer)
{
if (propertyName == null)
writer.Write("collection ordered");
else
{
writer.WritePredicate("collection ordered by");
writer.WriteExpectedValue(propertyName);
}
if (descending)
writer.WriteModifier("descending");
}
/// <summary>
/// Returns the string representation of the constraint.
/// </summary>
/// <returns></returns>
protected override string GetStringRepresentation()
{
StringBuilder sb = new StringBuilder("<ordered");
if (propertyName != null)
sb.Append("by " + propertyName);
if (descending)
sb.Append(" descending");
if (comparerName != null)
sb.Append(" " + comparerName);
sb.Append(">");
return sb.ToString();
}
}
#endregion
}
| |
/*$ preserve start $*/
/* ========================================================================================== */
/* FMOD Ex - DSP header file. Copyright (c), Firelight Technologies Pty, Ltd. 2004-2008. */
/* */
/* Use this header if you are interested in delving deeper into the FMOD software mixing / */
/* DSP engine. In this header you can find parameter structures for FMOD system reigstered */
/* DSP effects and generators. */
/* */
/* ========================================================================================== */
using System;
using System.Text;
using System.Runtime.InteropServices;
namespace FMOD
{
/*$ preserve end $*/
/*
DSP callbacks
*/
public delegate RESULT DSP_CREATECALLBACK (ref DSP_STATE dsp_state);
public delegate RESULT DSP_RELEASECALLBACK (ref DSP_STATE dsp_state);
public delegate RESULT DSP_RESETCALLBACK (ref DSP_STATE dsp_state);
public delegate RESULT DSP_READCALLBACK (ref DSP_STATE dsp_state, IntPtr inbuffer, IntPtr outbuffer, uint length, int inchannels, int outchannels);
public delegate RESULT DSP_SETPOSITIONCALLBACK (ref DSP_STATE dsp_state, uint seeklen);
public delegate RESULT DSP_SETPARAMCALLBACK (ref DSP_STATE dsp_state, int index, float val);
public delegate RESULT DSP_GETPARAMCALLBACK (ref DSP_STATE dsp_state, int index, ref float val, StringBuilder valuestr);
public delegate RESULT DSP_DIALOGCALLBACK (ref DSP_STATE dsp_state, IntPtr hwnd, bool show);
/*
[ENUM]
[
[DESCRIPTION]
These definitions can be used for creating FMOD defined special effects or DSP units.
[REMARKS]
To get them to be active, first create the unit, then add it somewhere into the DSP network, either at the front of the network near the soundcard unit to affect the global output (by using System::getDSPHead), or on a single channel (using Channel::getDSPHead).
[PLATFORMS]
Win32, Win64, Linux, Linux64, Macintosh, Xbox, Xbox360, PlayStation 2, GameCube, PlayStation Portable, PlayStation 3, Wii
[SEE_ALSO]
System::createDSPByType
]
*/
public enum DSP_TYPE
{
UNKNOWN, /* This unit was created via a non FMOD plugin so has an unknown purpose */
MIXER, /* This unit does nothing but take inputs and mix them together then feed the result to the soundcard unit. */
OSCILLATOR, /* This unit generates sine/square/saw/triangle or noise tones. */
LOWPASS, /* This unit filters sound using a high quality, resonant lowpass filter algorithm but consumes more CPU time. */
ITLOWPASS, /* This unit filters sound using a resonant lowpass filter algorithm that is used in Impulse Tracker, but with limited cutoff range (0 to 8060hz). */
HIGHPASS, /* This unit filters sound using a resonant highpass filter algorithm. */
ECHO, /* This unit produces an echo on the sound and fades out at the desired rate. */
FLANGE, /* This unit produces a flange effect on the sound. */
DISTORTION, /* This unit distorts the sound. */
NORMALIZE, /* This unit normalizes or amplifies the sound to a certain level. */
PARAMEQ, /* This unit attenuates or amplifies a selected frequency range. */
PITCHSHIFT, /* This unit bends the pitch of a sound without changing the speed of playback. */
CHORUS, /* This unit produces a chorus effect on the sound. */
REVERB, /* This unit produces a reverb effect on the sound. */
VSTPLUGIN, /* This unit allows the use of Steinberg VST plugins */
WINAMPPLUGIN, /* This unit allows the use of Nullsoft Winamp plugins */
ITECHO, /* This unit produces an echo on the sound and fades out at the desired rate as is used in Impulse Tracker. */
COMPRESSOR, /* This unit implements dynamic compression (linked multichannel, wideband) */
SFXREVERB, /* This unit implements SFX reverb */
LOWPASS_SIMPLE /* This unit filters sound using a simple lowpass with no resonance, but has flexible cutoff and is fast. */
}
/*
[STRUCTURE]
[
[DESCRIPTION]
[REMARKS]
Members marked with [in] mean the user sets the value before passing it to the function.<br>
Members marked with [out] mean FMOD sets the value to be used after the function exits.<br>
<br>
The step parameter tells the gui or application that the parameter has a certain granularity.<br>
For example in the example of cutoff frequency with a range from 100.0 to 22050.0 you might only want the selection to be in 10hz increments. For this you would simply use 10.0 as the step value.<br>
For a boolean, you can use min = 0.0, max = 1.0, step = 1.0. This way the only possible values are 0.0 and 1.0.<br>
Some applications may detect min = 0.0, max = 1.0, step = 1.0 and replace a graphical slider bar with a checkbox instead.<br>
A step value of 1.0 would simulate integer values only.<br>
A step value of 0.0 would mean the full floating point range is accessable.<br>
[PLATFORMS]
Win32, Win64, Linux, Linux64, Macintosh, Xbox, Xbox360, PlayStation 2, GameCube, PlayStation Portable, PlayStation 3, Wii
[SEE_ALSO]
System::createDSP
System::getDSP
]
*/
public struct DSP_PARAMETERDESC
{
public float min; /* [in] Minimum value of the parameter (ie 100.0). */
public float max; /* [in] Maximum value of the parameter (ie 22050.0). */
public float defaultval; /* [in] Default value of parameter. */
public string name; /* [in] Name of the parameter to be displayed (ie "Cutoff frequency"). */
public string label; /* [in] Short string to be put next to value to denote the unit type (ie "hz"). */
public string description; /* [in] Description of the parameter to be displayed as a help item / tooltip for this parameter. */
}
/*
[STRUCTURE]
[
[DESCRIPTION]
Strcture to define the parameters for a DSP unit.
[REMARKS]
Members marked with [in] mean the user sets the value before passing it to the function.<br>
Members marked with [out] mean FMOD sets the value to be used after the function exits.<br>
<br>
There are 2 different ways to change a parameter in this architecture.<br>
One is to use DSP::setParameter / DSP::getParameter. This is platform independant and is dynamic, so new unknown plugins can have their parameters enumerated and used.<br>
The other is to use DSP::showConfigDialog. This is platform specific and requires a GUI, and will display a dialog box to configure the plugin.<br>
[PLATFORMS]
Win32, Win64, Linux, Linux64, Macintosh, Xbox, Xbox360, PlayStation 2, GameCube, PlayStation Portable, PlayStation 3, Wii
[SEE_ALSO]
System::createDSP
System::getDSP
]
*/
public struct DSP_DESCRIPTION
{
[MarshalAs(UnmanagedType.ByValArray,SizeConst=32)]
public char[] name; /* [in] Name of the unit to be displayed in the network. */
public uint version; /* [in] Plugin writer's version number. */
public int channels; /* [in] Number of channels. Use 0 to process whatever number of channels is currently in the network. >0 would be mostly used if the unit is a unit that only generates sound. */
public DSP_CREATECALLBACK create; /* [in] Create callback. This is called when DSP unit is created. Can be null. */
public DSP_RELEASECALLBACK release; /* [in] Release callback. This is called just before the unit is freed so the user can do any cleanup needed for the unit. Can be null. */
public DSP_RESETCALLBACK reset; /* [in] Reset callback. This is called by the user to reset any history buffers that may need resetting for a filter, when it is to be used or re-used for the first time to its initial clean state. Use to avoid clicks or artifacts. */
public DSP_READCALLBACK read; /* [in] Read callback. Processing is done here. Can be null. */
public DSP_SETPOSITIONCALLBACK setposition; /* [in] Setposition callback. This is called if the unit wants to update its position info but not process data. Can be null. */
public int numparameters; /* [in] Number of parameters used in this filter. The user finds this with DSP::getNumParameters */
public DSP_PARAMETERDESC[] paramdesc; /* [in] Variable number of parameter structures. */
public DSP_SETPARAMCALLBACK setparameter; /* [in] This is called when the user calls DSP::setParameter. Can be null. */
public DSP_GETPARAMCALLBACK getparameter; /* [in] This is called when the user calls DSP::getParameter. Can be null. */
public DSP_DIALOGCALLBACK config; /* [in] This is called when the user calls DSP::showConfigDialog. Can be used to display a dialog to configure the filter. Can be null. */
public int configwidth; /* [in] Width of config dialog graphic if there is one. 0 otherwise.*/
public int configheight; /* [in] Height of config dialog graphic if there is one. 0 otherwise.*/
public IntPtr userdata; /* [in] Optional. Specify 0 to ignore. This is user data to be attached to the DSP unit during creation. Access via DSP::getUserData. */
}
/*
[STRUCTURE]
[
[DESCRIPTION]
DSP plugin structure that is passed into each callback.
[REMARKS]
Members marked with [in] mean the variable can be written to. The user can set the value.<br>
Members marked with [out] mean the variable is modified by FMOD and is for reading purposes only. Do not change this value.<br>
[PLATFORMS]
Win32, Win64, Linux, Linux64, Macintosh, Xbox, Xbox360, PlayStation 2, GameCube, PlayStation Portable, PlayStation 3
[SEE_ALSO]
FMOD_DSP_DESCRIPTION
]
*/
public struct DSP_STATE
{
public IntPtr instance; /* [out] Handle to the DSP hand the user created. Not to be modified. C++ users cast to FMOD::DSP to use. */
public IntPtr plugindata; /* [in] Plugin writer created data the output author wants to attach to this object. */
public ushort speakermask; /* Specifies which speakers the DSP effect is active on */
};
/*
==============================================================================================================
FMOD built in effect parameters.
Use DSP::setParameter with these enums for the 'index' parameter.
==============================================================================================================
*/
/*
[ENUM]
[
[DESCRIPTION]
Parameter types for the FMOD_DSP_TYPE_OSCILLATOR filter.
[REMARKS]
[PLATFORMS]
Win32, Win64, Linux, Linux64, Macintosh, Xbox, Xbox360, PlayStation 2, GameCube, PlayStation Portable, PlayStation 3, Wii
[SEE_ALSO]
DSP::setParameter
DSP::getParameter
FMOD_DSP_TYPE
]
*/
public enum DSP_OSCILLATOR
{
TYPE, /* Waveform type. 0 = sine. 1 = square. 2 = sawup. 3 = sawdown. 4 = triangle. 5 = noise. */
RATE /* Frequency of the sinewave in hz. 1.0 to 22000.0. Default = 220.0. */
}
/*
[ENUM]
[
[DESCRIPTION]
Parameter types for the FMOD_DSP_TYPE_LOWPASS filter.
[REMARKS]
[PLATFORMS]
Win32, Win64, Linux, Linux64, Macintosh, Xbox, Xbox360, PlayStation 2, GameCube, PlayStation Portable, PlayStation 3, Wii
[SEE_ALSO]
DSP::setParameter
DSP::getParameter
FMOD_DSP_TYPE
]
*/
public enum DSP_LOWPASS
{
CUTOFF, /* Lowpass cutoff frequency in hz. 1.0 to 22000.0. Default = 5000.0. */
RESONANCE /* Lowpass resonance Q value. 1.0 to 10.0. Default = 1.0. */
}
/*
[ENUM]
[
[DESCRIPTION]
Parameter types for the FMOD_DSP_TYPE_ITLOWPASS filter.
This is different to the default FMOD_DSP_TYPE_ITLOWPASS filter in that it uses a different quality algorithm and is
the filter used to produce the correct sounding playback in .IT files.<br>
FMOD Ex's .IT playback uses this filter.<br>
[REMARKS]
Note! This filter actually has a limited cutoff frequency below the specified maximum, due to its limited design,
so for a more open range filter use FMOD_DSP_LOWPASS or if you don't mind not having resonance,
FMOD_DSP_LOWPASS_SIMPLE.<br>
The effective maximum cutoff is about 8060hz.
[PLATFORMS]
Win32, Win64, Linux, Linux64, Macintosh, Xbox, Xbox360, PlayStation 2, GameCube, PlayStation Portable, PlayStation 3, Wii
[SEE_ALSO]
DSP::setParameter
DSP::getParameter
FMOD_DSP_TYPE
]
*/
public enum DSP_ITLOWPASS
{
CUTOFF, /* Lowpass cutoff frequency in hz. 1.0 to 22000.0. Default = 5000.0/ */
RESONANCE /* Lowpass resonance Q value. 0.0 to 127.0. Default = 1.0. */
}
/*
[ENUM]
[
[DESCRIPTION]
Parameter types for the FMOD_DSP_TYPE_HIGHPASS filter.
[REMARKS]
[PLATFORMS]
Win32, Win64, Linux, Linux64, Macintosh, Xbox, Xbox360, PlayStation 2, GameCube, PlayStation Portable, PlayStation 3, Wii
[SEE_ALSO]
DSP::setParameter
DSP::getParameter
FMOD_DSP_TYPE
]
*/
public enum DSP_HIGHPASS
{
CUTOFF, /* Highpass cutoff frequency in hz. 10.0 to output 22000.0. Default = 5000.0. */
RESONANCE /* Highpass resonance Q value. 1.0 to 10.0. Default = 1.0. */
}
/*
[ENUM]
[
[DESCRIPTION]
Parameter types for the FMOD_DSP_TYPE_ECHO filter.
[REMARKS]
Note. Every time the delay is changed, the plugin re-allocates the echo buffer. This means the echo will dissapear at that time while it refills its new buffer.<br>
Larger echo delays result in larger amounts of memory allocated.<br>
<br>
'<i>maxchannels</i>' also dictates the amount of memory allocated. By default, the maxchannels value is 0. If FMOD is set to stereo, the echo unit will allocate enough memory for 2 channels. If it is 5.1, it will allocate enough memory for a 6 channel echo, etc.<br>
If the echo effect is only ever applied to the global mix (ie it was added with System::addDSP), then 0 is the value to set as it will be enough to handle all speaker modes.<br>
When the echo is added to a channel (ie Channel::addDSP) then the channel count that comes in could be anything from 1 to 8 possibly. It is only in this case where you might want to increase the channel count above the output's channel count.<br>
If a channel echo is set to a lower number than the sound's channel count that is coming in, it will not echo the sound.<br>
[PLATFORMS]
Win32, Win64, Linux, Linux64, Macintosh, Xbox, Xbox360, PlayStation 2, GameCube, PlayStation Portable, PlayStation 3, Wii
[SEE_ALSO]
DSP::setParameter
DSP::getParameter
FMOD_DSP_TYPE
]
*/
public enum DSP_ECHO
{
DELAY, /* Echo delay in ms. 10 to 5000. Default = 500. */
DECAYRATIO, /* Echo decay per delay. 0 to 1. 1.0 = No decay, 0.0 = total decay. Default = 0.5. */
MAXCHANNELS, /* Maximum channels supported. 0 to 16. 0 = same as fmod's default output polyphony, 1 = mono, 2 = stereo etc. See remarks for more. Default = 0. It is suggested to leave at 0! */
DRYMIX, /* Volume of original signal to pass to output. 0.0 to 1.0. Default = 1.0. */
WETMIX /* Volume of echo signal to pass to output. 0.0 to 1.0. Default = 1.0. */
}
/*
[ENUM]
[
[DESCRIPTION]
Parameter types for the FMOD_DSP_TYPE_FLANGE filter.
[REMARKS]
Flange is an effect where the signal is played twice at the same time, and one copy slides back and forth creating a whooshing or flanging effect.<br>
As there are 2 copies of the same signal, by default each signal is given 50% mix, so that the total is not louder than the original unaffected signal.<br>
<br>
Flange depth is a percentage of a 10ms shift from the original signal. Anything above 10ms is not considered flange because to the ear it begins to 'echo' so 10ms is the highest value possible.<br>
[PLATFORMS]
Win32, Win64, Linux, Linux64, Macintosh, Xbox, Xbox360, PlayStation 2, GameCube, PlayStation Portable, PlayStation 3, Wii
[SEE_ALSO]
DSP::setParameter
DSP::getParameter
FMOD_DSP_TYPE
]
*/
public enum DSP_FLANGE
{
DRYMIX, /* Volume of original signal to pass to output. 0.0 to 1.0. Default = 0.45. */
WETMIX, /* Volume of flange signal to pass to output. 0.0 to 1.0. Default = 0.55. */
DEPTH, /* Flange depth. 0.01 to 1.0. Default = 1.0. */
RATE /* Flange speed in hz. 0.0 to 20.0. Default = 0.1. */
}
/*
[ENUM]
[
[DESCRIPTION]
Parameter types for the FMOD_DSP_TYPE_DISTORTION filter.
[REMARKS]
[PLATFORMS]
Win32, Win64, Linux, Linux64, Macintosh, Xbox, Xbox360, PlayStation 2, GameCube, PlayStation Portable, PlayStation 3, Wii
[SEE_ALSO]
DSP::setParameter
DSP::getParameter
FMOD_DSP_TYPE
]
*/
public enum DSP_DISTORTION
{
LEVEL /* Distortion value. 0.0 to 1.0. Default = 0.5. */
}
/*
[ENUM]
[
[DESCRIPTION]
Parameter types for the FMOD_DSP_TYPE_NORMALIZE filter.
[REMARKS]
Normalize amplifies the sound based on the maximum peaks within the signal.<br>
For example if the maximum peaks in the signal were 50% of the bandwidth, it would scale the whole sound by 2.<br>
The lower threshold value makes the normalizer ignores peaks below a certain point, to avoid over-amplification if a loud signal suddenly came in, and also to avoid amplifying to maximum things like background hiss.<br>
<br>
Because FMOD is a realtime audio processor, it doesn't have the luxury of knowing the peak for the whole sound (ie it can't see into the future), so it has to process data as it comes in.<br>
To avoid very sudden changes in volume level based on small samples of new data, fmod fades towards the desired amplification which makes for smooth gain control. The fadetime parameter can control this.<br>
[PLATFORMS]
Win32, Win64, Linux, Linux64, Macintosh, Xbox, Xbox360, PlayStation 2, GameCube, PlayStation Portable, PlayStation 3, Wii
[SEE_ALSO]
DSP::setParameter
DSP::getParameter
FMOD_DSP_TYPE
]
*/
public enum DSP_NORMALIZE
{
FADETIME, /* Time to ramp the silence to full in ms. 0.0 to 20000.0. Default = 5000.0. */
THRESHHOLD, /* Lower volume range threshold to ignore. 0.0 to 1.0. Default = 0.1. Raise higher to stop amplification of very quiet signals. */
MAXAMP /* Maximum amplification allowed. 1.0 to 100000.0. Default = 20.0. 1.0 = no amplifaction, higher values allow more boost. */
}
/*
[ENUM]
[
[DESCRIPTION]
Parameter types for the FMOD_DSP_TYPE_PARAMEQ filter.
[REMARKS]
Parametric EQ is a bandpass filter that attenuates or amplifies a selected frequency and its neighbouring frequencies.<br>
<br>
To create a multi-band EQ create multiple FMOD_DSP_TYPE_PARAMEQ units and set each unit to different frequencies, for example 1000hz, 2000hz, 4000hz, 8000hz, 16000hz with a range of 1 octave each.<br>
<br>
When a frequency has its gain set to 1.0, the sound will be unaffected and represents the original signal exactly.<br>
[PLATFORMS]
Win32, Win64, Linux, Linux64, Macintosh, Xbox, Xbox360, PlayStation 2, GameCube, PlayStation Portable, PlayStation 3, Wii
[SEE_ALSO]
DSP::setParameter
DSP::getParameter
FMOD_DSP_TYPE
]
*/
public enum DSP_PARAMEQ
{
CENTER, /* Frequency center. 20.0 to 22000.0. Default = 8000.0. */
BANDWIDTH, /* Octave range around the center frequency to filter. 0.2 to 5.0. Default = 1.0. */
GAIN /* Frequency Gain. 0.05 to 3.0. Default = 1.0. */
}
/*
[ENUM]
[
[DESCRIPTION]
Parameter types for the FMOD_DSP_TYPE_PITCHSHIFT filter.
[REMARKS]
This pitch shifting unit can be used to change the pitch of a sound without speeding it up or slowing it down.<br>
It can also be used for time stretching or scaling, for example if the pitch was doubled, and the frequency of the sound was halved, the pitch of the sound would sound correct but it would be twice as slow.<br>
<br>
<b>Warning!</b> This filter is very computationally expensive! Similar to a vocoder, it requires several overlapping FFT and IFFT's to produce smooth output, and can require around 440mhz for 1 stereo 48khz signal using the default settings.<br>
Reducing the signal to mono will half the cpu usage, as will the overlap count.<br>
Reducing this will lower audio quality, but what settings to use are largely dependant on the sound being played. A noisy polyphonic signal will need higher overlap and fft size compared to a speaking voice for example.<br>
<br>
This pitch shifter is based on the pitch shifter code at http://www.dspdimension.com, written by Stephan M. Bernsee.<br>
The original code is COPYRIGHT 1999-2003 Stephan M. Bernsee <smb@dspdimension.com>.<br>
<br>
'<i>maxchannels</i>' dictates the amount of memory allocated. By default, the maxchannels value is 0. If FMOD is set to stereo, the pitch shift unit will allocate enough memory for 2 channels. If it is 5.1, it will allocate enough memory for a 6 channel pitch shift, etc.<br>
If the pitch shift effect is only ever applied to the global mix (ie it was added with System::addDSP), then 0 is the value to set as it will be enough to handle all speaker modes.<br>
When the pitch shift is added to a channel (ie Channel::addDSP) then the channel count that comes in could be anything from 1 to 8 possibly. It is only in this case where you might want to increase the channel count above the output's channel count.<br>
If a channel pitch shift is set to a lower number than the sound's channel count that is coming in, it will not pitch shift the sound.<br>
[PLATFORMS]
Win32, Win64, Linux, Linux64, Macintosh, Xbox, Xbox360, PlayStation 2, GameCube, PlayStation Portable, PlayStation 3, Wii
[SEE_ALSO]
DSP::setParameter
DSP::getParameter
FMOD_DSP_TYPE
]
*/
public enum DSP_PITCHSHIFT
{
PITCH, /* Pitch value. 0.5 to 2.0. Default = 1.0. 0.5 = one octave down, 2.0 = one octave up. 1.0 does not change the pitch. */
FFTSIZE, /* FFT window size. 256, 512, 1024, 2048, 4096. Default = 1024. Increase this to reduce 'smearing'. This effect is a warbling sound similar to when an mp3 is encoded at very low bitrates. */
OVERLAP, /* Window overlap. 1 to 32. Default = 4. Increase this to reduce 'tremolo' effect. Increasing it by a factor of 2 doubles the CPU usage. */
MAXCHANNELS /* Maximum channels supported. 0 to 16. 0 = same as fmod's default output polyphony, 1 = mono, 2 = stereo etc. See remarks for more. Default = 0. It is suggested to leave at 0! */
}
/*
[ENUM]
[
[DESCRIPTION]
Parameter types for the FMOD_DSP_TYPE_CHORUS filter.
[REMARKS]
Chrous is an effect where the sound is more 'spacious' due to 1 to 3 versions of the sound being played along side the original signal but with the pitch of each copy modulating on a sine wave.<br>
This is a highly configurable chorus unit. It supports 3 taps, small and large delay times and also feedback.<br>
This unit also could be used to do a simple echo, or a flange effect.
[PLATFORMS]
Win32, Win64, Linux, Linux64, Macintosh, Xbox, Xbox360, PlayStation 2, GameCube, PlayStation Portable, PlayStation 3, Wii
[SEE_ALSO]
DSP::setParameter
DSP::getParameter
FMOD_DSP_TYPE
]
*/
public enum DSP_CHORUS
{
DRYMIX, /* Volume of original signal to pass to output. 0.0 to 1.0. Default = 0.5. */
WETMIX1, /* Volume of 1st chorus tap. 0.0 to 1.0. Default = 0.5. */
WETMIX2, /* Volume of 2nd chorus tap. This tap is 90 degrees out of phase of the first tap. 0.0 to 1.0. Default = 0.5. */
WETMIX3, /* Volume of 3rd chorus tap. This tap is 90 degrees out of phase of the second tap. 0.0 to 1.0. Default = 0.5. */
DELAY, /* Chorus delay in ms. 0.1 to 100.0. Default = 40.0 ms. */
RATE, /* Chorus modulation rate in hz. 0.0 to 20.0. Default = 0.8 hz. */
DEPTH, /* Chorus modulation depth. 0.0 to 1.0. Default = 0.03. */
FEEDBACK /* Chorus feedback. Controls how much of the wet signal gets fed back into the chorus buffer. 0.0 to 1.0. Default = 0.0. */
}
/*
[ENUM]
[
[DESCRIPTION]
Parameter types for the FMOD_DSP_TYPE_REVERB filter.
[REMARKS]
[PLATFORMS]
Win32, Win64, Linux, Macintosh, Xbox, Xbox360, PlayStation 2, GameCube, PlayStation Portable
[SEE_ALSO]
DSP::setParameter
DSP::getParameter
FMOD_DSP_TYPE
]
*/
public enum DSP_REVERB
{
ROOMSIZE, /* Roomsize. 0.0 to 1.0. Default = 0.5 */
DAMP, /* Damp. 0.0 to 1.0. Default = 0.5 */
WETMIX, /* Wet mix. 0.0 to 1.0. Default = 0.33 */
DRYMIX, /* Dry mix. 0.0 to 1.0. Default = 0.0 */
WIDTH, /* Width. 0.0 to 1.0. Default = 1.0 */
MODE /* Mode. 0 (normal), 1 (freeze). Default = 0 */
}
/*
[ENUM]
[
[DESCRIPTION]
Parameter types for the FMOD_DSP_TYPE_ITECHO filter.<br>
This is effectively a software based echo filter that emulates the DirectX DMO echo effect. Impulse tracker files can support this, and FMOD will produce the effect on ANY platform, not just those that support DirectX effects!<br>
[REMARKS]
Note. Every time the delay is changed, the plugin re-allocates the echo buffer. This means the echo will dissapear at that time while it refills its new buffer.<br>
Larger echo delays result in larger amounts of memory allocated.<br>
<br>
For stereo signals only! This will not work on mono or multichannel signals. This is fine for .IT format purposes, and also if you use System::addDSP with a standard stereo output.<br>
[PLATFORMS]
Win32, Win64, Linux, Macintosh, Xbox, Xbox360, PlayStation 2, GameCube, PlayStation Portable
[SEE_ALSO]
DSP::setParameter
DSP::getParameter
FMOD_DSP_TYPE
System::addDSP
]
*/
public enum DSP_ITECHO
{
WETDRYMIX, /* Ratio of wet (processed) signal to dry (unprocessed) signal. Must be in the range from 0.0 through 100.0 (all wet). The default value is 50. */
FEEDBACK, /* Percentage of output fed back into input, in the range from 0.0 through 100.0. The default value is 50. */
LEFTDELAY, /* Delay for left channel, in milliseconds, in the range from 1.0 through 2000.0. The default value is 500 ms. */
RIGHTDELAY, /* Delay for right channel, in milliseconds, in the range from 1.0 through 2000.0. The default value is 500 ms. */
PANDELAY /* Value that specifies whether to swap left and right delays with each successive echo. The default value is zero, meaning no swap. Possible values are defined as 0.0 (equivalent to FALSE) and 1.0 (equivalent to TRUE). */
}
/*
[ENUM]
[
[DESCRIPTION]
Parameter types for the FMOD_DSP_TYPE_COMPRESSOR unit.<br>
This is a simple linked multichannel software limiter that is uniform across the whole spectrum.<br>
[REMARKS]
The parameters are as follows:
Threshold: [-60dB to 0dB, default 0dB]
Attack Time: [10ms to 200ms, default 50ms]
Release Time: [20ms to 1000ms, default 50ms]
Gain Make Up: [0dB to +30dB, default 0dB]
<br>
The limiter is not guaranteed to catch every peak above the threshold level,
because it cannot apply gain reduction instantaneously - the time delay is
determined by the attack time. However setting the attack time too short will
distort the sound, so it is a compromise. High level peaks can be avoided by
using a short attack time - but not too short, and setting the threshold a few
decibels below the critical level.
<br>
[PLATFORMS]
Win32, Win64, Linux, Linux64, Macintosh, Xbox, Xbox360, PlayStation 2, GameCube, PlayStation Portable, PlayStation 3
[SEE_ALSO]
DSP::SetParameter
DSP::GetParameter
FMOD_DSP_TYPE
System::addDSP
]
*/
public enum DSP_COMPRESSOR
{
THRESHOLD, /* Threshold level (dB)in the range from -60 through 0. The default value is 50. */
ATTACK, /* Gain reduction attack time (milliseconds), in the range from 10 through 200. The default value is 50. */
RELEASE, /* Gain reduction release time (milliseconds), in the range from 20 through 1000. The default value is 50. */
GAINMAKEUP /* Make-up gain applied after limiting, in the range from 0.0 through 100.0. The default value is 50. */
}
/*
[ENUM]
[
[DESCRIPTION]
Parameter types for the FMOD_DSP_TYPE_SFXREVERB unit.<br>
[REMARKS]
This is a high quality I3DL2 based reverb which improves greatly on FMOD_DSP_REVERB.<br>
On top of the I3DL2 property set, "Dry Level" is also included to allow the dry mix to be changed.<br>
<br>
Currently FMOD_DSP_SFXREVERB_REFLECTIONSLEVEL, FMOD_DSP_SFXREVERB_REFLECTIONSDELAY and FMOD_DSP_SFXREVERB_REVERBDELAY are not enabled but will come in future versions.<br>
<br>
These properties can be set with presets in FMOD_REVERB_PRESETS.
[PLATFORMS]
Win32, Win64, Linux, Linux64, Macintosh, Xbox, Xbox360, PlayStation 2, GameCube, PlayStation Portable, PlayStation 3
[SEE_ALSO]
DSP::SetParameter
DSP::GetParameter
FMOD_DSP_TYPE
System::addDSP
FMOD_REVERB_PRESETS
]
*/
public enum DSP_SFXREVERB
{
DRYLEVEL, /* Dry Level : Mix level of dry signal in output in mB. Ranges from -10000.0 to 0.0. Default is 0.0. */
ROOM, /* Room : Room effect level at low frequencies in mB. Ranges from -10000.0 to 0.0. Default is 0.0. */
ROOMHF, /* Room HF : Room effect high-frequency level re. low frequency level in mB. Ranges from -10000.0 to 0.0. Default is 0.0. */
ROOMROLLOFFFACTOR, /* Room Rolloff : Like DS3D flRolloffFactor but for room effect. Ranges from 0.0 to 10.0. Default is 10.0 */
DECAYTIME, /* Decay Time : Reverberation decay time at low-frequencies in seconds. Ranges from 0.1 to 20.0. Default is 1.0. */
DECAYHFRATIO, /* Decay HF Ratio : High-frequency to low-frequency decay time ratio. Ranges from 0.1 to 2.0. Default is 0.5. */
REFLECTIONSLEVEL, /* Reflections : Early reflections level relative to room effect in mB. Ranges from -10000.0 to 1000.0. Default is -10000.0. */
REFLECTIONSDELAY, /* Reflect Delay : Delay time of first reflection in seconds. Ranges from 0.0 to 0.3. Default is 0.02. */
REVERBLEVEL, /* Reverb : Late reverberation level relative to room effect in mB. Ranges from -10000.0 to 2000.0. Default is 0.0. */
REVERBDELAY, /* Reverb Delay : Late reverberation delay time relative to first reflection in seconds. Ranges from 0.0 to 0.1. Default is 0.04. */
DIFFUSION, /* Diffusion : Reverberation diffusion (echo density) in percent. Ranges from 0.0 to 100.0. Default is 100.0. */
DENSITY, /* Density : Reverberation density (modal density) in percent. Ranges from 0.0 to 100.0. Default is 100.0. */
HFREFERENCE /* HF Reference : Reference high frequency in Hz. Ranges from 20.0 to 20000.0. Default is 5000.0. */
}
/*$ preserve start $*/
}
/*$ preserve end $*/
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Threading.Tasks;
using daq_api.Contracts;
using daq_api.Formatters;
using daq_api.Models;
using daq_api.Models.WebMap;
using Serilog;
namespace daq_api.Services
{
public class ArcOnlineHttpClient
{
private const string AgolUrl = "https://www.arcgis.com/sharing/rest/";
private const string OauthTokenUrl = "oauth2/token/";
private const string UserTokenUrl = "generateToken";
private const string AgolItemUrl = "content/items/";
private const int TenMinutesInSeconds = 600;
private const int TenMinuteBufferInMilliSeconds = 600000;
private readonly HttpClient _client;
private readonly IArcOnlineCredentials _credentials;
private DateTime _expiresIn = DateTime.UtcNow;
private string _currentToken;
public ArcOnlineHttpClient(IArcOnlineCredentials credentials)
{
var httpClientHandler = new HttpClientHandler();
if (httpClientHandler.SupportsAutomaticDecompression)
{
httpClientHandler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
}
_client = new HttpClient(httpClientHandler)
{
Timeout = TimeSpan.FromMinutes(5)
};
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
_credentials = credentials;
Formatters = new List<MediaTypeFormatter>
{
new PlainTextFormatter()
};
}
private IEnumerable<MediaTypeFormatter> Formatters { get; }
public async Task<ArcOnlineResponse<UploadResponse>> UploadDocument(string url, MultipartFormDataContent formContent)
{
Log.Information("{Action} attachments for {Url}, {@Payload}", "Uploading", url, formContent);
try
{
using (var response = await _client.PostAsync(url, formContent).ConfigureAwait(false))
{
if (response.StatusCode != HttpStatusCode.OK)
{
return new ArcOnlineResponse<UploadResponse>(response, new UploadResponse
{
Error = new Error
{
Details = new List<string>
{
"This file is most likely too large to be stored in ArcGIS Online."
}
}
});
}
try
{
var result = await response.Content.ReadAsAsync<UploadResponse>(Formatters).ConfigureAwait(false);
Log.Debug("{Action} response {@Response}", "upload", result);
return new ArcOnlineResponse<UploadResponse>(response, result);
}
catch (Exception ex)
{
var content = response.Content.ReadAsStringAsync().Result;
Log.Error(ex, "Reading {Action} response {Url} {@Response}", "upload attachment", url, content);
return new ArcOnlineResponse<UploadResponse>(response, new UploadResponse
{
Error = new Error
{
Details = new List<string>
{
ex.Message,
content
}
}
});
}
}
}
catch (Exception ex)
{
Log.Error(ex, "{Action} attachments for {Url}, {@Payload}", "Uploading", url, formContent);
return new ArcOnlineResponse<UploadResponse>(null, new UploadResponse
{
Error = new Error
{
Message = ex.Message
}
});
}
}
public async Task<ArcOnlineResponse<DeleteResponse>> DeleteDocument(string url, MultipartFormDataContent formContent)
{
Log.Information("{Action} attachments for {Url} {@Payload}", "deleting", url, formContent);
try
{
using (var response = await _client.PostAsync(url, formContent).ConfigureAwait(false))
{
try
{
var result = await response.Content.ReadAsAsync<DeleteResponse>(Formatters).ConfigureAwait(false);
result.DeleteAttachmentResult = result.DeleteAttachmentResults.Single();
result.DeleteAttachmentResults = null;
Log.Debug("{Action} response {@Response}", "delete", result);
return new ArcOnlineResponse<DeleteResponse>(response, result);
}
catch (Exception ex)
{
var content = response.Content.ReadAsStringAsync().Result;
Log.Error(ex, "Reading {Action} response {Url} {@Response}", "delete attachment", url, content);
return new ArcOnlineResponse<DeleteResponse>(response, new DeleteResponse
{
Error = new Error
{
Details = new List<string>
{
ex.Message,
content
}
}
});
}
}
}
catch (Exception ex)
{
Log.Error(ex, "{Action} attachments for {Url}, {@Payload}", "Deleting", url, formContent);
return new ArcOnlineResponse<DeleteResponse>(null, new DeleteResponse
{
Error = new Error
{
Message = ex.Message
}
});
}
}
public async Task<ArcOnlineResponse<AttachmentResponse>> GetAttachmentsFor(string url)
{
Log.Information("{Action} attachments for {Url}", "Fetching", url);
try
{
using (var response = await _client.GetAsync(url).ConfigureAwait(false))
{
try
{
var result = await response.Content.ReadAsAsync<AttachmentResponse>(Formatters).ConfigureAwait(false);
Log.Debug("{Action} response {@Response}", "Get Attachment", result);
return new ArcOnlineResponse<AttachmentResponse>(response, result);
}
catch (Exception ex)
{
var content = response.Content.ReadAsStringAsync().Result;
Log.Error(ex, "Reading {Action} response {Url} {@Response}", "attachment list", url, content);
return new ArcOnlineResponse<AttachmentResponse>(response, new AttachmentResponse
{
Error = new Error
{
Details = new List<string>
{
ex.Message,
content
}
}
});
}
}
}
catch (Exception ex)
{
Log.Error(ex, "{Action} attachments for {Url}", "Fetching", url);
return new ArcOnlineResponse<AttachmentResponse>(null, new AttachmentResponse
{
Error = new Error
{
Message = ex.Message
}
});
}
}
public async Task<WebMapJson> GetWebMapJsonFor(string webmap, string token)
{
if (string.IsNullOrEmpty(webmap))
{
Log.Error("Web Map Id cannot be empty when looking for a bookmark");
throw new ArgumentNullException(webmap, "Web Map Id cannot be empty when looking for a bookmark");
}
var queryParams = new[]
{
new KeyValuePair<string, string>("f", "json"),
new KeyValuePair<string, string>("token", token)
};
var formUrl = new FormUrlEncodedContent(queryParams);
var querystringContent = await formUrl.ReadAsStringAsync();
var url = AgolUrl + AgolItemUrl + webmap + "/data?" + querystringContent;
try
{
using (var response = await _client.GetAsync(url).ConfigureAwait(false))
{
try
{
var result = await response.Content.ReadAsAsync<WebMapJson>(Formatters).ConfigureAwait(false);
Log.Debug("{Action} response {@Response}", "Get webmap json", result);
return result;
}
catch (Exception ex)
{
var content = response.Content.ReadAsStringAsync().Result;
Log.Error(ex, "Reading {Action} response {Url} {@Response}", "web map json", url, content);
return new WebMapJson
{
Error = new Error
{
Details = new List<string>
{
ex.Message,
content
}
}
};
}
}
}
catch (Exception ex)
{
Log.Error(ex, "{Action} webmap json for {Url}", "Fetching", url);
return new WebMapJson
{
Error = new Error
{
Message = ex.Message
}
};
}
}
public async Task<WebMapUpdateResponse> UpdateWebMapJsonFor(string webmap, MultipartFormDataContent formContent)
{
var url = AgolUrl + "content/users/woswald9/items/" + webmap + "/update";
try
{
using (var response = await _client.PostAsync(url, formContent).ConfigureAwait(false))
{
try
{
var result = await response.Content.ReadAsAsync<WebMapUpdateResponse>(Formatters).ConfigureAwait(false);
Log.Debug("{Action} response {@Response}", "Get webmap json", result);
if (!result.Success)
{
Log.Warning("Bookmark not saved {@response}", result);
}
return result;
}
catch (Exception ex)
{
var content = response.Content.ReadAsStringAsync().Result;
Log.Error(ex, "Reading {Action} response {Url} {@Response}", "web map json", url, content);
return new WebMapUpdateResponse
{
Success = true
};
}
}
}
catch (Exception ex)
{
Log.Error(ex, "{Action} webmap json for {Url} {@Payload}", "Updating", url, formContent);
return new WebMapUpdateResponse
{
Success = false
};
}
}
public async Task<string> GetToken(bool oauth = false)
{
if (oauth)
{
return await GetOauthToken();
}
return await GetNamedUserToken();
}
public async Task<string> GetNamedUserToken()
{
Log.Verbose("GetToken");
if (!string.IsNullOrEmpty(_currentToken))
{
var utcNow = DateTime.UtcNow;
Log.Verbose("The time is {Now} and the token expires at {Expires}", utcNow, _expiresIn);
if (utcNow < _expiresIn)
{
Log.Debug("The current token is still valid.");
return _currentToken;
}
Log.Verbose("Requesting a new token");
}
Log.Debug("Requesting the first token");
using (var formContent = new MultipartFormDataContent())
{
try
{
formContent.Add(new StringContent(_credentials.Username), "username");
formContent.Add(new StringContent(_credentials.Password), "password");
formContent.Add(new StringContent("referer"), "client");
#if DEBUG
formContent.Add(new StringContent("http://localhost"), "referer");
#elif STAGING
formContent.Add(new StringContent("https://test.mapserv.utah.gov"), "referer");
#else
formContent.Add(new StringContent("https://complianceapp.utah.gov"), "referer");
#endif
formContent.Add(new StringContent("14400"), "expiration");
formContent.Add(new StringContent("json"), "f");
Log.Verbose("token request information {@Content}", _credentials);
}
catch (ArgumentNullException ex)
{
Log.Error(ex, "There was an issue creating the form content for {@User}", _credentials);
return null;
}
try
{
var response = await _client.PostAsync(AgolUrl + UserTokenUrl, formContent).ConfigureAwait(false);
var tokenResponse = await response.Content.ReadAsAsync<NamedUserTokenResponse>(Formatters).ConfigureAwait(false);
Log.Debug("Token service response {@Response}", tokenResponse);
var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
_expiresIn = epoch.AddMilliseconds(tokenResponse.Expires - TenMinuteBufferInMilliSeconds);
return _currentToken = tokenResponse.Token;
}
catch (Exception ex)
{
Log.Error(ex, "Getting a token from {Url} {@Payload}", UserTokenUrl, formContent);
return null;
}
}
}
public async Task<string> GetOauthToken()
{
Log.Verbose("GetToken");
if (!string.IsNullOrEmpty(_currentToken))
{
var utcNow = DateTime.UtcNow;
Log.Verbose("The time is {Now} and the token expires at {Expires}", utcNow, _expiresIn);
if (utcNow < _expiresIn)
{
Log.Debug("The current token is still valid.");
return _currentToken;
}
Log.Verbose("Requesting a new token");
}
Log.Debug("Requesting the first token");
using (var formContent = new MultipartFormDataContent())
{
try
{
formContent.Add(new StringContent(_credentials.Username), "client_id");
formContent.Add(new StringContent(_credentials.Password), "client_secret");
formContent.Add(new StringContent("client_credentials"), "grant_type");
formContent.Add(new StringContent("240"), "expiration");
formContent.Add(new StringContent("json"), "f");
}
catch (ArgumentNullException ex)
{
Log.Error(ex, "There was an issue creating the form content for {@User}", _credentials);
return null;
}
try
{
var response = await _client.PostAsync(AgolUrl + OauthTokenUrl, formContent).ConfigureAwait(false);
var tokenResponse = await response.Content.ReadAsAsync<OauthTokenResponse>(Formatters).ConfigureAwait(false);
Log.Debug("Token service response {@Response}", tokenResponse);
var expiresInSeconds = tokenResponse.Expires_In;
_expiresIn = DateTime.UtcNow + TimeSpan.FromSeconds(expiresInSeconds - TenMinutesInSeconds);
return _currentToken = tokenResponse.Access_Token;
}
catch (Exception ex)
{
Log.Error(ex, "Getting a token from {Url} {@Payload}", UserTokenUrl, formContent);
return null;
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
namespace Morph.Collections
{
public abstract class CollectionBase : IList, ICollection, IEnumerable
{
// private instance properties
private ArrayList list;
// public instance properties
public int Count { get { return InnerList.Count; } }
// Public Instance Methods
public IEnumerator GetEnumerator() { return InnerList.GetEnumerator(); }
public void Clear()
{
OnClear();
InnerList.Clear();
OnClearComplete();
}
public void RemoveAt(int index)
{
object objectToRemove;
objectToRemove = InnerList[index];
OnValidate(objectToRemove);
OnRemove(index, objectToRemove);
InnerList.RemoveAt(index);
OnRemoveComplete(index, objectToRemove);
}
// Protected Instance Constructors
protected CollectionBase()
{
}
protected CollectionBase(int capacity)
{
list = new ArrayList(capacity);
}
public int Capacity
{
get
{
if (list == null)
list = new ArrayList();
return list.Capacity;
}
set
{
if (list == null)
list = new ArrayList();
list.Capacity = value;
}
}
// Protected Instance Properties
protected ArrayList InnerList
{
get
{
if (list == null)
list = new ArrayList();
return list;
}
}
protected IList List { get { return this; } }
// Protected Instance Methods
protected virtual void OnClear() { }
protected virtual void OnClearComplete() { }
protected virtual void OnInsert(int index, object value) { }
protected virtual void OnInsertComplete(int index, object value) { }
protected virtual void OnRemove(int index, object value) { }
protected virtual void OnRemoveComplete(int index, object value) { }
protected virtual void OnSet(int index, object oldValue, object newValue) { }
protected virtual void OnSetComplete(int index, object oldValue, object newValue) { }
protected virtual void OnValidate(object value)
{
if (null == value)
{
throw new System.ArgumentNullException("CollectionBase.OnValidate: Invalid parameter value passed to method: null");
}
}
// ICollection methods
void ICollection.CopyTo(System.Array array, int index)
{
InnerList.CopyTo(array, index);
}
object ICollection.SyncRoot
{
get { return InnerList.SyncRoot; }
}
//bool ICollection.IsSynchronized
//{
// get { return InnerList.IsSynchronized; }
//}
// IList methods
int IList.Add(object value)
{
int newPosition;
OnValidate(value);
newPosition = InnerList.Count;
OnInsert(newPosition, value);
InnerList.Add(value);
try
{
OnInsertComplete(newPosition, value);
}
catch
{
InnerList.RemoveAt(newPosition);
throw;
}
return newPosition;
}
bool IList.Contains(object value)
{
return InnerList.Contains(value);
}
int IList.IndexOf(object value)
{
return InnerList.IndexOf(value);
}
void IList.Insert(int index, object value)
{
OnValidate(value);
OnInsert(index, value);
InnerList.Insert(index, value);
try
{
OnInsertComplete(index, value);
}
catch
{
InnerList.RemoveAt(index);
throw;
}
}
void IList.Remove(object value)
{
int removeIndex;
OnValidate(value);
removeIndex = InnerList.IndexOf(value);
if (removeIndex == -1)
throw new System.ArgumentException("The element cannot be found.", "value");
OnRemove(removeIndex, value);
InnerList.Remove(value);
OnRemoveComplete(removeIndex, value);
}
// IList properties
bool IList.IsFixedSize
{
get { return InnerList.IsFixedSize; }
}
bool IList.IsReadOnly
{
get { return InnerList.IsReadOnly; }
}
object IList.this[int index]
{
get { return InnerList[index]; }
set
{
if (index < 0 || index >= InnerList.Count)
throw new System.ArgumentOutOfRangeException("index");
object oldValue;
// make sure we have been given a valid value
OnValidate(value);
// save a reference to the object that is in the list now
oldValue = InnerList[index];
OnSet(index, oldValue, value);
InnerList[index] = value;
try
{
OnSetComplete(index, oldValue, value);
}
catch
{
InnerList[index] = oldValue;
throw;
}
}
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using log4net;
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using Nini.Config;
using OpenSim.Framework;
using OpenSim.Framework.Communications;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Services.Interfaces;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;
using OpenSim.Server.Base;
using OpenMetaverse;
namespace OpenSim.Services.Connectors
{
public class GridServicesConnector : IGridService
{
private static readonly ILog m_log =
LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
private string m_ServerURI = String.Empty;
public GridServicesConnector()
{
}
public GridServicesConnector(string serverURI)
{
m_ServerURI = serverURI.TrimEnd('/');
}
public GridServicesConnector(IConfigSource source)
{
Initialise(source);
}
public virtual void Initialise(IConfigSource source)
{
IConfig gridConfig = source.Configs["GridService"];
if (gridConfig == null)
{
m_log.Error("[GRID CONNECTOR]: GridService missing from OpenSim.ini");
throw new Exception("Grid connector init error");
}
string serviceURI = gridConfig.GetString("GridServerURI",
String.Empty);
if (serviceURI == String.Empty)
{
m_log.Error("[GRID CONNECTOR]: No Server URI named in section GridService");
throw new Exception("Grid connector init error");
}
m_ServerURI = serviceURI;
}
#region IGridService
public virtual string RegisterRegion(UUID scopeID, GridRegion regionInfo)
{
Dictionary<string, object> rinfo = regionInfo.ToKeyValuePairs();
Dictionary<string, object> sendData = new Dictionary<string,object>();
foreach (KeyValuePair<string, object> kvp in rinfo)
sendData[kvp.Key] = (string)kvp.Value;
sendData["SCOPEID"] = scopeID.ToString();
sendData["VERSIONMIN"] = ProtocolVersions.ClientProtocolVersionMin.ToString();
sendData["VERSIONMAX"] = ProtocolVersions.ClientProtocolVersionMax.ToString();
sendData["METHOD"] = "register";
string reqString = ServerUtils.BuildQueryString(sendData);
// m_log.DebugFormat("[GRID CONNECTOR]: queryString = {0}", reqString);
try
{
string reply = SynchronousRestFormsRequester.MakeRequest("POST",
m_ServerURI + "/grid",
reqString);
if (reply != string.Empty)
{
Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply);
if (replyData.ContainsKey("Result")&& (replyData["Result"].ToString().ToLower() == "success"))
{
return String.Empty;
}
else if (replyData.ContainsKey("Result")&& (replyData["Result"].ToString().ToLower() == "failure"))
{
m_log.DebugFormat("[GRID CONNECTOR]: Registration failed: {0}", replyData["Message"].ToString());
return replyData["Message"].ToString();
}
else if (!replyData.ContainsKey("Result"))
{
m_log.DebugFormat("[GRID CONNECTOR]: reply data does not contain result field");
}
else
{
m_log.DebugFormat("[GRID CONNECTOR]: unexpected result {0}", replyData["Result"].ToString());
return "Unexpected result "+replyData["Result"].ToString();
}
}
else
m_log.DebugFormat("[GRID CONNECTOR]: RegisterRegion received null reply");
}
catch (Exception e)
{
m_log.DebugFormat("[GRID CONNECTOR]: Exception when contacting grid server: {0}", e.Message);
}
return "Error communicating with grid service";
}
public virtual bool DeregisterRegion(UUID regionID)
{
Dictionary<string, object> sendData = new Dictionary<string, object>();
sendData["REGIONID"] = regionID.ToString();
sendData["METHOD"] = "deregister";
try
{
string reply = SynchronousRestFormsRequester.MakeRequest("POST",
m_ServerURI + "/grid",
ServerUtils.BuildQueryString(sendData));
if (reply != string.Empty)
{
Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply);
if ((replyData["Result"] != null) && (replyData["Result"].ToString().ToLower() == "success"))
return true;
}
else
m_log.DebugFormat("[GRID CONNECTOR]: DeregisterRegion received null reply");
}
catch (Exception e)
{
m_log.DebugFormat("[GRID CONNECTOR]: Exception when contacting grid server: {0}", e.Message);
}
return false;
}
public virtual List<GridRegion> GetNeighbours(UUID scopeID, UUID regionID)
{
Dictionary<string, object> sendData = new Dictionary<string, object>();
sendData["SCOPEID"] = scopeID.ToString();
sendData["REGIONID"] = regionID.ToString();
sendData["METHOD"] = "get_neighbours";
List<GridRegion> rinfos = new List<GridRegion>();
string reqString = ServerUtils.BuildQueryString(sendData);
string reply = string.Empty;
try
{
reply = SynchronousRestFormsRequester.MakeRequest("POST",
m_ServerURI + "/grid",
reqString);
}
catch (Exception e)
{
m_log.DebugFormat("[GRID CONNECTOR]: Exception when contacting grid server: {0}", e.Message);
return rinfos;
}
Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply);
if (replyData != null)
{
Dictionary<string, object>.ValueCollection rinfosList = replyData.Values;
//m_log.DebugFormat("[GRID CONNECTOR]: get neighbours returned {0} elements", rinfosList.Count);
foreach (object r in rinfosList)
{
if (r is Dictionary<string, object>)
{
GridRegion rinfo = new GridRegion((Dictionary<string, object>)r);
rinfos.Add(rinfo);
}
}
}
else
m_log.DebugFormat("[GRID CONNECTOR]: GetNeighbours {0}, {1} received null response",
scopeID, regionID);
return rinfos;
}
public virtual GridRegion GetRegionByUUID(UUID scopeID, UUID regionID)
{
Dictionary<string, object> sendData = new Dictionary<string, object>();
sendData["SCOPEID"] = scopeID.ToString();
sendData["REGIONID"] = regionID.ToString();
sendData["METHOD"] = "get_region_by_uuid";
string reply = string.Empty;
try
{
reply = SynchronousRestFormsRequester.MakeRequest("POST",
m_ServerURI + "/grid",
ServerUtils.BuildQueryString(sendData));
}
catch (Exception e)
{
m_log.DebugFormat("[GRID CONNECTOR]: Exception when contacting grid server: {0}", e.Message);
return null;
}
GridRegion rinfo = null;
if (reply != string.Empty)
{
Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply);
if ((replyData != null) && (replyData["result"] != null))
{
if (replyData["result"] is Dictionary<string, object>)
rinfo = new GridRegion((Dictionary<string, object>)replyData["result"]);
//else
// m_log.DebugFormat("[GRID CONNECTOR]: GetRegionByUUID {0}, {1} received null response",
// scopeID, regionID);
}
else
m_log.DebugFormat("[GRID CONNECTOR]: GetRegionByUUID {0}, {1} received null response",
scopeID, regionID);
}
else
m_log.DebugFormat("[GRID CONNECTOR]: GetRegionByUUID received null reply");
return rinfo;
}
public virtual GridRegion GetRegionByPosition(UUID scopeID, int x, int y)
{
Dictionary<string, object> sendData = new Dictionary<string, object>();
sendData["SCOPEID"] = scopeID.ToString();
sendData["X"] = x.ToString();
sendData["Y"] = y.ToString();
sendData["METHOD"] = "get_region_by_position";
string reply = string.Empty;
try
{
reply = SynchronousRestFormsRequester.MakeRequest("POST",
m_ServerURI + "/grid",
ServerUtils.BuildQueryString(sendData));
}
catch (Exception e)
{
m_log.DebugFormat("[GRID CONNECTOR]: Exception when contacting grid server: {0}", e.Message);
return null;
}
GridRegion rinfo = null;
if (reply != string.Empty)
{
Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply);
if ((replyData != null) && (replyData["result"] != null))
{
if (replyData["result"] is Dictionary<string, object>)
rinfo = new GridRegion((Dictionary<string, object>)replyData["result"]);
//else
// m_log.DebugFormat("[GRID CONNECTOR]: GetRegionByPosition {0}, {1}-{2} received no region",
// scopeID, x, y);
}
else
m_log.DebugFormat("[GRID CONNECTOR]: GetRegionByPosition {0}, {1}-{2} received null response",
scopeID, x, y);
}
else
m_log.DebugFormat("[GRID CONNECTOR]: GetRegionByPosition received null reply");
return rinfo;
}
public virtual GridRegion GetRegionByName(UUID scopeID, string regionName)
{
Dictionary<string, object> sendData = new Dictionary<string, object>();
sendData["SCOPEID"] = scopeID.ToString();
sendData["NAME"] = regionName;
sendData["METHOD"] = "get_region_by_name";
string reply = string.Empty;
try
{
reply = SynchronousRestFormsRequester.MakeRequest("POST",
m_ServerURI + "/grid",
ServerUtils.BuildQueryString(sendData));
}
catch (Exception e)
{
m_log.DebugFormat("[GRID CONNECTOR]: Exception when contacting grid server: {0}", e.Message);
return null;
}
GridRegion rinfo = null;
if (reply != string.Empty)
{
Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply);
if ((replyData != null) && (replyData["result"] != null))
{
if (replyData["result"] is Dictionary<string, object>)
rinfo = new GridRegion((Dictionary<string, object>)replyData["result"]);
}
else
m_log.DebugFormat("[GRID CONNECTOR]: GetRegionByPosition {0}, {1} received null response",
scopeID, regionName);
}
else
m_log.DebugFormat("[GRID CONNECTOR]: GetRegionByName received null reply");
return rinfo;
}
public virtual List<GridRegion> GetRegionsByName(UUID scopeID, string name, int maxNumber)
{
Dictionary<string, object> sendData = new Dictionary<string, object>();
sendData["SCOPEID"] = scopeID.ToString();
sendData["NAME"] = name;
sendData["MAX"] = maxNumber.ToString();
sendData["METHOD"] = "get_regions_by_name";
List<GridRegion> rinfos = new List<GridRegion>();
string reply = string.Empty;
try
{
reply = SynchronousRestFormsRequester.MakeRequest("POST",
m_ServerURI + "/grid",
ServerUtils.BuildQueryString(sendData));
}
catch (Exception e)
{
m_log.DebugFormat("[GRID CONNECTOR]: Exception when contacting grid server: {0}", e.Message);
return rinfos;
}
if (reply != string.Empty)
{
Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply);
if (replyData != null)
{
Dictionary<string, object>.ValueCollection rinfosList = replyData.Values;
foreach (object r in rinfosList)
{
if (r is Dictionary<string, object>)
{
GridRegion rinfo = new GridRegion((Dictionary<string, object>)r);
rinfos.Add(rinfo);
}
}
}
else
m_log.DebugFormat("[GRID CONNECTOR]: GetRegionsByName {0}, {1}, {2} received null response",
scopeID, name, maxNumber);
}
else
m_log.DebugFormat("[GRID CONNECTOR]: GetRegionsByName received null reply");
return rinfos;
}
public virtual List<GridRegion> GetRegionRange(UUID scopeID, int xmin, int xmax, int ymin, int ymax)
{
Dictionary<string, object> sendData = new Dictionary<string, object>();
sendData["SCOPEID"] = scopeID.ToString();
sendData["XMIN"] = xmin.ToString();
sendData["XMAX"] = xmax.ToString();
sendData["YMIN"] = ymin.ToString();
sendData["YMAX"] = ymax.ToString();
sendData["METHOD"] = "get_region_range";
List<GridRegion> rinfos = new List<GridRegion>();
string reply = string.Empty;
try
{
reply = SynchronousRestFormsRequester.MakeRequest("POST",
m_ServerURI + "/grid",
ServerUtils.BuildQueryString(sendData));
//m_log.DebugFormat("[GRID CONNECTOR]: reply was {0}", reply);
}
catch (Exception e)
{
m_log.DebugFormat("[GRID CONNECTOR]: Exception when contacting grid server: {0}", e.Message);
return rinfos;
}
if (reply != string.Empty)
{
Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply);
if (replyData != null)
{
Dictionary<string, object>.ValueCollection rinfosList = replyData.Values;
foreach (object r in rinfosList)
{
if (r is Dictionary<string, object>)
{
GridRegion rinfo = new GridRegion((Dictionary<string, object>)r);
rinfos.Add(rinfo);
}
}
}
else
m_log.DebugFormat("[GRID CONNECTOR]: GetRegionRange {0}, {1}-{2} {3}-{4} received null response",
scopeID, xmin, xmax, ymin, ymax);
}
else
m_log.DebugFormat("[GRID CONNECTOR]: GetRegionRange received null reply");
return rinfos;
}
public List<GridRegion> GetDefaultRegions(UUID scopeID)
{
Dictionary<string, object> sendData = new Dictionary<string, object>();
sendData["SCOPEID"] = scopeID.ToString();
sendData["METHOD"] = "get_default_regions";
List<GridRegion> rinfos = new List<GridRegion>();
string reply = string.Empty;
try
{
reply = SynchronousRestFormsRequester.MakeRequest("POST",
m_ServerURI + "/grid",
ServerUtils.BuildQueryString(sendData));
//m_log.DebugFormat("[GRID CONNECTOR]: reply was {0}", reply);
}
catch (Exception e)
{
m_log.DebugFormat("[GRID CONNECTOR]: Exception when contacting grid server: {0}", e.Message);
return rinfos;
}
if (reply != string.Empty)
{
Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply);
if (replyData != null)
{
Dictionary<string, object>.ValueCollection rinfosList = replyData.Values;
foreach (object r in rinfosList)
{
if (r is Dictionary<string, object>)
{
GridRegion rinfo = new GridRegion((Dictionary<string, object>)r);
rinfos.Add(rinfo);
}
}
}
else
m_log.DebugFormat("[GRID CONNECTOR]: GetDefaultRegions {0} received null response",
scopeID);
}
else
m_log.DebugFormat("[GRID CONNECTOR]: GetDefaultRegions received null reply");
return rinfos;
}
public List<GridRegion> GetFallbackRegions(UUID scopeID, int x, int y)
{
Dictionary<string, object> sendData = new Dictionary<string, object>();
sendData["SCOPEID"] = scopeID.ToString();
sendData["X"] = x.ToString();
sendData["Y"] = y.ToString();
sendData["METHOD"] = "get_fallback_regions";
List<GridRegion> rinfos = new List<GridRegion>();
string reply = string.Empty;
try
{
reply = SynchronousRestFormsRequester.MakeRequest("POST",
m_ServerURI + "/grid",
ServerUtils.BuildQueryString(sendData));
//m_log.DebugFormat("[GRID CONNECTOR]: reply was {0}", reply);
}
catch (Exception e)
{
m_log.DebugFormat("[GRID CONNECTOR]: Exception when contacting grid server: {0}", e.Message);
return rinfos;
}
if (reply != string.Empty)
{
Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply);
if (replyData != null)
{
Dictionary<string, object>.ValueCollection rinfosList = replyData.Values;
foreach (object r in rinfosList)
{
if (r is Dictionary<string, object>)
{
GridRegion rinfo = new GridRegion((Dictionary<string, object>)r);
rinfos.Add(rinfo);
}
}
}
else
m_log.DebugFormat("[GRID CONNECTOR]: GetFallbackRegions {0}, {1}-{2} received null response",
scopeID, x, y);
}
else
m_log.DebugFormat("[GRID CONNECTOR]: GetFallbackRegions received null reply");
return rinfos;
}
public List<GridRegion> GetHyperlinks(UUID scopeID)
{
Dictionary<string, object> sendData = new Dictionary<string, object>();
sendData["SCOPEID"] = scopeID.ToString();
sendData["METHOD"] = "get_hyperlinks";
List<GridRegion> rinfos = new List<GridRegion>();
string reply = string.Empty;
try
{
reply = SynchronousRestFormsRequester.MakeRequest("POST",
m_ServerURI + "/grid",
ServerUtils.BuildQueryString(sendData));
//m_log.DebugFormat("[GRID CONNECTOR]: reply was {0}", reply);
}
catch (Exception e)
{
m_log.DebugFormat("[GRID CONNECTOR]: Exception when contacting grid server: {0}", e.Message);
return rinfos;
}
if (reply != string.Empty)
{
Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply);
if (replyData != null)
{
Dictionary<string, object>.ValueCollection rinfosList = replyData.Values;
foreach (object r in rinfosList)
{
if (r is Dictionary<string, object>)
{
GridRegion rinfo = new GridRegion((Dictionary<string, object>)r);
rinfos.Add(rinfo);
}
}
}
else
m_log.DebugFormat("[GRID CONNECTOR]: GetHyperlinks {0} received null response",
scopeID);
}
else
m_log.DebugFormat("[GRID CONNECTOR]: GetHyperlinks received null reply");
return rinfos;
}
public virtual int GetRegionFlags(UUID scopeID, UUID regionID)
{
Dictionary<string, object> sendData = new Dictionary<string, object>();
sendData["SCOPEID"] = scopeID.ToString();
sendData["REGIONID"] = regionID.ToString();
sendData["METHOD"] = "get_region_flags";
string reply = string.Empty;
try
{
reply = SynchronousRestFormsRequester.MakeRequest("POST",
m_ServerURI + "/grid",
ServerUtils.BuildQueryString(sendData));
}
catch (Exception e)
{
m_log.DebugFormat("[GRID CONNECTOR]: Exception when contacting grid server: {0}", e.Message);
return -1;
}
int flags = -1;
if (reply != string.Empty)
{
Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply);
if ((replyData != null) && replyData.ContainsKey("result") && (replyData["result"] != null))
{
Int32.TryParse((string)replyData["result"], out flags);
//else
// m_log.DebugFormat("[GRID CONNECTOR]: GetRegionFlags {0}, {1} received wrong type {2}",
// scopeID, regionID, replyData["result"].GetType());
}
else
m_log.DebugFormat("[GRID CONNECTOR]: GetRegionFlags {0}, {1} received null response",
scopeID, regionID);
}
else
m_log.DebugFormat("[GRID CONNECTOR]: GetRegionFlags received null reply");
return flags;
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace System.Net.Tests
{
public class HttpRequestStreamTests : IDisposable
{
private HttpListenerFactory _factory;
private HttpListener _listener;
private GetContextHelper _helper;
public HttpRequestStreamTests()
{
_factory = new HttpListenerFactory();
_listener = _factory.GetListener();
_helper = new GetContextHelper(_listener, _factory.ListeningUrl);
}
public void Dispose()
{
_factory.Dispose();
_helper.Dispose();
}
[ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotOneCoreUAP))]
[InlineData(true, "")]
[InlineData(false, "")]
[InlineData(true, "Non-Empty")]
[InlineData(false, "Non-Empty")]
public async Task Read_FullLengthAsynchronous_Success(bool transferEncodingChunked, string text)
{
byte[] expected = Encoding.UTF8.GetBytes(text);
Task<HttpListenerContext> contextTask = _listener.GetContextAsync();
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.TransferEncodingChunked = transferEncodingChunked;
Task<HttpResponseMessage> clientTask = client.PostAsync(_factory.ListeningUrl, new StringContent(text));
HttpListenerContext context = await contextTask;
if (transferEncodingChunked)
{
Assert.Equal(-1, context.Request.ContentLength64);
Assert.Equal("chunked", context.Request.Headers["Transfer-Encoding"]);
}
else
{
Assert.Equal(expected.Length, context.Request.ContentLength64);
Assert.Null(context.Request.Headers["Transfer-Encoding"]);
}
byte[] buffer = new byte[expected.Length];
int bytesRead = await context.Request.InputStream.ReadAsync(buffer, 0, buffer.Length);
Assert.Equal(expected.Length, bytesRead);
Assert.Equal(expected, buffer);
// Subsequent reads don't do anything.
Assert.Equal(0, await context.Request.InputStream.ReadAsync(buffer, 0, buffer.Length));
Assert.Equal(expected, buffer);
context.Response.Close();
using (HttpResponseMessage response = await clientTask)
{
Assert.Equal(200, (int)response.StatusCode);
}
}
}
[ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotOneCoreUAP))]
// [InlineData(true, "")] Issue #20419 - HttpClient problem
[InlineData(false, "")]
[InlineData(true, "Non-Empty")]
[InlineData(false, "Non-Empty")]
public async Task Read_FullLengthAsynchronous_PadBuffer_Success(bool transferEncodingChunked, string text)
{
byte[] expected = Encoding.UTF8.GetBytes(text);
Task<HttpListenerContext> contextTask = _listener.GetContextAsync();
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.TransferEncodingChunked = transferEncodingChunked;
Task<HttpResponseMessage> clientTask = client.PostAsync(_factory.ListeningUrl, new StringContent(text));
HttpListenerContext context = await contextTask;
if (transferEncodingChunked)
{
Assert.Equal(-1, context.Request.ContentLength64);
Assert.Equal("chunked", context.Request.Headers["Transfer-Encoding"]);
}
else
{
Assert.Equal(expected.Length, context.Request.ContentLength64);
Assert.Null(context.Request.Headers["Transfer-Encoding"]);
}
const int pad = 128;
// Add padding at beginning and end to test for correct offset/size handling
byte[] buffer = new byte[pad + expected.Length + pad];
int bytesRead = await context.Request.InputStream.ReadAsync(buffer, pad, expected.Length);
Assert.Equal(expected.Length, bytesRead);
Assert.Equal(expected, buffer.Skip(pad).Take(bytesRead));
// Subsequent reads don't do anything.
Assert.Equal(0, await context.Request.InputStream.ReadAsync(buffer, pad, 1));
context.Response.Close();
using (HttpResponseMessage response = await clientTask)
{
Assert.Equal(200, (int)response.StatusCode);
}
}
}
[ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotOneCoreUAP))]
[InlineData(true, "")]
[InlineData(false, "")]
[InlineData(true, "Non-Empty")]
[InlineData(false, "Non-Empty")]
public async Task Read_FullLengthSynchronous_Success(bool transferEncodingChunked, string text)
{
byte[] expected = Encoding.UTF8.GetBytes(text);
Task<HttpListenerContext> contextTask = _listener.GetContextAsync();
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.TransferEncodingChunked = transferEncodingChunked;
Task<HttpResponseMessage> clientTask = client.PostAsync(_factory.ListeningUrl, new StringContent(text));
HttpListenerContext context = await contextTask;
if (transferEncodingChunked)
{
Assert.Equal(-1, context.Request.ContentLength64);
Assert.Equal("chunked", context.Request.Headers["Transfer-Encoding"]);
}
else
{
Assert.Equal(expected.Length, context.Request.ContentLength64);
Assert.Null(context.Request.Headers["Transfer-Encoding"]);
}
byte[] buffer = new byte[expected.Length];
int bytesRead = context.Request.InputStream.Read(buffer, 0, buffer.Length);
Assert.Equal(expected.Length, bytesRead);
Assert.Equal(expected, buffer);
// Subsequent reads don't do anything.
Assert.Equal(0, context.Request.InputStream.Read(buffer, 0, buffer.Length));
Assert.Equal(expected, buffer);
context.Response.Close();
using (HttpResponseMessage response = await clientTask)
{
Assert.Equal(200, (int)response.StatusCode);
}
}
}
[ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotOneCoreUAP))]
[InlineData(true)]
[InlineData(false)]
public async Task Read_LargeLengthAsynchronous_Success(bool transferEncodingChunked)
{
var rand = new Random(42);
byte[] expected = Enumerable
.Range(0, 128*1024 + 1) // More than 128kb
.Select(_ => (byte)('a' + rand.Next(0, 26)))
.ToArray();
Task<HttpListenerContext> contextTask = _listener.GetContextAsync();
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.TransferEncodingChunked = transferEncodingChunked;
Task<HttpResponseMessage> clientTask = client.PostAsync(_factory.ListeningUrl, new ByteArrayContent(expected));
HttpListenerContext context = await contextTask;
// If the size is greater than 128K, then we limit the size, and have to do multiple reads on
// Windows, which uses http.sys internally.
byte[] buffer = new byte[expected.Length];
int totalRead = 0;
while (totalRead < expected.Length)
{
int bytesRead = await context.Request.InputStream.ReadAsync(buffer, totalRead, expected.Length - totalRead);
Assert.InRange(bytesRead, 1, expected.Length - totalRead);
totalRead += bytesRead;
}
// Subsequent reads don't do anything.
Assert.Equal(0, await context.Request.InputStream.ReadAsync(buffer, 0, buffer.Length));
Assert.Equal(expected, buffer);
context.Response.Close();
}
}
[ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotOneCoreUAP))]
[InlineData(true)]
[InlineData(false)]
public async Task Read_LargeLengthSynchronous_Success(bool transferEncodingChunked)
{
var rand = new Random(42);
byte[] expected = Enumerable
.Range(0, 128 * 1024 + 1) // More than 128kb
.Select(_ => (byte)('a' + rand.Next(0, 26)))
.ToArray();
Task<HttpListenerContext> contextTask = _listener.GetContextAsync();
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.TransferEncodingChunked = transferEncodingChunked;
Task<HttpResponseMessage> clientTask = client.PostAsync(_factory.ListeningUrl, new ByteArrayContent(expected));
HttpListenerContext context = await contextTask;
// If the size is greater than 128K, then we limit the size, and have to do multiple reads on
// Windows, which uses http.sys internally.
byte[] buffer = new byte[expected.Length];
int totalRead = 0;
while (totalRead < expected.Length)
{
int bytesRead = context.Request.InputStream.Read(buffer, totalRead, expected.Length - totalRead);
Assert.InRange(bytesRead, 1, expected.Length - totalRead);
totalRead += bytesRead;
}
// Subsequent reads don't do anything.
Assert.Equal(0, context.Request.InputStream.Read(buffer, 0, buffer.Length));
Assert.Equal(expected, buffer);
context.Response.Close();
}
}
[ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotOneCoreUAP))]
[InlineData(true)]
[InlineData(false)]
public async Task Read_TooMuchAsynchronous_Success(bool transferEncodingChunked)
{
const string Text = "Some-String";
byte[] expected = Encoding.UTF8.GetBytes(Text);
Task<HttpListenerContext> contextTask = _listener.GetContextAsync();
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.TransferEncodingChunked = transferEncodingChunked;
Task<HttpResponseMessage> clientTask = client.PostAsync(_factory.ListeningUrl, new StringContent(Text));
HttpListenerContext context = await contextTask;
byte[] buffer = new byte[expected.Length + 5];
int bytesRead = await context.Request.InputStream.ReadAsync(buffer, 0, buffer.Length);
Assert.Equal(expected.Length, bytesRead);
Assert.Equal(expected.Concat(new byte[5]), buffer);
context.Response.Close();
}
}
[ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotOneCoreUAP))]
[InlineData(true)]
[InlineData(false)]
public async Task Read_TooMuchSynchronous_Success(bool transferEncodingChunked)
{
const string Text = "Some-String";
byte[] expected = Encoding.UTF8.GetBytes(Text);
Task<HttpListenerContext> contextTask = _listener.GetContextAsync();
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.TransferEncodingChunked = transferEncodingChunked;
Task<HttpResponseMessage> clientTask = client.PostAsync(_factory.ListeningUrl, new StringContent(Text));
HttpListenerContext context = await contextTask;
byte[] buffer = new byte[expected.Length + 5];
int bytesRead = context.Request.InputStream.Read(buffer, 0, buffer.Length);
Assert.Equal(expected.Length, bytesRead);
Assert.Equal(expected.Concat(new byte[5]), buffer);
context.Response.Close();
}
}
[ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotOneCoreUAP))]
[InlineData(true)]
[InlineData(false)]
public async Task Read_NotEnoughThenCloseAsynchronous_Success(bool transferEncodingChunked)
{
const string Text = "Some-String";
byte[] expected = Encoding.UTF8.GetBytes(Text);
Task<HttpListenerContext> contextTask = _listener.GetContextAsync();
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.TransferEncodingChunked = transferEncodingChunked;
Task<HttpResponseMessage> clientTask = client.PostAsync(_factory.ListeningUrl, new StringContent(Text));
HttpListenerContext context = await contextTask;
byte[] buffer = new byte[expected.Length - 5];
int bytesRead = await context.Request.InputStream.ReadAsync(buffer, 0, buffer.Length);
Assert.Equal(buffer.Length, bytesRead);
context.Response.Close();
}
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task Read_Disposed_ReturnsZero(bool transferEncodingChunked)
{
const string Text = "Some-String";
int bufferSize = Encoding.UTF8.GetByteCount(Text);
Task<HttpListenerContext> contextTask = _listener.GetContextAsync();
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.TransferEncodingChunked = transferEncodingChunked;
Task<HttpResponseMessage> clientTask = client.PostAsync(_factory.ListeningUrl, new StringContent(Text));
HttpListenerContext context = await contextTask;
context.Request.InputStream.Close();
byte[] buffer = new byte[bufferSize];
Assert.Equal(0, context.Request.InputStream.Read(buffer, 0, buffer.Length));
Assert.Equal(new byte[bufferSize], buffer);
IAsyncResult result = context.Request.InputStream.BeginRead(buffer, 0, buffer.Length, null, null);
Assert.Equal(0, context.Request.InputStream.EndRead(result));
Assert.Equal(new byte[bufferSize], buffer);
context.Response.Close();
}
}
[Fact]
public async Task CanSeek_Get_ReturnsFalse()
{
HttpListenerRequest response = await _helper.GetRequest(chunked: true);
using (Stream inputStream = response.InputStream)
{
Assert.False(inputStream.CanSeek);
Assert.Throws<NotSupportedException>(() => inputStream.Length);
Assert.Throws<NotSupportedException>(() => inputStream.SetLength(1));
Assert.Throws<NotSupportedException>(() => inputStream.Position);
Assert.Throws<NotSupportedException>(() => inputStream.Position = 1);
Assert.Throws<NotSupportedException>(() => inputStream.Seek(0, SeekOrigin.Begin));
}
}
[Fact]
public async Task CanRead_Get_ReturnsTrue()
{
HttpListenerRequest request = await _helper.GetRequest(chunked: true);
using (Stream inputStream = request.InputStream)
{
Assert.True(inputStream.CanRead);
}
}
[Fact]
public async Task CanWrite_Get_ReturnsFalse()
{
HttpListenerRequest request = await _helper.GetRequest(chunked: true);
using (Stream inputStream = request.InputStream)
{
Assert.False(inputStream.CanWrite);
Assert.Throws<InvalidOperationException>(() => inputStream.Write(new byte[0], 0, 0));
await Assert.ThrowsAsync<InvalidOperationException>(() => inputStream.WriteAsync(new byte[0], 0, 0));
Assert.Throws<InvalidOperationException>(() => inputStream.EndWrite(null));
// Flushing the output stream is a no-op.
inputStream.Flush();
Assert.Equal(Task.CompletedTask, inputStream.FlushAsync(CancellationToken.None));
}
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task Read_NullBuffer_ThrowsArgumentNullException(bool chunked)
{
HttpListenerRequest request = await _helper.GetRequest(chunked);
using (Stream inputStream = request.InputStream)
{
AssertExtensions.Throws<ArgumentNullException>("buffer", () => inputStream.Read(null, 0, 0));
await Assert.ThrowsAsync<ArgumentNullException>("buffer", () => inputStream.ReadAsync(null, 0, 0));
}
}
[Theory]
[InlineData(-1, true)]
[InlineData(3, true)]
[InlineData(-1, false)]
[InlineData(3, false)]
public async Task Read_InvalidOffset_ThrowsArgumentOutOfRangeException(int offset, bool chunked)
{
HttpListenerRequest request = await _helper.GetRequest(chunked);
using (Stream inputStream = request.InputStream)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("offset", () => inputStream.Read(new byte[2], offset, 0));
await Assert.ThrowsAsync<ArgumentOutOfRangeException>("offset", () => inputStream.ReadAsync(new byte[2], offset, 0));
}
}
[Theory]
[InlineData(0, 3, true)]
[InlineData(1, 2, true)]
[InlineData(2, 1, true)]
[InlineData(0, 3, false)]
[InlineData(1, 2, false)]
[InlineData(2, 1, false)]
public async Task Read_InvalidOffsetSize_ThrowsArgumentOutOfRangeException(int offset, int size, bool chunked)
{
HttpListenerRequest request = await _helper.GetRequest(chunked);
using (Stream inputStream = request.InputStream)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("size", () => inputStream.Read(new byte[2], offset, size));
await Assert.ThrowsAsync<ArgumentOutOfRangeException>("size", () => inputStream.ReadAsync(new byte[2], offset, size));
}
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task EndRead_NullAsyncResult_ThrowsArgumentNullException(bool chunked)
{
HttpListenerRequest request = await _helper.GetRequest(chunked);
using (Stream inputStream = request.InputStream)
{
AssertExtensions.Throws<ArgumentNullException>("asyncResult", () => inputStream.EndRead(null));
}
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task EndRead_InvalidAsyncResult_ThrowsArgumentException(bool chunked)
{
HttpListenerRequest request1 = await _helper.GetRequest(chunked);
HttpListenerRequest request2 = await _helper.GetRequest(chunked);
using (Stream inputStream1 = request1.InputStream)
using (Stream inputStream2 = request2.InputStream)
{
IAsyncResult beginReadResult = inputStream1.BeginRead(new byte[0], 0, 0, null, null);
AssertExtensions.Throws<ArgumentException>("asyncResult", () => inputStream2.EndRead(new CustomAsyncResult()));
AssertExtensions.Throws<ArgumentException>("asyncResult", () => inputStream2.EndRead(beginReadResult));
}
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task EndRead_CalledTwice_ThrowsInvalidOperationException(bool chunked)
{
HttpListenerRequest request = await _helper.GetRequest(chunked);
using (Stream inputStream = request.InputStream)
{
IAsyncResult beginReadResult = inputStream.BeginRead(new byte[0], 0, 0, null, null);
inputStream.EndRead(beginReadResult);
Assert.Throws<InvalidOperationException>(() => inputStream.EndRead(beginReadResult));
}
}
[ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotOneCoreUAP))]
public async Task Read_FromClosedConnectionAsynchronously_ThrowsHttpListenerException()
{
const string Text = "Some-String";
byte[] expected = Encoding.UTF8.GetBytes(Text);
using (Socket client = _factory.GetConnectedSocket())
{
// Send a header to the HttpListener to give it a context.
// Note: It's important here that we don't send the content.
// If the content is missing, then the HttpListener needs
// to get the content. However, the socket has been closed
// before the reading of the content, so reading should fail.
client.Send(_factory.GetContent(RequestTypes.POST, Text, headerOnly: true));
HttpListenerContext context = await _listener.GetContextAsync();
// Disconnect the Socket from the HttpListener.
Helpers.WaitForSocketShutdown(client);
// Reading from a closed connection should fail.
byte[] buffer = new byte[expected.Length];
await Assert.ThrowsAsync<HttpListenerException>(() => context.Request.InputStream.ReadAsync(buffer, 0, buffer.Length));
await Assert.ThrowsAsync<HttpListenerException>(() => context.Request.InputStream.ReadAsync(buffer, 0, buffer.Length));
}
}
[ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotOneCoreUAP))]
public async Task Read_FromClosedConnectionSynchronously_ThrowsHttpListenerException()
{
const string Text = "Some-String";
byte[] expected = Encoding.UTF8.GetBytes(Text);
using (Socket client = _factory.GetConnectedSocket())
{
// Send a header to the HttpListener to give it a context.
// Note: It's important here that we don't send the content.
// If the content is missing, then the HttpListener needs
// to get the content. However, the socket has been closed
// before the reading of the content, so reading should fail.
client.Send(_factory.GetContent(RequestTypes.POST, Text, headerOnly: true));
HttpListenerContext context = await _listener.GetContextAsync();
// Disconnect the Socket from the HttpListener.
Helpers.WaitForSocketShutdown(client);
// Reading from a closed connection should fail.
byte[] buffer = new byte[expected.Length];
Assert.Throws<HttpListenerException>(() => context.Request.InputStream.Read(buffer, 0, buffer.Length));
Assert.Throws<HttpListenerException>(() => context.Request.InputStream.Read(buffer, 0, buffer.Length));
}
}
}
}
| |
/*
Copyright 2012 Michael Edwards
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.
*/
//-CRE-
using Glass.Mapper.Pipelines.ConfigurationResolver.Tasks.OnDemandResolver;
using Glass.Mapper.Pipelines.DataMapperResolver;
using Glass.Mapper.Sc.Configuration;
using Glass.Mapper.Sc.Configuration.Attributes;
using Glass.Mapper.Sc.DataMappers;
using NSubstitute;
using NUnit.Framework;
using Sitecore.Data;
using Sitecore.Data.Items;
using Sitecore.Data.Managers;
using Sitecore.FakeDb;
namespace Glass.Mapper.Sc.FakeDb.DataMappers
{
[TestFixture]
public class SitecoreNodeMapperFixture
{
protected const string FieldName = "Field";
#region Property - ReadOnly
[Test]
public void ReadOnly_ReturnsTrue()
{
//Assign
var mapper = new SitecoreNodeMapper();
//Act
var result = mapper.ReadOnly;
//Assert
Assert.IsTrue(result);
}
#endregion
#region Method - CanHandle
[Test]
public void CanHandle_ConfigIsNodeAndClassMapped_ReturnsTrue()
{
//Assign
var config = new SitecoreNodeConfiguration();
var mapper = new SitecoreNodeMapper();
//Act
var result = mapper.CanHandle(config, null);
//Assert
Assert.IsTrue(result);
}
[Test]
public void CanHandle_ConfigIsNotNodeAndClassMapped_ReturnsFalse()
{
//Assign
var config = new SitecoreFieldConfiguration();
var mapper = new SitecoreNodeMapper();
//Act
var result = mapper.CanHandle(config, null);
//Assert
Assert.IsFalse(result);
}
#endregion
#region Method - MapToProperty
[Test]
public void MapToProperty_GetItemByPath_ReturnsItem()
{
//Assign
using (Db database = new Db
{
new Sitecore.FakeDb.DbItem("Source"),
new Sitecore.FakeDb.DbItem("Target")
})
{
var config = new SitecoreNodeConfiguration();
var mapper = new SitecoreNodeMapper();
var language = LanguageManager.GetLanguage("en");
mapper.Setup(new DataMapperResolverArgs(null, config));
var obj = new Stub();
var source = database.Database.GetItem("/sitecore/content/Source", language);
var target = database.Database.GetItem("/sitecore/content/Target", language);
var service = Substitute.For<ISitecoreService>();
var expected = new StubMapped();
config.PropertyInfo = typeof(Stub).GetProperty("StubMapped");
config.Path = "/sitecore/content/Target";
service.CreateType(
typeof(StubMapped),
Arg.Is<Item>(x => x.Paths.FullPath == target.Paths.FullPath && x.Language == language),
false,
false, null).Returns(expected);
service.ItemVersionHandler.VersionCountEnabledAndHasVersions(target).Returns(true);
var mappingContext = new SitecoreDataMappingContext(obj, source, service);
//Act
var result = mapper.MapToProperty(mappingContext);
//Assert
Assert.AreEqual(expected, result);
}
}
[Test]
public void MapToProperty_GetItemByPathDifferentLanguage_ReturnsItem()
{
//Assign
var language = LanguageManager.GetLanguage("af-ZA");
using (Db database = new Db
{
new Sitecore.FakeDb.DbItem("Source")
{
new Sitecore.FakeDb.DbField("Title")
{
{language.Name , language.Name }
}
},
new Sitecore.FakeDb.DbItem("Target")
{
new Sitecore.FakeDb.DbField("Title")
{
{language.Name , language.Name }
}
},
})
{
var config = new SitecoreNodeConfiguration();
var mapper = new SitecoreNodeMapper();
mapper.Setup(new DataMapperResolverArgs(null, config));
var obj = new Stub();
var source = database.Database.GetItem("/sitecore/content/Source", language);
var target = database.Database.GetItem("/sitecore/content/Target", language);
var service = Substitute.For<ISitecoreService>();
var expected = new StubMapped();
config.PropertyInfo = typeof(Stub).GetProperty("StubMapped");
config.Path = "/sitecore/content/Target";
service.CreateType(
typeof(StubMapped),
Arg.Is<Item>(x => x.Paths.FullPath == target.Paths.FullPath && x.Language == language),
false,
false, null).Returns(expected);
service.ItemVersionHandler.VersionCountEnabledAndHasVersions(target).Returns(true);
var mappingContext = new SitecoreDataMappingContext(obj, source, service);
//Act
var result = mapper.MapToProperty(mappingContext);
//Assert
Assert.AreEqual(expected, result);
}
}
[Test]
public void MapToProperty_GetItemByPathDifferentLanguageTargetDoesNotExistInLanguage_ReturnsNull()
{
//Assign
var config = new SitecoreNodeConfiguration();
var mapper = new SitecoreNodeMapper();
var language = LanguageManager.GetLanguage("af-ZA");
using (Db database = new Db
{
new Sitecore.FakeDb.DbItem("Source")
{
new Sitecore.FakeDb.DbField("Title")
{
{language.Name, language.Name}
}
},
new Sitecore.FakeDb.DbItem("TargetOneLanguage")
{
},
})
{
mapper.Setup(new DataMapperResolverArgs(null, config));
var obj = new Stub();
var source = database.Database.GetItem("/sitecore/content/Source", language);
var target = database.Database.GetItem(
"/sitecore/content/Tests/DataMappers/SitecoreNodeMapper/TargetOneLanguage", language);
var service = Substitute.For<ISitecoreService>();
var expected = new StubMapped();
config.PropertyInfo = typeof(Stub).GetProperty("StubMapped");
config.Path = "/sitecore/content/Tests/DataMappers/SitecoreNodeMapper/Target";
service.CreateType(
typeof(StubMapped),
Arg.Is<Item>(x =>
x.Paths.FullPath == target.Paths.FullPath
&& x.Language == language
&& x.Versions.Count == 0),
false,
false, null).Returns(expected);
var mappingContext = new SitecoreDataMappingContext(obj, source, service);
//Act
var result = mapper.MapToProperty(mappingContext);
//Assert
Assert.IsNull(result);
}
}
[Test]
public void MapToProperty_GetItemByID_ReturnsItem()
{
//Assign
var config = new SitecoreNodeConfiguration();
var context = Context.Create(FakeDb.Utilities.CreateStandardResolver());
var mapper = new SitecoreNodeMapper();
var language = LanguageManager.GetLanguage("en");
context.Load(new OnDemandLoader<SitecoreTypeConfiguration>(typeof(StubMapped)));
mapper.Setup(new DataMapperResolverArgs(context, config));
var obj = new Stub();
using (Db database = new Db{
new Sitecore.FakeDb.DbItem("Source"),
new Sitecore.FakeDb.DbItem("Target")
})
{
var source = database.Database.GetItem("/sitecore/content/Source", language);
var target = database.Database.GetItem("/sitecore/content/Target", language);
var service = Substitute.For<ISitecoreService>();
var expected = new StubMapped();
config.PropertyInfo = typeof(Stub).GetProperty("StubMapped");
config.Id = target.ID.Guid.ToString();
service.CreateType(
typeof(StubMapped),
Arg.Is<Item>(x => x.Paths.FullPath == target.Paths.FullPath && x.Language == language),
false,
false, null).Returns(expected);
service.ItemVersionHandler.VersionCountEnabledAndHasVersions(target).Returns(true);
var mappingContext = new SitecoreDataMappingContext(obj, source, service);
//Act
var result = mapper.MapToProperty(mappingContext);
//Assert
Assert.AreEqual(expected, result);
}
}
[Test]
public void MapToProperty_GetItemByIdDifferentLanguage_ReturnsItem()
{
//Assign
var config = new SitecoreNodeConfiguration();
var context = Context.Create(FakeDb.Utilities.CreateStandardResolver());
var mapper = new SitecoreNodeMapper();
var language = LanguageManager.GetLanguage("af-ZA");
context.Load(new OnDemandLoader<SitecoreTypeConfiguration>(typeof(StubMapped)));
mapper.Setup(new DataMapperResolverArgs(context, config));
var obj = new Stub();
using (Db database = new Db
{
new Sitecore.FakeDb.DbItem("Source"),
new Sitecore.FakeDb.DbItem("Target")
})
{
var source = database.Database.GetItem("/sitecore/content/Source", language);
var target = database.Database.GetItem("/sitecore/content/Target", language);
var service = Substitute.For<ISitecoreService>();
var expected = new StubMapped();
config.PropertyInfo = typeof(Stub).GetProperty("StubMapped");
config.Id = target.ID.Guid.ToString();
service.CreateType(
typeof(StubMapped),
Arg.Is<Item>(x => x.Paths.FullPath == target.Paths.FullPath && x.Language == language),
false,
false, null).Returns(expected);
service.ItemVersionHandler.VersionCountEnabledAndHasVersions(target).Returns(true);
var mappingContext = new SitecoreDataMappingContext(obj, source, service);
//Act
var result = mapper.MapToProperty(mappingContext);
//Assert
Assert.AreEqual(expected, result);
}
}
[Test]
public void MapToProperty_GetItemByIdDifferentLanguageTargetDoesNotExistInLanguage_ReturnsNull()
{
//Assign
var config = new SitecoreNodeConfiguration();
var context = Context.Create(FakeDb.Utilities.CreateStandardResolver());
var mapper = new SitecoreNodeMapper();
var language = LanguageManager.GetLanguage("af-ZA");
context.Load(new OnDemandLoader<SitecoreTypeConfiguration>(typeof(StubMapped)));
mapper.Setup(new DataMapperResolverArgs(context, config));
var obj = new Stub();
using (Db database = new Db
{
new Sitecore.FakeDb.DbItem("Source"),
new Sitecore.FakeDb.DbItem("Target")
})
{
var source = database.Database.GetItem("/sitecore/content/Source", language);
var target = database.Database.GetItem("/sitecore/content/Target", language);
var service = Substitute.For<ISitecoreService>();
var expected = new StubMapped();
config.PropertyInfo = typeof(Stub).GetProperty("StubMapped");
config.Id = target.ID.Guid.ToString();
service.CreateType(
typeof(StubMapped),
Arg.Is<Item>(x => x.Paths.FullPath == target.Paths.FullPath && x.Language == language),
false,
false, null).Returns(expected);
service.ItemVersionHandler.VersionCountEnabledAndHasVersions(target).Returns(false);
var mappingContext = new SitecoreDataMappingContext(obj, source, service);
//Act
var result = mapper.MapToProperty(mappingContext);
//Assert
Assert.IsNull(result);
}
}
[Test]
public void MapToProperty_GetItemByPathIsLazy_ReturnsItem()
{
//Assign
var config = new SitecoreNodeConfiguration();
var context = Context.Create(FakeDb.Utilities.CreateStandardResolver());
var mapper = new SitecoreNodeMapper();
var language = LanguageManager.GetLanguage("en");
context.Load(new OnDemandLoader<SitecoreTypeConfiguration>(typeof(StubMapped)));
mapper.Setup(new DataMapperResolverArgs(context, config));
var obj = new Stub();
using (Db database = new Db
{
new Sitecore.FakeDb.DbItem("Source"),
new Sitecore.FakeDb.DbItem("Target")
})
{
var source = database.Database.GetItem("/sitecore/content/Source", language);
var target = database.Database.GetItem("/sitecore/content/Target", language);
var service = Substitute.For<ISitecoreService>();
var expected = new StubMapped();
config.PropertyInfo = typeof(Stub).GetProperty("StubMapped");
config.Path = "/sitecore/content/Target";
config.IsLazy = true;
service.CreateType(
typeof(StubMapped),
Arg.Is<Item>(x => x.Paths.FullPath == target.Paths.FullPath && x.Language == language),
true,
false, null).Returns(expected);
service.ItemVersionHandler.VersionCountEnabledAndHasVersions(target).Returns(true);
var mappingContext = new SitecoreDataMappingContext(obj, source, service);
//Act
var result = mapper.MapToProperty(mappingContext);
//Assert
Assert.AreEqual(expected, result);
}
}
[Test]
public void MapToProperty_GetItemByPathInferType_ReturnsItem()
{
//Assign
var config = new SitecoreNodeConfiguration();
var context = Context.Create(FakeDb.Utilities.CreateStandardResolver());
var mapper = new SitecoreNodeMapper();
var language = LanguageManager.GetLanguage("en");
context.Load(new OnDemandLoader<SitecoreTypeConfiguration>(typeof(StubMapped)));
mapper.Setup(new DataMapperResolverArgs(context, config));
var obj = new Stub();
using (Db database = new Db
{
new Sitecore.FakeDb.DbItem("Source"),
new Sitecore.FakeDb.DbItem("Target")
})
{
var source = database.Database.GetItem("/sitecore/content/Source", language);
var target = database.Database.GetItem("/sitecore/content/Target", language);
var service = Substitute.For<ISitecoreService>();
var expected = new StubMapped();
config.PropertyInfo = typeof(Stub).GetProperty("StubMapped");
config.Path = "/sitecore/content/Target";
config.InferType = true;
service.CreateType(
typeof(StubMapped),
Arg.Is<Item>(x => x.Paths.FullPath == target.Paths.FullPath && x.Language == language),
false,
true, null).Returns(expected);
var mappingContext = new SitecoreDataMappingContext(obj, source, service);
service.ItemVersionHandler.VersionCountEnabledAndHasVersions(target).Returns(true);
//Act
var result = mapper.MapToProperty(mappingContext);
//Assert
Assert.AreEqual(expected, result);
}
}
#endregion
#region Stubs
[SitecoreType]
public class StubMapped
{
}
public class StubNotMapped
{
}
public class Stub
{
public StubMapped StubMapped { get; set; }
public StubNotMapped StubNotMapped { get; set; }
}
#endregion
}
}
| |
// 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.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using System.Xml.Linq;
using Microsoft.Win32;
namespace Microsoft.Extensions.Logging
{
/// <summary>
/// Helpful extension methods on <see cref="ILogger"/>.
/// </summary>
internal static partial class LoggingExtensions
{
/// <summary>
/// Returns a value stating whether the 'debug' log level is enabled.
/// Returns false if the logger instance is null.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool IsDebugLevelEnabled([NotNullWhen(true)] this ILogger? logger)
{
return IsLogLevelEnabledCore(logger, LogLevel.Debug);
}
/// <summary>
/// Returns a value stating whether the 'trace' log level is enabled.
/// Returns false if the logger instance is null.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool IsTraceLevelEnabled([NotNullWhen(true)] this ILogger? logger)
{
return IsLogLevelEnabledCore(logger, LogLevel.Trace);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static bool IsLogLevelEnabledCore([NotNullWhen(true)] ILogger? logger, LogLevel level)
{
return (logger != null && logger.IsEnabled(level));
}
[LoggerMessage(1, LogLevel.Warning, "Policy resolution states that a new key should be added to the key ring, but automatic generation of keys is disabled. Using fallback key {KeyId:B} with expiration {ExpirationDate:u} as default key.", EventName = "UsingFallbackKeyWithExpirationAsDefaultKey")]
public static partial void UsingFallbackKeyWithExpirationAsDefaultKey(this ILogger logger, Guid keyId, DateTimeOffset expirationDate);
[LoggerMessage(2, LogLevel.Debug, "Using key {KeyId:B} as the default key.", EventName = "UsingKeyAsDefaultKey")]
public static partial void UsingKeyAsDefaultKey(this ILogger logger, Guid keyId);
[LoggerMessage(3, LogLevel.Debug, "Opening CNG algorithm '{HashAlgorithm}' from provider '{HashAlgorithmProvider}' with HMAC.", EventName = "OpeningCNGAlgorithmFromProviderWithHMAC")]
public static partial void OpeningCNGAlgorithmFromProviderWithHMAC(this ILogger logger, string hashAlgorithm, string? hashAlgorithmProvider);
[LoggerMessage(4, LogLevel.Debug, "Opening CNG algorithm '{EncryptionAlgorithm}' from provider '{EncryptionAlgorithmProvider}' with chaining mode CBC.", EventName = "OpeningCNGAlgorithmFromProviderWithChainingModeCBC")]
public static partial void OpeningCNGAlgorithmFromProviderWithChainingModeCBC(this ILogger logger, string encryptionAlgorithm, string? encryptionAlgorithmProvider);
[LoggerMessage(5, LogLevel.Trace, "Performing unprotect operation to key {KeyId:B} with purposes {Purposes}.", EventName = "PerformingUnprotectOperationToKeyWithPurposes")]
public static partial void PerformingUnprotectOperationToKeyWithPurposes(this ILogger logger, Guid keyId, string purposes);
[LoggerMessage(6, LogLevel.Trace, "Key {KeyId:B} was not found in the key ring. Unprotect operation cannot proceed.", EventName = "KeyWasNotFoundInTheKeyRingUnprotectOperationCannotProceed")]
public static partial void KeyWasNotFoundInTheKeyRingUnprotectOperationCannotProceed(this ILogger logger, Guid keyId);
[LoggerMessage(7, LogLevel.Debug, "Key {KeyId:B} was revoked. Caller requested unprotect operation proceed regardless.", EventName = "KeyWasRevokedCallerRequestedUnprotectOperationProceedRegardless")]
public static partial void KeyWasRevokedCallerRequestedUnprotectOperationProceedRegardless(this ILogger logger, Guid keyId);
[LoggerMessage(8, LogLevel.Debug, "Key {KeyId:B} was revoked. Unprotect operation cannot proceed.", EventName = "KeyWasRevokedUnprotectOperationCannotProceed")]
public static partial void KeyWasRevokedUnprotectOperationCannotProceed(this ILogger logger, Guid keyId);
[LoggerMessage(9, LogLevel.Debug, "Opening CNG algorithm '{EncryptionAlgorithm}' from provider '{EncryptionAlgorithmProvider}' with chaining mode GCM.", EventName = "OpeningCNGAlgorithmFromProviderWithChainingModeGCM")]
public static partial void OpeningCNGAlgorithmFromProviderWithChainingModeGCM(this ILogger logger, string encryptionAlgorithm, string? encryptionAlgorithmProvider);
[LoggerMessage(10, LogLevel.Debug, "Using managed keyed hash algorithm '{FullName}'.", EventName = "UsingManagedKeyedHashAlgorithm")]
public static partial void UsingManagedKeyedHashAlgorithm(this ILogger logger, string fullName);
[LoggerMessage(11, LogLevel.Debug, "Using managed symmetric algorithm '{FullName}'.", EventName = "UsingManagedSymmetricAlgorithm")]
public static partial void UsingManagedSymmetricAlgorithm(this ILogger logger, string fullName);
[LoggerMessage(12, LogLevel.Warning, "Key {KeyId:B} is ineligible to be the default key because its {MethodName} method failed.", EventName = "KeyIsIneligibleToBeTheDefaultKeyBecauseItsMethodFailed")]
public static partial void KeyIsIneligibleToBeTheDefaultKeyBecauseItsMethodFailed(this ILogger logger, Guid keyId, string methodName, Exception exception);
[LoggerMessage(13, LogLevel.Debug, "Considering key {KeyId:B} with expiration date {ExpirationDate:u} as default key.", EventName = "ConsideringKeyWithExpirationDateAsDefaultKey")]
public static partial void ConsideringKeyWithExpirationDateAsDefaultKey(this ILogger logger, Guid keyId, DateTimeOffset expirationDate);
[LoggerMessage(14, LogLevel.Debug, "Key {KeyId:B} is no longer under consideration as default key because it is expired, revoked, or cannot be deciphered.", EventName = "KeyIsNoLongerUnderConsiderationAsDefault")]
public static partial void KeyIsNoLongerUnderConsiderationAsDefault(this ILogger logger, Guid keyId);
[LoggerMessage(15, LogLevel.Warning, "Unknown element with name '{Name}' found in keyring, skipping.", EventName = "UnknownElementWithNameFoundInKeyringSkipping")]
public static partial void UnknownElementWithNameFoundInKeyringSkipping(this ILogger logger, XName name);
[LoggerMessage(16, LogLevel.Debug, "Marked key {KeyId:B} as revoked in the keyring.", EventName = "MarkedKeyAsRevokedInTheKeyring")]
public static partial void MarkedKeyAsRevokedInTheKeyring(this ILogger logger, Guid keyId);
[LoggerMessage(17, LogLevel.Warning, "Tried to process revocation of key {KeyId:B}, but no such key was found in keyring. Skipping.", EventName = "TriedToProcessRevocationOfKeyButNoSuchKeyWasFound")]
public static partial void TriedToProcessRevocationOfKeyButNoSuchKeyWasFound(this ILogger logger, Guid keyId);
[LoggerMessage(18, LogLevel.Debug, "Found key {KeyId:B}.", EventName = "FoundKey")]
public static partial void FoundKey(this ILogger logger, Guid keyId);
[LoggerMessage(19, LogLevel.Debug, "Found revocation of all keys created prior to {RevocationDate:u}.", EventName = "FoundRevocationOfAllKeysCreatedPriorTo")]
public static partial void FoundRevocationOfAllKeysCreatedPriorTo(this ILogger logger, DateTimeOffset revocationDate);
[LoggerMessage(20, LogLevel.Debug, "Found revocation of key {KeyId:B}.", EventName = "FoundRevocationOfKey")]
public static partial void FoundRevocationOfKey(this ILogger logger, Guid keyId);
[LoggerMessage(21, LogLevel.Error, "An exception occurred while processing the revocation element '{RevocationElement}'. Cannot continue keyring processing.", EventName = "ExceptionWhileProcessingRevocationElement")]
public static partial void ExceptionWhileProcessingRevocationElement(this ILogger logger, XElement revocationElement, Exception exception);
[LoggerMessage(22, LogLevel.Information, "Revoking all keys as of {RevocationDate:u} for reason '{Reason}'.", EventName = "RevokingAllKeysAsOfForReason")]
public static partial void RevokingAllKeysAsOfForReason(this ILogger logger, DateTimeOffset revocationDate, string? reason);
[LoggerMessage(23, LogLevel.Debug, "Key cache expiration token triggered by '{OperationName}' operation.", EventName = "KeyCacheExpirationTokenTriggeredByOperation")]
public static partial void KeyCacheExpirationTokenTriggeredByOperation(this ILogger logger, string operationName);
[LoggerMessage(24, LogLevel.Error, "An exception occurred while processing the key element '{Element}'.", EventName = "ExceptionOccurredWhileProcessingTheKeyElement")]
public static partial void ExceptionWhileProcessingKeyElement(this ILogger logger, XElement element, Exception exception);
[LoggerMessage(25, LogLevel.Trace, "An exception occurred while processing the key element '{Element}'.", EventName = "ExceptionOccurredWhileProcessingTheKeyElementDebug")]
public static partial void AnExceptionOccurredWhileProcessingElementDebug(this ILogger logger, XElement element, Exception exception);
[LoggerMessage(26, LogLevel.Debug, "Encrypting to Windows DPAPI for current user account ({Name}).", EventName = "EncryptingToWindowsDPAPIForCurrentUserAccount")]
public static partial void EncryptingToWindowsDPAPIForCurrentUserAccount(this ILogger logger, string name);
[LoggerMessage(28, LogLevel.Error, "An error occurred while encrypting to X.509 certificate with thumbprint '{Thumbprint}'.", EventName = "ErrorOccurredWhileEncryptingToX509CertificateWithThumbprint")]
public static partial void AnErrorOccurredWhileEncryptingToX509CertificateWithThumbprint(this ILogger logger, string thumbprint, Exception exception);
[LoggerMessage(29, LogLevel.Debug, "Encrypting to X.509 certificate with thumbprint '{Thumbprint}'.", EventName = "EncryptingToX509CertificateWithThumbprint")]
public static partial void EncryptingToX509CertificateWithThumbprint(this ILogger logger, string thumbprint);
[LoggerMessage(30, LogLevel.Error, "An exception occurred while trying to resolve certificate with thumbprint '{Thumbprint}'.", EventName = "ExceptionOccurredWhileTryingToResolveCertificateWithThumbprint")]
public static partial void ExceptionWhileTryingToResolveCertificateWithThumbprint(this ILogger logger, string thumbprint, Exception exception);
[LoggerMessage(31, LogLevel.Trace, "Performing protect operation to key {KeyId:B} with purposes {Purposes}.", EventName = "PerformingProtectOperationToKeyWithPurposes")]
public static partial void PerformingProtectOperationToKeyWithPurposes(this ILogger logger, Guid keyId, string purposes);
[LoggerMessage(32, LogLevel.Debug, "Descriptor deserializer type for key {KeyId:B} is '{AssemblyQualifiedName}'.", EventName = "DescriptorDeserializerTypeForKeyIs")]
public static partial void DescriptorDeserializerTypeForKeyIs(this ILogger logger, Guid keyId, string assemblyQualifiedName);
[LoggerMessage(33, LogLevel.Debug, "Key escrow sink found. Writing key {KeyId:B} to escrow.", EventName = "KeyEscrowSinkFoundWritingKeyToEscrow")]
public static partial void KeyEscrowSinkFoundWritingKeyToEscrow(this ILogger logger, Guid keyId);
[LoggerMessage(34, LogLevel.Debug, "No key escrow sink found. Not writing key {KeyId:B} to escrow.", EventName = "NoKeyEscrowSinkFoundNotWritingKeyToEscrow")]
public static partial void NoKeyEscrowSinkFoundNotWritingKeyToEscrow(this ILogger logger, Guid keyId);
[LoggerMessage(35, LogLevel.Warning, "No XML encryptor configured. Key {KeyId:B} may be persisted to storage in unencrypted form.", EventName = "NoXMLEncryptorConfiguredKeyMayBePersistedToStorageInUnencryptedForm")]
public static partial void NoXMLEncryptorConfiguredKeyMayBePersistedToStorageInUnencryptedForm(this ILogger logger, Guid keyId);
[LoggerMessage(36, LogLevel.Information, "Revoking key {KeyId:B} at {RevocationDate:u} for reason '{Reason}'.", EventName = "RevokingKeyForReason")]
public static partial void RevokingKeyForReason(this ILogger logger, Guid keyId, DateTimeOffset revocationDate, string? reason);
[LoggerMessage(37, LogLevel.Debug, "Reading data from file '{FullPath}'.", EventName = "ReadingDataFromFile")]
public static partial void ReadingDataFromFile(this ILogger logger, string fullPath);
[LoggerMessage(38, LogLevel.Debug, "The name '{FriendlyName}' is not a safe file name, using '{NewFriendlyName}' instead.", EventName = "NameIsNotSafeFileName")]
public static partial void NameIsNotSafeFileName(this ILogger logger, string friendlyName, string newFriendlyName);
[LoggerMessage(39, LogLevel.Information, "Writing data to file '{FileName}'.", EventName = "WritingDataToFile")]
public static partial void WritingDataToFile(this ILogger logger, string fileName);
[LoggerMessage(40, LogLevel.Debug, "Reading data from registry key '{RegistryKeyName}', value '{Value}'.", EventName = "ReadingDataFromRegistryKeyValue")]
public static partial void ReadingDataFromRegistryKeyValue(this ILogger logger, RegistryKey registryKeyName, string value);
[LoggerMessage(41, LogLevel.Debug, "The name '{FriendlyName}' is not a safe registry value name, using '{NewFriendlyName}' instead.", EventName = "NameIsNotSafeRegistryValueName")]
public static partial void NameIsNotSafeRegistryValueName(this ILogger logger, string friendlyName, string newFriendlyName);
[LoggerMessage(42, LogLevel.Debug, "Decrypting secret element using Windows DPAPI-NG with protection descriptor rule '{DescriptorRule}'.", EventName = "DecryptingSecretElementUsingWindowsDPAPING")]
public static partial void DecryptingSecretElementUsingWindowsDPAPING(this ILogger logger, string? descriptorRule);
[LoggerMessage(27, LogLevel.Debug, "Encrypting to Windows DPAPI-NG using protection descriptor rule '{DescriptorRule}'.", EventName = "EncryptingToWindowsDPAPINGUsingProtectionDescriptorRule")]
public static partial void EncryptingToWindowsDPAPINGUsingProtectionDescriptorRule(this ILogger logger, string descriptorRule);
[LoggerMessage(43, LogLevel.Error, "An exception occurred while trying to decrypt the element.", EventName = "ExceptionOccurredTryingToDecryptElement")]
public static partial void ExceptionOccurredTryingToDecryptElement(this ILogger logger, Exception exception);
[LoggerMessage(44, LogLevel.Warning, "Encrypting using a null encryptor; secret information isn't being protected.", EventName = "EncryptingUsingNullEncryptor")]
public static partial void EncryptingUsingNullEncryptor(this ILogger logger);
[LoggerMessage(45, LogLevel.Information, "Using ephemeral data protection provider. Payloads will be undecipherable upon application shutdown.", EventName = "UsingEphemeralDataProtectionProvider")]
public static partial void UsingEphemeralDataProtectionProvider(this ILogger logger);
[LoggerMessage(46, LogLevel.Debug, "Existing cached key ring is expired. Refreshing.", EventName = "ExistingCachedKeyRingIsExpiredRefreshing")]
public static partial void ExistingCachedKeyRingIsExpired(this ILogger logger);
[LoggerMessage(47, LogLevel.Error, "An error occurred while refreshing the key ring. Will try again in 2 minutes.", EventName = "ErrorOccurredWhileRefreshingKeyRing")]
public static partial void ErrorOccurredWhileRefreshingKeyRing(this ILogger logger, Exception exception);
[LoggerMessage(48, LogLevel.Error, "An error occurred while reading the key ring.", EventName = "ErrorOccurredWhileReadingKeyRing")]
public static partial void ErrorOccurredWhileReadingKeyRing(this ILogger logger, Exception exception);
[LoggerMessage(49, LogLevel.Error, "The key ring does not contain a valid default key, and the key manager is configured with auto-generation of keys disabled.", EventName = "KeyRingDoesNotContainValidDefaultKey")]
public static partial void KeyRingDoesNotContainValidDefaultKey(this ILogger logger);
[LoggerMessage(50, LogLevel.Warning, "Using an in-memory repository. Keys will not be persisted to storage.", EventName = "UsingInMemoryRepository")]
public static partial void UsingInmemoryRepository(this ILogger logger);
[LoggerMessage(51, LogLevel.Debug, "Decrypting secret element using Windows DPAPI.", EventName = "DecryptingSecretElementUsingWindowsDPAPI")]
public static partial void DecryptingSecretElementUsingWindowsDPAPI(this ILogger logger);
[LoggerMessage(52, LogLevel.Debug, "Default key expiration imminent and repository contains no viable successor. Caller should generate a successor.", EventName = "DefaultKeyExpirationImminentAndRepository")]
public static partial void DefaultKeyExpirationImminentAndRepository(this ILogger logger);
[LoggerMessage(53, LogLevel.Debug, "Repository contains no viable default key. Caller should generate a key with immediate activation.", EventName = "RepositoryContainsNoViableDefaultKey")]
public static partial void RepositoryContainsNoViableDefaultKey(this ILogger logger);
[LoggerMessage(54, LogLevel.Error, "An error occurred while encrypting to Windows DPAPI.", EventName = "ErrorOccurredWhileEncryptingToWindowsDPAPI")]
public static partial void ErrorOccurredWhileEncryptingToWindowsDPAPI(this ILogger logger, Exception exception);
[LoggerMessage(55, LogLevel.Debug, "Encrypting to Windows DPAPI for local machine account.", EventName = "EncryptingToWindowsDPAPIForLocalMachineAccount")]
public static partial void EncryptingToWindowsDPAPIForLocalMachineAccount(this ILogger logger);
[LoggerMessage(56, LogLevel.Error, "An error occurred while encrypting to Windows DPAPI-NG.", EventName = "ErrorOccurredWhileEncryptingToWindowsDPAPING")]
public static partial void ErrorOccurredWhileEncryptingToWindowsDPAPING(this ILogger logger, Exception exception);
[LoggerMessage(57, LogLevel.Debug, "Policy resolution states that a new key should be added to the key ring.", EventName = "PolicyResolutionStatesThatANewKeyShouldBeAddedToTheKeyRing")]
public static partial void PolicyResolutionStatesThatANewKeyShouldBeAddedToTheKeyRing(this ILogger logger);
[LoggerMessage(58, LogLevel.Information, "Creating key {KeyId:B} with creation date {CreationDate:u}, activation date {ActivationDate:u}, and expiration date {ExpirationDate:u}.", EventName = "CreatingKey")]
public static partial void CreatingKey(this ILogger logger, Guid keyId, DateTimeOffset creationDate, DateTimeOffset activationDate, DateTimeOffset expirationDate);
[LoggerMessage(59, LogLevel.Warning, "Neither user profile nor HKLM registry available. Using an ephemeral key repository. Protected data will be unavailable when application exits.", EventName = "UsingEphemeralKeyRepository")]
public static partial void UsingEphemeralKeyRepository(this ILogger logger);
[LoggerMessage(61, LogLevel.Information, "User profile not available. Using '{Name}' as key repository and Windows DPAPI to encrypt keys at rest.", EventName = "UsingRegistryAsKeyRepositoryWithDPAPI")]
public static partial void UsingRegistryAsKeyRepositoryWithDPAPI(this ILogger logger, string name);
[LoggerMessage(62, LogLevel.Information, "User profile is available. Using '{FullName}' as key repository; keys will not be encrypted at rest.", EventName = "UsingProfileAsKeyRepository")]
public static partial void UsingProfileAsKeyRepository(this ILogger logger, string fullName);
[LoggerMessage(63, LogLevel.Information, "User profile is available. Using '{FullName}' as key repository and Windows DPAPI to encrypt keys at rest.", EventName = "UsingProfileAsKeyRepositoryWithDPAPI")]
public static partial void UsingProfileAsKeyRepositoryWithDPAPI(this ILogger logger, string fullName);
[LoggerMessage(64, LogLevel.Information, "Azure Web Sites environment detected. Using '{FullName}' as key repository; keys will not be encrypted at rest.", EventName = "UsingAzureAsKeyRepository")]
public static partial void UsingAzureAsKeyRepository(this ILogger logger, string fullName);
[LoggerMessage(65, LogLevel.Debug, "Key ring with default key {KeyId:B} was loaded during application startup.", EventName = "KeyRingWasLoadedOnStartup")]
public static partial void KeyRingWasLoadedOnStartup(this ILogger logger, Guid keyId);
[LoggerMessage(66, LogLevel.Information, "Key ring failed to load during application startup.", EventName = "KeyRingFailedToLoadOnStartup")]
public static partial void KeyRingFailedToLoadOnStartup(this ILogger logger, Exception innerException);
[LoggerMessage(60, LogLevel.Warning, "Storing keys in a directory '{path}' that may not be persisted outside of the container. Protected data will be unavailable when container is destroyed.", EventName = "UsingEphemeralFileSystemLocationInContainer")]
public static partial void UsingEphemeralFileSystemLocationInContainer(this ILogger logger, string path);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.