context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
namespace PokerTell.PokerHand.Aquisition
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using Base;
using Infrastructure.Enumerations.PokerHand;
using Infrastructure.Interfaces.PokerHand;
using log4net;
/// <summary>
/// Description of PokerPlayer.
/// </summary>
public class AquiredPokerPlayer : PokerPlayer, IAquiredPokerPlayer
{
#region Constants and Fields
static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
#endregion
#region Constructors and Destructors
public AquiredPokerPlayer()
{
Rounds = new List<IAquiredPokerRound>();
}
/// <summary>
/// Initializes a new instance of the <see cref="AquiredPokerPlayer"/> class.
/// Create a player with given characteristics
/// Used when parsing a hand
/// </summary>
/// <param name="name">
/// <see cref="name"></see>
/// </param>
/// <param name="stack">
/// <see cref="stack"></see>
/// </param>
public AquiredPokerPlayer(string name, double stack)
: this()
{
InitializeWith(name, stack);
}
/// <summary>
/// Initializes a new instance of the <see cref="AquiredPokerPlayer"/> class.
/// Create a player with given characteristics
/// Used when adding a hand from Poker Office
/// when using this constructor positions, position names, playernames need to be set later
/// </summary>
/// <param name="playerId">
/// <see cref="PokerPlayer.Id"></see>
/// </param>
/// <param name="seatNum">
/// <see cref="PokerPlayer.SeatNumber"></see>
/// </param>
/// <param name="holecards">
/// <see cref="AquiredPokerPlayer.Holecards"></see>
/// </param>
public AquiredPokerPlayer(long playerId, int seatNum, string holecards)
: this()
{
InitializeWith(seatNum, holecards, playerId);
}
#endregion
#region Properties
/// <summary>
/// Seat relative to seat of small blind
/// </summary>
public int RelativeSeatNumber { get; set; }
/// <summary>
/// Stack of Player after the hand is played
/// Calculated by substracting betting,raising and calling amounts and adding winning amounts
/// for all rounds
/// </summary>
public double StackAfter
{
get { return StackBefore + ChipsGained(); }
}
/// <summary>
/// Stack of Player at the start of the hand
/// Determined by the Parser from the Hand History
/// </summary>
public double StackBefore { get; set; }
/// <summary>
/// Number of Rounds that player saw
/// </summary>
public int Count
{
get { return Rounds.Count; }
}
/// <summary>
/// List of all Poker Rounds for current hand Preflop Flop
/// </summary>
public IList<IAquiredPokerRound> Rounds { get; set; }
#endregion
#region Implemented Interfaces
#region IAquiredPokerPlayer
/// <summary>
/// Add a new Poker Round to the player
/// </summary>
public IAquiredPokerPlayer AddRound()
{
AddRound(new AquiredPokerRound());
return this;
}
/// <summary>
/// Add a given Poker round to the Player
/// </summary>
/// <param name="aquiredRound">Poker Round to add</param>
public IAquiredPokerPlayer AddRound(IAquiredPokerRound aquiredRound)
{
try
{
if (aquiredRound == null)
{
throw new ArgumentNullException(
"aquiredRound", "Could be caused because wrong correct Round type was passed in.");
}
if (Count < 4)
{
Rounds.Add(aquiredRound);
}
else
{
throw new ArgumentOutOfRangeException("aquiredRound",
"Tried to add BettingRound when Count is >= 4 already");
}
}
catch (Exception excep)
{
Log.Error("Unexpected", excep);
}
return this;
}
public IAquiredPokerPlayer InitializeWith(string name, double stack)
{
try
{
if (name == null)
{
throw new ArgumentNullException("Name");
}
Name = name;
StackBefore = stack;
Holecards = "?? ??";
Position = -1;
}
catch (ArgumentNullException excep)
{
Log.Error("Unhandled", excep);
}
return this;
}
public IAquiredPokerPlayer InitializeWith(int seatNum, string holecards, long playerId)
{
try
{
if (seatNum < 0 || seatNum > 10)
{
throw new ArgumentOutOfRangeException("seatNum", seatNum, "Value must be between 0 and 10");
}
if (holecards == null)
{
throw new ArgumentNullException("holecards");
}
Id = playerId;
SeatNumber = seatNum;
Holecards = holecards;
Position = -1;
// Unknown when adding from Pokeroffice
StackBefore = 0;
}
catch (Exception excep)
{
Log.Error("Unhandled", excep);
}
return this;
}
/// <summary>
/// This is called from the Parser, after all players have been added.
/// </summary>
/// <description>
/// Important: At this point PlayerCount = TotalPlayers at table allowed to play
/// Determines and sets the Position of the player in a Seat# x
/// Result:
/// SB will be 0
/// BB will be 1
/// etc.
/// Button will be TotalPlayers -1
/// Then it determines the strategic position (SB,BB,EA,MI) etc. by calling SetStrategicPosition
/// </description>
/// <param name="sbPosition">Position (Seat) of the small blind</param>
/// <param name="playerCount">Total amount of players in the hand - empty seats not counted</param>
/// <returns>true if all went well</returns>
public bool SetPosition(int sbPosition, int playerCount)
{
if (RelativeSeatNumber > playerCount)
{
LogInvalidInputError(playerCount, sbPosition);
return false;
}
if (RelativeSeatNumber >= sbPosition)
{
Position = RelativeSeatNumber - sbPosition;
}
else
{
Position = playerCount - (sbPosition - RelativeSeatNumber);
}
if (Position < 0)
{
LogInvalidInputError(playerCount, sbPosition);
return false;
}
return true;
}
void LogInvalidInputError(int playerCount, int sbPosition)
{
Log.DebugFormat(
"Pos_num {0} PlayerCount: {1} Seat: {2} SBPosition: {3}",
Position,
playerCount,
sbPosition,
RelativeSeatNumber);
}
/// <summary>
/// Gives string representation of Players info and actions
/// </summary>
/// <returns>String representation of Players info and actions</returns>
public override string ToString()
{
try
{
return string.Format(
"[{3} {0} {1}] {4} - {5} \t{2}\n",
Position,
Name,
BettingRoundsToString(),
Holecards,
StackBefore,
StackAfter);
}
catch (ArgumentNullException excep)
{
Log.Error("Returning empty string", excep);
return string.Empty;
}
}
#endregion
#endregion
#region Methods
protected double ChipsGained()
{
double gainedChips = 0;
foreach (IAquiredPokerRound iRound in this)
{
gainedChips += iRound.ChipsGained;
}
return gainedChips;
}
#endregion
/// <summary>
/// The this.
/// </summary>
/// <param name="index">
/// The index.
/// </param>
public IAquiredPokerRound this[int index]
{
get { return Rounds[index]; }
}
[NonSerialized]
long _id;
/// <summary>
/// Id of player in Database
/// </summary>
public long Id
{
get { return _id; }
set { _id = value; }
}
/// <summary>
/// The this.
/// </summary>
/// <param name="theStreet">
/// The the street.
/// </param>
public IAquiredPokerRound this[Streets theStreet]
{
get { return this[(int)theStreet]; }
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj))
{
return false;
}
if (ReferenceEquals(this, obj))
{
return true;
}
if (obj.GetType() != GetType())
{
return false;
}
return Equals((AquiredPokerPlayer)obj);
}
public bool Equals(AquiredPokerPlayer other)
{
if (ReferenceEquals(null, other))
{
return false;
}
if (ReferenceEquals(this, other))
{
return true;
}
return Equals(other._holecards, _holecards) && other.SeatNumber == SeatNumber && Equals(other.Name, Name) &&
other.Id == Id && other.Position == Position && Equals(other.Rounds, Rounds);
}
public override int GetHashCode()
{
int result = Holecards != null ? Holecards.GetHashCode() : 0;
result = (result * 397) ^ SeatNumber;
result = (result * 397) ^ (Name != null ? Name.GetHashCode() : 0);
result = (result * 397) ^ Id.GetHashCode();
result = (result * 397) ^ Position;
result = (result * 397) ^ (Rounds != null ? Rounds.GetHashCode() : 0);
return result;
}
public int CompareTo(object obj)
{
return CompareTo((IAquiredPokerPlayer)obj);
}
public int CompareTo(IAquiredPokerPlayer other)
{
if (Position < other.Position)
{
return -1;
}
if (Position > other.Position)
{
return 1;
}
return 0;
}
IEnumerator IEnumerable.GetEnumerator()
{
return Rounds.GetEnumerator();
}
string BettingRoundsToString()
{
string betting = string.Empty;
try
{
// Iterate through rounds pre-flop to river
foreach (object iB in this)
{
betting += "| " + iB;
}
}
catch (ArgumentNullException excep)
{
excep.Data.Add("betRoundCount = ", Rounds.Count);
Log.Error("Returning betting Rounds I go so far", excep);
}
return betting;
}
}
}
| |
using System;
using System.Linq;
using NUnit.Framework;
using Shouldly;
using StructureMap.Configuration.DSL;
using StructureMap.Pipeline;
using StructureMap.Testing.Widget;
using StructureMap.Testing.Widget3;
using StructureMap.TypeRules;
namespace StructureMap.Testing.Configuration.DSL
{
[TestFixture]
public class CreatePluginFamilyTester
{
#region Setup/Teardown
[SetUp]
public void SetUp()
{
}
#endregion
public interface SomethingElseEntirely : Something, SomethingElse
{
}
public interface SomethingElse
{
}
public interface Something
{
}
public class OrangeSomething : SomethingElseEntirely
{
public readonly Guid Id = Guid.NewGuid();
public override string ToString()
{
return string.Format("OrangeSomething: {0}", Id);
}
protected bool Equals(OrangeSomething other)
{
return Id.Equals(other.Id);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != this.GetType()) return false;
return Equals((OrangeSomething) obj);
}
public override int GetHashCode()
{
return Id.GetHashCode();
}
}
public class RedSomething : Something
{
}
public class GreenSomething : Something
{
}
public class ClassWithStringInConstructor
{
public ClassWithStringInConstructor(string name)
{
}
}
[Test]
public void Add_an_instance_by_lambda()
{
var container = new Container(r => { r.For<IWidget>().Add(c => new AWidget()); });
container.GetAllInstances<IWidget>()
.First()
.ShouldBeOfType<AWidget>();
}
[Test]
public void add_an_instance_by_literal_object()
{
var aWidget = new AWidget();
var container = new Container(x => { x.For<IWidget>().Use(aWidget); });
container.GetAllInstances<IWidget>().First().ShouldBeTheSameAs(aWidget);
}
[Test]
public void AddInstanceByNameOnlyAddsOneInstanceToStructureMap()
{
var container = new Container(r => { r.For<Something>().Add<RedSomething>().Named("Red"); });
container.GetAllInstances<Something>().Count().ShouldBe(1);
}
[Test]
public void AddInstanceWithNameOnlyAddsOneInstanceToStructureMap()
{
var container = new Container(x => { x.For<Something>().Add<RedSomething>().Named("Red"); });
container.GetAllInstances<Something>()
.Count().ShouldBe(1);
}
[Test]
public void as_another_lifecycle()
{
var registry = new Registry();
registry.For<IGateway>(Lifecycles.ThreadLocal).ShouldNotBeNull();
var pluginGraph = registry.Build();
var family = pluginGraph.Families[typeof (IGateway)];
family.Lifecycle.ShouldBeOfType<ThreadLocalStorageLifecycle>();
}
[Test]
public void BuildInstancesOfType()
{
var registry = new Registry();
registry.For<IGateway>();
var pluginGraph = registry.Build();
pluginGraph.Families.Has(typeof (IGateway)).ShouldBeTrue();
}
[Test]
public void BuildPluginFamilyAsPerRequest()
{
var registry = new Registry();
var pluginGraph = registry.Build();
var family = pluginGraph.Families[typeof (IGateway)];
family.Lifecycle.ShouldBeNull();
}
[Test]
public void BuildPluginFamilyAsSingleton()
{
var registry = new Registry();
registry.For<IGateway>().Singleton()
.ShouldNotBeNull();
var pluginGraph = registry.Build();
var family = pluginGraph.Families[typeof (IGateway)];
family.Lifecycle.ShouldBeOfType<SingletonLifecycle>();
}
[Test]
public void CanOverrideTheDefaultInstance1()
{
var registry = new Registry();
// Specify the default implementation for an interface
registry.For<IGateway>().Use<StubbedGateway>();
var pluginGraph = registry.Build();
pluginGraph.Families.Has(typeof (IGateway)).ShouldBeTrue();
var manager = new Container(pluginGraph);
var gateway = (IGateway) manager.GetInstance(typeof (IGateway));
gateway.ShouldBeOfType<StubbedGateway>();
}
[Test]
public void CanOverrideTheDefaultInstanceAndCreateAnAllNewPluginOnTheFly()
{
var registry = new Registry();
registry.For<IGateway>().Use<FakeGateway>();
var pluginGraph = registry.Build();
pluginGraph.Families.Has(typeof (IGateway)).ShouldBeTrue();
var container = new Container(pluginGraph);
var gateway = (IGateway) container.GetInstance(typeof (IGateway));
gateway.ShouldBeOfType<FakeGateway>();
}
[Test]
public void CreatePluginFamilyWithADefault()
{
var container = new Container(r =>
{
r.For<IWidget>().Use<ColorWidget>()
.Ctor<string>("color").Is("Red");
});
container.GetInstance<IWidget>().ShouldBeOfType<ColorWidget>().Color.ShouldBe("Red");
}
[Test]
public void weird_generics_casting()
{
typeof (SomethingElseEntirely).CanBeCastTo<SomethingElse>()
.ShouldBeTrue();
}
[Test]
public void CreatePluginFamilyWithReferenceToAnotherFamily()
{
var container = new Container(r =>
{
// Had to be a singleton for this to work
r.ForSingletonOf<SomethingElseEntirely>().Use<OrangeSomething>();
r.For<SomethingElse>().Use(context =>
// If the return is cast to OrangeSomething, this works.
context.GetInstance<SomethingElseEntirely>());
r.For<Something>().Use(context =>
// If the return is cast to OrangeSomething, this works.
context.GetInstance<SomethingElseEntirely>());
});
var orangeSomething = container.GetInstance<SomethingElseEntirely>();
orangeSomething.ShouldBeOfType<OrangeSomething>();
container.GetInstance<SomethingElse>()
.ShouldBeOfType<OrangeSomething>()
.ShouldBe(orangeSomething);
container.GetInstance<Something>()
.ShouldBeOfType<OrangeSomething>()
.ShouldBe(orangeSomething);
}
[Test]
public void PutAnInterceptorIntoTheInterceptionChainOfAPluginFamilyInTheDSL()
{
var lifecycle = new StubbedLifecycle();
var registry = new Registry();
registry.For<IGateway>().LifecycleIs(lifecycle);
var pluginGraph = registry.Build();
pluginGraph.Families[typeof (IGateway)].Lifecycle.ShouldBeTheSameAs(lifecycle);
}
[Test]
public void Set_the_default_by_a_lambda()
{
var manager =
new Container(
registry => registry.For<IWidget>().Use(() => new AWidget()));
manager.GetInstance<IWidget>().ShouldBeOfType<AWidget>();
}
[Test]
public void Set_the_default_to_a_built_object()
{
var aWidget = new AWidget();
var manager =
new Container(
registry => registry.For<IWidget>().Use(aWidget));
aWidget.ShouldBeTheSameAs(manager.GetInstance<IWidget>());
}
// Guid test based on problems encountered by Paul Segaro. See http://groups.google.com/group/structuremap-users/browse_thread/thread/34ddaf549ebb14f7?hl=en
[Test]
public void TheDefaultInstanceIsALambdaForGuidNewGuid()
{
var manager =
new Container(
registry => registry.For<Guid>().Use(() => Guid.NewGuid()));
manager.GetInstance<Guid>().ShouldBeOfType<Guid>();
}
[Test]
public void TheDefaultInstanceIsConcreteType()
{
IContainer manager = new Container(
registry => registry.For<Rule>().Use<ARule>());
manager.GetInstance<Rule>().ShouldBeOfType<ARule>();
}
}
public class StubbedLifecycle : ILifecycle
{
public void EjectAll(ILifecycleContext context)
{
throw new NotImplementedException();
}
public IObjectCache FindCache(ILifecycleContext context)
{
throw new NotImplementedException();
}
public string Description
{
get { return "Stubbed"; }
}
}
}
| |
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) Microsoft Corporation. All rights reserved.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
using System;
using System.IO;
using System.Text;
namespace FileSystemTest
{
public class OpenWrite : IMFTestInterface
{
[SetUp]
public InitializeResult Initialize()
{
// These tests rely on underlying file system so we need to make
// sure we can format it before we start the tests. If we can't
// format it, then we assume there is no FS to test on this platform.
// delete the directory DOTNETMF_FS_EMULATION
try
{
IOTests.IntializeVolume();
Directory.CreateDirectory(testDir);
Directory.SetCurrentDirectory(testDir);
}
catch (Exception ex)
{
Log.Comment("Skipping: Unable to initialize file system" + ex.Message);
return InitializeResult.Skip;
}
return InitializeResult.ReadyToGo;
}
[TearDown]
public void CleanUp()
{
}
#region Local vars
private const string file1Name = "file1.tmp";
private const string file2Name = "file2.txt";
private const string testDir = "OpenWrite";
#endregion Local vars
#region Test Cases
[TestMethod]
public MFTestResults InvalidArguments()
{
MFTestResults result = MFTestResults.Pass;
FileStream file = null;
try
{
try
{
Log.Comment("Null");
file = File.OpenWrite(null);
Log.Exception( "Expected ArgumentException, but got " + file.Name );
return MFTestResults.Fail;
}
catch (ArgumentException ae)
{
/* pass case */ Log.Comment( "Got correct exception: " + ae.Message );
result = MFTestResults.Pass;
}
try
{
Log.Comment("String.Empty");
file = File.OpenWrite(String.Empty);
Log.Exception( "Expected ArgumentException, but got " + file.Name );
return MFTestResults.Fail;
}
catch (ArgumentException ae)
{
result = MFTestResults.Pass;
/* pass case */ Log.Comment( "Got correct exception: " + ae.Message );
}
try
{
Log.Comment("White Space");
file = File.OpenWrite(" ");
Log.Exception( "Expected ArgumentException, but got " + file.Name );
return MFTestResults.Fail;
}
catch (ArgumentException ae)
{
result = MFTestResults.Pass;
/* pass case */ Log.Comment( "Got correct exception: " + ae.Message );
}
}
catch (Exception ex)
{
Log.Exception("Unexpected exception: " + ex.Message);
return MFTestResults.Fail;
}
finally
{
if (file != null)
file.Close();
}
return result;
}
[TestMethod]
public MFTestResults IOExceptionTests()
{
MFTestResults result = MFTestResults.Pass;
new FileStream(file1Name, FileMode.Create).Close();
try
{
Log.Comment("Current Directory: " + Directory.GetCurrentDirectory());
try
{
Log.Comment("ReadOnly file");
File.SetAttributes(file1Name, FileAttributes.ReadOnly);
FileStream fs = File.OpenWrite(file1Name);
Log.Exception( "Expected IOException" );
fs.Close();
return MFTestResults.Fail;
}
catch (IOException ex1)
{
Log.Comment( "Got correct exception: " + ex1.Message );
/// Validate IOException.ErrorCode.
result = MFTestResults.Pass;
}
}
catch (Exception ex)
{
Log.Exception("Unexpected exception: " + ex.Message);
return MFTestResults.Fail;
}
finally
{
// clean up
File.SetAttributes(file1Name, FileAttributes.Normal);
File.Delete(file1Name);
}
return result;
}
[TestMethod]
public MFTestResults ValidCase()
{
MFTestResults result = MFTestResults.Pass;
FileStream fs1 = null;
byte[] writebytes = Encoding.UTF8.GetBytes(file2Name);
byte[] readbytes = new byte[writebytes.Length + 10];
try
{
// Clean up
if (File.Exists(file2Name))
File.Delete(file2Name);
Log.Comment("OpenWrite file");
fs1 = File.OpenWrite(file2Name);
Log.Comment("Try to write to file");
if (!fs1.CanWrite)
{
Log.Exception( "Expected CanWrite to be true!" );
return MFTestResults.Fail;
}
fs1.Write(writebytes, 0, writebytes.Length);
Log.Comment("Try to read from file");
if (fs1.CanRead)
{
Log.Exception( "Expected CanRead to be false!" );
return MFTestResults.Fail;
}
try
{
fs1.Read(readbytes, 0, readbytes.Length);
Log.Exception( "Expected IOException" );
return MFTestResults.Fail;
}
catch (NotSupportedException nse)
{
/* pass case */
Log.Comment( "Got correct exception: " + nse.Message );
result = MFTestResults.Pass;
}
}
catch (Exception ex)
{
Log.Exception("Unexpected exception: " + ex.Message);
Log.Exception("Stack: " + ex.Message);
return MFTestResults.Fail;
}
finally
{
if (fs1 != null)
fs1.Close();
}
return result;
}
#endregion Test Cases
public MFTestMethod[] Tests
{
get
{
return new MFTestMethod[]
{
new MFTestMethod( InvalidArguments, "InvalidArguments" ),
new MFTestMethod( IOExceptionTests, "IOExceptionTests" ),
new MFTestMethod( ValidCase, "ValidCase" ),
};
}
}
}
}
| |
#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
using System;
using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.Crypto.Modes;
using Org.BouncyCastle.Crypto.Paddings;
using Org.BouncyCastle.Crypto.Parameters;
namespace Org.BouncyCastle.Crypto.Macs
{
/**
* DES based CBC Block Cipher MAC according to ISO9797, algorithm 3 (ANSI X9.19 Retail MAC)
*
* This could as well be derived from CBCBlockCipherMac, but then the property mac in the base
* class must be changed to protected
*/
public class ISO9797Alg3Mac : IMac
{
private byte[] mac;
private byte[] buf;
private int bufOff;
private IBlockCipher cipher;
private IBlockCipherPadding padding;
private int macSize;
private KeyParameter lastKey2;
private KeyParameter lastKey3;
/**
* create a Retail-MAC based on a CBC block cipher. This will produce an
* authentication code of the length of the block size of the cipher.
*
* @param cipher the cipher to be used as the basis of the MAC generation. This must
* be DESEngine.
*/
public ISO9797Alg3Mac(
IBlockCipher cipher)
: this(cipher, cipher.GetBlockSize() * 8, null)
{
}
/**
* create a Retail-MAC based on a CBC block cipher. This will produce an
* authentication code of the length of the block size of the cipher.
*
* @param cipher the cipher to be used as the basis of the MAC generation.
* @param padding the padding to be used to complete the last block.
*/
public ISO9797Alg3Mac(
IBlockCipher cipher,
IBlockCipherPadding padding)
: this(cipher, cipher.GetBlockSize() * 8, padding)
{
}
/**
* create a Retail-MAC based on a block cipher with the size of the
* MAC been given in bits. This class uses single DES CBC mode as the basis for the
* MAC generation.
* <p>
* Note: the size of the MAC must be at least 24 bits (FIPS Publication 81),
* or 16 bits if being used as a data authenticator (FIPS Publication 113),
* and in general should be less than the size of the block cipher as it reduces
* the chance of an exhaustive attack (see Handbook of Applied Cryptography).
* </p>
* @param cipher the cipher to be used as the basis of the MAC generation.
* @param macSizeInBits the size of the MAC in bits, must be a multiple of 8.
*/
public ISO9797Alg3Mac(
IBlockCipher cipher,
int macSizeInBits)
: this(cipher, macSizeInBits, null)
{
}
/**
* create a standard MAC based on a block cipher with the size of the
* MAC been given in bits. This class uses single DES CBC mode as the basis for the
* MAC generation. The final block is decrypted and then encrypted using the
* middle and right part of the key.
* <p>
* Note: the size of the MAC must be at least 24 bits (FIPS Publication 81),
* or 16 bits if being used as a data authenticator (FIPS Publication 113),
* and in general should be less than the size of the block cipher as it reduces
* the chance of an exhaustive attack (see Handbook of Applied Cryptography).
* </p>
* @param cipher the cipher to be used as the basis of the MAC generation.
* @param macSizeInBits the size of the MAC in bits, must be a multiple of 8.
* @param padding the padding to be used to complete the last block.
*/
public ISO9797Alg3Mac(
IBlockCipher cipher,
int macSizeInBits,
IBlockCipherPadding padding)
{
if ((macSizeInBits % 8) != 0)
throw new ArgumentException("MAC size must be multiple of 8");
if (!(cipher is DesEngine))
throw new ArgumentException("cipher must be instance of DesEngine");
this.cipher = new CbcBlockCipher(cipher);
this.padding = padding;
this.macSize = macSizeInBits / 8;
mac = new byte[cipher.GetBlockSize()];
buf = new byte[cipher.GetBlockSize()];
bufOff = 0;
}
public string AlgorithmName
{
get { return "ISO9797Alg3"; }
}
public void Init(
ICipherParameters parameters)
{
Reset();
if (!(parameters is KeyParameter || parameters is ParametersWithIV))
throw new ArgumentException("parameters must be an instance of KeyParameter or ParametersWithIV");
// KeyParameter must contain a double or triple length DES key,
// however the underlying cipher is a single DES. The middle and
// right key are used only in the final step.
KeyParameter kp;
if (parameters is KeyParameter)
{
kp = (KeyParameter)parameters;
}
else
{
kp = (KeyParameter)((ParametersWithIV)parameters).Parameters;
}
KeyParameter key1;
byte[] keyvalue = kp.GetKey();
if (keyvalue.Length == 16)
{ // Double length DES key
key1 = new KeyParameter(keyvalue, 0, 8);
this.lastKey2 = new KeyParameter(keyvalue, 8, 8);
this.lastKey3 = key1;
}
else if (keyvalue.Length == 24)
{ // Triple length DES key
key1 = new KeyParameter(keyvalue, 0, 8);
this.lastKey2 = new KeyParameter(keyvalue, 8, 8);
this.lastKey3 = new KeyParameter(keyvalue, 16, 8);
}
else
{
throw new ArgumentException("Key must be either 112 or 168 bit long");
}
if (parameters is ParametersWithIV)
{
cipher.Init(true, new ParametersWithIV(key1, ((ParametersWithIV)parameters).GetIV()));
}
else
{
cipher.Init(true, key1);
}
}
public int GetMacSize()
{
return macSize;
}
public void Update(
byte input)
{
if (bufOff == buf.Length)
{
cipher.ProcessBlock(buf, 0, mac, 0);
bufOff = 0;
}
buf[bufOff++] = input;
}
public void BlockUpdate(
byte[] input,
int inOff,
int len)
{
if (len < 0)
throw new ArgumentException("Can't have a negative input length!");
int blockSize = cipher.GetBlockSize();
int resultLen = 0;
int gapLen = blockSize - bufOff;
if (len > gapLen)
{
Array.Copy(input, inOff, buf, bufOff, gapLen);
resultLen += cipher.ProcessBlock(buf, 0, mac, 0);
bufOff = 0;
len -= gapLen;
inOff += gapLen;
while (len > blockSize)
{
resultLen += cipher.ProcessBlock(input, inOff, mac, 0);
len -= blockSize;
inOff += blockSize;
}
}
Array.Copy(input, inOff, buf, bufOff, len);
bufOff += len;
}
public int DoFinal(
byte[] output,
int outOff)
{
int blockSize = cipher.GetBlockSize();
if (padding == null)
{
// pad with zeroes
while (bufOff < blockSize)
{
buf[bufOff++] = 0;
}
}
else
{
if (bufOff == blockSize)
{
cipher.ProcessBlock(buf, 0, mac, 0);
bufOff = 0;
}
padding.AddPadding(buf, bufOff);
}
cipher.ProcessBlock(buf, 0, mac, 0);
// Added to code from base class
DesEngine deseng = new DesEngine();
deseng.Init(false, this.lastKey2);
deseng.ProcessBlock(mac, 0, mac, 0);
deseng.Init(true, this.lastKey3);
deseng.ProcessBlock(mac, 0, mac, 0);
// ****
Array.Copy(mac, 0, output, outOff, macSize);
Reset();
return macSize;
}
/**
* Reset the mac generator.
*/
public void Reset()
{
Array.Clear(buf, 0, buf.Length);
bufOff = 0;
// reset the underlying cipher.
cipher.Reset();
}
}
}
#endif
| |
using System;
using Orleans.Runtime;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
namespace Orleans
{
/// <summary>
/// Extension methods for grains.
/// </summary>
public static class GrainExtensions
{
private const string WRONG_GRAIN_ERROR_MSG = "Passing a half baked grain as an argument. It is possible that you instantiated a grain class explicitly, as a regular object and not via Orleans runtime or via proper test mocking";
/// <summary>
/// Returns a reference to the provided grain.
/// </summary>
/// <param name="grain">The grain to create a reference for.</param>
/// <returns>A reference to the provided grain.</returns>
internal static GrainReference AsReference(this IAddressable grain)
{
if (grain is null)
{
ThrowGrainNull();
}
// When called against an instance of a grain reference class, do nothing
var reference = grain as GrainReference;
if (reference != null) return reference;
var context = grain switch
{
Grain grainBase => grainBase.GrainContext,
IGrainBase activation => activation.GrainContext,
ISystemTargetBase systemTarget => systemTarget,
_ => throw new ArgumentException(GetWrongGrainTypeErrorMessage(grain), nameof(grain))
};
if (context?.GrainReference is not { } grainRef)
{
throw new ArgumentException(WRONG_GRAIN_ERROR_MSG, nameof(grain));
}
return grainRef;
}
/// <summary>
/// Returns a typed reference to the provided grain.
/// </summary>
/// <typeparam name="TGrainInterface">The type of the grain interface.</typeparam>
/// <param name="grain">The grain to convert.</param>
/// <remarks>
/// If the provided value is a grain instance, this will create a reference which implements the provided interface.
/// If the provided value is already grain reference, this will create a new reference which implements the provided interface.
/// </remarks>
/// <returns>A strongly typed reference to the provided grain which implements <typeparamref name="TGrainInterface"/>.</returns>
public static TGrainInterface AsReference<TGrainInterface>(this IAddressable grain)
{
if (grain is null)
{
ThrowGrainNull();
}
var grainReference = grain.AsReference();
return (TGrainInterface)grainReference.Runtime.Cast(grain, typeof(TGrainInterface));
}
/// <summary>
/// Returns a typed reference to the provided grain.
/// </summary>
/// <typeparam name="TGrainInterface">The type of the grain interface.</typeparam>
/// <param name="grain">The grain to convert.</param>
/// <remarks>
/// This method is equivalent to <see cref="AsReference{TGrainInterface}"/>.
/// If the provided value is a grain instance, this will create a reference which implements the provided interface.
/// If the provided value is already grain reference, this will create a new reference which implements the provided interface.
/// </remarks>
/// <returns>A strongly typed reference to the provided grain which implements <typeparamref name="TGrainInterface"/>.</returns>
public static TGrainInterface Cast<TGrainInterface>(this IAddressable grain) => grain.AsReference<TGrainInterface>();
/// <summary>
/// Returns a typed reference to the provided grain.
/// </summary>
/// <param name="grain">The grain to convert.</param>
/// <param name="interfaceType">The type of the grain interface.</param>
/// <remarks>
/// If the provided value is a grain instance, this will create a reference which implements the provided interface.
/// If the provided value is already grain reference, this will create a new reference which implements the provided interface.
/// </remarks>
/// <returns>A strongly typed reference to the provided grain which implements <paramref name="interfaceType"/>.</returns>
public static object AsReference(this IAddressable grain, Type interfaceType) => grain.AsReference().Runtime.Cast(grain, interfaceType);
/// <summary>
/// Returns a typed reference to the provided grain.
/// </summary>
/// <param name="grain">The grain to convert.</param>
/// <param name="interfaceType">The type of the grain interface.</param>
/// <remarks>
/// This method is equivalent to <see cref="AsReference(IAddressable, Type)"/>.
/// If the provided value is a grain instance, this will create a reference which implements the provided interface.
/// If the provided value is already grain reference, this will create a new reference which implements the provided interface.
/// </remarks>
/// <returns>A strongly typed reference to the provided grain which implements <paramref name="interfaceType"/>.</returns>
public static object Cast(this IAddressable grain, Type interfaceType) => grain.AsReference().Runtime.Cast(grain, interfaceType);
/// <summary>
/// Returns the grain id corresponding to the provided grain.
/// </summary>
/// <param name="grain">The grain</param>
/// <returns>The grain id corresponding to the provided grain.</returns>
/// <exception cref="ArgumentException">The provided value has the wrong type or has no id.</exception>
public static GrainId GetGrainId(this IAddressable grain)
{
var grainId = grain switch
{
Grain grainBase => grainBase.GrainId,
GrainReference grainReference => grainReference.GrainId,
IGrainBase grainActivation => grainActivation.GrainContext.GrainId,
ISystemTargetBase systemTarget => systemTarget.GrainId,
_ => throw new ArgumentException(GetWrongGrainTypeErrorMessage(grain), nameof(grain))
};
if (grainId.IsDefault)
{
throw new ArgumentException(WRONG_GRAIN_ERROR_MSG, nameof(grain));
}
return grainId;
}
/// <summary>
/// Gets the exception message which is thrown when a grain argument has a non-supported implementation type.
/// </summary>
/// <param name="grain">The argument.</param>
/// <returns>The exception message which is thrown when a grain argument has a non-supported implementation type.</returns>
private static string GetWrongGrainTypeErrorMessage(IAddressable grain) =>
$"{nameof(GetGrainId)} has been called on an unexpected type: {grain.GetType().FullName}."
+ $" If the parameter is a grain implementation, you can derive from {nameof(Grain)} or implement"
+ $" {nameof(IGrainBase)} in order to support this method. Alternatively, inject {nameof(IGrainContext)} and"
+ $" access the {nameof(IGrainContext.GrainId)} or {nameof(IGrainContext.GrainReference)} property.";
/// <summary>
/// Returns whether part of the primary key is of type <see langword="long"/>.
/// </summary>
/// <param name="grain">The target grain.</param>
/// <exception cref="InvalidOperationException">The provided grain does not have a <see cref="long"/>-based key.</exception>
public static bool IsPrimaryKeyBasedOnLong(this IAddressable grain)
{
var grainId = GetGrainId(grain);
if (grainId.TryGetIntegerKey(out _))
{
return true;
}
if (LegacyGrainId.TryConvertFromGrainId(grainId, out var legacyId))
{
return legacyId.IsLongKey;
}
throw new InvalidOperationException($"Unable to extract integer key from grain id {grainId}");
}
/// <summary>
/// Returns the <see langword="long"/> representation of a grain primary key.
/// </summary>
/// <param name="grain">The grain to find the primary key for.</param>
/// <param name="keyExt">The output parameter to return the extended key part of the grain primary key, if extended primary key was provided for that grain.</param>
/// <returns>A <see langword="long"/> representing the primary key for this grain.</returns>
/// <exception cref="InvalidOperationException">The provided grain does not have a <see cref="long"/>-based key.</exception>
public static long GetPrimaryKeyLong(this IAddressable grain, out string keyExt)
{
var grainId = GetGrainId(grain);
if (grainId.TryGetIntegerKey(out var primaryKey, out keyExt))
{
return primaryKey;
}
if (LegacyGrainId.TryConvertFromGrainId(grainId, out var legacyId))
{
return legacyId.GetPrimaryKeyLong(out keyExt);
}
throw new InvalidOperationException($"Unable to extract integer key from grain id {grainId}");
}
/// <summary>
/// Returns the <see langword="long"/> representation of a grain primary key.
/// </summary>
/// <param name="grain">The grain to find the primary key for.</param>
/// <returns>A <see langword="long"/> representing the primary key for this grain.</returns>
/// <exception cref="InvalidOperationException">The provided grain does not have a <see cref="long"/>-based key.</exception>
public static long GetPrimaryKeyLong(this IAddressable grain)
{
var grainId = GetGrainId(grain);
if (grainId.TryGetIntegerKey(out var primaryKey))
{
return primaryKey;
}
if (LegacyGrainId.TryConvertFromGrainId(grainId, out var legacyId))
{
return legacyId.GetPrimaryKeyLong();
}
throw new InvalidOperationException($"Unable to extract integer key from grain id {grainId}");
}
/// <summary>
/// Returns the <see cref="Guid"/> representation of a grain primary key.
/// </summary>
/// <param name="grain">The grain to find the primary key for.</param>
/// <param name="keyExt">The output parameter to return the extended key part of the grain primary key, if extended primary key was provided for that grain.</param>
/// <returns>A <see cref="Guid"/> representing the primary key for this grain.</returns>
/// <exception cref="InvalidOperationException">The provided grain does not have a <see cref="Guid"/>-based key.</exception>
public static Guid GetPrimaryKey(this IAddressable grain, out string keyExt)
{
var grainId = GetGrainId(grain);
if (grainId.TryGetGuidKey(out var guid, out keyExt))
{
return guid;
}
if (LegacyGrainId.TryConvertFromGrainId(grainId, out var legacyId))
{
return legacyId.GetPrimaryKey(out keyExt);
}
if (grainId.TryGetIntegerKey(out var integerKey, out keyExt))
{
var N1 = integerKey;
return new Guid(0, 0, 0, (byte)N1, (byte)(N1 >> 8), (byte)(N1 >> 16), (byte)(N1 >> 24), (byte)(N1 >> 32), (byte)(N1 >> 40), (byte)(N1 >> 48), (byte)(N1 >> 56));
}
throw new InvalidOperationException($"Unable to extract GUID key from grain id {grainId}");
}
/// <summary>
/// Returns the <see cref="Guid"/> representation of a grain primary key.
/// </summary>
/// <param name="grain">The grain to find the primary key for.</param>
/// <returns>A <see cref="Guid"/> representing the primary key for this grain.</returns>
/// <exception cref="InvalidOperationException">The provided grain does not have a <see cref="Guid"/>-based key.</exception>
public static Guid GetPrimaryKey(this IAddressable grain)
{
var grainId = GetGrainId(grain);
if (grainId.TryGetGuidKey(out var guid))
return guid;
if (LegacyGrainId.TryConvertFromGrainId(grainId, out var legacyId))
return legacyId.GetPrimaryKey();
if (grainId.TryGetIntegerKey(out var integerKey))
{
var N1 = integerKey;
return new Guid(0, 0, 0, (byte)N1, (byte)(N1 >> 8), (byte)(N1 >> 16), (byte)(N1 >> 24), (byte)(N1 >> 32), (byte)(N1 >> 40), (byte)(N1 >> 48), (byte)(N1 >> 56));
}
throw new InvalidOperationException($"Unable to extract GUID key from grain id {grainId}");
}
/// <summary>
/// Returns the <see langword="string"/> primary key of the grain.
/// </summary>
/// <param name="grain">The grain to find the primary key for.</param>
/// <returns>A <see langword="string"/> representing the primary key for this grain.</returns>
public static string GetPrimaryKeyString(this IAddressable grain)
{
var grainId = GetGrainId(grain);
if (LegacyGrainId.TryConvertFromGrainId(grainId, out var legacyId))
{
return legacyId.GetPrimaryKeyString();
}
return grainId.Key.ToStringUtf8();
}
/// <summary>
/// Throw an <see cref="ArgumentNullException"/> indicating that the grain argument is null.
/// </summary>
/// <exception cref="ArgumentNullException">The grain argument is null.</exception>
[DoesNotReturn]
[MethodImpl(MethodImplOptions.NoInlining)]
private static void ThrowGrainNull() => throw new ArgumentNullException("grain");
}
}
| |
//
// Copyright (c) 2012-2021 Antmicro
//
// This file is licensed under the MIT License.
// Full license text is available in the LICENSE file.
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Collections;
using Antmicro.Migrant.Hooks;
using Antmicro.Migrant.Generators;
using System.Threading;
using Antmicro.Migrant.VersionTolerance;
using Antmicro.Migrant.Utilities;
using Antmicro.Migrant.Customization;
using System.Text;
using System.Reflection;
namespace Antmicro.Migrant
{
internal class ObjectWriter
{
public ObjectWriter(Stream stream, Serializer.WriteMethods writeMethods, Action<object> preSerializationCallback = null,
Action<object> postSerializationCallback = null, SwapList surrogatesForObjects = null, SwapList objectsForSurrogates = null,
bool treatCollectionAsUserObject = false, bool useBuffering = true, bool disableStamping = false,
ReferencePreservation referencePreservation = ReferencePreservation.Preserve)
{
this.treatCollectionAsUserObject = treatCollectionAsUserObject;
this.objectsForSurrogates = objectsForSurrogates;
this.referencePreservation = referencePreservation;
this.preSerializationCallback = preSerializationCallback;
this.postSerializationCallback = postSerializationCallback;
this.writeMethods = writeMethods;
this.surrogatesForObjects = surrogatesForObjects ?? new SwapList();
parentObjects = new Dictionary<object, object>();
postSerializationHooks = new List<Action>();
types = new IdentifiedElementsDictionary<TypeDescriptor>(this);
Methods = new IdentifiedElementsDictionary<MethodDescriptor>(this);
Assemblies = new IdentifiedElementsDictionary<AssemblyDescriptor>(this);
Modules = new IdentifiedElementsDictionary<ModuleDescriptor>(this);
writer = new PrimitiveWriter(stream, useBuffering);
if(referencePreservation == ReferencePreservation.Preserve)
{
identifier = new ObjectIdentifier();
}
touchTypeMethod = disableStamping ? (Func<Type, int>)TouchAndWriteTypeIdWithSimpleStamp : TouchAndWriteTypeIdWithFullStamp;
objectsWrittenInline = new HashSet<int>();
}
public void ReuseWithNewStream(Stream stream)
{
postSerializationHooks.Clear();
types.Clear();
Methods.Clear();
Assemblies.Clear();
Modules.Clear();
writer = new PrimitiveWriter(stream, writer.IsBuffered);
identifier.Clear();
}
public void WriteObject(object o)
{
if(o == null || Helpers.IsTransient(o.GetType()))
{
throw new ArgumentException("Cannot write a null object or a transient object.");
}
if(referencePreservation != ReferencePreservation.Preserve)
{
identifier = identifierContext == null ? new ObjectIdentifier() : new ObjectIdentifier(identifierContext);
identifierContext = null;
}
try
{
var writtenBefore = identifier.Count;
writeMethods.writeReferenceMethodsProvider.GetOrCreate(typeof(object))(this, o);
if(writtenBefore != identifier.Count)
{
var refId = identifier.GetId(o);
do
{
if(!objectsWrittenInline.Contains(refId))
{
var obj = identifier.GetObject(refId);
writer.Write(refId);
InvokeCallbacksAndExecute(obj, WriteObjectInner);
}
refId++;
}
while(identifier.Count > refId);
}
}
finally
{
for(var i = identifier.Count - 1; i >= 0; i--)
{
Completed(identifier.GetObject(i));
}
foreach(var postHook in postSerializationHooks)
{
postHook();
}
PrepareForNextWrite();
}
}
public void Flush()
{
writer.Dispose();
}
// It is necessary to pass `objectType` when `o` is null.
private void CheckForNullOrTransientnessAndWriteDeferredReference (object o, Type objectFormalType = null)
{
if(objectFormalType != null && Helpers.IsTransient(objectFormalType))
{
return;
}
if(o == null || Helpers.IsTransient(o))
{
writer.Write(Consts.NullObjectId);
return;
}
CheckLegalityAndWriteDeferredReference(o);
}
internal void CheckLegalityAndWriteDeferredReference(object o)
{
CheckLegality(o, parentObjects);
WriteDeferredReference(o);
}
internal void WriteDeferredReference(object o)
{
bool isNew;
var refId = identifier.GetId(o, out isNew);
writer.Write(refId);
if(isNew)
{
var method = writeMethods.surrogateObjectIfNeededMethodsProvider.GetOrCreate(o.GetType());
if(method != null)
{
o = method(this, o, refId);
}
// we should write a type reference here!
// and some special data in case of some types, i.e. surrogates or arrays
var type = o.GetType();
TouchAndWriteTypeId(type);
writeMethods.handleNewReferenceMethodsProvider.GetOrCreate(type)(this, o, refId);
}
}
internal object SurrogateObjectIfNeeded(object o, int refId)
{
var surrogateId = surrogatesForObjects.FindMatchingIndex(o.GetType());
if(surrogateId != -1)
{
o = surrogatesForObjects.GetByIndex(surrogateId).DynamicInvoke(new[] { o });
// special case - surrogation!
// setting identifier for new object does not remove original one from the mapping
// thanks to that behaviour surrogation preserves identity
identifier.SetIdentifierForObject(o, refId);
}
return o;
}
internal void HandleNewReference(object o, int refId)
{
var objectForSurrogatesIndex = objectsForSurrogates == null ? -1 : objectsForSurrogates.FindMatchingIndex(o.GetType());
writer.Write(objectForSurrogatesIndex != -1);
if(objectForSurrogatesIndex != -1)
{
// we use counter-surrogate here just to determine the type of final object
// bare in mind that it does not have to be the same as initial type of an object
var restoredObject = objectsForSurrogates.GetByIndex(objectForSurrogatesIndex).DynamicInvoke(new[] { o });
TouchAndWriteTypeId(restoredObject.GetType());
}
if(TryWriteObjectInline(o))
{
objectsWrittenInline.Add(refId);
}
}
internal bool TryWriteObjectInline(object o)
{
var type = o.GetType();
if(type.IsArray)
{
WriteArrayMetadata((Array)o);
return false;
}
if(type == typeof(string))
{
InvokeCallbacksAndExecute(o, s => writer.Write((string)s));
return true;
}
return WriteSpecialObject(o, false);
}
internal Delegate[] GetDelegatesWithNonTransientTargets(MulticastDelegate mDelegate)
{
return mDelegate.GetInvocationList().Where(x => x.Target == null || !Helpers.IsTransient(x.Target)).ToArray();
}
internal static void CheckLegality(Type type)
{
if(IsTypeIllegal(type))
{
throw new InvalidOperationException("Pointer or ThreadLocal or SpinLock encountered during serialization. In order to obtain detailed information including classes path that lead here, please use generated version of serializer.");
}
}
internal static void CheckLegality(object obj, Dictionary<object, object> parents)
{
if(obj == null)
{
return;
}
var type = obj.GetType();
// containing type is a hint in case of
if(IsTypeIllegal(type))
{
var path = new StringBuilder();
var current = obj;
while(parents.ContainsKey(current))
{
path.Insert(0, " => ");
path.Insert(0, current.GetType().Name);
current = parents[current];
}
path.Insert(0, " => ");
path.Insert(0, current.GetType().Name);
throw new InvalidOperationException("Pointer or ThreadLocal or SpinLock encountered during serialization. The classes path that lead to it was: " + path);
}
}
private static bool IsTypeIllegal(Type type)
{
return type.IsPointer || type == typeof(IntPtr) || type == typeof(Pointer) || (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(ThreadLocal<>)) || type == typeof(SpinLock);
}
internal int TouchAndWriteTypeId(Type type)
{
return touchTypeMethod(type);
}
private int TouchAndWriteTypeIdWithSimpleStamp(Type type)
{
var typeDescriptor = (TypeSimpleDescriptor)type;
int typeId;
if(types.Dictionary.TryGetValue(typeDescriptor, out typeId))
{
writer.Write(typeId);
return typeId;
}
typeId = types.AddAndAdvanceId(typeDescriptor);
writer.Write(typeId);
typeDescriptor.Write(this);
return typeId;
}
private int TouchAndWriteTypeIdWithFullStamp(Type type)
{
var typeDescriptor = (TypeFullDescriptor)type;
// stamping `Type` is different than `Module`, `Assembly`, etc. so we need a special method for that
ArrayDescriptor arrayDescriptor = null;
if(Helpers.ContainsGenericArguments(typeDescriptor.UnderlyingType))
{
if(typeDescriptor.UnderlyingType.IsArray)
{
arrayDescriptor = new ArrayDescriptor(typeDescriptor.UnderlyingType);
typeDescriptor = (TypeFullDescriptor)arrayDescriptor.ElementType;
}
else
{
arrayDescriptor = ArrayDescriptor.EmptyRanks;
}
}
if(typeDescriptor.UnderlyingType.IsGenericType)
{
var genericTypeDefinition = typeDescriptor.UnderlyingType.GetGenericTypeDefinition();
var genericTypeDefinitionDescriptor = (TypeFullDescriptor)genericTypeDefinition;
TouchAndWriteTypeIdWithFullStampInner(genericTypeDefinitionDescriptor);
var typeOfUnderlyingType = Helpers.GetTypeOfGenericType(typeDescriptor.UnderlyingType);
if(typeOfUnderlyingType == Helpers.TypeOfGenericType.OpenGenericType)
{
writer.Write(false);
}
else if(typeOfUnderlyingType == Helpers.TypeOfGenericType.ClosedGenericType || typeOfUnderlyingType == Helpers.TypeOfGenericType.FixedNestedGenericType)
{
writer.Write(true);
foreach(var genericArgumentType in typeDescriptor.UnderlyingType.GetGenericArguments())
{
TouchAndWriteTypeIdWithFullStamp(genericArgumentType);
}
}
else
{
throw new ArgumentException(string.Format("Unexpected generic type: {0}", typeDescriptor.UnderlyingType));
}
}
else
{
TouchAndWriteTypeIdWithFullStampInner(typeDescriptor);
}
if(arrayDescriptor != null)
{
writer.WriteArray(arrayDescriptor.Ranks);
}
return 0;
}
private int TouchAndWriteTypeIdWithFullStampInner(TypeDescriptor typeDescriptor)
{
if(typeDescriptor.UnderlyingType.IsGenericParameter)
{
writer.Write(typeDescriptor.UnderlyingType.GenericParameterPosition);
writer.Write(true);
return TouchAndWriteTypeIdWithFullStamp(typeDescriptor.UnderlyingType.DeclaringType);
}
else
{
int typeId;
if(types.Dictionary.TryGetValue(typeDescriptor, out typeId))
{
writer.Write(typeId);
writer.Write(false); // generic-argument
return typeId;
}
typeId = types.AddAndAdvanceId(typeDescriptor);
writer.Write(typeId);
writer.Write(false); // generic-argument
typeDescriptor.Write(this);
return typeId;
}
}
private void PrepareForNextWrite()
{
objectsWrittenInline.Clear();
parentObjects.Clear();
if(referencePreservation == ReferencePreservation.UseWeakReference)
{
identifierContext = identifier.GetContext();
}
if(referencePreservation != ReferencePreservation.Preserve)
{
identifier = null;
}
}
private void InvokeCallbacksAndExecute(object o, Action<object> action)
{
try
{
if(preSerializationCallback != null)
{
preSerializationCallback(o);
}
action(o);
}
finally
{
if(postSerializationCallback != null)
{
postSerializationCallback(o);
}
}
}
private void WriteObjectInner(object o)
{
writeMethods.writeMethodsProvider.GetOrCreate(o.GetType())(this, o);
}
private void WriteObjectsFields(object o, Type type)
{
// fields in the alphabetical order
var fields = StampHelpers.GetFieldsInSerializationOrder(type);
foreach(var field in fields)
{
var formalType = field.FieldType;
var value = field.GetValue(o);
if(value != null)
{
parentObjects[value] = o;
}
if(Helpers.IsTypeWritableDirectly(formalType))
{
WriteValueType(formalType, value);
}
else
{
CheckForNullOrTransientnessAndWriteDeferredReference(value, formalType);
}
}
}
private bool WriteSpecialObject(object o, bool checkForCollections)
{
// if the object here is value type, it is in fact boxed
// value type - the reference layout is fine, we should
// write it using WriteField
var type = o.GetType();
if(type.IsValueType)
{
WriteField(type, o);
return true;
}
var mDelegate = o as MulticastDelegate;
if(mDelegate != null)
{
// if the target is trasient, we omit associated delegate entry
var invocationList = GetDelegatesWithNonTransientTargets(mDelegate);
writer.Write(invocationList.Length);
foreach(var del in invocationList)
{
WriteField(typeof(object), del.Target);
Methods.TouchAndWriteId(new MethodDescriptor(del.Method));
}
return true;
}
if(type.IsArray)
{
var elementType = type.GetElementType();
var array = o as Array;
WriteArray(elementType, array);
return true;
}
if(checkForCollections)
{
CollectionMetaToken collectionToken;
if (CollectionMetaToken.TryGetCollectionMetaToken(o.GetType(), out collectionToken))
{
// here we can have normal or extension method that needs to be treated differently
int count = collectionToken.CountMethod.IsStatic ?
(int)collectionToken.CountMethod.Invoke(null, new[] { o }) :
(int)collectionToken.CountMethod.Invoke(o, null);
WriteEnumerable(collectionToken.FormalElementType, count, (IEnumerable)o);
return true;
}
}
return false;
}
private void WriteEnumerable(Type elementFormalType, int count, IEnumerable collection)
{
writer.Write(count);
foreach(var element in collection)
{
WriteField(elementFormalType, element);
}
}
private void WriteArrayMetadata(Array array)
{
var rank = array.Rank;
writer.Write(rank);
for(var i = 0; i < rank; i++)
{
writer.Write(array.GetLength(i));
}
}
private void WriteArray(Type elementFormalType, Array array)
{
var position = new int[array.Rank];
WriteArrayRowRecursive(array, 0, elementFormalType, position);
}
private void WriteArrayRowRecursive(Array array, int currentDimension, Type elementFormalType, int[] position)
{
var length = array.GetLength(currentDimension);
for(var i = 0; i < length; i++)
{
if(currentDimension == array.Rank - 1)
{
// the final row
WriteField(elementFormalType, array.GetValue(position));
}
else
{
WriteArrayRowRecursive(array, currentDimension + 1, elementFormalType, position);
}
position[currentDimension]++;
for(var j = currentDimension + 1; j < array.Rank; j++)
{
position[j] = 0;
}
}
}
private void WriteField(Type formalType, object value)
{
var serializationType = Helpers.GetSerializationType(formalType);
switch(serializationType)
{
case SerializationType.Transient:
break;
case SerializationType.Value:
WriteValueType(formalType, value);
break;
case SerializationType.Reference:
CheckForNullOrTransientnessAndWriteDeferredReference(value, formalType);
break;
}
}
private void WriteValueType(Type formalType, object value)
{
CheckLegality(value, parentObjects);
// value type -> actual type is the formal type
if(formalType.IsEnum)
{
var underlyingType = Enum.GetUnderlyingType(formalType);
var convertedValue = Convert.ChangeType(value, underlyingType);
var method = writer.GetType().GetMethod("Write", new [] { underlyingType });
method.Invoke(writer, new[] { convertedValue });
return;
}
var nullableActualType = Nullable.GetUnderlyingType(formalType);
if(nullableActualType != null)
{
if(value != null)
{
writer.Write(true);
WriteValueType(nullableActualType, value);
}
else
{
writer.Write(false);
}
return;
}
if(Helpers.IsWriteableByPrimitiveWriter(formalType))
{
writer.Write((dynamic)value);
return;
}
// so we guess it is struct
WriteObjectsFields(value, formalType);
}
internal static WriteMethodDelegate LinkSpecialWrite(Type actualType)
{
if(actualType == typeof(string))
{
return (ow, obj) =>
{
ow.writer.Write((string)obj);
};
}
if(typeof(ISpeciallySerializable).IsAssignableFrom(actualType))
{
return (ow, obj) =>
{
var startingPosition = ow.writer.Position;
((ISpeciallySerializable)obj).Save(ow.writer);
ow.writer.Write(ow.writer.Position - startingPosition);
};
}
if(actualType == typeof(byte[]))
{
return (ow, objToWrite) =>
{
var array = (byte[])objToWrite;
ow.writer.Write(array);
};
}
return null;
}
/// <summary>
/// Writes the object using reflection.
///
/// REMARK: this method is not thread-safe!
/// </summary>
/// <param name="objectWriter">Object writer's object</param>
/// <param name="o">Object to serialize</param>
internal static void WriteObjectUsingReflection(ObjectWriter objectWriter, object o)
{
Helpers.InvokeAttribute(typeof(PreSerializationAttribute), o);
if(!objectWriter.WriteSpecialObject(o, !objectWriter.treatCollectionAsUserObject))
{
objectWriter.WriteObjectsFields(o, o.GetType());
}
}
private void Completed(object o)
{
var method = writeMethods.callPostSerializationHooksMethodsProvider.GetOrCreate(o.GetType());
if(method != null)
{
method(this, o);
}
}
internal void CallPostSerializationHooksUsingReflection(object o)
{
Helpers.InvokeAttribute(typeof(PostSerializationAttribute), o);
var postHook = Helpers.GetDelegateWithAttribute(typeof(LatePostSerializationAttribute), o);
if(postHook != null)
{
postSerializationHooks.Add(postHook);
}
}
internal bool TreatCollectionAsUserObject { get { return treatCollectionAsUserObject; } }
internal PrimitiveWriter PrimitiveWriter { get { return writer; } }
internal IdentifiedElementsDictionary<ModuleDescriptor> Modules { get; private set; }
internal IdentifiedElementsDictionary<AssemblyDescriptor> Assemblies { get; private set; }
internal IdentifiedElementsDictionary<MethodDescriptor> Methods { get; private set; }
internal ObjectIdentifier identifier;
internal PrimitiveWriter writer;
internal readonly Action<object> preSerializationCallback;
internal readonly Action<object> postSerializationCallback;
internal readonly List<Action> postSerializationHooks;
internal readonly SwapList surrogatesForObjects;
internal readonly SwapList objectsForSurrogates;
internal readonly HashSet<int> objectsWrittenInline;
private IdentifiedElementsDictionary<TypeDescriptor> types;
private ObjectIdentifierContext identifierContext;
private readonly Func<Type, int> touchTypeMethod;
private readonly bool treatCollectionAsUserObject;
private readonly ReferencePreservation referencePreservation;
private readonly Dictionary<object, object> parentObjects;
private readonly Serializer.WriteMethods writeMethods;
}
internal delegate void WriteMethodDelegate(ObjectWriter writer, object obj);
internal delegate object SurrogateObjectIfNeededDelegate(ObjectWriter writer, object obj, int referenceId);
internal delegate void HandleNewReferenceMethodDelegate(ObjectWriter writer, object obj, int referenceId);
internal delegate void WriteReferenceMethodDelegate(ObjectWriter writer, object obj);
internal delegate void CallPostSerializationHooksMethodDelegate(ObjectWriter writer, object o);
}
| |
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using SubSonic;
using SubSonic.Utilities;
namespace DalSic
{
/// <summary>
/// Controller class for PN_legajos
/// </summary>
[System.ComponentModel.DataObject]
public partial class PnLegajoController
{
// Preload our schema..
PnLegajo thisSchemaLoad = new PnLegajo();
private string userName = String.Empty;
protected string UserName
{
get
{
if (userName.Length == 0)
{
if (System.Web.HttpContext.Current != null)
{
userName=System.Web.HttpContext.Current.User.Identity.Name;
}
else
{
userName=System.Threading.Thread.CurrentPrincipal.Identity.Name;
}
}
return userName;
}
}
[DataObjectMethod(DataObjectMethodType.Select, true)]
public PnLegajoCollection FetchAll()
{
PnLegajoCollection coll = new PnLegajoCollection();
Query qry = new Query(PnLegajo.Schema);
coll.LoadAndCloseReader(qry.ExecuteReader());
return coll;
}
[DataObjectMethod(DataObjectMethodType.Select, false)]
public PnLegajoCollection FetchByID(object IdLegajo)
{
PnLegajoCollection coll = new PnLegajoCollection().Where("id_legajo", IdLegajo).Load();
return coll;
}
[DataObjectMethod(DataObjectMethodType.Select, false)]
public PnLegajoCollection FetchByQuery(Query qry)
{
PnLegajoCollection coll = new PnLegajoCollection();
coll.LoadAndCloseReader(qry.ExecuteReader());
return coll;
}
[DataObjectMethod(DataObjectMethodType.Delete, true)]
public bool Delete(object IdLegajo)
{
return (PnLegajo.Delete(IdLegajo) == 1);
}
[DataObjectMethod(DataObjectMethodType.Delete, false)]
public bool Destroy(object IdLegajo)
{
return (PnLegajo.Destroy(IdLegajo) == 1);
}
/// <summary>
/// Inserts a record, can be used with the Object Data Source
/// </summary>
[DataObjectMethod(DataObjectMethodType.Insert, true)]
public void Insert(string Apellido,string Nombre,string Dni,DateTime? FechaNacimiento,string LugarNacimiento,string Domicilio,string TelCelular,string TelParticular,string Localidad,string Provincia,string EmNombre,string EmTelefono,string EmDireccion,string EmRelacion,string Comentarios,int? IdUsuario,int? IdEvaluador,DateTime? FechaIngreso,string Cuil,string CajaAhorroPesosNro,int? IdTarea,int? IdCalificacion,int? IdAfjp,int? Idbanco,short? TipoLiq,short? TipoJub,DateTime? FechaBaja,short? Activo,string HrEntra,string HrSale,short? Ubicacion)
{
PnLegajo item = new PnLegajo();
item.Apellido = Apellido;
item.Nombre = Nombre;
item.Dni = Dni;
item.FechaNacimiento = FechaNacimiento;
item.LugarNacimiento = LugarNacimiento;
item.Domicilio = Domicilio;
item.TelCelular = TelCelular;
item.TelParticular = TelParticular;
item.Localidad = Localidad;
item.Provincia = Provincia;
item.EmNombre = EmNombre;
item.EmTelefono = EmTelefono;
item.EmDireccion = EmDireccion;
item.EmRelacion = EmRelacion;
item.Comentarios = Comentarios;
item.IdUsuario = IdUsuario;
item.IdEvaluador = IdEvaluador;
item.FechaIngreso = FechaIngreso;
item.Cuil = Cuil;
item.CajaAhorroPesosNro = CajaAhorroPesosNro;
item.IdTarea = IdTarea;
item.IdCalificacion = IdCalificacion;
item.IdAfjp = IdAfjp;
item.Idbanco = Idbanco;
item.TipoLiq = TipoLiq;
item.TipoJub = TipoJub;
item.FechaBaja = FechaBaja;
item.Activo = Activo;
item.HrEntra = HrEntra;
item.HrSale = HrSale;
item.Ubicacion = Ubicacion;
item.Save(UserName);
}
/// <summary>
/// Updates a record, can be used with the Object Data Source
/// </summary>
[DataObjectMethod(DataObjectMethodType.Update, true)]
public void Update(int IdLegajo,string Apellido,string Nombre,string Dni,DateTime? FechaNacimiento,string LugarNacimiento,string Domicilio,string TelCelular,string TelParticular,string Localidad,string Provincia,string EmNombre,string EmTelefono,string EmDireccion,string EmRelacion,string Comentarios,int? IdUsuario,int? IdEvaluador,DateTime? FechaIngreso,string Cuil,string CajaAhorroPesosNro,int? IdTarea,int? IdCalificacion,int? IdAfjp,int? Idbanco,short? TipoLiq,short? TipoJub,DateTime? FechaBaja,short? Activo,string HrEntra,string HrSale,short? Ubicacion)
{
PnLegajo item = new PnLegajo();
item.MarkOld();
item.IsLoaded = true;
item.IdLegajo = IdLegajo;
item.Apellido = Apellido;
item.Nombre = Nombre;
item.Dni = Dni;
item.FechaNacimiento = FechaNacimiento;
item.LugarNacimiento = LugarNacimiento;
item.Domicilio = Domicilio;
item.TelCelular = TelCelular;
item.TelParticular = TelParticular;
item.Localidad = Localidad;
item.Provincia = Provincia;
item.EmNombre = EmNombre;
item.EmTelefono = EmTelefono;
item.EmDireccion = EmDireccion;
item.EmRelacion = EmRelacion;
item.Comentarios = Comentarios;
item.IdUsuario = IdUsuario;
item.IdEvaluador = IdEvaluador;
item.FechaIngreso = FechaIngreso;
item.Cuil = Cuil;
item.CajaAhorroPesosNro = CajaAhorroPesosNro;
item.IdTarea = IdTarea;
item.IdCalificacion = IdCalificacion;
item.IdAfjp = IdAfjp;
item.Idbanco = Idbanco;
item.TipoLiq = TipoLiq;
item.TipoJub = TipoJub;
item.FechaBaja = FechaBaja;
item.Activo = Activo;
item.HrEntra = HrEntra;
item.HrSale = HrSale;
item.Ubicacion = Ubicacion;
item.Save(UserName);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
namespace Microsoft.Msagl.Drawing {
#pragma warning disable 0660, 0661
/// <summary>
/// Color structure
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes"), Serializable]
public struct Color {
byte a;
/// <summary>
/// constructor with alpha and red, green, bluee components
/// </summary>
/// <param name="a"></param>
/// <param name="r"></param>
/// <param name="g"></param>
/// <param name="b"></param>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "r"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "g"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "b"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "a")]
public Color(byte a, byte r, byte g, byte b) {
this.a = a;
this.r = r;
this.g = g;
this.b = b;
}
/// <summary>
/// opaque color
/// </summary>
/// <param name="r"></param>
/// <param name="g"></param>
/// <param name="b"></param>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "r"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "g"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "b")]
public Color(byte r, byte g, byte b) {
this.a = 255;
this.r = r;
this.g = g;
this.b = b;
}
/// <summary>
/// alpha - transparency
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "A")]
public byte A {
get { return a; }
set { a = value; }
}
byte r;
/// <summary>
/// red
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "R")]
public byte R {
get { return r; }
set { r = value; }
}
byte g;
/// <summary>
/// green
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "G")]
public byte G {
get { return g; }
set { g = value; }
}
byte b;
/// <summary>
/// blue
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "B")]
public byte B {
get { return b; }
set { b = value; }
}
///<summary>
///</summary>
///<param name="i"></param>
///<returns></returns>
public static string Xex(int i) {
string s = Convert.ToString(i, 16);
if (s.Length == 1)
return "0" + s;
return s.Substring(s.Length - 2, 2);
}
/// <summary>
/// ==
/// </summary>
/// <param name="a"></param>
/// <param name="b"></param>
/// <returns></returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "b"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "a")]
public static bool operator ==(Color a, Color b) {
return a.a == b.a && a.r == b.r && a.b == b.b && a.g == b.g;
}
/// <summary>
/// !=
/// </summary>
/// <param name="a"></param>
/// <param name="b"></param>
/// <returns></returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "b"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "a")]
public static bool operator !=(Color a, Color b) {
return a.a != b.a || a.r != b.r || a.b != b.b || a.g != b.g;
}
/// <summary>
/// ToString
/// </summary>
/// <returns></returns>
public override string ToString() {
return "\"#" + Xex(A) + Xex(R) + Xex(G) + Xex(B) + "\"";
}
/// <summary>
///
/// </summary>
static public Color AliceBlue { get { return new Color(255, 240, 248, 255); } }
/// <summary>
///
/// </summary>
static public Color AntiqueWhite { get { return new Color(255, 250, 235, 215); } }
/// <summary>
///
/// </summary>
static public Color Aqua { get { return new Color(255, 0, 255, 255); } }
/// <summary>
///
/// </summary>
static public Color Aquamarine { get { return new Color(255, 127, 255, 212); } }
/// <summary>
///
/// </summary>
static public Color Azure { get { return new Color(255, 240, 255, 255); } }
/// <summary>
///
/// </summary>
static public Color Beige { get { return new Color(255, 245, 245, 220); } }
/// <summary>
///
/// </summary>
static public Color Bisque { get { return new Color(255, 255, 228, 196); } }
/// <summary>
///
/// </summary>
static public Color Black { get { return new Color(255, 0, 0, 0); } }
/// <summary>
///
/// </summary>
static public Color BlanchedAlmond { get { return new Color(255, 255, 235, 205); } }
/// <summary>
///
/// </summary>
static public Color Blue { get { return new Color(255, 0, 0, 255); } }
/// <summary>
///
/// </summary>
static public Color BlueViolet { get { return new Color(255, 138, 43, 226); } }
/// <summary>
///
/// </summary>
static public Color Brown { get { return new Color(255, 165, 42, 42); } }
/// <summary>
///
/// </summary>
static public Color BurlyWood { get { return new Color(255, 222, 184, 135); } }
/// <summary>
///
/// </summary>
static public Color CadetBlue { get { return new Color(255, 95, 158, 160); } }
/// <summary>
///
/// </summary>
static public Color Chartreuse { get { return new Color(255, 127, 255, 0); } }
/// <summary>
///
/// </summary>
static public Color Chocolate { get { return new Color(255, 210, 105, 30); } }
/// <summary>
///
/// </summary>
static public Color Coral { get { return new Color(255, 255, 127, 80); } }
/// <summary>
///
/// </summary>
static public Color CornflowerBlue { get { return new Color(255, 100, 149, 237); } }
/// <summary>
///
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Cornsilk")]
static public Color Cornsilk { get { return new Color(255, 255, 248, 220); } }
/// <summary>
///
/// </summary>
static public Color Crimson { get { return new Color(255, 220, 20, 60); } }
/// <summary>
///
/// </summary>
static public Color Cyan { get { return new Color(255, 0, 255, 255); } }
/// <summary>
///
/// </summary>
static public Color DarkBlue { get { return new Color(255, 0, 0, 139); } }
/// <summary>
///
/// </summary>
static public Color DarkCyan { get { return new Color(255, 0, 139, 139); } }
/// <summary>
///
/// </summary>
static public Color DarkGoldenrod { get { return new Color(255, 184, 134, 11); } }
/// <summary>
///
/// </summary>
static public Color DarkGray { get { return new Color(255, 169, 169, 169); } }
/// <summary>
///
/// </summary>
static public Color DarkGreen { get { return new Color(255, 0, 100, 0); } }
/// <summary>
///
/// </summary>
static public Color DarkKhaki { get { return new Color(255, 189, 183, 107); } }
/// <summary>
///
/// </summary>
static public Color DarkMagenta { get { return new Color(255, 139, 0, 139); } }
/// <summary>
///
/// </summary>
static public Color DarkOliveGreen { get { return new Color(255, 85, 107, 47); } }
/// <summary>
///
/// </summary>
static public Color DarkOrange { get { return new Color(255, 255, 140, 0); } }
/// <summary>
///
/// </summary>
static public Color DarkOrchid { get { return new Color(255, 153, 50, 204); } }
/// <summary>
///
/// </summary>
static public Color DarkRed { get { return new Color(255, 139, 0, 0); } }
/// <summary>
///
/// </summary>
static public Color DarkSalmon { get { return new Color(255, 233, 150, 122); } }
/// <summary>
///
/// </summary>
static public Color DarkSeaGreen { get { return new Color(255, 143, 188, 139); } }
/// <summary>
///
/// </summary>
static public Color DarkSlateBlue { get { return new Color(255, 72, 61, 139); } }
/// <summary>
///
/// </summary>
static public Color DarkSlateGray { get { return new Color(255, 47, 79, 79); } }
/// <summary>
///
/// </summary>
static public Color DarkTurquoise { get { return new Color(255, 0, 206, 209); } }
/// <summary>
///
/// </summary>
static public Color DarkViolet { get { return new Color(255, 148, 0, 211); } }
/// <summary>
///
/// </summary>
static public Color DeepPink { get { return new Color(255, 255, 20, 147); } }
/// <summary>
///
/// </summary>
static public Color DeepSkyBlue { get { return new Color(255, 0, 191, 255); } }
/// <summary>
///
/// </summary>
static public Color DimGray { get { return new Color(255, 105, 105, 105); } }
/// <summary>
///
/// </summary>
static public Color DodgerBlue { get { return new Color(255, 30, 144, 255); } }
/// <summary>
///
/// </summary>
static public Color Firebrick { get { return new Color(255, 178, 34, 34); } }
/// <summary>
///
/// </summary>
static public Color FloralWhite { get { return new Color(255, 255, 250, 240); } }
/// <summary>
///
/// </summary>
static public Color ForestGreen { get { return new Color(255, 34, 139, 34); } }
/// <summary>
///
/// </summary>
static public Color Fuchsia { get { return new Color(255, 255, 0, 255); } }
/// <summary>
///
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Gainsboro")]
static public Color Gainsboro { get { return new Color(255, 220, 220, 220); } }
/// <summary>
///
/// </summary>
static public Color GhostWhite { get { return new Color(255, 248, 248, 255); } }
/// <summary>
///
/// </summary>
static public Color Gold { get { return new Color(255, 255, 215, 0); } }
/// <summary>
///
/// </summary>
static public Color Goldenrod { get { return new Color(255, 218, 165, 32); } }
/// <summary>
///
/// </summary>
static public Color Gray { get { return new Color(255, 128, 128, 128); } }
/// <summary>
///
/// </summary>
static public Color Green { get { return new Color(255, 0, 128, 0); } }
/// <summary>
///
/// </summary>
static public Color GreenYellow { get { return new Color(255, 173, 255, 47); } }
/// <summary>
///
/// </summary>
static public Color Honeydew { get { return new Color(255, 240, 255, 240); } }
/// <summary>
///
/// </summary>
static public Color HotPink { get { return new Color(255, 255, 105, 180); } }
/// <summary>
///
/// </summary>
static public Color IndianRed { get { return new Color(255, 205, 92, 92); } }
/// <summary>
///
/// </summary>
static public Color Indigo { get { return new Color(255, 75, 0, 130); } }
/// <summary>
///
/// </summary>
static public Color Ivory { get { return new Color(255, 255, 255, 240); } }
/// <summary>
///
/// </summary>
static public Color Khaki { get { return new Color(255, 240, 230, 140); } }
/// <summary>
///
/// </summary>
static public Color Lavender { get { return new Color(255, 230, 230, 250); } }
/// <summary>
///
/// </summary>
static public Color LavenderBlush { get { return new Color(255, 255, 240, 245); } }
/// <summary>
///
/// </summary>
static public Color LawnGreen { get { return new Color(255, 124, 252, 0); } }
/// <summary>
///
/// </summary>
static public Color LemonChiffon { get { return new Color(255, 255, 250, 205); } }
/// <summary>
///
/// </summary>
static public Color LightBlue { get { return new Color(255, 173, 216, 230); } }
/// <summary>
///
/// </summary>
static public Color LightCoral { get { return new Color(255, 240, 128, 128); } }
/// <summary>
///
/// </summary>
static public Color LightCyan { get { return new Color(255, 224, 255, 255); } }
/// <summary>
///
/// </summary>
static public Color LightGoldenrodYellow { get { return new Color(255, 250, 250, 210); } }
/// <summary>
///
/// </summary>
static public Color LightGray { get { return new Color(255, 211, 211, 211); } }
/// <summary>
///
/// </summary>
static public Color LightGreen { get { return new Color(255, 144, 238, 144); } }
/// <summary>
///
/// </summary>
static public Color LightPink { get { return new Color(255, 255, 182, 193); } }
/// <summary>
///
/// </summary>
static public Color LightSalmon { get { return new Color(255, 255, 160, 122); } }
/// <summary>
///
/// </summary>
static public Color LightSeaGreen { get { return new Color(255, 32, 178, 170); } }
/// <summary>
///
/// </summary>
static public Color LightSkyBlue { get { return new Color(255, 135, 206, 250); } }
/// <summary>
///
/// </summary>
static public Color LightSlateGray { get { return new Color(255, 119, 136, 153); } }
/// <summary>
///
/// </summary>
static public Color LightSteelBlue { get { return new Color(255, 176, 196, 222); } }
/// <summary>
///
/// </summary>
static public Color LightYellow { get { return new Color(255, 255, 255, 224); } }
/// <summary>
///
/// </summary>
static public Color Lime { get { return new Color(255, 0, 255, 0); } }
/// <summary>
///
/// </summary>
static public Color LimeGreen { get { return new Color(255, 50, 205, 50); } }
/// <summary>
///
/// </summary>
static public Color Linen { get { return new Color(255, 250, 240, 230); } }
/// <summary>
///
/// </summary>
static public Color Magenta { get { return new Color(255, 255, 0, 255); } }
/// <summary>
///
/// </summary>
static public Color Maroon { get { return new Color(255, 128, 0, 0); } }
/// <summary>
///
/// </summary>
static public Color MediumAquamarine { get { return new Color(255, 102, 205, 170); } }
/// <summary>
///
/// </summary>
static public Color MediumBlue { get { return new Color(255, 0, 0, 205); } }
/// <summary>
///
/// </summary>
static public Color MediumOrchid { get { return new Color(255, 186, 85, 211); } }
/// <summary>
///
/// </summary>
static public Color MediumPurple { get { return new Color(255, 147, 112, 219); } }
/// <summary>
///
/// </summary>
static public Color MediumSeaGreen { get { return new Color(255, 60, 179, 113); } }
/// <summary>
///
/// </summary>
static public Color MediumSlateBlue { get { return new Color(255, 123, 104, 238); } }
/// <summary>
///
/// </summary>
static public Color MediumSpringGreen { get { return new Color(255, 0, 250, 154); } }
/// <summary>
///
/// </summary>
static public Color MediumTurquoise { get { return new Color(255, 72, 209, 204); } }
/// <summary>
///
/// </summary>
static public Color MediumVioletRed { get { return new Color(255, 199, 21, 133); } }
/// <summary>
///
/// </summary>
static public Color MidnightBlue { get { return new Color(255, 25, 25, 112); } }
/// <summary>
///
/// </summary>
static public Color MintCream { get { return new Color(255, 245, 255, 250); } }
/// <summary>
///
/// </summary>
static public Color MistyRose { get { return new Color(255, 255, 228, 225); } }
/// <summary>
///
/// </summary>
static public Color Moccasin { get { return new Color(255, 255, 228, 181); } }
/// <summary>
///
/// </summary>
static public Color NavajoWhite { get { return new Color(255, 255, 222, 173); } }
/// <summary>
///
/// </summary>
static public Color Navy { get { return new Color(255, 0, 0, 128); } }
/// <summary>
///
/// </summary>
static public Color OldLace { get { return new Color(255, 253, 245, 230); } }
/// <summary>
///
/// </summary>
static public Color Olive { get { return new Color(255, 128, 128, 0); } }
/// <summary>
///
/// </summary>
static public Color OliveDrab { get { return new Color(255, 107, 142, 35); } }
/// <summary>
///
/// </summary>
static public Color Orange { get { return new Color(255, 255, 165, 0); } }
/// <summary>
///
/// </summary>
static public Color OrangeRed { get { return new Color(255, 255, 69, 0); } }
/// <summary>
///
/// </summary>
static public Color Orchid { get { return new Color(255, 218, 112, 214); } }
/// <summary>
///
/// </summary>
static public Color PaleGoldenrod { get { return new Color(255, 238, 232, 170); } }
/// <summary>
///
/// </summary>
static public Color PaleGreen { get { return new Color(255, 152, 251, 152); } }
/// <summary>
///
/// </summary>
static public Color PaleTurquoise { get { return new Color(255, 175, 238, 238); } }
/// <summary>
///
/// </summary>
static public Color PaleVioletRed { get { return new Color(255, 219, 112, 147); } }
/// <summary>
///
/// </summary>
static public Color PapayaWhip { get { return new Color(255, 255, 239, 213); } }
/// <summary>
///
/// </summary>
static public Color PeachPuff { get { return new Color(255, 255, 218, 185); } }
/// <summary>
///
/// </summary>
static public Color Peru { get { return new Color(255, 205, 133, 63); } }
/// <summary>
///
/// </summary>
static public Color Pink { get { return new Color(255, 255, 192, 203); } }
/// <summary>
///
/// </summary>
static public Color Plum { get { return new Color(255, 221, 160, 221); } }
/// <summary>
///
/// </summary>
static public Color PowderBlue { get { return new Color(255, 176, 224, 230); } }
/// <summary>
///
/// </summary>
static public Color Purple { get { return new Color(255, 128, 0, 128); } }
/// <summary>
///
/// </summary>
static public Color Red { get { return new Color(255, 255, 0, 0); } }
/// <summary>
///
/// </summary>
static public Color RosyBrown { get { return new Color(255, 188, 143, 143); } }
/// <summary>
///
/// </summary>
static public Color RoyalBlue { get { return new Color(255, 65, 105, 225); } }
/// <summary>
///
/// </summary>
static public Color SaddleBrown { get { return new Color(255, 139, 69, 19); } }
/// <summary>
///
/// </summary>
static public Color Salmon { get { return new Color(255, 250, 128, 114); } }
/// <summary>
///
/// </summary>
static public Color SandyBrown { get { return new Color(255, 244, 164, 96); } }
/// <summary>
///
/// </summary>
static public Color SeaGreen { get { return new Color(255, 46, 139, 87); } }
/// <summary>
///
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "SeaShell")]
static public Color SeaShell { get { return new Color(255, 255, 245, 238); } }
/// <summary>
///
/// </summary>
static public Color Sienna { get { return new Color(255, 160, 82, 45); } }
/// <summary>
///
/// </summary>
static public Color Silver { get { return new Color(255, 192, 192, 192); } }
/// <summary>
///
/// </summary>
static public Color SkyBlue { get { return new Color(255, 135, 206, 235); } }
/// <summary>
///
/// </summary>
static public Color SlateBlue { get { return new Color(255, 106, 90, 205); } }
/// <summary>
///
/// </summary>
static public Color SlateGray { get { return new Color(255, 112, 128, 144); } }
/// <summary>
///
/// </summary>
static public Color Snow { get { return new Color(255, 255, 250, 250); } }
/// <summary>
///
/// </summary>
static public Color SpringGreen { get { return new Color(255, 0, 255, 127); } }
/// <summary>
///
/// </summary>
static public Color SteelBlue { get { return new Color(255, 70, 130, 180); } }
/// <summary>
///
/// </summary>
static public Color Tan { get { return new Color(255, 210, 180, 140); } }
/// <summary>
///
/// </summary>
static public Color Teal { get { return new Color(255, 0, 128, 128); } }
/// <summary>
///
/// </summary>
static public Color Thistle { get { return new Color(255, 216, 191, 216); } }
/// <summary>
///
/// </summary>
static public Color Tomato { get { return new Color(255, 255, 99, 71); } }
/// <summary>
///
/// </summary>
static public Color Transparent { get { return new Color(0, 255, 255, 255); } }
/// <summary>
///
/// </summary>
static public Color Turquoise { get { return new Color(255, 64, 224, 208); } }
/// <summary>
///
/// </summary>
static public Color Violet { get { return new Color(255, 238, 130, 238); } }
/// <summary>
///
/// </summary>
static public Color Wheat { get { return new Color(255, 245, 222, 179); } }
/// <summary>
///
/// </summary>
static public Color White { get { return new Color(255, 255, 255, 255); } }
/// <summary>
///
/// </summary>
static public Color WhiteSmoke { get { return new Color(255, 245, 245, 245); } }
/// <summary>
///
/// </summary>
static public Color Yellow { get { return new Color(255, 255, 255, 0); } }
/// <summary>
///
/// </summary>
static public Color YellowGreen { get { return new Color(255, 154, 205, 50); } }
}
}
| |
namespace iControl {
using System.Xml.Serialization;
using System.Web.Services;
using System.ComponentModel;
using System.Web.Services.Protocols;
using System;
using System.Diagnostics;
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Web.Services.WebServiceBindingAttribute(Name="Networking.TunnelBinding", Namespace="urn:iControl")]
[System.Xml.Serialization.SoapIncludeAttribute(typeof(NetworkingTunnelL2TunnelFDBEntry))]
[System.Xml.Serialization.SoapIncludeAttribute(typeof(NetworkingTunnelL2TunnelFDBEntryV2))]
[System.Xml.Serialization.SoapIncludeAttribute(typeof(NetworkingTunnelTunnelProfileAttribute))]
public partial class NetworkingTunnel : iControlInterface {
public NetworkingTunnel() {
this.Url = "https://url_to_service";
}
//=======================================================================
// Operations
//=======================================================================
//-----------------------------------------------------------------------
// add_static_forwarding
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/Tunnel",
RequestNamespace="urn:iControl:Networking/Tunnel", ResponseNamespace="urn:iControl:Networking/Tunnel")]
public void add_static_forwarding(
string [] tunnels,
NetworkingTunnelL2TunnelFDBEntry [] [] entries
) {
this.Invoke("add_static_forwarding", new object [] {
tunnels,
entries});
}
public System.IAsyncResult Beginadd_static_forwarding(string [] tunnels,NetworkingTunnelL2TunnelFDBEntry [] [] entries, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("add_static_forwarding", new object[] {
tunnels,
entries}, callback, asyncState);
}
public void Endadd_static_forwarding(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// add_static_forwarding_v2
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/Tunnel",
RequestNamespace="urn:iControl:Networking/Tunnel", ResponseNamespace="urn:iControl:Networking/Tunnel")]
public void add_static_forwarding_v2(
string [] tunnels,
NetworkingTunnelL2TunnelFDBEntryV2 [] [] entries
) {
this.Invoke("add_static_forwarding_v2", new object [] {
tunnels,
entries});
}
public System.IAsyncResult Beginadd_static_forwarding_v2(string [] tunnels,NetworkingTunnelL2TunnelFDBEntryV2 [] [] entries, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("add_static_forwarding_v2", new object[] {
tunnels,
entries}, callback, asyncState);
}
public void Endadd_static_forwarding_v2(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// create
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/Tunnel",
RequestNamespace="urn:iControl:Networking/Tunnel", ResponseNamespace="urn:iControl:Networking/Tunnel")]
public void create(
string [] tunnels,
string [] local_addresses,
string [] remote_addresses,
string [] profiles
) {
this.Invoke("create", new object [] {
tunnels,
local_addresses,
remote_addresses,
profiles});
}
public System.IAsyncResult Begincreate(string [] tunnels,string [] local_addresses,string [] remote_addresses,string [] profiles, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("create", new object[] {
tunnels,
local_addresses,
remote_addresses,
profiles}, callback, asyncState);
}
public void Endcreate(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// create_with_key
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/Tunnel",
RequestNamespace="urn:iControl:Networking/Tunnel", ResponseNamespace="urn:iControl:Networking/Tunnel")]
public void create_with_key(
string [] tunnels,
string [] local_addresses,
string [] remote_addresses,
string [] profiles,
long [] keys
) {
this.Invoke("create_with_key", new object [] {
tunnels,
local_addresses,
remote_addresses,
profiles,
keys});
}
public System.IAsyncResult Begincreate_with_key(string [] tunnels,string [] local_addresses,string [] remote_addresses,string [] profiles,long [] keys, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("create_with_key", new object[] {
tunnels,
local_addresses,
remote_addresses,
profiles,
keys}, callback, asyncState);
}
public void Endcreate_with_key(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// create_with_transparent_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/Tunnel",
RequestNamespace="urn:iControl:Networking/Tunnel", ResponseNamespace="urn:iControl:Networking/Tunnel")]
public void create_with_transparent_state(
string [] tunnels,
string [] local_addresses,
string [] remote_addresses,
string [] profiles,
CommonEnabledState [] states
) {
this.Invoke("create_with_transparent_state", new object [] {
tunnels,
local_addresses,
remote_addresses,
profiles,
states});
}
public System.IAsyncResult Begincreate_with_transparent_state(string [] tunnels,string [] local_addresses,string [] remote_addresses,string [] profiles,CommonEnabledState [] states, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("create_with_transparent_state", new object[] {
tunnels,
local_addresses,
remote_addresses,
profiles,
states}, callback, asyncState);
}
public void Endcreate_with_transparent_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// delete_all_tunnels
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/Tunnel",
RequestNamespace="urn:iControl:Networking/Tunnel", ResponseNamespace="urn:iControl:Networking/Tunnel")]
public void delete_all_tunnels(
) {
this.Invoke("delete_all_tunnels", new object [0]);
}
public System.IAsyncResult Begindelete_all_tunnels(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("delete_all_tunnels", new object[0], callback, asyncState);
}
public void Enddelete_all_tunnels(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// delete_tunnel
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/Tunnel",
RequestNamespace="urn:iControl:Networking/Tunnel", ResponseNamespace="urn:iControl:Networking/Tunnel")]
public void delete_tunnel(
string [] tunnels
) {
this.Invoke("delete_tunnel", new object [] {
tunnels});
}
public System.IAsyncResult Begindelete_tunnel(string [] tunnels, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("delete_tunnel", new object[] {
tunnels}, callback, asyncState);
}
public void Enddelete_tunnel(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// get_auto_lasthop
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/Tunnel",
RequestNamespace="urn:iControl:Networking/Tunnel", ResponseNamespace="urn:iControl:Networking/Tunnel")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public CommonAutoLasthop [] get_auto_lasthop(
string [] tunnels
) {
object [] results = this.Invoke("get_auto_lasthop", new object [] {
tunnels});
return ((CommonAutoLasthop [])(results[0]));
}
public System.IAsyncResult Beginget_auto_lasthop(string [] tunnels, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_auto_lasthop", new object[] {
tunnels}, callback, asyncState);
}
public CommonAutoLasthop [] Endget_auto_lasthop(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((CommonAutoLasthop [])(results[0]));
}
//-----------------------------------------------------------------------
// get_description
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/Tunnel",
RequestNamespace="urn:iControl:Networking/Tunnel", ResponseNamespace="urn:iControl:Networking/Tunnel")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_description(
string [] tunnels
) {
object [] results = this.Invoke("get_description", new object [] {
tunnels});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_description(string [] tunnels, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_description", new object[] {
tunnels}, callback, asyncState);
}
public string [] Endget_description(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_direction
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/Tunnel",
RequestNamespace="urn:iControl:Networking/Tunnel", ResponseNamespace="urn:iControl:Networking/Tunnel")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public NetworkingTunnelTunnelDirection [] get_direction(
string [] tunnels
) {
object [] results = this.Invoke("get_direction", new object [] {
tunnels});
return ((NetworkingTunnelTunnelDirection [])(results[0]));
}
public System.IAsyncResult Beginget_direction(string [] tunnels, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_direction", new object[] {
tunnels}, callback, asyncState);
}
public NetworkingTunnelTunnelDirection [] Endget_direction(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((NetworkingTunnelTunnelDirection [])(results[0]));
}
//-----------------------------------------------------------------------
// get_idle_timeout
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/Tunnel",
RequestNamespace="urn:iControl:Networking/Tunnel", ResponseNamespace="urn:iControl:Networking/Tunnel")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public long [] get_idle_timeout(
string [] tunnels
) {
object [] results = this.Invoke("get_idle_timeout", new object [] {
tunnels});
return ((long [])(results[0]));
}
public System.IAsyncResult Beginget_idle_timeout(string [] tunnels, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_idle_timeout", new object[] {
tunnels}, callback, asyncState);
}
public long [] Endget_idle_timeout(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((long [])(results[0]));
}
//-----------------------------------------------------------------------
// get_if_index
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/Tunnel",
RequestNamespace="urn:iControl:Networking/Tunnel", ResponseNamespace="urn:iControl:Networking/Tunnel")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public long [] get_if_index(
string [] tunnels
) {
object [] results = this.Invoke("get_if_index", new object [] {
tunnels});
return ((long [])(results[0]));
}
public System.IAsyncResult Beginget_if_index(string [] tunnels, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_if_index", new object[] {
tunnels}, callback, asyncState);
}
public long [] Endget_if_index(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((long [])(results[0]));
}
//-----------------------------------------------------------------------
// get_key
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/Tunnel",
RequestNamespace="urn:iControl:Networking/Tunnel", ResponseNamespace="urn:iControl:Networking/Tunnel")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public long [] get_key(
string [] tunnels
) {
object [] results = this.Invoke("get_key", new object [] {
tunnels});
return ((long [])(results[0]));
}
public System.IAsyncResult Beginget_key(string [] tunnels, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_key", new object[] {
tunnels}, callback, asyncState);
}
public long [] Endget_key(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((long [])(results[0]));
}
//-----------------------------------------------------------------------
// get_list
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/Tunnel",
RequestNamespace="urn:iControl:Networking/Tunnel", ResponseNamespace="urn:iControl:Networking/Tunnel")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_list(
) {
object [] results = this.Invoke("get_list", new object [0]);
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_list(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_list", new object[0], callback, asyncState);
}
public string [] Endget_list(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_local_address
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/Tunnel",
RequestNamespace="urn:iControl:Networking/Tunnel", ResponseNamespace="urn:iControl:Networking/Tunnel")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_local_address(
string [] tunnels
) {
object [] results = this.Invoke("get_local_address", new object [] {
tunnels});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_local_address(string [] tunnels, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_local_address", new object[] {
tunnels}, callback, asyncState);
}
public string [] Endget_local_address(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_mac_address
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/Tunnel",
RequestNamespace="urn:iControl:Networking/Tunnel", ResponseNamespace="urn:iControl:Networking/Tunnel")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_mac_address(
string [] tunnels
) {
object [] results = this.Invoke("get_mac_address", new object [] {
tunnels});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_mac_address(string [] tunnels, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_mac_address", new object[] {
tunnels}, callback, asyncState);
}
public string [] Endget_mac_address(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_mtu
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/Tunnel",
RequestNamespace="urn:iControl:Networking/Tunnel", ResponseNamespace="urn:iControl:Networking/Tunnel")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public long [] get_mtu(
string [] tunnels
) {
object [] results = this.Invoke("get_mtu", new object [] {
tunnels});
return ((long [])(results[0]));
}
public System.IAsyncResult Beginget_mtu(string [] tunnels, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_mtu", new object[] {
tunnels}, callback, asyncState);
}
public long [] Endget_mtu(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((long [])(results[0]));
}
//-----------------------------------------------------------------------
// get_profile
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/Tunnel",
RequestNamespace="urn:iControl:Networking/Tunnel", ResponseNamespace="urn:iControl:Networking/Tunnel")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_profile(
string [] tunnels
) {
object [] results = this.Invoke("get_profile", new object [] {
tunnels});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_profile(string [] tunnels, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_profile", new object[] {
tunnels}, callback, asyncState);
}
public string [] Endget_profile(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_profile_v2
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/Tunnel",
RequestNamespace="urn:iControl:Networking/Tunnel", ResponseNamespace="urn:iControl:Networking/Tunnel")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public NetworkingTunnelTunnelProfileAttribute [] get_profile_v2(
string [] tunnels
) {
object [] results = this.Invoke("get_profile_v2", new object [] {
tunnels});
return ((NetworkingTunnelTunnelProfileAttribute [])(results[0]));
}
public System.IAsyncResult Beginget_profile_v2(string [] tunnels, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_profile_v2", new object[] {
tunnels}, callback, asyncState);
}
public NetworkingTunnelTunnelProfileAttribute [] Endget_profile_v2(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((NetworkingTunnelTunnelProfileAttribute [])(results[0]));
}
//-----------------------------------------------------------------------
// get_remote_address
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/Tunnel",
RequestNamespace="urn:iControl:Networking/Tunnel", ResponseNamespace="urn:iControl:Networking/Tunnel")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_remote_address(
string [] tunnels
) {
object [] results = this.Invoke("get_remote_address", new object [] {
tunnels});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_remote_address(string [] tunnels, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_remote_address", new object[] {
tunnels}, callback, asyncState);
}
public string [] Endget_remote_address(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_secondary_address
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/Tunnel",
RequestNamespace="urn:iControl:Networking/Tunnel", ResponseNamespace="urn:iControl:Networking/Tunnel")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_secondary_address(
string [] tunnels
) {
object [] results = this.Invoke("get_secondary_address", new object [] {
tunnels});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_secondary_address(string [] tunnels, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_secondary_address", new object[] {
tunnels}, callback, asyncState);
}
public string [] Endget_secondary_address(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_static_forwarding
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/Tunnel",
RequestNamespace="urn:iControl:Networking/Tunnel", ResponseNamespace="urn:iControl:Networking/Tunnel")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public NetworkingTunnelL2TunnelFDBEntry [] [] get_static_forwarding(
string [] tunnels
) {
object [] results = this.Invoke("get_static_forwarding", new object [] {
tunnels});
return ((NetworkingTunnelL2TunnelFDBEntry [] [])(results[0]));
}
public System.IAsyncResult Beginget_static_forwarding(string [] tunnels, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_static_forwarding", new object[] {
tunnels}, callback, asyncState);
}
public NetworkingTunnelL2TunnelFDBEntry [] [] Endget_static_forwarding(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((NetworkingTunnelL2TunnelFDBEntry [] [])(results[0]));
}
//-----------------------------------------------------------------------
// get_static_forwarding_v2
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/Tunnel",
RequestNamespace="urn:iControl:Networking/Tunnel", ResponseNamespace="urn:iControl:Networking/Tunnel")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public NetworkingTunnelL2TunnelFDBEntryV2 [] [] get_static_forwarding_v2(
string [] tunnels
) {
object [] results = this.Invoke("get_static_forwarding_v2", new object [] {
tunnels});
return ((NetworkingTunnelL2TunnelFDBEntryV2 [] [])(results[0]));
}
public System.IAsyncResult Beginget_static_forwarding_v2(string [] tunnels, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_static_forwarding_v2", new object[] {
tunnels}, callback, asyncState);
}
public NetworkingTunnelL2TunnelFDBEntryV2 [] [] Endget_static_forwarding_v2(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((NetworkingTunnelL2TunnelFDBEntryV2 [] [])(results[0]));
}
//-----------------------------------------------------------------------
// get_tos
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/Tunnel",
RequestNamespace="urn:iControl:Networking/Tunnel", ResponseNamespace="urn:iControl:Networking/Tunnel")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public long [] get_tos(
string [] tunnels
) {
object [] results = this.Invoke("get_tos", new object [] {
tunnels});
return ((long [])(results[0]));
}
public System.IAsyncResult Beginget_tos(string [] tunnels, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_tos", new object[] {
tunnels}, callback, asyncState);
}
public long [] Endget_tos(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((long [])(results[0]));
}
//-----------------------------------------------------------------------
// get_traffic_group
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/Tunnel",
RequestNamespace="urn:iControl:Networking/Tunnel", ResponseNamespace="urn:iControl:Networking/Tunnel")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_traffic_group(
string [] tunnels
) {
object [] results = this.Invoke("get_traffic_group", new object [] {
tunnels});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_traffic_group(string [] tunnels, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_traffic_group", new object[] {
tunnels}, callback, asyncState);
}
public string [] Endget_traffic_group(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_transparent_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/Tunnel",
RequestNamespace="urn:iControl:Networking/Tunnel", ResponseNamespace="urn:iControl:Networking/Tunnel")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public CommonEnabledState [] get_transparent_state(
string [] tunnels
) {
object [] results = this.Invoke("get_transparent_state", new object [] {
tunnels});
return ((CommonEnabledState [])(results[0]));
}
public System.IAsyncResult Beginget_transparent_state(string [] tunnels, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_transparent_state", new object[] {
tunnels}, callback, asyncState);
}
public CommonEnabledState [] Endget_transparent_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((CommonEnabledState [])(results[0]));
}
//-----------------------------------------------------------------------
// get_version
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/Tunnel",
RequestNamespace="urn:iControl:Networking/Tunnel", ResponseNamespace="urn:iControl:Networking/Tunnel")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string get_version(
) {
object [] results = this.Invoke("get_version", new object [] {
});
return ((string)(results[0]));
}
public System.IAsyncResult Beginget_version(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_version", new object[] {
}, callback, asyncState);
}
public string Endget_version(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string)(results[0]));
}
//-----------------------------------------------------------------------
// remove_all_static_forwardings
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/Tunnel",
RequestNamespace="urn:iControl:Networking/Tunnel", ResponseNamespace="urn:iControl:Networking/Tunnel")]
public void remove_all_static_forwardings(
string [] tunnels
) {
this.Invoke("remove_all_static_forwardings", new object [] {
tunnels});
}
public System.IAsyncResult Beginremove_all_static_forwardings(string [] tunnels, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("remove_all_static_forwardings", new object[] {
tunnels}, callback, asyncState);
}
public void Endremove_all_static_forwardings(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// remove_static_forwarding
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/Tunnel",
RequestNamespace="urn:iControl:Networking/Tunnel", ResponseNamespace="urn:iControl:Networking/Tunnel")]
public void remove_static_forwarding(
string [] tunnels,
NetworkingTunnelL2TunnelFDBEntry [] [] entries
) {
this.Invoke("remove_static_forwarding", new object [] {
tunnels,
entries});
}
public System.IAsyncResult Beginremove_static_forwarding(string [] tunnels,NetworkingTunnelL2TunnelFDBEntry [] [] entries, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("remove_static_forwarding", new object[] {
tunnels,
entries}, callback, asyncState);
}
public void Endremove_static_forwarding(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// remove_static_forwarding_v2
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/Tunnel",
RequestNamespace="urn:iControl:Networking/Tunnel", ResponseNamespace="urn:iControl:Networking/Tunnel")]
public void remove_static_forwarding_v2(
string [] tunnels,
NetworkingTunnelL2TunnelFDBEntryV2 [] [] entries
) {
this.Invoke("remove_static_forwarding_v2", new object [] {
tunnels,
entries});
}
public System.IAsyncResult Beginremove_static_forwarding_v2(string [] tunnels,NetworkingTunnelL2TunnelFDBEntryV2 [] [] entries, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("remove_static_forwarding_v2", new object[] {
tunnels,
entries}, callback, asyncState);
}
public void Endremove_static_forwarding_v2(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_auto_lasthop
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/Tunnel",
RequestNamespace="urn:iControl:Networking/Tunnel", ResponseNamespace="urn:iControl:Networking/Tunnel")]
public void set_auto_lasthop(
string [] tunnels,
CommonAutoLasthop [] values
) {
this.Invoke("set_auto_lasthop", new object [] {
tunnels,
values});
}
public System.IAsyncResult Beginset_auto_lasthop(string [] tunnels,CommonAutoLasthop [] values, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_auto_lasthop", new object[] {
tunnels,
values}, callback, asyncState);
}
public void Endset_auto_lasthop(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_description
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/Tunnel",
RequestNamespace="urn:iControl:Networking/Tunnel", ResponseNamespace="urn:iControl:Networking/Tunnel")]
public void set_description(
string [] tunnels,
string [] descriptions
) {
this.Invoke("set_description", new object [] {
tunnels,
descriptions});
}
public System.IAsyncResult Beginset_description(string [] tunnels,string [] descriptions, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_description", new object[] {
tunnels,
descriptions}, callback, asyncState);
}
public void Endset_description(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_direction
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/Tunnel",
RequestNamespace="urn:iControl:Networking/Tunnel", ResponseNamespace="urn:iControl:Networking/Tunnel")]
public void set_direction(
string [] tunnels,
NetworkingTunnelTunnelDirection [] directions
) {
this.Invoke("set_direction", new object [] {
tunnels,
directions});
}
public System.IAsyncResult Beginset_direction(string [] tunnels,NetworkingTunnelTunnelDirection [] directions, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_direction", new object[] {
tunnels,
directions}, callback, asyncState);
}
public void Endset_direction(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_idle_timeout
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/Tunnel",
RequestNamespace="urn:iControl:Networking/Tunnel", ResponseNamespace="urn:iControl:Networking/Tunnel")]
public void set_idle_timeout(
string [] tunnels,
long [] timeouts
) {
this.Invoke("set_idle_timeout", new object [] {
tunnels,
timeouts});
}
public System.IAsyncResult Beginset_idle_timeout(string [] tunnels,long [] timeouts, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_idle_timeout", new object[] {
tunnels,
timeouts}, callback, asyncState);
}
public void Endset_idle_timeout(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_key
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/Tunnel",
RequestNamespace="urn:iControl:Networking/Tunnel", ResponseNamespace="urn:iControl:Networking/Tunnel")]
public void set_key(
string [] tunnels,
long [] keys
) {
this.Invoke("set_key", new object [] {
tunnels,
keys});
}
public System.IAsyncResult Beginset_key(string [] tunnels,long [] keys, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_key", new object[] {
tunnels,
keys}, callback, asyncState);
}
public void Endset_key(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_local_address
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/Tunnel",
RequestNamespace="urn:iControl:Networking/Tunnel", ResponseNamespace="urn:iControl:Networking/Tunnel")]
public void set_local_address(
string [] tunnels,
string [] addresses
) {
this.Invoke("set_local_address", new object [] {
tunnels,
addresses});
}
public System.IAsyncResult Beginset_local_address(string [] tunnels,string [] addresses, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_local_address", new object[] {
tunnels,
addresses}, callback, asyncState);
}
public void Endset_local_address(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_local_address_with_transparent_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/Tunnel",
RequestNamespace="urn:iControl:Networking/Tunnel", ResponseNamespace="urn:iControl:Networking/Tunnel")]
public void set_local_address_with_transparent_state(
string [] tunnels,
string [] addresses,
CommonEnabledState [] states
) {
this.Invoke("set_local_address_with_transparent_state", new object [] {
tunnels,
addresses,
states});
}
public System.IAsyncResult Beginset_local_address_with_transparent_state(string [] tunnels,string [] addresses,CommonEnabledState [] states, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_local_address_with_transparent_state", new object[] {
tunnels,
addresses,
states}, callback, asyncState);
}
public void Endset_local_address_with_transparent_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_mtu
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/Tunnel",
RequestNamespace="urn:iControl:Networking/Tunnel", ResponseNamespace="urn:iControl:Networking/Tunnel")]
public void set_mtu(
string [] tunnels,
long [] mtus
) {
this.Invoke("set_mtu", new object [] {
tunnels,
mtus});
}
public System.IAsyncResult Beginset_mtu(string [] tunnels,long [] mtus, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_mtu", new object[] {
tunnels,
mtus}, callback, asyncState);
}
public void Endset_mtu(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_profile
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/Tunnel",
RequestNamespace="urn:iControl:Networking/Tunnel", ResponseNamespace="urn:iControl:Networking/Tunnel")]
public void set_profile(
string [] tunnels,
string [] profiles
) {
this.Invoke("set_profile", new object [] {
tunnels,
profiles});
}
public System.IAsyncResult Beginset_profile(string [] tunnels,string [] profiles, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_profile", new object[] {
tunnels,
profiles}, callback, asyncState);
}
public void Endset_profile(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_remote_address
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/Tunnel",
RequestNamespace="urn:iControl:Networking/Tunnel", ResponseNamespace="urn:iControl:Networking/Tunnel")]
public void set_remote_address(
string [] tunnels,
string [] addresses
) {
this.Invoke("set_remote_address", new object [] {
tunnels,
addresses});
}
public System.IAsyncResult Beginset_remote_address(string [] tunnels,string [] addresses, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_remote_address", new object[] {
tunnels,
addresses}, callback, asyncState);
}
public void Endset_remote_address(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_secondary_address
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/Tunnel",
RequestNamespace="urn:iControl:Networking/Tunnel", ResponseNamespace="urn:iControl:Networking/Tunnel")]
public void set_secondary_address(
string [] tunnels,
string [] addresses
) {
this.Invoke("set_secondary_address", new object [] {
tunnels,
addresses});
}
public System.IAsyncResult Beginset_secondary_address(string [] tunnels,string [] addresses, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_secondary_address", new object[] {
tunnels,
addresses}, callback, asyncState);
}
public void Endset_secondary_address(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_tos
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/Tunnel",
RequestNamespace="urn:iControl:Networking/Tunnel", ResponseNamespace="urn:iControl:Networking/Tunnel")]
public void set_tos(
string [] tunnels,
long [] values
) {
this.Invoke("set_tos", new object [] {
tunnels,
values});
}
public System.IAsyncResult Beginset_tos(string [] tunnels,long [] values, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_tos", new object[] {
tunnels,
values}, callback, asyncState);
}
public void Endset_tos(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_traffic_group
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/Tunnel",
RequestNamespace="urn:iControl:Networking/Tunnel", ResponseNamespace="urn:iControl:Networking/Tunnel")]
public void set_traffic_group(
string [] tunnels,
string [] traffic_groups
) {
this.Invoke("set_traffic_group", new object [] {
tunnels,
traffic_groups});
}
public System.IAsyncResult Beginset_traffic_group(string [] tunnels,string [] traffic_groups, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_traffic_group", new object[] {
tunnels,
traffic_groups}, callback, asyncState);
}
public void Endset_traffic_group(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_transparent_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/Tunnel",
RequestNamespace="urn:iControl:Networking/Tunnel", ResponseNamespace="urn:iControl:Networking/Tunnel")]
public void set_transparent_state(
string [] tunnels,
CommonEnabledState [] states
) {
this.Invoke("set_transparent_state", new object [] {
tunnels,
states});
}
public System.IAsyncResult Beginset_transparent_state(string [] tunnels,CommonEnabledState [] states, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_transparent_state", new object[] {
tunnels,
states}, callback, asyncState);
}
public void Endset_transparent_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
}
//=======================================================================
// Enums
//=======================================================================
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Xml.Serialization.SoapTypeAttribute(TypeName = "Networking.Tunnel.TunnelDirection", Namespace = "urn:iControl")]
public enum NetworkingTunnelTunnelDirection
{
TUNNEL_DIRECTION_UNKNOWN,
TUNNEL_DIRECTION_INBOUND,
TUNNEL_DIRECTION_OUTBOUND,
TUNNEL_DIRECTION_BIDIRECTIONAL,
}
//=======================================================================
// Structs
//=======================================================================
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.SoapTypeAttribute(TypeName = "Networking.Tunnel.L2TunnelFDBEntry", Namespace = "urn:iControl")]
public partial class NetworkingTunnelL2TunnelFDBEntry
{
private string mac_addressField;
public string mac_address
{
get { return this.mac_addressField; }
set { this.mac_addressField = value; }
}
private string endpointField;
public string endpoint
{
get { return this.endpointField; }
set { this.endpointField = value; }
}
};
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.SoapTypeAttribute(TypeName = "Networking.Tunnel.L2TunnelFDBEntryV2", Namespace = "urn:iControl")]
public partial class NetworkingTunnelL2TunnelFDBEntryV2
{
private string mac_addressField;
public string mac_address
{
get { return this.mac_addressField; }
set { this.mac_addressField = value; }
}
private string endpointField;
public string endpoint
{
get { return this.endpointField; }
set { this.endpointField = value; }
}
private string [] replicatorsField;
public string [] replicators
{
get { return this.replicatorsField; }
set { this.replicatorsField = value; }
}
};
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.SoapTypeAttribute(TypeName = "Networking.Tunnel.TunnelProfileAttribute", Namespace = "urn:iControl")]
public partial class NetworkingTunnelTunnelProfileAttribute
{
private NetworkingTunnelProfileType profile_typeField;
public NetworkingTunnelProfileType profile_type
{
get { return this.profile_typeField; }
set { this.profile_typeField = value; }
}
private string profile_nameField;
public string profile_name
{
get { return this.profile_nameField; }
set { this.profile_nameField = value; }
}
};
}
| |
using System.Diagnostics.Contracts;
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
//
// <OWNER>[....]</OWNER>
/*============================================================
**
** Class: ExecutionContext
**
**
** Purpose: Capture Host execution context for a thread
**
**
===========================================================*/
namespace System.Threading
{
using System.Security;
using System.Runtime.Remoting;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
using System.Security.Permissions;
using System.Runtime.Remoting.Messaging;
using System.Runtime.ConstrainedExecution;
using System.Runtime.Versioning;
using System.Runtime.InteropServices;
internal class HostExecutionContextSwitcher
{
internal ExecutionContext executionContext;
internal HostExecutionContext previousHostContext;
internal HostExecutionContext currentHostContext;
[System.Security.SecurityCritical] // auto-generated
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
static public void Undo(Object switcherObject)
{
if (switcherObject == null)
return;
// otherwise call the host
HostExecutionContextManager hostMgr = HostExecutionContextManager.GetCurrentHostExecutionContextManager();
if (hostMgr != null)
{
hostMgr.Revert(switcherObject);
}
}
}
public class HostExecutionContext : IDisposable
{
private Object state;
protected internal Object State {
get {
return state;
}
set {
state = value;
}
}
public HostExecutionContext()
{
}
public HostExecutionContext(Object state)
{
this.state = state;
}
[System.Security.SecuritySafeCritical] // auto-generated
public virtual HostExecutionContext CreateCopy()
{
Object newState = state;
if (state is IUnknownSafeHandle)
{
// Clone the IUnknown handle
newState = ((IUnknownSafeHandle)state).Clone();
}
return new HostExecutionContext(state);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
public virtual void Dispose(bool disposing)
{
return;
}
}
[System.Security.SecurityCritical] // auto-generated
internal class IUnknownSafeHandle : SafeHandle
{
public IUnknownSafeHandle() : base(IntPtr.Zero, true)
{
}
public override bool IsInvalid {
[System.Security.SecurityCritical]
get { return handle == IntPtr.Zero; }
}
[System.Security.SecurityCritical]
override protected bool ReleaseHandle()
{
HostExecutionContextManager.ReleaseHostSecurityContext(this.handle);
return true;
}
internal Object Clone()
{
IUnknownSafeHandle unkSafeHandleCloned = new IUnknownSafeHandle();
// call into the Hosting API to CLONE the host context
// stores the output IUnknown in the safehandle,
if (!IsInvalid)
{
HostExecutionContextManager.CloneHostSecurityContext(this, unkSafeHandleCloned);
}
return unkSafeHandleCloned;
}
}
public class HostExecutionContextManager
{
private static volatile bool _fIsHostedChecked;
private static volatile bool _fIsHosted;
private static HostExecutionContextManager _hostExecutionContextManager;
[System.Security.SecurityCritical] // auto-generated
[ResourceExposure(ResourceScope.None)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
static private extern bool HostSecurityManagerPresent();
[System.Security.SecurityCritical] // auto-generated
[ResourceExposure(ResourceScope.None)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
static internal extern int ReleaseHostSecurityContext(IntPtr context);
[System.Security.SecurityCritical] // auto-generated
[ResourceExposure(ResourceScope.None)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
static internal extern int CloneHostSecurityContext(SafeHandle context, SafeHandle clonedContext);
[System.Security.SecurityCritical] // auto-generated
[ResourceExposure(ResourceScope.None)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
static private extern int CaptureHostSecurityContext(SafeHandle capturedContext);
[System.Security.SecurityCritical] // auto-generated
[ResourceExposure(ResourceScope.None)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
static private extern int SetHostSecurityContext(SafeHandle context, bool fReturnPrevious, SafeHandle prevContext);
[System.Security.SecurityCritical] // auto-generated
internal static bool CheckIfHosted()
{
if (!_fIsHostedChecked)
{
_fIsHosted = HostSecurityManagerPresent();
_fIsHostedChecked = true;
}
return _fIsHosted;
}
// capture Host SecurityContext
[System.Security.SecuritySafeCritical] // auto-generated
public virtual HostExecutionContext Capture()
{
HostExecutionContext context = null;
// check if we are hosted
if (CheckIfHosted())
{
IUnknownSafeHandle unkSafeHandle = new IUnknownSafeHandle();
context = new HostExecutionContext(unkSafeHandle);
// call into the Hosting API to capture the host context
// stores the output IUnknown in the safehandle,
CaptureHostSecurityContext(unkSafeHandle);
}
// otherwise
return context;
}
// Set Host SecurityContext
[System.Security.SecurityCritical] // auto-generated_required
public virtual Object SetHostExecutionContext(HostExecutionContext hostExecutionContext)
{
if (hostExecutionContext == null)
{
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotNewCaptureContext"));
}
Contract.EndContractBlock();
HostExecutionContextSwitcher switcher = new HostExecutionContextSwitcher();
ExecutionContext currentExecutionContext = Thread.CurrentThread.GetMutableExecutionContext();
switcher.executionContext = currentExecutionContext;
switcher.currentHostContext = hostExecutionContext;
switcher.previousHostContext = null;
if (CheckIfHosted())
{
if (hostExecutionContext.State is IUnknownSafeHandle)
{
// setup the previous unknown handle
IUnknownSafeHandle unkPrevSafeHandle = new IUnknownSafeHandle();
switcher.previousHostContext = new HostExecutionContext(unkPrevSafeHandle);
// get the current handle
IUnknownSafeHandle unkSafeHandle = (IUnknownSafeHandle)hostExecutionContext.State;
// call into the Hosting API to set the host context
// second arg indicates whether we want to retrieve the previous context
SetHostSecurityContext(unkSafeHandle,true,unkPrevSafeHandle);
}
}
// store the current HostExecutionContext in the ExecutionContext.
currentExecutionContext.HostExecutionContext = hostExecutionContext;
return switcher;
}
// this method needs to be reliable
[System.Security.SecurityCritical] // auto-generated_required
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
public virtual void Revert(Object previousState)
{
HostExecutionContextSwitcher hostContextSwitcher = previousState as HostExecutionContextSwitcher;
if (hostContextSwitcher == null)
{
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CannotOverrideSetWithoutRevert"));
}
// check Undo is happening on the correct thread
ExecutionContext executionContext = Thread.CurrentThread.GetMutableExecutionContext();
if (executionContext != hostContextSwitcher.executionContext)
{
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CannotUseSwitcherOtherThread"));
}
hostContextSwitcher.executionContext = null; // Make sure switcher cannot be re-used.
HostExecutionContext revertFromHostContext = executionContext.HostExecutionContext;
// if the current host context is not the same as the one in the switcher, then revert is being called out of order
if (revertFromHostContext != hostContextSwitcher.currentHostContext)
{
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CannotUseSwitcherOtherThread"));
}
// get the previous host context
HostExecutionContext revertToHostContext = hostContextSwitcher.previousHostContext;
// now check if we are hosted and revert the context in the host
if (CheckIfHosted())
{
// try restore the previous context as the current context
if (revertToHostContext != null && revertToHostContext.State is IUnknownSafeHandle)
{
IUnknownSafeHandle unkprevSafeHandle = (IUnknownSafeHandle)revertToHostContext.State;
// call into the Hosting API to set the host context
SetHostSecurityContext(unkprevSafeHandle, false, null);
}
}
//restore the previous host context in the executioncontext
executionContext.HostExecutionContext = revertToHostContext;
}
[System.Security.SecurityCritical] // auto-generated
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static HostExecutionContext CaptureHostExecutionContext()
{
HostExecutionContext hostContext = null;
// capture the host execution context
HostExecutionContextManager hostMgr = HostExecutionContextManager.GetCurrentHostExecutionContextManager();
if (hostMgr != null)
{
hostContext = hostMgr.Capture();
}
return hostContext;
}
[System.Security.SecurityCritical] // auto-generated
internal static Object SetHostExecutionContextInternal(HostExecutionContext hostContext)
{
HostExecutionContextManager hostMgr = HostExecutionContextManager.GetCurrentHostExecutionContextManager();
Object switcher = null;
if (hostMgr != null)
{
switcher = hostMgr.SetHostExecutionContext(hostContext);
//
}
return switcher;
}
// retun the HostExecutionContextManager for the current AppDomain
[System.Security.SecurityCritical] // auto-generated
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static HostExecutionContextManager GetCurrentHostExecutionContextManager()
{
// this is called during AppDomainManager initialization, this is a thread safe place
// to setup the HostExecutionContextManager for the current AppDomain
AppDomainManager mgr = AppDomainManager.CurrentAppDomainManager;
if (mgr != null)
return mgr.HostExecutionContextManager;
return null;
}
// retun the HostExecutionContextManager for the current AppDomain
internal static HostExecutionContextManager GetInternalHostExecutionContextManager()
{
if (_hostExecutionContextManager == null) {
// setup the HostExecutionContextManager for the current AppDomain
Contract.Assert(_hostExecutionContextManager == null, "HostExecutionContextManager should be null");
_hostExecutionContextManager = new HostExecutionContextManager();
}
return _hostExecutionContextManager;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using Azure.ResourceManager.Resources;
using System.Threading.Tasks;
using Azure.ResourceManager.Resources.Models;
using Azure.ResourceManager.Dns.Models;
using System.Collections.Generic;
using System.Net;
namespace Azure.Management.Dns.Tests
{
public static class Helper
{
public static async Task TryRegisterResourceGroupAsync(ResourceGroupContainer resourceGroupsOperations, string location, string resourceGroupName)
{
await resourceGroupsOperations.CreateOrUpdateAsync(resourceGroupName, new ResourceGroupData(location));
}
public static bool AreEqualPrereq(
Azure.ResourceManager.Dns.Models.Resource first,
Azure.ResourceManager.Dns.Models.Resource second,
bool ignoreEtag = false)
{
if (first == null || second == null)
{
return false;
}
if (!String.Equals(first.Location, second.Location, StringComparison.OrdinalIgnoreCase))
{
return false;
}
if (first.Tags != null && second.Tags != null)
{
if (first.Tags.Count != second.Tags.Count)
{
return false;
}
foreach (string key in first.Tags.Keys)
{
if (!second.Tags.ContainsKey(key) ||
first.Tags[key] != second.Tags[key])
{
return false;
}
}
}
else{
return false;
}
return true;
}
public static bool AreEqual(
Zone first,
Zone second,
bool ignoreEtag = false)
{
if (!AreEqualPrereq(first, second))
{
return false;
}
if (first != null && second != null)
{
return ignoreEtag || (first.Etag == second.Etag);
}
return true;
}
public static bool AreEqual(
RecordSet first,
RecordSet second,
bool ignoreEtag = false)
{
if (first != null && second != null)
{
return (ignoreEtag || (first.Etag == second.Etag))
&& first.TTL == second.TTL
&& AreEqual(first.ARecords, second.ARecords)
&& AreEqual(first.AaaaRecords, second.AaaaRecords)
&& AreEqual(first.MxRecords, second.MxRecords)
&& AreEqual(first.NsRecords, second.NsRecords)
&& AreEqual(first.PtrRecords, second.PtrRecords)
&& AreEqual(first.SrvRecords, second.SrvRecords)
&& AreEqual(first.CnameRecord, second.CnameRecord)
&& AreEqual(first.SoaRecord, second.SoaRecord);
}
return true;
}
public static bool AreEqual(string first, string second)
{
return string.Equals(first, second, StringComparison.OrdinalIgnoreCase);
}
public static bool AreEqual(CnameRecord first, CnameRecord second)
{
if (first == null && second == null)
{
return true;
}
else if (first == null || second == null)
{
return false;
}
return first.Cname == second.Cname;
}
public static bool AreEqual(SoaRecord first, SoaRecord second)
{
if (first == null && second == null)
{
return true;
}
else if (first == null || second == null)
{
return false;
}
return first.Email == second.Email
&& first.ExpireTime == second.ExpireTime
&& first.Host == second.Host
&& first.MinimumTtl == second.MinimumTtl
&& first.RefreshTime == second.RefreshTime
&& first.RetryTime == second.RetryTime
&& first.SerialNumber == second.SerialNumber;
}
public static bool AreEqualCount<T>(IList<T> first, IList<T> second)
{
if ((first == null || first.Count == 0) &&
(second == null || second.Count == 0))
{
return true;
}
else if (first == null || second == null || first.Count == 0 ||
second.Count == 0)
{
return false;
}
else
{
return first.Count == second.Count;
}
}
public static bool AreEqual(IList<ARecord> first, IList<ARecord> second)
{
if (!AreEqualCount(first, second))
{
return false;
}
if (first != null && second != null)
{
for (int i = 0; i < first.Count; i++)
{
if (first[i].Ipv4Address != second[i].Ipv4Address)
{
return false;
}
}
}
return true;
}
public static bool AreEqual(
IList<AaaaRecord> first,
IList<AaaaRecord> second)
{
if (!AreEqualCount(first, second))
{
return false;
}
if (first != null && second != null)
{
for (int i = 0; i < first.Count; i++)
{
var firstAddress = IPAddress.Parse(first[i].Ipv6Address);
var secondAddress = IPAddress.Parse(second[i].Ipv6Address);
if (!firstAddress.Equals(secondAddress))
{
return false;
}
}
}
return true;
}
public static bool AreEqual(
IList<MxRecord> first,
IList<MxRecord> second)
{
if (!AreEqualCount(first, second))
{
return false;
}
if (first != null && second != null)
{
for (int i = 0; i < first.Count; i++)
{
if (first[i].Exchange != second[i].Exchange
|| first[i].Preference != second[i].Preference)
{
return false;
}
}
}
return true;
}
public static bool AreEqual(
IList<NsRecord> first,
IList<NsRecord> second)
{
if (!AreEqualCount(first, second))
{
return false;
}
if (first != null && second != null)
{
for (int i = 0; i < first.Count; i++)
{
if (first[i].Nsdname != second[i].Nsdname)
{
return false;
}
}
}
return true;
}
public static bool AreEqual(
IList<PtrRecord> first,
IList<PtrRecord> second)
{
if (!AreEqualCount(first, second))
{
return false;
}
if (first != null && second != null)
{
for (int i = 0; i < first.Count; i++)
{
if (first[i].Ptrdname != second[i].Ptrdname)
{
return false;
}
}
}
return true;
}
public static bool AreEqual(
IList<SrvRecord> first,
IList<SrvRecord> second)
{
if (!AreEqualCount(first, second))
{
return false;
}
if (first != null && second != null)
{
for (int i = 0; i < first.Count; i++)
{
if (first[i].Port != second[i].Port
|| first[i].Target != second[i].Target
|| first[i].Weight != second[i].Weight
|| first[i].Priority != second[i].Priority)
{
return false;
}
}
}
return true;
}
public static bool AreEqual(
IList<TxtRecord> first,
IList<TxtRecord> second)
{
if (!AreEqualCount(first, second))
{
return false;
}
if (first != null && second != null)
{
for (int i = 0; i < first.Count; i++)
{
if (first[i].Value != second[i].Value)
{
return false;
}
}
}
return true;
}
public static bool AreEqual(
Azure.ResourceManager.Dns.Models.SubResource first,
Azure.ResourceManager.Dns.Models.SubResource second)
{
if (first != null && second != null)
{
return first.Id == second.Id;
}
return true;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.IO.Compression;
using System.Security;
using ZErrorCode = System.IO.Pipelines.Compression.ZLibNative.ErrorCode;
using ZFlushCode = System.IO.Pipelines.Compression.ZLibNative.FlushCode;
namespace System.IO.Pipelines.Compression
{
/// <summary>
/// Provides a wrapper around the ZLib compression API
/// </summary>
internal sealed class Deflater : IDisposable
{
private ZLibNative.ZLibStreamHandle _zlibStream;
private bool _isDisposed;
private const int minWindowBits = -15; // WindowBits must be between -8..-15 to write no header, 8..15 for a
private const int maxWindowBits = 31; // zlib header, or 24..31 for a GZip header
// Note, DeflateStream or the deflater do not try to be thread safe.
// The lock is just used to make writing to unmanaged structures atomic to make sure
// that they do not get inconsistent fields that may lead to an unmanaged memory violation.
// To prevent *managed* buffer corruption or other weird behaviour users need to synchronise
// on the stream explicitly.
private readonly object _syncLock = new object();
public int AvailableInput => (int)_zlibStream.AvailIn;
#region exposed members
internal Deflater(CompressionLevel compressionLevel, int windowBits)
{
Debug.Assert(windowBits >= minWindowBits && windowBits <= maxWindowBits);
ZLibNative.CompressionLevel zlibCompressionLevel;
int memLevel;
switch (compressionLevel)
{
// See the note in ZLibNative.CompressionLevel for the recommended combinations.
case CompressionLevel.Optimal:
zlibCompressionLevel = ZLibNative.CompressionLevel.DefaultCompression;
memLevel = ZLibNative.Deflate_DefaultMemLevel;
break;
case CompressionLevel.Fastest:
zlibCompressionLevel = ZLibNative.CompressionLevel.BestSpeed;
memLevel = ZLibNative.Deflate_DefaultMemLevel;
break;
case CompressionLevel.NoCompression:
zlibCompressionLevel = ZLibNative.CompressionLevel.NoCompression;
memLevel = ZLibNative.Deflate_NoCompressionMemLevel;
break;
default:
throw new ArgumentOutOfRangeException(nameof(compressionLevel));
}
ZLibNative.CompressionStrategy strategy = ZLibNative.CompressionStrategy.DefaultStrategy;
DeflateInit(zlibCompressionLevel, windowBits, memLevel, strategy);
}
~Deflater()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
[SecuritySafeCritical]
private void Dispose(bool disposing)
{
if (!_isDisposed)
{
if (disposing)
_zlibStream.Dispose();
_isDisposed = true;
}
}
public bool NeedsInput()
{
return 0 == _zlibStream.AvailIn;
}
internal void SetInput(IntPtr buffer, int count)
{
Debug.Assert(NeedsInput(), "We have something left in previous input!");
if (0 == count)
return;
lock (_syncLock)
{
_zlibStream.NextIn = buffer;
_zlibStream.AvailIn = (uint)count;
}
}
public int ReadDeflateOutput(IntPtr buffer, int count)
{
Contract.Ensures(Contract.Result<int>() >= 0 && Contract.Result<int>() <= count);
Debug.Assert(!NeedsInput(), "GetDeflateOutput should only be called after providing input");
try
{
int bytesRead;
ReadDeflateOutput(buffer, count, ZFlushCode.NoFlush, out bytesRead);
return bytesRead;
}
finally
{
// Before returning, make sure to release input buffer if necessary:
if (0 == _zlibStream.AvailIn)
DeallocateInputBufferHandle();
}
}
private unsafe ZErrorCode ReadDeflateOutput(IntPtr buffer, int count, ZFlushCode flushCode, out int bytesRead)
{
lock (_syncLock)
{
_zlibStream.NextOut = buffer;
_zlibStream.AvailOut = (uint)count;
ZErrorCode errC = Deflate(flushCode);
bytesRead = count - (int)_zlibStream.AvailOut;
return errC;
}
}
internal bool Finish(IntPtr buffer, int count, out int bytesRead)
{
Debug.Assert(NeedsInput(), "We have something left in previous input!");
// Note: we require that NeedsInput() == true, i.e. that 0 == _zlibStream.AvailIn.
// If there is still input left we should never be getting here; instead we
// should be calling GetDeflateOutput.
ZErrorCode errC = ReadDeflateOutput(buffer, count, ZFlushCode.Finish, out bytesRead);
return errC == ZErrorCode.StreamEnd;
}
/// <summary>
/// Returns true if there was something to flush. Otherwise False.
/// </summary>
internal bool Flush(IntPtr buffer, int count, out int bytesRead)
{
Debug.Assert(NeedsInput(), "We have something left in previous input!");
// Note: we require that NeedsInput() == true, i.e. that 0 == _zlibStream.AvailIn.
// If there is still input left we should never be getting here; instead we
// should be calling GetDeflateOutput.
return ReadDeflateOutput(buffer, count, ZFlushCode.SyncFlush, out bytesRead) == ZErrorCode.Ok;
}
#endregion
#region helpers & native call wrappers
private void DeallocateInputBufferHandle()
{
lock (_syncLock)
{
_zlibStream.AvailIn = 0;
_zlibStream.NextIn = ZLibNative.ZNullPtr;
}
}
[SecuritySafeCritical]
private void DeflateInit(ZLibNative.CompressionLevel compressionLevel, int windowBits, int memLevel,
ZLibNative.CompressionStrategy strategy)
{
ZErrorCode errC;
try
{
errC = ZLibNative.CreateZLibStreamForDeflate(out _zlibStream, compressionLevel,
windowBits, memLevel, strategy);
}
catch (Exception cause)
{
throw new ZLibException("SR.ZLibErrorDLLLoadError", cause);
}
switch (errC)
{
case ZErrorCode.Ok:
return;
case ZErrorCode.MemError:
throw new ZLibException("SR.ZLibErrorNotEnoughMemory", "deflateInit2_", (int)errC, _zlibStream.GetErrorMessage());
case ZErrorCode.VersionError:
throw new ZLibException("SR.ZLibErrorVersionMismatch", "deflateInit2_", (int)errC, _zlibStream.GetErrorMessage());
case ZErrorCode.StreamError:
throw new ZLibException("SR.ZLibErrorIncorrectInitParameters", "deflateInit2_", (int)errC, _zlibStream.GetErrorMessage());
default:
throw new ZLibException("SR.ZLibErrorUnexpected", "deflateInit2_", (int)errC, _zlibStream.GetErrorMessage());
}
}
[SecuritySafeCritical]
private ZErrorCode Deflate(ZFlushCode flushCode)
{
ZErrorCode errC;
try
{
errC = _zlibStream.Deflate(flushCode);
}
catch (Exception cause)
{
throw new ZLibException("SR.ZLibErrorDLLLoadError", cause);
}
switch (errC)
{
case ZErrorCode.Ok:
case ZErrorCode.StreamEnd:
return errC;
case ZErrorCode.BufError:
return errC; // This is a recoverable error
case ZErrorCode.StreamError:
throw new ZLibException("SR.ZLibErrorInconsistentStream", "deflate", (int)errC, _zlibStream.GetErrorMessage());
default:
throw new ZLibException("SR.ZLibErrorUnexpected", "deflate", (int)errC, _zlibStream.GetErrorMessage());
}
}
#endregion
}
}
| |
// ===========================================================
// Copyright (c) 2014-2015, Enrico Da Ros/kendar.org
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// ===========================================================
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using CoroutinesLib.Shared;
using CoroutinesLib.TestHelpers;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
namespace CoroutinesLib.Test
{
[TestClass]
public class CoroutinesManagerTest_NotWaiting
{
#region Coroutines not waiting
public IEnumerable<ICoroutineResult> NotWaitingWaitForReturnValue(int waitCount)
{
while (waitCount > 0)
{
yield return CoroutineResult.Wait;
waitCount--;
}
yield return CoroutineResult.Return("RESULT");
}
public IEnumerable<ICoroutineResult> NotWaitingCoroutineWaitingForSingleResult(int waitCount = 1)
{
yield return CoroutineResult.Wait;
yield return CoroutineResult.RunAndGetResult(NotWaitingWaitForReturnValue(waitCount),"NotWaitingWaitForReturnValue")
.OnComplete<string>((r) =>
{
_coroutineSingleResult = r;
});
}
[TestMethod]
public void NotWaitingItShouldBePossibleToWaitForCoroutineCallingFunctionThatWait()
{
const int items = 10;
const int itemsAndWait = items*2;
var coroutine = new Mock<ICoroutineThread>();
coroutine.Setup(a => a.Execute())
.Returns(NotWaitingCoroutineWaitingForSingleResult(items));
var target = new CoroutinesManager();
target.TestInitialize();
target.StartCoroutine(coroutine.Object);
target.TestRun(itemsAndWait);
Assert.AreEqual("RESULT", _coroutineSingleResult);
}
[TestMethod]
public void NotWaitingItShouldBePossibleToWaitForEnEntireForEach()
{
_notWaitingStarted = false;
_notWaitingCompleted = false;
_coroutineResultsCount = 0;
var coroutine = new Mock<ICoroutineThread>();
coroutine.Setup(a => a.Execute())
.Returns(NotWaitingForAllResults(10));
var target = new CoroutinesManager();
target.TestInitialize();
var rtt = new RunnerForTest(target);
target.StartCoroutine(coroutine.Object);
rtt.RunCycle(); //Coroutine initialized
Assert.IsTrue(_notWaitingStarted);
rtt.RunCycle(2); //Coroutine started
Assert.IsTrue(_notWaitingCompleted);
Assert.AreEqual(0, _coroutineResultsCount);
rtt.RunCycle(50); //Coroutine started
Assert.AreEqual(10, _coroutineResultsCount);
}
public IEnumerable<ICoroutineResult> GetAllItems(int waitCount)
{
int results = 0;
while (waitCount > 0)
{
yield return CoroutineResult.Wait;
yield return CoroutineResult.YieldReturn(results);
waitCount--;
results++;
}
}
bool _notWaitingStarted;
bool _notWaitingCompleted;
public IEnumerable<ICoroutineResult> NotWaitingForAllResults(int waitCount = 1)
{
_notWaitingStarted = true;
_completed = false;
var result = 0;
yield return CoroutineResult.Wait;
yield return CoroutineResult.ForEachItem(GetAllItems(waitCount),"GetAllItems")
.Do<int>((r) =>
{
result++;
return true;
})
.OnComplete(() =>
{
_coroutineResultsCount = result;
})
.WithTimeout(TimeSpan.FromDays(10));
_notWaitingCompleted = true;
}
public IEnumerable<ICoroutineResult> NotWaitingForTask()
{
_notWaitingStarted = true;
yield return CoroutineResult.Wait;
yield return CoroutineResult.RunTask(Task.Factory.StartNew(() =>
{
_taskStarted = true;
Thread.Sleep(100);
_taskRun = true;
}),"NotWaitingForTask")
.OnComplete(() =>
{
_completedTaks = true;
});
_notWaitingCompleted = true;
}
bool _completedTaks;
[TestMethod]
public void NotWaitingItShouldBePossibleToWaitForATaskToComplete()
{
_notWaitingCompleted = false;
_notWaitingStarted = false;
_taskRun = false;
_taskStarted = false;
_completedTaks = false;
_exception = null;
var coroutine = new Mock<ICoroutineThread>();
coroutine.Setup(a => a.Execute())
.Returns(NotWaitingForTask());
var target = new CoroutinesManager();
target.TestInitialize();
var rtt = new RunnerForTest(target);
target.StartCoroutine(coroutine.Object);
rtt.RunCycle(); //Coroutine initialized
Assert.IsTrue(_notWaitingStarted);
rtt.RunCycle(); //Coroutine started
Thread.Sleep(50);
rtt.RunCycle();
Assert.IsTrue(_notWaitingCompleted);
Assert.IsTrue(_taskStarted);
Assert.IsNull(_exception);
Assert.IsFalse(_completedTaks);
rtt.RunCycleFor(150);
Assert.IsTrue(_taskStarted);
Assert.IsNull(_exception);
Assert.IsTrue(_completedTaks);
}
private Exception _exception;
private string _coroutineSingleResult;
private bool _taskRun;
private bool _taskStarted;
private bool _completed;
private int _coroutineResultsCount;
public IEnumerable<ICoroutineResult> NotWaitingHavingTimeout()
{
_notWaitingStarted = true;
yield return CoroutineResult.Wait;
yield return CoroutineResult.RunTask(Task.Factory.StartNew(() =>
{
_taskStarted = true;
Thread.Sleep(150);
_taskRun = true;
}),"NotWaitingHavingTimeout")
.OnComplete(() =>
{
_completedTaks = true;
})
.WithTimeout(100)
.OnError((e) =>
{
_exception = e;
return true;
});
_notWaitingCompleted = true;
}
[TestMethod]
public void NotWaitingItShouldBePossibleToWaitForATaskToCompleteWithTimeoutError()
{
_notWaitingCompleted = false;
_notWaitingStarted = false;
_taskRun = false;
_taskStarted = false;
_completedTaks = false;
_exception = null;
var coroutine = new Mock<ICoroutineThread>();
coroutine.Setup(a => a.Execute())
.Returns(NotWaitingHavingTimeout());
var target = new CoroutinesManager();
target.TestInitialize();
var rtt = new RunnerForTest(target);
target.StartCoroutine(coroutine.Object);
rtt.RunCycle(); //Coroutine initialized
Assert.IsTrue(_notWaitingStarted);
rtt.RunCycle(2); //Coroutine started
Assert.IsTrue(_notWaitingCompleted);
Assert.IsTrue(_taskStarted);
Assert.IsNull(_exception);
Assert.IsFalse(_completedTaks);
rtt.RunCycleFor(150);
Assert.IsTrue(_taskStarted);
Assert.IsNotNull(_exception);
Assert.IsFalse(_completedTaks);
}
public IEnumerable<ICoroutineResult> NotWaitingCoroutineWaitingHavingTimeoutNotExploding()
{
_taskRun = false;
_taskStarted = false;
_completed = false;
_completed = false;
yield return CoroutineResult.Wait;
yield return CoroutineResult.RunTask(Task.Factory.StartNew(() =>
{
_taskStarted = true;
Thread.Sleep(100);
_taskRun = true;
}),"NotWaitingCoroutineWaitingHavingTimeoutNotExploding")
.OnComplete(() =>
{
_completed = true;
})
.WithTimeout(1000);
}
[TestMethod]
public void NotWaitingItShouldBePossibleToWaitForATaskToCompleteWithTimeout()
{
var coroutine = new Mock<ICoroutineThread>();
coroutine.Setup(a => a.Execute())
.Returns(NotWaitingCoroutineWaitingHavingTimeoutNotExploding());
coroutine.Setup(o => o.OnError(It.IsAny<Exception>())).Returns(true);
var target = new CoroutinesManager();
target.TestInitialize();
target.StartCoroutine(coroutine.Object);
Task.Factory.StartNew(() => target.TestRun(3));
Thread.Sleep(300);
target.TestRun();
coroutine.Verify(a => a.OnError(It.IsAny<Exception>()), Times.Never);
Assert.IsTrue(_taskStarted);
Assert.IsTrue(_taskRun);
Assert.IsTrue(_completed);
}
#endregion
}
}
| |
using System.Reflection;
public class RatNumTest
{
public static void Main(string[] args)
{
RatNumTest test = new RatNumTest("test");
foreach (var method in test.GetType().GetMethods())
{
if (method.Name.StartsWith("test"))
{
System.Console.WriteLine(method.Name);
method.Invoke(test, null);
}
}
}
// naming convention used throughout class: spell out number in
// variable as its constructive form. Unary minus is notated with
// the prefix "neg", and the solidus is notated with an 'I'
// character. Thus, "1 + 2/3" becomes one_plus_two_I_three
// some simple base RatNums
private RatNum zero = new RatNum(0);
private RatNum one = new RatNum(1);
private RatNum negOne = new RatNum(-1);
private RatNum two = new RatNum(2);
private RatNum three = new RatNum(3);
private RatNum one_I_two = new RatNum(1, 2);
private RatNum one_I_three = new RatNum(1, 3);
private RatNum one_I_four = new RatNum(1, 4);
private RatNum two_I_three = new RatNum(2, 3);
private RatNum three_I_four = new RatNum(3, 4);
private RatNum five_I_six = new RatNum(5, 6);
private RatNum six_I_five = new RatNum(6, 5);
private RatNum eight_I_seven = new RatNum(8, 7);
private RatNum negOne_I_two = new RatNum(-1, 2);
// improper fraction
private RatNum three_I_two = new RatNum(3, 2);
// NaNs
private RatNum one_I_zero = new RatNum(1, 0);
private RatNum negOne_I_zero = new RatNum(-1, 0);
private RatNum hundred_I_zero = new RatNum(100, 0);
private RatNum two_I_zero = new RatNum(2, 0);
private RatNum negTwo_I_zero = new RatNum(-2, 0);
private RatNum nine_I_zero = new RatNum(9, 0);
// ratnums: Set of varied ratnums (includes NaNs)
// set is { 0, 1, -1, 2, 1/2, 3/2, 1/0, -1/0, 100/0, 8/7}
private RatNum[] ratnums;
// ratnans: Set of varied NaNs
// set is { 1/0, -1/0, 100/0 , 2/0, -2/0, 1000/0}
private RatNum[] ratnans;
// ratnanans: Set of varied non-NaN ratnums
// set is ratnums - ratnans
private RatNum[] ratnanans;
public RatNumTest(string name)
{
// ratnums: Set of varied ratnums (includes NaNs)
// set is { 0, 1, -1, 2, 1/2, 3/2, 1/0, -1/0, 100/0, 8/7}
ratnums = new RatNum[] {
zero, one, negOne, two, one_I_two, negOne_I_two, three_I_two,
/* NaNs */ one_I_zero, negOne_I_zero, hundred_I_zero, eight_I_seven
};
// ratnans: Set of varied NaNs
// set is { 1/0, -1/0, 100/0 , 2/0, -2/0, 1000/0}
ratnans = new RatNum[] {
one_I_zero, negOne_I_zero, hundred_I_zero, two_I_zero,
negTwo_I_zero, nine_I_zero
};
// ratnanans: Set of varied non-NaN ratnums
// set is ratnums - ratnans
ratnanans = new RatNum[] {
zero, one, negOne, two, one_I_two, three_I_two, one_I_four,
one_I_three, five_I_six, six_I_five, eight_I_seven
};
}
// self-explanatory helper function
private void eq(RatNum ratNum, string rep)
{
assertEquals(rep, ratNum.unparse());
}
public void testOneArgCtor()
{
eq(zero, "0");
eq(one, "1");
RatNum four = new RatNum(4);
eq(four, "4");
eq(negOne, "-1");
RatNum negFive = new RatNum(-5);
eq(negFive, "-5");
RatNum negZero = new RatNum(-0);
eq(negZero, "0");
}
public void testTwoArgCtor()
{
RatNum one_I_two = new RatNum(1, 2);
eq(one_I_two, "1/2");
RatNum two_I_one = new RatNum(2, 1);
eq(two_I_one, "2");
RatNum three_I_two = new RatNum(3, 2);
eq(three_I_two, "3/2");
RatNum negOne_I_thirteen = new RatNum(-1, 13);
eq(negOne_I_thirteen, "-1/13");
RatNum fiftyThree_I_seven = new RatNum(53, 7);
eq(fiftyThree_I_seven, "53/7");
RatNum zero_I_one = new RatNum(0, 1);
eq(zero_I_one, "0");
}
public void testTwoArgCtorOnNaN()
{
RatNum one_I_zero = new RatNum(1, 0);
eq(one_I_zero, "NaN");
RatNum two_I_zero = new RatNum(2, 0);
eq(two_I_zero, "NaN");
RatNum negOne_I_zero = new RatNum(-1, 0);
eq(negOne_I_zero, "NaN");
RatNum zero_I_zero = new RatNum(0, 0);
eq(zero_I_zero, "NaN");
RatNum negHundred_I_zero = new RatNum(-100, 0);
eq(negHundred_I_zero, "NaN");
}
public void testReduction()
{
RatNum negOne_I_negTwo = new RatNum(-1, -2);
eq(negOne_I_negTwo, "1/2");
RatNum two_I_four = new RatNum(2, 4);
eq(two_I_four, "1/2");
RatNum six_I_four = new RatNum(6, 4);
eq(six_I_four, "3/2");
RatNum twentySeven_I_thirteen = new RatNum(27, 13);
eq(twentySeven_I_thirteen, "27/13");
RatNum negHundred_I_negHundred = new RatNum(-100, -100);
eq(negHundred_I_negHundred, "1");
}
// self-explanatory helper function
private void approxEq(double d1, double d2)
{
assertTrue(System.Math.Abs(d1 - d2) < .0000001);
}
public void testApprox() {
approxEq( zero.approx(), 0.0 );
approxEq( one.approx(), 1.0 );
approxEq( negOne.approx(), -1.0 );
approxEq( two.approx(), 2.0 );
approxEq( one_I_two.approx(), 0.5 );
approxEq( two_I_three.approx(), 2.0/3.0 );
approxEq( three_I_four.approx(), 0.75 );
// cannot test that one_I_zero.approx() approxEq double.NaN,
// because it WON'T!!! Instead, construct corresponding
// instance of double and use .Equals(..) method
/*
assertTrue( (new System.Double(double.NaN)).
Equals
(new double(one_I_zero.approx())) );
assertTrue( (new double(double.NaN)).
Equals
(new double(negOne_I_zero.approx())) );
assertTrue( (new double(double.NaN)).
Equals
(new double(two_I_zero.approx())) );
assertTrue( (new double(double.NaN)).
Equals
(new double(negTwo_I_zero.approx())) );
assertTrue( (new double(double.NaN)).
Equals
(new double(hundred_I_zero.approx())) );
assertTrue( (new double(double.NaN)).
Equals
(new double(negOne_I_zero.approx())) );
assertTrue( (new double(double.NaN)).
Equals
(new double(nine_I_zero.approx())) );
*/
// use left-shift operator "<<" to create integer for 2^30
RatNum one_I_twoToThirty = new RatNum(1, (1<<30) );
double quiteSmall = 1.0/System.Math.Pow(2, 30);
approxEq( one_I_twoToThirty.approx(), quiteSmall );
}
public void testAddSimple()
{
eq(zero.add(zero), "0");
eq(zero.add(one), "1");
eq(one.add(zero), "1");
eq(one.add(one), "2");
eq(one.add(negOne), "0");
eq(one.add(two), "3");
eq(two.add(two), "4");
}
public void testAddComplex()
{
eq(one_I_two.add(zero), "1/2");
eq(one_I_two.add(one), "3/2");
eq(one_I_two.add(one_I_two), "1");
eq(one_I_two.add(one_I_three), "5/6");
eq(one_I_two.add(negOne), "-1/2");
eq(one_I_two.add(two), "5/2");
eq(one_I_two.add(two_I_three), "7/6");
eq(one_I_two.add(three_I_four), "5/4");
eq(one_I_three.add(zero), "1/3");
eq(one_I_three.add(two_I_three), "1");
eq(one_I_three.add(three_I_four), "13/12");
}
public void testAddImproper()
{
eq(three_I_two.add(one_I_two), "2");
eq(three_I_two.add(one_I_three), "11/6");
eq(three_I_four.add(three_I_four), "3/2");
eq(three_I_two.add(three_I_two), "3");
}
public void testAddOnNaN()
{
// each test case (addend, augend) drawn from the set
// ratnums x ratnans
for (int i = 0; i < ratnums.Length; i++)
{
for (int j = 0; j < ratnans.Length; j++)
{
eq(ratnums[i].add(ratnans[j]), "NaN");
eq(ratnans[j].add(ratnums[i]), "NaN");
}
}
}
public void testAddTransitively()
{
eq(one.add(one).add(one), "3");
eq(one.add(one.add(one)), "3");
eq(zero.add(zero).add(zero), "0");
eq(zero.add(zero.add(zero)), "0");
eq(one.add(two).add(three), "6");
eq(one.add(two.add(three)), "6");
eq(one_I_three.add(one_I_three).add(one_I_three), "1");
eq(one_I_three.add(one_I_three.add(one_I_three)), "1");
eq(one_I_zero.add(one_I_zero).add(one_I_zero), "NaN");
eq(one_I_zero.add(one_I_zero.add(one_I_zero)), "NaN");
eq(one_I_two.add(one_I_three).add(one_I_four), "13/12");
eq(one_I_two.add(one_I_three.add(one_I_four)), "13/12");
}
public void testSubSimple()
{
eq(zero.sub(one), "-1");
eq(zero.sub(zero), "0");
eq(one.sub(zero), "1");
eq(one.sub(one), "0");
eq(two.sub(one), "1");
eq(one.sub(negOne), "2");
eq(one.sub(two), "-1");
eq(one.sub(three), "-2");
}
public void testSubComplex()
{
eq(one.sub(one_I_two), "1/2");
eq(one_I_two.sub(one), "-1/2");
eq(one_I_two.sub(zero), "1/2");
eq(one_I_two.sub(two_I_three), "-1/6");
eq(one_I_two.sub(three_I_four), "-1/4");
}
public void testSubImproper()
{
eq(three_I_two.sub(one_I_two), "1");
eq(three_I_two.sub(one_I_three), "7/6");
}
public void testSubOnNaN()
{
// analogous to testAddOnNaN()
for (int i = 0; i < ratnums.Length; i++)
{
for (int j = 0; j < ratnans.Length; j++)
{
eq(ratnums[i].sub(ratnans[j]), "NaN");
eq(ratnans[j].sub(ratnums[i]), "NaN");
}
}
}
public void testSubTransitively()
{
// subtraction is not transitive; testing that operation is
// correct when *applied transitivitely*, not that it obeys
// the transitive property
eq(one.sub(one).sub(one), "-1");
eq(one.sub(one.sub(one)), "1");
eq(zero.sub(zero).sub(zero), "0");
eq(zero.sub(zero.sub(zero)), "0");
eq(one.sub(two).sub(three), "-4");
eq(one.sub(two.sub(three)), "2");
eq(one_I_three.sub(one_I_three).sub(one_I_three), "-1/3");
eq(one_I_three.sub(one_I_three.sub(one_I_three)), "1/3");
eq(one_I_zero.sub(one_I_zero).sub(one_I_zero), "NaN");
eq(one_I_zero.sub(one_I_zero.sub(one_I_zero)), "NaN");
eq(one_I_two.sub(one_I_three).sub(one_I_four), "-1/12");
eq(one_I_two.sub(one_I_three.sub(one_I_four)), "5/12");
}
public void testMulProperties()
{
// zero property
for (int i = 0; i < ratnanans.Length; i++)
{
eq(zero.mul(ratnanans[i]), "0");
eq(ratnanans[i].mul(zero), "0");
}
// one property
for (int i = 0; i < ratnanans.Length; i++)
{
eq(one.mul(ratnanans[i]), ratnanans[i].unparse());
eq(ratnanans[i].mul(one), ratnanans[i].unparse());
}
// negOne property
for (int i = 0; i < ratnanans.Length; i++)
{
eq(negOne.mul(ratnanans[i]), ratnanans[i].negate().unparse());
eq(ratnanans[i].mul(negOne), ratnanans[i].negate().unparse());
}
}
public void testMulSimple()
{
eq(two.mul(two), "4");
eq(two.mul(three), "6");
eq(three.mul(two), "6");
}
public void testMulComplex()
{
eq(one_I_two.mul(two), "1");
eq(two.mul(one_I_two), "1");
eq(one_I_two.mul(one_I_two), "1/4");
eq(one_I_two.mul(one_I_three), "1/6");
eq(one_I_three.mul(one_I_two), "1/6");
}
public void testMulImproper()
{
eq(three_I_two.mul(one_I_two), "3/4");
eq(three_I_two.mul(one_I_three), "1/2");
eq(three_I_two.mul(three_I_four), "9/8");
eq(three_I_two.mul(three_I_two), "9/4");
}
public void testMulOnNaN()
{
// analogous to testAddOnNaN()
for (int i = 0; i < ratnums.Length; i++)
{
for (int j = 0; j < ratnans.Length; j++)
{
eq(ratnums[i].mul(ratnans[j]), "NaN");
eq(ratnans[j].mul(ratnums[i]), "NaN");
}
}
}
public void testMulTransitively()
{
eq(one.mul(one).mul(one), "1");
eq(one.mul(one.mul(one)), "1");
eq(zero.mul(zero).mul(zero), "0");
eq(zero.mul(zero.mul(zero)), "0");
eq(one.mul(two).mul(three), "6");
eq(one.mul(two.mul(three)), "6");
eq(one_I_three.mul(one_I_three).mul(one_I_three), "1/27");
eq(one_I_three.mul(one_I_three.mul(one_I_three)), "1/27");
eq(one_I_zero.mul(one_I_zero).mul(one_I_zero), "NaN");
eq(one_I_zero.mul(one_I_zero.mul(one_I_zero)), "NaN");
eq(one_I_two.mul(one_I_three).mul(one_I_four), "1/24");
eq(one_I_two.mul(one_I_three.mul(one_I_four)), "1/24");
}
public void testDivSimple()
{
eq(zero.div(zero), "NaN");
eq(zero.div(one), "0");
eq(one.div(zero), "NaN");
eq(one.div(one), "1");
eq(one.div(negOne), "-1");
eq(one.div(two), "1/2");
eq(two.div(two), "1");
}
public void testDivComplex()
{
eq(one_I_two.div(zero), "NaN");
eq(one_I_two.div(one), "1/2");
eq(one_I_two.div(one_I_two), "1");
eq(one_I_two.div(one_I_three), "3/2");
eq(one_I_two.div(negOne), "-1/2");
eq(one_I_two.div(two), "1/4");
eq(one_I_two.div(two_I_three), "3/4");
eq(one_I_two.div(three_I_four), "2/3");
eq(one_I_three.div(zero), "NaN");
eq(one_I_three.div(two_I_three), "1/2");
eq(one_I_three.div(three_I_four), "4/9");
}
public void testDivImproper()
{
eq(three_I_two.div(one_I_two), "3");
eq(three_I_two.div(one_I_three), "9/2");
eq(three_I_two.div(three_I_two), "1");
}
public void testDivOnNaN()
{
// each test case (addend, augend) drawn from the set
// ratnums x ratnans
for (int i = 0; i < ratnums.Length; i++)
{
for (int j = 0; j < ratnans.Length; j++)
{
eq(ratnums[i].div(ratnans[j]), "NaN");
eq(ratnans[j].div(ratnums[i]), "NaN");
}
}
}
public void testDivTransitively()
{
// (same note as in testSubTransitively re: transitivity property)
eq(one.div(one).div(one), "1");
eq(one.div(one.div(one)), "1");
eq(zero.div(zero).div(zero), "NaN");
eq(zero.div(zero.div(zero)), "NaN");
eq(one.div(two).div(three), "1/6");
eq(one.div(two.div(three)), "3/2");
eq(one_I_three.div(one_I_three).div(one_I_three), "3");
eq(one_I_three.div(one_I_three.div(one_I_three)), "1/3");
eq(one_I_zero.div(one_I_zero).div(one_I_zero), "NaN");
eq(one_I_zero.div(one_I_zero.div(one_I_zero)), "NaN");
eq(one_I_two.div(one_I_three).div(one_I_four), "6");
eq(one_I_two.div(one_I_three.div(one_I_four)), "3/8");
}
public void testNegate()
{
eq(zero.negate(), "0");
eq(one.negate(), "-1");
eq(negOne.negate(), "1");
eq(two.negate(), "-2");
eq(three.negate(), "-3");
eq(one_I_two.negate(), "-1/2");
eq(one_I_three.negate(), "-1/3");
eq(one_I_four.negate(), "-1/4");
eq(two_I_three.negate(), "-2/3");
eq(three_I_four.negate(), "-3/4");
eq(three_I_two.negate(), "-3/2");
eq(one_I_zero.negate(), "NaN");
eq(negOne_I_zero.negate(), "NaN");
eq(hundred_I_zero.negate(), "NaN");
}
// helper function, "decode-and-check"
private void decChk(string s, RatNum expected)
{
eq(RatNum.parse(s), expected.unparse());
}
public void testParse()
{
decChk("0", zero);
decChk("1", one);
decChk("1/1", one);
decChk("2/2", one);
decChk("-1/-1", one);
decChk("-1", negOne);
decChk("1/-1", negOne);
decChk("-3/3", negOne);
decChk("2", two);
decChk("2/1", two);
decChk("-4/-2", two);
decChk("1/2", one_I_two);
decChk("2/4", one_I_two);
decChk("3/2", three_I_two);
decChk("-6/-4", three_I_two);
decChk("5/6", five_I_six);
decChk("6/5", six_I_five);
decChk("8/7", eight_I_seven);
decChk("NaN", one_I_zero);
decChk("NaN", negOne_I_zero);
}
public void testEqualsReflexive()
{
for (int i = 0; i < ratnums.Length; i++)
{
assertTrue(ratnums[i].Equals(ratnums[i]));
}
}
public void testEquals()
{
assertTrue(one.Equals(one));
assertTrue(one.add(one).Equals(two));
assertTrue(one_I_two.Equals(one.div(two)));
assertTrue(three_I_two.Equals(three.div(two)));
assertTrue(five_I_six.Equals(one_I_two.add(one_I_three)));
assertTrue(six_I_five.Equals(six_I_five));
assertTrue(one_I_zero.Equals(one_I_zero));
assertTrue(one_I_zero.Equals(negOne_I_zero));
assertTrue(one_I_zero.Equals(hundred_I_zero));
assertTrue(two_I_zero.Equals(hundred_I_zero));
assertTrue(negTwo_I_zero.Equals(hundred_I_zero));
assertTrue(negTwo_I_zero.Equals(nine_I_zero));
assertTrue(!one.Equals(zero));
assertTrue(!zero.Equals(one));
assertTrue(!one.Equals(two));
assertTrue(!two.Equals(one));
assertTrue(!one.Equals(negOne));
assertTrue(!negOne.Equals(one));
assertTrue(!one.Equals(one_I_two));
assertTrue(!one_I_two.Equals(one));
assertTrue(!one.Equals(three_I_two));
assertTrue(!three_I_two.Equals(one));
assertTrue(!five_I_six.Equals(one));
assertTrue(!six_I_five.Equals(five_I_six));
}
private void assertGreater(RatNum larger, RatNum smaller)
{
assertTrue(larger.CompareTo(smaller) > 0);
assertTrue(smaller.CompareTo(larger) < 0);
}
public void testCompareToReflexive()
{
// reflexivitiy
for (int i = 0; i < ratnums.Length; i++)
{
assertTrue(ratnums[i].CompareTo(ratnums[i]) == 0);
}
}
public void testCompareToNonFract()
{
assertGreater(one, zero);
assertGreater(one, negOne);
assertGreater(two, one);
assertGreater(two, zero);
assertGreater(zero, negOne);
}
public void testCompareToFract()
{
assertGreater(one, one_I_two);
assertGreater(two, one_I_three);
assertGreater(one, two_I_three);
assertGreater(two, two_I_three);
assertGreater(one_I_two, zero);
assertGreater(one_I_two, negOne);
assertGreater(one_I_two, negOne_I_two);
assertGreater(zero, negOne_I_two);
}
public void testCompareToNaNs()
{
for (int i = 0; i < ratnans.Length; i++)
{
for (int j = 0; j < ratnans.Length; j++)
{
assertTrue(ratnans[i].CompareTo(ratnans[j]) == 0);
}
for (int j = 0; j < ratnanans.Length; j++)
{
assertGreater(ratnans[i], ratnanans[j]);
}
}
}
private void assertPos(RatNum n)
{
assertTrue(n.isPositive());
assertTrue(!n.isNegative());
}
private void assertNeg(RatNum n)
{
assertTrue(n.isNegative());
assertTrue(!n.isPositive());
}
public void testIsPosAndIsNeg()
{
assertTrue(!zero.isPositive());
assertTrue(!zero.isNegative());
assertPos(one);
assertNeg(negOne);
assertPos(two);
assertPos(three);
assertPos(one_I_two);
assertPos(one_I_three);
assertPos(one_I_four);
assertPos(two_I_three);
assertPos(three_I_four);
assertNeg(negOne_I_two);
assertPos(three_I_two);
assertPos(one_I_zero);
assertPos(negOne_I_zero); // non-intuitive; see spec
assertPos(hundred_I_zero);
}
public void testIsNaN()
{
for (int i = 0; i < ratnans.Length; i++)
{
assertTrue(ratnans[i].isNaN());
}
for (int i = 0; i < ratnanans.Length; i++)
{
assertTrue(!ratnanans[i].isNaN());
}
}
public void testToString()
{
assertTrue((five_I_six.toString()).Equals("RatNum<numer:5 denom:6>"));
assertTrue((six_I_five.toString()).Equals("RatNum<numer:6 denom:5>"));
assertTrue((three_I_four.toString()).Equals("RatNum<numer:3 denom:4>"));
}
// KJD: Mimic Junit Functionality
public void assertTrue(bool a)
{
if (!a)
{
throw new System.Exception("Uhoh");
}
}
// KJD: Mimic Junit Functionality
public void assertEquals(object a, object b)
{
assertTrue(a.Equals(b));
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using Lucene.Net.Support;
using NUnit.Framework;
using LuceneTestCase = Lucene.Net.Util.LuceneTestCase;
using _TestUtil = Lucene.Net.Util._TestUtil;
namespace Lucene.Net.Store
{
[TestFixture]
public class TestDirectory:LuceneTestCase
{
[Test]
public virtual void TestDetectClose()
{
Directory dir = new RAMDirectory();
dir.Close();
Assert.Throws<AlreadyClosedException>(() => dir.CreateOutput("test"), "did not hit expected exception");
dir = FSDirectory.Open(new System.IO.DirectoryInfo(AppSettings.Get("tempDir", System.IO.Path.GetTempPath())));
dir.Close();
Assert.Throws<AlreadyClosedException>(() => dir.CreateOutput("test"), "did not hit expected exception");
}
// Test that different instances of FSDirectory can coexist on the same
// path, can read, write, and lock files.
[Test]
public virtual void TestDirectInstantiation()
{
System.IO.DirectoryInfo path = new System.IO.DirectoryInfo(AppSettings.Get("tempDir", System.IO.Path.GetTempPath()));
int sz = 2;
Directory[] dirs = new Directory[sz];
dirs[0] = new SimpleFSDirectory(path, null);
// dirs[1] = new NIOFSDirectory(path, null);
System.Console.WriteLine("Skipping NIOFSDirectory() test under Lucene.Net");
dirs[1] = new MMapDirectory(path, null);
for (int i = 0; i < sz; i++)
{
Directory dir = dirs[i];
dir.EnsureOpen();
System.String fname = "foo." + i;
System.String lockname = "foo" + i + ".lck";
IndexOutput out_Renamed = dir.CreateOutput(fname);
out_Renamed.WriteByte((byte) i);
out_Renamed.Close();
for (int j = 0; j < sz; j++)
{
Directory d2 = dirs[j];
d2.EnsureOpen();
Assert.IsTrue(d2.FileExists(fname));
Assert.AreEqual(1, d2.FileLength(fname));
// don't test read on MMapDirectory, since it can't really be
// closed and will cause a failure to delete the file.
if (d2 is MMapDirectory)
continue;
IndexInput input = d2.OpenInput(fname);
Assert.AreEqual((byte) i, input.ReadByte());
input.Close();
}
// delete with a different dir
dirs[(i + 1) % sz].DeleteFile(fname);
for (int j = 0; j < sz; j++)
{
Directory d2 = dirs[j];
Assert.IsFalse(d2.FileExists(fname));
}
Lock lock_Renamed = dir.MakeLock(lockname);
Assert.IsTrue(lock_Renamed.Obtain());
for (int j = 0; j < sz; j++)
{
Directory d2 = dirs[j];
Lock lock2 = d2.MakeLock(lockname);
try
{
Assert.IsFalse(lock2.Obtain(1));
}
catch (LockObtainFailedException)
{
// OK
}
}
lock_Renamed.Release();
// now lock with different dir
lock_Renamed = dirs[(i + 1) % sz].MakeLock(lockname);
Assert.IsTrue(lock_Renamed.Obtain());
lock_Renamed.Release();
}
for (int i = 0; i < sz; i++)
{
Directory dir = dirs[i];
dir.EnsureOpen();
dir.Close();
Assert.IsFalse(dir.isOpen_ForNUnit);
}
}
// LUCENE-1464
[Test]
public virtual void TestDontCreate()
{
System.IO.DirectoryInfo path = new System.IO.DirectoryInfo(System.IO.Path.Combine(AppSettings.Get("tempDir", ""), "doesnotexist"));
try
{
bool tmpBool;
if (System.IO.File.Exists(path.FullName))
tmpBool = true;
else
tmpBool = System.IO.Directory.Exists(path.FullName);
Assert.IsTrue(!tmpBool);
Directory dir = new SimpleFSDirectory(path, null);
bool tmpBool2;
if (System.IO.File.Exists(path.FullName))
tmpBool2 = true;
else
tmpBool2 = System.IO.Directory.Exists(path.FullName);
Assert.IsTrue(!tmpBool2);
dir.Close();
}
finally
{
_TestUtil.RmDir(path);
}
}
// LUCENE-1468
[Test]
public virtual void TestRAMDirectoryFilter()
{
CheckDirectoryFilter(new RAMDirectory());
}
// LUCENE-1468
[Test]
public virtual void TestFSDirectoryFilter()
{
CheckDirectoryFilter(FSDirectory.Open(new System.IO.DirectoryInfo("test")));
}
// LUCENE-1468
private void CheckDirectoryFilter(Directory dir)
{
System.String name = "file";
try
{
dir.CreateOutput(name).Close();
Assert.IsTrue(dir.FileExists(name));
Assert.IsTrue(new System.Collections.ArrayList(dir.ListAll()).Contains(name));
}
finally
{
dir.Close();
}
}
// LUCENE-1468
[Test]
public virtual void TestCopySubdir()
{
System.IO.DirectoryInfo path = new System.IO.DirectoryInfo(System.IO.Path.Combine(AppSettings.Get("tempDir", ""), "testsubdir"));
try
{
System.IO.Directory.CreateDirectory(path.FullName);
System.IO.Directory.CreateDirectory(new System.IO.DirectoryInfo(System.IO.Path.Combine(path.FullName, "subdir")).FullName);
Directory fsDir = new SimpleFSDirectory(path, null);
Assert.AreEqual(0, new RAMDirectory(fsDir).ListAll().Length);
}
finally
{
_TestUtil.RmDir(path);
}
}
// LUCENE-1468
[Test]
public virtual void TestNotDirectory()
{
System.IO.DirectoryInfo path = new System.IO.DirectoryInfo(System.IO.Path.Combine(AppSettings.Get("tempDir", ""), "testnotdir"));
Directory fsDir = new SimpleFSDirectory(path, null);
try
{
IndexOutput out_Renamed = fsDir.CreateOutput("afile");
out_Renamed.Close();
Assert.IsTrue(fsDir.FileExists("afile"));
Assert.Throws<NoSuchDirectoryException>(
() =>
new SimpleFSDirectory(new System.IO.DirectoryInfo(System.IO.Path.Combine(path.FullName, "afile")), null),
"did not hit expected exception");
}
finally
{
fsDir.Close();
_TestUtil.RmDir(path);
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.IO;
using System.Security.Cryptography.X509Certificates;
using Microsoft.Protocols.TestTools.StackSdk.Security.Sspi;
namespace Microsoft.Protocols.TestTools.StackSdk.RemoteDesktop.Rdpbcgr
{
/// <summary>
/// Performs enhanced RDP security transport. The External Security Protocol is CredSSP.
/// </summary>
internal class RdpbcgrServerCredSspStream : Stream
{
#region Member variables
/// <summary>
/// Indicates whether the instance is disposed
/// </summary>
private bool disposed = false;
/// <summary>
/// Maximum buffer size
/// </summary>
private const int MaxBufferSize = 102400;
/// <summary>
/// A read block size
/// </summary>
//private const int BlockSize = 1500;
private const int BlockSize = 5500;
/// <summary>
/// Underlying network stream
/// </summary>
private Stream serverStream;
/// <summary>
/// The buffer that contains decrypted data
/// </summary>
private byte[] decryptedBuffer;
/// <summary>
/// The buffer pooled for decryption. There may be extra data left when decrypting a
/// sequence of bytes, the extra data is then pooled in this buffer for next decryption
/// </summary>
private byte[] pooledBuffer;
/// <summary>
/// Start offset that contains decrypted data in buffer
/// </summary>
private int startIndex;
/// <summary>
/// End offset that contains decrypted data in buffer
/// </summary>
private int endIndex;
/// <summary>
/// Indicates whether CredSSP has been established
/// </summary>
private bool isAuthenticated;
/// <summary>
/// Client credential for authentication
/// </summary>
private CertificateCredential credential;
/// <summary>
/// Client context for authentication
/// </summary>
private SspiServerSecurityContext context;
/// <summary>
/// Context attribute used for CredSsp
/// </summary>
private const ServerSecurityContextAttribute attribute =
ServerSecurityContextAttribute.Delegate
| ServerSecurityContextAttribute.ReplayDetect
| ServerSecurityContextAttribute.SequenceDetect
| ServerSecurityContextAttribute.Confidentiality
| ServerSecurityContextAttribute.AllocMemory
| ServerSecurityContextAttribute.ExtendedError
| ServerSecurityContextAttribute.Stream;
/// <summary>
/// Server principal to be logged on
/// </summary>
private string serverPrincipal;
#endregion Member variables
#region Helper methods
/// <summary>
/// Checks if the decrypted buffer is empty
/// </summary>
/// <returns></returns>
private bool IsBufferEmpty()
{
return (this.startIndex == this.endIndex);
}
/// <summary>
/// Checks if there's enough buffer for reading
/// </summary>
/// <param name="count">The size to read</param>
/// <returns>True if there's enough buffer for reading, false otherwise</returns>
private bool CheckAvailableCount(int count)
{
return (this.startIndex + count < this.endIndex);
}
/// <summary>
/// Closes the underlying network stream
/// </summary>
private void CloseServerStream()
{
if (this.serverStream != null)
{
serverStream.Close();
serverStream = null;
}
}
#endregion Helper methods
#region Overriden properties
/// <summary>
/// Indicates whether the current stream supports reading.
/// </summary>
public override bool CanRead
{
get
{
return serverStream.CanRead;
}
}
/// <summary>
/// Indicates whether the current stream supports seeking.
/// CredSspStream does not support seeking.
/// </summary>
public override bool CanSeek
{
get
{
return serverStream.CanSeek;
}
}
/// <summary>
/// Indicates whether the current stream supports writing.
/// </summary>
public override bool CanWrite
{
get
{
return serverStream.CanWrite;
}
}
/// <summary>
/// Length of bytes in stream.
/// </summary>
public override long Length
{
get
{
return serverStream.Length;
}
}
/// <summary>
/// The current position within the stream.
/// </summary>
public override long Position
{
get
{
return serverStream.Position;
}
set
{
serverStream.Position = value;
}
}
#endregion Overriden properties
#region Public methods
/// <summary>
/// Constructor
/// </summary>
/// <param name="server">The underlying network stream</param>
/// <param name="principal">Server principal to be logged on, prefixed with "TERMSRV/"</param>
public RdpbcgrServerCredSspStream(Stream server, string principal)
{
if (server == null)
{
throw new ArgumentNullException("server");
}
if (principal == null)
{
throw new ArgumentNullException("principal");
}
this.serverStream = server;
this.serverPrincipal = principal;
this.decryptedBuffer = new byte[MaxBufferSize];
this.pooledBuffer = null;
this.startIndex = 0;
this.endIndex = 0;
this.isAuthenticated = false;
}
/// <summary>
/// Performs CredSSP authentication.
/// </summary>
/// <param name="x509Cert">The certificate used by TLS.</param>
/// <exception cref="IOException">Raised when attempting to read from/write to the remote connection which
/// has been closed</exception>
/// <exception cref="EndOfStreamException">Raised when the username or password doesn't match or authentication
/// fails</exception>
public void Authenticate(X509Certificate x509Cert)
{
// Authenticated already, do nothing
if (isAuthenticated)
{
return;
}
credential = new CertificateCredential(x509Cert);
byte[] receivedBuffer = new byte[MaxBufferSize];
int bytesReceived = 0;
// Dispose the context as it may be timed out
if (context != null)
{
context.Dispose();
}
context = new SspiServerSecurityContext(
SecurityPackageType.CredSsp,
credential,
serverPrincipal,
attribute,
SecurityTargetDataRepresentation.SecurityNativeDrep);
// Get first token
byte[] token = context.Token;
// Credssp handshake
while (context.NeedContinueProcessing)
{
// Get handshake resopnse
bytesReceived = serverStream.Read(receivedBuffer, 0, receivedBuffer.Length);
// The remote connection has been closed
if (bytesReceived == 0)
{
throw new EndOfStreamException("Authentication failed: remote connection has been closed.");
}
byte[] inToken = new byte[bytesReceived];
Array.Copy(receivedBuffer, inToken, bytesReceived);
// Get next token from response
context.Accept(inToken);
token = context.Token;
if (token != null)
{
// Send handshake request
serverStream.Write(token, 0, token.Length);
}
}
isAuthenticated = true;
}
/// <summary>
/// Reads a sequence of bytes from the current stream.
/// </summary>
/// <param name="buffer">The buffer that contains decrypted data.</param>
/// <param name="offset">The offset in buffer at which to begin storing the decrypted data.</param>
/// <param name="count">The maximum number of bytes to get.</param>
/// <exception cref="ArgumentOutOfRangeException">Raised when buffer or the internal decryptedBuffer doesn't
/// contain enough space
/// </exception>
/// <exception cref="IOException">Raised when attempting to read from/write to a remote connection which
/// has been closed</exception>
/// <returns>The actual number of bytes read into the buffer. Could be less than count</returns>
public override int Read(byte[] buffer, int offset, int count)
{
if (offset > buffer.Length - 1)
{
throw new ArgumentOutOfRangeException("offset");
}
if (offset + count > buffer.Length)
{
throw new ArgumentOutOfRangeException("count");
}
if (!IsBufferEmpty())
{
if (CheckAvailableCount(count))
{
Array.Copy(decryptedBuffer, this.startIndex, buffer, offset, count);
this.startIndex += count;
return count;
}
else
{
int sizeRead = this.endIndex - this.startIndex;
Array.Copy(decryptedBuffer, this.startIndex, buffer, offset, sizeRead);
// All data is read, reset indices
this.startIndex = 0;
this.endIndex = 0;
return sizeRead;
}
}
// The buffer is empty, read data from network stream
byte[] recvBuffer = new byte[BlockSize];
byte[] encryptedMsg = null;
int bytesReceived = 0;
byte[] decryptedMsg = null;
bool triedPooledBuffer = false;
while (decryptedMsg == null)
{
if (!triedPooledBuffer && this.pooledBuffer != null && this.pooledBuffer.Length > 0)
{// try to decrypte the data in this.pooledBuffer firstly.
encryptedMsg = new byte[this.pooledBuffer.Length];
Array.Copy(this.pooledBuffer, encryptedMsg, encryptedMsg.Length);
this.pooledBuffer = null;
triedPooledBuffer = true;
}
else
{
// decryptedMsg being null indicates incomplete data, so we continue reading and decrypting.
bytesReceived = serverStream.Read(recvBuffer, 0, recvBuffer.Length);
// The connection has been closed by remote server
if (bytesReceived == 0)
{
return 0;
}
// There's pooled data, concatenate the buffer together for decryption
if (this.pooledBuffer != null && this.pooledBuffer.Length > 0)
{
encryptedMsg = new byte[this.pooledBuffer.Length + bytesReceived];
Array.Copy(this.pooledBuffer, encryptedMsg, this.pooledBuffer.Length);
Array.Copy(recvBuffer, 0, encryptedMsg, this.pooledBuffer.Length, bytesReceived);
this.pooledBuffer = null;
}
else
{
encryptedMsg = new byte[bytesReceived];
Array.Copy(recvBuffer, encryptedMsg, bytesReceived);
}
}
byte[] extraData = null;
// Do decryption
SecurityBuffer[] securityBuffers = new SecurityBuffer[]
{
new SecurityBuffer(SecurityBufferType.Data, encryptedMsg),
new SecurityBuffer(SecurityBufferType.Empty, null),
new SecurityBuffer(SecurityBufferType.Empty, null),
new SecurityBuffer(SecurityBufferType.Empty, null)
};
context.Decrypt(securityBuffers);
for (int i = 0; i < securityBuffers.Length; i++)
{
if (securityBuffers[i].BufferType == SecurityBufferType.Data)
{
decryptedMsg = ArrayUtility.ConcatenateArrays(decryptedMsg, securityBuffers[i].Buffer);
}
else if (securityBuffers[i].BufferType == SecurityBufferType.Extra)
{
extraData = ArrayUtility.ConcatenateArrays(extraData, securityBuffers[i].Buffer);
}
}
if (extraData != null && extraData.Length > 0)
{
this.pooledBuffer = extraData;
}
}
Array.Copy(decryptedMsg, 0, this.decryptedBuffer, this.endIndex, decryptedMsg.Length);
this.endIndex += decryptedMsg.Length;
return Read(buffer, offset, count);
}
/// <summary>
/// Writes a sequence of bytes to the current stream. The data is encrypted first before sending out.
/// </summary>
/// <param name="buffer">The buffer to be sent.</param>
/// <param name="offset">The offset in buffer at which to begin writing to the stream.</param>
/// <param name="count">The number of bytes to be written.</param>
/// <exception cref="IOException">Raised when attempting to read from/write to a remote connection which
/// has been closed</exception>
/// <exception cref="ArgumentOutOfRangeException">Raised when the offset incremented by count exceeds
/// the length of buffer</exception>
public override void Write(byte[] buffer, int offset, int count)
{
if (offset > buffer.Length - 1)
{
throw new ArgumentOutOfRangeException("offset");
}
if (offset + count > buffer.Length)
{
throw new ArgumentOutOfRangeException("count");
}
byte[] outBuffer = new byte[count];
Array.Copy(buffer, offset, outBuffer, 0, count);
// Encrypt message
SecurityPackageContextStreamSizes streamSizes =
(SecurityPackageContextStreamSizes)context.QueryContextAttributes("SECPKG_ATTR_STREAM_SIZES");
SecurityBuffer messageBuffer = new SecurityBuffer(SecurityBufferType.Data, buffer);
SecurityBuffer headerBuffer = new SecurityBuffer(
SecurityBufferType.StreamHeader,
new byte[streamSizes.Header]);
SecurityBuffer trailerBuffer = new SecurityBuffer(
SecurityBufferType.StreamTrailer,
new byte[streamSizes.Trailer]);
SecurityBuffer emptyBuffer = new SecurityBuffer(SecurityBufferType.Empty, null);
context.Encrypt(headerBuffer, messageBuffer, trailerBuffer, emptyBuffer);
byte[] encryptedMsg = ArrayUtility.ConcatenateArrays(
headerBuffer.Buffer,
messageBuffer.Buffer,
trailerBuffer.Buffer);
serverStream.Write(encryptedMsg, 0, encryptedMsg.Length);
}
/// <summary>
/// clears all buffers for this stream and causes any buffered data to be written to the underlying device.
/// </summary>
/// <returns></returns>
public override void Flush()
{
serverStream.Flush();
}
/// <summary>
/// Sets the position within the current stream.
/// </summary>
/// <param name="offset">A byte offset relative to the origin parameter.</param>
/// <param name="origin">A value of type System.IO.SeekOrigin indicating the reference point used
/// to obtain the new position.</param>
/// <returns>The new position within the current stream.</returns>
/// <exception>NotSupportedException</exception>
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotSupportedException("This is not supported for CredSspStream.");
}
/// <summary>
/// Sets the length of the current stream.
/// </summary>
/// <param name="value">The desired length of the current stream in bytes.</param>
/// <returns>The new position within the current stream.</returns>
/// <exception>NotSupportedException</exception>
public override void SetLength(long value)
{
throw new NotSupportedException("This is not supported for CredSspStream.");
}
#endregion Public methods
#region Implements dispose pattern
/// <summary>
/// Implements IDisposable interface(from NetworkStream)
/// </summary>
/// <param name="disposing">Indicates if there's managed resource to release</param>
protected override void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing)
{
// Clean managed resource
CloseServerStream();
if (context != null)
{
context.Dispose();
context = null;
}
}
this.disposed = true;
this.isAuthenticated = false;
}
base.Dispose(disposing);
}
/// <summary>
/// Overrides Close method of NetworkStream
/// </summary>
public override void Close()
{
CloseServerStream();
}
/// <summary>
/// Finalizer, cleans up unmanaged resources
/// </summary>
~RdpbcgrServerCredSspStream()
{
this.Dispose(false);
}
#endregion Implements dispose pattern
}
}
| |
namespace Krystals4Application
{
partial class NewModulationDialog
{
/// <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.CompulsoryTextlabel = new System.Windows.Forms.Label();
this.YInputFilenameLabel = new System.Windows.Forms.Label();
this.XInputFilenameLabel = new System.Windows.Forms.Label();
this.ModulatorFilenameLabel = new System.Windows.Forms.Label();
this.InputValuesLabel = new System.Windows.Forms.Label();
this.DensityInputLabel = new System.Windows.Forms.Label();
this.ModulatorLabel = new System.Windows.Forms.Label();
this.SetInputValuesButton = new System.Windows.Forms.Button();
this.SetDensityInputButton = new System.Windows.Forms.Button();
this.CancelBtn = new System.Windows.Forms.Button();
this.OKBtn = new System.Windows.Forms.Button();
this.SetInputFieldButton = new System.Windows.Forms.Button();
this.LoadKrystalButton = new System.Windows.Forms.Button();
this.label1 = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// CompulsoryTextlabel
//
this.CompulsoryTextlabel.AutoSize = true;
this.CompulsoryTextlabel.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.CompulsoryTextlabel.ForeColor = System.Drawing.Color.SlateGray;
this.CompulsoryTextlabel.Location = new System.Drawing.Point(29, 157);
this.CompulsoryTextlabel.Name = "CompulsoryTextlabel";
this.CompulsoryTextlabel.Size = new System.Drawing.Size(166, 13);
this.CompulsoryTextlabel.TabIndex = 9;
this.CompulsoryTextlabel.Text = "* the above two fields must be set";
//
// YInputFilenameLabel
//
this.YInputFilenameLabel.AutoSize = true;
this.YInputFilenameLabel.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.YInputFilenameLabel.Location = new System.Drawing.Point(82, 128);
this.YInputFilenameLabel.Name = "YInputFilenameLabel";
this.YInputFilenameLabel.Size = new System.Drawing.Size(77, 13);
this.YInputFilenameLabel.TabIndex = 8;
this.YInputFilenameLabel.Text = "<unassigned>*";
//
// XInputFilenameLabel
//
this.XInputFilenameLabel.AutoSize = true;
this.XInputFilenameLabel.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.XInputFilenameLabel.Location = new System.Drawing.Point(82, 97);
this.XInputFilenameLabel.Name = "XInputFilenameLabel";
this.XInputFilenameLabel.Size = new System.Drawing.Size(77, 13);
this.XInputFilenameLabel.TabIndex = 6;
this.XInputFilenameLabel.Text = "<unassigned>*";
//
// ModulatorFilenameLabel
//
this.ModulatorFilenameLabel.AutoSize = true;
this.ModulatorFilenameLabel.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.ModulatorFilenameLabel.Location = new System.Drawing.Point(86, 199);
this.ModulatorFilenameLabel.Name = "ModulatorFilenameLabel";
this.ModulatorFilenameLabel.Size = new System.Drawing.Size(104, 13);
this.ModulatorFilenameLabel.TabIndex = 11;
this.ModulatorFilenameLabel.Text = "to be edited (default)";
//
// InputValuesLabel
//
this.InputValuesLabel.AutoSize = true;
this.InputValuesLabel.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.InputValuesLabel.Location = new System.Drawing.Point(29, 128);
this.InputValuesLabel.Name = "InputValuesLabel";
this.InputValuesLabel.Size = new System.Drawing.Size(43, 13);
this.InputValuesLabel.TabIndex = 7;
this.InputValuesLabel.Text = "Y input:";
//
// DensityInputLabel
//
this.DensityInputLabel.AutoSize = true;
this.DensityInputLabel.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.DensityInputLabel.Location = new System.Drawing.Point(29, 97);
this.DensityInputLabel.Name = "DensityInputLabel";
this.DensityInputLabel.Size = new System.Drawing.Size(43, 13);
this.DensityInputLabel.TabIndex = 5;
this.DensityInputLabel.Text = "X input:";
//
// ModulatorLabel
//
this.ModulatorLabel.AutoSize = true;
this.ModulatorLabel.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.ModulatorLabel.Location = new System.Drawing.Point(29, 199);
this.ModulatorLabel.Name = "ModulatorLabel";
this.ModulatorLabel.Size = new System.Drawing.Size(57, 13);
this.ModulatorLabel.TabIndex = 10;
this.ModulatorLabel.Text = "Modulator:";
//
// SetInputValuesButton
//
this.SetInputValuesButton.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.SetInputValuesButton.Location = new System.Drawing.Point(217, 123);
this.SetInputValuesButton.Name = "SetInputValuesButton";
this.SetInputValuesButton.Size = new System.Drawing.Size(60, 23);
this.SetInputValuesButton.TabIndex = 1;
this.SetInputValuesButton.Text = "Set...";
this.SetInputValuesButton.UseVisualStyleBackColor = true;
this.SetInputValuesButton.Click += new System.EventHandler(this.SetYInputButton_Click);
//
// SetDensityInputButton
//
this.SetDensityInputButton.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.SetDensityInputButton.Location = new System.Drawing.Point(217, 92);
this.SetDensityInputButton.Name = "SetDensityInputButton";
this.SetDensityInputButton.Size = new System.Drawing.Size(60, 23);
this.SetDensityInputButton.TabIndex = 0;
this.SetDensityInputButton.Text = "Set...";
this.SetDensityInputButton.UseVisualStyleBackColor = true;
this.SetDensityInputButton.Click += new System.EventHandler(this.SetXInputButton_Click);
//
// CancelBtn
//
this.CancelBtn.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.CancelBtn.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.CancelBtn.Location = new System.Drawing.Point(202, 244);
this.CancelBtn.Name = "CancelBtn";
this.CancelBtn.Size = new System.Drawing.Size(75, 23);
this.CancelBtn.TabIndex = 4;
this.CancelBtn.Text = "Cancel";
this.CancelBtn.UseVisualStyleBackColor = true;
this.CancelBtn.Click += new System.EventHandler(this.CancelBtn_Click);
//
// OKBtn
//
this.OKBtn.DialogResult = System.Windows.Forms.DialogResult.OK;
this.OKBtn.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.OKBtn.Location = new System.Drawing.Point(102, 244);
this.OKBtn.Name = "OKBtn";
this.OKBtn.Size = new System.Drawing.Size(75, 23);
this.OKBtn.TabIndex = 3;
this.OKBtn.Text = "OK";
this.OKBtn.UseVisualStyleBackColor = true;
this.OKBtn.Click += new System.EventHandler(this.OKBtn_Click);
//
// SetInputFieldButton
//
this.SetInputFieldButton.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.SetInputFieldButton.Location = new System.Drawing.Point(217, 194);
this.SetInputFieldButton.Name = "SetInputFieldButton";
this.SetInputFieldButton.Size = new System.Drawing.Size(60, 23);
this.SetInputFieldButton.TabIndex = 2;
this.SetInputFieldButton.Text = "Set...";
this.SetInputFieldButton.UseVisualStyleBackColor = true;
this.SetInputFieldButton.Click += new System.EventHandler(this.SetModulatorButton_Click);
//
// LoadKrystalButton
//
this.LoadKrystalButton.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.LoadKrystalButton.Location = new System.Drawing.Point(28, 21);
this.LoadKrystalButton.Name = "LoadKrystalButton";
this.LoadKrystalButton.Size = new System.Drawing.Size(248, 23);
this.LoadKrystalButton.TabIndex = 12;
this.LoadKrystalButton.Text = "Load Existing Modulation Krystal...";
this.LoadKrystalButton.UseVisualStyleBackColor = true;
this.LoadKrystalButton.Click += new System.EventHandler(this.OpenKrystalButton_Click);
//
// label1
//
this.label1.AutoSize = true;
this.label1.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.label1.ForeColor = System.Drawing.Color.SlateGray;
this.label1.Location = new System.Drawing.Point(28, 49);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(268, 26);
this.label1.TabIndex = 13;
this.label1.Text = "Use the above button to set the values of the three\r\nfields below, and/or use the" +
" \'Set...\' buttons individually. ";
//
// NewModulationDialog
//
this.AcceptButton = this.OKBtn;
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.SystemColors.ControlLight;
this.CancelButton = this.CancelBtn;
this.ClientSize = new System.Drawing.Size(307, 292);
this.Controls.Add(this.label1);
this.Controls.Add(this.LoadKrystalButton);
this.Controls.Add(this.CompulsoryTextlabel);
this.Controls.Add(this.YInputFilenameLabel);
this.Controls.Add(this.XInputFilenameLabel);
this.Controls.Add(this.ModulatorFilenameLabel);
this.Controls.Add(this.InputValuesLabel);
this.Controls.Add(this.DensityInputLabel);
this.Controls.Add(this.ModulatorLabel);
this.Controls.Add(this.SetInputValuesButton);
this.Controls.Add(this.SetDensityInputButton);
this.Controls.Add(this.CancelBtn);
this.Controls.Add(this.OKBtn);
this.Controls.Add(this.SetInputFieldButton);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "NewModulationDialog";
this.ShowIcon = false;
this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "new modulation";
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Label CompulsoryTextlabel;
private System.Windows.Forms.Label YInputFilenameLabel;
private System.Windows.Forms.Label XInputFilenameLabel;
private System.Windows.Forms.Label ModulatorFilenameLabel;
private System.Windows.Forms.Label InputValuesLabel;
private System.Windows.Forms.Label DensityInputLabel;
private System.Windows.Forms.Label ModulatorLabel;
private System.Windows.Forms.Button SetInputValuesButton;
private System.Windows.Forms.Button SetDensityInputButton;
private System.Windows.Forms.Button CancelBtn;
private System.Windows.Forms.Button OKBtn;
private System.Windows.Forms.Button SetInputFieldButton;
private System.Windows.Forms.Button LoadKrystalButton;
private System.Windows.Forms.Label label1;
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#region Assembly System.Windows.Forms.dll, v4.0.30319
// C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0\System.Windows.Forms.dll
#endregion
using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Design;
using System.Runtime.InteropServices;
using System.Diagnostics.Contracts;
namespace System.Windows.Forms {
// Summary:
// Displays a hierarchical collection of labeled items, each represented by
// a System.Windows.Forms.TreeNode.
[ComVisible(true)]
[Designer("System.Windows.Forms.Design.TreeViewDesigner, System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")]
//[Docking(DockingBehavior.Ask)]
[DefaultProperty("Nodes")]
[ClassInterface(ClassInterfaceType.AutoDispatch)]
[DefaultEvent("AfterSelect")]
//[SRDescription("DescriptionTreeView")]
public class TreeView : Control {
// Summary:
// Initializes a new instance of the System.Windows.Forms.TreeView class.
//public TreeView();
//
// Returns:
// A System.Drawing.Color that represents the background color of the control.
// The default is the value of the System.Windows.Forms.Control.DefaultBackColor
// property.
//public override Color BackColor { get { return default(); } set { } }
//
// Summary:
// Gets or set the background image for the System.Windows.Forms.TreeView control.
//
// Returns:
// The System.Drawing.Image that is the background image for the System.Windows.Forms.TreeView
// control.
[EditorBrowsable(EditorBrowsableState.Never)]
[Browsable(false)]
//public override Image BackgroundImage { get { return default(); } set { } }
//
// Summary:
// Gets or sets the layout of the background image for the System.Windows.Forms.TreeView
// control.
//
// Returns:
// One of the System.Windows.Forms.ImageLayout values. The default is System.Windows.Forms.ImageLayout.Tile.
//[EditorBrowsable(EditorBrowsableState.Never)]
//[Browsable(false)]
//public override ImageLayout BackgroundImageLayout { get { return default(); } set { } }
//
// Summary:
// Gets or sets the border style of the tree view control.
//
// Returns:
// One of the System.Windows.Forms.BorderStyle values. The default is System.Windows.Forms.BorderStyle.Fixed3D.
//
// Exceptions:
// System.ComponentModel.InvalidEnumArgumentException:
// The assigned value is not one of the System.Windows.Forms.BorderStyle values.
//[SRDescription("borderStyleDescr")]
//[DispId(-504)]
//[SRCategory("CatAppearance")]
//public BorderStyle BorderStyle { get { return default(); } set { } }
//
// Summary:
// Gets or sets a value indicating whether check boxes are displayed next to
// the tree nodes in the tree view control.
//
// Returns:
// true if a check box is displayed next to each tree node in the tree view
// control; otherwise, false. The default is false.
//[SRDescription("TreeViewCheckBoxesDescr")]
//[SRCategory("CatAppearance")]
//[DefaultValue(false)]
public bool CheckBoxes { get { return default(bool); } set { } }
//
// Summary:
// Overrides System.Windows.Forms.Control.CreateParams.
//
// Returns:
// A System.Windows.Forms.CreateParams that contains the required creation parameters
// when the handle to the control is created.
//protected override CreateParams CreateParams { get { return default(); } }
//
//
// Returns:
// The default System.Drawing.Size of the control.
//protected override Size DefaultSize { get { return default(); } }
//
// Summary:
// Gets or sets a value indicating whether the control should redraw its surface
// using a secondary buffer. The System.Windows.Forms.TreeView.DoubleBuffered
// property has no effect on the System.Windows.Forms.TreeView control.
//
// Returns:
// true if the control uses a secondary buffer; otherwise, false.
[EditorBrowsable(EditorBrowsableState.Never)]
//protected override bool DoubleBuffered { get { return default(); } set { } }
//
// Summary:
// Gets or sets the mode in which the control is drawn.
//
// Returns:
// One of the System.Windows.Forms.TreeViewDrawMode values. The default is System.Windows.Forms.TreeViewDrawMode.Normal.
//
// Exceptions:
// System.ComponentModel.InvalidEnumArgumentException:
// The property value is not a valid System.Windows.Forms.TreeViewDrawMode value.
//[SRDescription("TreeViewDrawModeDescr")]
//[SRCategory("CatBehavior")]
//public TreeViewDrawMode DrawMode { get { return default(); } set { } }
//
// Summary:
// The current foreground color for this control, which is the color the control
// uses to draw its text.
//
// Returns:
// The foreground System.Drawing.Color of the control. The default is the value
// of the System.Windows.Forms.Control.DefaultForeColor property.
//public override Color ForeColor { get { return default(); } set { } }
//
// Summary:
// Gets or sets a value indicating whether the selection highlight spans the
// width of the tree view control.
//
// Returns:
// true if the selection highlight spans the width of the tree view control;
// otherwise, false. The default is false.
//[SRDescription("TreeViewFullRowSelectDescr")]
//[DefaultValue(false)]
//[SRCategory("CatBehavior")]
public bool FullRowSelect { get { return default(bool); } set { } }
//
// Summary:
// Gets or sets a value indicating whether the selected tree node remains highlighted
// even when the tree view has lost the focus.
//
// Returns:
// true if the selected tree node is not highlighted when the tree view has
// lost the focus; otherwise, false. The default is true.
//[SRDescription("TreeViewHideSelectionDescr")]
//[SRCategory("CatBehavior")]
//[DefaultValue(true)]
public bool HideSelection { get { return default(bool); } set { } }
//
// Summary:
// Gets or sets a value indicating whether a tree node label takes on the appearance
// of a hyperlink as the mouse pointer passes over it.
//
// Returns:
// true if a tree node label takes on the appearance of a hyperlink as the mouse
// pointer passes over it; otherwise, false. The default is false.
[DefaultValue(false)]
//[SRCategory("CatBehavior")]
//[SRDescription("TreeViewHotTrackingDescr")]
public bool HotTracking { get { return default(bool); } set { } }
//
// Summary:
// Gets or sets the image-list index value of the default image that is displayed
// by the tree nodes.
//
// Returns:
// A zero-based index that represents the position of an System.Drawing.Image
// in an System.Windows.Forms.ImageList. The default is zero.
//
// Exceptions:
// System.ArgumentOutOfRangeException:
// The specified index is less than 0.
//[SRCategory("CatBehavior")]
[DefaultValue(-1)]
//[RelatedImageList("ImageList")]
[Localizable(true)]
[RefreshProperties(RefreshProperties.Repaint)]
//[TypeConverter(typeof(NoneExcludedImageIndexConverter))]
[Editor("System.Windows.Forms.Design.ImageIndexEditor, System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", typeof(UITypeEditor))]
//[SRDescription("TreeViewImageIndexDescr")]
public int ImageIndex { get { return default(int); } set { } }
//
// Summary:
// Gets or sets the key of the default image for each node in the System.Windows.Forms.TreeView
// control when it is in an unselected state.
//
// Returns:
// The key of the default image shown for each node System.Windows.Forms.TreeView
// control when the node is in an unselected state.
//[SRCategory("CatBehavior")]
//[RelatedImageList("ImageList")]
[Localizable(true)]
//[TypeConverter(typeof(ImageKeyConverter))]
[Editor("System.Windows.Forms.Design.ImageIndexEditor, System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", typeof(UITypeEditor))]
[DefaultValue("")]
[RefreshProperties(RefreshProperties.Repaint)]
//[SRDescription("TreeViewImageKeyDescr")]
public string ImageKey { get { return default(string); } set { } }
//
// Summary:
// Gets or sets the System.Windows.Forms.ImageList that contains the System.Drawing.Image
// objects used by the tree nodes.
//
// Returns:
// The System.Windows.Forms.ImageList that contains the System.Drawing.Image
// objects used by the tree nodes. The default value is null.
[DefaultValue("")]
//[SRCategory("CatBehavior")]
//[SRDescription("TreeViewImageListDescr")]
[RefreshProperties(RefreshProperties.Repaint)]
public ImageList ImageList { get { return default(ImageList); } set { } }
//
// Summary:
// Gets or sets the distance to indent each of the child tree node levels.
//
// Returns:
// The distance, in pixels, to indent each of the child tree node levels. The
// default value is 19.
//
// Exceptions:
// System.ArgumentOutOfRangeException:
// The assigned value is less than 0 (see Remarks).-or- The assigned value is
// greater than 32,000.
[Localizable(true)]
//[SRCategory("CatBehavior")]
//[SRDescription("TreeViewIndentDescr")]
public int Indent { get { return default(int); } set { } }
//
// Summary:
// Gets or sets the height of each tree node in the tree view control.
//
// Returns:
// The height, in pixels, of each tree node in the tree view.
//
// Exceptions:
// System.ArgumentOutOfRangeException:
// The assigned value is less than one.-or- The assigned value is greater than
// the System.Int16.MaxValue value.
//[SRDescription("TreeViewItemHeightDescr")]
//[SRCategory("CatAppearance")]
public int ItemHeight { get { return default(int); } set { } }
//
// Summary:
// Gets or sets a value indicating whether the label text of the tree nodes
// can be edited.
//
// Returns:
// true if the label text of the tree nodes can be edited; otherwise, false.
// The default is false.
[DefaultValue(false)]
//[SRCategory("CatBehavior")]
//[SRDescription("TreeViewLabelEditDescr")]
public bool LabelEdit { get { return default(bool); } set { } }
//
// Summary:
// Gets or sets the color of the lines connecting the nodes of the System.Windows.Forms.TreeView
// control.
//
// Returns:
// The System.Drawing.Color of the lines connecting the tree nodes.
//[SRCategory("CatBehavior")]
//[SRDescription("TreeViewLineColorDescr")]
[DefaultValue(typeof(Color), "Black")]
public Color LineColor { get { return default(Color); } set { } }
//
// Summary:
// Gets the collection of tree nodes that are assigned to the tree view control.
//
// Returns:
// A System.Windows.Forms.TreeNodeCollection that represents the tree nodes
// assigned to the tree view control.
//[MergableProperty(false)]
//[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
//[Localizable(true)]
//[SRDescription("TreeViewNodesDescr")]
//[SRCategory("CatBehavior")]
//public TreeNodeCollection Nodes { get { return default(); } }
//
// Summary:
// Gets or sets the spacing between the System.Windows.Forms.TreeView control's
// contents and its edges.
//
// Returns:
// A System.Windows.Forms.Padding indicating the space between the control edges
// and its contents.
//[Browsable(false)]
//[EditorBrowsable(EditorBrowsableState.Never)]
//[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
//public Padding Padding { get { return default(); } set { } }
//
// Summary:
// Gets or sets the delimiter string that the tree node path uses.
//
// Returns:
// The delimiter string that the tree node System.Windows.Forms.TreeNode.FullPath
// property uses. The default is the backslash character (\).
[DefaultValue(@"\")]
//[SRCategory("CatBehavior")]
//[SRDescription("TreeViewPathSeparatorDescr")]
public string PathSeparator { get { return default(string); } set { } }
//
// Summary:
// Gets or sets a value indicating whether the System.Windows.Forms.TreeView
// should be laid out from right-to-left.
//
// Returns:
// true to indicate the control should be laid out from right-to-left; otherwise,
// false. The default is false.
//[SRCategory("CatAppearance")]
[DefaultValue(false)]
[Localizable(true)]
//[SRDescription("ControlRightToLeftLayoutDescr")]
public virtual bool RightToLeftLayout { get { return default(bool); } set { } }
//
// Summary:
// Gets or sets a value indicating whether the tree view control displays scroll
// bars when they are needed.
//
// Returns:
// true if the tree view control displays scroll bars when they are needed;
// otherwise, false. The default is true.
//[SRDescription("TreeViewScrollableDescr")]
//[SRCategory("CatBehavior")]
[DefaultValue(true)]
public bool Scrollable { get { return default(bool); } set { } }
//
// Summary:
// Gets or sets the image list index value of the image that is displayed when
// a tree node is selected.
//
// Returns:
// A zero-based index value that represents the position of an System.Drawing.Image
// in an System.Windows.Forms.ImageList.
//
// Exceptions:
// System.ArgumentException:
// The index assigned value is less than zero.
[Localizable(true)]
[DefaultValue(-1)]
//[SRCategory("CatBehavior")]
//[TypeConverter(typeof(NoneExcludedImageIndexConverter))]
[Editor("System.Windows.Forms.Design.ImageIndexEditor, System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", typeof(UITypeEditor))]
//[SRDescription("TreeViewSelectedImageIndexDescr")]
//[RelatedImageList("ImageList")]
public int SelectedImageIndex { get { return default(int); } set { } }
//
// Summary:
// Gets or sets the key of the default image shown when a System.Windows.Forms.TreeNode
// is in a selected state.
//
// Returns:
// The key of the default image shown when a System.Windows.Forms.TreeNode is
// in a selected state.
//[SRCategory("CatBehavior")]
//[RelatedImageList("ImageList")]
[Localizable(true)]
//[TypeConverter(typeof(ImageKeyConverter))]
[Editor("System.Windows.Forms.Design.ImageIndexEditor, System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", typeof(UITypeEditor))]
[DefaultValue("")]
[RefreshProperties(RefreshProperties.Repaint)]
//[SRDescription("TreeViewSelectedImageKeyDescr")]
public string SelectedImageKey { get { return default(string); } set { } }
//
// Summary:
// Gets or sets the tree node that is currently selected in the tree view control.
//
// Returns:
// The System.Windows.Forms.TreeNode that is currently selected in the tree
// view control.
//[SRCategory("CatAppearance")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[Browsable(false)]
//[SRDescription("TreeViewSelectedNodeDescr")]
public TreeNode SelectedNode { get { return default(TreeNode); } set { } }
//
// Summary:
// Gets or sets a value indicating whether lines are drawn between tree nodes
// in the tree view control.
//
// Returns:
// true if lines are drawn between tree nodes in the tree view control; otherwise,
// false. The default is true.
//[SRDescription("TreeViewShowLinesDescr")]
//[SRCategory("CatBehavior")]
[DefaultValue(true)]
public bool ShowLines { get { return default(bool); } set { } }
//
// Summary:
// Gets or sets a value indicating ToolTips are shown when the mouse pointer
// hovers over a System.Windows.Forms.TreeNode.
//
// Returns:
// true if ToolTips are shown when the mouse pointer hovers over a System.Windows.Forms.TreeNode;
// otherwise, false. The default is false.
//[SRCategory("CatBehavior")]
//[SRDescription("TreeViewShowShowNodeToolTipsDescr")]
[DefaultValue(false)]
public bool ShowNodeToolTips { get { return default(bool); } set { } }
//
// Summary:
// Gets or sets a value indicating whether plus-sign (+) and minus-sign (-)
// buttons are displayed next to tree nodes that contain child tree nodes.
//
// Returns:
// true if plus sign and minus sign buttons are displayed next to tree nodes
// that contain child tree nodes; otherwise, false. The default is true.
//[SRCategory("CatBehavior")]
//[SRDescription("TreeViewShowPlusMinusDescr")]
[DefaultValue(true)]
public bool ShowPlusMinus { get { return default(bool); } set { } }
//
// Summary:
// Gets or sets a value indicating whether lines are drawn between the tree
// nodes that are at the root of the tree view.
//
// Returns:
// true if lines are drawn between the tree nodes that are at the root of the
// tree view; otherwise, false. The default is true.
//[SRDescription("TreeViewShowRootLinesDescr")]
//[SRCategory("CatBehavior")]
[DefaultValue(true)]
public bool ShowRootLines { get { return default(bool); } set { } }
//
// Summary:
// Gets or sets a value indicating whether the tree nodes in the tree view are
// sorted.
//
// Returns:
// true if the tree nodes in the tree view are sorted; otherwise, false. The
// default is false.
[DefaultValue(false)]
//[SRCategory("CatBehavior")]
//[SRDescription("TreeViewSortedDescr")]
[Browsable(false)]
[EditorBrowsable(EditorBrowsableState.Never)]
public bool Sorted { get { return default(bool); } set { } }
//
// Summary:
// Gets or sets the image list used for indicating the state of the System.Windows.Forms.TreeView
// and its nodes.
//
// Returns:
// The System.Windows.Forms.ImageList used for indicating the state of the System.Windows.Forms.TreeView
// and its nodes.
[DefaultValue("")]
//[SRCategory("CatBehavior")]
//[SRDescription("TreeViewStateImageListDescr")]
public ImageList StateImageList { get { return default(ImageList); } set { } }
//
// Summary:
// Gets or sets the text of the System.Windows.Forms.TreeView.
//
// Returns:
// Null.
//[Browsable(false)]
//[Bindable(false)]
//[EditorBrowsable(EditorBrowsableState.Never)]
//public override string Text { get { return default(); } set { } }
//
// Summary:
// Gets or sets the first fully-visible tree node in the tree view control.
//
// Returns:
// A System.Windows.Forms.TreeNode that represents the first fully-visible tree
// node in the tree view control.
[Browsable(false)]
//[SRCategory("CatAppearance")]
//[SRDescription("TreeViewTopNodeDescr")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public TreeNode TopNode { get { return default(TreeNode); } set { } }
//
// Summary:
// Gets or sets the implementation of System.Collections.IComparer to perform
// a custom sort of the System.Windows.Forms.TreeView nodes.
//
// Returns:
// The System.Collections.IComparer to perform the custom sort.
//[SRCategory("CatBehavior")]
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
//[SRDescription("TreeViewNodeSorterDescr")]
public IComparer TreeViewNodeSorter { get { return default(IComparer); } set { } }
//
// Summary:
// Gets the number of tree nodes that can be fully visible in the tree view
// control.
//
// Returns:
// The number of System.Windows.Forms.TreeNode items that can be fully visible
// in the System.Windows.Forms.TreeView control.
//[SRCategory("CatAppearance")]
//[SRDescription("TreeViewVisibleCountDescr")]
//[Browsable(false)]
//[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
//public int VisibleCount { get { return default(); } }
// Summary:
// Occurs after the tree node check box is checked.
//[SRDescription("TreeViewAfterCheckDescr")]
//[SRCategory("CatBehavior")]
//public event TreeViewEventHandler AfterCheck;
//
// Summary:
// Occurs after the tree node is collapsed.
//[SRCategory("CatBehavior")]
//[SRDescription("TreeViewAfterCollapseDescr")]
//public event TreeViewEventHandler AfterCollapse;
//
// Summary:
// Occurs after the tree node is expanded.
//[SRCategory("CatBehavior")]
//[SRDescription("TreeViewAfterExpandDescr")]
//public event TreeViewEventHandler AfterExpand;
//
// Summary:
// Occurs after the tree node label text is edited.
//[SRCategory("CatBehavior")]
//[SRDescription("TreeViewAfterEditDescr")]
//public event NodeLabelEditEventHandler AfterLabelEdit;
//
// Summary:
// Occurs after the tree node is selected.
//[SRDescription("TreeViewAfterSelectDescr")]
//[SRCategory("CatBehavior")]
//public event TreeViewEventHandler AfterSelect;
//
// Summary:
// Occurs when the System.Windows.Forms.TreeView.BackgroundImage property changes.
//[Browsable(false)]
//[EditorBrowsable(EditorBrowsableState.Never)]
//public event EventHandler BackgroundImageChanged;
//
// Summary:
// Occurs when the System.Windows.Forms.TreeView.BackgroundImageLayout property
// changes.
//[EditorBrowsable(EditorBrowsableState.Never)]
//[Browsable(false)]
//public event EventHandler BackgroundImageLayoutChanged;
//
// Summary:
// Occurs before the tree node check box is checked.
//[SRDescription("TreeViewBeforeCheckDescr")]
//[SRCategory("CatBehavior")]
//public event TreeViewCancelEventHandler BeforeCheck;
//
// Summary:
// Occurs before the tree node is collapsed.
//[SRCategory("CatBehavior")]
//[SRDescription("TreeViewBeforeCollapseDescr")]
//public event TreeViewCancelEventHandler BeforeCollapse;
//
// Summary:
// Occurs before the tree node is expanded.
//[SRCategory("CatBehavior")]
//[SRDescription("TreeViewBeforeExpandDescr")]
//public event TreeViewCancelEventHandler BeforeExpand;
//
// Summary:
// Occurs before the tree node label text is edited.
//[SRCategory("CatBehavior")]
//[SRDescription("TreeViewBeforeEditDescr")]
//public event NodeLabelEditEventHandler BeforeLabelEdit;
//
// Summary:
// Occurs before the tree node is selected.
//[SRCategory("CatBehavior")]
//[SRDescription("TreeViewBeforeSelectDescr")]
//public event TreeViewCancelEventHandler BeforeSelect;
//
// Summary:
// Occurs when a System.Windows.Forms.TreeView is drawn and the System.Windows.Forms.TreeView.DrawMode
// property is set to a System.Windows.Forms.TreeViewDrawMode value other than
// System.Windows.Forms.TreeViewDrawMode.Normal.
//[SRDescription("TreeViewDrawNodeEventDescr")]
//[SRCategory("CatBehavior")]
//public event DrawTreeNodeEventHandler DrawNode;
//
// Summary:
// Occurs when the user begins dragging a node.
//[SRDescription("ListViewItemDragDescr")]
//[SRCategory("CatAction")]
//public event ItemDragEventHandler ItemDrag;
//
// Summary:
// Occurs when the user clicks a System.Windows.Forms.TreeNode with the mouse.
//[SRDescription("TreeViewNodeMouseClickDescr")]
//[SRCategory("CatBehavior")]
//public event TreeNodeMouseClickEventHandler NodeMouseClick;
//
// Summary:
// Occurs when the user double-clicks a System.Windows.Forms.TreeNode with the
// mouse.
//[SRCategory("CatBehavior")]
//[SRDescription("TreeViewNodeMouseDoubleClickDescr")]
//public event TreeNodeMouseClickEventHandler NodeMouseDoubleClick;
//
// Summary:
// Occurs when the mouse hovers over a System.Windows.Forms.TreeNode.
//[SRDescription("TreeViewNodeMouseHoverDescr")]
//[SRCategory("CatAction")]
//public event TreeNodeMouseHoverEventHandler NodeMouseHover;
//
// Summary:
// Occurs when the value of the System.Windows.Forms.TreeView.Padding property
// changes.
//[Browsable(false)]
//[EditorBrowsable(EditorBrowsableState.Never)]
//public event EventHandler PaddingChanged;
//
// Summary:
// Occurs when the System.Windows.Forms.TreeView is drawn.
//[Browsable(false)]
//[EditorBrowsable(EditorBrowsableState.Never)]
//public event PaintEventHandler Paint;
//
// Summary:
// Occurs when the value of the System.Windows.Forms.TreeView.RightToLeftLayout
// property changes.
//[SRCategory("CatPropertyChanged")]
//[SRDescription("ControlOnRightToLeftLayoutChangedDescr")]
//public event EventHandler RightToLeftLayoutChanged;
//
// Summary:
// Occurs when the System.Windows.Forms.TreeView.Text property changes.
//[EditorBrowsable(EditorBrowsableState.Never)]
//[Browsable(false)]
//public event EventHandler TextChanged;
// Summary:
// Disables any redrawing of the tree view.
//public void BeginUpdate();
//
// Summary:
// Collapses all the tree nodes.
//public void CollapseAll();
//protected override void CreateHandle();
//
// Summary:
// Releases the unmanaged resources used by the System.Windows.Forms.TreeView
// and optionally releases the managed resources.
//
// Parameters:
// disposing:
// true to release both managed and unmanaged resources; false to release only
// unmanaged resources.
//protected override void Dispose(bool disposing);
//
// Summary:
// Enables the redrawing of the tree view.
//public void EndUpdate();
//
// Summary:
// Expands all the tree nodes.
//public void ExpandAll();
//
// Summary:
// Returns an System.Windows.Forms.OwnerDrawPropertyBag for the specified System.Windows.Forms.TreeNode.
//
// Parameters:
// node:
// The System.Windows.Forms.TreeNode for which to return an System.Windows.Forms.OwnerDrawPropertyBag.
//
// state:
// The visible state of the System.Windows.Forms.TreeNode.
//
// Returns:
// An System.Windows.Forms.OwnerDrawPropertyBag for the specified System.Windows.Forms.TreeNode.
//protected OwnerDrawPropertyBag GetItemRenderStyles(TreeNode node, int state);
//
// Summary:
// Retrieves the tree node that is at the specified point.
//
// Parameters:
// pt:
// The System.Drawing.Point to evaluate and retrieve the node from.
//
// Returns:
// The System.Windows.Forms.TreeNode at the specified point, in tree view (client)
// coordinates, or null if there is no node at that location.
//public TreeNode GetNodeAt(Point pt);
//
// Summary:
// Retrieves the tree node at the point with the specified coordinates.
//
// Parameters:
// x:
// The System.Drawing.Point.X position to evaluate and retrieve the node from.
//
// y:
// The System.Drawing.Point.Y position to evaluate and retrieve the node from.
//
// Returns:
// The System.Windows.Forms.TreeNode at the specified location, in tree view
// (client) coordinates, or null if there is no node at that location.
//public TreeNode GetNodeAt(int x, int y);
//
// Summary:
// Retrieves the number of tree nodes, optionally including those in all subtrees,
// assigned to the tree view control.
//
// Parameters:
// includeSubTrees:
// true to count the System.Windows.Forms.TreeNode items that the subtrees contain;
// otherwise, false.
//
// Returns:
// The number of tree nodes, optionally including those in all subtrees, assigned
// to the tree view control.
//public int GetNodeCount(bool includeSubTrees);
//
// Summary:
// Provides node information, given a point.
//
// Parameters:
// pt:
// The System.Drawing.Point at which to retrieve node information.
//
// Returns:
// A System.Windows.Forms.TreeViewHitTestInfo.
//public TreeViewHitTestInfo HitTest(Point pt);
//
// Summary:
// Provides node information, given x- and y-coordinates.
//
// Parameters:
// x:
// The x-coordinate at which to retrieve node information
//
// y:
// The y-coordinate at which to retrieve node information.
//
// Returns:
// A System.Windows.Forms.TreeViewHitTestInfo.
//public TreeViewHitTestInfo HitTest(int x, int y);
//
// Summary:
// Determines whether the specified key is a regular input key or a special
// key that requires preprocessing.
//
// Parameters:
// keyData:
// One of the Keys values.
//
// Returns:
// true if the specified key is a regular input key; otherwise, false.
//protected override bool IsInputKey(Keys keyData);
//
// Summary:
// Raises the System.Windows.Forms.TreeView.AfterCheck event.
//
// Parameters:
// e:
// A System.Windows.Forms.TreeViewEventArgs that contains the event data.
protected virtual void OnAfterCheck(TreeViewEventArgs e) {
Contract.Requires(e != null);
}
//
// Summary:
// Raises the System.Windows.Forms.TreeView.AfterCollapse event.
//
// Parameters:
// e:
// A System.Windows.Forms.TreeViewEventArgs that contains the event data.
protected internal virtual void OnAfterCollapse(TreeViewEventArgs e) {
Contract.Requires(e != null);
}
//
// Summary:
// Raises the System.Windows.Forms.TreeView.AfterExpand event.
//
// Parameters:
// e:
// A System.Windows.Forms.TreeViewEventArgs that contains the event data.
protected virtual void OnAfterExpand(TreeViewEventArgs e) {
Contract.Requires(e != null);
}
//
// Summary:
// Raises the System.Windows.Forms.TreeView.AfterLabelEdit event.
//
// Parameters:
// e:
// A System.Windows.Forms.NodeLabelEditEventArgs that contains the event data.
protected virtual void OnAfterLabelEdit(NodeLabelEditEventArgs e) {
Contract.Requires(e != null);
}
//
// Summary:
// Raises the System.Windows.Forms.TreeView.AfterSelect event.
//
// Parameters:
// e:
// A System.Windows.Forms.TreeViewEventArgs that contains the event data.
protected virtual void OnAfterSelect(TreeViewEventArgs e) {
Contract.Requires(e != null);
}
//
// Summary:
// Raises the System.Windows.Forms.TreeView.BeforeCheck event.
//
// Parameters:
// e:
// A System.Windows.Forms.TreeViewCancelEventArgs that contains the event data.
protected virtual void OnBeforeCheck(TreeViewCancelEventArgs e) {
Contract.Requires(e != null);
}
//
// Summary:
// Raises the System.Windows.Forms.TreeView.BeforeCollapse event.
//
// Parameters:
// e:
// A System.Windows.Forms.TreeViewCancelEventArgs that contains the event data.
protected internal virtual void OnBeforeCollapse(TreeViewCancelEventArgs e) {
Contract.Requires(e != null);
}
//
// Summary:
// Raises the System.Windows.Forms.TreeView.BeforeExpand event.
//
// Parameters:
// e:
// A System.Windows.Forms.TreeViewCancelEventArgs that contains the event data.
protected virtual void OnBeforeExpand(TreeViewCancelEventArgs e) {
Contract.Requires(e != null);
}
//
// Summary:
// Raises the System.Windows.Forms.TreeView.BeforeLabelEdit event.
//
// Parameters:
// e:
// A System.Windows.Forms.NodeLabelEditEventArgs that contains the event data.
protected virtual void OnBeforeLabelEdit(NodeLabelEditEventArgs e) {
Contract.Requires(e != null);
}
//
// Summary:
// Raises the System.Windows.Forms.TreeView.BeforeSelect event.
//
// Parameters:
// e:
// A System.Windows.Forms.TreeViewCancelEventArgs that contains the event data.
protected virtual void OnBeforeSelect(TreeViewCancelEventArgs e) {
Contract.Requires(e != null);
}
//
// Summary:
// Raises the System.Windows.Forms.TreeView.DrawNode event.
//
// Parameters:
// e:
// A System.Windows.Forms.DrawTreeNodeEventArgs that contains the event data.
//protected virtual void OnDrawNode(DrawTreeNodeEventArgs e);
//
// Summary:
// Overrides System.Windows.Forms.Control.OnHandleCreated(System.EventArgs).
//
// Parameters:
// e:
// An System.EventArgs that contains the event data.
//protected override void OnHandleCreated(EventArgs e);
//
// Summary:
// Overrides System.Windows.Forms.Control.OnHandleDestroyed(System.EventArgs).
//
// Parameters:
// e:
// An System.EventArgs that contains the event data.
//protected override void OnHandleDestroyed(EventArgs e);
//
// Summary:
// Raises the System.Windows.Forms.TreeView.ItemDrag event.
//
// Parameters:
// e:
// An System.Windows.Forms.ItemDragEventArgs that contains the event data.
protected virtual void OnItemDrag(ItemDragEventArgs e) {
Contract.Requires(e != null);
}
//
// Summary:
// Raises the System.Windows.Forms.Control.KeyDown event.
//
// Parameters:
// e:
// A System.Windows.Forms.KeyEventArgs that contains the event data.
//protected override void OnKeyDown(KeyEventArgs e);
//
// Summary:
// Raises the System.Windows.Forms.Control.KeyPress event.
//
// Parameters:
// e:
// A System.Windows.Forms.KeyPressEventArgs that contains the event data.
//protected override void OnKeyPress(KeyPressEventArgs e);
//
// Summary:
// Overrides System.Windows.Forms.Control.OnKeyUp(System.Windows.Forms.KeyEventArgs).
//
// Parameters:
// e:
// A System.Windows.Forms.KeyEventArgs that contains the event data.
//protected override void OnKeyUp(KeyEventArgs e);
//
// Summary:
// Raises the System.Windows.Forms.Control.MouseHover event.
//
// Parameters:
// e:
// An System.EventArgs that contains the event data.
//protected override void OnMouseHover(EventArgs e);
//
// Summary:
// Raises the System.Windows.Forms.Control.MouseLeave event.
//
// Parameters:
// e:
// A System.EventArgs that contains the event data.
//protected override void OnMouseLeave(EventArgs e);
//
// Summary:
// Raises the System.Windows.Forms.TreeView.NodeMouseClick event.
//
// Parameters:
// e:
// A System.Windows.Forms.TreeNodeMouseClickEventArgs that contains the event
// data.
protected virtual void OnNodeMouseClick(TreeNodeMouseClickEventArgs e) {
Contract.Requires(e != null);
}
//
// Summary:
// Raises the System.Windows.Forms.TreeView.NodeMouseDoubleClick event.
//
// Parameters:
// e:
// A System.Windows.Forms.TreeNodeMouseClickEventArgs that contains the event
// data.
protected virtual void OnNodeMouseDoubleClick(TreeNodeMouseClickEventArgs e) {
Contract.Requires(e != null);
}
//
// Summary:
// Raises the System.Windows.Forms.TreeView.NodeMouseHover event.
//
// Parameters:
// e:
// The System.Windows.Forms.TreeNodeMouseHoverEventArgs that contains the event
// data.
//protected virtual void OnNodeMouseHover(TreeNodeMouseHoverEventArgs e);
//
// Summary:
// Raises the System.Windows.Forms.TreeView.RightToLeftLayoutChanged event.
//
// Parameters:
// e:
// A System.EventArgs that contains the event data.
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected virtual void OnRightToLeftLayoutChanged(EventArgs e) {
Contract.Requires(e != null);
}
//
// Summary:
// Sorts the items in System.Windows.Forms.TreeView control.
//public void Sort();
//
// Summary:
// Overrides System.ComponentModel.Component.ToString().
//public override string ToString();
//
// Summary:
// Overrides System.Windows.Forms.Control.WndProc(System.Windows.Forms.Message@).
//
// Parameters:
// m:
// The Windows System.Windows.Forms.Message to process.
//protected override void WndProc(ref Message m);
}
}
| |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using QuantConnect.Data;
using QuantConnect.Data.Market;
using QuantConnect.Data.UniverseSelection;
using QuantConnect.Interfaces;
using QuantConnect.Orders;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Regression algorithm that test if the fill prices are the correct quote side.
/// </summary>
/// <meta name="tag" content="using data" />
/// <meta name="tag" content="using quantconnect" />
/// <meta name="tag" content="trading and orders" />
public class EquityTradeAndQuotesRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
private Symbol _symbol;
private bool _canTrade;
private int _quoteCounter;
private int _tradeCounter;
/// <summary>
/// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
/// </summary>
public override void Initialize()
{
SetStartDate(2013, 10, 07); //Set Start Date
SetEndDate(2013, 10, 11); //Set End Date
SetCash(100000); //Set Strategy Cash
SetSecurityInitializer(x => x.SetDataNormalizationMode(DataNormalizationMode.Raw));
_symbol = AddEquity("IBM", Resolution.Minute).Symbol;
AddEquity("AAPL", Resolution.Daily);
// 2013-10-07 was Monday, that's why we ask 3 days history to get data from previous Friday.
var history = History(new[] { _symbol }, TimeSpan.FromDays(3), Resolution.Minute).ToList();
Log($"{Time} - history.Count: {history.Count}");
const int expectedSliceCount = 390;
if (history.Count != expectedSliceCount)
{
throw new Exception($"History slices - expected: {expectedSliceCount}, actual: {history.Count}");
}
if (history.Any(s => s.Bars.Count != 1 && s.QuoteBars.Count != 1))
{
throw new Exception($"History not all slices have trades and quotes.");
}
Schedule.On(DateRules.EveryDay(_symbol), TimeRules.AfterMarketOpen(_symbol, 0), () => { _canTrade = true; });
Schedule.On(DateRules.EveryDay(_symbol), TimeRules.BeforeMarketClose(_symbol, 16), () => { _canTrade = false; });
}
/// <summary>
/// OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
/// </summary>
/// <param name="data">Slice object keyed by symbol containing the stock data</param>
public override void OnData(Slice data)
{
_quoteCounter += data.QuoteBars.Count;
_tradeCounter += data.Bars.Count;
if (!Portfolio.Invested && _canTrade)
{
SetHoldings(_symbol, 1);
Log($"Purchased Security {_symbol.ID}");
}
if (Time.Minute % 15 == 0)
{
Liquidate();
}
}
public override void OnSecuritiesChanged(SecurityChanges changes)
{
foreach (var addedSecurity in changes.AddedSecurities)
{
var subscriptions = SubscriptionManager.SubscriptionDataConfigService.GetSubscriptionDataConfigs(addedSecurity.Symbol);
if (addedSecurity.Symbol == _symbol)
{
if (!(subscriptions.Count == 2 &&
subscriptions.Any(s => s.TickType == TickType.Trade) &&
subscriptions.Any(s => s.TickType == TickType.Quote)))
{
throw new Exception($"Subscriptions were not correctly added for high resolution.");
}
}
else
{
if (subscriptions.Single().TickType != TickType.Trade)
{
throw new Exception($"Subscriptions were not correctly added for low resolution.");
}
}
}
}
public override void OnOrderEvent(OrderEvent orderEvent)
{
if (orderEvent.Status == OrderStatus.Filled)
{
Log($"{Time:s} {orderEvent.Direction}");
var expectedFillPrice = orderEvent.Direction == OrderDirection.Buy ? Securities[_symbol].AskPrice : Securities[_symbol].BidPrice;
if (orderEvent.FillPrice != expectedFillPrice)
{
throw new Exception($"Fill price is not the expected for OrderId {orderEvent.OrderId} at Algorithm Time {Time:s}." +
$"\n\tExpected fill price: {expectedFillPrice}, Actual fill price: {orderEvent.FillPrice}");
}
}
}
public override void OnEndOfAlgorithm()
{
// We expect at least 390 * 5 = 1950 minute bar
// + 5 daily bars, but those are pumped into OnData every minute
if (_tradeCounter <= 1955)
{
throw new Exception($"Fail at trade bars count expected >= 1955, actual: {_tradeCounter}.");
}
// We expect 390 * 5 = 1950 quote bars.
if (_quoteCounter != 1950)
{
throw new Exception($"Fail at trade bars count expected: 1950, actual: {_quoteCounter}.");
}
}
/// <summary>
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
/// </summary>
public bool CanRunLocally { get; } = true;
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp };
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "250"},
{"Average Win", "0.12%"},
{"Average Loss", "-0.10%"},
{"Compounding Annual Return", "-86.494%"},
{"Drawdown", "3.300%"},
{"Expectancy", "-0.225"},
{"Net Profit", "-2.705%"},
{"Sharpe Ratio", "-5.022"},
{"Probabilistic Sharpe Ratio", "1.586%"},
{"Loss Rate", "65%"},
{"Win Rate", "35%"},
{"Profit-Loss Ratio", "1.20"},
{"Alpha", "-1.879"},
{"Beta", "0.571"},
{"Annual Standard Deviation", "0.149"},
{"Annual Variance", "0.022"},
{"Information Ratio", "-22.181"},
{"Tracking Error", "0.123"},
{"Treynor Ratio", "-1.31"},
{"Total Fees", "$670.68"},
{"Estimated Strategy Capacity", "$190000.00"},
{"Lowest Capacity Asset", "IBM R735QTJ8XC9X"},
{"Fitness Score", "0.023"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "-6.961"},
{"Return Over Maximum Drawdown", "-31.972"},
{"Portfolio Turnover", "49.956"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
{"Total Insights Analysis Completed", "0"},
{"Long Insight Count", "0"},
{"Short Insight Count", "0"},
{"Long/Short Ratio", "100%"},
{"Estimated Monthly Alpha Value", "$0"},
{"Total Accumulated Estimated Alpha Value", "$0"},
{"Mean Population Estimated Insight Value", "$0"},
{"Mean Population Direction", "0%"},
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "a832e5f029696f1cf0b9f7964978164e"}
};
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Runtime.CompilerServices;
namespace System.Collections.Generic
{
// The SortedDictionary class implements a generic sorted list of keys
// and values. Entries in a sorted list are sorted by their keys and
// are accessible both by key and by index. The keys of a sorted dictionary
// can be ordered either according to a specific IComparer
// implementation given when the sorted dictionary is instantiated, or
// according to the IComparable implementation provided by the keys
// themselves. In either case, a sorted dictionary does not allow entries
// with duplicate or null keys.
//
// A sorted list internally maintains two arrays that store the keys and
// values of the entries. The capacity of a sorted list is the allocated
// length of these internal arrays. As elements are added to a sorted list, the
// capacity of the sorted list is automatically increased as required by
// reallocating the internal arrays. The capacity is never automatically
// decreased, but users can call either TrimExcess or
// Capacity explicitly.
//
// The GetKeyList and GetValueList methods of a sorted list
// provides access to the keys and values of the sorted list in the form of
// List implementations. The List objects returned by these
// methods are aliases for the underlying sorted list, so modifications
// made to those lists are directly reflected in the sorted list, and vice
// versa.
//
// The SortedList class provides a convenient way to create a sorted
// copy of another dictionary, such as a Hashtable. For example:
//
// Hashtable h = new Hashtable();
// h.Add(...);
// h.Add(...);
// ...
// SortedList s = new SortedList(h);
//
// The last line above creates a sorted list that contains a copy of the keys
// and values stored in the hashtable. In this particular example, the keys
// will be ordered according to the IComparable interface, which they
// all must implement. To impose a different ordering, SortedList also
// has a constructor that allows a specific IComparer implementation to
// be specified.
//
[DebuggerTypeProxy(typeof(IDictionaryDebugView<,>))]
[DebuggerDisplay("Count = {Count}")]
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public class SortedList<TKey, TValue> :
IDictionary<TKey, TValue>, IDictionary, IReadOnlyDictionary<TKey, TValue>
{
private TKey[] keys; // Do not rename (binary serialization)
private TValue[] values; // Do not rename (binary serialization)
private int _size; // Do not rename (binary serialization)
private int version; // Do not rename (binary serialization)
private IComparer<TKey> comparer; // Do not rename (binary serialization)
private KeyList keyList; // Do not rename (binary serialization)
private ValueList valueList; // Do not rename (binary serialization)
[NonSerialized]
private object _syncRoot;
private const int DefaultCapacity = 4;
// Constructs a new sorted list. The sorted list is initially empty and has
// a capacity of zero. Upon adding the first element to the sorted list the
// capacity is increased to DefaultCapacity, and then increased in multiples of two as
// required. The elements of the sorted list are ordered according to the
// IComparable interface, which must be implemented by the keys of
// all entries added to the sorted list.
public SortedList()
{
keys = Array.Empty<TKey>();
values = Array.Empty<TValue>();
_size = 0;
comparer = Comparer<TKey>.Default;
}
// Constructs a new sorted list. The sorted list is initially empty and has
// a capacity of zero. Upon adding the first element to the sorted list the
// capacity is increased to 16, and then increased in multiples of two as
// required. The elements of the sorted list are ordered according to the
// IComparable interface, which must be implemented by the keys of
// all entries added to the sorted list.
//
public SortedList(int capacity)
{
if (capacity < 0)
throw new ArgumentOutOfRangeException(nameof(capacity), capacity, SR.ArgumentOutOfRange_NeedNonNegNum);
keys = new TKey[capacity];
values = new TValue[capacity];
comparer = Comparer<TKey>.Default;
}
// Constructs a new sorted list with a given IComparer
// implementation. The sorted list is initially empty and has a capacity of
// zero. Upon adding the first element to the sorted list the capacity is
// increased to 16, and then increased in multiples of two as required. The
// elements of the sorted list are ordered according to the given
// IComparer implementation. If comparer is null, the
// elements are compared to each other using the IComparable
// interface, which in that case must be implemented by the keys of all
// entries added to the sorted list.
//
public SortedList(IComparer<TKey> comparer)
: this()
{
if (comparer != null)
{
this.comparer = comparer;
}
}
// Constructs a new sorted dictionary with a given IComparer
// implementation and a given initial capacity. The sorted list is
// initially empty, but will have room for the given number of elements
// before any reallocations are required. The elements of the sorted list
// are ordered according to the given IComparer implementation. If
// comparer is null, the elements are compared to each other using
// the IComparable interface, which in that case must be implemented
// by the keys of all entries added to the sorted list.
//
public SortedList(int capacity, IComparer<TKey> comparer)
: this(comparer)
{
Capacity = capacity;
}
// Constructs a new sorted list containing a copy of the entries in the
// given dictionary. The elements of the sorted list are ordered according
// to the IComparable interface, which must be implemented by the
// keys of all entries in the given dictionary as well as keys
// subsequently added to the sorted list.
//
public SortedList(IDictionary<TKey, TValue> dictionary)
: this(dictionary, null)
{
}
// Constructs a new sorted list containing a copy of the entries in the
// given dictionary. The elements of the sorted list are ordered according
// to the given IComparer implementation. If comparer is
// null, the elements are compared to each other using the
// IComparable interface, which in that case must be implemented
// by the keys of all entries in the given dictionary as well as keys
// subsequently added to the sorted list.
//
public SortedList(IDictionary<TKey, TValue> dictionary, IComparer<TKey> comparer)
: this((dictionary != null ? dictionary.Count : 0), comparer)
{
if (dictionary == null)
throw new ArgumentNullException(nameof(dictionary));
int count = dictionary.Count;
if (count != 0)
{
TKey[] keys = this.keys;
dictionary.Keys.CopyTo(keys, 0);
dictionary.Values.CopyTo(values, 0);
Debug.Assert(count == this.keys.Length);
if (count > 1)
{
comparer = Comparer; // obtain default if this is null.
Array.Sort<TKey, TValue>(keys, values, comparer);
for (int i = 1; i != keys.Length; ++i)
{
if (comparer.Compare(keys[i - 1], keys[i]) == 0)
{
throw new ArgumentException(SR.Format(SR.Argument_AddingDuplicate, keys[i]));
}
}
}
}
_size = count;
}
// Adds an entry with the given key and value to this sorted list. An
// ArgumentException is thrown if the key is already present in the sorted list.
//
public void Add(TKey key, TValue value)
{
if (key == null) throw new ArgumentNullException(nameof(key));
int i = Array.BinarySearch<TKey>(keys, 0, _size, key, comparer);
if (i >= 0)
throw new ArgumentException(SR.Format(SR.Argument_AddingDuplicate, key), nameof(key));
Insert(~i, key, value);
}
void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> keyValuePair)
{
Add(keyValuePair.Key, keyValuePair.Value);
}
bool ICollection<KeyValuePair<TKey, TValue>>.Contains(KeyValuePair<TKey, TValue> keyValuePair)
{
int index = IndexOfKey(keyValuePair.Key);
if (index >= 0 && EqualityComparer<TValue>.Default.Equals(values[index], keyValuePair.Value))
{
return true;
}
return false;
}
bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> keyValuePair)
{
int index = IndexOfKey(keyValuePair.Key);
if (index >= 0 && EqualityComparer<TValue>.Default.Equals(values[index], keyValuePair.Value))
{
RemoveAt(index);
return true;
}
return false;
}
// Returns the capacity of this sorted list. The capacity of a sorted list
// represents the allocated length of the internal arrays used to store the
// keys and values of the list, and thus also indicates the maximum number
// of entries the list can contain before a reallocation of the internal
// arrays is required.
//
public int Capacity
{
get
{
return keys.Length;
}
set
{
if (value != keys.Length)
{
if (value < _size)
{
throw new ArgumentOutOfRangeException(nameof(value), value, SR.ArgumentOutOfRange_SmallCapacity);
}
if (value > 0)
{
TKey[] newKeys = new TKey[value];
TValue[] newValues = new TValue[value];
if (_size > 0)
{
Array.Copy(keys, 0, newKeys, 0, _size);
Array.Copy(values, 0, newValues, 0, _size);
}
keys = newKeys;
values = newValues;
}
else
{
keys = Array.Empty<TKey>();
values = Array.Empty<TValue>();
}
}
}
}
public IComparer<TKey> Comparer
{
get
{
return comparer;
}
}
void IDictionary.Add(object key, object value)
{
if (key == null)
throw new ArgumentNullException(nameof(key));
if (value == null && !(default(TValue) == null)) // null is an invalid value for Value types
throw new ArgumentNullException(nameof(value));
if (!(key is TKey))
throw new ArgumentException(SR.Format(SR.Arg_WrongType, key, typeof(TKey)), nameof(key));
if (!(value is TValue) && value != null) // null is a valid value for Reference Types
throw new ArgumentException(SR.Format(SR.Arg_WrongType, value, typeof(TValue)), nameof(value));
Add((TKey)key, (TValue)value);
}
// Returns the number of entries in this sorted list.
public int Count
{
get
{
return _size;
}
}
// Returns a collection representing the keys of this sorted list. This
// method returns the same object as GetKeyList, but typed as an
// ICollection instead of an IList.
public IList<TKey> Keys
{
get
{
return GetKeyListHelper();
}
}
ICollection<TKey> IDictionary<TKey, TValue>.Keys
{
get
{
return GetKeyListHelper();
}
}
ICollection IDictionary.Keys
{
get
{
return GetKeyListHelper();
}
}
IEnumerable<TKey> IReadOnlyDictionary<TKey, TValue>.Keys
{
get
{
return GetKeyListHelper();
}
}
// Returns a collection representing the values of this sorted list. This
// method returns the same object as GetValueList, but typed as an
// ICollection instead of an IList.
//
public IList<TValue> Values
{
get
{
return GetValueListHelper();
}
}
ICollection<TValue> IDictionary<TKey, TValue>.Values
{
get
{
return GetValueListHelper();
}
}
ICollection IDictionary.Values
{
get
{
return GetValueListHelper();
}
}
IEnumerable<TValue> IReadOnlyDictionary<TKey, TValue>.Values
{
get
{
return GetValueListHelper();
}
}
private KeyList GetKeyListHelper()
{
if (keyList == null)
keyList = new KeyList(this);
return keyList;
}
private ValueList GetValueListHelper()
{
if (valueList == null)
valueList = new ValueList(this);
return valueList;
}
bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly
{
get { return false; }
}
bool IDictionary.IsReadOnly
{
get { return false; }
}
bool IDictionary.IsFixedSize
{
get { return false; }
}
bool ICollection.IsSynchronized
{
get { return false; }
}
// Synchronization root for this object.
object ICollection.SyncRoot
{
get
{
if (_syncRoot == null)
{
Threading.Interlocked.CompareExchange(ref _syncRoot, new object(), null);
}
return _syncRoot;
}
}
// Removes all entries from this sorted list.
public void Clear()
{
// clear does not change the capacity
version++;
// Don't need to doc this but we clear the elements so that the gc can reclaim the references.
if (RuntimeHelpers.IsReferenceOrContainsReferences<TKey>())
{
Array.Clear(keys, 0, _size);
}
if (RuntimeHelpers.IsReferenceOrContainsReferences<TValue>())
{
Array.Clear(values, 0, _size);
}
_size = 0;
}
bool IDictionary.Contains(object key)
{
if (IsCompatibleKey(key))
{
return ContainsKey((TKey)key);
}
return false;
}
// Checks if this sorted list contains an entry with the given key.
public bool ContainsKey(TKey key)
{
return IndexOfKey(key) >= 0;
}
// Checks if this sorted list contains an entry with the given value. The
// values of the entries of the sorted list are compared to the given value
// using the Object.Equals method. This method performs a linear
// search and is substantially slower than the Contains
// method.
public bool ContainsValue(TValue value)
{
return IndexOfValue(value) >= 0;
}
// Copies the values in this SortedList to an array.
void ICollection<KeyValuePair<TKey, TValue>>.CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
{
if (array == null)
{
throw new ArgumentNullException(nameof(array));
}
if (arrayIndex < 0 || arrayIndex > array.Length)
{
throw new ArgumentOutOfRangeException(nameof(arrayIndex), arrayIndex, SR.ArgumentOutOfRange_Index);
}
if (array.Length - arrayIndex < Count)
{
throw new ArgumentException(SR.Arg_ArrayPlusOffTooSmall);
}
for (int i = 0; i < Count; i++)
{
KeyValuePair<TKey, TValue> entry = new KeyValuePair<TKey, TValue>(keys[i], values[i]);
array[arrayIndex + i] = entry;
}
}
void ICollection.CopyTo(Array array, int index)
{
if (array == null)
{
throw new ArgumentNullException(nameof(array));
}
if (array.Rank != 1)
{
throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array));
}
if (array.GetLowerBound(0) != 0)
{
throw new ArgumentException(SR.Arg_NonZeroLowerBound, nameof(array));
}
if (index < 0 || index > array.Length)
{
throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_Index);
}
if (array.Length - index < Count)
{
throw new ArgumentException(SR.Arg_ArrayPlusOffTooSmall);
}
KeyValuePair<TKey, TValue>[] keyValuePairArray = array as KeyValuePair<TKey, TValue>[];
if (keyValuePairArray != null)
{
for (int i = 0; i < Count; i++)
{
keyValuePairArray[i + index] = new KeyValuePair<TKey, TValue>(keys[i], values[i]);
}
}
else
{
object[] objects = array as object[];
if (objects == null)
{
throw new ArgumentException(SR.Argument_InvalidArrayType, nameof(array));
}
try
{
for (int i = 0; i < Count; i++)
{
objects[i + index] = new KeyValuePair<TKey, TValue>(keys[i], values[i]);
}
}
catch (ArrayTypeMismatchException)
{
throw new ArgumentException(SR.Argument_InvalidArrayType, nameof(array));
}
}
}
private const int MaxArrayLength = 0X7FEFFFFF;
// Ensures that the capacity of this sorted list is at least the given
// minimum value. If the current capacity of the list is less than
// min, the capacity is increased to twice the current capacity or
// to min, whichever is larger.
private void EnsureCapacity(int min)
{
int newCapacity = keys.Length == 0 ? DefaultCapacity : keys.Length * 2;
// Allow the list to grow to maximum possible capacity (~2G elements) before encountering overflow.
// Note that this check works even when _items.Length overflowed thanks to the (uint) cast
if ((uint)newCapacity > MaxArrayLength) newCapacity = MaxArrayLength;
if (newCapacity < min) newCapacity = min;
Capacity = newCapacity;
}
// Returns the value of the entry at the given index.
private TValue GetByIndex(int index)
{
if (index < 0 || index >= _size)
throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_Index);
return values[index];
}
public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
{
return new Enumerator(this, Enumerator.KeyValuePair);
}
IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator()
{
return new Enumerator(this, Enumerator.KeyValuePair);
}
IDictionaryEnumerator IDictionary.GetEnumerator()
{
return new Enumerator(this, Enumerator.DictEntry);
}
IEnumerator IEnumerable.GetEnumerator()
{
return new Enumerator(this, Enumerator.KeyValuePair);
}
// Returns the key of the entry at the given index.
private TKey GetKey(int index)
{
if (index < 0 || index >= _size)
throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_Index);
return keys[index];
}
// Returns the value associated with the given key. If an entry with the
// given key is not found, the returned value is null.
public TValue this[TKey key]
{
get
{
int i = IndexOfKey(key);
if (i >= 0)
return values[i];
throw new KeyNotFoundException(SR.Format(SR.Arg_KeyNotFoundWithKey, key.ToString()));
}
set
{
if (((object)key) == null) throw new ArgumentNullException(nameof(key));
int i = Array.BinarySearch<TKey>(keys, 0, _size, key, comparer);
if (i >= 0)
{
values[i] = value;
version++;
return;
}
Insert(~i, key, value);
}
}
object IDictionary.this[object key]
{
get
{
if (IsCompatibleKey(key))
{
int i = IndexOfKey((TKey)key);
if (i >= 0)
{
return values[i];
}
}
return null;
}
set
{
if (!IsCompatibleKey(key))
{
throw new ArgumentNullException(nameof(key));
}
if (value == null && !(default(TValue) == null))
throw new ArgumentNullException(nameof(value));
TKey tempKey = (TKey)key;
try
{
this[tempKey] = (TValue)value;
}
catch (InvalidCastException)
{
throw new ArgumentException(SR.Format(SR.Arg_WrongType, value, typeof(TValue)), nameof(value));
}
}
}
// Returns the index of the entry with a given key in this sorted list. The
// key is located through a binary search, and thus the average execution
// time of this method is proportional to Log2(size), where
// size is the size of this sorted list. The returned value is -1 if
// the given key does not occur in this sorted list. Null is an invalid
// key value.
public int IndexOfKey(TKey key)
{
if (key == null)
throw new ArgumentNullException(nameof(key));
int ret = Array.BinarySearch<TKey>(keys, 0, _size, key, comparer);
return ret >= 0 ? ret : -1;
}
// Returns the index of the first occurrence of an entry with a given value
// in this sorted list. The entry is located through a linear search, and
// thus the average execution time of this method is proportional to the
// size of this sorted list. The elements of the list are compared to the
// given value using the Object.Equals method.
public int IndexOfValue(TValue value)
{
return Array.IndexOf(values, value, 0, _size);
}
// Inserts an entry with a given key and value at a given index.
private void Insert(int index, TKey key, TValue value)
{
if (_size == keys.Length) EnsureCapacity(_size + 1);
if (index < _size)
{
Array.Copy(keys, index, keys, index + 1, _size - index);
Array.Copy(values, index, values, index + 1, _size - index);
}
keys[index] = key;
values[index] = value;
_size++;
version++;
}
public bool TryGetValue(TKey key, out TValue value)
{
int i = IndexOfKey(key);
if (i >= 0)
{
value = values[i];
return true;
}
value = default(TValue);
return false;
}
// Removes the entry at the given index. The size of the sorted list is
// decreased by one.
public void RemoveAt(int index)
{
if (index < 0 || index >= _size)
throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_Index);
_size--;
if (index < _size)
{
Array.Copy(keys, index + 1, keys, index, _size - index);
Array.Copy(values, index + 1, values, index, _size - index);
}
if (RuntimeHelpers.IsReferenceOrContainsReferences<TKey>())
{
keys[_size] = default(TKey);
}
if (RuntimeHelpers.IsReferenceOrContainsReferences<TValue>())
{
values[_size] = default(TValue);
}
version++;
}
// Removes an entry from this sorted list. If an entry with the specified
// key exists in the sorted list, it is removed. An ArgumentException is
// thrown if the key is null.
public bool Remove(TKey key)
{
int i = IndexOfKey(key);
if (i >= 0)
RemoveAt(i);
return i >= 0;
}
void IDictionary.Remove(object key)
{
if (IsCompatibleKey(key))
{
Remove((TKey)key);
}
}
// Sets the capacity of this sorted list to the size of the sorted list.
// This method can be used to minimize a sorted list's memory overhead once
// it is known that no new elements will be added to the sorted list. To
// completely clear a sorted list and release all memory referenced by the
// sorted list, execute the following statements:
//
// SortedList.Clear();
// SortedList.TrimExcess();
public void TrimExcess()
{
int threshold = (int)(((double)keys.Length) * 0.9);
if (_size < threshold)
{
Capacity = _size;
}
}
private static bool IsCompatibleKey(object key)
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
return (key is TKey);
}
private struct Enumerator : IEnumerator<KeyValuePair<TKey, TValue>>, IDictionaryEnumerator
{
private SortedList<TKey, TValue> _sortedList;
private TKey _key;
private TValue _value;
private int _index;
private int _version;
private int _getEnumeratorRetType; // What should Enumerator.Current return?
internal const int KeyValuePair = 1;
internal const int DictEntry = 2;
internal Enumerator(SortedList<TKey, TValue> sortedList, int getEnumeratorRetType)
{
_sortedList = sortedList;
_index = 0;
_version = _sortedList.version;
_getEnumeratorRetType = getEnumeratorRetType;
_key = default(TKey);
_value = default(TValue);
}
public void Dispose()
{
_index = 0;
_key = default(TKey);
_value = default(TValue);
}
object IDictionaryEnumerator.Key
{
get
{
if (_index == 0 || (_index == _sortedList.Count + 1))
{
throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen);
}
return _key;
}
}
public bool MoveNext()
{
if (_version != _sortedList.version) throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion);
if ((uint)_index < (uint)_sortedList.Count)
{
_key = _sortedList.keys[_index];
_value = _sortedList.values[_index];
_index++;
return true;
}
_index = _sortedList.Count + 1;
_key = default(TKey);
_value = default(TValue);
return false;
}
DictionaryEntry IDictionaryEnumerator.Entry
{
get
{
if (_index == 0 || (_index == _sortedList.Count + 1))
{
throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen);
}
return new DictionaryEntry(_key, _value);
}
}
public KeyValuePair<TKey, TValue> Current
{
get
{
return new KeyValuePair<TKey, TValue>(_key, _value);
}
}
object IEnumerator.Current
{
get
{
if (_index == 0 || (_index == _sortedList.Count + 1))
{
throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen);
}
if (_getEnumeratorRetType == DictEntry)
{
return new DictionaryEntry(_key, _value);
}
else
{
return new KeyValuePair<TKey, TValue>(_key, _value);
}
}
}
object IDictionaryEnumerator.Value
{
get
{
if (_index == 0 || (_index == _sortedList.Count + 1))
{
throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen);
}
return _value;
}
}
void IEnumerator.Reset()
{
if (_version != _sortedList.version)
{
throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion);
}
_index = 0;
_key = default(TKey);
_value = default(TValue);
}
}
private sealed class SortedListKeyEnumerator : IEnumerator<TKey>, IEnumerator
{
private SortedList<TKey, TValue> _sortedList;
private int _index;
private int _version;
private TKey _currentKey;
internal SortedListKeyEnumerator(SortedList<TKey, TValue> sortedList)
{
_sortedList = sortedList;
_version = sortedList.version;
}
public void Dispose()
{
_index = 0;
_currentKey = default(TKey);
}
public bool MoveNext()
{
if (_version != _sortedList.version)
{
throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion);
}
if ((uint)_index < (uint)_sortedList.Count)
{
_currentKey = _sortedList.keys[_index];
_index++;
return true;
}
_index = _sortedList.Count + 1;
_currentKey = default(TKey);
return false;
}
public TKey Current
{
get
{
return _currentKey;
}
}
object IEnumerator.Current
{
get
{
if (_index == 0 || (_index == _sortedList.Count + 1))
{
throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen);
}
return _currentKey;
}
}
void IEnumerator.Reset()
{
if (_version != _sortedList.version)
{
throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion);
}
_index = 0;
_currentKey = default(TKey);
}
}
private sealed class SortedListValueEnumerator : IEnumerator<TValue>, IEnumerator
{
private SortedList<TKey, TValue> _sortedList;
private int _index;
private int _version;
private TValue _currentValue;
internal SortedListValueEnumerator(SortedList<TKey, TValue> sortedList)
{
_sortedList = sortedList;
_version = sortedList.version;
}
public void Dispose()
{
_index = 0;
_currentValue = default(TValue);
}
public bool MoveNext()
{
if (_version != _sortedList.version)
{
throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion);
}
if ((uint)_index < (uint)_sortedList.Count)
{
_currentValue = _sortedList.values[_index];
_index++;
return true;
}
_index = _sortedList.Count + 1;
_currentValue = default(TValue);
return false;
}
public TValue Current
{
get
{
return _currentValue;
}
}
object IEnumerator.Current
{
get
{
if (_index == 0 || (_index == _sortedList.Count + 1))
{
throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen);
}
return _currentValue;
}
}
void IEnumerator.Reset()
{
if (_version != _sortedList.version)
{
throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion);
}
_index = 0;
_currentValue = default(TValue);
}
}
[DebuggerTypeProxy(typeof(DictionaryKeyCollectionDebugView<,>))]
[DebuggerDisplay("Count = {Count}")]
[Serializable]
public sealed class KeyList : IList<TKey>, ICollection
{
private SortedList<TKey, TValue> _dict; // Do not rename (binary serialization)
internal KeyList(SortedList<TKey, TValue> dictionary)
{
_dict = dictionary;
}
public int Count
{
get { return _dict._size; }
}
public bool IsReadOnly
{
get { return true; }
}
bool ICollection.IsSynchronized
{
get { return false; }
}
object ICollection.SyncRoot
{
get { return ((ICollection)_dict).SyncRoot; }
}
public void Add(TKey key)
{
throw new NotSupportedException(SR.NotSupported_SortedListNestedWrite);
}
public void Clear()
{
throw new NotSupportedException(SR.NotSupported_SortedListNestedWrite);
}
public bool Contains(TKey key)
{
return _dict.ContainsKey(key);
}
public void CopyTo(TKey[] array, int arrayIndex)
{
// defer error checking to Array.Copy
Array.Copy(_dict.keys, 0, array, arrayIndex, _dict.Count);
}
void ICollection.CopyTo(Array array, int arrayIndex)
{
if (array != null && array.Rank != 1)
throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array));
try
{
// defer error checking to Array.Copy
Array.Copy(_dict.keys, 0, array, arrayIndex, _dict.Count);
}
catch (ArrayTypeMismatchException)
{
throw new ArgumentException(SR.Argument_InvalidArrayType, nameof(array));
}
}
public void Insert(int index, TKey value)
{
throw new NotSupportedException(SR.NotSupported_SortedListNestedWrite);
}
public TKey this[int index]
{
get
{
return _dict.GetKey(index);
}
set
{
throw new NotSupportedException(SR.NotSupported_KeyCollectionSet);
}
}
public IEnumerator<TKey> GetEnumerator()
{
return new SortedListKeyEnumerator(_dict);
}
IEnumerator IEnumerable.GetEnumerator()
{
return new SortedListKeyEnumerator(_dict);
}
public int IndexOf(TKey key)
{
if (((object)key) == null)
throw new ArgumentNullException(nameof(key));
int i = Array.BinarySearch<TKey>(_dict.keys, 0,
_dict.Count, key, _dict.comparer);
if (i >= 0) return i;
return -1;
}
public bool Remove(TKey key)
{
throw new NotSupportedException(SR.NotSupported_SortedListNestedWrite);
// return false;
}
public void RemoveAt(int index)
{
throw new NotSupportedException(SR.NotSupported_SortedListNestedWrite);
}
}
[DebuggerTypeProxy(typeof(DictionaryValueCollectionDebugView<,>))]
[DebuggerDisplay("Count = {Count}")]
[Serializable]
public sealed class ValueList : IList<TValue>, ICollection
{
private SortedList<TKey, TValue> _dict; // Do not rename (binary serialization)
internal ValueList(SortedList<TKey, TValue> dictionary)
{
_dict = dictionary;
}
public int Count
{
get { return _dict._size; }
}
public bool IsReadOnly
{
get { return true; }
}
bool ICollection.IsSynchronized
{
get { return false; }
}
object ICollection.SyncRoot
{
get { return ((ICollection)_dict).SyncRoot; }
}
public void Add(TValue key)
{
throw new NotSupportedException(SR.NotSupported_SortedListNestedWrite);
}
public void Clear()
{
throw new NotSupportedException(SR.NotSupported_SortedListNestedWrite);
}
public bool Contains(TValue value)
{
return _dict.ContainsValue(value);
}
public void CopyTo(TValue[] array, int arrayIndex)
{
// defer error checking to Array.Copy
Array.Copy(_dict.values, 0, array, arrayIndex, _dict.Count);
}
void ICollection.CopyTo(Array array, int index)
{
if (array != null && array.Rank != 1)
throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array));
try
{
// defer error checking to Array.Copy
Array.Copy(_dict.values, 0, array, index, _dict.Count);
}
catch (ArrayTypeMismatchException)
{
throw new ArgumentException(SR.Argument_InvalidArrayType, nameof(array));
}
}
public void Insert(int index, TValue value)
{
throw new NotSupportedException(SR.NotSupported_SortedListNestedWrite);
}
public TValue this[int index]
{
get
{
return _dict.GetByIndex(index);
}
set
{
throw new NotSupportedException(SR.NotSupported_SortedListNestedWrite);
}
}
public IEnumerator<TValue> GetEnumerator()
{
return new SortedListValueEnumerator(_dict);
}
IEnumerator IEnumerable.GetEnumerator()
{
return new SortedListValueEnumerator(_dict);
}
public int IndexOf(TValue value)
{
return Array.IndexOf(_dict.values, value, 0, _dict.Count);
}
public bool Remove(TValue value)
{
throw new NotSupportedException(SR.NotSupported_SortedListNestedWrite);
// return false;
}
public void RemoveAt(int index)
{
throw new NotSupportedException(SR.NotSupported_SortedListNestedWrite);
}
}
}
}
| |
#region MIT.
//
// Gorgon.
// Copyright (C) 2011 Michael Winsor
//
// 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
// 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.
//
// Created: Saturday, June 18, 2011 4:20:26 PM
//
#endregion
using System;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Text;
using System.Windows.Forms;
namespace Gorgon.UI
{
/// <summary>
/// The base form for Gorgon dialogs.
/// </summary>
internal partial class BaseDialog
: Form
{
#region Variables.
private string _message = string.Empty; // Message to be displayed.
private Point _textPosition = new(60, 2); // Text position.
private Size _maxTextSize; // Maximum text size.
#endregion
#region Properties
/// <summary>
/// Property to set or return the maximum width of the text.
/// </summary>
protected int MessageWidth
{
get => _maxTextSize.Width;
set => _maxTextSize.Width = value;
}
/// <summary>
/// Property to set or return the maximum height of the text.
/// </summary>
public int MessageHeight
{
get => _maxTextSize.Height;
set => _maxTextSize.Height = value;
}
/// <summary>
/// Property to set or return the image for the dialog.
/// </summary>
public Image DialogImage
{
get => pictureDialog.Image;
set => pictureDialog.Image = value;
}
/// <summary>
/// Property to set or return the action for the default button.
/// </summary>
[Browsable(false)]
public DialogResult ButtonAction
{
get => buttonOK.DialogResult;
set => buttonOK.DialogResult = value;
}
/// <summary>
/// Property to set or return the message for the dialog.
/// </summary>
[Browsable(false)]
public virtual string Message
{
get => _message;
set
{
_message = value;
ValidateFunctions();
}
}
#endregion
#region Methods.
/// <summary>
/// Raises the <see cref="E:System.Windows.Forms.Control.KeyDown"></see> event.
/// </summary>
/// <param name="e">A <see cref="KeyEventArgs"></see> that contains the event data.</param>
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
if (e.KeyCode == Keys.Escape)
{
Close();
}
}
/// <summary>
/// Function to validate the various functions bound to the form.
/// </summary>
protected virtual void ValidateFunctions()
{
}
/// <summary>
/// Form load event.
/// </summary>
/// <param name="e">Event arguments.</param>
protected override void OnLoad(EventArgs e)
{
if (DesignMode)
{
return;
}
var currentScreen = Screen.FromControl(this);
_textPosition = new Point(pictureDialog.DisplayRectangle.Right + 4, 2);
if (_maxTextSize.Height <= 0)
{
_maxTextSize.Height = currentScreen.WorkingArea.Height - (ClientSize.Height - buttonOK.Top - 8);
}
_maxTextSize.Width = _maxTextSize.Width <= 0 ? currentScreen.WorkingArea.Width / 4 : _maxTextSize.Width;
// Inherit the parent icon.
if (Owner is not null)
{
Icon = Owner.Icon;
}
ValidateFunctions();
OnSizeChanged(EventArgs.Empty);
Visible = true;
}
/// <summary>
/// Raises the <see cref="E:System.Windows.Forms.Form.Shown"></see> event.
/// </summary>
/// <param name="e">A <see cref="EventArgs"></see> that contains the event data.</param>
protected override void OnShown(EventArgs e)
{
base.OnShown(e);
if ((!DesignMode) && (Owner is not null))
{
Icon = Owner.Icon;
}
}
/// <summary>
/// Function to perform the actual drawing of the dialog.
/// </summary>
/// <param name="g">Graphics object to use.</param>
protected virtual void DrawDialog(System.Drawing.Graphics g)
{
// Get size.
float maxTextHeight = AdjustSize(g, 0);
// Relocate buttons.
buttonOK.Left = ClientSize.Width - buttonOK.Width - 8;
buttonOK.Top = ClientSize.Height - 6 - buttonOK.Height;
DrawMessage(g, maxTextHeight);
}
/// <summary>
/// Function to adjust the size of the form based on the details.
/// </summary>
/// <param name="g">Graphics interface.</param>
/// <param name="margin">Places a margin at the bottom of the form.</param>
/// <returns>The new maximum height of the client area.</returns>
protected float AdjustSize(System.Drawing.Graphics g, int margin)
{
g.PageUnit = GraphicsUnit.Pixel;
SizeF textDimensions = g.MeasureString(_message, Font, _maxTextSize.Width);
// Resize the form if needed.
Size newClientSize = ClientSize;
if (textDimensions.Width + _textPosition.X > newClientSize.Width)
{
newClientSize.Width = (int)textDimensions.Width + _textPosition.X + 8;
}
float maxTextHeight = textDimensions.Height;
if (maxTextHeight > _maxTextSize.Height)
{
maxTextHeight = _maxTextSize.Height;
}
if (maxTextHeight + 2 > newClientSize.Height - buttonOK.Height - (10 + margin))
{
newClientSize.Height = ((int)maxTextHeight) + 2 + buttonOK.Height + 10 + margin;
}
if ((ClientSize.Width != newClientSize.Width) || (ClientSize.Height != newClientSize.Height))
{
ClientSize = newClientSize;
}
return maxTextHeight;
}
/// <summary>
/// Function to draw the dialog box message.
/// </summary>
/// <param name="g">Graphics interface.</param>
/// <param name="maxTextHeight">Maximum height that the text will fit into.</param>
protected void DrawMessage(System.Drawing.Graphics g, float maxTextHeight)
{
int borderHeight = buttonOK.Top - 5;
g.TextRenderingHint = TextRenderingHint.ClearTypeGridFit;
SizeF textDimensions = g.MeasureString(_message, Font, new SizeF(_maxTextSize.Width - 2, maxTextHeight));
using (Brush backBrush = new SolidBrush(Color.FromArgb(255, 240, 240, 240)))
{
g.FillRectangle(backBrush, 0, 0, Size.Width, borderHeight);
}
g.FillRectangle(Brushes.White, 0, borderHeight + 1, Size.Width, DisplayRectangle.Bottom - borderHeight + 1);
pictureDialog.Refresh();
g.DrawLine(Pens.Black, new Point(0, borderHeight), new Point(Size.Width, borderHeight));
g.DrawString(_message, Font, Brushes.Black, new RectangleF(_textPosition.X, 2, textDimensions.Width, maxTextHeight));
}
/// <summary>
/// Size changed event.
/// </summary>
/// <param name="e">Event arguments.</param>
protected override void OnSizeChanged(EventArgs e)
{
if (DesignMode)
{
return;
}
// Reposition.
if (StartPosition is not FormStartPosition.CenterScreen and not FormStartPosition.CenterParent)
{
return;
}
if (Parent is null)
{
CenterToScreen();
}
else
{
CenterToParent();
}
}
/// <summary>Raises the <see cref="E:System.Windows.Forms.Control.Paint" /> event.</summary>
/// <param name="e">A <see cref="PaintEventArgs" /> that contains the event data.</param>
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
if (!DesignMode)
{
DrawDialog(e.Graphics);
}
}
#endregion
#region Constructor
/// <summary>
/// Constructor.
/// </summary>
public BaseDialog() => InitializeComponent();
#endregion
}
}
| |
using System.Collections;
using System.Collections.Generic;
namespace System.Linq
{
[Bridge.Convention(Member = Bridge.ConventionMember.Field | Bridge.ConventionMember.Method, Notation = Bridge.Notation.CamelCase)]
[Bridge.External]
[Bridge.IgnoreGeneric]
public class EnumerableInstance<TElement> : IEnumerable<TElement>
{
internal extern EnumerableInstance();
[Bridge.Convention(Bridge.Notation.None)]
public extern IEnumerator<TElement> GetEnumerator();
[Bridge.Convention(Bridge.Notation.None)]
extern IEnumerator IEnumerable.GetEnumerator();
public extern TElement Aggregate(Func<TElement, TElement, TElement> func);
public extern TAccumulate Aggregate<TAccumulate>(TAccumulate seed, Func<TAccumulate, TElement, TAccumulate> func);
public extern TResult Aggregate<TAccumulate, TResult>(TAccumulate seed, Func<TAccumulate, TElement, TAccumulate> func,
Func<TAccumulate, TResult> resultSelector);
public extern bool All(Func<TElement, bool> predicate);
public extern EnumerableInstance<TElement> Alternate(TElement value);
public extern bool Any();
public extern bool Any(Func<TElement, bool> predicate);
public extern double Average(Func<TElement, int> selector);
public extern double Average(Func<TElement, long> selector);
public extern float Average(Func<TElement, float> selector);
public extern double Average(Func<TElement, double> selector);
[Bridge.Template("{this}.average({selector}, System.Decimal.Zero)")]
public extern decimal Average(Func<TElement, decimal> selector);
public extern EnumerableInstance<TElement[]> Buffer(int count);
public extern EnumerableInstance<TElement> CascadeBreadthFirst(Func<TElement, IEnumerable<TElement>> func);
public extern EnumerableInstance<TResult> CascadeBreadthFirst<TResult>(Func<TElement, IEnumerable<TElement>> func,
Func<TElement, TResult> resultSelector);
public extern EnumerableInstance<TResult> CascadeBreadthFirst<TResult>(Func<TElement, IEnumerable<TElement>> func,
Func<TElement, int, TResult> resultSelector);
public extern EnumerableInstance<TElement> CascadeDepthFirst(Func<TElement, IEnumerable<TElement>> func);
public extern EnumerableInstance<TResult> CascadeDepthFirst<TResult>(Func<TElement, IEnumerable<TElement>> func,
Func<TElement, TResult> resultSelector);
public extern EnumerableInstance<TResult> CascadeDepthFirst<TResult>(Func<TElement, IEnumerable<TElement>> func,
Func<TElement, int, TResult> resultSelector);
[Bridge.Template("{this}.select(function (x) {{ return Bridge.cast(x, {TResult}); }})")]
public extern EnumerableInstance<TResult> Cast<TResult>();
public extern EnumerableInstance<TElement> CatchError(Action<Exception> action);
public extern EnumerableInstance<TElement> Concat(IEnumerable<TElement> other);
public extern bool Contains(TElement value);
public extern bool Contains(TElement value, IEqualityComparer<TElement> comparer);
public extern int Count();
public extern int Count(Func<TElement, bool> predicate);
[Bridge.Template("{this}.defaultIfEmpty({TElement:default})")]
public extern EnumerableInstance<TElement> DefaultIfEmpty();
public extern EnumerableInstance<TElement> DefaultIfEmpty(TElement defaultValue);
public extern EnumerableInstance<TElement> Distinct();
public extern EnumerableInstance<TElement> Distinct(IEqualityComparer<TElement> comparer);
public extern EnumerableInstance<TElement> DoAction(Action<TElement> action);
public extern EnumerableInstance<TElement> DoAction(Action<TElement, int> action);
public extern TElement ElementAt(int index);
[Bridge.Template("{this}.elementAtOrDefault({index}, {TElement:default})")]
public extern TElement ElementAtOrDefault(int index);
public extern TElement ElementAtOrDefault(int index, TElement defaultValue);
public extern EnumerableInstance<TElement> Except(IEnumerable<TElement> other);
public extern EnumerableInstance<TElement> Except(IEnumerable<TElement> other, IEqualityComparer<TElement> comparer);
public extern EnumerableInstance<TElement> FinallyAction(Action action);
public extern TElement First();
public extern TElement First(Func<TElement, bool> predicate);
[Bridge.Template("{this}.firstOrDefault(null, {TElement:default})")]
public extern TElement FirstOrDefault();
[Bridge.Template("{this}.firstOrDefault(null, {defaultValue})")]
public extern TElement FirstOrDefault(TElement defaultValue);
[Bridge.Template("{this}.firstOrDefault({predicate}, {TElement:default})")]
public extern TElement FirstOrDefault(Func<TElement, bool> predicate);
[Bridge.Template("{this}.firstOrDefault({predicate}, {defaultValue})")]
public extern TElement FirstOrDefault(Func<TElement, bool> predicate, TElement defaultValue);
public extern EnumerableInstance<object> Flatten();
public extern void Force();
public extern void ForEach(Action<TElement> action);
public extern void ForEach(Func<TElement, bool> action);
public extern void ForEach(Action<TElement, int> action);
public extern void ForEach(Func<TElement, int, bool> action);
public extern EnumerableInstance<Grouping<TKey, TElement>> GroupBy<TKey>(Func<TElement, TKey> keySelector);
[Bridge.Template("{this}.groupBy({keySelector}, null, null, {comparer})")]
public extern EnumerableInstance<Grouping<TKey, TElement>> GroupBy<TKey>(Func<TElement, TKey> keySelector,
IEqualityComparer<TKey> comparer);
public extern EnumerableInstance<Grouping<TKey, TSource>> GroupBy<TKey, TSource>(Func<TSource, TKey> keySelector,
Func<TSource, TSource> elementSelector);
[Bridge.Template("{this}.groupBy({keySelector}, null, {resultSelector})")]
public extern EnumerableInstance<TResult> GroupBy<TKey, TResult>(Func<TElement, TKey> keySelector,
Func<TKey, IEnumerable<TElement>, TResult> resultSelector);
[Bridge.Template("{this}.groupBy({keySelector}, {elementSelector}, null, {comparer})")]
public extern EnumerableInstance<Grouping<TKey, TSource>> GroupBy<TKey, TSource>(Func<TSource, TKey> keySelector,
Func<TSource, TSource> elementSelector, IEqualityComparer<TKey> comparer);
public extern EnumerableInstance<TResult> GroupBy<TKey, TSource, TResult>(Func<TSource, TKey> keySelector,
Func<TSource, TSource> elementSelector, Func<TKey, IEnumerable<TSource>, TResult> resultSelector);
[Bridge.Template("{this}.groupBy({keySelector}, null, {resultSelector}, {comparer})")]
public extern EnumerableInstance<TResult> GroupBy<TKey, TResult>(Func<TElement, TKey> keySelector,
Func<TKey, IEnumerable<TElement>, TResult> resultSelector, IEqualityComparer<TKey> comparer);
public extern EnumerableInstance<TResult> GroupBy<TKey, TSource, TResult>(Func<TSource, TKey> keySelector,
Func<TSource, TSource> elementSelector, Func<TKey, IEnumerable<TSource>, TResult> resultSelector,
IEqualityComparer<TKey> comperer);
public extern EnumerableInstance<TResult> GroupJoin<TInner, TKey, TResult>(IEnumerable<TInner> inner,
Func<TElement, TKey> outerKeySelector, Func<TInner, TKey> innerKeySelector,
Func<TElement, IEnumerable<TInner>, TResult> resultSelector);
public extern EnumerableInstance<TResult> GroupJoin<TInner, TKey, TResult>(IEnumerable<TInner> inner,
Func<TElement, TKey> outerKeySelector, Func<TInner, TKey> innerKeySelector,
Func<TElement, IEnumerable<TInner>, TResult> resultSelector, IEqualityComparer<TKey> comparer);
public extern int IndexOf(TElement item);
public extern int IndexOf(TElement item, Func<TElement, bool> predicate);
public extern int IndexOf(TElement item, IEqualityComparer<TElement> comparer);
public extern EnumerableInstance<TElement> Insert(int index, IEnumerable<TElement> other);
public extern EnumerableInstance<TResult> Join<TInner, TKey, TResult>(IEnumerable<TInner> inner,
Func<TElement, TKey> outerKeySelector, Func<TInner, TKey> innerKeySelector,
Func<TElement, TInner, TResult> resultSelector);
public extern EnumerableInstance<TResult> Join<TInner, TKey, TResult>(IEnumerable<TInner> inner,
Func<TElement, TKey> outerKeySelector, Func<TInner, TKey> innerKeySelector,
Func<TElement, TInner, TResult> resultSelector, IEqualityComparer<TKey> comparer);
public extern TElement Last();
public extern TElement Last(Func<TElement, bool> predicate);
public extern int LastIndexOf(TElement item);
public extern int LastIndexOf(TElement item, Func<TElement, bool> predicate);
public extern int LastIndexOf(TElement item, IEqualityComparer<TElement> comparer);
[Bridge.Template("{this}.count()")]
public extern long LongCount<TSource>();
[Bridge.Template("{this}.count({predicate})")]
public extern long LongCount<TSource>(Func<TSource, bool> predicate);
[Bridge.Template("{this}.lastOrDefault(null, {TElement:default})")]
public extern TElement LastOrDefault();
[Bridge.Template("{this}.lastOrDefault(null, {defaultValue})")]
public extern TElement LastOrDefault(TElement defaultValue);
[Bridge.Template("{this}.lastOrDefault({predicate}, {TElement:default})")]
public extern TElement LastOrDefault(Func<TElement, bool> predicate);
[Bridge.Template("{this}.lastOrDefault({predicate}, {defaultValue})")]
public extern TElement LastOrDefault(Func<TElement, bool> predicate, TElement defaultValue);
public extern EnumerableInstance<TResult> LetBind<TResult>(Func<IEnumerable<TElement>, IEnumerable<TResult>> func);
public extern TSource Max<TSource>();
public extern TResult Max<TSource, TResult>(Func<TSource, TResult> selector);
public extern int Max(Func<TElement, int> selector);
public extern long Max(Func<TElement, long> selector);
public extern float Max(Func<TElement, float> selector);
public extern double Max(Func<TElement, double> selector);
public extern decimal Max(Func<TElement, decimal> selector);
public extern TElement MaxBy(Func<TElement, int> selector);
public extern TElement MaxBy(Func<TElement, long> selector);
public extern TElement MaxBy(Func<TElement, float> selector);
public extern TElement MaxBy(Func<TElement, double> selector);
public extern TElement MaxBy(Func<TElement, decimal> selector);
public extern EnumerableInstance<TElement> Memoize();
public extern TSource Min<TSource>();
public extern TResult Min<TSource, TResult>(Func<TSource, TResult> selector);
public extern int Min(Func<TElement, int> selector);
public extern long Min(Func<TElement, long> selector);
public extern float Min(Func<TElement, float> selector);
public extern double Min(Func<TElement, double> selector);
public extern decimal Min(Func<TElement, decimal> selector);
public extern TElement MinBy(Func<TElement, int> selector);
public extern TElement MinBy(Func<TElement, long> selector);
public extern TElement MinBy(Func<TElement, float> selector);
public extern TElement MinBy(Func<TElement, double> selector);
public extern TElement MinBy(Func<TElement, decimal> selector);
[Bridge.Template("{this}.ofType({TResult})")]
public extern EnumerableInstance<TResult> OfType<TResult>();
public extern OrderedEnumerable<TElement> OrderBy();
public extern OrderedEnumerable<TElement> OrderBy<TKey>(Func<TElement, TKey> keySelector);
public extern OrderedEnumerable<TElement> OrderBy<TKey>(Func<TElement, TKey> keySelector, IComparer<TKey> comparer);
public extern OrderedEnumerable<TElement> OrderByDescending();
public extern OrderedEnumerable<TElement> OrderByDescending<TKey>(Func<TElement, TKey> keySelector);
public extern OrderedEnumerable<TElement> OrderByDescending<TKey>(Func<TElement, TKey> keySelector,
IComparer<TKey> comparer);
public extern EnumerableInstance<TResult> Pairwise<TResult>(Func<TElement, TElement, TResult> selector);
public extern EnumerableInstance<Grouping<TKey, TElement>> PartitionBy<TKey>(Func<TElement, TKey> keySelector);
[Bridge.Template("{this}.partitionBy({keySelector}, null, null, {comparer})")]
public extern EnumerableInstance<Grouping<TKey, TElement>> PartitionBy<TKey>(Func<TElement, TKey> keySelector,
IEqualityComparer<TKey> comparer);
public extern EnumerableInstance<Grouping<TKey, TSource>> PartitionBy<TKey, TSource>(
Func<TSource, TKey> keySelector, Func<TSource, TSource> elementSelector);
[Bridge.Template("{this}.partitionBy({keySelector}, null, {resultSelector})")]
public extern EnumerableInstance<TResult> PartitionBy<TKey, TResult>(Func<TElement, TKey> keySelector,
Func<TKey, IEnumerable<TElement>, TResult> resultSelector);
[Bridge.Template("{this}.partitionBy({keySelector}, {elementSelector}, null, {comparer})")]
public extern EnumerableInstance<Grouping<TKey, TSource>> PartitionBy<TKey, TSource>(
Func<TSource, TKey> keySelector, Func<TSource, TSource> elementSelector, IEqualityComparer<TKey> comparer);
public extern EnumerableInstance<TResult> PartitionBy<TKey, TSource, TResult>(Func<TSource, TKey> keySelector,
Func<TSource, TSource> elementSelector, Func<TKey, IEnumerable<TSource>, TResult> resultSelector);
[Bridge.Template("{this}.partitionBy({keySelector}, null, {resultSelector}, {comparer})")]
public extern EnumerableInstance<TResult> PartitionBy<TKey, TResult>(Func<TElement, TKey> keySelector,
Func<TKey, IEnumerable<TElement>, TResult> resultSelector, IEqualityComparer<TKey> comparer);
public extern EnumerableInstance<TResult> PartitionBy<TKey, TSource, TResult>(Func<TSource, TKey> keySelector,
Func<TSource, TSource> elementSelector, Func<TKey, IEnumerable<TSource>, TResult> resultSelector,
IEqualityComparer<TKey> comperer);
public extern EnumerableInstance<TElement> Reverse();
public extern EnumerableInstance<T> Scan<T>(Func<T, T, T> func);
public extern EnumerableInstance<TAccumulate> Scan<TAccumulate>(TAccumulate seed,
Func<TAccumulate, TElement, TAccumulate> func);
public extern EnumerableInstance<TResult> Select<TResult>(Func<TElement, TResult> selector);
public extern EnumerableInstance<TResult> Select<TResult>(Func<TElement, int, TResult> selector);
public extern EnumerableInstance<TResult> SelectMany<TResult>(Func<TElement, IEnumerable<TResult>> selector);
public extern EnumerableInstance<TResult> SelectMany<TResult>(Func<TElement, int, IEnumerable<TResult>> selector);
public extern EnumerableInstance<TResult> SelectMany<TCollection, TResult>(
Func<TElement, IEnumerable<TCollection>> collectionSelector,
Func<TElement, TCollection, TResult> resultSelector);
public extern EnumerableInstance<TResult> SelectMany<TCollection, TResult>(
Func<TElement, int, IEnumerable<TCollection>> collectionSelector,
Func<TElement, TCollection, TResult> resultSelector);
public extern bool SequenceEqual(IEnumerable<TElement> other);
public extern bool SequenceEqual<TKey>(IEnumerable<TElement> other, Func<TElement, TKey> compareSelector);
public extern EnumerableInstance<TElement> Share();
public extern EnumerableInstance<TElement> Shuffle();
public extern TElement Single();
public extern TElement Single(Func<TElement, bool> predicate);
[Bridge.Template("{this}.singleOrDefault(null, {TElement:default})")]
public extern TElement SingleOrDefault();
[Bridge.Template("{this}.singleOrDefault(null, {defaultValue})")]
public extern TElement SingleOrDefault(TElement defaultValue);
[Bridge.Template("{this}.singleOrDefault({predicate}, {TElement:default})")]
public extern TElement SingleOrDefault(Func<TElement, bool> predicate);
[Bridge.Template("{this}.singleOrDefault({predicate}, {defaultValue})")]
public extern TElement SingleOrDefault(Func<TElement, bool> predicate, TElement defaultValue);
public extern EnumerableInstance<TElement> Skip(int count);
public extern EnumerableInstance<TElement> SkipWhile(Func<TElement, bool> predicate);
public extern EnumerableInstance<TElement> SkipWhile(Func<TElement, int, bool> predicate);
public extern int Sum(Func<TElement, int> selector);
[Bridge.Template("{this}.sum({selector}, System.Int64.Zero)")]
public extern long Sum(Func<TElement, long> selector);
public extern float Sum(Func<TElement, float> selector);
public extern double Sum(Func<TElement, double> selector);
[Bridge.Template("{this}.sum({selector}, System.Decimal.Zero)")]
public extern decimal Sum(Func<TElement, decimal> selector);
public extern EnumerableInstance<TElement> Take(int count);
public extern EnumerableInstance<TElement> TakeExceptLast();
public extern EnumerableInstance<TElement> TakeExceptLast(int count);
public extern EnumerableInstance<TElement> TakeFromLast(int count);
public extern EnumerableInstance<TElement> TakeWhile(Func<TElement, bool> predicate);
public extern EnumerableInstance<TElement> TakeWhile(Func<TElement, int, bool> predicate);
public static extern IOrderedEnumerable<TSource> ThenBy<TSource, TKey>(Func<TSource, TKey> keySelector);
public static extern IOrderedEnumerable<TSource> ThenBy<TSource, TKey>(Func<TSource, TKey> keySelector, IComparer<TKey> comparer);
public static extern IOrderedEnumerable<TSource> ThenByDescending<TSource, TKey>(Func<TSource, TKey> keySelector);
public static extern IOrderedEnumerable<TSource> ThenByDescending<TSource, TKey>(Func<TSource, TKey> keySelector, IComparer<TKey> comparer);
[Bridge.Template("{this}.ToArray({TElement})")]
public extern TElement[] ToArray();
[Bridge.Template("{this}.toDictionary({keySelector}, null, {TKey}, {TElement})")]
public extern Dictionary<TKey, TElement> ToDictionary<TKey>(Func<TElement, TKey> keySelector);
[Bridge.Template("{this}.toDictionary({keySelector}, null, {TKey}, {TElement}, {comparer})")]
public extern Dictionary<TKey, TElement> ToDictionary<TKey>(Func<TElement, TKey> keySelector,
IEqualityComparer<TKey> comparer);
[Bridge.Template("{this}.toDictionary({keySelector}, {elementSelector}, {TKey}, {TValue})")]
public extern Dictionary<TKey, TValue> ToDictionary<TKey, TValue>(Func<TElement, TKey> keySelector,
Func<TElement, TValue> elementSelector);
[Bridge.Template("{this}.toDictionary({keySelector}, {elementSelector}, {TKey}, {TValue}, {comparer})")]
public extern Dictionary<TKey, TValue> ToDictionary<TKey, TValue>(Func<TElement, TKey> keySelector,
Func<TElement, TValue> elementSelector, IEqualityComparer<TKey> comparer);
public extern string ToJoinedString();
public extern string ToJoinedString(string separator);
public extern string ToJoinedString(string separator, Func<TElement, string> selector);
[Bridge.Template("{this}.toList({TElement})")]
public extern List<TElement> ToList();
public extern Lookup<TKey, TElement> ToLookup<TKey>(Func<TElement, TKey> keySelector);
[Bridge.Template("{this}.toLookup({keySelector}, null, {comparer})")]
public extern Lookup<TKey, TElement> ToLookup<TKey>(Func<TElement, TKey> keySelector, IEqualityComparer<TKey> comparer);
public extern Lookup<TKey, TSource> ToLookup<TKey, TSource>(Func<TSource, TKey> keySelector,
Func<TSource, TSource> elementSelector);
public extern Lookup<TKey, TSource> ToLookup<TKey, TSource>(Func<TSource, TKey> keySelector,
Func<TSource, TSource> elementSelector, IEqualityComparer<TKey> comparer);
public extern object ToObject<TKey, TValue>(Func<TElement, TKey> keySelector,
Func<TElement, TValue> valueSelector);
public extern EnumerableInstance<TElement> Trace();
public extern EnumerableInstance<TElement> Trace(string message);
public extern EnumerableInstance<TElement> Trace(string message, Func<TElement, string> selector);
public extern EnumerableInstance<TElement> Union(IEnumerable<TElement> other);
public extern EnumerableInstance<TElement> Union(IEnumerable<TElement> other, IEqualityComparer<TElement> comparer);
public extern EnumerableInstance<TElement> Where(Func<TElement, bool> predicate);
public extern EnumerableInstance<TElement> Where(Func<TElement, int, bool> predicate);
public extern EnumerableInstance<TResult> Zip<TOther, TResult>(IEnumerable<TOther> other,
Func<TElement, TOther, TResult> selector);
public extern EnumerableInstance<TResult> Zip<TOther, TResult>(IEnumerable<TOther> other,
Func<TElement, TOther, int, TResult> selector);
}
}
| |
#region License
//-----------------------------------------------------------------------
// <copyright>
// The MIT License (MIT)
//
// Copyright (c) 2014 Kirk S Woll
//
// 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.
// </copyright>
//-----------------------------------------------------------------------
#endregion
using System.Collections.Generic;
using System.Runtime.WootzJs;
using System.Text;
namespace System
{
/// <summary>
/// Equivalent to the Number type in Javascript.
/// </summary>
[Js(Name = "Number", BuiltIn = true, BaseType = typeof(Object))]
public abstract class Number : IComparable
{
public const int MAX_VALUE = 0;
public const int MIN_VALUE = 0;
public const int NaN = 0;
public const int NEGATIVE_INFINITY = 0;
public const int POSITIVE_INFINITY = 0;
[Js(Name = "GetType")]
public new Type GetType()
{
return base.GetType();
}
public string Format(string format)
{
return null;
}
public static bool IsFinite(Number n)
{
return false;
}
public static bool IsNaN(Number n)
{
return false;
}
public string LocaleFormat(string format)
{
return null;
}
public static Number Parse(string s)
{
return null;
}
public static double ParseDouble(string s)
{
return 0.0;
}
public static float ParseFloat(string s)
{
return 0f;
}
public static int ParseInt(float f)
{
return 0;
}
public static int ParseInt(double d)
{
return 0;
}
public static int ParseInt(string s)
{
return 0;
}
public static int ParseInt(string s, int radix)
{
return 0;
}
/// <summary>
/// Returns a string containing the number represented in exponential notation.
/// </summary>
/// <returns>The exponential representation</returns>
public string ToExponential()
{
return null;
}
/// <summary>
/// Returns a string containing the number represented in exponential notation.
/// </summary>
/// <param name="fractionDigits">The number of digits after the decimal point (0 - 20)</param>
/// <returns>The exponential representation</returns>
public string ToExponential(int fractionDigits)
{
return null;
}
/// <summary>
/// Returns a string representing the number in fixed-point notation.
/// </summary>
/// <returns>The fixed-point notation</returns>
public string ToFixed()
{
return null;
}
/// <summary>
/// Returns a string representing the number in fixed-point notation.
/// </summary>
/// <param name="fractionDigits">The number of digits after the decimal point from 0 - 20</param>
/// <returns>The fixed-point notation</returns>
public string ToFixed(int fractionDigits)
{
return null;
}
/// <summary>
/// Returns a string containing the number represented either in exponential or
/// fixed-point notation with a specified number of digits.
/// </summary>
/// <returns>The string representation of the value.</returns>
public string ToPrecision()
{
return null;
}
/// <summary>
/// Returns a string containing the number represented either in exponential or
/// fixed-point notation with a specified number of digits.
/// </summary>
/// <param name="precision">The number of significant digits (in the range 1 to 21)</param>
/// <returns>The string representation of the value.</returns>
public string ToPrecision(int precision)
{
return null;
}
/// <summary>
/// Converts the value to its string representation.
/// </summary>
/// <param name="radix">The radix used in the conversion (eg. 10 for decimal, 16 for hexadecimal)</param>
/// <returns>The string representation of the value.</returns>
public string ToString(int radix)
{
return null;
}
enum DecimalState { Before, On, After }
public string ToString(string format)
{
if (string.IsNullOrEmpty(format))
return ToString();
if (format[0] == 'X')
{
var radix = 16;
var remainingFormat = format.Substring(1);
var s = this.As<JsNumber>().toString(radix);
if (remainingFormat.Length > 0)
{
var minimumDigits = int.Parse(remainingFormat);
while (s.length < minimumDigits.As<JsNumber>())
s = "0" + s;
}
return s;
}
else
{
var parts = this.ToString().Split('.');
var leftOfDecimal = parts[0];
var rightOfDecimal = parts.Length > 1 ? parts[1] : "";
var leftDigits = new Queue<char>(leftOfDecimal);
var rightDigits = new Queue<char>(rightOfDecimal);
var result = new StringBuilder();
if (this.As<JsNumber>() < 0)
result.Append("-");
var state = DecimalState.Before;
foreach (var token in format)
{
switch (token)
{
case '0':
case '#':
switch (state)
{
case DecimalState.Before:
if (leftDigits.Count > 0)
result.Append(leftDigits.Dequeue());
else if (token == '0')
result.Append('0');
break;
case DecimalState.On:
state = DecimalState.After;
if ((rightDigits.Count == 0 && token == '0') || rightDigits.Count > 0)
result.Append('.');
if (rightDigits.Count == 0 && token == '0')
result.Append('0');
else if (rightDigits.Count > 0)
result.Append(rightDigits.Dequeue());
break;
case DecimalState.After:
if (rightDigits.Count == 0 && token == '0')
result.Append('0');
else if (rightDigits.Count > 0)
result.Append(rightDigits.Dequeue());
break;
}
break;
case '.':
state = DecimalState.On;
while (leftDigits.Count > 0)
result.Append(leftDigits.Dequeue());
break;
}
}
return result.ToString();
}
}
public int CompareTo(object obj)
{
return (this.As<JsNumber>() - obj.As<JsNumber>()).As<int>();
}
// ReSharper disable once RedundantOverridenMember
/*
public override string GetStringHashCode()
{
// We need to override it to make sure this method gets added to the String prototype.
return base.GetStringHashCode();
}
*/
// ReSharper disable once RedundantOverridenMember
public override bool Equals(object obj)
{
return base.Equals(obj);
}
public override int GetHashCode()
{
return this.As<int>();
}
public override string ToString()
{
return this.As<JsObject>().toString();
}
}
}
| |
//
// Copyright 2011-2013, Xamarin Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Android.Content;
using Android.Content.PM;
using Android.OS;
using Android.Provider;
using Media.Plugin.Abstractions;
namespace Media.Plugin
{
/// <summary>
/// Implementation for Feature
/// </summary>
[Android.Runtime.Preserve(AllMembers = true)]
public class MediaImplementation : IMedia
{
/// <summary>
/// Implementation
/// </summary>
public MediaImplementation()
{
this.context = Android.App.Application.Context;
IsCameraAvailable = context.PackageManager.HasSystemFeature(PackageManager.FeatureCamera);
if (Build.VERSION.SdkInt >= BuildVersionCodes.Gingerbread)
IsCameraAvailable |= context.PackageManager.HasSystemFeature(PackageManager.FeatureCameraFront);
}
/// <inheritdoc/>
public bool IsCameraAvailable
{
get;
private set;
}
/// <inheritdoc/>
public bool IsTakePhotoSupported
{
get { return true; }
}
/// <inheritdoc/>
public bool IsPickPhotoSupported
{
get { return true; }
}
/// <inheritdoc/>
public bool IsTakeVideoSupported
{
get { return true; }
}
/// <inheritdoc/>
public bool IsPickVideoSupported
{
get { return true; }
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public Intent GetPickPhotoUI()
{
int id = GetRequestId();
return CreateMediaIntent(id, "image/*", Intent.ActionPick, null, tasked: false);
}
/// <summary>
///
/// </summary>
/// <param name="options"></param>
/// <returns></returns>
public Intent GetTakePhotoUI(StoreCameraMediaOptions options)
{
if (!IsCameraAvailable)
throw new NotSupportedException();
VerifyOptions(options);
int id = GetRequestId();
return CreateMediaIntent(id, "image/*", MediaStore.ActionImageCapture, options, tasked: false);
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public Intent GetPickVideoUI()
{
int id = GetRequestId();
return CreateMediaIntent(id, "video/*", Intent.ActionPick, null, tasked: false);
}
/// <summary>
///
/// </summary>
/// <param name="options"></param>
/// <returns></returns>
public Intent GetTakeVideoUI(StoreVideoOptions options)
{
if (!IsCameraAvailable)
throw new NotSupportedException();
VerifyOptions(options);
return CreateMediaIntent(GetRequestId(), "video/*", MediaStore.ActionVideoCapture, options, tasked: false);
}
/// <summary>
/// Picks a photo from the default gallery
/// </summary>
/// <returns>Media file or null if canceled</returns>
public Task<Media.Plugin.Abstractions.MediaFile> PickPhotoAsync()
{
return TakeMediaAsync("image/*", Intent.ActionPick, null);
}
/// <summary>
/// Take a photo async with specified options
/// </summary>
/// <param name="options">Camera Media Options</param>
/// <returns>Media file of photo or null if canceled</returns>
public Task<Media.Plugin.Abstractions.MediaFile> TakePhotoAsync(StoreCameraMediaOptions options)
{
if (!IsCameraAvailable)
throw new NotSupportedException();
VerifyOptions(options);
return TakeMediaAsync("image/*", MediaStore.ActionImageCapture, options);
}
/// <summary>
/// Picks a video from the default gallery
/// </summary>
/// <returns>Media file of video or null if canceled</returns>
public Task<Media.Plugin.Abstractions.MediaFile> PickVideoAsync()
{
return TakeMediaAsync("video/*", Intent.ActionPick, null);
}
/// <summary>
/// Take a video with specified options
/// </summary>
/// <param name="options">Video Media Options</param>
/// <returns>Media file of new video or null if canceled</returns>
public Task<Media.Plugin.Abstractions.MediaFile> TakeVideoAsync(StoreVideoOptions options)
{
if (!IsCameraAvailable)
throw new NotSupportedException();
VerifyOptions(options);
return TakeMediaAsync("video/*", MediaStore.ActionVideoCapture, options);
}
private readonly Context context;
private int requestId;
private TaskCompletionSource<Media.Plugin.Abstractions.MediaFile> completionSource;
private void VerifyOptions(StoreMediaOptions options)
{
if (options == null)
throw new ArgumentNullException("options");
if (Path.IsPathRooted(options.Directory))
throw new ArgumentException("options.Directory must be a relative path", "options");
}
private Intent CreateMediaIntent(int id, string type, string action, StoreMediaOptions options, bool tasked = true)
{
Intent pickerIntent = new Intent(this.context, typeof(MediaPickerActivity));
pickerIntent.PutExtra(MediaPickerActivity.ExtraId, id);
pickerIntent.PutExtra(MediaPickerActivity.ExtraType, type);
pickerIntent.PutExtra(MediaPickerActivity.ExtraAction, action);
pickerIntent.PutExtra(MediaPickerActivity.ExtraTasked, tasked);
if (options != null)
{
pickerIntent.PutExtra(MediaPickerActivity.ExtraPath, options.Directory);
pickerIntent.PutExtra(MediaStore.Images.ImageColumns.Title, options.Name);
var vidOptions = (options as StoreVideoOptions);
if (vidOptions != null)
{
pickerIntent.PutExtra(MediaStore.ExtraDurationLimit, (int)vidOptions.DesiredLength.TotalSeconds);
pickerIntent.PutExtra(MediaStore.ExtraVideoQuality, (int)vidOptions.Quality);
}
}
//pickerIntent.SetFlags(ActivityFlags.ClearTop);
pickerIntent.SetFlags(ActivityFlags.NewTask);
return pickerIntent;
}
private int GetRequestId()
{
int id = this.requestId;
if (this.requestId == Int32.MaxValue)
this.requestId = 0;
else
this.requestId++;
return id;
}
private Task<Media.Plugin.Abstractions.MediaFile> TakeMediaAsync(string type, string action, StoreMediaOptions options)
{
int id = GetRequestId();
var ntcs = new TaskCompletionSource<Media.Plugin.Abstractions.MediaFile>(id);
if (Interlocked.CompareExchange(ref this.completionSource, ntcs, null) != null)
throw new InvalidOperationException("Only one operation can be active at a time");
this.context.StartActivity(CreateMediaIntent(id, type, action, options));
EventHandler<MediaPickedEventArgs> handler = null;
handler = (s, e) =>
{
var tcs = Interlocked.Exchange(ref this.completionSource, null);
MediaPickerActivity.MediaPicked -= handler;
if (e.RequestId != id)
return;
if (e.Error != null)
tcs.SetResult(null);
else if (e.IsCanceled)
tcs.SetResult(null);
else
tcs.SetResult(e.Media);
};
MediaPickerActivity.MediaPicked += handler;
return ntcs.Task;
}
}
}
| |
// Copyright 2017 Esri.
//
// 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 Esri.ArcGISRuntime.Data;
using Esri.ArcGISRuntime.Geometry;
using Esri.ArcGISRuntime.Mapping;
using Esri.ArcGISRuntime.Tasks;
using Esri.ArcGISRuntime.Tasks.Offline;
using System;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
namespace ArcGISRuntime.WPF.Samples.GeodatabaseTransactions
{
[ArcGISRuntime.Samples.Shared.Attributes.Sample(
name: "Geodatabase transactions",
category: "Data",
description: "Use transactions to manage how changes are committed to a geodatabase.",
instructions: "When the sample loads, a feature service is taken offline as a geodatabase. When the geodatabase is ready, you can add multiple types of features. To apply edits directly, uncheck the 'Require a transaction for edits' checkbox. When using transactions, use the buttons to start editing and stop editing. When you stop editing, you can choose to commit the changes or roll them back. At any point, you can synchronize the local geodatabase with the feature service.",
tags: new[] { "commit", "database", "geodatabase", "transact", "transactions" })]
public partial class GeodatabaseTransactions
{
// URL for the editable feature service
private const string SyncServiceUrl = "https://sampleserver6.arcgisonline.com/arcgis/rest/services/Sync/SaveTheBaySync/FeatureServer/";
// Work in a small extent south of Galveston, TX
private Envelope _extent = new Envelope(-95.3035, 29.0100, -95.1053, 29.1298, SpatialReferences.Wgs84);
// Store the local geodatabase to edit
private Geodatabase _localGeodatabase;
// Store references to two tables to edit: Birds and Marine points
private GeodatabaseFeatureTable _birdTable;
private GeodatabaseFeatureTable _marineTable;
public GeodatabaseTransactions()
{
InitializeComponent();
// When the map view loads, add a new map
MyMapView.Loaded += (s, e) =>
{
// Create a new map with the oceans basemap and add it to the map view
MyMapView.Map = new Map(BasemapStyle.ArcGISOceans);
};
// When the spatial reference changes (the map loads) add the local geodatabase tables as feature layers
MyMapView.SpatialReferenceChanged += async (s, e) =>
{
// Call a function (and await it) to get the local geodatabase (or generate it from the feature service)
await GetLocalGeodatabase();
// Once the local geodatabase is available, load the tables as layers to the map
LoadLocalGeodatabaseTables();
};
}
private async Task GetLocalGeodatabase()
{
// Get the path to the local geodatabase for this platform (temp directory, for example)
string localGeodatabasePath = GetGdbPath();
try
{
// See if the geodatabase file is already present
if (System.IO.File.Exists(localGeodatabasePath))
{
// If the geodatabase is already available, open it, hide the progress control, and update the message
_localGeodatabase = await Geodatabase.OpenAsync(localGeodatabasePath);
LoadingProgressBar.Visibility = Visibility.Collapsed;
MessageTextBlock.Text = "Using local geodatabase from '" + _localGeodatabase.Path + "'";
}
else
{
// Create a new GeodatabaseSyncTask with the uri of the feature server to pull from
Uri uri = new Uri(SyncServiceUrl);
GeodatabaseSyncTask gdbTask = await GeodatabaseSyncTask.CreateAsync(uri);
// Create parameters for the task: layers and extent to include, out spatial reference, and sync model
GenerateGeodatabaseParameters gdbParams = await gdbTask.CreateDefaultGenerateGeodatabaseParametersAsync(_extent);
gdbParams.OutSpatialReference = MyMapView.SpatialReference;
gdbParams.SyncModel = SyncModel.Layer;
gdbParams.LayerOptions.Clear();
gdbParams.LayerOptions.Add(new GenerateLayerOption(0));
gdbParams.LayerOptions.Add(new GenerateLayerOption(1));
// Create a geodatabase job that generates the geodatabase
GenerateGeodatabaseJob generateGdbJob = gdbTask.GenerateGeodatabase(gdbParams, localGeodatabasePath);
// Handle the job changed event and check the status of the job; store the geodatabase when it's ready
generateGdbJob.JobChanged += (s, e) =>
{
// See if the job succeeded
if (generateGdbJob.Status == JobStatus.Succeeded)
{
Dispatcher.Invoke(() =>
{
// Hide the progress control and update the message
LoadingProgressBar.Visibility = Visibility.Collapsed;
MessageTextBlock.Text = "Created local geodatabase";
});
}
else if (generateGdbJob.Status == JobStatus.Failed)
{
Dispatcher.Invoke(() =>
{
// Hide the progress control and report the exception
LoadingProgressBar.Visibility = Visibility.Collapsed;
MessageTextBlock.Text = "Unable to create local geodatabase: " + generateGdbJob.Error.Message;
});
}
};
// Start the generate geodatabase job
_localGeodatabase = await generateGdbJob.GetResultAsync();
}
}
catch (Exception ex)
{
// Show a message for the exception encountered
Dispatcher.Invoke(() => MessageBox.Show("Unable to create offline database: " + ex.Message));
}
}
// Function that loads the two point tables from the local geodatabase and displays them as feature layers
private async void LoadLocalGeodatabaseTables()
{
// Read the geodatabase tables and add them as layers
foreach (GeodatabaseFeatureTable table in _localGeodatabase.GeodatabaseFeatureTables)
{
try
{
// Load the table so the TableName can be read
await table.LoadAsync();
// Store a reference to the Birds table
if (table.TableName.ToLower().Contains("birds"))
{
_birdTable = table;
}
// Store a reference to the Marine table
if (table.TableName.ToLower().Contains("marine"))
{
_marineTable = table;
}
// Create a new feature layer to show the table in the map
FeatureLayer layer = new FeatureLayer(table);
Dispatcher.Invoke(() => MyMapView.Map.OperationalLayers.Add(layer));
}
catch (Exception e)
{
MessageBox.Show(e.ToString(), "Error");
}
}
// Handle the transaction status changed event
_localGeodatabase.TransactionStatusChanged += GdbTransactionStatusChanged;
// Zoom the map view to the extent of the generated local datasets
Dispatcher.Invoke(() =>
{
MyMapView.SetViewpoint(new Viewpoint(_marineTable.Extent));
StartEditingButton.IsEnabled = true;
});
}
private void GdbTransactionStatusChanged(object sender, TransactionStatusChangedEventArgs e)
{
// Update UI controls based on whether the geodatabase has a current transaction
Dispatcher.Invoke(() =>
{
// These buttons should be enabled when there IS a transaction
AddBirdButton.IsEnabled = e.IsInTransaction;
AddMarineButton.IsEnabled = e.IsInTransaction;
StopEditingButton.IsEnabled = e.IsInTransaction;
// These buttons should be enabled when there is NOT a transaction
StartEditingButton.IsEnabled = !e.IsInTransaction;
SyncEditsButton.IsEnabled = !e.IsInTransaction;
});
}
private string GetGdbPath()
{
// Return the WPF-specific path for storing the geodatabase
return Environment.ExpandEnvironmentVariables("%TEMP%\\savethebay.geodatabase");
}
private void BeginTransaction(object sender, RoutedEventArgs e)
{
// See if there is a transaction active for the geodatabase
if (!_localGeodatabase.IsInTransaction)
{
// If not, begin a transaction
_localGeodatabase.BeginTransaction();
MessageTextBlock.Text = "Transaction started";
}
}
private async void AddNewFeature(object sender, RoutedEventArgs args)
{
// See if it was the "Birds" or "Marine" button that was clicked
Button addFeatureButton = (Button)sender;
try
{
// Cancel execution of the sketch task if it is already active
if (MyMapView.SketchEditor.CancelCommand.CanExecute(null))
{
MyMapView.SketchEditor.CancelCommand.Execute(null);
}
// Store the correct table to edit (for the button clicked)
GeodatabaseFeatureTable editTable;
if (addFeatureButton == AddBirdButton)
{
editTable = _birdTable;
}
else
{
editTable = _marineTable;
}
// Inform the user which table is being edited
MessageTextBlock.Text = "Click the map to add a new feature to the geodatabase table '" + editTable.TableName + "'";
// Create a random value for the 'type' attribute (integer between 1 and 7)
Random random = new Random(DateTime.Now.Millisecond);
int featureType = random.Next(1, 7);
// Use the sketch editor to allow the user to draw a point on the map
MapPoint clickPoint = await MyMapView.SketchEditor.StartAsync(Esri.ArcGISRuntime.UI.SketchCreationMode.Point, false) as MapPoint;
// Create a new feature (row) in the selected table
Feature newFeature = editTable.CreateFeature();
// Set the geometry with the point the user clicked and the 'type' with the random integer
newFeature.Geometry = clickPoint;
newFeature.SetAttributeValue("type", featureType);
// Add the new feature to the table
await editTable.AddFeatureAsync(newFeature);
// Clear the message
MessageTextBlock.Text = "New feature added to the '" + editTable.TableName + "' table";
}
catch (TaskCanceledException)
{
// Ignore if the edit was canceled
}
catch (Exception ex)
{
// Report other exception messages
MessageTextBlock.Text = ex.Message;
}
}
private void StopEditTransaction(object sender, RoutedEventArgs e)
{
// Ask the user if they want to commit or rollback the transaction (or cancel to keep working in the transaction)
MessageBoxResult commitAnswer = MessageBox.Show("Commit your edits? ('No' to discard)", "Stop Editing", MessageBoxButton.YesNoCancel);
if (commitAnswer == MessageBoxResult.Yes)
{
// See if there is a transaction active for the geodatabase
if (_localGeodatabase.IsInTransaction)
{
// If there is, commit the transaction to store the edits (this will also end the transaction)
_localGeodatabase.CommitTransaction();
MessageTextBlock.Text = "Edits were committed to the local geodatabase.";
}
}
else if (commitAnswer == MessageBoxResult.No)
{
// See if there is a transaction active for the geodatabase
if (_localGeodatabase.IsInTransaction)
{
// If there is, rollback the transaction to discard the edits (this will also end the transaction)
_localGeodatabase.RollbackTransaction();
MessageTextBlock.Text = "Edits were rolled back and not stored to the local geodatabase.";
}
}
else
{
// For 'cancel' don't end the transaction with a commit or rollback
}
}
// Change which controls are enabled if the user chooses to require/not require transactions for edits
private void RequireTransactionChanged(object sender, RoutedEventArgs e)
{
// If the local geodatabase isn't created yet, return
if (_localGeodatabase == null) { return; }
// Get the value of the "require transactions" checkbox
bool mustHaveTransaction = RequireTransactionCheckBox.IsChecked == true;
// Warn the user if disabling transactions while a transaction is active
if (!mustHaveTransaction && _localGeodatabase.IsInTransaction)
{
MessageBox.Show("Stop editing to end the current transaction.", "Current Transaction");
RequireTransactionCheckBox.IsChecked = true;
return;
}
// Enable or disable controls according to the checkbox value
StartEditingButton.IsEnabled = mustHaveTransaction;
StopEditingButton.IsEnabled = mustHaveTransaction && _localGeodatabase.IsInTransaction;
AddBirdButton.IsEnabled = !mustHaveTransaction;
AddMarineButton.IsEnabled = !mustHaveTransaction;
}
// Synchronize edits in the local geodatabase with the service
public async void SynchronizeEdits(object sender, RoutedEventArgs e)
{
// Show the progress bar while the sync is working
LoadingProgressBar.Visibility = Visibility.Visible;
try
{
// Create a sync task with the URL of the feature service to sync
GeodatabaseSyncTask syncTask = await GeodatabaseSyncTask.CreateAsync(new Uri(SyncServiceUrl));
// Create sync parameters
SyncGeodatabaseParameters taskParameters = await syncTask.CreateDefaultSyncGeodatabaseParametersAsync(_localGeodatabase);
// Create a synchronize geodatabase job, pass in the parameters and the geodatabase
SyncGeodatabaseJob job = syncTask.SyncGeodatabase(taskParameters, _localGeodatabase);
// Handle the JobChanged event for the job
job.JobChanged += (s, arg) =>
{
// Report changes in the job status
if (job.Status == JobStatus.Succeeded)
{
// Report success ...
Dispatcher.Invoke(() => MessageTextBlock.Text = "Synchronization is complete!");
}
else if (job.Status == JobStatus.Failed)
{
// Report failure ...
Dispatcher.Invoke(() => MessageTextBlock.Text = job.Error.Message);
}
else
{
// Report that the job is in progress ...
Dispatcher.Invoke(() => MessageTextBlock.Text = "Sync in progress ...");
}
};
// Await the completion of the job
await job.GetResultAsync();
}
catch (Exception ex)
{
// Show the message if an exception occurred
MessageTextBlock.Text = "Error when synchronizing: " + ex.Message;
}
finally
{
// Hide the progress bar when the sync job is complete
LoadingProgressBar.Visibility = Visibility.Collapsed;
}
}
}
}
| |
// Copyright (c) 2010-2014 SharpDX - Alexandre Mutel
//
// 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 SharpDX.Direct3D11;
namespace SharpDX.Toolkit.Graphics
{
/// <summary>
/// A RenderTarget1D front end to <see cref="SharpDX.Direct3D11.Texture1D"/>.
/// </summary>
/// <remarks>
/// This class instantiates a <see cref="Texture1D"/> with the binding flags <see cref="BindFlags.RenderTarget"/>.
/// This class is also castable to <see cref="RenderTargetView"/>.
/// </remarks>
public class RenderTarget1D : Texture1DBase
{
internal RenderTarget1D(Device device, Texture1DDescription description1D)
: base(device, description1D)
{
}
internal RenderTarget1D(Device device, Direct3D11.Texture1D texture)
: base(device, texture)
{
}
/// <summary>
/// RenderTargetView casting operator.
/// </summary>
/// <param name="from">Source for the.</param>
public static implicit operator RenderTargetView(RenderTarget1D from)
{
return from == null ? null : from.renderTargetViews != null ? from.renderTargetViews[0] : null;
}
/// <summary>
///
/// </summary>
protected override void InitializeViews()
{
// Perform default initialization
base.InitializeViews();
if ((this.Description.BindFlags & BindFlags.RenderTarget) != 0)
{
this.renderTargetViews = new TextureView[GetViewCount()];
GetRenderTargetView(ViewType.Full, 0, 0);
}
}
internal override TextureView GetRenderTargetView(ViewType viewType, int arrayOrDepthSlice, int mipIndex)
{
if ((this.Description.BindFlags & BindFlags.RenderTarget) == 0)
return null;
if (viewType == ViewType.MipBand)
throw new NotSupportedException("ViewSlice.MipBand is not supported for render targets");
int arrayCount;
int mipCount;
GetViewSliceBounds(viewType, ref arrayOrDepthSlice, ref mipIndex, out arrayCount, out mipCount);
var rtvIndex = GetViewIndex(viewType, arrayOrDepthSlice, mipIndex);
lock (this.renderTargetViews)
{
var rtv = this.renderTargetViews[rtvIndex];
// Creates the shader resource view
if (rtv == null)
{
// Create the render target view
var rtvDescription = new RenderTargetViewDescription() { Format = this.Description.Format };
if (this.Description.ArraySize > 1)
{
rtvDescription.Dimension = RenderTargetViewDimension.Texture1DArray;
rtvDescription.Texture1DArray.ArraySize = arrayCount;
rtvDescription.Texture1DArray.FirstArraySlice = arrayOrDepthSlice;
rtvDescription.Texture1DArray.MipSlice = mipIndex;
}
else
{
rtvDescription.Dimension = RenderTargetViewDimension.Texture1D;
rtvDescription.Texture1D.MipSlice = mipIndex;
}
rtv = new TextureView(this, new RenderTargetView(GraphicsDevice, Resource, rtvDescription));
this.renderTargetViews[rtvIndex] = ToDispose(rtv);
}
return rtv;
}
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public override Texture Clone()
{
return new RenderTarget1D(GraphicsDevice, this.Description);
}
/// <summary>
/// Creates a new <see cref="RenderTarget1D"/> from a <see cref="Texture1DDescription"/>.
/// </summary>
/// <param name="device">The <see cref="Direct3D11.Device"/>.</param>
/// <param name="description">The description.</param>
/// <returns>
/// A new instance of <see cref="RenderTarget1D"/> class.
/// </returns>
/// <msdn-id>ff476520</msdn-id>
/// <unmanaged>HRESULT ID3D11Device::CreateTexture1D([In] const D3D11_TEXTURE1D_DESC* pDesc,[In, Buffer, Optional] const D3D11_SUBRESOURCE_DATA* pInitialData,[Out, Fast] ID3D11Texture1D** ppTexture1D)</unmanaged>
/// <unmanaged-short>ID3D11Device::CreateTexture1D</unmanaged-short>
public static RenderTarget1D New(Device device, Texture1DDescription description)
{
return new RenderTarget1D(device, description);
}
/// <summary>
/// Creates a new <see cref="RenderTarget1D"/> from a <see cref="Direct3D11.Texture1D"/>.
/// </summary>
/// <param name="device">The <see cref="Direct3D11.Device"/>.</param>
/// <param name="texture">The native texture <see cref="Direct3D11.Texture1D"/>.</param>
/// <returns>
/// A new instance of <see cref="RenderTarget1D"/> class.
/// </returns>
/// <msdn-id>ff476520</msdn-id>
/// <unmanaged>HRESULT ID3D11Device::CreateTexture1D([In] const D3D11_TEXTURE1D_DESC* pDesc,[In, Buffer, Optional] const D3D11_SUBRESOURCE_DATA* pInitialData,[Out, Fast] ID3D11Texture1D** ppTexture1D)</unmanaged>
/// <unmanaged-short>ID3D11Device::CreateTexture1D</unmanaged-short>
public static RenderTarget1D New(Device device, Direct3D11.Texture1D texture)
{
return new RenderTarget1D(device, texture);
}
/// <summary>
/// Creates a new <see cref="RenderTarget1D" /> with a single mipmap.
/// </summary>
/// <param name="device">The <see cref="Direct3D11.Device"/>.</param>
/// <param name="width">The width.</param>
/// <param name="format">Describes the format to use.</param>
/// <param name="flags">Sets the texture flags (for unordered access...etc.)</param>
/// <param name="arraySize">Size of the texture 1D array, default to 1.</param>
/// <returns>A new instance of <see cref="RenderTarget1D" /> class.</returns>
/// <msdn-id>ff476520</msdn-id>
/// <unmanaged>HRESULT ID3D11Device::CreateTexture1D([In] const D3D11_TEXTURE1D_DESC* pDesc,[In, Buffer, Optional] const D3D11_SUBRESOURCE_DATA* pInitialData,[Out, Fast] ID3D11Texture1D** ppTexture1D)</unmanaged>
/// <unmanaged-short>ID3D11Device::CreateTexture1D</unmanaged-short>
public static RenderTarget1D New(Device device, int width, PixelFormat format, TextureFlags flags = TextureFlags.RenderTarget | TextureFlags.ShaderResource, int arraySize = 1)
{
return New(device, width, false, format, flags | TextureFlags.RenderTarget, arraySize);
}
/// <summary>
/// Creates a new <see cref="RenderTarget1D" />.
/// </summary>
/// <param name="device">The <see cref="Direct3D11.Device"/>.</param>
/// <param name="width">The width.</param>
/// <param name="mipCount">Number of mipmaps, set to true to have all mipmaps, set to an int >=1 for a particular mipmap count.</param>
/// <param name="format">Describes the format to use.</param>
/// <param name="flags">Sets the texture flags (for unordered access...etc.)</param>
/// <param name="arraySize">Size of the texture 1D array, default to 1.</param>
/// <returns>A new instance of <see cref="RenderTarget1D" /> class.</returns>
/// <msdn-id>ff476520</msdn-id>
/// <unmanaged>HRESULT ID3D11Device::CreateTexture1D([In] const D3D11_TEXTURE1D_DESC* pDesc,[In, Buffer, Optional] const D3D11_SUBRESOURCE_DATA* pInitialData,[Out, Fast] ID3D11Texture1D** ppTexture1D)</unmanaged>
/// <unmanaged-short>ID3D11Device::CreateTexture1D</unmanaged-short>
public static RenderTarget1D New(Device device, int width, MipMapCount mipCount, PixelFormat format, TextureFlags flags = TextureFlags.RenderTarget | TextureFlags.ShaderResource, int arraySize = 1)
{
return new RenderTarget1D(device, NewRenderTargetDescription(width, format, flags | TextureFlags.RenderTarget, mipCount, arraySize));
}
/// <summary>
///
/// </summary>
/// <param name="width"></param>
/// <param name="format"></param>
/// <param name="textureFlags"></param>
/// <param name="mipCount"></param>
/// <param name="arraySize"></param>
/// <returns></returns>
protected static Texture1DDescription NewRenderTargetDescription(int width, PixelFormat format, TextureFlags textureFlags, int mipCount, int arraySize)
{
var desc = Texture1DBase.NewDescription(width, format, textureFlags, mipCount, arraySize, ResourceUsage.Default);
return desc;
}
}
}
| |
// 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 System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Security.Permissions;
using System.Security.Policy;
namespace System.Runtime.InteropServices
{
[GuidAttribute("BCA8B44D-AAD6-3A86-8AB7-03349F4F2DA2")]
[CLSCompliant(false)]
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
[TypeLibImportClassAttribute(typeof(System.Type))]
[System.Runtime.InteropServices.ComVisible(true)]
public interface _Type
{
#if !FEATURE_CORECLR
#region IDispatch Members
void GetTypeInfoCount(out uint pcTInfo);
void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo);
void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId);
void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr);
#endregion
#region Object Members
String ToString();
bool Equals(Object other);
int GetHashCode();
Type GetType();
#endregion
#region MemberInfo Members
MemberTypes MemberType { get; }
String Name { get; }
Type DeclaringType { get; }
Type ReflectedType { get; }
Object[] GetCustomAttributes(Type attributeType, bool inherit);
Object[] GetCustomAttributes(bool inherit);
bool IsDefined(Type attributeType, bool inherit);
#endregion
#region Type Members
Guid GUID { get; }
Module Module { get; }
Assembly Assembly { get; }
RuntimeTypeHandle TypeHandle { get; }
String FullName { get; }
String Namespace { get; }
String AssemblyQualifiedName { get; }
int GetArrayRank();
Type BaseType { get; }
ConstructorInfo[] GetConstructors(BindingFlags bindingAttr);
Type GetInterface(String name, bool ignoreCase);
Type[] GetInterfaces();
Type[] FindInterfaces(TypeFilter filter,Object filterCriteria);
EventInfo GetEvent(String name,BindingFlags bindingAttr);
EventInfo[] GetEvents();
EventInfo[] GetEvents(BindingFlags bindingAttr);
Type[] GetNestedTypes(BindingFlags bindingAttr);
Type GetNestedType(String name, BindingFlags bindingAttr);
MemberInfo[] GetMember(String name, MemberTypes type, BindingFlags bindingAttr);
MemberInfo[] GetDefaultMembers();
MemberInfo[] FindMembers(MemberTypes memberType,BindingFlags bindingAttr,MemberFilter filter,Object filterCriteria);
Type GetElementType();
bool IsSubclassOf(Type c);
bool IsInstanceOfType(Object o);
bool IsAssignableFrom(Type c);
InterfaceMapping GetInterfaceMap(Type interfaceType);
MethodInfo GetMethod(String name, BindingFlags bindingAttr, Binder binder, Type[] types, ParameterModifier[] modifiers);
MethodInfo GetMethod(String name, BindingFlags bindingAttr);
MethodInfo[] GetMethods(BindingFlags bindingAttr);
FieldInfo GetField(String name, BindingFlags bindingAttr);
FieldInfo[] GetFields(BindingFlags bindingAttr);
PropertyInfo GetProperty(String name, BindingFlags bindingAttr);
PropertyInfo GetProperty(String name,BindingFlags bindingAttr,Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers);
PropertyInfo[] GetProperties(BindingFlags bindingAttr);
MemberInfo[] GetMember(String name, BindingFlags bindingAttr);
MemberInfo[] GetMembers(BindingFlags bindingAttr);
Object InvokeMember(String name, BindingFlags invokeAttr, Binder binder, Object target, Object[] args, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParameters);
Type UnderlyingSystemType
{
get;
}
Object InvokeMember(String name,BindingFlags invokeAttr,Binder binder, Object target, Object[] args, CultureInfo culture);
Object InvokeMember(String name,BindingFlags invokeAttr,Binder binder, Object target, Object[] args);
ConstructorInfo GetConstructor(BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers);
ConstructorInfo GetConstructor(BindingFlags bindingAttr, Binder binder, Type[] types, ParameterModifier[] modifiers);
ConstructorInfo GetConstructor(Type[] types);
ConstructorInfo[] GetConstructors();
ConstructorInfo TypeInitializer
{
get;
}
MethodInfo GetMethod(String name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers);
MethodInfo GetMethod(String name, Type[] types, ParameterModifier[] modifiers);
MethodInfo GetMethod(String name, Type[] types);
MethodInfo GetMethod(String name);
MethodInfo[] GetMethods();
FieldInfo GetField(String name);
FieldInfo[] GetFields();
Type GetInterface(String name);
EventInfo GetEvent(String name);
PropertyInfo GetProperty(String name, Type returnType, Type[] types,ParameterModifier[] modifiers);
PropertyInfo GetProperty(String name, Type returnType, Type[] types);
PropertyInfo GetProperty(String name, Type[] types);
PropertyInfo GetProperty(String name, Type returnType);
PropertyInfo GetProperty(String name);
PropertyInfo[] GetProperties();
Type[] GetNestedTypes();
Type GetNestedType(String name);
MemberInfo[] GetMember(String name);
MemberInfo[] GetMembers();
TypeAttributes Attributes { get; }
bool IsNotPublic { get; }
bool IsPublic { get; }
bool IsNestedPublic { get; }
bool IsNestedPrivate { get; }
bool IsNestedFamily { get; }
bool IsNestedAssembly { get; }
bool IsNestedFamANDAssem { get; }
bool IsNestedFamORAssem { get; }
bool IsAutoLayout { get; }
bool IsLayoutSequential { get; }
bool IsExplicitLayout { get; }
bool IsClass { get; }
bool IsInterface { get; }
bool IsValueType { get; }
bool IsAbstract { get; }
bool IsSealed { get; }
bool IsEnum { get; }
bool IsSpecialName { get; }
bool IsImport { get; }
bool IsSerializable { get; }
bool IsAnsiClass { get; }
bool IsUnicodeClass { get; }
bool IsAutoClass { get; }
bool IsArray { get; }
bool IsByRef { get; }
bool IsPointer { get; }
bool IsPrimitive { get; }
bool IsCOMObject { get; }
bool HasElementType { get; }
bool IsContextful { get; }
bool IsMarshalByRef { get; }
bool Equals(Type o);
#endregion
#endif
}
[GuidAttribute("17156360-2f1a-384a-bc52-fde93c215c5b")]
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsDual)]
[TypeLibImportClassAttribute(typeof(System.Reflection.Assembly))]
[CLSCompliant(false)]
[System.Runtime.InteropServices.ComVisible(true)]
public interface _Assembly
{
#if !FEATURE_CORECLR
#region Object Members
String ToString();
bool Equals(Object other);
int GetHashCode();
Type GetType();
#endregion
#region Assembly Members
String CodeBase {
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
get; }
String EscapedCodeBase { get; }
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
AssemblyName GetName();
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
AssemblyName GetName(bool copiedName);
String FullName { get; }
MethodInfo EntryPoint { get; }
Type GetType(String name);
Type GetType(String name, bool throwOnError);
Type[] GetExportedTypes();
Type[] GetTypes();
Stream GetManifestResourceStream(Type type, String name);
Stream GetManifestResourceStream(String name);
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
FileStream GetFile(String name);
FileStream[] GetFiles();
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
FileStream[] GetFiles(bool getResourceModules);
String[] GetManifestResourceNames();
ManifestResourceInfo GetManifestResourceInfo(String resourceName);
String Location {
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
get; }
#if FEATURE_CAS_POLICY
Evidence Evidence { get; }
#endif // FEATURE_CAS_POLICY
Object[] GetCustomAttributes(Type attributeType, bool inherit);
Object[] GetCustomAttributes(bool inherit);
bool IsDefined(Type attributeType, bool inherit);
#if FEATURE_SERIALIZATION
[System.Security.SecurityCritical] // auto-generated_required
void GetObjectData(SerializationInfo info, StreamingContext context);
#endif
[method: System.Security.SecurityCritical]
event ModuleResolveEventHandler ModuleResolve;
Type GetType(String name, bool throwOnError, bool ignoreCase);
Assembly GetSatelliteAssembly(CultureInfo culture);
Assembly GetSatelliteAssembly(CultureInfo culture, Version version);
#if FEATURE_MULTIMODULE_ASSEMBLIES
Module LoadModule(String moduleName, byte[] rawModule);
Module LoadModule(String moduleName, byte[] rawModule, byte[] rawSymbolStore);
#endif
Object CreateInstance(String typeName);
Object CreateInstance(String typeName, bool ignoreCase);
Object CreateInstance(String typeName, bool ignoreCase, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes);
Module[] GetLoadedModules();
Module[] GetLoadedModules(bool getResourceModules);
Module[] GetModules();
Module[] GetModules(bool getResourceModules);
Module GetModule(String name);
AssemblyName[] GetReferencedAssemblies();
bool GlobalAssemblyCache { get; }
#endregion
#endif
}
[GuidAttribute("f7102fa9-cabb-3a74-a6da-b4567ef1b079")]
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
[TypeLibImportClassAttribute(typeof(System.Reflection.MemberInfo))]
[CLSCompliant(false)]
[System.Runtime.InteropServices.ComVisible(true)]
public interface _MemberInfo
{
#if !FEATURE_CORECLR
#region IDispatch Members
void GetTypeInfoCount(out uint pcTInfo);
void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo);
void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId);
void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr);
#endregion
#region Object Members
String ToString();
bool Equals(Object other);
int GetHashCode();
Type GetType();
#endregion
#region MemberInfo Members
MemberTypes MemberType { get; }
String Name { get; }
Type DeclaringType { get; }
Type ReflectedType { get; }
Object[] GetCustomAttributes(Type attributeType, bool inherit);
Object[] GetCustomAttributes(bool inherit);
bool IsDefined(Type attributeType, bool inherit);
#endregion
#endif
}
[GuidAttribute("6240837A-707F-3181-8E98-A36AE086766B")]
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
[CLSCompliant(false)]
[TypeLibImportClassAttribute(typeof(System.Reflection.MethodBase))]
[System.Runtime.InteropServices.ComVisible(true)]
public interface _MethodBase
{
#if !FEATURE_CORECLR
#region IDispatch Members
void GetTypeInfoCount(out uint pcTInfo);
void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo);
void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId);
void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr);
#endregion
#region Object Members
String ToString();
bool Equals(Object other);
int GetHashCode();
Type GetType();
#endregion
#region MemberInfo Members
MemberTypes MemberType { get; }
String Name { get; }
Type DeclaringType { get; }
Type ReflectedType { get; }
Object[] GetCustomAttributes(Type attributeType, bool inherit);
Object[] GetCustomAttributes(bool inherit);
bool IsDefined(Type attributeType, bool inherit);
#endregion
#region MethodBase Members
ParameterInfo[] GetParameters();
MethodImplAttributes GetMethodImplementationFlags();
RuntimeMethodHandle MethodHandle { get; }
MethodAttributes Attributes { get; }
CallingConventions CallingConvention { get; }
Object Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture);
bool IsPublic { get; }
bool IsPrivate { get; }
bool IsFamily { get; }
bool IsAssembly { get; }
bool IsFamilyAndAssembly { get; }
bool IsFamilyOrAssembly { get; }
bool IsStatic { get; }
bool IsFinal { get; }
bool IsVirtual { get; }
bool IsHideBySig { get; }
bool IsAbstract { get; }
bool IsSpecialName { get; }
bool IsConstructor { get; }
Object Invoke(Object obj, Object[] parameters);
#endregion
#endif
}
[GuidAttribute("FFCC1B5D-ECB8-38DD-9B01-3DC8ABC2AA5F")]
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
[CLSCompliant(false)]
[TypeLibImportClassAttribute(typeof(System.Reflection.MethodInfo))]
[System.Runtime.InteropServices.ComVisible(true)]
public interface _MethodInfo
{
#if !FEATURE_CORECLR
#region IDispatch Members
void GetTypeInfoCount(out uint pcTInfo);
void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo);
void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId);
void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr);
#endregion
#region Object Members
String ToString();
bool Equals(Object other);
int GetHashCode();
Type GetType();
#endregion
#region MemberInfo Members
MemberTypes MemberType { get; }
String Name { get; }
Type DeclaringType { get; }
Type ReflectedType { get; }
Object[] GetCustomAttributes(Type attributeType, bool inherit);
Object[] GetCustomAttributes(bool inherit);
bool IsDefined(Type attributeType, bool inherit);
#endregion
#region MethodBase Members
ParameterInfo[] GetParameters();
MethodImplAttributes GetMethodImplementationFlags();
RuntimeMethodHandle MethodHandle { get; }
MethodAttributes Attributes { get; }
CallingConventions CallingConvention { get; }
Object Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture);
bool IsPublic { get; }
bool IsPrivate { get; }
bool IsFamily { get; }
bool IsAssembly { get; }
bool IsFamilyAndAssembly { get; }
bool IsFamilyOrAssembly { get; }
bool IsStatic { get; }
bool IsFinal { get; }
bool IsVirtual { get; }
bool IsHideBySig { get; }
bool IsAbstract { get; }
bool IsSpecialName { get; }
bool IsConstructor { get; }
Object Invoke(Object obj, Object[] parameters);
#endregion
#region MethodInfo Members
Type ReturnType { get; }
ICustomAttributeProvider ReturnTypeCustomAttributes { get; }
MethodInfo GetBaseDefinition();
#endregion
#endif
}
[GuidAttribute("E9A19478-9646-3679-9B10-8411AE1FD57D")]
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
[CLSCompliant(false)]
[TypeLibImportClassAttribute(typeof(System.Reflection.ConstructorInfo))]
[System.Runtime.InteropServices.ComVisible(true)]
public interface _ConstructorInfo
{
#if !FEATURE_CORECLR
#region IDispatch Members
void GetTypeInfoCount(out uint pcTInfo);
void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo);
void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId);
void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr);
#endregion
#region Object Members
String ToString();
bool Equals(Object other);
int GetHashCode();
Type GetType();
#endregion
#region MemberInfo Members
MemberTypes MemberType { get; }
String Name { get; }
Type DeclaringType { get; }
Type ReflectedType { get; }
Object[] GetCustomAttributes(Type attributeType, bool inherit);
Object[] GetCustomAttributes(bool inherit);
bool IsDefined(Type attributeType, bool inherit);
#endregion
#region MethodBase Members
ParameterInfo[] GetParameters();
MethodImplAttributes GetMethodImplementationFlags();
RuntimeMethodHandle MethodHandle { get; }
MethodAttributes Attributes { get; }
CallingConventions CallingConvention { get; }
Object Invoke_2(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture);
bool IsPublic { get; }
bool IsPrivate { get; }
bool IsFamily { get; }
bool IsAssembly { get; }
bool IsFamilyAndAssembly { get; }
bool IsFamilyOrAssembly { get; }
bool IsStatic { get; }
bool IsFinal { get; }
bool IsVirtual { get; }
bool IsHideBySig { get; }
bool IsAbstract { get; }
bool IsSpecialName { get; }
bool IsConstructor { get; }
Object Invoke_3(Object obj, Object[] parameters);
#endregion
#region ConstructorInfo
Object Invoke_4(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture);
Object Invoke_5(Object[] parameters);
#endregion
#endif
}
[GuidAttribute("8A7C1442-A9FB-366B-80D8-4939FFA6DBE0")]
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
[CLSCompliant(false)]
[TypeLibImportClassAttribute(typeof(System.Reflection.FieldInfo))]
[System.Runtime.InteropServices.ComVisible(true)]
public interface _FieldInfo
{
#if !FEATURE_CORECLR
#region IDispatch Members
void GetTypeInfoCount(out uint pcTInfo);
void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo);
void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId);
void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr);
#endregion
#region Object Members
String ToString();
bool Equals(Object other);
int GetHashCode();
Type GetType();
#endregion
#region MemberInfo Members
MemberTypes MemberType { get; }
String Name { get; }
Type DeclaringType { get; }
Type ReflectedType { get; }
Object[] GetCustomAttributes(Type attributeType, bool inherit);
Object[] GetCustomAttributes(bool inherit);
bool IsDefined(Type attributeType, bool inherit);
#endregion
#region FieldInfo Members
Type FieldType { get; }
Object GetValue(Object obj);
Object GetValueDirect(TypedReference obj);
void SetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, CultureInfo culture);
void SetValueDirect(TypedReference obj,Object value);
RuntimeFieldHandle FieldHandle { get; }
FieldAttributes Attributes { get; }
void SetValue(Object obj, Object value);
bool IsPublic { get; }
bool IsPrivate { get; }
bool IsFamily { get; }
bool IsAssembly { get; }
bool IsFamilyAndAssembly { get; }
bool IsFamilyOrAssembly { get; }
bool IsStatic { get; }
bool IsInitOnly { get; }
bool IsLiteral { get; }
bool IsNotSerialized { get; }
bool IsSpecialName { get; }
bool IsPinvokeImpl { get; }
#endregion
#endif
}
[GuidAttribute("F59ED4E4-E68F-3218-BD77-061AA82824BF")]
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
[CLSCompliant(false)]
[TypeLibImportClassAttribute(typeof(System.Reflection.PropertyInfo))]
[System.Runtime.InteropServices.ComVisible(true)]
public interface _PropertyInfo
{
#if !FEATURE_CORECLR
#region IDispatch Members
void GetTypeInfoCount(out uint pcTInfo);
void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo);
void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId);
void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr);
#endregion
#region Object Members
String ToString();
bool Equals(Object other);
int GetHashCode();
Type GetType();
#endregion
#region MemberInfo Members
MemberTypes MemberType { get; }
String Name { get; }
Type DeclaringType { get; }
Type ReflectedType { get; }
Object[] GetCustomAttributes(Type attributeType, bool inherit);
Object[] GetCustomAttributes(bool inherit);
bool IsDefined(Type attributeType, bool inherit);
#endregion
#region Property Members
Type PropertyType { get; }
Object GetValue(Object obj,Object[] index);
Object GetValue(Object obj,BindingFlags invokeAttr,Binder binder, Object[] index, CultureInfo culture);
void SetValue(Object obj, Object value, Object[] index);
void SetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, Object[] index, CultureInfo culture);
MethodInfo[] GetAccessors(bool nonPublic);
MethodInfo GetGetMethod(bool nonPublic);
MethodInfo GetSetMethod(bool nonPublic);
ParameterInfo[] GetIndexParameters();
PropertyAttributes Attributes { get; }
bool CanRead { get; }
bool CanWrite { get; }
MethodInfo[] GetAccessors();
MethodInfo GetGetMethod();
MethodInfo GetSetMethod();
bool IsSpecialName { get; }
#endregion
#endif
}
[GuidAttribute("9DE59C64-D889-35A1-B897-587D74469E5B")]
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
[CLSCompliant(false)]
[TypeLibImportClassAttribute(typeof(System.Reflection.EventInfo))]
[System.Runtime.InteropServices.ComVisible(true)]
public interface _EventInfo
{
#if !FEATURE_CORECLR
#region IDispatch Members
void GetTypeInfoCount(out uint pcTInfo);
void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo);
void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId);
void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr);
#endregion
#region Object Members
String ToString();
bool Equals(Object other);
int GetHashCode();
Type GetType();
#endregion
#region MemberInfo Members
MemberTypes MemberType { get; }
String Name { get; }
Type DeclaringType { get; }
Type ReflectedType { get; }
Object[] GetCustomAttributes(Type attributeType, bool inherit);
Object[] GetCustomAttributes(bool inherit);
bool IsDefined(Type attributeType, bool inherit);
#endregion
#region EventInfo Members
MethodInfo GetAddMethod(bool nonPublic);
MethodInfo GetRemoveMethod(bool nonPublic);
MethodInfo GetRaiseMethod(bool nonPublic);
EventAttributes Attributes { get; }
MethodInfo GetAddMethod();
MethodInfo GetRemoveMethod();
MethodInfo GetRaiseMethod();
void AddEventHandler(Object target, Delegate handler);
void RemoveEventHandler(Object target, Delegate handler);
Type EventHandlerType { get; }
bool IsSpecialName { get; }
bool IsMulticast { get; }
#endregion
#endif
}
[GuidAttribute("993634C4-E47A-32CC-BE08-85F567DC27D6")]
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
[CLSCompliant(false)]
[TypeLibImportClassAttribute(typeof(System.Reflection.ParameterInfo))]
[System.Runtime.InteropServices.ComVisible(true)]
public interface _ParameterInfo
{
#if !FEATURE_CORECLR
void GetTypeInfoCount(out uint pcTInfo);
void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo);
void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId);
void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr);
#endif
}
[GuidAttribute("D002E9BA-D9E3-3749-B1D3-D565A08B13E7")]
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
[CLSCompliant(false)]
[TypeLibImportClassAttribute(typeof(System.Reflection.Module))]
[System.Runtime.InteropServices.ComVisible(true)]
public interface _Module
{
#if !FEATURE_CORECLR
void GetTypeInfoCount(out uint pcTInfo);
void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo);
void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId);
void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr);
#endif
}
[GuidAttribute("B42B6AAC-317E-34D5-9FA9-093BB4160C50")]
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
[CLSCompliant(false)]
[TypeLibImportClassAttribute(typeof(System.Reflection.AssemblyName))]
[System.Runtime.InteropServices.ComVisible(true)]
public interface _AssemblyName
{
#if !FEATURE_CORECLR
void GetTypeInfoCount(out uint pcTInfo);
void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo);
void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId);
void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr);
#endif
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// File System.Windows.Controls.Frame.cs
// Automatically generated contract file.
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;
// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0067
// Disable the "this event is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108
namespace System.Windows.Controls
{
public partial class Frame : ContentControl, MS.Internal.AppModel.INavigator, MS.Internal.AppModel.INavigatorImpl, MS.Internal.AppModel.IJournalNavigationScopeHost, MS.Internal.AppModel.INavigatorBase, MS.Internal.AppModel.IDownloader, MS.Internal.AppModel.IJournalState, System.Windows.Markup.IAddChild, System.Windows.Markup.IUriContext
{
#region Methods and constructors
public void AddBackEntry(System.Windows.Navigation.CustomContentState state)
{
}
protected override void AddChild(Object value)
{
}
protected override void AddText(string text)
{
}
public Frame()
{
}
public void GoBack()
{
}
public void GoForward()
{
}
bool MS.Internal.AppModel.IJournalNavigationScopeHost.GoBackOverride()
{
return default(bool);
}
bool MS.Internal.AppModel.IJournalNavigationScopeHost.GoForwardOverride()
{
return default(bool);
}
void MS.Internal.AppModel.IJournalNavigationScopeHost.OnJournalAvailable()
{
}
void MS.Internal.AppModel.IJournalNavigationScopeHost.VerifyContextAndObjectState()
{
}
System.Windows.Media.Visual MS.Internal.AppModel.INavigatorImpl.FindRootViewer()
{
return default(System.Windows.Media.Visual);
}
void MS.Internal.AppModel.INavigatorImpl.OnSourceUpdatedFromNavService(bool journalOrCancel)
{
}
public bool Navigate(Uri source)
{
return default(bool);
}
public bool Navigate(Object content, Object extraData)
{
return default(bool);
}
public bool Navigate(Object content)
{
return default(bool);
}
public bool Navigate(Uri source, Object extraData)
{
return default(bool);
}
public override void OnApplyTemplate()
{
}
protected virtual new void OnContentRendered(EventArgs args)
{
}
protected override System.Windows.Automation.Peers.AutomationPeer OnCreateAutomationPeer()
{
return default(System.Windows.Automation.Peers.AutomationPeer);
}
public void Refresh()
{
}
public System.Windows.Navigation.JournalEntry RemoveBackEntry()
{
return default(System.Windows.Navigation.JournalEntry);
}
public override bool ShouldSerializeContent()
{
return default(bool);
}
public void StopLoading()
{
}
#endregion
#region Properties and indexers
public System.Collections.IEnumerable BackStack
{
get
{
return default(System.Collections.IEnumerable);
}
}
protected virtual new Uri BaseUri
{
get
{
return default(Uri);
}
set
{
}
}
public bool CanGoBack
{
get
{
return default(bool);
}
}
public bool CanGoForward
{
get
{
return default(bool);
}
}
public Uri CurrentSource
{
get
{
return default(Uri);
}
}
public System.Collections.IEnumerable ForwardStack
{
get
{
return default(System.Collections.IEnumerable);
}
}
public System.Windows.Navigation.JournalOwnership JournalOwnership
{
get
{
return default(System.Windows.Navigation.JournalOwnership);
}
set
{
}
}
System.Windows.Navigation.NavigationService MS.Internal.AppModel.IDownloader.Downloader
{
get
{
return default(System.Windows.Navigation.NavigationService);
}
}
public System.Windows.Navigation.NavigationService NavigationService
{
get
{
return default(System.Windows.Navigation.NavigationService);
}
}
public System.Windows.Navigation.NavigationUIVisibility NavigationUIVisibility
{
get
{
return default(System.Windows.Navigation.NavigationUIVisibility);
}
set
{
}
}
public bool SandboxExternalContent
{
get
{
return default(bool);
}
set
{
}
}
public Uri Source
{
get
{
return default(Uri);
}
set
{
}
}
Uri System.Windows.Markup.IUriContext.BaseUri
{
get
{
return default(Uri);
}
set
{
}
}
#endregion
#region Events
public event EventHandler ContentRendered
{
add
{
}
remove
{
}
}
public event System.Windows.Navigation.FragmentNavigationEventHandler FragmentNavigation
{
add
{
}
remove
{
}
}
public event System.Windows.Navigation.LoadCompletedEventHandler LoadCompleted
{
add
{
}
remove
{
}
}
public event System.Windows.Navigation.NavigatedEventHandler Navigated
{
add
{
}
remove
{
}
}
public event System.Windows.Navigation.NavigatingCancelEventHandler Navigating
{
add
{
}
remove
{
}
}
public event System.Windows.Navigation.NavigationFailedEventHandler NavigationFailed
{
add
{
}
remove
{
}
}
public event System.Windows.Navigation.NavigationProgressEventHandler NavigationProgress
{
add
{
}
remove
{
}
}
public event System.Windows.Navigation.NavigationStoppedEventHandler NavigationStopped
{
add
{
}
remove
{
}
}
#endregion
#region Fields
public readonly static System.Windows.DependencyProperty BackStackProperty;
public readonly static System.Windows.DependencyProperty CanGoBackProperty;
public readonly static System.Windows.DependencyProperty CanGoForwardProperty;
public readonly static System.Windows.DependencyProperty ForwardStackProperty;
public readonly static System.Windows.DependencyProperty JournalOwnershipProperty;
public readonly static System.Windows.DependencyProperty NavigationUIVisibilityProperty;
public readonly static System.Windows.DependencyProperty SandboxExternalContentProperty;
public readonly static System.Windows.DependencyProperty SourceProperty;
#endregion
}
}
| |
using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
using UMA.CharacterSystem;
using UnityEditorInternal;
namespace UMA.Editors
{
public class UmaSlotBuilderWindow : EditorWindow
{
/// <summary>
/// This class is pretty dumb. It exists solely because "string" has no default constructor, so can't be created using reflection.
/// </summary>
public class BoneName : Object
{
public string strValue;
public static implicit operator BoneName(string value)
{
return new BoneName(value);
}
public static BoneName operator +(BoneName first, BoneName second)
{
return new BoneName(first.strValue + second.strValue);
}
public BoneName()
{
strValue = "";
}
public override string ToString()
{
return strValue;
}
public BoneName(string val)
{
strValue = val;
}
}
public string slotName;
public string RootBone = "Global";
public UnityEngine.Object slotFolder;
public UnityEngine.Object relativeFolder;
public SkinnedMeshRenderer normalReferenceMesh;
public SkinnedMeshRenderer slotMesh;
public GameObject AllSlots;
public UMAMaterial slotMaterial;
public bool createOverlay;
public bool createRecipe;
public bool addToGlobalLibrary;
public bool binarySerialization;
public bool calcTangents=true;
public string errmsg = "";
public List<string> Tags = new List<string>();
public bool showTags;
public bool nameAfterMaterial=true;
public List<BoneName> KeepBones = new List<BoneName>();
private ReorderableList boneList;
private bool boneListInitialized;
string GetAssetFolder()
{
int index = slotName.LastIndexOf('/');
if( index > 0 )
{
return slotName.Substring(0, index+1);
}
return "";
}
string GetAssetName()
{
int index = slotName.LastIndexOf('/');
if (index > 0)
{
return slotName.Substring(index + 1);
}
return slotName;
}
string GetSlotName(SkinnedMeshRenderer smr)
{
if (nameAfterMaterial)
{
return smr.sharedMaterial.name.ToTitleCase();
}
int index = slotName.LastIndexOf('/');
if (index > 0)
{
return slotName.Substring(index + 1);
}
return slotName;
}
public void EnforceFolder(ref UnityEngine.Object folderObject)
{
if (folderObject != null)
{
string destpath = AssetDatabase.GetAssetPath(folderObject);
if (string.IsNullOrEmpty(destpath))
{
folderObject = null;
}
else if (!System.IO.Directory.Exists(destpath))
{
destpath = destpath.Substring(0, destpath.LastIndexOf('/'));
folderObject = AssetDatabase.LoadMainAssetAtPath(destpath);
}
}
}
private void InitBoneList()
{
boneList = new ReorderableList(KeepBones,typeof(BoneName), true, true, true, true);
boneList.drawHeaderCallback = (Rect rect) => {
EditorGUI.LabelField(rect, "Keep Bones Containing");
};
boneList.drawElementCallback = (Rect rect, int index, bool isActive, bool isFocused) => {
rect.y += 2;
KeepBones[index].strValue = EditorGUI.TextField(new Rect(rect.x + 10, rect.y, rect.width - 10, EditorGUIUtility.singleLineHeight), KeepBones[index].strValue);
};
boneListInitialized = true;
}
void OnGUI()
{
if (!boneListInitialized || boneList == null)
{
InitBoneList();
}
GUIHelper.BeginVerticalPadded(10, new Color(0.75f, 0.85f, 1f), EditorStyles.helpBox);
GUILayout.Label("Common Parameters", EditorStyles.boldLabel);
normalReferenceMesh = EditorGUILayout.ObjectField("Seams Mesh (Optional) ", normalReferenceMesh, typeof(SkinnedMeshRenderer), false) as SkinnedMeshRenderer;
slotMaterial = EditorGUILayout.ObjectField("UMAMaterial ", slotMaterial, typeof(UMAMaterial), false) as UMAMaterial;
slotFolder = EditorGUILayout.ObjectField("Slot Destination Folder", slotFolder, typeof(UnityEngine.Object), false) as UnityEngine.Object;
//EditorGUILayout.LabelField("", GUI.skin.horizontalSlider);
EditorGUILayout.BeginHorizontal();
createOverlay = EditorGUILayout.Toggle("Create Overlay", createOverlay);
createRecipe = EditorGUILayout.Toggle("Create Wardrobe Recipe ", createRecipe);
EditorGUILayout.EndHorizontal();
//EditorGUILayout.LabelField(slotName + "_Overlay");
//EditorGUILayout.EndHorizontal();
//EditorGUILayout.BeginHorizontal();
//EditorGUILayout.LabelField(slotName + "_Recipe");
//EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginHorizontal();
binarySerialization = EditorGUILayout.Toggle(new GUIContent("Binary Serialization", "Forces the created Mesh object to be serialized as binary. Recommended for large meshes and blendshapes."), binarySerialization);
addToGlobalLibrary = EditorGUILayout.Toggle("Add To Global Library", addToGlobalLibrary);
EditorGUILayout.EndHorizontal();
calcTangents = EditorGUILayout.Toggle("Calculate Tangents", calcTangents);
boneList.DoLayoutList();
GUIHelper.EndVerticalPadded(10);
DoDragDrop();
EnforceFolder(ref slotFolder);
//
// For now, we will disable this option.
// It doesn't work in most cases.
// RootBone = EditorGUILayout.TextField("Root Bone (ex:'Global')", RootBone);
//
GUIHelper.BeginVerticalPadded(10, new Color(0.75f, 0.85f, 1f),EditorStyles.helpBox);
GUILayout.Label("Single Slot Processing", EditorStyles.boldLabel);
var newslotMesh = EditorGUILayout.ObjectField("Slot Mesh ", slotMesh, typeof(SkinnedMeshRenderer), false) as SkinnedMeshRenderer;
if (newslotMesh != slotMesh)
{
errmsg = "";
slotMesh = newslotMesh;
}
slotName = EditorGUILayout.TextField("Slot Name", slotName);
if (GUILayout.Button("Verify Slot"))
{
if (slotMesh == null)
{
errmsg = "Slot is null.";
}
else
{
Vector2[] uv = slotMesh.sharedMesh.uv;
foreach (Vector2 v in uv)
{
if (v.x > 1.0f || v.x < 0.0f || v.y > 1.0f || v.y < 0.0f)
{
errmsg = "UV Coordinates are out of range and will likely have issues with atlassed materials. Textures should not be tiled unless using non-atlassed materials.";
break;
}
}
if (string.IsNullOrEmpty(errmsg))
{
errmsg = "No errors found";
}
}
}
if (!string.IsNullOrEmpty(errmsg))
{
EditorGUILayout.HelpBox(errmsg, MessageType.Warning);
}
if (GUILayout.Button("Create Slot"))
{
Debug.Log("Processing...");
SlotDataAsset sd = CreateSlot();
if (sd != null)
{
Debug.Log("Success.");
string AssetPath = AssetDatabase.GetAssetPath(sd.GetInstanceID());
if (addToGlobalLibrary)
{
UMAAssetIndexer.Instance.EvilAddAsset(typeof(SlotDataAsset), sd);
}
OverlayDataAsset od = null;
if (createOverlay)
{
od = CreateOverlay(AssetPath.Replace(sd.name, sd.slotName + "_Overlay"), sd);
}
if (createRecipe)
{
CreateRecipe(AssetPath.Replace(sd.name, sd.slotName + "_Recipe"), sd, od);
}
}
}
GUIHelper.EndVerticalPadded(10);
GUILayout.BeginHorizontal(EditorStyles.toolbarButton);
GUILayout.Space(10);
showTags = EditorGUILayout.Foldout(showTags, "Tags");
GUILayout.EndHorizontal();
if (showTags)
{
GUIHelper.BeginVerticalPadded(10, new Color(0.75f, 0.875f, 1f),EditorStyles.helpBox);
// Draw the button area
GUILayout.BeginHorizontal();
if (GUILayout.Button("Add Tag", GUILayout.Width(80)))
{
Tags.Add("");
Repaint();
}
GUILayout.Label(Tags.Count + " Tags defined");
GUILayout.EndHorizontal();
if (Tags.Count == 0)
{
GUILayout.Label("No tags defined", EditorStyles.helpBox);
}
else
{
int del = -1;
for (int i = 0; i < Tags.Count; i++)
{
GUILayout.BeginHorizontal();
Tags[i] = GUILayout.TextField(Tags[i]);
if (GUILayout.Button("\u0078", EditorStyles.miniButton, GUILayout.ExpandWidth(false)))
{
del = i;
}
GUILayout.EndHorizontal();
}
if (del >= 0)
{
Tags.RemoveAt(del);
Repaint();
}
}
// Draw the tags (or "No tags defined");
GUIHelper.EndVerticalPadded(10);
}
if (slotMesh != null)
{
if (slotMesh.localBounds.size.x > 10.0f || slotMesh.localBounds.size.y > 10.0f || slotMesh.localBounds.size.z > 10.0f)
EditorGUILayout.HelpBox("This slot's size is very large. It's import scale may be incorrect!", MessageType.Warning);
if (slotMesh.localBounds.size.x < 0.01f || slotMesh.localBounds.size.y < 0.01f || slotMesh.localBounds.size.z < 0.01f)
EditorGUILayout.HelpBox("This slot's size is very small. It's import scale may be incorrect!", MessageType.Warning);
if (slotName == null || slotName == "")
{
slotName = slotMesh.name;
}
if (RootBone == null || RootBone == "")
{
RootBone = "Global";
}
}
}
private void DoDragDrop()
{
GUIHelper.BeginVerticalPadded(10, new Color(0.75f, 0.85f, 1f), EditorStyles.helpBox);
GUILayout.Label("Automatic Drag and Drop processing", EditorStyles.boldLabel);
Rect dropArea = GUILayoutUtility.GetRect(0.0f, 50.0f, GUILayout.ExpandWidth(true));
nameAfterMaterial = GUILayout.Toggle(nameAfterMaterial, "Name slot by material");
Color save = GUI.color;
GUI.color = Color.white;
GUI.Box(dropArea, "Drag FBX GameObject or meshes here to generate all slots and overlays for the GameObject");
relativeFolder = EditorGUILayout.ObjectField("Relative Folder", relativeFolder, typeof(UnityEngine.Object), false) as UnityEngine.Object;
EnforceFolder(ref relativeFolder);
DropAreaGUI(dropArea);
GUI.color = save;
GUIHelper.EndVerticalPadded(10);
}
private SlotDataAsset CreateSlot()
{
if(slotName == null || slotName == ""){
Debug.LogError("slotName must be specified.");
return null;
}
SlotDataAsset sd = CreateSlot_Internal();
UMAUpdateProcessor.UpdateSlot(sd);
return sd;
}
private OverlayDataAsset CreateOverlay(string path, SlotDataAsset sd)
{
OverlayDataAsset asset = ScriptableObject.CreateInstance<OverlayDataAsset>();
asset.overlayName = slotName + "_Overlay";
asset.material = sd.material;
AssetDatabase.CreateAsset(asset, path);
AssetDatabase.SaveAssets();
if (addToGlobalLibrary)
{
UMAAssetIndexer.Instance.EvilAddAsset(typeof(OverlayDataAsset), asset);
}
return asset;
}
private void CreateRecipe(string path, SlotDataAsset sd, OverlayDataAsset od)
{
UMAEditorUtilities.CreateRecipe(path, sd, od, sd.name, addToGlobalLibrary);
}
private SlotDataAsset CreateSlot_Internal()
{
var material = slotMaterial;
if (slotName == null || slotName == "")
{
Debug.LogError("slotName must be specified.");
return null;
}
if (material == null)
{
Debug.LogWarning("No UMAMaterial specified, you need to specify that later.");
return null;
}
if (slotFolder == null)
{
Debug.LogError("Slot folder not supplied");
return null;
}
if (slotMesh == null)
{
Debug.LogError("Slot Mesh not supplied.");
return null;
}
List<string> KeepList = new List<string>();
foreach(BoneName b in KeepBones)
{
KeepList.Add(b.strValue);
}
SlotDataAsset slot = UMASlotProcessingUtil.CreateSlotData(AssetDatabase.GetAssetPath(slotFolder), GetAssetFolder(), GetAssetName(),GetSlotName(slotMesh),nameAfterMaterial, slotMesh, material, normalReferenceMesh,KeepList, RootBone, binarySerialization,calcTangents);
slot.tags = Tags.ToArray();
return slot;
}
private void DropAreaGUI(Rect dropArea)
{
var evt = Event.current;
if (evt.type == EventType.DragUpdated)
{
if (dropArea.Contains(evt.mousePosition))
{
DragAndDrop.visualMode = DragAndDropVisualMode.Copy;
}
}
if (evt.type == EventType.DragPerform)
{
if (dropArea.Contains(evt.mousePosition))
{
DragAndDrop.AcceptDrag();
UnityEngine.Object[] draggedObjects = DragAndDrop.objectReferences as UnityEngine.Object[];
var meshes = new HashSet<SkinnedMeshRenderer>();
for (int i = 0; i < draggedObjects.Length; i++)
{
RecurseObject(draggedObjects[i], meshes);
}
SlotDataAsset sd = null;
float current = 1f;
float total = (float)meshes.Count;
foreach(var mesh in meshes)
{
EditorUtility.DisplayProgressBar(string.Format("Creating Slots {0} of {1}", current, total), string.Format("Slot: {0}", mesh.name), (current / total));
slotMesh = mesh;
GetMaterialName(mesh.name, mesh);
sd = CreateSlot();
if (sd != null)
{
Debug.Log("Batch importer processed mesh: " + slotName);
string AssetPath = AssetDatabase.GetAssetPath(sd.GetInstanceID());
if (createOverlay)
{
CreateOverlay(AssetPath.Replace(sd.name, sd.slotName + "_Overlay"), sd);
}
if (createRecipe)
{
CreateRecipe(AssetPath.Replace(sd.name, sd.slotName + "_Recipe"), sd, null);
}
}
current++;
}
EditorUtility.ClearProgressBar();
}
}
}
private string AsciiName(string name)
{
return name.ToTitleCase();
}
private void RecurseObject(Object obj, HashSet<SkinnedMeshRenderer> meshes)
{
GameObject go = obj as GameObject;
if (go != null)
{
foreach (var smr in go.GetComponentsInChildren<SkinnedMeshRenderer>(true))
{
meshes.Add(smr);
}
return;
}
var path = AssetDatabase.GetAssetPath(obj);
if (!string.IsNullOrEmpty(path) && System.IO.Directory.Exists(path))
{
foreach (var guid in AssetDatabase.FindAssets("t:GameObject", new string[] {path}))
{
RecurseObject(AssetDatabase.LoadAssetAtPath(AssetDatabase.GUIDToAssetPath(guid), typeof(GameObject)), meshes);
}
}
}
private string ProcessTextureTypeAndName(Texture2D tex)
{
var suffixes = new string[] { "_dif", "_spec", "_nor" };
int index = 0;
foreach( var suffix in suffixes )
{
index = tex.name.IndexOf(suffix, System.StringComparison.InvariantCultureIgnoreCase);
if( index > 0 )
{
string name = tex.name.Substring(0,index);
GetMaterialName(name, tex);
return suffix;
}
}
return "";
}
private void GetMaterialName(string name, UnityEngine.Object obj)
{
if (relativeFolder != null)
{
var relativeLocation = AssetDatabase.GetAssetPath(relativeFolder);
var assetLocation = AssetDatabase.GetAssetPath(obj);
if (assetLocation.StartsWith(relativeLocation, System.StringComparison.InvariantCultureIgnoreCase))
{
string temp = assetLocation.Substring(relativeLocation.Length + 1); // remove the prefix
temp = temp.Substring(0, temp.LastIndexOf('/') + 1); // remove the asset name
slotName = temp + name; // add the cleaned name
}
}
else
{
slotName = name;
}
}
[MenuItem("UMA/Slot Builder", priority = 20)]
public static void OpenUmaTexturePrepareWindow()
{
UmaSlotBuilderWindow window = (UmaSlotBuilderWindow)EditorWindow.GetWindow(typeof(UmaSlotBuilderWindow));
window.titleContent.text = "Slot Builder";
}
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Research.AbstractDomains;
using System.Diagnostics.Contracts;
namespace Microsoft.Research.CodeAnalysis
{
public static partial class AnalysisWrapper
{
public static partial class TypeBindings<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Expression, Variable>
where Variable : IEquatable<Variable>
where Expression : IEquatable<Expression>
where Type : IEquatable<Type>
{
internal class ArithmeticObligations
: ProofObligations<Local, Parameter, Method, Field, Property, Event, Type, Variable, Attribute, Assembly, BoxedExpression, ProofObligationBase<BoxedExpression, Variable>>
{
BoxedExpressionDecoder<Type, Variable, Expression> expressionDecoder;
new IExpressionContext<Local, Parameter, Method, Field, Type, Expression, Variable> Context
{
get
{
return this.MethodDriver.Context;
}
}
BoxedExpressionDecoder<Type, Variable, Expression> DecoderForExpressions
{
get
{
if (this.expressionDecoder == null)
{
this.expressionDecoder = BoxedExpressionDecoder<Variable>.Decoder(new ValueExpDecoder(Context, this.MetaDataDecoder));
}
return this.expressionDecoder;
}
}
IMethodDriver<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Expression, Variable, ILogOptions> MethodDriver
{
get;
set;
}
public readonly Analyzers.Arithmetic.ArithmeticOptions myOptions;
public ArithmeticObligations
(
IMethodDriver<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Expression, Variable, ILogOptions> mdriver,
Analyzers.Arithmetic.ArithmeticOptions myOptions
)
{
this.MethodDriver = mdriver;
this.myOptions = myOptions;
this.Run(this.MethodDriver.ValueLayer);
}
public override string Name
{
get { return "Arithmetic"; }
}
public override bool Binary(APC pc, BinaryOperator op, Variable dest, Variable s1, Variable s2, bool data)
{
if (this.IgnoreProofObligationAtPC(pc))
{
return data;
}
var mdDecoder = this.MetaDataDecoder;
var valueContext = this.Context.ValueContext;
var methodContext = this.Context.MethodContext;
var expressionContext = this.Context.ExpressionContext;
var expressionDecoder = this.DecoderForExpressions;
if (this.myOptions.Div0Obligations)
{
var type = valueContext.GetType(methodContext.CFG.Post(pc), s1);
if (type.IsNormal && mdDecoder.IsIntegerType(type.Value))
{
if (op == BinaryOperator.Div || op == BinaryOperator.Div_Un || op == BinaryOperator.Rem || op == BinaryOperator.Rem_Un)
{
var s2AsBoxedExpression = BoxedExpression.Convert(expressionContext.Refine(pc, s2), expressionDecoder.Outdecoder);
if (s2AsBoxedExpression != null)
{
this.Add(new DivisionByZeroObligation(s2AsBoxedExpression, expressionDecoder, pc, this.MethodDriver));
}
}
}
}
if (this.myOptions.DivOverflowObligations
&& (op == BinaryOperator.Div || op == BinaryOperator.Rem))
{
var type = valueContext.GetType(methodContext.CFG.Post(pc), s1);
if (type.IsNormal && mdDecoder.IsIntegerType(type.Value))
{
var op1 = BoxedExpression.Convert(expressionContext.Refine(pc, s1), expressionDecoder.Outdecoder);
var op2 = BoxedExpression.Convert(expressionContext.Refine(pc, s2), expressionDecoder.Outdecoder);
if (op1 != null && op2 != null)
{
this.Add(new DivisionOverflowObligation(op1, op2, type.Value, expressionDecoder, pc, this.MethodDriver));
}
}
}
var emitProofObligationsForInts = this.myOptions.ArithmeticOverflow && op.IsOverflowChecked();
var emitProofObligationsForFloats = this.myOptions.FloatingPointOverflow;
if (emitProofObligationsForInts || emitProofObligationsForFloats)
{
var type = valueContext.GetType(methodContext.CFG.Post(pc), dest);
if (type.IsNormal)
{
var left = BoxedExpression.Convert(expressionContext.Refine(pc, s1), expressionDecoder.Outdecoder);
var right = BoxedExpression.Convert(expressionContext.Refine(pc, s2), expressionDecoder.Outdecoder);
if (left != null && right != null)
{
var exp = BoxedExpression.Binary(op, left, right);
// According to the type we generate different proof obligations
if (emitProofObligationsForInts && (mdDecoder.IsIntegerType(type.Value) || mdDecoder.IsUnsignedIntegerType(type.Value)))
{
this.Add(new ArithmeticUnderflow(exp, type.Value, pc, expressionDecoder, this.MethodDriver));
this.Add(new ArithmeticOverflow(exp, type.Value, pc, expressionDecoder, this.MethodDriver));
}
else if (emitProofObligationsForFloats && !op.IsComparisonBinaryOperator() && mdDecoder.IsFloatType(type.Value))
{
this.Add(new ArithmeticUnderflowForFloats(exp, type.Value, pc, expressionDecoder, this.MethodDriver));
this.Add(new ArithmeticOverflowForFloats(exp, type.Value, pc, expressionDecoder, this.MethodDriver));
}
}
}
}
if (this.myOptions.FloatingPointIsNaN)
{
var type = valueContext.GetType(methodContext.CFG.Post(pc), dest);
if (IsFloat(type))
{
}
}
if (op == BinaryOperator.Ceq && this.myOptions.FloatEqualityObligations)
{
var t1 = valueContext.GetType(pc, s1);
var t2 = valueContext.GetType(pc, s2);
if (!t1.IsBottom && !t2.IsBottom && (IsFloat(t1) || IsFloat(t2)))
{
var s1Exp = BoxedExpression.Convert(expressionContext.Refine(pc, s1), expressionDecoder.Outdecoder);
var s2Exp = BoxedExpression.Convert(expressionContext.Refine(pc, s2), expressionDecoder.Outdecoder);
if (s1Exp != null && s2Exp != null)
{
this.Add(new FloatEqualityObligation(pc, dest, s1Exp, s2Exp, expressionDecoder, this.MethodDriver));
}
}
}
return data;
}
public override bool Newarray<ArgList>(APC pc, Type type, Variable dest, ArgList lengths, bool data)
{
if (this.IgnoreProofObligationAtPC(pc))
{
return data;
}
if (this.myOptions.ArithmeticOverflow && lengths.Count == 1)
{
var condition = BoxedExpression.Convert(this.Context.ExpressionContext.Refine(pc, lengths[0]), this.DecoderForExpressions.Outdecoder);
if (condition != null)
{
this.Add(new NewArrayArithmeticOverflow(condition, pc, this.DecoderForExpressions, this.MethodDriver));
}
}
return data;
}
public override bool Unary(APC pc, UnaryOperator op, bool overflow, bool unsigned, Variable dest, Variable source, bool data)
{
if (this.IgnoreProofObligationAtPC(pc))
{
return data;
}
var mdDecoder = this.MetaDataDecoder;
if (this.myOptions.NegMinObligations && op == UnaryOperator.Neg)
{
var type = this.Context.ValueContext.GetType(pc, source);
if (type.IsNormal &&
(mdDecoder.Equal(type.Value, mdDecoder.System_Int32) ||
mdDecoder.Equal(type.Value, mdDecoder.System_Int64) ||
mdDecoder.Equal(type.Value, mdDecoder.System_Int16) ||
mdDecoder.Equal(type.Value, mdDecoder.System_Int8)
))
{
var argAsBoxedExpression = BoxedExpression.Convert(this.Context.ExpressionContext.Refine(pc, source), this.DecoderForExpressions.Outdecoder);
if (argAsBoxedExpression != null)
{
this.Add(new NoMinValueObligation(type.Value, mdDecoder.Name(type.Value), argAsBoxedExpression, this.DecoderForExpressions, pc, this.MethodDriver));
}
}
}
if (overflow && this.myOptions.ArithmeticOverflow && op.IsConversionOperator())
{
// this.Context.ValueContext.GetType fails sometimes. This is why we infer the type from the operator
Type type;
if (mdDecoder.TryInferTypeForOperator(op, out type))
{
var exp = BoxedExpression.Convert(this.Context.ExpressionContext.Refine(pc, source), this.DecoderForExpressions.Outdecoder);
if (exp != null)
{
this.Add(new ArithmeticUnderflow(exp, type, pc, this.DecoderForExpressions, this.MethodDriver));
this.Add(new ArithmeticOverflow(exp, type, pc, this.DecoderForExpressions, this.MethodDriver));
}
}
}
return data;
}
private bool IsFloat(FlatDomain<Type> t)
{
var mdDecoder = this.MetaDataDecoder;
return t.IsNormal && (t.Value.Equals(mdDecoder.System_Single) || t.Value.Equals(mdDecoder.System_Double));
}
}
#region Proof obligations
class DivisionByZeroObligation
: ProofObligationWithDecoder
{
#region Statics
public static readonly string[] fixedMessages =
{
"Possible division by zero",
"This arithmetic operation is unreached",
"Division by zero ok",
"Division by zero detected"
};
#endregion
#region Object invariant
[ContractInvariantMethod]
private void ObjectInvariant()
{
Contract.Invariant(this.denominator != null);
}
#endregion
#region State
readonly BoxedExpression denominator;
#endregion
#region Constructor
public DivisionByZeroObligation
(
BoxedExpression denominator, BoxedExpressionDecoder<Variable> decoder, APC pc,
IMethodDriver<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Expression, Variable, ILogOptions> mdriver
)
: base(pc, decoder, mdriver, null)
{
Contract.Requires(denominator != null);
this.denominator = denominator;
}
#endregion
#region Overridden
public override BoxedExpression Condition
{
get
{
return
BoxedExpression.Binary(BinaryOperator.Cne_Un,
this.denominator,
BoxedExpression.Const(0, this.DecoderForMetaData.System_Int32, this.DecoderForMetaData));
}
}
protected override void PopulateWarningContextInternal(ProofOutcome outcome)
{
if (outcome == ProofOutcome.Top)
{
this.AdditionalInformationOnTheWarning.AddRange(WarningContextFetcher.InferContext(this.PC, this.denominator, this.Context, this.DecoderForMetaData.IsBoolean));
}
}
public override void EmitOutcome(ProofOutcome outcome, IOutputResults output)
{
output.EmitOutcome(GetWitness(outcome), this.AddHintsForTheUser(outcome, "{0}"), fixedMessages[(int)outcome]);
}
public override Witness GetWitness(ProofOutcome outcome)
{
this.PopulateWarningContext(outcome);
return new Witness(this.ID, WarningType.ArithmeticDivisionByZero, outcome, this.PC, this.AdditionalInformationOnTheWarning);
}
protected override ProofOutcome ValidateInternalSpecific(IFactQuery<BoxedExpression, Variable> query, ContractInferenceManager inferenceManager, IOutputResults output)
{
return query.IsNonZero(this.PC, this.denominator);
}
public override string ObligationName
{
get { return "DivisionByZeroObligation"; }
}
#endregion
}
class DivisionOverflowObligation
: ProofObligationWithDecoder
{
#region Statics
public static readonly string[] fixedMessages =
{
"Possible overflow in division (MinValue / -1)",
"This arithmetic operation is unreached",
"No overflow",
"Overflow in division"
};
#endregion
#region Invariant
[ContractInvariantMethod]
private void ObjectInvariant()
{
Contract.Invariant(this.Op1 != null);
Contract.Invariant(this.Op2 != null);
}
#endregion
#region State
readonly private BoxedExpression Op1;
readonly private BoxedExpression Op2;
readonly private Type TypeOp1;
#endregion
#region Constructor
public DivisionOverflowObligation(BoxedExpression op1, BoxedExpression op2,
Type typeOp1,
BoxedExpressionDecoder<Variable> decoder, APC pc,
IMethodDriver<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Expression, Variable, ILogOptions> mdriver)
: base(pc, decoder, mdriver, null)
{
Contract.Requires(op1 != null);
Contract.Requires(op2 != null);
this.Op1 = op1;
this.Op2 = op2;
this.TypeOp1 = typeOp1;
}
#endregion
#region Overridden
public override BoxedExpression Condition
{
get
{
object minValue;
if (!this.DecoderForMetaData.TryGetMinValueForType(this.TypeOp1, out minValue))
{
return null;
}
var condition1 = BoxedExpression.Binary(BinaryOperator.Cne_Un, this.Op1, BoxedExpression.Const(minValue, this.TypeOp1, this.DecoderForMetaData));
var condition2 = BoxedExpression.Binary(BinaryOperator.Cne_Un, this.Op2, BoxedExpression.Const(-1, this.DecoderForMetaData.System_Int32, this.DecoderForMetaData));
return BoxedExpression.Binary(BinaryOperator.LogicalOr, condition1, condition2);
}
}
protected override ProofOutcome ValidateInternalSpecific(IFactQuery<BoxedExpression, Variable> query, ContractInferenceManager inferenceManager, IOutputResults output)
{
object minValue;
if (!this.DecoderForMetaData.TryGetMinValueForType(this.TypeOp1, out minValue))
{
return ProofOutcome.Top;
}
// first, we check that Op1 != MinValue
var condition1 = BoxedExpression.Binary(BinaryOperator.Cne_Un, this.Op1, BoxedExpression.Const(minValue, this.TypeOp1, this.DecoderForMetaData));
var resultOp1 = query.IsTrue(this.PC, condition1);
// second, we check Op2 != -1
var condition2 = BoxedExpression.Binary(BinaryOperator.Cne_Un, this.Op2, BoxedExpression.Const(-1, this.DecoderForMetaData.System_Int32, this.DecoderForMetaData));
var resultOp2 = query.IsTrue(this.PC, condition2);
// One of the two conditions is true, so it is ok!
if (resultOp1 == ProofOutcome.True || resultOp2 == ProofOutcome.True)
{
return ProofOutcome.True;
}
// Both conditions are false, so division is definitely an overflow
if (resultOp1 == ProofOutcome.False && resultOp2 == ProofOutcome.False)
{
return ProofOutcome.False;
}
return ProofOutcome.Top;
}
protected override void PopulateWarningContextInternal(ProofOutcome outcome)
{
if (outcome == ProofOutcome.Top)
{
this.AdditionalInformationOnTheWarning.AddRange(WarningContextFetcher.InferContext(this.PC, this.Op1, this.Context, this.DecoderForMetaData.IsBoolean));
}
}
public override void EmitOutcome(ProofOutcome outcome, IOutputResults output)
{
output.EmitOutcome(GetWitness(outcome), AddHintsForTheUser(outcome, "{0}"), fixedMessages[(int)outcome]);
}
public override Witness GetWitness(ProofOutcome outcome)
{
this.PopulateWarningContext(outcome);
return new Witness(this.ID, WarningType.ArithmeticDivisionOverflow, outcome, this.PC, this.AdditionalInformationOnTheWarning);
}
public override string ObligationName
{
get { return "DivisionOverflowObligation"; }
}
}
/// <summary>
/// The proof obligation for Arithmetic Overflow
/// </summary>
abstract class ArithmeticUnderflowOrOverflowObligation
: ProofObligationWithDecoder
{
#region Object Invariant
[ContractInvariantMethod]
private void ObjectInvariant()
{
Contract.Invariant(this.exp != null);
}
#endregion
#region State
readonly protected BoxedExpression exp;
readonly protected Type type;
#endregion
#region To be Overridden
//protected virtual abstract BoxedExpression Condition { get; }
protected abstract string What { get; }
protected abstract string what { get; }
#endregion
#region Constructor
protected ArithmeticUnderflowOrOverflowObligation(BoxedExpression exp, Type type, APC pc,
BoxedExpressionDecoder<Variable> decoder,
IMethodDriver<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Expression, Variable, ILogOptions> mdriver)
: base(pc, decoder, mdriver, null)
{
Contract.Requires(exp != null);
this.exp = exp;
this.type = type;
}
#endregion
#region overridden
protected override ProofOutcome ValidateInternalSpecific(IFactQuery<BoxedExpression, Variable> query, ContractInferenceManager inferenceManager, IOutputResults output)
{
// We check the condition
var condition = this.Condition;
if (condition == null)
{
return ProofOutcome.Top;
}
return query.IsTrue(this.PC, condition);
}
protected override void PopulateWarningContextInternal(ProofOutcome outcome)
{
if (outcome == ProofOutcome.Top)
{
this.AdditionalInformationOnTheWarning.AddRange(WarningContextFetcher.InferContext(this.PC, this.exp, this.Context, this.DecoderForMetaData.IsBoolean));
}
}
public override void EmitOutcome(ProofOutcome outcome, IOutputResults output)
{
output.EmitOutcome(GetWitness(outcome), AddHintsForTheUser(outcome, "{0}"), FixedMessages(outcome));
}
public override Witness GetWitness(ProofOutcome outcome)
{
this.PopulateWarningContext(outcome);
return new Witness(this.ID, WarningType.ArithmeticDivisionOverflow, outcome, this.PC, this.AdditionalInformationOnTheWarning);
}
protected string FixedMessages(ProofOutcome outcome)
{
switch (outcome)
{
case ProofOutcome.Bottom:
return "This arithmetic operation is unreached";
case ProofOutcome.False:
return What + " in the arithmetic operation";
case ProofOutcome.Top:
return "Possible " + what + " in the arithmetic operation";
case ProofOutcome.True:
return "No " + what;
default:
return "unknown outcome";
}
}
public override string ObligationName
{
get { return "ArithmeticUnderflowOrOverflowObligation"; }
}
#endregion
}
class ArithmeticUnderflow
: ArithmeticUnderflowOrOverflowObligation
{
private BoxedExpression condition;
public ArithmeticUnderflow(BoxedExpression exp, Type type, APC pc, BoxedExpressionDecoder<Variable> decoder,
IMethodDriver<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Expression, Variable, ILogOptions> mdriver)
: base(exp, type, pc, decoder, mdriver)
{ }
public override BoxedExpression Condition
{
get
{
if (condition == null)
{
object minvalue;
if (this.DecoderForMetaData.TryGetMinValueForType(type, out minvalue))
{
condition = BoxedExpression.Binary(BinaryOperator.Cle, BoxedExpression.Const(minvalue, this.type, this.DecoderForMetaData), this.exp);
}
}
return condition;
}
}
protected override string What
{
get { return "Underflow"; }
}
protected override string what
{
get { return "underflow"; }
}
public override string ObligationName
{
get { return "ArithemeticUnderflow"; }
}
}
class ArithmeticOverflow
: ArithmeticUnderflowOrOverflowObligation
{
private BoxedExpression condition;
public ArithmeticOverflow(BoxedExpression exp, Type type, APC pc, BoxedExpressionDecoder<Variable> decoder,
IMethodDriver<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Expression, Variable, ILogOptions> mdriver)
: base(exp, type, pc, decoder, mdriver)
{ }
public override BoxedExpression Condition
{
get
{
if (condition == null)
{
object maxvalue;
if (this.DecoderForMetaData.TryGetMaxValueForType(type, out maxvalue))
{
condition = BoxedExpression.Binary(BinaryOperator.Cle, this.exp, BoxedExpression.Const(maxvalue, this.type, this.DecoderForMetaData));
}
}
return condition;
}
}
protected override string What
{
get { return "Overflow"; }
}
protected override string what
{
get { return "overflow"; }
}
public override string ObligationName
{
get { return "ArithmeticOverflow"; }
}
}
class ArithmeticUnderflowForFloats
: ArithmeticUnderflowOrOverflowObligation
{
private BoxedExpression condition;
public ArithmeticUnderflowForFloats(BoxedExpression exp, Type type, APC pc, BoxedExpressionDecoder<Variable> decoder,
IMethodDriver<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Expression, Variable, ILogOptions> mdriver)
: base(exp, type, pc, decoder, mdriver)
{ }
protected override string What
{
get { return "Too small floating point result"; }
}
protected override string what
{
get { return "too small floating point result"; }
}
public override BoxedExpression Condition
{
get
{
if (condition == null)
{
object minvalue;
if (this.DecoderForMetaData.TryGetMinValueForType(type, out minvalue))
{
condition = BoxedExpression.Binary(BinaryOperator.Cle, BoxedExpression.Const(minvalue, this.type, this.DecoderForMetaData), this.exp);
}
}
return condition;
}
}
}
class ArithmeticOverflowForFloats
: ArithmeticUnderflowOrOverflowObligation
{
private BoxedExpression condition;
public ArithmeticOverflowForFloats(BoxedExpression exp, Type type, APC pc, BoxedExpressionDecoder<Variable> decoder,
IMethodDriver<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Expression, Variable, ILogOptions> mdriver)
: base(exp, type, pc, decoder, mdriver)
{ }
protected override string What
{
get { return "Too large floating point result"; }
}
protected override string what
{
get { return "too large floating point result"; }
}
public override BoxedExpression Condition
{
get
{
if (condition == null)
{
object maxvalue;
if (this.DecoderForMetaData.TryGetMaxValueForType(type, out maxvalue))
{
condition = BoxedExpression.Binary(BinaryOperator.Cle, this.exp, BoxedExpression.Const(maxvalue, this.type, this.DecoderForMetaData));
}
}
return condition;
}
}
}
class ArithmeticIsNaN
: ArithmeticUnderflowOrOverflowObligation
{
#region state
private BoxedExpression condition;
#endregion
public ArithmeticIsNaN(BoxedExpression exp, Type type, APC pc, BoxedExpressionDecoder<Variable> decoder,
IMethodDriver<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Expression, Variable, ILogOptions> mdriver,
object provenance = null)
: base(exp, type, pc, decoder, mdriver)
{
Contract.Requires(exp != null);
Contract.Requires(decoder != null);
Contract.Requires(mdriver != null);
this.condition = null;
}
protected override string What
{
get { return "Is not NaN"; }
}
protected override string what
{
get { return "is not NaN"; }
}
public override BoxedExpression Condition
{
get
{
if (this.condition == null)
{
// MinusInfinity <= exp
var geqMinValue = BoxedExpression.Binary(
BinaryOperator.Cge_Un,
BoxedExpression.Const(this.MinusInfinity, this.type, this.DecoderForMetaData),
this.exp);
// exp <= PlusInfinity
var leqPlusInfinity = BoxedExpression.Binary(
BinaryOperator.Cge_Un,
this.exp,
BoxedExpression.Const(this.PlusInfinity, this.type, this.DecoderForMetaData));
condition = BoxedExpression.Binary(BinaryOperator.LogicalOr, geqMinValue, leqPlusInfinity);
}
return this.condition;
}
}
private object MinusInfinity
{
get
{
if (this.MethodDriver.MetaDataDecoder.System_Single.Equals(this.type))
{
return Single.NegativeInfinity;
}
else
{
return Double.NegativeInfinity;
}
}
}
private object PlusInfinity
{
get
{
if (this.MethodDriver.MetaDataDecoder.System_Single.Equals(this.type))
{
return Single.PositiveInfinity;
}
else
{
return Double.PositiveInfinity;
}
}
}
}
class NewArrayArithmeticOverflow
: ArithmeticUnderflowOrOverflowObligation
{
private BoxedExpression condition;
public NewArrayArithmeticOverflow(BoxedExpression exp, APC pc, BoxedExpressionDecoder<Variable> decoder,
IMethodDriver<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Expression, Variable, ILogOptions> mdriver)
: base(exp, mdriver.MetaDataDecoder.System_Int32, pc, decoder, mdriver)
{ }
public override BoxedExpression Condition
{
get
{
if (condition == null)
{
condition = BoxedExpression.Binary(BinaryOperator.Cle, this.exp, BoxedExpression.Const((Int64)Int32.MaxValue, this.DecoderForMetaData.System_Int64, this.DecoderForMetaData));
}
return condition;
}
}
/// <summary>
/// We return 0 leq exp
/// </summary>
public override BoxedExpression ConditionForPreconditionInference
{
get
{
return BoxedExpression.Binary(BinaryOperator.Cle, BoxedExpression.Const(0, this.DecoderForMetaData.System_Int32, this.DecoderForMetaData), this.exp);
}
}
protected override ProofOutcome ValidateInternalSpecific(IFactQuery<BoxedExpression, Variable> query, ContractInferenceManager inferenceManager, IOutputResults output)
{
// If it is a variable or a constant, then there is nothing to do, and we return true.
if (this.exp.IsConstant || this.exp.IsVariable)
{
return ProofOutcome.True;
}
return base.ValidateInternalSpecific(query, inferenceManager, output);
}
protected override string What
{
get { return "Overflow (caused by a negative array size)"; }
}
protected override string what
{
get { return "overflow (caused by a negative array size)"; }
}
public override string ObligationName
{
get { return "NewArrayArithmeticOverflow"; }
}
}
/// <summary>
/// The proof obligation for the unary negation
/// </summary>
class NoMinValueObligation
: ProofObligationWithDecoder
{
#region Statics
public static readonly string[] fixedMessages =
{
"Possible negation of MinValue",
"This arithmetic operation is unreached",
"Negation ok (no MinValue)",
"Negation of MinValue"
};
#endregion
#region Object invariant
[ContractInvariantMethod]
private void ObjectInvariant()
{
Contract.Invariant(this.arg != null);
}
#endregion
#region State
readonly BoxedExpression arg;
readonly Type typeOfArg; // either int8, int16, int32, or int64
string nameOfTypeOfArg;
#endregion
#region Constructor
public NoMinValueObligation
(
Type typeOfArg,
string nameOfTypeOfArg,
BoxedExpression arg, BoxedExpressionDecoder<Variable> decoder, APC pc,
IMethodDriver<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Expression, Variable, ILogOptions> mdriver
)
: base(pc, decoder, mdriver, null)
{
Contract.Requires(arg != null);
this.arg = arg;
this.typeOfArg = typeOfArg;
this.nameOfTypeOfArg = nameOfTypeOfArg;
}
#endregion
#region Overridden
public override BoxedExpression Condition
{
get
{
object value;
if (!this.DecoderForMetaData.TryGetMinValueForType(this.typeOfArg, out value))
{
return null;
}
return BoxedExpression.Binary(BinaryOperator.Cne_Un, this.arg, BoxedExpression.Const(value, this.typeOfArg, this.DecoderForMetaData));
}
}
public override void EmitOutcome(ProofOutcome outcome, IOutputResults output)
{
output.EmitOutcome(GetWitness(outcome), AddHintsForTheUser(outcome, "{0} of type {1}"), fixedMessages[(int)outcome], nameOfTypeOfArg);
}
public override Witness GetWitness(ProofOutcome outcome)
{
this.PopulateWarningContext(outcome);
return new Witness(this.ID, WarningType.ArithmeticMinValueNegation, outcome, this.PC, this.AdditionalInformationOnTheWarning);
}
protected override void PopulateWarningContextInternal(ProofOutcome outcome)
{
if (outcome == ProofOutcome.Top)
{
this.AdditionalInformationOnTheWarning.AddRange(WarningContextFetcher.InferContext(this.PC, this.arg, this.Context, this.DecoderForMetaData.IsBoolean));
}
}
protected override ProofOutcome ValidateInternalSpecific(IFactQuery<BoxedExpression, Variable> query, ContractInferenceManager inferenceManager, IOutputResults output)
{
// First, we check if arg != MinValue
object value;
if (!this.DecoderForMetaData.TryGetMinValueForType(this.typeOfArg, out value))
{
return ProofOutcome.Top;
}
var condition = this.Condition;
if (condition != null) // this.Condition may return null
{
var result = query.IsTrue(this.PC, condition);
if (result != ProofOutcome.Top)
{
return result;
}
}
// We check a sufficient condition: if arg is >= 0, then it is not the negation of a negative "extreme"
var greaterThanZero = query.IsGreaterEqualToZero(this.PC, this.arg);
return (greaterThanZero == ProofOutcome.True || greaterThanZero == ProofOutcome.Bottom)
? greaterThanZero : ProofOutcome.Top;
}
private string TypeMinValueAsString()
{
string prefix;
var MetaDataDecoder = this.MethodDriver.MetaDataDecoder;
if (MetaDataDecoder.Equal(this.typeOfArg, MetaDataDecoder.System_Int32))
prefix = "Int32";
else if (MetaDataDecoder.Equal(this.typeOfArg, MetaDataDecoder.System_Int64))
prefix = "Int64";
else if (MetaDataDecoder.Equal(this.typeOfArg, MetaDataDecoder.System_Int16))
prefix = "Int16";
else if (MetaDataDecoder.Equal(this.typeOfArg, MetaDataDecoder.System_Int8))
prefix = "Int8";
else
prefix = "UnknownType";
return string.Format("{0}.MinValue", prefix);
}
public override string ObligationName
{
get { return "NoMinValueObligation"; }
}
#endregion
}
class FloatEqualityObligation : ProofObligationWithDecoder
{
#region Statics
public static readonly string[] fixedMessages =
{
"Possible precision mismatch for the arguments of ==",
"This comparison is unreached",
"The arguments of the comparison have a compatible precision",
"The arguments of the comparisons have an INCOMPATIBLE precision"
};
#endregion
#region Invariant
[ContractInvariantMethod]
private void ObjectInvariant()
{
Contract.Invariant(this.left != null);
Contract.Invariant(this.right != null);
}
#endregion
#region State
private readonly Variable var;
private readonly BoxedExpression left, right;
public FloatEqualityObligation(APC pc, Variable var, BoxedExpression left, BoxedExpression right, BoxedExpressionDecoder<Variable> decoder, IMethodDriver<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Expression, Variable, ILogOptions> mdriver)
: base(pc, decoder, mdriver, null)
{
this.var = var;
this.left = left;
this.right = right;
}
#endregion
#region Overridden
public override BoxedExpression Condition
{
get { return null; }
}
/// <summary>
/// If we cannot validate the precision of the operands, we try to suggest an explicit cast
/// </summary>
protected override ProofOutcome ValidateInternalSpecific(IFactQuery<BoxedExpression, Variable> query, ContractInferenceManager inferenceManager, IOutputResults output)
{
var outcome = query.HaveSameFloatType(PC, this.left, this.right);
switch (outcome)
{
case ProofOutcome.Top:
{
ConcreteFloat leftType, rightType;
if (query.TryGetFloatType(this.PC, this.left, out leftType) && query.TryGetFloatType(this.PC, this.right, out rightType))
{
APC conditionPC;
if (!this.MethodDriver.AdditionalSyntacticInformation.VariableDefinitions.TryGetValue(this.var, out conditionPC))
{
conditionPC = this.PC;
}
if(inferenceManager.CodeFixesManager.TrySuggestFloatingPointComparisonFix(this, conditionPC, this.left, this.right, leftType, rightType))
{
// do something? Returning true seems a bad idea
}
}
return outcome;
}
default:
{
return outcome;
}
}
}
protected override void PopulateWarningContextInternal(ProofOutcome outcome)
{
// does nothing
}
public override void EmitOutcome(ProofOutcome outcome, IOutputResults output)
{
output.EmitOutcome(GetWitness(outcome), fixedMessages[(int)outcome]);
}
public override Witness GetWitness(ProofOutcome outcome)
{
this.PopulateWarningContext(outcome);
return new Witness(this.ID, WarningType.ArithmeticFloatEqualityPrecisionMismatch, outcome, this.PC, this.AdditionalInformationOnTheWarning);
}
public override string ObligationName
{
get { return "EnumIsDefinedProofObligation"; }
}
#endregion
}
}
}
#endregion
#endregion
}
| |
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using Medivh.Json.Utilities;
namespace Medivh.Json.Linq.JsonPath
{
internal class JPath
{
private readonly string _expression;
public List<PathFilter> Filters { get; private set; }
private int _currentIndex;
public JPath(string expression)
{
ValidationUtils.ArgumentNotNull(expression, nameof(expression));
_expression = expression;
Filters = new List<PathFilter>();
ParseMain();
}
private void ParseMain()
{
int currentPartStartIndex = _currentIndex;
EatWhitespace();
if (_expression.Length == _currentIndex)
{
return;
}
if (_expression[_currentIndex] == '$')
{
if (_expression.Length == 1)
{
return;
}
// only increment position for "$." or "$["
// otherwise assume property that starts with $
char c = _expression[_currentIndex + 1];
if (c == '.' || c == '[')
{
_currentIndex++;
currentPartStartIndex = _currentIndex;
}
}
if (!ParsePath(Filters, currentPartStartIndex, false))
{
int lastCharacterIndex = _currentIndex;
EatWhitespace();
if (_currentIndex < _expression.Length)
{
throw new JsonException("Unexpected character while parsing path: " + _expression[lastCharacterIndex]);
}
}
}
private bool ParsePath(List<PathFilter> filters, int currentPartStartIndex, bool query)
{
bool scan = false;
bool followingIndexer = false;
bool followingDot = false;
bool ended = false;
while (_currentIndex < _expression.Length && !ended)
{
char currentChar = _expression[_currentIndex];
switch (currentChar)
{
case '[':
case '(':
if (_currentIndex > currentPartStartIndex)
{
string member = _expression.Substring(currentPartStartIndex, _currentIndex - currentPartStartIndex);
PathFilter filter = (scan) ? (PathFilter)new ScanFilter() { Name = member } : new FieldFilter() { Name = member };
filters.Add(filter);
scan = false;
}
filters.Add(ParseIndexer(currentChar));
_currentIndex++;
currentPartStartIndex = _currentIndex;
followingIndexer = true;
followingDot = false;
break;
case ']':
case ')':
ended = true;
break;
case ' ':
//EatWhitespace();
if (_currentIndex < _expression.Length)
{
ended = true;
}
break;
case '.':
if (_currentIndex > currentPartStartIndex)
{
string member = _expression.Substring(currentPartStartIndex, _currentIndex - currentPartStartIndex);
if (member == "*")
{
member = null;
}
PathFilter filter = (scan) ? (PathFilter)new ScanFilter() { Name = member } : new FieldFilter() { Name = member };
filters.Add(filter);
scan = false;
}
if (_currentIndex + 1 < _expression.Length && _expression[_currentIndex + 1] == '.')
{
scan = true;
_currentIndex++;
}
_currentIndex++;
currentPartStartIndex = _currentIndex;
followingIndexer = false;
followingDot = true;
break;
default:
if (query && (currentChar == '=' || currentChar == '<' || currentChar == '!' || currentChar == '>' || currentChar == '|' || currentChar == '&'))
{
ended = true;
}
else
{
if (followingIndexer)
{
throw new JsonException("Unexpected character following indexer: " + currentChar);
}
_currentIndex++;
}
break;
}
}
bool atPathEnd = (_currentIndex == _expression.Length);
if (_currentIndex > currentPartStartIndex)
{
string member = _expression.Substring(currentPartStartIndex, _currentIndex - currentPartStartIndex).TrimEnd();
if (member == "*")
{
member = null;
}
PathFilter filter = (scan) ? (PathFilter)new ScanFilter() { Name = member } : new FieldFilter() { Name = member };
filters.Add(filter);
}
else
{
// no field name following dot in path and at end of base path/query
if (followingDot && (atPathEnd || query))
{
throw new JsonException("Unexpected end while parsing path.");
}
}
return atPathEnd;
}
private PathFilter ParseIndexer(char indexerOpenChar)
{
_currentIndex++;
char indexerCloseChar = (indexerOpenChar == '[') ? ']' : ')';
EnsureLength("Path ended with open indexer.");
EatWhitespace();
if (_expression[_currentIndex] == '\'')
{
return ParseQuotedField(indexerCloseChar);
}
else if (_expression[_currentIndex] == '?')
{
return ParseQuery(indexerCloseChar);
}
else
{
return ParseArrayIndexer(indexerCloseChar);
}
}
private PathFilter ParseArrayIndexer(char indexerCloseChar)
{
int start = _currentIndex;
int? end = null;
List<int> indexes = null;
int colonCount = 0;
int? startIndex = null;
int? endIndex = null;
int? step = null;
while (_currentIndex < _expression.Length)
{
char currentCharacter = _expression[_currentIndex];
if (currentCharacter == ' ')
{
end = _currentIndex;
EatWhitespace();
continue;
}
if (currentCharacter == indexerCloseChar)
{
int length = (end ?? _currentIndex) - start;
if (indexes != null)
{
if (length == 0)
{
throw new JsonException("Array index expected.");
}
string indexer = _expression.Substring(start, length);
int index = Convert.ToInt32(indexer, CultureInfo.InvariantCulture);
indexes.Add(index);
return new ArrayMultipleIndexFilter { Indexes = indexes };
}
else if (colonCount > 0)
{
if (length > 0)
{
string indexer = _expression.Substring(start, length);
int index = Convert.ToInt32(indexer, CultureInfo.InvariantCulture);
if (colonCount == 1)
{
endIndex = index;
}
else
{
step = index;
}
}
return new ArraySliceFilter { Start = startIndex, End = endIndex, Step = step };
}
else
{
if (length == 0)
{
throw new JsonException("Array index expected.");
}
string indexer = _expression.Substring(start, length);
int index = Convert.ToInt32(indexer, CultureInfo.InvariantCulture);
return new ArrayIndexFilter { Index = index };
}
}
else if (currentCharacter == ',')
{
int length = (end ?? _currentIndex) - start;
if (length == 0)
{
throw new JsonException("Array index expected.");
}
if (indexes == null)
{
indexes = new List<int>();
}
string indexer = _expression.Substring(start, length);
indexes.Add(Convert.ToInt32(indexer, CultureInfo.InvariantCulture));
_currentIndex++;
EatWhitespace();
start = _currentIndex;
end = null;
}
else if (currentCharacter == '*')
{
_currentIndex++;
EnsureLength("Path ended with open indexer.");
EatWhitespace();
if (_expression[_currentIndex] != indexerCloseChar)
{
throw new JsonException("Unexpected character while parsing path indexer: " + currentCharacter);
}
return new ArrayIndexFilter();
}
else if (currentCharacter == ':')
{
int length = (end ?? _currentIndex) - start;
if (length > 0)
{
string indexer = _expression.Substring(start, length);
int index = Convert.ToInt32(indexer, CultureInfo.InvariantCulture);
if (colonCount == 0)
{
startIndex = index;
}
else if (colonCount == 1)
{
endIndex = index;
}
else
{
step = index;
}
}
colonCount++;
_currentIndex++;
EatWhitespace();
start = _currentIndex;
end = null;
}
else if (!char.IsDigit(currentCharacter) && currentCharacter != '-')
{
throw new JsonException("Unexpected character while parsing path indexer: " + currentCharacter);
}
else
{
if (end != null)
{
throw new JsonException("Unexpected character while parsing path indexer: " + currentCharacter);
}
_currentIndex++;
}
}
throw new JsonException("Path ended with open indexer.");
}
private void EatWhitespace()
{
while (_currentIndex < _expression.Length)
{
if (_expression[_currentIndex] != ' ')
{
break;
}
_currentIndex++;
}
}
private PathFilter ParseQuery(char indexerCloseChar)
{
_currentIndex++;
EnsureLength("Path ended with open indexer.");
if (_expression[_currentIndex] != '(')
{
throw new JsonException("Unexpected character while parsing path indexer: " + _expression[_currentIndex]);
}
_currentIndex++;
QueryExpression expression = ParseExpression();
_currentIndex++;
EnsureLength("Path ended with open indexer.");
EatWhitespace();
if (_expression[_currentIndex] != indexerCloseChar)
{
throw new JsonException("Unexpected character while parsing path indexer: " + _expression[_currentIndex]);
}
return new QueryFilter
{
Expression = expression
};
}
private QueryExpression ParseExpression()
{
QueryExpression rootExpression = null;
CompositeExpression parentExpression = null;
while (_currentIndex < _expression.Length)
{
EatWhitespace();
if (_expression[_currentIndex] != '@')
{
throw new JsonException("Unexpected character while parsing path query: " + _expression[_currentIndex]);
}
_currentIndex++;
List<PathFilter> expressionPath = new List<PathFilter>();
if (ParsePath(expressionPath, _currentIndex, true))
{
throw new JsonException("Path ended with open query.");
}
EatWhitespace();
EnsureLength("Path ended with open query.");
QueryOperator op;
object value = null;
if (_expression[_currentIndex] == ')'
|| _expression[_currentIndex] == '|'
|| _expression[_currentIndex] == '&')
{
op = QueryOperator.Exists;
}
else
{
op = ParseOperator();
EatWhitespace();
EnsureLength("Path ended with open query.");
value = ParseValue();
EatWhitespace();
EnsureLength("Path ended with open query.");
}
BooleanQueryExpression booleanExpression = new BooleanQueryExpression
{
Path = expressionPath,
Operator = op,
Value = (op != QueryOperator.Exists) ? new JValue(value) : null
};
if (_expression[_currentIndex] == ')')
{
if (parentExpression != null)
{
parentExpression.Expressions.Add(booleanExpression);
return rootExpression;
}
return booleanExpression;
}
if (_expression[_currentIndex] == '&' && Match("&&"))
{
if (parentExpression == null || parentExpression.Operator != QueryOperator.And)
{
CompositeExpression andExpression = new CompositeExpression { Operator = QueryOperator.And };
if (parentExpression != null)
{
parentExpression.Expressions.Add(andExpression);
}
parentExpression = andExpression;
if (rootExpression == null)
{
rootExpression = parentExpression;
}
}
parentExpression.Expressions.Add(booleanExpression);
}
if (_expression[_currentIndex] == '|' && Match("||"))
{
if (parentExpression == null || parentExpression.Operator != QueryOperator.Or)
{
CompositeExpression orExpression = new CompositeExpression { Operator = QueryOperator.Or };
if (parentExpression != null)
{
parentExpression.Expressions.Add(orExpression);
}
parentExpression = orExpression;
if (rootExpression == null)
{
rootExpression = parentExpression;
}
}
parentExpression.Expressions.Add(booleanExpression);
}
}
throw new JsonException("Path ended with open query.");
}
private object ParseValue()
{
char currentChar = _expression[_currentIndex];
if (currentChar == '\'')
{
return ReadQuotedString();
}
else if (char.IsDigit(currentChar) || currentChar == '-')
{
StringBuilder sb = new StringBuilder();
sb.Append(currentChar);
_currentIndex++;
while (_currentIndex < _expression.Length)
{
currentChar = _expression[_currentIndex];
if (currentChar == ' ' || currentChar == ')')
{
string numberText = sb.ToString();
if (numberText.IndexOfAny(new char[] { '.', 'E', 'e' }) != -1)
{
double d;
if (double.TryParse(numberText, NumberStyles.Float | NumberStyles.AllowThousands, CultureInfo.InvariantCulture, out d))
{
return d;
}
else
{
throw new JsonException("Could not read query value.");
}
}
else
{
long l;
if (long.TryParse(numberText, NumberStyles.Integer, CultureInfo.InvariantCulture, out l))
{
return l;
}
else
{
throw new JsonException("Could not read query value.");
}
}
}
else
{
sb.Append(currentChar);
_currentIndex++;
}
}
}
else if (currentChar == 't')
{
if (Match("true"))
{
return true;
}
}
else if (currentChar == 'f')
{
if (Match("false"))
{
return false;
}
}
else if (currentChar == 'n')
{
if (Match("null"))
{
return null;
}
}
throw new JsonException("Could not read query value.");
}
private string ReadQuotedString()
{
StringBuilder sb = new StringBuilder();
_currentIndex++;
while (_currentIndex < _expression.Length)
{
char currentChar = _expression[_currentIndex];
if (currentChar == '\\' && _currentIndex + 1 < _expression.Length)
{
_currentIndex++;
if (_expression[_currentIndex] == '\'')
{
sb.Append('\'');
}
else if (_expression[_currentIndex] == '\\')
{
sb.Append('\\');
}
else
{
throw new JsonException(@"Unknown escape chracter: \" + _expression[_currentIndex]);
}
_currentIndex++;
}
else if (currentChar == '\'')
{
_currentIndex++;
{
return sb.ToString();
}
}
else
{
_currentIndex++;
sb.Append(currentChar);
}
}
throw new JsonException("Path ended with an open string.");
}
private bool Match(string s)
{
int currentPosition = _currentIndex;
foreach (char c in s)
{
if (currentPosition < _expression.Length && _expression[currentPosition] == c)
{
currentPosition++;
}
else
{
return false;
}
}
_currentIndex = currentPosition;
return true;
}
private QueryOperator ParseOperator()
{
if (_currentIndex + 1 >= _expression.Length)
{
throw new JsonException("Path ended with open query.");
}
if (Match("=="))
{
return QueryOperator.Equals;
}
if (Match("!=") || Match("<>"))
{
return QueryOperator.NotEquals;
}
if (Match("<="))
{
return QueryOperator.LessThanOrEquals;
}
if (Match("<"))
{
return QueryOperator.LessThan;
}
if (Match(">="))
{
return QueryOperator.GreaterThanOrEquals;
}
if (Match(">"))
{
return QueryOperator.GreaterThan;
}
throw new JsonException("Could not read query operator.");
}
private PathFilter ParseQuotedField(char indexerCloseChar)
{
List<string> fields = null;
while (_currentIndex < _expression.Length)
{
string field = ReadQuotedString();
EatWhitespace();
EnsureLength("Path ended with open indexer.");
if (_expression[_currentIndex] == indexerCloseChar)
{
if (fields != null)
{
fields.Add(field);
return new FieldMultipleFilter { Names = fields };
}
else
{
return new FieldFilter { Name = field };
}
}
else if (_expression[_currentIndex] == ',')
{
_currentIndex++;
EatWhitespace();
if (fields == null)
{
fields = new List<string>();
}
fields.Add(field);
}
else
{
throw new JsonException("Unexpected character while parsing path indexer: " + _expression[_currentIndex]);
}
}
throw new JsonException("Path ended with open indexer.");
}
private void EnsureLength(string message)
{
if (_currentIndex >= _expression.Length)
{
throw new JsonException(message);
}
}
internal IEnumerable<JToken> Evaluate(JToken t, bool errorWhenNoMatch)
{
return Evaluate(Filters, t, errorWhenNoMatch);
}
internal static IEnumerable<JToken> Evaluate(List<PathFilter> filters, JToken t, bool errorWhenNoMatch)
{
IEnumerable<JToken> current = new[] { t };
foreach (PathFilter filter in filters)
{
current = filter.ExecuteFilter(current, errorWhenNoMatch);
}
return current;
}
}
}
| |
// System.Xml.Xsl.XslTransform
//
// Authors:
// Tim Coleman <tim@timcoleman.com>
// Gonzalo Paniagua Javier (gonzalo@ximian.com)
//
// (C) Copyright 2002 Tim Coleman
// (c) 2003 Ximian Inc. (http://www.ximian.com)
//
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections;
using System.IO;
using System.Text;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Policy;
using System.Xml.XPath;
using Mono.Xml.Xsl;
namespace System.Xml.Xsl {
internal class SimpleXsltDebugger
{
public void OnCompile (XPathNavigator style)
{
Console.Write ("Compiling: ");
PrintXPathNavigator (style);
Console.WriteLine ();
}
public void OnExecute (XPathNodeIterator currentNodeSet, XPathNavigator style, XsltContext xsltContext)
{
Console.Write ("Executing: ");
PrintXPathNavigator (style);
Console.WriteLine (" / NodeSet: (type {1}) {0} / XsltContext: {2}", currentNodeSet, currentNodeSet.GetType (), xsltContext);
}
void PrintXPathNavigator (XPathNavigator nav)
{
IXmlLineInfo li = nav as IXmlLineInfo;
li = li != null && li.HasLineInfo () ? li : null;
Console.Write ("({0}, {1}) element {2}", li != null ? li.LineNumber : 0, li != null ? li.LinePosition : 0, nav.Name);
}
}
[Obsolete]
public sealed class XslTransform {
internal static readonly bool TemplateStackFrameError;
internal static readonly TextWriter TemplateStackFrameOutput;
static XslTransform ()
{
string env = Environment.GetEnvironmentVariable ("MONO_XSLT_STACK_FRAME");
switch (env) {
case "stdout":
TemplateStackFrameOutput = Console.Out;
break;
case "stderr":
TemplateStackFrameOutput = Console.Error;
break;
case "error":
TemplateStackFrameError = true;
break;
}
}
static object GetDefaultDebugger ()
{
string env = Environment.GetEnvironmentVariable ("MONO_XSLT_DEBUGGER");
if (env == null)
return null;
if (env == "simple")
return new SimpleXsltDebugger ();
object obj = Activator.CreateInstance (Type.GetType (env));
return obj;
}
public XslTransform ()
: this (GetDefaultDebugger ())
{
}
internal XslTransform (object debugger)
{
this.debugger = debugger;
}
object debugger;
CompiledStylesheet s;
XmlResolver xmlResolver = new XmlUrlResolver ();
[MonoTODO] // FIXME: audit security check
public XmlResolver XmlResolver {
set {
xmlResolver = value;
}
}
#region Transform
public XmlReader Transform (IXPathNavigable input, XsltArgumentList args)
{
return Transform (input.CreateNavigator (), args, xmlResolver);
}
public XmlReader Transform (IXPathNavigable input, XsltArgumentList args, XmlResolver resolver)
{
return Transform (input.CreateNavigator (), args, resolver);
}
public XmlReader Transform (XPathNavigator input, XsltArgumentList args)
{
return Transform (input, args, xmlResolver);
}
public XmlReader Transform (XPathNavigator input, XsltArgumentList args, XmlResolver resolver)
{
// todo: is this right?
MemoryStream stream = new MemoryStream ();
Transform (input, args, new XmlTextWriter (stream, null), resolver);
stream.Position = 0;
return new XmlTextReader (stream, XmlNodeType.Element, null);
}
public void Transform (IXPathNavigable input, XsltArgumentList args, TextWriter output)
{
Transform (input.CreateNavigator (), args, output, xmlResolver);
}
public void Transform (IXPathNavigable input, XsltArgumentList args, TextWriter output, XmlResolver resolver)
{
Transform (input.CreateNavigator (), args, output, resolver);
}
public void Transform (IXPathNavigable input, XsltArgumentList args, Stream output)
{
Transform (input.CreateNavigator (), args, output, xmlResolver);
}
public void Transform (IXPathNavigable input, XsltArgumentList args, Stream output, XmlResolver resolver)
{
Transform (input.CreateNavigator (), args, output, resolver);
}
public void Transform (IXPathNavigable input, XsltArgumentList args, XmlWriter output)
{
Transform (input.CreateNavigator (), args, output, xmlResolver);
}
public void Transform (IXPathNavigable input, XsltArgumentList args, XmlWriter output, XmlResolver resolver)
{
Transform (input.CreateNavigator (), args, output, resolver);
}
public void Transform (XPathNavigator input, XsltArgumentList args, XmlWriter output)
{
Transform (input, args, output, xmlResolver);
}
public void Transform (XPathNavigator input, XsltArgumentList args, XmlWriter output, XmlResolver resolver)
{
if (s == null)
throw new XsltException ("No stylesheet was loaded.", null);
Outputter outputter = new GenericOutputter (output, s.Outputs, null);
new XslTransformProcessor (s, debugger).Process (input, outputter, args, resolver);
output.Flush ();
}
public void Transform (XPathNavigator input, XsltArgumentList args, Stream output)
{
Transform (input, args, output, xmlResolver);
}
public void Transform (XPathNavigator input, XsltArgumentList args, Stream output, XmlResolver resolver)
{
XslOutput xslOutput = (XslOutput)s.Outputs[String.Empty];
Transform (input, args, new StreamWriter (output, xslOutput.Encoding), resolver);
}
public void Transform (XPathNavigator input, XsltArgumentList args, TextWriter output)
{
Transform (input, args, output, xmlResolver);
}
public void Transform (XPathNavigator input, XsltArgumentList args, TextWriter output, XmlResolver resolver)
{
if (s == null)
throw new XsltException ("No stylesheet was loaded.", null);
Outputter outputter = new GenericOutputter(output, s.Outputs, output.Encoding);
new XslTransformProcessor (s, debugger).Process (input, outputter, args, resolver);
outputter.Done ();
output.Flush ();
}
public void Transform (string inputfile, string outputfile)
{
Transform (inputfile, outputfile, xmlResolver);
}
public void Transform (string inputfile, string outputfile, XmlResolver resolver)
{
using (Stream s = new FileStream (outputfile, FileMode.Create, FileAccess.ReadWrite)) {
Transform(new XPathDocument (inputfile).CreateNavigator (), null, s, resolver);
}
}
#endregion
#region Load
public void Load (string url)
{
Load (url, null);
}
public void Load (string url, XmlResolver resolver)
{
XmlResolver res = resolver;
if (res == null)
res = new XmlUrlResolver ();
Uri uri = res.ResolveUri (null, url);
using (Stream s = res.GetEntity (uri, null, typeof (Stream)) as Stream) {
XmlTextReader xtr = new XmlTextReader (uri.ToString (), s);
xtr.XmlResolver = res;
XmlValidatingReader xvr = new XmlValidatingReader (xtr);
xvr.XmlResolver = res;
xvr.ValidationType = ValidationType.None;
Load (new XPathDocument (xvr, XmlSpace.Preserve).CreateNavigator (), resolver, null);
}
}
public void Load (XmlReader stylesheet)
{
Load (stylesheet, null, null);
}
public void Load (XmlReader stylesheet, XmlResolver resolver)
{
Load (stylesheet, resolver, null);
}
public void Load (XPathNavigator stylesheet)
{
Load (stylesheet, null, null);
}
public void Load (XPathNavigator stylesheet, XmlResolver resolver)
{
Load (stylesheet, resolver, null);
}
public void Load (IXPathNavigable stylesheet)
{
Load (stylesheet.CreateNavigator(), null);
}
public void Load (IXPathNavigable stylesheet, XmlResolver resolver)
{
Load (stylesheet.CreateNavigator(), resolver);
}
// Introduced in .NET 1.1
public void Load (IXPathNavigable stylesheet, XmlResolver resolver, Evidence evidence)
{
Load (stylesheet.CreateNavigator(), resolver, evidence);
}
public void Load (XPathNavigator stylesheet, XmlResolver resolver, Evidence evidence)
{
s = new Compiler (debugger).Compile (stylesheet, resolver, evidence);
}
public void Load (XmlReader stylesheet, XmlResolver resolver, Evidence evidence)
{
Load (new XPathDocument (stylesheet, XmlSpace.Preserve).CreateNavigator (), resolver, evidence);
}
#endregion
}
}
| |
#if ANDROID || WINDOWS_8 || IOS
#define USES_DOT_SLASH_ABOLUTE_FILES
#endif
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using FileManager = FlatRedBall.IO.FileManager;
using FlatRedBall.Graphics;
using FlatRedBall.Graphics.Texture;
using FlatRedBall.Graphics.Particle;
using FlatRedBall.Content.Particle;
using FlatRedBall.AI.Pathfinding;
using FlatRedBall.Content.AI.Pathfinding;
using FlatRedBall.Math.Geometry;
using FlatRedBall.Content.Math.Geometry;
using FlatRedBall.Math;
using FlatRedBall.Content.Polygon;
using FlatRedBall.Graphics.Animation;
using FlatRedBall.Content.AnimationChain;
using FlatRedBall.Gui;
using FlatRedBall.Content.Saves;
using FlatRedBall.Math.Splines;
using FlatRedBall.Content.Math.Splines;
using System.Threading;
using Microsoft.Xna.Framework.Media;
#if MONOGAME
using Microsoft.Xna.Framework.Audio;
#endif
#if !MONOGAME
using Image = System.Drawing.Image;
using FlatRedBall.IO.Gif;
using FlatRedBall.IO; // For Image
#endif
using FlatRedBall.IO.Csv;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using System.IO;
using Color = Microsoft.Xna.Framework.Color;
using FlatRedBall.Content.ContentLoaders;
using FlatRedBall.Performance.Measurement;
using FlatRedBall.IO;
namespace FlatRedBall.Content
{
//public delegate void UnloadMethod();
public partial class ContentManager : Microsoft.Xna.Framework.Content.ContentManager
{
#region Fields
TextureContentLoader textureContentLoader = new TextureContentLoader();
//internal Dictionary<string, Type> mAssetTypeAssociation;
internal Dictionary<string, object> mAssets;
internal Dictionary<string, IDisposable> mDisposableDictionary = new Dictionary<string, IDisposable>();
Dictionary<string, object> mNonDisposableDictionary = new Dictionary<string, object>();
Dictionary<string, Action> mUnloadMethods = new Dictionary<string, Action>();
/// <summary>
/// If true FlatRedBall will look for cached content in the Global content manager even if
/// the ContentManager passed to the Load function is not Global. This defaults to true.
/// </summary>
public static bool LoadFromGlobalIfExists = true;
public static Dictionary<FilePath, FilePath> FileAliases { get; private set; } = new Dictionary<FilePath, FilePath>();
#if FRB_XNA && !MONOGAME
internal Effect mFirstEffect = null;
internal EffectCache mFirstEffectCache = null;
#endif
#if PROFILE
static List<ContentLoadHistory> mHistory = new List<ContentLoadHistory>();
#endif
string mName;
#endregion
#region Default Content
public static Texture2D GetDefaultFontTexture(GraphicsDevice graphicsDevice)
{
#if ANDROID
var activity = FlatRedBallServices.Game.Services.GetService<Android.App.Activity>();
if(activity == null)
{
string message =
"As of July 2017, FlatRedBall Android performs a much faster loading of the default font. This requires a change to the Activity1.cs file. You can look at a brand-new Android template to see the required changes.";
throw new NullReferenceException(message);
}
Android.Content.Res.AssetManager androidAssetManager = activity.Assets;
Texture2D texture;
try
{
using (var stream = androidAssetManager.Open("content/defaultfonttexture.png"))
{
texture = Texture2D.FromStream(graphicsDevice, stream);
}
}
catch
{
throw new Exception("The file defaultfonttexture.png in the game's content folder is missing. If you are missing this file, look at the default Android template to see where it should be added (in Assets/content/)");
}
#else
var colors = DefaultFontDataColors.GetColorArray();
Texture2D texture = new Texture2D(graphicsDevice, 256, 128);
texture.SetData<Microsoft.Xna.Framework.Color>(colors);
#endif
return texture;
}
#endregion
#region Properties
public IEnumerable<IDisposable> DisposableObjects
{
get
{
return mDisposableDictionary.Values;
}
}
public List<ManualResetEvent> ManualResetEventList
{
get;
private set;
}
public bool IsWaitingOnAsyncLoadsToFinish
{
get
{
foreach (ManualResetEvent mre in ManualResetEventList)
{
if (mre.WaitOne(0) == false)
{
return true;
}
}
return false;
}
}
public string Name
{
get { return mName; }
}
#if PROFILE
public static List<ContentLoadHistory> LoadingHistory
{
get { return mHistory; }
}
#endif
#if DEBUG
public static bool ThrowExceptionOnGlobalContentLoadedInNonGlobal
{
get;
set;
}
#endif
#endregion
#region Methods
#region Constructors
public ContentManager(string name, IServiceProvider serviceProvider)
: base(serviceProvider)
{
mName = name;
// mAssetTypeAssociation = new Dictionary<string, Type>();
mAssets = new Dictionary<string, object>();
ManualResetEventList = new List<ManualResetEvent>();
}
public ContentManager(string name, IServiceProvider serviceProvider, string rootDictionary)
: base(serviceProvider, rootDictionary)
{
mName = name;
// mAssetTypeAssociation = new Dictionary<string, Type>();
mAssets = new Dictionary<string, object>();
ManualResetEventList = new List<ManualResetEvent>();
}
#endregion
#region Public Methods
/// <summary>
/// Adds the argument disposable object to the content manager, to be disposed when the ContentManager Unload method is eventually called.
/// </summary>
/// <remarks>
/// This method is used for objects which either need to be cached and obtained later (such as custom from-file content) or which
/// is not usually referenced by its key but which does noeed to be disposed later (such as a RenderTarget2D).
/// </remarks>
/// <param name="disposableName">The name of the disposable, so that it can be retrieved later if needed.</param>
/// <param name="disposable">The disposable object to be added for disposal upon Unload.</param>
public void AddDisposable(string disposableName, IDisposable disposable)
{
if (FileManager.IsRelative(disposableName))
{
disposableName = FileManager.MakeAbsolute(disposableName);
}
disposableName = FileManager.Standardize(disposableName);
string modifiedName = disposableName + disposable.GetType().Name;
lock (mDisposableDictionary)
{
mDisposableDictionary.Add(modifiedName, disposable);
}
}
public void AddNonDisposable(string objectName, object objectToAdd)
{
if (FileManager.IsRelative(objectName))
{
objectName = FileManager.MakeAbsolute(objectName);
}
string modifiedName = objectName + objectToAdd.GetType().Name;
bool shouldAdd = true;
if(mNonDisposableDictionary.ContainsKey(modifiedName))
{
var existing = objectToAdd;
if(existing != objectToAdd)
{
throw new InvalidOperationException($"The name {objectName} is already taken by {objectToAdd}");
}
else
{
shouldAdd = false;
}
}
if(shouldAdd)
{
mNonDisposableDictionary.Add(modifiedName, objectToAdd);
}
}
public void AddUnloadMethod(string uniqueID, Action unloadMethod)
{
if (!mUnloadMethods.ContainsKey(uniqueID))
{
mUnloadMethods.Add(uniqueID, unloadMethod);
}
}
public T GetDisposable<T>(string objectName)
{
if (FileManager.IsRelative(objectName))
{
objectName = FileManager.MakeAbsolute(objectName);
}
objectName += typeof(T).Name;
return (T)mDisposableDictionary[objectName];
}
// This used to be internal - making it public since users use this
public T GetNonDisposable<T>(string objectName)
{
if (FileManager.IsRelative(objectName))
{
objectName = FileManager.MakeAbsolute(objectName);
}
objectName += typeof(T).Name;
return (T)mNonDisposableDictionary[objectName];
}
public bool IsAssetLoadedByName<T>(string assetName)
{
if (FileManager.IsRelative(assetName))
{
assetName = FileManager.MakeAbsolute(assetName);
}
assetName = FileManager.Standardize(assetName);
string combinedName = assetName + typeof(T).Name;
if (mDisposableDictionary.ContainsKey(combinedName))
{
return true;
}
else if (mNonDisposableDictionary.ContainsKey(combinedName))
{
return true;
}
else if (mAssets.ContainsKey(combinedName))
{
return true;
}
else
{
return false;
}
}
public bool IsAssetLoadedByReference(object objectToCheck)
{
return mDisposableDictionary.ContainsValue(objectToCheck as IDisposable) ||
mNonDisposableDictionary.ContainsValue(objectToCheck) ||
mAssets.ContainsValue(objectToCheck);
}
// Ok, let's explain why this method uses the "new" keyword.
// In the olden days (before September 2009) the user would call
// FlatRedBallServices.Load<TypeToLoad> which would investigate whether
// the user passed an assetName that had an extension or not. Then the
// FlatRedBallServices class would call LoadFromFile or LoadFromProject
// depending on the presence of an extension.
//
// In an effort to reduce the responsibilities of the FlatRedBallServices
// class, Vic decided to move the loading code (including the logic that branches
// depending on whether an asset has an extension) into the ContentManager class.
// To keep things simple, the FlatRedBallServices just has to call Load and the Load
// method will do the branching inside the ContentManager class. That all worked well,
// except that the branching code also "standardizes" the name, which means it turns relative
// paths into absolute paths. The reason this is a problem is IF the user loads an object (such
// as a .X file) which references another file, then the Load method will be called again on the referenced
// asset name.
//
// The FRB ContentManager doesn't use relative directories - instead, it makes all assets relative to the .exe
// by calling Standardize. However, if Load is called by XNA code (such as when loading a .X file)
// then any files referenced by the X will come in already made relative to the ContentManager.
// This means that if a .X file was "Content\myModel" and it referenced myTexture.png which was in the same
// folder as the .X file, then Load would get called with "Content\myTexture" as the argument. That is, the .X loading
// code would already prepend "Content\" before "myTexture. But the FRB content manager wouldn't know this, and it'd
// try to standardize it as well, making the file "Content\Content\myTexture."
//
// So the solution? We make Load a "new" method. That means that if Load is called by XNA, then it'll call the
// Load of XNA's ContentManager. But if FRB calls it, it'll call the "new" version. Problem solved.
public new T Load<T>(string assetName)
{
var standardized = FileManager.Standardize(assetName);
if(FileAliases.ContainsKey(standardized))
{
assetName = FileAliases[standardized].FullPath;
}
// Assets can be loaded either from file or from assets referenced
// in the project.
string extension = FileManager.GetExtension(assetName);
#region If there is an extension, loading from file or returning an already-loaded asset
assetName = FileManager.Standardize(assetName);
if (extension != String.Empty)
{
return LoadFromFile<T>(assetName);
}
#endregion
#region Else there is no extension, so the file is already part of the project. Use a ContentManager
else
{
#if PROFILE
bool exists = false;
exists = IsAssetLoadedByName<T>(assetName);
if (exists)
{
mHistory.Add(new ContentLoadHistory(
TimeManager.CurrentTime, typeof(T).Name, assetName, ContentLoadDetail.Cached));
}
else
{
mHistory.Add(new ContentLoadHistory(
TimeManager.CurrentTime, typeof(T).Name, assetName, ContentLoadDetail.HddFromContentPipeline));
}
#endif
return LoadFromProject<T>(assetName);
}
#endregion
}
public T LoadFromProject<T>(string assetName)
{
string oldRelativePath = FileManager.RelativeDirectory;
FlatRedBall.IO.FileManager.RelativeDirectory = FileManager.GetDirectory(assetName);
#if DEBUG
bool shouldCheckForXnb = true;
string fileToCheckFor = assetName + ".xnb";
if (shouldCheckForXnb && !FileManager.FileExists(fileToCheckFor))
{
string errorString = "Could not find the file " + fileToCheckFor + "\n";
throw new FileNotFoundException(errorString);
}
#endif
#if !MONOGAME
if (!FileManager.IsRelative(assetName))
{
assetName = FileManager.MakeRelative(
assetName, System.Windows.Forms.Application.StartupPath + "/");
}
#endif
#if USES_DOT_SLASH_ABOLUTE_FILES
T asset;
if (assetName.StartsWith(@".\") || assetName.StartsWith(@"./"))
{
asset = base.Load<T>(assetName.Substring(2));
}
else
{
asset = base.Load<T>(assetName);
}
#else
T asset = base.Load<T>(assetName);
#endif
if (!mAssets.ContainsKey(assetName))
{
mAssets.Add(assetName, asset);
}
FileManager.RelativeDirectory = oldRelativePath;
return AdjustNewAsset(asset, assetName);
}
public T LoadFromFile<T>(string assetName)
{
string extension = FileManager.GetExtension(assetName);
if (FileManager.IsRelative(assetName))
{
// get the absolute path using the current relative directory
assetName = FileManager.RelativeDirectory + assetName;
}
string fullNameWithType = assetName + typeof(T).Name;
// get the dictionary by the contentManagerName. If it doesn't exist, GetDisposableDictionaryByName
// will create it.
if (mDisposableDictionary.ContainsKey(fullNameWithType))
{
#if PROFILE
mHistory.Add(new ContentLoadHistory(
TimeManager.CurrentTime, typeof(T).Name, fullNameWithType, ContentLoadDetail.Cached));
#endif
return ((T)mDisposableDictionary[fullNameWithType]);
}
else if (mNonDisposableDictionary.ContainsKey(fullNameWithType))
{
return ((T)mNonDisposableDictionary[fullNameWithType]);
}
else
{
#if PROFILE
mHistory.Add(new ContentLoadHistory(
TimeManager.CurrentTime,
typeof(T).Name,
fullNameWithType,
ContentLoadDetail.HddFromFile));
#endif
#if DEBUG
// The ThrowExceptionIfFileDoesntExist
// call used to be done before the checks
// in the dictionaries. But whatever is held
// in there may not really be a file so let's check
// if the file exists after we check the dictionaries.
FileManager.ThrowExceptionIfFileDoesntExist(assetName);
#endif
IDisposable loadedAsset = null;
if (typeof(T) == typeof(Texture2D) || typeof(T) == typeof(Microsoft.Xna.Framework.Graphics.Texture2D))
{
// for now we'll create it here, eventually have it in a dictionary:
loadedAsset = textureContentLoader.Load(assetName);
}
#region Scene
else if (typeof(T) == typeof(FlatRedBall.Scene))
{
FlatRedBall.Scene scene = FlatRedBall.Content.Scene.SceneSave.FromFile(assetName).ToScene(mName);
object sceneAsObject = scene;
lock (mNonDisposableDictionary)
{
if (!mNonDisposableDictionary.ContainsKey(fullNameWithType))
{
mNonDisposableDictionary.Add(fullNameWithType, scene);
}
}
return (T)sceneAsObject;
}
#endregion
#region EmitterList
else if (typeof(T) == typeof(EmitterList))
{
EmitterList emitterList = EmitterSaveList.FromFile(assetName).ToEmitterList(mName);
mNonDisposableDictionary.Add(fullNameWithType, emitterList);
return (T)((object)emitterList);
}
#endregion
#region Image
#if !MONOGAME
else if (typeof(T) == typeof(Image))
{
switch (extension.ToLowerInvariant())
{
case "gif":
Image image = Image.FromFile(assetName);
loadedAsset = image;
break;
}
}
#endif
#endregion
#region BitmapList
#if !XBOX360 && !SILVERLIGHT && !WINDOWS_PHONE && !MONOGAME
else if (typeof(T) == typeof(BitmapList))
{
loadedAsset = BitmapList.FromFile(assetName);
}
#endif
#endregion
#region NodeNetwork
else if (typeof(T) == typeof(NodeNetwork))
{
NodeNetwork nodeNetwork = NodeNetworkSave.FromFile(assetName).ToNodeNetwork();
mNonDisposableDictionary.Add(fullNameWithType, nodeNetwork);
return (T)((object)nodeNetwork);
}
#endregion
#region ShapeCollection
else if (typeof(T) == typeof(ShapeCollection))
{
ShapeCollection shapeCollection =
ShapeCollectionSave.FromFile(assetName).ToShapeCollection();
mNonDisposableDictionary.Add(fullNameWithType, shapeCollection);
return (T)((object)shapeCollection);
}
#endregion
#region PositionedObjectList<Polygon>
else if (typeof(T) == typeof(PositionedObjectList<FlatRedBall.Math.Geometry.Polygon>))
{
PositionedObjectList<FlatRedBall.Math.Geometry.Polygon> polygons =
PolygonSaveList.FromFile(assetName).ToPolygonList();
mNonDisposableDictionary.Add(fullNameWithType, polygons);
return (T)((object)polygons);
}
#endregion
#region AnimationChainList
else if (typeof(T) == typeof(AnimationChainList))
{
if (assetName.EndsWith("gif"))
{
#if WINDOWS_8 || UWP || DESKTOP_GL || STANDARD
throw new NotImplementedException();
#else
AnimationChainList acl = new AnimationChainList();
acl.Add(FlatRedBall.Graphics.Animation.AnimationChain.FromGif(assetName, this.mName));
acl[0].ParentGifFileName = assetName;
loadedAsset = acl;
#endif
}
else
{
loadedAsset =
AnimationChainListSave.FromFile(assetName).ToAnimationChainList(mName);
}
mNonDisposableDictionary.Add(fullNameWithType, loadedAsset);
}
#endregion
else if(typeof(T) == typeof(Song))
{
var loader = new SongLoader();
return (T)(object) loader.Load(assetName);
}
#if MONOGAME
else if (typeof(T) == typeof(SoundEffect))
{
T soundEffect;
if (assetName.StartsWith(@".\") || assetName.StartsWith(@"./"))
{
soundEffect = base.Load<T>(assetName.Substring(2));
}
else
{
soundEffect = base.Load<T>(assetName);
}
return soundEffect;
}
#endif
#region RuntimeCsvRepresentation
#if !SILVERLIGHT
else if (typeof(T) == typeof(RuntimeCsvRepresentation))
{
#if XBOX360
throw new NotImplementedException("Can't load CSV from file. Try instead to use the content pipeline.");
#else
return (T)((object)CsvFileManager.CsvDeserializeToRuntime(assetName));
#endif
}
#endif
#endregion
#region SplineList
else if (typeof(T) == typeof(List<Spline>))
{
List<Spline> splineList = SplineSaveList.FromFile(assetName).ToSplineList();
mNonDisposableDictionary.Add(fullNameWithType, splineList);
object asObject = splineList;
return (T)asObject;
}
else if (typeof(T) == typeof(SplineList))
{
SplineList splineList = SplineSaveList.FromFile(assetName).ToSplineList();
mNonDisposableDictionary.Add(fullNameWithType, splineList);
object asObject = splineList;
return (T)asObject;
}
#endregion
#region BitmapFont
else if (typeof(T) == typeof(BitmapFont))
{
// We used to assume the texture is named the same as the font file
// But now FRB understands the .fnt file and gets the PNG from the font file
//string pngFile = FileManager.RemoveExtension(assetName) + ".png";
string fntFile = FileManager.RemoveExtension(assetName) + ".fnt";
BitmapFont bitmapFont = new BitmapFont(fntFile, this.mName);
object bitmapFontAsObject = bitmapFont;
return (T)bitmapFontAsObject;
}
#endregion
#region Text
else if (typeof(T) == typeof(string))
{
return (T)((object)FileManager.FromFileText(assetName));
}
#endregion
#region Catch mistakes
#if DEBUG
else if (typeof(T) == typeof(Spline))
{
throw new Exception("Cannot load Splines. Try using the List<Spline> type instead.");
}
else if (typeof(T) == typeof(Emitter))
{
throw new Exception("Cannot load Emitters. Try using the EmitterList type instead.");
}
#endif
#endregion
#region else, exception!
else
{
throw new NotImplementedException("Cannot load content of type " +
typeof(T).AssemblyQualifiedName + " from file. If you are loading " +
"through the content pipeline be sure to remove the extension of the file " +
"name.");
}
#endregion
if (loadedAsset != null)
{
lock (mDisposableDictionary)
{
// Multiple threads could try to load this content simultaneously
if (!mDisposableDictionary.ContainsKey(fullNameWithType))
{
mDisposableDictionary.Add(fullNameWithType, loadedAsset);
}
}
}
return ((T)loadedAsset);
}
}
/// <summary>
/// Removes an IDisposable from the ContentManager. This method does not call Dispose on the argument Disposable. It
/// must be disposed
/// </summary>
/// <param name="disposable">The IDisposable to be removed</param>
public void RemoveDisposable(IDisposable disposable)
{
KeyValuePair<string, IDisposable>? found = null;
foreach(var kvp in mDisposableDictionary)
{
if(kvp.Value == disposable)
{
found = kvp;
break;
}
}
if(found != null)
{
mDisposableDictionary.Remove(found.Value.Key);
}
}
public void UnloadAsset<T>(T assetToUnload)
{
#region Remove from non-disposables if the non-disposables containes the assetToUnload
if (this.mNonDisposableDictionary.ContainsValue(assetToUnload))
{
string assetName = "";
foreach (KeyValuePair<string, object> kvp in mNonDisposableDictionary)
{
if (kvp.Value == assetToUnload as object)
{
assetName = kvp.Key;
break;
}
}
mNonDisposableDictionary.Remove(assetName);
}
#endregion
#region If it's an IDisposable, then remove it from the disposable dictionary
if (assetToUnload is IDisposable)
{
IDisposable asDisposable = assetToUnload as IDisposable;
if (this.mDisposableDictionary.ContainsValue(asDisposable))
{
asDisposable.Dispose();
string assetName = "";
foreach (KeyValuePair<string, IDisposable> kvp in mDisposableDictionary)
{
if (kvp.Value == ((IDisposable)assetToUnload))
{
assetName = kvp.Key;
break;
}
}
mDisposableDictionary.Remove(assetName);
}
else
{
throw new ArgumentException("The content manager " + mName + " does not contain the argument " +
"assetToUnload, of the file has been loaded from XNB and cannot be unloaded without disposing the content manager. Check the " +
"contentManagerName and verify that it is a contentManager that has loaded this asset. Assets which have been " +
"loaded from the project must be loaded by unloading an entire Content Manager");
}
}
#endregion
}
public new void Unload()
{
if (IsWaitingOnAsyncLoadsToFinish)
{
FlatRedBallServices.MoveContentManagerToWaitingToUnloadList(this);
}
else
{
base.Unload();
this.mAssets.Clear();
this.mNonDisposableDictionary.Clear();
foreach (KeyValuePair<string, IDisposable> kvp in mDisposableDictionary)
{
kvp.Value.Dispose();
}
foreach (Action unloadMethod in mUnloadMethods.Values)
{
unloadMethod();
}
mUnloadMethods.Clear();
mDisposableDictionary.Clear();
}
}
#if PROFILE
public static void RecordEvent(string eventName)
{
ContentLoadHistory history = new ContentLoadHistory();
history.SpecialEvent = eventName;
mHistory.Add(history);
}
public static void SaveContentLoadingHistory(string fileToSaveTo)
{
StringBuilder stringBuilder = new StringBuilder();
foreach (ContentLoadHistory clh in mHistory)
{
if (!string.IsNullOrEmpty(clh.SpecialEvent))
{
stringBuilder.AppendLine("========================================");
stringBuilder.AppendLine(clh.SpecialEvent);
stringBuilder.AppendLine("========================================");
stringBuilder.AppendLine();
}
else
{
stringBuilder.AppendLine("Time:\t\t" + clh.Time);
stringBuilder.AppendLine("Content Type:\t" + clh.Type);
stringBuilder.AppendLine("Content Name:\t" + clh.ContentName);
stringBuilder.AppendLine("Detail:\t\t" + clh.ContentLoadDetail);
stringBuilder.AppendLine();
}
}
FileManager.SaveText(stringBuilder.ToString(), fileToSaveTo);
}
#endif
#endregion
#region Internal Methods
// Vic says: I don't think we need this anymore
internal void RefreshTextureOnDeviceLost()
{
//List<string> texturesToReload = new List<string>();
//foreach(KeyValuePair<string, IDisposable> kvp in mDisposableDictionary)
//{
// if (kvp.Value is Texture2D)
// {
// texturesToReload.Add(kvp.Key);
// kvp.Value.Dispose();
// contentManagers.Add(kvp.Key);
// fileNames.Add(subKvp.Key);
// }
//}
//kvp.Value.Clear();
}
#endregion
#region Private Methods
private T AdjustNewAsset<T>(T asset, string assetName)
{
if (asset is Microsoft.Xna.Framework.Graphics.Texture)
{
(asset as Microsoft.Xna.Framework.Graphics.Texture).Name = assetName;
}
if (asset is FlatRedBall.Scene)
{
return (T)(object)((asset as FlatRedBall.Scene).Clone());
}
else if (asset is FlatRedBall.Graphics.Particle.EmitterList)
{
return (T)(object)(asset as FlatRedBall.Graphics.Particle.EmitterList).Clone();
}
else
{
return asset;
}
}
#endregion
#endregion
}
}
| |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using System;
using System.Globalization;
using System.Linq;
using System.Management.Automation;
using Microsoft.WindowsAzure.Commands.Common;
using Microsoft.WindowsAzure.Commands.SqlDatabase.Properties;
using Microsoft.WindowsAzure.Commands.SqlDatabase.Services.Common;
using Microsoft.WindowsAzure.Commands.SqlDatabase.Services.Server;
using Microsoft.WindowsAzure.Commands.Utilities.Common;
namespace Microsoft.WindowsAzure.Commands.SqlDatabase.Database.Cmdlet
{
using DatabaseCopyModel = Model.DatabaseCopy;
using Microsoft.Azure.Common.Authentication;
/// <summary>
/// Stop an ongoing copy operation for a Microsoft Azure SQL Database in the given server context.
/// </summary>
[Cmdlet(VerbsLifecycle.Stop, "AzureSqlDatabaseCopy", SupportsShouldProcess = true,
ConfirmImpact = ConfirmImpact.Medium)]
public class StopAzureSqlDatabaseCopy : AzureSMCmdlet
{
#region ParameterSetNames
internal const string ByInputObject = "ByInputObject";
internal const string ByDatabase = "ByDatabase";
internal const string ByDatabaseName = "ByDatabaseName";
#endregion
#region Parameters
/// <summary>
/// Gets or sets the name of the server upon which to operate
/// </summary>
[Parameter(Mandatory = true, Position = 0, ValueFromPipeline = true,
ValueFromPipelineByPropertyName = true,
HelpMessage = "The name of the server to operate on.")]
[ValidateNotNullOrEmpty]
public string ServerName { get; set; }
/// <summary>
/// Gets or sets the sql database copy object.
/// </summary>
[Parameter(Mandatory = true, Position = 1, ParameterSetName = ByInputObject,
ValueFromPipeline = true, HelpMessage = "The database copy operation to stop.")]
[ValidateNotNull]
public DatabaseCopyModel DatabaseCopy { get; set; }
/// <summary>
/// Gets or sets the database object to refresh.
/// </summary>
[Parameter(Mandatory = true, Position = 1, ParameterSetName = ByDatabase,
ValueFromPipeline = true, HelpMessage = "The database object to stop a copy from or to.")]
[ValidateNotNull]
public Services.Server.Database Database { get; set; }
/// <summary>
/// Gets or sets the name of the database to retrieve.
/// </summary>
[Parameter(Mandatory = true, Position = 1, ParameterSetName = ByDatabaseName,
HelpMessage = "The name of the database to stop copy.")]
[ValidateNotNullOrEmpty]
public string DatabaseName { get; set; }
/// <summary>
/// Gets or sets the name of the partner server.
/// </summary>
[Parameter(Mandatory = false, ParameterSetName = ByDatabase,
HelpMessage = "The name of the partner server")]
[Parameter(Mandatory = false, ParameterSetName = ByDatabaseName,
HelpMessage = "The name of the partner server")]
[ValidateNotNullOrEmpty]
public string PartnerServer { get; set; }
/// <summary>
/// Gets or sets the name of the partner database.
/// </summary>
[Parameter(Mandatory = false, ParameterSetName = ByDatabase,
HelpMessage = "The name of the partner database")]
[Parameter(Mandatory = false, ParameterSetName = ByDatabaseName,
HelpMessage = "The name of the partner database")]
[ValidateNotNullOrEmpty]
public string PartnerDatabase { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to forcefully terminate the copy.
/// </summary>
[Parameter(HelpMessage = "Forcefully terminate the copy operation.")]
public SwitchParameter ForcedTermination { get; set; }
/// <summary>
/// Gets or sets the switch to not confirm on the termination of the database copy.
/// </summary>
[Parameter(HelpMessage = "Do not confirm on the termination of the database copy")]
public SwitchParameter Force { get; set; }
#endregion
/// <summary>
/// Execute the command.
/// </summary>
public override void ExecuteCmdlet()
{
// Obtain the database name from the given parameters.
string databaseName = null;
if (this.MyInvocation.BoundParameters.ContainsKey("Database"))
{
databaseName = this.Database.Name;
}
else if (this.MyInvocation.BoundParameters.ContainsKey("DatabaseName"))
{
databaseName = this.DatabaseName;
}
// Use the provided ServerDataServiceContext or create one from the
// provided ServerName and the active subscription.
IServerDataServiceContext context = ServerDataServiceCertAuth.Create(this.ServerName,
Profile,
Profile.Context.Subscription);
DatabaseCopyModel databaseCopy;
if (this.MyInvocation.BoundParameters.ContainsKey("DatabaseCopy"))
{
// Refreshes the given copy object
databaseCopy = context.GetDatabaseCopy(this.DatabaseCopy);
}
else
{
// Retrieve all database copy object with matching parameters
DatabaseCopyModel[] copies = context.GetDatabaseCopy(
databaseName,
this.PartnerServer,
this.PartnerDatabase);
if (copies.Length == 0)
{
throw new ApplicationException(Resources.DatabaseCopyNotFoundGeneric);
}
else if (copies.Length > 1)
{
throw new ApplicationException(Resources.MoreThanOneDatabaseCopyFound);
}
databaseCopy = copies.Single();
}
// Do nothing if force is not specified and user cancelled the operation
string actionDescription = string.Format(
CultureInfo.InvariantCulture,
Resources.StopAzureSqlDatabaseCopyDescription,
databaseCopy.SourceServerName,
databaseCopy.SourceDatabaseName,
databaseCopy.DestinationServerName,
databaseCopy.DestinationDatabaseName);
string actionWarning = string.Format(
CultureInfo.InvariantCulture,
Resources.StopAzureSqlDatabaseCopyWarning,
databaseCopy.SourceServerName,
databaseCopy.SourceDatabaseName,
databaseCopy.DestinationServerName,
databaseCopy.DestinationDatabaseName);
this.WriteVerbose(actionDescription);
if (!this.Force.IsPresent &&
!this.ShouldProcess(
actionDescription,
actionWarning,
Resources.ShouldProcessCaption))
{
return;
}
try
{
// Stop the specified database copy
context.StopDatabaseCopy(
databaseCopy,
this.ForcedTermination.IsPresent);
}
catch (Exception ex)
{
SqlDatabaseExceptionHandler.WriteErrorDetails(
this,
context.ClientRequestId,
ex);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using Xunit;
namespace System.Tests
{
// TODO: Remove these extension methods when the actual methods are available on String in System.Runtime.dll
internal static class TemporaryStringSplitExtensions
{
public static string[] Split(this string value, char separator)
{
return value.Split(new[] { separator });
}
public static string[] Split(this string value, char separator, StringSplitOptions options)
{
return value.Split(new[] { separator }, options);
}
public static string[] Split(this string value, char separator, int count, StringSplitOptions options)
{
return value.Split(new[] { separator }, count, options);
}
public static string[] Split(this string value, string separator)
{
return value.Split(new[] { separator }, StringSplitOptions.None);
}
public static string[] Split(this string value, string separator, StringSplitOptions options)
{
return value.Split(new[] { separator }, options);
}
public static string[] Split(this string value, string separator, int count, StringSplitOptions options)
{
return value.Split(new[] { separator }, count, options);
}
}
public static class StringSplitTests
{
[Fact]
public static void SplitInvalidCount()
{
const string value = "a,b";
const int count = -1;
const StringSplitOptions options = StringSplitOptions.None;
Assert.Throws<ArgumentOutOfRangeException>(() => value.Split(',', count, options));
Assert.Throws<ArgumentOutOfRangeException>(() => value.Split(new[] { ',' }, count));
Assert.Throws<ArgumentOutOfRangeException>(() => value.Split(new[] { ',' }, count, options));
Assert.Throws<ArgumentOutOfRangeException>(() => value.Split(",", count, options));
Assert.Throws<ArgumentOutOfRangeException>(() => value.Split(new[] { "," }, count, options));
}
[Fact]
public static void SplitInvalidOptions()
{
const string value = "a,b";
const int count = int.MaxValue;
const StringSplitOptions optionsTooLow = StringSplitOptions.None - 1;
const StringSplitOptions optionsTooHigh = StringSplitOptions.RemoveEmptyEntries + 1;
Assert.Throws<ArgumentException>(() => value.Split(',', optionsTooLow));
Assert.Throws<ArgumentException>(() => value.Split(',', optionsTooHigh));
Assert.Throws<ArgumentException>(() => value.Split(',', count, optionsTooLow));
Assert.Throws<ArgumentException>(() => value.Split(',', count, optionsTooHigh));
Assert.Throws<ArgumentException>(() => value.Split(new[] { ',' }, optionsTooLow));
Assert.Throws<ArgumentException>(() => value.Split(new[] { ',' }, optionsTooHigh));
Assert.Throws<ArgumentException>(() => value.Split(new[] { ',' }, count, optionsTooLow));
Assert.Throws<ArgumentException>(() => value.Split(new[] { ',' }, count, optionsTooHigh));
Assert.Throws<ArgumentException>(() => value.Split(",", optionsTooLow));
Assert.Throws<ArgumentException>(() => value.Split(",", optionsTooHigh));
Assert.Throws<ArgumentException>(() => value.Split(",", count, optionsTooLow));
Assert.Throws<ArgumentException>(() => value.Split(",", count, optionsTooHigh));
Assert.Throws<ArgumentException>(() => value.Split(new[] { "," }, optionsTooLow));
Assert.Throws<ArgumentException>(() => value.Split(new[] { "," }, optionsTooHigh));
Assert.Throws<ArgumentException>(() => value.Split(new[] { "," }, count, optionsTooLow));
Assert.Throws<ArgumentException>(() => value.Split(new[] { "," }, count, optionsTooHigh));
}
[Fact]
public static void SplitZeroCountEmptyResult()
{
const string value = "a,b";
const int count = 0;
const StringSplitOptions options = StringSplitOptions.None;
string[] expected = new string[0];
Assert.Equal(expected, value.Split(',', count, options));
Assert.Equal(expected, value.Split(new[] { ',' }, count));
Assert.Equal(expected, value.Split(new[] { ',' }, count, options));
Assert.Equal(expected, value.Split(",", count, options));
Assert.Equal(expected, value.Split(new[] { "," }, count, options));
}
[Fact]
public static void SplitEmptyValueWithRemoveEmptyEntriesOptionEmptyResult()
{
string value = string.Empty;
const int count = int.MaxValue;
const StringSplitOptions options = StringSplitOptions.RemoveEmptyEntries;
string[] expected = new string[0];
Assert.Equal(expected, value.Split(',', options));
Assert.Equal(expected, value.Split(',', count, options));
Assert.Equal(expected, value.Split(new[] { ',' }, options));
Assert.Equal(expected, value.Split(new[] { ',' }, count, options));
Assert.Equal(expected, value.Split(",", options));
Assert.Equal(expected, value.Split(",", count, options));
Assert.Equal(expected, value.Split(new[] { "," }, options));
Assert.Equal(expected, value.Split(new[] { "," }, count, options));
}
[Fact]
public static void SplitOneCountSingleResult()
{
const string value = "a,b";
const int count = 1;
const StringSplitOptions options = StringSplitOptions.None;
string[] expected = new[] { value };
Assert.Equal(expected, value.Split(',', count, options));
Assert.Equal(expected, value.Split(new[] { ',' }, count));
Assert.Equal(expected, value.Split(new[] { ',' }, count, options));
Assert.Equal(expected, value.Split(",", count, options));
Assert.Equal(expected, value.Split(new[] { "," }, count, options));
}
[Fact]
public static void SplitNoMatchSingleResult()
{
const string value = "a b";
const int count = int.MaxValue;
const StringSplitOptions options = StringSplitOptions.None;
string[] expected = new[] { value };
Assert.Equal(expected, value.Split(','));
Assert.Equal(expected, value.Split(',', options));
Assert.Equal(expected, value.Split(',', count, options));
Assert.Equal(expected, value.Split(new[] { ',' }));
Assert.Equal(expected, value.Split(new[] { ',' }, options));
Assert.Equal(expected, value.Split(new[] { ',' }, count));
Assert.Equal(expected, value.Split(new[] { ',' }, count, options));
Assert.Equal(expected, value.Split(","));
Assert.Equal(expected, value.Split(",", options));
Assert.Equal(expected, value.Split(",", count, options));
Assert.Equal(expected, value.Split(new[] { "," }, options));
Assert.Equal(expected, value.Split(new[] { "," }, count, options));
}
private const int M = int.MaxValue;
[Theory]
[InlineData("", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData("", ',', 1, StringSplitOptions.None, new[] { "" })]
[InlineData("", ',', 2, StringSplitOptions.None, new[] { "" })]
[InlineData("", ',', 3, StringSplitOptions.None, new[] { "" })]
[InlineData("", ',', 4, StringSplitOptions.None, new[] { "" })]
[InlineData("", ',', M, StringSplitOptions.None, new[] { "" })]
[InlineData("", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData("", ',', 1, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData("", ',', 2, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData("", ',', 3, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData("", ',', 4, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData("", ',', M, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData(",", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData(",", ',', 1, StringSplitOptions.None, new[] { "," })]
[InlineData(",", ',', 2, StringSplitOptions.None, new[] { "", "" })]
[InlineData(",", ',', 3, StringSplitOptions.None, new[] { "", "" })]
[InlineData(",", ',', 4, StringSplitOptions.None, new[] { "", "" })]
[InlineData(",", ',', M, StringSplitOptions.None, new[] { "", "" })]
[InlineData(",", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData(",", ',', 1, StringSplitOptions.RemoveEmptyEntries, new[] { "," })]
[InlineData(",", ',', 2, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData(",", ',', 3, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData(",", ',', 4, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData(",", ',', M, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData(",,", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData(",,", ',', 1, StringSplitOptions.None, new[] { ",," })]
[InlineData(",,", ',', 2, StringSplitOptions.None, new[] { "", ",", })]
[InlineData(",,", ',', 3, StringSplitOptions.None, new[] { "", "", "" })]
[InlineData(",,", ',', 4, StringSplitOptions.None, new[] { "", "", "" })]
[InlineData(",,", ',', M, StringSplitOptions.None, new[] { "", "", "" })]
[InlineData(",,", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData(",,", ',', 1, StringSplitOptions.RemoveEmptyEntries, new[] { ",," })]
[InlineData(",,", ',', 2, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData(",,", ',', 3, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData(",,", ',', 4, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData(",,", ',', M, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData("ab", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData("ab", ',', 1, StringSplitOptions.None, new[] { "ab" })]
[InlineData("ab", ',', 2, StringSplitOptions.None, new[] { "ab" })]
[InlineData("ab", ',', 3, StringSplitOptions.None, new[] { "ab" })]
[InlineData("ab", ',', 4, StringSplitOptions.None, new[] { "ab" })]
[InlineData("ab", ',', M, StringSplitOptions.None, new[] { "ab" })]
[InlineData("ab", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData("ab", ',', 1, StringSplitOptions.RemoveEmptyEntries, new[] { "ab" })]
[InlineData("ab", ',', 2, StringSplitOptions.RemoveEmptyEntries, new[] { "ab" })]
[InlineData("ab", ',', 3, StringSplitOptions.RemoveEmptyEntries, new[] { "ab" })]
[InlineData("ab", ',', 4, StringSplitOptions.RemoveEmptyEntries, new[] { "ab" })]
[InlineData("ab", ',', M, StringSplitOptions.RemoveEmptyEntries, new[] { "ab" })]
[InlineData("a,b", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData("a,b", ',', 1, StringSplitOptions.None, new[] { "a,b" })]
[InlineData("a,b", ',', 2, StringSplitOptions.None, new[] { "a", "b" })]
[InlineData("a,b", ',', 3, StringSplitOptions.None, new[] { "a", "b" })]
[InlineData("a,b", ',', 4, StringSplitOptions.None, new[] { "a", "b" })]
[InlineData("a,b", ',', M, StringSplitOptions.None, new[] { "a", "b" })]
[InlineData("a,b", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData("a,b", ',', 1, StringSplitOptions.RemoveEmptyEntries, new[] { "a,b" })]
[InlineData("a,b", ',', 2, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b" })]
[InlineData("a,b", ',', 3, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b" })]
[InlineData("a,b", ',', 4, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b" })]
[InlineData("a,b", ',', M, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b" })]
[InlineData("a,", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData("a,", ',', 1, StringSplitOptions.None, new[] { "a," })]
[InlineData("a,", ',', 2, StringSplitOptions.None, new[] { "a", "" })]
[InlineData("a,", ',', 3, StringSplitOptions.None, new[] { "a", "" })]
[InlineData("a,", ',', 4, StringSplitOptions.None, new[] { "a", "" })]
[InlineData("a,", ',', M, StringSplitOptions.None, new[] { "a", "" })]
[InlineData("a,", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData("a,", ',', 1, StringSplitOptions.RemoveEmptyEntries, new[] { "a," })]
[InlineData("a,", ',', 2, StringSplitOptions.RemoveEmptyEntries, new[] { "a" })]
[InlineData("a,", ',', 3, StringSplitOptions.RemoveEmptyEntries, new[] { "a" })]
[InlineData("a,", ',', 4, StringSplitOptions.RemoveEmptyEntries, new[] { "a" })]
[InlineData("a,", ',', M, StringSplitOptions.RemoveEmptyEntries, new[] { "a" })]
[InlineData(",b", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData(",b", ',', 1, StringSplitOptions.None, new[] { ",b" })]
[InlineData(",b", ',', 2, StringSplitOptions.None, new[] { "", "b" })]
[InlineData(",b", ',', 3, StringSplitOptions.None, new[] { "", "b" })]
[InlineData(",b", ',', 4, StringSplitOptions.None, new[] { "", "b" })]
[InlineData(",b", ',', M, StringSplitOptions.None, new[] { "", "b" })]
[InlineData(",b", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData(",b", ',', 1, StringSplitOptions.RemoveEmptyEntries, new[] { ",b" })]
[InlineData(",b", ',', 2, StringSplitOptions.RemoveEmptyEntries, new[] { "b" })]
[InlineData(",b", ',', 3, StringSplitOptions.RemoveEmptyEntries, new[] { "b" })]
[InlineData(",b", ',', 4, StringSplitOptions.RemoveEmptyEntries, new[] { "b" })]
[InlineData(",b", ',', M, StringSplitOptions.RemoveEmptyEntries, new[] { "b" })]
[InlineData(",a,b", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData(",a,b", ',', 1, StringSplitOptions.None, new[] { ",a,b" })]
[InlineData(",a,b", ',', 2, StringSplitOptions.None, new[] { "", "a,b" })]
[InlineData(",a,b", ',', 3, StringSplitOptions.None, new[] { "", "a", "b" })]
[InlineData(",a,b", ',', 4, StringSplitOptions.None, new[] { "", "a", "b" })]
[InlineData(",a,b", ',', M, StringSplitOptions.None, new[] { "", "a", "b" })]
[InlineData(",a,b", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData(",a,b", ',', 1, StringSplitOptions.RemoveEmptyEntries, new[] { ",a,b" })]
[InlineData(",a,b", ',', 2, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b" })]
[InlineData(",a,b", ',', 3, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b" })]
[InlineData(",a,b", ',', 4, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b" })]
[InlineData(",a,b", ',', 5, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b" })]
[InlineData("a,b,", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData("a,b,", ',', 1, StringSplitOptions.None, new[] { "a,b," })]
[InlineData("a,b,", ',', 2, StringSplitOptions.None, new[] { "a", "b,", })]
[InlineData("a,b,", ',', 3, StringSplitOptions.None, new[] { "a", "b", "" })]
[InlineData("a,b,", ',', 4, StringSplitOptions.None, new[] { "a", "b", "" })]
[InlineData("a,b,", ',', M, StringSplitOptions.None, new[] { "a", "b", "" })]
[InlineData("a,b,", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData("a,b,", ',', 1, StringSplitOptions.RemoveEmptyEntries, new[] { "a,b," })]
[InlineData("a,b,", ',', 2, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b," })]
[InlineData("a,b,", ',', 3, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b" })]
[InlineData("a,b,", ',', 4, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b" })]
[InlineData("a,b,", ',', M, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b" })]
[InlineData("a,b,c", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData("a,b,c", ',', 1, StringSplitOptions.None, new[] { "a,b,c" })]
[InlineData("a,b,c", ',', 2, StringSplitOptions.None, new[] { "a", "b,c" })]
[InlineData("a,b,c", ',', 3, StringSplitOptions.None, new[] { "a", "b", "c" })]
[InlineData("a,b,c", ',', 4, StringSplitOptions.None, new[] { "a", "b", "c" })]
[InlineData("a,b,c", ',', M, StringSplitOptions.None, new[] { "a", "b", "c" })]
[InlineData("a,b,c", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData("a,b,c", ',', 1, StringSplitOptions.RemoveEmptyEntries, new[] { "a,b,c" })]
[InlineData("a,b,c", ',', 2, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b,c", })]
[InlineData("a,b,c", ',', 3, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b", "c" })]
[InlineData("a,b,c", ',', 4, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b", "c" })]
[InlineData("a,b,c", ',', M, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b", "c" })]
[InlineData("a,,c", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData("a,,c", ',', 1, StringSplitOptions.None, new[] { "a,,c" })]
[InlineData("a,,c", ',', 2, StringSplitOptions.None, new[] { "a", ",c", })]
[InlineData("a,,c", ',', 3, StringSplitOptions.None, new[] { "a", "", "c" })]
[InlineData("a,,c", ',', 4, StringSplitOptions.None, new[] { "a", "", "c" })]
[InlineData("a,,c", ',', M, StringSplitOptions.None, new[] { "a", "", "c" })]
[InlineData("a,,c", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData("a,,c", ',', 1, StringSplitOptions.RemoveEmptyEntries, new[] { "a,,c" })]
[InlineData("a,,c", ',', 2, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "c", })]
[InlineData("a,,c", ',', 3, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "c" })]
[InlineData("a,,c", ',', 4, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "c" })]
[InlineData("a,,c", ',', M, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "c" })]
[InlineData(",a,b,c", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData(",a,b,c", ',', 1, StringSplitOptions.None, new[] { ",a,b,c" })]
[InlineData(",a,b,c", ',', 2, StringSplitOptions.None, new[] { "", "a,b,c" })]
[InlineData(",a,b,c", ',', 3, StringSplitOptions.None, new[] { "", "a", "b,c" })]
[InlineData(",a,b,c", ',', 4, StringSplitOptions.None, new[] { "", "a", "b", "c" })]
[InlineData(",a,b,c", ',', M, StringSplitOptions.None, new[] { "", "a", "b", "c" })]
[InlineData(",a,b,c", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData(",a,b,c", ',', 1, StringSplitOptions.RemoveEmptyEntries, new[] { ",a,b,c" })]
[InlineData(",a,b,c", ',', 2, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b,c", })]
[InlineData(",a,b,c", ',', 3, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b", "c" })]
[InlineData(",a,b,c", ',', 4, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b", "c" })]
[InlineData(",a,b,c", ',', M, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b", "c" })]
[InlineData("a,b,c,", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData("a,b,c,", ',', 1, StringSplitOptions.None, new[] { "a,b,c," })]
[InlineData("a,b,c,", ',', 2, StringSplitOptions.None, new[] { "a", "b,c," })]
[InlineData("a,b,c,", ',', 3, StringSplitOptions.None, new[] { "a", "b", "c,", })]
[InlineData("a,b,c,", ',', 4, StringSplitOptions.None, new[] { "a", "b", "c", "" })]
[InlineData("a,b,c,", ',', M, StringSplitOptions.None, new[] { "a", "b", "c", "" })]
[InlineData("a,b,c,", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData("a,b,c,", ',', 1, StringSplitOptions.RemoveEmptyEntries, new[] { "a,b,c," })]
[InlineData("a,b,c,", ',', 2, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b,c,", })]
[InlineData("a,b,c,", ',', 3, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b", "c," })]
[InlineData("a,b,c,", ',', 4, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b", "c" })]
[InlineData("a,b,c,", ',', M, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b", "c" })]
[InlineData(",a,b,c,", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData(",a,b,c,", ',', 1, StringSplitOptions.None, new[] { ",a,b,c," })]
[InlineData(",a,b,c,", ',', 2, StringSplitOptions.None, new[] { "", "a,b,c," })]
[InlineData(",a,b,c,", ',', 3, StringSplitOptions.None, new[] { "", "a", "b,c," })]
[InlineData(",a,b,c,", ',', 4, StringSplitOptions.None, new[] { "", "a", "b", "c," })]
[InlineData(",a,b,c,", ',', M, StringSplitOptions.None, new[] { "", "a", "b", "c", "" })]
[InlineData(",a,b,c,", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData(",a,b,c,", ',', 1, StringSplitOptions.RemoveEmptyEntries, new[] { ",a,b,c," })]
[InlineData(",a,b,c,", ',', 2, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b,c," })]
[InlineData(",a,b,c,", ',', 3, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b", "c," })]
[InlineData(",a,b,c,", ',', 4, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b", "c" })]
[InlineData(",a,b,c,", ',', M, StringSplitOptions.RemoveEmptyEntries, new[] { "a", "b", "c" })]
[InlineData("first,second", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData("first,second", ',', 1, StringSplitOptions.None, new[] { "first,second" })]
[InlineData("first,second", ',', 2, StringSplitOptions.None, new[] { "first", "second" })]
[InlineData("first,second", ',', 3, StringSplitOptions.None, new[] { "first", "second" })]
[InlineData("first,second", ',', 4, StringSplitOptions.None, new[] { "first", "second" })]
[InlineData("first,second", ',', M, StringSplitOptions.None, new[] { "first", "second" })]
[InlineData("first,second", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData("first,second", ',', 1, StringSplitOptions.RemoveEmptyEntries, new[] { "first,second" })]
[InlineData("first,second", ',', 2, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second" })]
[InlineData("first,second", ',', 3, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second" })]
[InlineData("first,second", ',', 4, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second" })]
[InlineData("first,second", ',', M, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second" })]
[InlineData("first,", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData("first,", ',', 1, StringSplitOptions.None, new[] { "first," })]
[InlineData("first,", ',', 2, StringSplitOptions.None, new[] { "first", "" })]
[InlineData("first,", ',', 3, StringSplitOptions.None, new[] { "first", "" })]
[InlineData("first,", ',', 4, StringSplitOptions.None, new[] { "first", "" })]
[InlineData("first,", ',', M, StringSplitOptions.None, new[] { "first", "" })]
[InlineData("first,", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData("first,", ',', 1, StringSplitOptions.RemoveEmptyEntries, new[] { "first," })]
[InlineData("first,", ',', 2, StringSplitOptions.RemoveEmptyEntries, new[] { "first" })]
[InlineData("first,", ',', 3, StringSplitOptions.RemoveEmptyEntries, new[] { "first" })]
[InlineData("first,", ',', 4, StringSplitOptions.RemoveEmptyEntries, new[] { "first" })]
[InlineData("first,", ',', M, StringSplitOptions.RemoveEmptyEntries, new[] { "first" })]
[InlineData(",second", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData(",second", ',', 1, StringSplitOptions.None, new[] { ",second" })]
[InlineData(",second", ',', 2, StringSplitOptions.None, new[] { "", "second" })]
[InlineData(",second", ',', 3, StringSplitOptions.None, new[] { "", "second" })]
[InlineData(",second", ',', 4, StringSplitOptions.None, new[] { "", "second" })]
[InlineData(",second", ',', M, StringSplitOptions.None, new[] { "", "second" })]
[InlineData(",second", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData(",second", ',', 1, StringSplitOptions.RemoveEmptyEntries, new[] { ",second" })]
[InlineData(",second", ',', 2, StringSplitOptions.RemoveEmptyEntries, new[] { "second" })]
[InlineData(",second", ',', 3, StringSplitOptions.RemoveEmptyEntries, new[] { "second" })]
[InlineData(",second", ',', 4, StringSplitOptions.RemoveEmptyEntries, new[] { "second" })]
[InlineData(",second", ',', M, StringSplitOptions.RemoveEmptyEntries, new[] { "second" })]
[InlineData(",first,second", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData(",first,second", ',', 1, StringSplitOptions.None, new[] { ",first,second" })]
[InlineData(",first,second", ',', 2, StringSplitOptions.None, new[] { "", "first,second" })]
[InlineData(",first,second", ',', 3, StringSplitOptions.None, new[] { "", "first", "second" })]
[InlineData(",first,second", ',', 4, StringSplitOptions.None, new[] { "", "first", "second" })]
[InlineData(",first,second", ',', M, StringSplitOptions.None, new[] { "", "first", "second" })]
[InlineData(",first,second", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData(",first,second", ',', 1, StringSplitOptions.RemoveEmptyEntries, new[] { ",first,second" })]
[InlineData(",first,second", ',', 2, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second" })]
[InlineData(",first,second", ',', 3, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second" })]
[InlineData(",first,second", ',', 4, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second" })]
[InlineData(",first,second", ',', 5, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second" })]
[InlineData("first,second,", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData("first,second,", ',', 1, StringSplitOptions.None, new[] { "first,second," })]
[InlineData("first,second,", ',', 2, StringSplitOptions.None, new[] { "first", "second,", })]
[InlineData("first,second,", ',', 3, StringSplitOptions.None, new[] { "first", "second", "" })]
[InlineData("first,second,", ',', 4, StringSplitOptions.None, new[] { "first", "second", "" })]
[InlineData("first,second,", ',', M, StringSplitOptions.None, new[] { "first", "second", "" })]
[InlineData("first,second,", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData("first,second,", ',', 1, StringSplitOptions.RemoveEmptyEntries, new[] { "first,second," })]
[InlineData("first,second,", ',', 2, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second," })]
[InlineData("first,second,", ',', 3, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second" })]
[InlineData("first,second,", ',', 4, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second" })]
[InlineData("first,second,", ',', M, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second" })]
[InlineData("first,second,third", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData("first,second,third", ',', 1, StringSplitOptions.None, new[] { "first,second,third" })]
[InlineData("first,second,third", ',', 2, StringSplitOptions.None, new[] { "first", "second,third" })]
[InlineData("first,second,third", ',', 3, StringSplitOptions.None, new[] { "first", "second", "third" })]
[InlineData("first,second,third", ',', 4, StringSplitOptions.None, new[] { "first", "second", "third" })]
[InlineData("first,second,third", ',', M, StringSplitOptions.None, new[] { "first", "second", "third" })]
[InlineData("first,second,third", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData("first,second,third", ',', 1, StringSplitOptions.RemoveEmptyEntries, new[] { "first,second,third" })]
[InlineData("first,second,third", ',', 2, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second,third", })]
[InlineData("first,second,third", ',', 3, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second", "third" })]
[InlineData("first,second,third", ',', 4, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second", "third" })]
[InlineData("first,second,third", ',', M, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second", "third" })]
[InlineData("first,,third", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData("first,,third", ',', 1, StringSplitOptions.None, new[] { "first,,third" })]
[InlineData("first,,third", ',', 2, StringSplitOptions.None, new[] { "first", ",third", })]
[InlineData("first,,third", ',', 3, StringSplitOptions.None, new[] { "first", "", "third" })]
[InlineData("first,,third", ',', 4, StringSplitOptions.None, new[] { "first", "", "third" })]
[InlineData("first,,third", ',', M, StringSplitOptions.None, new[] { "first", "", "third" })]
[InlineData("first,,third", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData("first,,third", ',', 1, StringSplitOptions.RemoveEmptyEntries, new[] { "first,,third" })]
[InlineData("first,,third", ',', 2, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "third", })]
[InlineData("first,,third", ',', 3, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "third" })]
[InlineData("first,,third", ',', 4, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "third" })]
[InlineData("first,,third", ',', M, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "third" })]
[InlineData(",first,second,third", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData(",first,second,third", ',', 1, StringSplitOptions.None, new[] { ",first,second,third" })]
[InlineData(",first,second,third", ',', 2, StringSplitOptions.None, new[] { "", "first,second,third" })]
[InlineData(",first,second,third", ',', 3, StringSplitOptions.None, new[] { "", "first", "second,third" })]
[InlineData(",first,second,third", ',', 4, StringSplitOptions.None, new[] { "", "first", "second", "third" })]
[InlineData(",first,second,third", ',', M, StringSplitOptions.None, new[] { "", "first", "second", "third" })]
[InlineData(",first,second,third", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData(",first,second,third", ',', 1, StringSplitOptions.RemoveEmptyEntries, new[] { ",first,second,third" })]
[InlineData(",first,second,third", ',', 2, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second,third", })]
[InlineData(",first,second,third", ',', 3, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second", "third" })]
[InlineData(",first,second,third", ',', 4, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second", "third" })]
[InlineData(",first,second,third", ',', M, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second", "third" })]
[InlineData("first,second,third,", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData("first,second,third,", ',', 1, StringSplitOptions.None, new[] { "first,second,third," })]
[InlineData("first,second,third,", ',', 2, StringSplitOptions.None, new[] { "first", "second,third," })]
[InlineData("first,second,third,", ',', 3, StringSplitOptions.None, new[] { "first", "second", "third,", })]
[InlineData("first,second,third,", ',', 4, StringSplitOptions.None, new[] { "first", "second", "third", "" })]
[InlineData("first,second,third,", ',', M, StringSplitOptions.None, new[] { "first", "second", "third", "" })]
[InlineData("first,second,third,", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData("first,second,third,", ',', 1, StringSplitOptions.RemoveEmptyEntries, new[] { "first,second,third," })]
[InlineData("first,second,third,", ',', 2, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second,third,", })]
[InlineData("first,second,third,", ',', 3, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second", "third," })]
[InlineData("first,second,third,", ',', 4, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second", "third" })]
[InlineData("first,second,third,", ',', M, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second", "third" })]
[InlineData(",first,second,third,", ',', 0, StringSplitOptions.None, new string[0])]
[InlineData(",first,second,third,", ',', 1, StringSplitOptions.None, new[] { ",first,second,third," })]
[InlineData(",first,second,third,", ',', 2, StringSplitOptions.None, new[] { "", "first,second,third," })]
[InlineData(",first,second,third,", ',', 3, StringSplitOptions.None, new[] { "", "first", "second,third," })]
[InlineData(",first,second,third,", ',', 4, StringSplitOptions.None, new[] { "", "first", "second", "third," })]
[InlineData(",first,second,third,", ',', M, StringSplitOptions.None, new[] { "", "first", "second", "third", "" })]
[InlineData(",first,second,third,", ',', 0, StringSplitOptions.RemoveEmptyEntries, new string[0])]
[InlineData(",first,second,third,", ',', 1, StringSplitOptions.RemoveEmptyEntries, new[] { ",first,second,third," })]
[InlineData(",first,second,third,", ',', 2, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second,third," })]
[InlineData(",first,second,third,", ',', 3, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second", "third," })]
[InlineData(",first,second,third,", ',', 4, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second", "third" })]
[InlineData(",first,second,third,", ',', M, StringSplitOptions.RemoveEmptyEntries, new[] { "first", "second", "third" })]
[InlineData("first,second,third", ' ', M, StringSplitOptions.None, new[] { "first,second,third" })]
[InlineData("first,second,third", ' ', M, StringSplitOptions.RemoveEmptyEntries, new[] { "first,second,third" })]
[InlineData("Foo Bar Baz", ' ', 2, StringSplitOptions.RemoveEmptyEntries, new[] { "Foo", "Bar Baz" })]
[InlineData("Foo Bar Baz", ' ', M, StringSplitOptions.None, new[] { "Foo", "Bar", "Baz" })]
public static void SplitCharSeparator(string value, char separator, int count, StringSplitOptions options, string[] expected)
{
Assert.Equal(expected, value.Split(separator, count, options));
Assert.Equal(expected, value.Split(new[] { separator }, count, options));
Assert.Equal(expected, value.Split(separator.ToString(), count, options));
Assert.Equal(expected, value.Split(new[] { separator.ToString() }, count, options));
}
[Theory]
[InlineData("a,b,c", null, M, StringSplitOptions.None, new[] { "a,b,c" })]
[InlineData("a,b,c", "", M, StringSplitOptions.None, new[] { "a,b,c" })]
[InlineData("aaabaaabaaa", "aa", M, StringSplitOptions.None, new[] { "", "ab", "ab", "a" })]
[InlineData("aaabaaabaaa", "aa", M, StringSplitOptions.RemoveEmptyEntries, new[] { "ab", "ab", "a" })]
[InlineData("this, is, a, string, with some spaces", ", ", M, StringSplitOptions.None, new[] { "this", "is", "a", "string", "with some spaces" })]
public static void SplitStringSeparator(string value, string separator, int count, StringSplitOptions options, string[] expected)
{
Assert.Equal(expected, value.Split(separator, count, options));
Assert.Equal(expected, value.Split(new[] { separator }, count, options));
}
[Theory]
[InlineData("a b c", null, M, StringSplitOptions.None, new[] { "a", "b", "c" })]
[InlineData("a b c", new char[0], M, StringSplitOptions.None, new[] { "a", "b", "c" })]
[InlineData("a,b,c", null, M, StringSplitOptions.None, new[] { "a,b,c" })]
[InlineData("a,b,c", new char[0], M, StringSplitOptions.None, new[] { "a,b,c" })]
[InlineData("this, is, a, string, with some spaces", new[] { ' ', ',' }, M, StringSplitOptions.None, new[] { "this", "", "is", "", "a", "", "string", "", "with", "some", "spaces" })]
[InlineData("this, is, a, string, with some spaces", new[] { ',', ' ' }, M, StringSplitOptions.None, new[] { "this", "", "is", "", "a", "", "string", "", "with", "some", "spaces" })]
[InlineData("this, is, a, string, with some spaces", new[] { ' ', ',' }, M, StringSplitOptions.RemoveEmptyEntries, new[] { "this", "is", "a", "string", "with", "some", "spaces" })]
[InlineData("this, is, a, string, with some spaces", new[] { ',', ' ' }, M, StringSplitOptions.RemoveEmptyEntries, new[] { "this", "is", "a", "string", "with", "some", "spaces" })]
public static void SplitCharArraySeparator(string value, char[] separators, int count, StringSplitOptions options, string[] expected)
{
Assert.Equal(expected, value.Split(separators, count, options));
Assert.Equal(expected, value.Split(ToStringArray(separators), count, options));
}
[Theory]
[InlineData("a b c", null, M, StringSplitOptions.None, new[] { "a", "b", "c" })]
[InlineData("a b c", new string[0], M, StringSplitOptions.None, new[] { "a", "b", "c" })]
[InlineData("a,b,c", null, M, StringSplitOptions.None, new[] { "a,b,c" })]
[InlineData("a,b,c", new string[0], M, StringSplitOptions.None, new[] { "a,b,c" })]
[InlineData("a,b,c", new string[] { null }, M, StringSplitOptions.None, new[] { "a,b,c" })]
[InlineData("a,b,c", new string[] { "" }, M, StringSplitOptions.None, new[] { "a,b,c" })]
[InlineData("this, is, a, string, with some spaces", new[] { " ", ", " }, M, StringSplitOptions.None, new[] { "this", "is", "a", "string", "with", "some", "spaces" })]
[InlineData("this, is, a, string, with some spaces", new[] { ", ", " " }, M, StringSplitOptions.None, new[] { "this", "is", "a", "string", "with", "some", "spaces" })]
[InlineData("this, is, a, string, with some spaces", new[] { " ", ", " }, M, StringSplitOptions.RemoveEmptyEntries, new[] { "this", "is", "a", "string", "with", "some", "spaces" })]
[InlineData("this, is, a, string, with some spaces", new[] { ", ", " " }, M, StringSplitOptions.RemoveEmptyEntries, new[] { "this", "is", "a", "string", "with", "some", "spaces" })]
public static void SplitStringArraySeparator(string value, string[] separators, int count, StringSplitOptions options, string[] expected)
{
Assert.Equal(expected, value.Split(separators, count, options));
}
private static string[] ToStringArray(char[] source)
{
if (source == null)
return null;
string[] result = new string[source.Length];
for (int i = 0; i < source.Length; i++)
{
result[i] = source[i].ToString();
}
return result;
}
}
}
| |
// #[license]
// SmartsheetClient SDK for C#
// %%
// Copyright (C) 2014 SmartsheetClient
// %%
// 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.
// %[license]
using System.Collections.Generic;
namespace Smartsheet.Api.Models
{
/// <summary>
/// Represents the Cell object that holds data in a sheet.
/// </summary>
public class Cell
{
/// <summary>
/// Represents the column Id for this cell.
/// </summary>
private long? columnId;
/// <summary>
/// Represents the column Type.
/// </summary>
private ColumnType? columnType;
/// <summary>
/// The format descriptor describing this cell's conditional format. Only returned if the include query
/// string parameter contains format and this cell has a conditional format applied.
/// </summary>
private string conditionalFormat;
/// <summary>
/// Represents the display value.
/// </summary>
private string displayValue;
/// <summary>
/// The format descriptor. Only returned if the include query string parameter contains format and this cell
/// has a non-default format applied.
/// </summary>
private string format;
/// <summary>
/// The formula for the cell.
/// </summary>
private string formula;
/// <summary>
/// Represents a hyperlink to a URL, sheet, or report.
/// </summary>
private Hyperlink hyperlink;
/// <summary>
/// The image that the cell contains. Only returned if the cell contains an image
/// </summary>
private Image image;
/// <summary>
/// An inbound link from a cell in another sheet. This cell's value mirrors the linked cell's value
/// </summary>
private CellLink linkInFromCell;
/// <summary>
/// An array of CellLink objects. Zero or more outbound links from this cell to cells in other sheets
/// whose values mirror this cell's value
/// </summary>
private IList<CellLink> linksOutToCells;
/// <summary>
/// is an object representation of a cell's value and is currently used for adding or updating predecessor cell values
/// </summary>
ObjectValue objectValue;
/// <summary>
/// (Admin only) Indicates whether the cell value can contain a value outside of the validation limits (value = true).
/// When using this parameter, you must also set strict to false to bypass value type checking. This property is honored
/// for POST or PUT actions that update rows.
/// </summary>
private bool? overrideValidation;
/// <summary>
/// Represents the Strict flag.
/// </summary>
private bool? strict;
/// <summary>
/// Represents the value.
/// </summary>
private object value;
/// <summary>
/// Gets the column Id for this cell.
/// </summary>
/// <returns> the column Id </returns>
public long? ColumnId
{
get { return columnId; }
set { columnId = value; }
}
/// <summary>
/// Gets the column Type.
/// </summary>
/// <returns> the Type </returns>
public ColumnType? ColumnType
{
get { return columnType; }
set { columnType = value; }
}
/// <summary>
/// The format descriptor describing this cell's conditional format. Only returned if the include query string
/// parameter contains format and this cell has a conditional format applied.
/// </summary>
public string ConditionalFormat
{
get { return conditionalFormat; }
set { conditionalFormat = value; }
}
/// <summary>
/// Gets the display value used on special columns such as "Contact List".
/// </summary>
/// <returns> the display value </returns>
public string DisplayValue
{
get { return displayValue; }
set { displayValue = value; }
}
/// <summary>
/// The format descriptor. Only returned if the include query string parameter contains format and this cell
/// has a non-default format applied.
/// </summary>
public string Format
{
get { return format; }
set { format = value; }
}
/// <summary>
/// Gets the formula for this cell.
/// </summary>
/// <returns> the formula </returns>
public string Formula
{
get { return formula; }
set { formula = value; }
}
/// <summary>
/// A hyperlink to a URL, sheet, or report
/// </summary>
/// <returns> the link </returns>
public Hyperlink Hyperlink
{
get { return hyperlink; }
set { hyperlink = value; }
}
/// <summary>
/// Gets the Strict value for this cell.
/// </summary>
/// <seealso href="http://www.Smartsheet.com/developers/Api-documentation#h.lay2yj3x1pp8">Column Types</seealso>
/// <returns> the Strict </returns>
public Image Image
{
get { return image; }
set { image = value; }
}
/// <summary>
/// An inbound link from a cell in another sheet. This cell's value mirrors the linked cell's value.
/// </summary>
public CellLink LinkInFromCell
{
get { return linkInFromCell; }
set { linkInFromCell = value; }
}
/// <summary>
/// An array of CellLink objects. Zero or more outbound links from this cell to cells in other sheets
/// whose values mirror this cell's value.
/// </summary>
public IList<CellLink> LinksOutToCells
{
get { return linksOutToCells; }
set { linksOutToCells = value; }
}
/// <summary>
/// An object representation of a cell's value that is currently used for adding or updating predecessor cell values.
/// </summary>
/// <returns> the ObjectValue </returns>
public ObjectValue ObjectValue
{
get { return objectValue; }
set { objectValue = value; }
}
/// <summary>
/// (Admin only) Indicates whether the cell value can contain a value outside of the validation limits (value = true).
/// When using this parameter, you must also set strict to false to bypass value type checking. This property is
/// honored for POST or PUT actions that update rows.
/// </summary>
/// <returns> the override validation flag </returns>
public bool? OverrideValidation
{
get { return overrideValidation; }
set { overrideValidation = value; }
}
/// <summary>
/// Gets the Strict value for this cell.
/// </summary>
/// <seealso href="http://www.Smartsheet.com/developers/Api-documentation#h.lay2yj3x1pp8">Column Types</seealso>
/// <returns> the Strict </returns>
public bool? Strict
{
get { return strict; }
set { strict = value; }
}
/// <summary>
/// Gets the value.
/// </summary>
/// <returns> the value </returns>
public object Value
{
get { return value; }
set { this.value = value; }
}
/// <summary>
/// A convenience class for adding a cell with the necessary fields for inserting into a list of cells.
/// </summary>
public class AddCellBuilder
{
private long? columnId;
private object value;
private bool? strict;
private string format;
private Hyperlink hyperlink;
/// <summary>
/// Set required properties.
/// </summary>
/// <param name="columnId">the column Id</param>
/// <param name="value">the value of the cell</param>
public AddCellBuilder(long? columnId, object value)
{
this.columnId = columnId;
this.value = value;
}
/// <summary>
/// Sets the column Id
/// </summary>
/// <param name="columnId">the column Id</param>
/// <returns>this AddCellBuilder</returns>
public AddCellBuilder SetColumnId(long? columnId)
{
this.columnId = columnId;
return this;
}
/// <summary>
/// Sets the cell value
/// </summary>
/// <param name="value">the value</param>
/// <returns>this AddCellBuilder</returns>
public AddCellBuilder SetValue(object value)
{
this.value = value;
return this;
}
/// <summary>
/// Sets whether cells is Strict or not.
/// </summary>
/// <param name="strict">the Strict option</param>
/// <returns>this AddCellBuilder</returns>
public AddCellBuilder SetStrict(bool? strict)
{
this.strict = strict;
return this;
}
/// <summary>
/// Sets the format.
/// </summary>
/// <param name="format">the format</param>
/// <returns>this AddCellBuilder</returns>
public AddCellBuilder SetFormat(string format)
{
this.format = format;
return this;
}
/// <summary>
/// Sets the hyperlink.
/// </summary>
/// <param name="hyperlink">the hyperlink</param>
/// <returns> this AddCellBuilder </returns>
public AddCellBuilder SetHyperlink(Hyperlink hyperlink)
{
this.hyperlink = hyperlink;
return this;
}
/// <summary>
/// Gets the column Id.
/// </summary>
/// <returns>the column Id</returns>
public long? GetColumnId()
{
return columnId;
}
/// <summary>
/// Gets the value.
/// </summary>
/// <returns>the value</returns>
public object GetValue()
{
return value;
}
/// <summary>
/// Gets the Strict option.
/// </summary>
/// <returns>the Strict option</returns>
public bool? GetStrict()
{
return strict;
}
/// <summary>
/// Gets the format.
/// </summary>
/// <returns>the format</returns>
public string GetFormat()
{
return format;
}
/// <summary>
/// Gets the hyperlink.
/// </summary>
/// <returns>the hyperlink</returns>
public Hyperlink GetHyperlink()
{
return hyperlink;
}
/// <summary>
/// Builds and returns the Cell object.
/// </summary>
/// <returns>Cell object</returns>
public Cell Build()
{
Cell cell = new Cell();
cell.ColumnId = columnId;
cell.Value = value;
cell.Strict = strict;
cell.Format = format;
cell.Hyperlink = hyperlink;
return cell;
}
}
/// <summary>
/// A convenience class for updating a cell with the necessary fields for inserting into a list of cells.
/// </summary>
public class UpdateCellBuilder
{
private long? columnId;
private object value;
private bool? strict;
private string format;
private Hyperlink hyperlink;
private CellLink linkInFromCell;
/// <summary>
/// Set required properties.
/// </summary>
/// <param name="columnId">required</param>
/// <param name="value">required</param>
public UpdateCellBuilder(long? columnId, object value)
{
this.columnId = columnId;
this.value = value;
}
/// <summary>
/// Sets the column Id
/// </summary>
/// <param name="columnId">columnId</param>
/// <returns>this UpdateCellBuilder</returns>
public UpdateCellBuilder SetColumnId(long? columnId)
{
this.columnId = columnId;
return this;
}
/// <summary>
/// Sets the value.
/// </summary>
/// <param name="value">(required)</param>
/// <returns>this UpdateCellBuilder</returns>
public UpdateCellBuilder SetValue(object value)
{
this.value = value;
return this;
}
/// <summary>
/// Sets the strict.
/// </summary>
/// <param name="strict">(optional)</param>
/// <returns>this UpdateCellBuilder</returns>
public UpdateCellBuilder SetStrict(bool? strict)
{
this.strict = strict;
return this;
}
/// <summary>
/// Sets the format.
/// </summary>
/// <param name="format">(optional)</param>
/// <returns>this UpdateCellBuilder</returns>
public UpdateCellBuilder SetFormat(string format)
{
this.format = format;
return this;
}
/// <summary>
/// (optional) with exactly one of the following attributes set:
/// <list type="bullet">
/// <item>url</item>
/// <item>sheetId</item>
/// <item>reportId</item>
/// </list>
/// </summary>
/// <param name="hyperlink"> Link object </param>
/// <returns> this UpdateCellBuilder </returns>
public UpdateCellBuilder SetHyperlink(Hyperlink hyperlink)
{
this.hyperlink = hyperlink;
return this;
}
/// <summary>
/// (optional) with all of the following attributes set:
/// <list type="bullet">
/// <item>sheetId</item>
/// <item>rowId</item>
/// <item>columnId</item>
/// </list>
/// </summary>
/// <param name="linkInFromCell"> CellLink object </param>
/// <returns> this UpdateCellBuilder </returns>
public UpdateCellBuilder SetLinkInFromCell(CellLink linkInFromCell)
{
this.linkInFromCell = linkInFromCell;
return this;
}
/// <summary>
/// Gets the column Id.
/// </summary>
/// <returns>the column Id.</returns>
public long? GetColumnId()
{
return columnId;
}
/// <summary>
/// Gets the value.
/// </summary>
/// <returns>the value.</returns>
public object GetValue()
{
return value;
}
/// <summary>
/// Gets the Strict.
/// </summary>
/// <returns>
/// the strict.
/// </returns>
public bool? GetStrict()
{
return strict;
}
/// <summary>
/// Gets the format.
/// </summary>
/// <returns>the format</returns>
public string GetFormat()
{
return format;
}
/// <summary>
/// Gets the hyperLink
/// </summary>
/// <returns>the hyperlink</returns>
public Hyperlink GetHyperlink()
{
return hyperlink;
}
/// <summary>
/// Gets link in from cell.
/// </summary>
/// <returns>the link in from cell</returns>
public CellLink GetLinkInFromCell()
{
return linkInFromCell;
}
/// <summary>
/// Builds and returns the Cell object.
/// </summary>
/// <returns>Cell object</returns>
public Cell Build()
{
Cell cell = new Cell();
cell.ColumnId = columnId;
cell.Value = value;
cell.Strict = strict;
cell.Format = format;
cell.Hyperlink = hyperlink;
cell.LinkInFromCell = linkInFromCell;
return cell;
}
}
}
}
| |
#region
/*
Copyright (c) 2002-2012, Bas Geertsema, Xih Solutions
(http://www.xihsolutions.net), Thiago.Sayao, Pang Wu, Ethem Evlice, Andy Phan, Chang Liu.
All rights reserved. http://code.google.com/p/msnp-sharp/
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 names of Bas Geertsema or Xih Solutions 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;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
namespace MSNPSharp
{
/// <summary>
/// Represent the information of a certain endpoint.
/// </summary>
[Serializable]
public class EndPointData
{
#region Fields and Properties
private Guid id = Guid.Empty;
private string account = string.Empty;
private ClientCapabilities imCapabilities = ClientCapabilities.None;
private ClientCapabilitiesEx imCapabilitiesEx = ClientCapabilitiesEx.None;
private ClientCapabilities peCapabilities = ClientCapabilities.None;
private ClientCapabilitiesEx peCapabilitiesEx = ClientCapabilitiesEx.None;
/// <summary>
/// The Id of endpoint data.
/// </summary>
public Guid Id
{
get
{
return id;
}
}
/// <summary>
/// The account of this endpoint, different endpoints might share the same account.
/// </summary>
public string Account
{
get
{
return account;
}
}
/// <summary>
/// The IM capacities of the client at this enpoint.
/// </summary>
public ClientCapabilities IMCapabilities
{
get
{
return imCapabilities;
}
internal set
{
imCapabilities = value;
}
}
/// <summary>
/// The IM extended capabilities of the client at this enpoint.
/// </summary>
public ClientCapabilitiesEx IMCapabilitiesEx
{
get
{
return imCapabilitiesEx;
}
internal set
{
imCapabilitiesEx = value;
}
}
/// <summary>
/// The PE (p2p) capacities of the client at this enpoint.
/// </summary>
public ClientCapabilities PECapabilities
{
get
{
return peCapabilities;
}
internal set
{
peCapabilities = value;
}
}
/// <summary>
/// The PE (p2p) extended capabilities of the client at this enpoint.
/// </summary>
public ClientCapabilitiesEx PECapabilitiesEx
{
get
{
return peCapabilitiesEx;
}
internal set
{
peCapabilitiesEx = value;
}
}
public P2PVersion P2PVersionSupported
{
get
{
if (PECapabilitiesEx != ClientCapabilitiesEx.None)
{
return (Id == Guid.Empty) ? P2PVersion.P2PV1 : P2PVersion.P2PV2;
}
return P2PVersion.None;
}
}
#endregion
protected EndPointData()
{
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="account"></param>
/// <param name="epId">The endpoint Id.</param>
public EndPointData(string account, Guid epId)
{
this.id = epId;
this.account = account.ToLowerInvariant();
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="uniqueEPIDString">The string represents the endpoint with the format [account];[EndPoingGUID]</param>
public EndPointData(string uniqueEPIDString)
{
account = GetAccountFromUniqueEPIDString(uniqueEPIDString);
id = GetEndPointIDFromUniqueEPIDString(uniqueEPIDString);
}
public static string GetAccountFromUniqueEPIDString(string uniqueEPIDString)
{
string[] accountGuid = uniqueEPIDString.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
return accountGuid[0].ToLowerInvariant();
}
public static Guid GetEndPointIDFromUniqueEPIDString(string uniqueEPIDString)
{
string[] accountGuid = uniqueEPIDString.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
try
{
if (accountGuid.Length > 0)
{
return new Guid(accountGuid[1]);
}
else
{
return Guid.Empty;
}
}
catch (Exception ex)
{
Trace.WriteLineIf(Settings.TraceSwitch.TraceError, "GetEndPointIDFromUniqueEPIDString error, empty GUID returned. StackTrace: " + ex.StackTrace);
return Guid.Empty;
}
}
public override string ToString()
{
return Account + ";" + Id.ToString("B") +
"/IM/" + IMCapabilities + ":" + IMCapabilitiesEx +
"/PE/" + PECapabilities + ":" + PECapabilitiesEx;
}
}
[Serializable]
public class PrivateEndPointData : EndPointData
{
private string name = string.Empty;
public const string EveryWherePlace = "Everywhere";
/// <summary>
/// The EpName xml node of UBX command payload.
/// </summary>
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
private string clientType = string.Empty;
/// <summary>
/// The ClientType xml node of UBX command payload.
/// </summary>
public string ClientType
{
get
{
return clientType;
}
set
{
clientType = value;
}
}
private bool idle = false;
/// <summary>
/// The Idle xml node of UBX command payload.
/// </summary>
public bool Idle
{
get
{
return idle;
}
set
{
idle = value;
}
}
private PresenceStatus state = PresenceStatus.Unknown;
public PresenceStatus State
{
get
{
return state;
}
set
{
state = value;
}
}
public PrivateEndPointData(string account, Guid epId)
: base(account, epId)
{
if (epId == NSMessageHandler.MachineGuid)
{
Name = Environment.MachineName;
}
if (epId == Guid.Empty)
{
Name = EveryWherePlace;
}
}
public PrivateEndPointData(string uniqueEPIDString)
: base(uniqueEPIDString)
{
}
}
};
| |
using System;
using System.Diagnostics;
using System.IO;
using System.Collections.Generic;
using RadioLogger;
namespace Configuration
{
public class FileSettings : BasicSettings
{
public Dictionary<string, string> config = new Dictionary<string, string>();
public FileSettings(string file) {
read(file);
}
public void read(string configFile) {
string basis = "";
bool blockComment = false;
Dictionary<string, int> vars;
int lineNumber = 0;
try {
if (!File.Exists(configFile)) {
return;
}
using (StreamReader fi = new StreamReader(configFile)) {
vars = new Dictionary<string, int>();
while (!fi.EndOfStream) {
string line;
string trimed;
string varName;
string[] parts;
int i, j, varVal;
lineNumber++;
line = fi.ReadLine();
trimed = line.Trim();
// filter block komments
if (blockComment) {
blockComment = !trimed.EndsWith("*/");
continue;
}
if (trimed.StartsWith("/*")) {
blockComment = true;
continue;
}
// skip comments and empty lines
if (trimed.StartsWith("//") || trimed == "") {
continue;
}
// append next line on line break
while (!fi.EndOfStream && line != "" && line[line.Length - 1] == '\\') {
line = line.Substring(0, line.Length - 1) + fi.ReadLine().TrimStart();
}
line = line.Trim();
if (line == "") {
continue;
}
// get line information
if (line[0] == '#') {
// instruction
if (line.Length > 9 && line.StartsWith("#include") && (line[8] == ' ' || line[8] == '\t')) {
read(new FileInfo(configFile).Directory.FullName + "/" + line.Substring(9).Trim());
} else {
Logger.LogWarning("[Config] [Reading] unknown operation: \"" + line + "\" at line: " + lineNumber);
}
} else if (line[0] == '$') {
// var
if (line.EndsWith("++")) {
varName = line.Substring(1, line.Length - 3).Trim();
if (-1 == varName.IndexOf(" ")) {
varVal = 0;
if (vars.TryGetValue(varName, out varVal)) {
vars[varName] = varVal + 1;
} else {
Logger.LogWarning("[Config] [Reading] variable not set: \"" + varName + "\" at line: " + lineNumber);
}
} else {
Logger.LogWarning("[Config] [Reading] not a variable: \"" + varName + "\" at line: " + lineNumber);
}
} else if (-1 != line.IndexOf("=")) {
parts = line.Split(new char[] { '=' }, 2);
if (parts.Length == 2) {
parts[0] = parts[0].Substring(1).Trim();
try {
vars[parts[0]] = Convert.ToInt32(parts[1]);
} catch {
Logger.LogError("[Config] [Reading] not a number: \"" + parts[1] + "\" at line: " + lineNumber);
}
} else {
Logger.LogWarning("[Config] [Reading] unknown operation: \"" + line + "\" at line: " + lineNumber);
}
} else {
Logger.LogWarning("[Config] [Reading] unknown operation: \"" + line + "\" at line: " + lineNumber);
}
} else if (line[0] == '[' && line[line.Length - 1] == ']') {
// new basis
basis = line.Substring(1, line.Length - 2).Trim() + ".";
if (basis == ".") {
basis = "";
}
} else {
// a assignment
while (-1 != (i = line.LastIndexOf("$"))) {
j = line.IndexOfAny(new char [] { ']', '=' }, i);
if (j != -1) {
varName = line.Substring(i + 1, j - i - 1).Trim();
} else {
varName = line.Substring(i + 1).Trim();
}
if (i>=2 && line[i-1]=='+' && line[i-2]=='+') {
// pre increment the value
varVal = 0;
i -= 2;
if (vars.TryGetValue(varName, out varVal)) {
vars[varName] = varVal + 1;
} else {
Logger.LogWarning("[Config] [Reading] variable not set: \"" + varName + "\" at line: " + lineNumber);
break;
}
}
if (varName.EndsWith("++")) {
if (-1 == varName.IndexOf(" ")) {
varName = varName.Substring(0, varName.Length - 2).Trim();
// First evaluate the variable
varVal = 0;
if (vars.TryGetValue(varName, out varVal)) {
if(j!=-1) {
line = line.Substring(0, i) + varVal.ToString() + line.Substring(j);
} else {
line = line.Substring(0, i) + varVal.ToString();
}
} else {
Logger.LogWarning("[Config] [Reading] variable not set: \"" + varName + "\" at line: " + lineNumber);
break;
}
// post increment the value
varVal = 0;
if (vars.TryGetValue(varName, out varVal)) {
vars[varName] = varVal + 1;
} else {
Logger.LogWarning("[Config] [Reading] variable not set: \"" + varName + "\" at line: " + lineNumber);
break;
}
} else {
Logger.LogWarning("[Config] [Reading] not a variable: \"" + varName + "\" at line: " + lineNumber);
break;
}
} else {
// just evaluate the value
varVal = 0;
if (vars.TryGetValue(varName, out varVal)) {
if(j!=-1) {
line = line.Substring(0, i) + varVal.ToString() + line.Substring(j);
} else {
line = line.Substring(0, i) + varVal.ToString();
}
} else {
Logger.LogWarning("[Config] [Reading] variable not set: \"" + varName + "\" at line: " + lineNumber);
break;
}
}
}
if (i == -1) {
parts = line.Split(new char[] { '=' }, 2);
if (parts.Length == 2) {
config[basis + parts[0].Trim()] = parts[1].Trim();
} else {
Logger.LogWarning("[Config] [Reading] invalid entry \"" + line + "\" at line: " + lineNumber);
}
}
}
}
}
} catch (Exception ex) {
Logger.LogException(ex);
Logger.LogError("[Config] [Reading] Could not fully read the config file \"" + configFile + "\" last line: " + lineNumber + " Message: " + ex.ToString());
}
}
public override string getString(string s, string init) {
string str;
try {
str = config[s];
} catch {
Logger.LogInformation("Missing config option for \"" + s + "\"");
config.Add(s, init);
str = init;
}
return str;
}
public override void setString(string s, string value) {
config.Remove(s);
config.Add(s, value);
}
}
}
| |
/*
* Copyright 2008-2013 the GAP developers. See the NOTICE file at the
* top-level directory of this distribution, and at
* https://gapwiki.chiro.be/copyright
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System.Collections.Generic;
using System.Linq;
using Chiro.Gap.Domain;
using Chiro.Gap.Poco.Model;
using Chiro.Gap.Poco.Model.Exceptions;
using Chiro.Gap.Test;
using NUnit.Framework;
namespace Chiro.Gap.Workers.Test
{
/// <summary>
/// Dit is een testclass voor Unit Tests van FunctiesManagerTest,
/// to contain all FunctiesManagerTest Unit Tests
/// </summary>
[TestFixture]
public class FunctiesManagerTest: ChiroTest
{
#pragma warning disable CS0168 // Variable is declared but never used
Services.Dev.AdServiceMock blablabla;
#pragma warning restore CS0168 // Variable is declared but never used
/// <summary>
/// Opsporen functie met te veel aantal members
/// </summary>
[Test]
public void TweeKeerUniekeFunctieToekennenTestVerschillendLid()
{
// ARRANGE
var groepsWerkJaar = new GroepsWerkJaar
{
Groep = new ChiroGroep(),
WerkJaar = 2012
};
groepsWerkJaar.Groep.GroepsWerkJaar.Add(groepsWerkJaar);
var uniekeFunctie = new Functie
{
MaxAantal = 1,
Groep = groepsWerkJaar.Groep,
Niveau = Niveau.Groep
};
var lid1 = new Leiding { GroepsWerkJaar = groepsWerkJaar, Functie = new List<Functie> { uniekeFunctie } };
var lid2 = new Leiding { GroepsWerkJaar = groepsWerkJaar };
uniekeFunctie.Lid.Add(lid1);
groepsWerkJaar.Lid.Add(lid1);
groepsWerkJaar.Lid.Add(lid2);
// ACT
var functiesManager = Factory.Maak<FunctiesManager>();
functiesManager.Toekennen(lid2, new List<Functie> { uniekeFunctie });
// ASSERT
var issues = functiesManager.AantallenControleren(groepsWerkJaar, new List<Functie> {uniekeFunctie});
Assert.IsTrue(issues.Select(src=>src.ID).Contains(uniekeFunctie.ID));
}
/// <summary>
/// Als een functie maar 1 keer mag voorkomen, maar ze wordt 2 keer toegekend aan dezelfde
/// persoon, dan moet dat zonder problemen kunnen.
/// </summary>
[Test]
public void TweeKeerUniekeFunctieToekennenTestZelfdeLid()
{
// Arrange
// Genereer de situatie
var groep = new ChiroGroep();
var groepsWerkJaar = new GroepsWerkJaar {Groep = groep};
groep.GroepsWerkJaar = new List<GroepsWerkJaar> {groepsWerkJaar};
var leider = new Leiding {GroepsWerkJaar = groepsWerkJaar};
var functie = new Functie
{
MaxAantal = 1,
Type = LidType.Alles,
IsNationaal = true,
Niveau = Niveau.Alles
};
var fm = Factory.Maak<FunctiesManager>();
// Act
fm.Toekennen(leider, new[]{functie});
fm.Toekennen(leider, new[]{functie});
// Assert
var problemen = fm.AantallenControleren(groepsWerkJaar, new[]{functie});
Assert.AreEqual(problemen.Count(), 0);
}
/// <summary>
/// Het toekennen van een functie die niet geldig is in het huidige werkjaar, moet
/// een exception opleveren
/// </summary>
[Test]
public void ToekennenFunctieOngeldigWerkJaar()
{
// ARRANGE
var groepsWerkJaar = new GroepsWerkJaar
{
Groep = new ChiroGroep(),
WerkJaar = 2012
};
groepsWerkJaar.Groep.GroepsWerkJaar.Add(groepsWerkJaar);
var lid = new Leiding {GroepsWerkJaar = groepsWerkJaar};
var vervallenFunctie = new Functie
{
WerkJaarTot = groepsWerkJaar.WerkJaar - 1,
MinAantal = 1,
Groep = groepsWerkJaar.Groep,
Niveau = Niveau.Groep
};
var functiesManager = Factory.Maak<FunctiesManager>();
// ASSERT
Assert.Throws<FoutNummerException>(() => functiesManager.Toekennen(lid, new List<Functie>{vervallenFunctie}));
// Als er geen exception gethrowd worden, zal de test failen.
}
/// <summary>
/// Functies voor leiding mogen niet aan een kind toegewezen worden.
/// </summary>
[Test]
public void ToekennenLidFunctieAanLeiding()
{
// Arrange
var fm = Factory.Maak<FunctiesManager>();
Groep groep = new ChiroGroep
{
Functie = new List<Functie>()
};
var functie = new Functie
{
Groep = groep,
MaxAantal = 1,
MinAantal = 0,
Niveau = Niveau.LidInGroep
};
groep.Functie.Add(functie);
var leider = new Leiding
{
GroepsWerkJaar = new GroepsWerkJaar {Groep = groep}
};
groep.GroepsWerkJaar.Add(leider.GroepsWerkJaar);
// Assert
Assert.Throws<FoutNummerException>(() => fm.Toekennen(leider, new List<Functie> {functie}));
}
/// <summary>
/// Verplichte functie die niet toegekend wordt
/// </summary>
[Test]
public void NietToegekendeVerplichteFunctie()
{
// ARRANGE
var g = new ChiroGroep();
// een (eigen) functie waarvan er precies 1 moet zijn
var f = new Functie
{
MinAantal = 1,
Type = LidType.Alles,
ID = 1,
IsNationaal = false,
Niveau = Niveau.Alles,
Groep = g,
};
// groepswerkjaar zonder leden
var gwj = new GroepsWerkJaar
{
Lid = new List<Lid>(),
Groep = g
};
// Maak een functiesmanager
var fm = Factory.Maak<FunctiesManager>();
// ACT
var problemen = fm.AantallenControleren(gwj, new[] {f});
// ASSERT
Assert.IsTrue(problemen.Any(prb => prb.ID == f.ID));
}
/// <summary>
/// Kijkt na of de verplichte aantallen genegeerd worden voor functies die niet geldig zijn
/// in het gegeven groepswerkjaar.
/// </summary>
[Test]
public void IrrelevanteVerplichteFunctie()
{
// ARRANGE
var groepsWerkJaar = new GroepsWerkJaar {Groep = new ChiroGroep(), WerkJaar = 2012};
var vervallenFunctie = new Functie
{
WerkJaarTot = groepsWerkJaar.WerkJaar - 1,
MinAantal = 1,
Groep = groepsWerkJaar.Groep
};
// ACT
var functiesManager = Factory.Maak<FunctiesManager>();
var probleemIDs = functiesManager.AantallenControleren(groepsWerkJaar, new List<Functie> {vervallenFunctie}).Select(src => src.ID);
// ASSERT
Assert.IsFalse(probleemIDs.Contains(vervallenFunctie.ID));
}
/// <summary>
/// Kijkt na of er een exception opgeworpen wordt als iemand zonder e-mailadres contactpersoon wil worden.
/// </summary>
[Test]
public void ContactZonderEmail()
{
// ARRANGE
var groepsWerkJaar = new GroepsWerkJaar { Groep = new ChiroGroep(), WerkJaar = 2012 };
groepsWerkJaar.Groep.GroepsWerkJaar.Add(groepsWerkJaar);
var contactPersoonFunctie = new Functie
{
ID = (int)NationaleFunctie.ContactPersoon,
MinAantal = 1,
IsNationaal = true,
Niveau = Niveau.LeidingInGroep,
};
var lid = new Leiding
{
GroepsWerkJaar = groepsWerkJaar,
GelieerdePersoon = new GelieerdePersoon()
};
var functiesManager = Factory.Maak<FunctiesManager>();
// ASSERT
var ex = Assert.Throws<FoutNummerException>(
() => functiesManager.Toekennen(lid, new List<Functie> {contactPersoonFunctie}));
Assert.AreEqual(FoutNummer.EMailVerplicht, ex.FoutNummer);
}
/// <summary>
/// Standaard 'AantallenControleren'. Nakijken of rekening wordt gehouden
/// met nationaal bepaalde functies.
/// </summary>
[Test]
public void OntbrekendeNationaalBepaaldeFuncties()
{
// ARRANGE
// een nationale functie waarvan er precies 1 moet zijn
var f = new Functie
{
MinAantal = 1,
Type = LidType.Alles,
ID = 1,
IsNationaal = true,
Niveau = Niveau.Alles
};
// groepswerkjaar zonder leden
var gwj = new GroepsWerkJaar
{
Lid = new List<Lid>()
};
// Maak een functiesmanager
var fm = Factory.Maak<FunctiesManager>();
// ACT
var problemen = fm.AantallenControleren(gwj, new[] { f });
// ASSERT
Assert.IsTrue(problemen.Any(prb => prb.ID == f.ID));
}
/// <summary>
/// Testfuncties vervangen
/// </summary>
[Test]
public void FunctiesVervangen()
{
// Arrange
// testdata
var gwj = new GroepsWerkJaar();
var groep = new ChiroGroep
{
GroepsWerkJaar = new List<GroepsWerkJaar> { gwj }
};
gwj.Groep = groep;
var contactPersoon = new Functie
{
ID = 1,
IsNationaal = true,
Niveau = Niveau.Alles,
Naam = "Contactpersoon",
Type = LidType.Leiding
};
var finVer = new Functie
{
ID = 2,
IsNationaal = true,
Niveau = Niveau.Alles,
Naam = "FinancieelVerantwoordelijke",
Type = LidType.Leiding
};
var vb = new Functie
{
ID = 3,
IsNationaal = true,
Niveau = Niveau.Alles,
Naam = "VB",
Type = LidType.Leiding
};
var redactie = new Functie
{
ID = 4,
IsNationaal = false,
Niveau = Niveau.Groep,
Naam = "RED",
Type = LidType.Leiding,
Groep = groep
};
var leiding = new Leiding
{
ID = 100,
GroepsWerkJaar = gwj,
Functie = new List<Functie> { contactPersoon, redactie },
GelieerdePersoon = new GelieerdePersoon { Groep = groep }
};
var functiesMgr = Factory.Maak<FunctiesManager>();
// ACT
var leidingsFuncties = leiding.Functie; // bewaren voor latere referentie
functiesMgr.Vervangen(leiding, new List<Functie> { finVer, vb, redactie });
// ASSERT
Assert.AreEqual(leiding.Functie.Count(), 3);
Assert.IsTrue(leiding.Functie.Contains(finVer));
Assert.IsTrue(leiding.Functie.Contains(vb));
Assert.IsTrue(leiding.Functie.Contains(redactie));
// om problemen te vermijden met entity framework, mag je bestaande collecties niet zomaar vervangen;
// je moet entiteiten toevoegen aan/verwijderen uit bestaande collecties.
Assert.AreEqual(leiding.Functie, leidingsFuncties);
}
/// <summary>
/// probeert een functie die dit jaar in gebruik is te verwijderen. We verwachten een exception.
/// </summary>
[Test]
public void FunctieDitJaarInGebruikVerwijderenTest()
{
// arrange
// testsituatie creeren
var functie = new Functie();
var groepswerkjaar = new GroepsWerkJaar
{
ID = 11,
Groep =
new ChiroGroep
{
ID = 1,
GroepsWerkJaar = new List<GroepsWerkJaar>()
}
};
groepswerkjaar.Groep.GroepsWerkJaar.Add(groepswerkjaar);
functie.Groep = groepswerkjaar.Groep;
var lid = new Leiding {Functie = new List<Functie>() {functie}, GroepsWerkJaar = groepswerkjaar};
functie.Lid.Add(lid);
var mgr = Factory.Maak<FunctiesManager>();
// assert
Assert.Throws<BlokkerendeObjectenException<Lid>>(() => mgr.Verwijderen(functie, false));
}
/// <summary>
/// probeert een functie die zowel dit jaar als vorig jaar gebruikt is,
/// geforceerd te verwijderen. We verwachten dat het 'werkJaar tot' wordt
/// ingevuld.
/// </summary>
[Test]
public void FunctieLangerInGebruikGeforceerdVerwijderenTest()
{
// ARRANGE
// model
var groep = new ChiroGroep();
var vorigWerkJaar = new GroepsWerkJaar {WerkJaar = 2011, Groep = groep, ID = 2};
var ditWerkJaar = new GroepsWerkJaar {WerkJaar = 2012, Groep = groep, ID = 3};
groep.GroepsWerkJaar.Add(vorigWerkJaar);
groep.GroepsWerkJaar.Add(ditWerkJaar);
var functie = new Functie {Groep = groep, ID = 1};
groep.Functie.Add(functie);
var gelieerdePersoon = new GelieerdePersoon {Groep = groep};
groep.GelieerdePersoon.Add(gelieerdePersoon);
var leidingToen = new Leiding {GelieerdePersoon = gelieerdePersoon, GroepsWerkJaar = vorigWerkJaar};
var leidingNu = new Leiding {GelieerdePersoon = gelieerdePersoon, GroepsWerkJaar = ditWerkJaar};
vorigWerkJaar.Lid.Add(leidingToen);
ditWerkJaar.Lid.Add(leidingNu);
leidingToen.Functie.Add(functie);
leidingNu.Functie.Add(functie);
functie.Lid.Add(leidingToen);
functie.Lid.Add(leidingNu);
// ACT
var mgr = Factory.Maak<FunctiesManager>();
var result = mgr.Verwijderen(functie, true);
// ASSERT
// functie niet meer geldig
Assert.IsTrue(groep.Functie.Contains(functie));
Assert.AreEqual(result.WerkJaarTot, ditWerkJaar.WerkJaar - 1);
// enkel het lid van dit werkJaar blijft over
Assert.AreEqual(result.Lid.Count, 1);
}
/// <summary>
/// Bekijkt AantallenControleren wel degelijk enkel de angeleverde functies?
/// </summary>
[Test]
public void AantallenControlerenBeperkTest()
{
// ARRANGE
var functie1 = new Functie {MaxAantal = 1};
var functie2 = new Functie();
var groepsWerkJaar = new GroepsWerkJaar();
groepsWerkJaar.Lid.Add(new Leiding {Functie = new List<Functie> {functie1}});
groepsWerkJaar.Lid.Add(new Leiding {Functie = new List<Functie> {functie1}}); // 2 personen met de functie
// ACT
var target = Factory.Maak<FunctiesManager>();
var actual = target.AantallenControleren(groepsWerkJaar, new List<Functie>{functie2});
// controleer enkel op functie2.
// ASSERT
Assert.AreEqual(0, actual.Count);
}
/// <summary>
/// Test op het controleren van maximum aantal leden met gegeven functie.
///</summary>
[Test]
public void AantallenControlerenBovengrensTest()
{
// ARRANGE
var functie = new Functie { IsNationaal = true, MaxAantal = 1 };
var groepsWerkJaar1 = new GroepsWerkJaar();
var leiding1 = new Leiding {Functie = new List<Functie> {functie}};
functie.Lid.Add(leiding1);
groepsWerkJaar1.Lid.Add(leiding1);
var groepsWerkJaar2 = new GroepsWerkJaar();
var leiding2 = new Leiding { Functie = new List<Functie> { functie } };
functie.Lid.Add(leiding2);
groepsWerkJaar2.Lid.Add(leiding2);
// ACT
var target = Factory.Maak<FunctiesManager>();
var actual = target.AantallenControleren(groepsWerkJaar1, new List<Functie> { functie });
// controleer enkel op functie2.
// ASSERT
Assert.AreEqual(0, actual.Count);
}
}
}
| |
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
{
/// <summary>
/// Static class that contains static glm functions
/// </summary>
public static partial class glm
{
/// <summary>
/// Returns an object that can be used for arbitrary swizzling (e.g. swizzle.zy)
/// </summary>
public static swizzle_decvec3 swizzle(decvec3 v) => v.swizzle;
/// <summary>
/// Returns an array with all values
/// </summary>
public static decimal[] Values(decvec3 v) => v.Values;
/// <summary>
/// Returns an enumerator that iterates through all components.
/// </summary>
public static IEnumerator<decimal> GetEnumerator(decvec3 v) => v.GetEnumerator();
/// <summary>
/// Returns a string representation of this vector using ', ' as a seperator.
/// </summary>
public static string ToString(decvec3 v) => v.ToString();
/// <summary>
/// Returns a string representation of this vector using a provided seperator.
/// </summary>
public static string ToString(decvec3 v, string sep) => v.ToString(sep);
/// <summary>
/// Returns a string representation of this vector using a provided seperator and a format provider for each component.
/// </summary>
public static string ToString(decvec3 v, string sep, IFormatProvider provider) => v.ToString(sep, provider);
/// <summary>
/// Returns a string representation of this vector using a provided seperator and a format for each component.
/// </summary>
public static string ToString(decvec3 v, string sep, string format) => v.ToString(sep, format);
/// <summary>
/// Returns a string representation of this vector using a provided seperator and a format and format provider for each component.
/// </summary>
public static string ToString(decvec3 v, string sep, string format, IFormatProvider provider) => v.ToString(sep, format, provider);
/// <summary>
/// Returns the number of components (3).
/// </summary>
public static int Count(decvec3 v) => v.Count;
/// <summary>
/// Returns true iff this equals rhs component-wise.
/// </summary>
public static bool Equals(decvec3 v, decvec3 rhs) => v.Equals(rhs);
/// <summary>
/// Returns true iff this equals rhs type- and component-wise.
/// </summary>
public static bool Equals(decvec3 v, object obj) => v.Equals(obj);
/// <summary>
/// Returns a hash code for this instance.
/// </summary>
public static int GetHashCode(decvec3 v) => v.GetHashCode();
/// <summary>
/// Returns true iff distance between lhs and rhs is less than or equal to epsilon
/// </summary>
public static bool ApproxEqual(decvec3 lhs, decvec3 rhs, decimal eps = 0.1m) => decvec3.ApproxEqual(lhs, rhs, eps);
/// <summary>
/// Returns a bvec3 from component-wise application of Equal (lhs == rhs).
/// </summary>
public static bvec3 Equal(decvec3 lhs, decvec3 rhs) => decvec3.Equal(lhs, rhs);
/// <summary>
/// Returns a bvec3 from component-wise application of Equal (lhs == rhs).
/// </summary>
public static bool Equal(decimal lhs, decimal rhs) => lhs == rhs;
/// <summary>
/// Returns a bvec3 from component-wise application of NotEqual (lhs != rhs).
/// </summary>
public static bvec3 NotEqual(decvec3 lhs, decvec3 rhs) => decvec3.NotEqual(lhs, rhs);
/// <summary>
/// Returns a bvec3 from component-wise application of NotEqual (lhs != rhs).
/// </summary>
public static bool NotEqual(decimal lhs, decimal rhs) => lhs != rhs;
/// <summary>
/// Returns a bvec3 from component-wise application of GreaterThan (lhs > rhs).
/// </summary>
public static bvec3 GreaterThan(decvec3 lhs, decvec3 rhs) => decvec3.GreaterThan(lhs, rhs);
/// <summary>
/// Returns a bvec3 from component-wise application of GreaterThan (lhs > rhs).
/// </summary>
public static bool GreaterThan(decimal lhs, decimal rhs) => lhs > rhs;
/// <summary>
/// Returns a bvec3 from component-wise application of GreaterThanEqual (lhs >= rhs).
/// </summary>
public static bvec3 GreaterThanEqual(decvec3 lhs, decvec3 rhs) => decvec3.GreaterThanEqual(lhs, rhs);
/// <summary>
/// Returns a bvec3 from component-wise application of GreaterThanEqual (lhs >= rhs).
/// </summary>
public static bool GreaterThanEqual(decimal lhs, decimal rhs) => lhs >= rhs;
/// <summary>
/// Returns a bvec3 from component-wise application of LesserThan (lhs < rhs).
/// </summary>
public static bvec3 LesserThan(decvec3 lhs, decvec3 rhs) => decvec3.LesserThan(lhs, rhs);
/// <summary>
/// Returns a bvec3 from component-wise application of LesserThan (lhs < rhs).
/// </summary>
public static bool LesserThan(decimal lhs, decimal rhs) => lhs < rhs;
/// <summary>
/// Returns a bvec3 from component-wise application of LesserThanEqual (lhs <= rhs).
/// </summary>
public static bvec3 LesserThanEqual(decvec3 lhs, decvec3 rhs) => decvec3.LesserThanEqual(lhs, rhs);
/// <summary>
/// Returns a bvec3 from component-wise application of LesserThanEqual (lhs <= rhs).
/// </summary>
public static bool LesserThanEqual(decimal lhs, decimal rhs) => lhs <= rhs;
/// <summary>
/// Returns a decvec3 from component-wise application of Abs (Math.Abs(v)).
/// </summary>
public static decvec3 Abs(decvec3 v) => decvec3.Abs(v);
/// <summary>
/// Returns a decvec3 from component-wise application of Abs (Math.Abs(v)).
/// </summary>
public static decimal Abs(decimal v) => Math.Abs(v);
/// <summary>
/// Returns a decvec3 from component-wise application of HermiteInterpolationOrder3 ((3 - 2 * v) * v * v).
/// </summary>
public static decvec3 HermiteInterpolationOrder3(decvec3 v) => decvec3.HermiteInterpolationOrder3(v);
/// <summary>
/// Returns a decvec3 from component-wise application of HermiteInterpolationOrder3 ((3 - 2 * v) * v * v).
/// </summary>
public static decimal HermiteInterpolationOrder3(decimal v) => (3 - 2 * v) * v * v;
/// <summary>
/// Returns a decvec3 from component-wise application of HermiteInterpolationOrder5 (((6 * v - 15) * v + 10) * v * v * v).
/// </summary>
public static decvec3 HermiteInterpolationOrder5(decvec3 v) => decvec3.HermiteInterpolationOrder5(v);
/// <summary>
/// Returns a decvec3 from component-wise application of HermiteInterpolationOrder5 (((6 * v - 15) * v + 10) * v * v * v).
/// </summary>
public static decimal HermiteInterpolationOrder5(decimal v) => ((6 * v - 15) * v + 10) * v * v * v;
/// <summary>
/// Returns a decvec3 from component-wise application of Sqr (v * v).
/// </summary>
public static decvec3 Sqr(decvec3 v) => decvec3.Sqr(v);
/// <summary>
/// Returns a decvec3 from component-wise application of Sqr (v * v).
/// </summary>
public static decimal Sqr(decimal v) => v * v;
/// <summary>
/// Returns a decvec3 from component-wise application of Pow2 (v * v).
/// </summary>
public static decvec3 Pow2(decvec3 v) => decvec3.Pow2(v);
/// <summary>
/// Returns a decvec3 from component-wise application of Pow2 (v * v).
/// </summary>
public static decimal Pow2(decimal v) => v * v;
/// <summary>
/// Returns a decvec3 from component-wise application of Pow3 (v * v * v).
/// </summary>
public static decvec3 Pow3(decvec3 v) => decvec3.Pow3(v);
/// <summary>
/// Returns a decvec3 from component-wise application of Pow3 (v * v * v).
/// </summary>
public static decimal Pow3(decimal v) => v * v * v;
/// <summary>
/// Returns a decvec3 from component-wise application of Step (v >= 0m ? 1m : 0m).
/// </summary>
public static decvec3 Step(decvec3 v) => decvec3.Step(v);
/// <summary>
/// Returns a decvec3 from component-wise application of Step (v >= 0m ? 1m : 0m).
/// </summary>
public static decimal Step(decimal v) => v >= 0m ? 1m : 0m;
/// <summary>
/// Returns a decvec3 from component-wise application of Sqrt ((decimal)Math.Sqrt((double)v)).
/// </summary>
public static decvec3 Sqrt(decvec3 v) => decvec3.Sqrt(v);
/// <summary>
/// Returns a decvec3 from component-wise application of Sqrt ((decimal)Math.Sqrt((double)v)).
/// </summary>
public static decimal Sqrt(decimal v) => (decimal)Math.Sqrt((double)v);
/// <summary>
/// Returns a decvec3 from component-wise application of InverseSqrt ((decimal)(1.0 / Math.Sqrt((double)v))).
/// </summary>
public static decvec3 InverseSqrt(decvec3 v) => decvec3.InverseSqrt(v);
/// <summary>
/// Returns a decvec3 from component-wise application of InverseSqrt ((decimal)(1.0 / Math.Sqrt((double)v))).
/// </summary>
public static decimal InverseSqrt(decimal v) => (decimal)(1.0 / Math.Sqrt((double)v));
/// <summary>
/// Returns a ivec3 from component-wise application of Sign (Math.Sign(v)).
/// </summary>
public static ivec3 Sign(decvec3 v) => decvec3.Sign(v);
/// <summary>
/// Returns a ivec3 from component-wise application of Sign (Math.Sign(v)).
/// </summary>
public static int Sign(decimal v) => Math.Sign(v);
/// <summary>
/// Returns a decvec3 from component-wise application of Max (Math.Max(lhs, rhs)).
/// </summary>
public static decvec3 Max(decvec3 lhs, decvec3 rhs) => decvec3.Max(lhs, rhs);
/// <summary>
/// Returns a decvec3 from component-wise application of Max (Math.Max(lhs, rhs)).
/// </summary>
public static decimal Max(decimal lhs, decimal rhs) => Math.Max(lhs, rhs);
/// <summary>
/// Returns a decvec3 from component-wise application of Min (Math.Min(lhs, rhs)).
/// </summary>
public static decvec3 Min(decvec3 lhs, decvec3 rhs) => decvec3.Min(lhs, rhs);
/// <summary>
/// Returns a decvec3 from component-wise application of Min (Math.Min(lhs, rhs)).
/// </summary>
public static decimal Min(decimal lhs, decimal rhs) => Math.Min(lhs, rhs);
/// <summary>
/// Returns a decvec3 from component-wise application of Pow ((decimal)Math.Pow((double)lhs, (double)rhs)).
/// </summary>
public static decvec3 Pow(decvec3 lhs, decvec3 rhs) => decvec3.Pow(lhs, rhs);
/// <summary>
/// Returns a decvec3 from component-wise application of Pow ((decimal)Math.Pow((double)lhs, (double)rhs)).
/// </summary>
public static decimal Pow(decimal lhs, decimal rhs) => (decimal)Math.Pow((double)lhs, (double)rhs);
/// <summary>
/// Returns a decvec3 from component-wise application of Log ((decimal)Math.Log((double)lhs, (double)rhs)).
/// </summary>
public static decvec3 Log(decvec3 lhs, decvec3 rhs) => decvec3.Log(lhs, rhs);
/// <summary>
/// Returns a decvec3 from component-wise application of Log ((decimal)Math.Log((double)lhs, (double)rhs)).
/// </summary>
public static decimal Log(decimal lhs, decimal rhs) => (decimal)Math.Log((double)lhs, (double)rhs);
/// <summary>
/// Returns a decvec3 from component-wise application of Clamp (Math.Min(Math.Max(v, min), max)).
/// </summary>
public static decvec3 Clamp(decvec3 v, decvec3 min, decvec3 max) => decvec3.Clamp(v, min, max);
/// <summary>
/// Returns a decvec3 from component-wise application of Clamp (Math.Min(Math.Max(v, min), max)).
/// </summary>
public static decimal Clamp(decimal v, decimal min, decimal max) => Math.Min(Math.Max(v, min), max);
/// <summary>
/// Returns a decvec3 from component-wise application of Mix (min * (1-a) + max * a).
/// </summary>
public static decvec3 Mix(decvec3 min, decvec3 max, decvec3 a) => decvec3.Mix(min, max, a);
/// <summary>
/// Returns a decvec3 from component-wise application of Mix (min * (1-a) + max * a).
/// </summary>
public static decimal Mix(decimal min, decimal max, decimal a) => min * (1-a) + max * a;
/// <summary>
/// Returns a decvec3 from component-wise application of Lerp (min * (1-a) + max * a).
/// </summary>
public static decvec3 Lerp(decvec3 min, decvec3 max, decvec3 a) => decvec3.Lerp(min, max, a);
/// <summary>
/// Returns a decvec3 from component-wise application of Lerp (min * (1-a) + max * a).
/// </summary>
public static decimal Lerp(decimal min, decimal max, decimal a) => min * (1-a) + max * a;
/// <summary>
/// Returns a decvec3 from component-wise application of Smoothstep (((v - edge0) / (edge1 - edge0)).Clamp().HermiteInterpolationOrder3()).
/// </summary>
public static decvec3 Smoothstep(decvec3 edge0, decvec3 edge1, decvec3 v) => decvec3.Smoothstep(edge0, edge1, v);
/// <summary>
/// Returns a decvec3 from component-wise application of Smoothstep (((v - edge0) / (edge1 - edge0)).Clamp().HermiteInterpolationOrder3()).
/// </summary>
public static decimal Smoothstep(decimal edge0, decimal edge1, decimal v) => ((v - edge0) / (edge1 - edge0)).Clamp().HermiteInterpolationOrder3();
/// <summary>
/// Returns a decvec3 from component-wise application of Smootherstep (((v - edge0) / (edge1 - edge0)).Clamp().HermiteInterpolationOrder5()).
/// </summary>
public static decvec3 Smootherstep(decvec3 edge0, decvec3 edge1, decvec3 v) => decvec3.Smootherstep(edge0, edge1, v);
/// <summary>
/// Returns a decvec3 from component-wise application of Smootherstep (((v - edge0) / (edge1 - edge0)).Clamp().HermiteInterpolationOrder5()).
/// </summary>
public static decimal Smootherstep(decimal edge0, decimal edge1, decimal v) => ((v - edge0) / (edge1 - edge0)).Clamp().HermiteInterpolationOrder5();
/// <summary>
/// Returns a decvec3 from component-wise application of Fma (a * b + c).
/// </summary>
public static decvec3 Fma(decvec3 a, decvec3 b, decvec3 c) => decvec3.Fma(a, b, c);
/// <summary>
/// Returns a decvec3 from component-wise application of Fma (a * b + c).
/// </summary>
public static decimal Fma(decimal a, decimal b, decimal c) => a * b + c;
/// <summary>
/// OuterProduct treats the first parameter c as a column vector (matrix with one column) and the second parameter r as a row vector (matrix with one row) and does a linear algebraic matrix multiply c * r, yielding a matrix whose number of rows is the number of components in c and whose number of columns is the number of components in r.
/// </summary>
public static decmat2x3 OuterProduct(decvec3 c, decvec2 r) => decvec3.OuterProduct(c, r);
/// <summary>
/// OuterProduct treats the first parameter c as a column vector (matrix with one column) and the second parameter r as a row vector (matrix with one row) and does a linear algebraic matrix multiply c * r, yielding a matrix whose number of rows is the number of components in c and whose number of columns is the number of components in r.
/// </summary>
public static decmat3 OuterProduct(decvec3 c, decvec3 r) => decvec3.OuterProduct(c, r);
/// <summary>
/// OuterProduct treats the first parameter c as a column vector (matrix with one column) and the second parameter r as a row vector (matrix with one row) and does a linear algebraic matrix multiply c * r, yielding a matrix whose number of rows is the number of components in c and whose number of columns is the number of components in r.
/// </summary>
public static decmat4x3 OuterProduct(decvec3 c, decvec4 r) => decvec3.OuterProduct(c, r);
/// <summary>
/// Returns a decvec3 from component-wise application of Add (lhs + rhs).
/// </summary>
public static decvec3 Add(decvec3 lhs, decvec3 rhs) => decvec3.Add(lhs, rhs);
/// <summary>
/// Returns a decvec3 from component-wise application of Add (lhs + rhs).
/// </summary>
public static decimal Add(decimal lhs, decimal rhs) => lhs + rhs;
/// <summary>
/// Returns a decvec3 from component-wise application of Sub (lhs - rhs).
/// </summary>
public static decvec3 Sub(decvec3 lhs, decvec3 rhs) => decvec3.Sub(lhs, rhs);
/// <summary>
/// Returns a decvec3 from component-wise application of Sub (lhs - rhs).
/// </summary>
public static decimal Sub(decimal lhs, decimal rhs) => lhs - rhs;
/// <summary>
/// Returns a decvec3 from component-wise application of Mul (lhs * rhs).
/// </summary>
public static decvec3 Mul(decvec3 lhs, decvec3 rhs) => decvec3.Mul(lhs, rhs);
/// <summary>
/// Returns a decvec3 from component-wise application of Mul (lhs * rhs).
/// </summary>
public static decimal Mul(decimal lhs, decimal rhs) => lhs * rhs;
/// <summary>
/// Returns a decvec3 from component-wise application of Div (lhs / rhs).
/// </summary>
public static decvec3 Div(decvec3 lhs, decvec3 rhs) => decvec3.Div(lhs, rhs);
/// <summary>
/// Returns a decvec3 from component-wise application of Div (lhs / rhs).
/// </summary>
public static decimal Div(decimal lhs, decimal rhs) => lhs / rhs;
/// <summary>
/// Returns a decvec3 from component-wise application of Modulo (lhs % rhs).
/// </summary>
public static decvec3 Modulo(decvec3 lhs, decvec3 rhs) => decvec3.Modulo(lhs, rhs);
/// <summary>
/// Returns a decvec3 from component-wise application of Modulo (lhs % rhs).
/// </summary>
public static decimal Modulo(decimal lhs, decimal rhs) => lhs % rhs;
/// <summary>
/// Returns a decvec3 from component-wise application of Degrees (Radians-To-Degrees Conversion).
/// </summary>
public static decvec3 Degrees(decvec3 v) => decvec3.Degrees(v);
/// <summary>
/// Returns a decvec3 from component-wise application of Degrees (Radians-To-Degrees Conversion).
/// </summary>
public static decimal Degrees(decimal v) => (decimal)(v * 57.295779513082320876798154814105170332405472466564321m);
/// <summary>
/// Returns a decvec3 from component-wise application of Radians (Degrees-To-Radians Conversion).
/// </summary>
public static decvec3 Radians(decvec3 v) => decvec3.Radians(v);
/// <summary>
/// Returns a decvec3 from component-wise application of Radians (Degrees-To-Radians Conversion).
/// </summary>
public static decimal Radians(decimal v) => (decimal)(v * 0.0174532925199432957692369076848861271344287188854172m);
/// <summary>
/// Returns a decvec3 from component-wise application of Acos ((decimal)Math.Acos((double)v)).
/// </summary>
public static decvec3 Acos(decvec3 v) => decvec3.Acos(v);
/// <summary>
/// Returns a decvec3 from component-wise application of Acos ((decimal)Math.Acos((double)v)).
/// </summary>
public static decimal Acos(decimal v) => (decimal)Math.Acos((double)v);
/// <summary>
/// Returns a decvec3 from component-wise application of Asin ((decimal)Math.Asin((double)v)).
/// </summary>
public static decvec3 Asin(decvec3 v) => decvec3.Asin(v);
/// <summary>
/// Returns a decvec3 from component-wise application of Asin ((decimal)Math.Asin((double)v)).
/// </summary>
public static decimal Asin(decimal v) => (decimal)Math.Asin((double)v);
/// <summary>
/// Returns a decvec3 from component-wise application of Atan ((decimal)Math.Atan((double)v)).
/// </summary>
public static decvec3 Atan(decvec3 v) => decvec3.Atan(v);
/// <summary>
/// Returns a decvec3 from component-wise application of Atan ((decimal)Math.Atan((double)v)).
/// </summary>
public static decimal Atan(decimal v) => (decimal)Math.Atan((double)v);
/// <summary>
/// Returns a decvec3 from component-wise application of Cos ((decimal)Math.Cos((double)v)).
/// </summary>
public static decvec3 Cos(decvec3 v) => decvec3.Cos(v);
/// <summary>
/// Returns a decvec3 from component-wise application of Cos ((decimal)Math.Cos((double)v)).
/// </summary>
public static decimal Cos(decimal v) => (decimal)Math.Cos((double)v);
/// <summary>
/// Returns a decvec3 from component-wise application of Cosh ((decimal)Math.Cosh((double)v)).
/// </summary>
public static decvec3 Cosh(decvec3 v) => decvec3.Cosh(v);
/// <summary>
/// Returns a decvec3 from component-wise application of Cosh ((decimal)Math.Cosh((double)v)).
/// </summary>
public static decimal Cosh(decimal v) => (decimal)Math.Cosh((double)v);
/// <summary>
/// Returns a decvec3 from component-wise application of Exp ((decimal)Math.Exp((double)v)).
/// </summary>
public static decvec3 Exp(decvec3 v) => decvec3.Exp(v);
/// <summary>
/// Returns a decvec3 from component-wise application of Exp ((decimal)Math.Exp((double)v)).
/// </summary>
public static decimal Exp(decimal v) => (decimal)Math.Exp((double)v);
/// <summary>
/// Returns a decvec3 from component-wise application of Log ((decimal)Math.Log((double)v)).
/// </summary>
public static decvec3 Log(decvec3 v) => decvec3.Log(v);
/// <summary>
/// Returns a decvec3 from component-wise application of Log ((decimal)Math.Log((double)v)).
/// </summary>
public static decimal Log(decimal v) => (decimal)Math.Log((double)v);
/// <summary>
/// Returns a decvec3 from component-wise application of Log2 ((decimal)Math.Log((double)v, 2)).
/// </summary>
public static decvec3 Log2(decvec3 v) => decvec3.Log2(v);
/// <summary>
/// Returns a decvec3 from component-wise application of Log2 ((decimal)Math.Log((double)v, 2)).
/// </summary>
public static decimal Log2(decimal v) => (decimal)Math.Log((double)v, 2);
/// <summary>
/// Returns a decvec3 from component-wise application of Log10 ((decimal)Math.Log10((double)v)).
/// </summary>
public static decvec3 Log10(decvec3 v) => decvec3.Log10(v);
/// <summary>
/// Returns a decvec3 from component-wise application of Log10 ((decimal)Math.Log10((double)v)).
/// </summary>
public static decimal Log10(decimal v) => (decimal)Math.Log10((double)v);
/// <summary>
/// Returns a decvec3 from component-wise application of Floor ((decimal)Math.Floor(v)).
/// </summary>
public static decvec3 Floor(decvec3 v) => decvec3.Floor(v);
/// <summary>
/// Returns a decvec3 from component-wise application of Floor ((decimal)Math.Floor(v)).
/// </summary>
public static decimal Floor(decimal v) => (decimal)Math.Floor(v);
/// <summary>
/// Returns a decvec3 from component-wise application of Ceiling ((decimal)Math.Ceiling(v)).
/// </summary>
public static decvec3 Ceiling(decvec3 v) => decvec3.Ceiling(v);
/// <summary>
/// Returns a decvec3 from component-wise application of Ceiling ((decimal)Math.Ceiling(v)).
/// </summary>
public static decimal Ceiling(decimal v) => (decimal)Math.Ceiling(v);
/// <summary>
/// Returns a decvec3 from component-wise application of Round ((decimal)Math.Round(v)).
/// </summary>
public static decvec3 Round(decvec3 v) => decvec3.Round(v);
/// <summary>
/// Returns a decvec3 from component-wise application of Round ((decimal)Math.Round(v)).
/// </summary>
public static decimal Round(decimal v) => (decimal)Math.Round(v);
/// <summary>
/// Returns a decvec3 from component-wise application of Sin ((decimal)Math.Sin((double)v)).
/// </summary>
public static decvec3 Sin(decvec3 v) => decvec3.Sin(v);
/// <summary>
/// Returns a decvec3 from component-wise application of Sin ((decimal)Math.Sin((double)v)).
/// </summary>
public static decimal Sin(decimal v) => (decimal)Math.Sin((double)v);
/// <summary>
/// Returns a decvec3 from component-wise application of Sinh ((decimal)Math.Sinh((double)v)).
/// </summary>
public static decvec3 Sinh(decvec3 v) => decvec3.Sinh(v);
/// <summary>
/// Returns a decvec3 from component-wise application of Sinh ((decimal)Math.Sinh((double)v)).
/// </summary>
public static decimal Sinh(decimal v) => (decimal)Math.Sinh((double)v);
/// <summary>
/// Returns a decvec3 from component-wise application of Tan ((decimal)Math.Tan((double)v)).
/// </summary>
public static decvec3 Tan(decvec3 v) => decvec3.Tan(v);
/// <summary>
/// Returns a decvec3 from component-wise application of Tan ((decimal)Math.Tan((double)v)).
/// </summary>
public static decimal Tan(decimal v) => (decimal)Math.Tan((double)v);
/// <summary>
/// Returns a decvec3 from component-wise application of Tanh ((decimal)Math.Tanh((double)v)).
/// </summary>
public static decvec3 Tanh(decvec3 v) => decvec3.Tanh(v);
/// <summary>
/// Returns a decvec3 from component-wise application of Tanh ((decimal)Math.Tanh((double)v)).
/// </summary>
public static decimal Tanh(decimal v) => (decimal)Math.Tanh((double)v);
/// <summary>
/// Returns a decvec3 from component-wise application of Truncate ((decimal)Math.Truncate((double)v)).
/// </summary>
public static decvec3 Truncate(decvec3 v) => decvec3.Truncate(v);
/// <summary>
/// Returns a decvec3 from component-wise application of Truncate ((decimal)Math.Truncate((double)v)).
/// </summary>
public static decimal Truncate(decimal v) => (decimal)Math.Truncate((double)v);
/// <summary>
/// Returns a decvec3 from component-wise application of Fract ((decimal)(v - Math.Floor(v))).
/// </summary>
public static decvec3 Fract(decvec3 v) => decvec3.Fract(v);
/// <summary>
/// Returns a decvec3 from component-wise application of Fract ((decimal)(v - Math.Floor(v))).
/// </summary>
public static decimal Fract(decimal v) => (decimal)(v - Math.Floor(v));
/// <summary>
/// Returns a decvec3 from component-wise application of Trunc ((long)(v)).
/// </summary>
public static decvec3 Trunc(decvec3 v) => decvec3.Trunc(v);
/// <summary>
/// Returns a decvec3 from component-wise application of Trunc ((long)(v)).
/// </summary>
public static decimal Trunc(decimal v) => (long)(v);
/// <summary>
/// Returns the minimal component of this vector.
/// </summary>
public static decimal MinElement(decvec3 v) => v.MinElement;
/// <summary>
/// Returns the maximal component of this vector.
/// </summary>
public static decimal MaxElement(decvec3 v) => v.MaxElement;
/// <summary>
/// Returns the euclidean length of this vector.
/// </summary>
public static decimal Length(decvec3 v) => v.Length;
/// <summary>
/// Returns the squared euclidean length of this vector.
/// </summary>
public static decimal LengthSqr(decvec3 v) => v.LengthSqr;
/// <summary>
/// Returns the sum of all components.
/// </summary>
public static decimal Sum(decvec3 v) => v.Sum;
/// <summary>
/// Returns the euclidean norm of this vector.
/// </summary>
public static decimal Norm(decvec3 v) => v.Norm;
/// <summary>
/// Returns the one-norm of this vector.
/// </summary>
public static decimal Norm1(decvec3 v) => v.Norm1;
/// <summary>
/// Returns the two-norm (euclidean length) of this vector.
/// </summary>
public static decimal Norm2(decvec3 v) => v.Norm2;
/// <summary>
/// Returns the max-norm of this vector.
/// </summary>
public static decimal NormMax(decvec3 v) => v.NormMax;
/// <summary>
/// Returns the p-norm of this vector.
/// </summary>
public static double NormP(decvec3 v, double p) => v.NormP(p);
/// <summary>
/// Returns a copy of this vector with length one (undefined if this has zero length).
/// </summary>
public static decvec3 Normalized(decvec3 v) => v.Normalized;
/// <summary>
/// Returns a copy of this vector with length one (returns zero if length is zero).
/// </summary>
public static decvec3 NormalizedSafe(decvec3 v) => v.NormalizedSafe;
/// <summary>
/// Returns the inner product (dot product, scalar product) of the two vectors.
/// </summary>
public static decimal Dot(decvec3 lhs, decvec3 rhs) => decvec3.Dot(lhs, rhs);
/// <summary>
/// Returns the euclidean distance between the two vectors.
/// </summary>
public static decimal Distance(decvec3 lhs, decvec3 rhs) => decvec3.Distance(lhs, rhs);
/// <summary>
/// Returns the squared euclidean distance between the two vectors.
/// </summary>
public static decimal DistanceSqr(decvec3 lhs, decvec3 rhs) => decvec3.DistanceSqr(lhs, rhs);
/// <summary>
/// Calculate the reflection direction for an incident vector (N should be normalized in order to achieve the desired result).
/// </summary>
public static decvec3 Reflect(decvec3 I, decvec3 N) => decvec3.Reflect(I, N);
/// <summary>
/// Calculate the refraction direction for an incident vector (The input parameters I and N should be normalized in order to achieve the desired result).
/// </summary>
public static decvec3 Refract(decvec3 I, decvec3 N, decimal eta) => decvec3.Refract(I, N, eta);
/// <summary>
/// Returns a vector pointing in the same direction as another (faceforward orients a vector to point away from a surface as defined by its normal. If dot(Nref, I) is negative faceforward returns N, otherwise it returns -N).
/// </summary>
public static decvec3 FaceForward(decvec3 N, decvec3 I, decvec3 Nref) => decvec3.FaceForward(N, I, Nref);
/// <summary>
/// Returns the outer product (cross product, vector product) of the two vectors.
/// </summary>
public static decvec3 Cross(decvec3 l, decvec3 r) => decvec3.Cross(l, r);
/// <summary>
/// Returns a decvec3 with independent and identically distributed uniform values between 'minValue' and 'maxValue'.
/// </summary>
public static decvec3 Random(Random random, decvec3 minValue, decvec3 maxValue) => decvec3.Random(random, minValue, maxValue);
/// <summary>
/// Returns a decvec3 with independent and identically distributed uniform values between 'minValue' and 'maxValue'.
/// </summary>
public static decimal Random(Random random, decimal minValue, decimal maxValue) => (decimal)random.NextDouble() * (maxValue - minValue) + minValue;
/// <summary>
/// Returns a decvec3 with independent and identically distributed uniform values between 'minValue' and 'maxValue'.
/// </summary>
public static decvec3 RandomUniform(Random random, decvec3 minValue, decvec3 maxValue) => decvec3.RandomUniform(random, minValue, maxValue);
/// <summary>
/// Returns a decvec3 with independent and identically distributed uniform values between 'minValue' and 'maxValue'.
/// </summary>
public static decimal RandomUniform(Random random, decimal minValue, decimal maxValue) => (decimal)random.NextDouble() * (maxValue - minValue) + minValue;
/// <summary>
/// Returns a decvec3 with independent and identically distributed values according to a normal/Gaussian distribution with specified mean and variance.
/// </summary>
public static decvec3 RandomNormal(Random random, decvec3 mean, decvec3 variance) => decvec3.RandomNormal(random, mean, variance);
/// <summary>
/// Returns a decvec3 with independent and identically distributed values according to a normal/Gaussian distribution with specified mean and variance.
/// </summary>
public static decimal RandomNormal(Random random, decimal mean, decimal variance) => (decimal)(Math.Sqrt((double)variance) * Math.Cos(2 * Math.PI * random.NextDouble()) * Math.Sqrt(-2.0 * Math.Log(random.NextDouble()))) + mean;
/// <summary>
/// Returns a decvec3 with independent and identically distributed values according to a normal/Gaussian distribution with specified mean and variance.
/// </summary>
public static decvec3 RandomGaussian(Random random, decvec3 mean, decvec3 variance) => decvec3.RandomGaussian(random, mean, variance);
/// <summary>
/// Returns a decvec3 with independent and identically distributed values according to a normal/Gaussian distribution with specified mean and variance.
/// </summary>
public static decimal RandomGaussian(Random random, decimal mean, decimal variance) => (decimal)(Math.Sqrt((double)variance) * Math.Cos(2 * Math.PI * random.NextDouble()) * Math.Sqrt(-2.0 * Math.Log(random.NextDouble()))) + mean;
}
}
| |
// Copyright (c) 2014-2015 Robert Rouhani <robert.rouhani@gmail.com> and other contributors (see CONTRIBUTORS file).
// Licensed under the MIT License - https://raw.github.com/Robmaister/SharpNav/master/LICENSE
using System;
using System.Collections.Generic;
using SharpNav.Collections.Generic;
using SharpNav.Geometry;
#if MONOGAME
using Vector3 = Microsoft.Xna.Framework.Vector3;
#elif OPENTK
using Vector3 = OpenTK.Vector3;
#elif SHARPDX
using Vector3 = SharpDX.Vector3;
#endif
namespace SharpNav.Collections.Generic
{
/// <summary>
/// A <see cref="ProximityGrid{T}"/> is a uniform 2d grid that can efficiently retrieve items near a specified grid cell.
/// </summary>
/// <typeparam name="T">An equatable type.</typeparam>
public class ProximityGrid<T>
where T : IEquatable<T>
{
#region Fields
private const int Invalid = -1;
private float cellSize;
private float invCellSize;
private Item[] pool;
private int poolHead;
private int[] buckets;
private BBox2i bounds;
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="ProximityGrid{T}"/> class.
/// </summary>
/// <param name="poolSize">The size of the item array</param>
/// <param name="cellSize">The size of each cell</param>
public ProximityGrid(int poolSize, float cellSize)
{
this.cellSize = cellSize;
this.invCellSize = 1.0f / cellSize;
//allocate hash buckets
this.buckets = new int[MathHelper.NextPowerOfTwo(poolSize)];
//allocate pool of items
this.poolHead = 0;
this.pool = new Item[poolSize];
for (int i = 0; i < this.pool.Length; i++)
this.pool[i] = new Item();
this.bounds = new BBox2i(Vector2i.Max, Vector2i.Min);
Clear();
}
#endregion
#region Methods
/// <summary>
/// Reset all the data
/// </summary>
public void Clear()
{
for (int i = 0; i < buckets.Length; i++)
buckets[i] = Invalid;
poolHead = 0;
this.bounds = new BBox2i(Vector2i.Max, Vector2i.Min);
}
/// <summary>
/// Take all the coordinates within a certain range and add them all to an array
/// </summary>
/// <param name="value">The value.</param>
/// <param name="minX">Minimum x-coordinate</param>
/// <param name="minY">Minimum y-coordinate</param>
/// <param name="maxX">Maximum x-coordinate</param>
/// <param name="maxY">Maximum y-coordinate</param>
public void AddItem(T value, float minX, float minY, float maxX, float maxY)
{
int invMinX = (int)Math.Floor(minX * invCellSize);
int invMinY = (int)Math.Floor(minY * invCellSize);
int invMaxX = (int)Math.Floor(maxX * invCellSize);
int invMaxY = (int)Math.Floor(maxY * invCellSize);
bounds.Min.X = Math.Min(bounds.Min.X, invMinX);
bounds.Min.Y = Math.Min(bounds.Min.Y, invMinY);
bounds.Max.X = Math.Max(bounds.Max.X, invMaxX);
bounds.Max.Y = Math.Max(bounds.Max.Y, invMaxY);
for (int y = invMinY; y <= invMaxY; y++)
{
for (int x = invMinX; x <= invMaxX; x++)
{
if (poolHead < pool.Length)
{
int h = HashPos2(x, y, buckets.Length);
int idx = poolHead;
poolHead++;
pool[idx].X = x;
pool[idx].Y = y;
pool[idx].Value = value;
pool[idx].Next = buckets[h];
buckets[h] = idx;
}
}
}
}
/// <summary>
/// Take all the items within a certain range and add their ids to an array.
/// </summary>
/// <param name="minX">The minimum x-coordinate</param>
/// <param name="minY">The minimum y-coordinate</param>
/// <param name="maxX">The maximum x-coordinate</param>
/// <param name="maxY">The maximum y-coordinate</param>
/// <param name="values">The array of values</param>
/// <param name="maxVals">The maximum number of values that can be stored</param>
/// <returns>The number of unique values</returns>
public int QueryItems(float minX, float minY, float maxX, float maxY, T[] values, int maxVals)
{
int invMinX = (int)Math.Floor(minX * invCellSize);
int invMinY = (int)Math.Floor(minY * invCellSize);
int invMaxX = (int)Math.Floor(maxX * invCellSize);
int invMaxY = (int)Math.Floor(maxY * invCellSize);
int n = 0;
for (int y = invMinY; y <= invMaxY; y++)
{
for (int x = invMinX; x <= invMaxX; x++)
{
int h = HashPos2(x, y, buckets.Length);
int idx = buckets[h];
while (idx != Invalid)
{
if (pool[idx].X == x && pool[idx].Y == y)
{
//check if the id exists already
int i = 0;
while (i != n && !values[i].Equals(pool[idx].Value))
i++;
//item not found, add it
if (i == n)
{
if (n >= maxVals)
return n;
values[n++] = pool[idx].Value;
}
}
idx = pool[idx].Next;
}
}
}
return n;
}
/// <summary>
/// Gets the number of items at a specific location.
/// </summary>
/// <param name="x">The X coordinate.</param>
/// <param name="y">The Y coordinate.</param>
/// <returns>The number of items at the specified coordinates.</returns>
public int GetItemCountAtLocation(int x, int y)
{
int n = 0;
int h = HashPos2(x, y, buckets.Length);
int idx = buckets[h];
while (idx != Invalid)
{
Item item = pool[idx];
if (item.X == x && item.Y == y)
n++;
idx = item.Next;
}
return n;
}
/// <summary>
/// Hash function
/// </summary>
/// <param name="x">The x-coordinate</param>
/// <param name="y">The y-coordinate</param>
/// <param name="n">Total size of hash table</param>
/// <returns>A hash value</returns>
public static int HashPos2(int x, int y, int n)
{
return ((x * 73856093) ^ (y * 19349663)) & (n - 1);
}
#endregion
/// <summary>
/// An "item" is simply a coordinate on the proximity grid
/// </summary>
private class Item
{
public T Value { get; set; }
public int X { get; set; }
public int Y { get; set; }
public int Next { get; set; }
}
}
}
| |
//
// PangoUtils.cs
//
// Author:
// Michael Hutchinson <mhutchinson@novell.com>
//
// Copyright (c) 2010 Novell, Inc. (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using Gtk;
using System.Runtime.InteropServices;
using System.Collections.Generic;
using Xwt.Drawing;
namespace Xwt.GtkBackend
{
public static class GtkInterop
{
internal const string LIBATK = "libatk-1.0-0.dll";
internal const string LIBGLIB = "libglib-2.0-0.dll";
internal const string LIBGOBJECT = "libgobject-2.0-0.dll";
internal const string LIBPANGO = "libpango-1.0-0.dll";
internal const string LIBPANGOCAIRO = "libpangocairo-1.0-0.dll";
internal const string LIBFONTCONFIG = "fontconfig";
#if XWT_GTK3
internal const string LIBGTK = "libgtk-3-0.dll";
internal const string LIBGDK = "libgdk-3-0.dll";
internal const string LIBGTKGLUE = "gtksharpglue-3";
internal const string LIBGLIBGLUE = "glibsharpglue-3";
internal const string LIBWEBKIT = "libwebkitgtk-3.0-0.dll";
#else
internal const string LIBGTK = "libgtk-win32-2.0-0.dll";
internal const string LIBGDK = "libgdk-win32-2.0-0.dll";
internal const string LIBGTKGLUE = "gtksharpglue-2";
internal const string LIBGLIBGLUE = "glibsharpglue-2";
internal const string LIBWEBKIT = "libwebkitgtk-1.0-0.dll";
#endif
}
/// <summary>
/// This creates a Pango list and applies attributes to it with *much* less overhead than the GTK# version.
/// </summary>
internal class FastPangoAttrList : IDisposable
{
IntPtr list;
public Gdk.Color DefaultLinkColor = Toolkit.CurrentEngine.Defaults.FallbackLinkColor.ToGtkValue ();
public FastPangoAttrList ()
{
list = pango_attr_list_new ();
}
public void AddAttributes (TextIndexer indexer, IEnumerable<TextAttribute> attrs)
{
foreach (var attr in attrs)
AddAttribute (indexer, attr);
}
public void AddAttribute (TextIndexer indexer, TextAttribute attr)
{
var start = (uint) indexer.IndexToByteIndex (attr.StartIndex);
var end = (uint) indexer.IndexToByteIndex (attr.StartIndex + attr.Count);
if (attr is BackgroundTextAttribute) {
var xa = (BackgroundTextAttribute)attr;
AddBackgroundAttribute (xa.Color.ToGtkValue (), start, end);
}
else if (attr is ColorTextAttribute) {
var xa = (ColorTextAttribute)attr;
AddForegroundAttribute (xa.Color.ToGtkValue (), start, end);
}
else if (attr is FontWeightTextAttribute) {
var xa = (FontWeightTextAttribute)attr;
AddWeightAttribute ((Pango.Weight)(int)xa.Weight, start, end);
}
else if (attr is FontStyleTextAttribute) {
var xa = (FontStyleTextAttribute)attr;
AddStyleAttribute ((Pango.Style)(int)xa.Style, start, end);
}
else if (attr is UnderlineTextAttribute) {
var xa = (UnderlineTextAttribute)attr;
AddUnderlineAttribute (xa.Underline ? Pango.Underline.Single : Pango.Underline.None, start, end);
}
else if (attr is StrikethroughTextAttribute) {
var xa = (StrikethroughTextAttribute)attr;
AddStrikethroughAttribute (xa.Strikethrough, start, end);
}
else if (attr is FontTextAttribute) {
var xa = (FontTextAttribute)attr;
AddFontAttribute ((Pango.FontDescription)Toolkit.GetBackend (xa.Font), start, end);
}
else if (attr is LinkTextAttribute) {
// TODO: support "link-color" style prop for TextLayoutBackendHandler and CellRendererText
AddUnderlineAttribute (Pango.Underline.Single, start, end);
AddForegroundAttribute (DefaultLinkColor, start, end);
}
}
public IntPtr Handle {
get { return list; }
}
public void AddStyleAttribute (Pango.Style style, uint start, uint end)
{
Add (pango_attr_style_new (style), start, end);
}
public void AddWeightAttribute (Pango.Weight weight, uint start, uint end)
{
Add (pango_attr_weight_new (weight), start, end);
}
public void AddForegroundAttribute (Gdk.Color color, uint start, uint end)
{
Add (pango_attr_foreground_new (color.Red, color.Green, color.Blue), start, end);
}
public void AddBackgroundAttribute (Gdk.Color color, uint start, uint end)
{
Add (pango_attr_background_new (color.Red, color.Green, color.Blue), start, end);
}
public void AddUnderlineAttribute (Pango.Underline underline, uint start, uint end)
{
Add (pango_attr_underline_new (underline), start, end);
}
public void AddStrikethroughAttribute (bool strikethrough, uint start, uint end)
{
Add (pango_attr_strikethrough_new (strikethrough), start, end);
}
public void AddFontAttribute (Pango.FontDescription font, uint start, uint end)
{
Add (pango_attr_font_desc_new (font.Handle), start, end);
}
void Add (IntPtr attribute, uint start, uint end)
{
unsafe {
PangoAttribute *attPtr = (PangoAttribute *) attribute;
attPtr->start_index = start;
attPtr->end_index = end;
}
pango_attr_list_insert (list, attribute);
}
[DllImport (GtkInterop.LIBPANGO, CallingConvention=CallingConvention.Cdecl)]
static extern IntPtr pango_attr_style_new (Pango.Style style);
[DllImport (GtkInterop.LIBPANGO, CallingConvention=CallingConvention.Cdecl)]
static extern IntPtr pango_attr_stretch_new (Pango.Stretch stretch);
[DllImport (GtkInterop.LIBPANGO, CallingConvention=CallingConvention.Cdecl)]
static extern IntPtr pango_attr_weight_new (Pango.Weight weight);
[DllImport (GtkInterop.LIBPANGO, CallingConvention=CallingConvention.Cdecl)]
static extern IntPtr pango_attr_foreground_new (ushort red, ushort green, ushort blue);
[DllImport (GtkInterop.LIBPANGO, CallingConvention=CallingConvention.Cdecl)]
static extern IntPtr pango_attr_background_new (ushort red, ushort green, ushort blue);
[DllImport (GtkInterop.LIBPANGO, CallingConvention=CallingConvention.Cdecl)]
static extern IntPtr pango_attr_underline_new (Pango.Underline underline);
[DllImport (GtkInterop.LIBPANGO, CallingConvention=CallingConvention.Cdecl)]
static extern IntPtr pango_attr_strikethrough_new (bool strikethrough);
[DllImport (GtkInterop.LIBPANGO, CallingConvention=CallingConvention.Cdecl)]
static extern IntPtr pango_attr_font_desc_new (IntPtr desc);
[DllImport (GtkInterop.LIBPANGO, CallingConvention=CallingConvention.Cdecl)]
static extern IntPtr pango_attr_list_new ();
[DllImport (GtkInterop.LIBPANGO, CallingConvention=CallingConvention.Cdecl)]
static extern void pango_attr_list_unref (IntPtr list);
[DllImport (GtkInterop.LIBPANGO, CallingConvention=CallingConvention.Cdecl)]
static extern void pango_attr_list_insert (IntPtr list, IntPtr attr);
[DllImport (GtkInterop.LIBPANGO, CallingConvention=CallingConvention.Cdecl)]
static extern void pango_layout_set_attributes (IntPtr layout, IntPtr attrList);
[DllImport (GtkInterop.LIBPANGO, CallingConvention=CallingConvention.Cdecl)]
static extern void pango_attr_list_splice (IntPtr attr_list, IntPtr other, Int32 pos, Int32 len);
public void Splice (Pango.AttrList attrs, int pos, int len)
{
pango_attr_list_splice (list, attrs.Handle, pos, len);
}
public void AssignTo (Pango.Layout layout)
{
pango_layout_set_attributes (layout.Handle, list);
}
[StructLayout (LayoutKind.Sequential)]
struct PangoAttribute
{
public IntPtr klass;
public uint start_index;
public uint end_index;
}
public void Dispose ()
{
pango_attr_list_unref (list);
list = IntPtr.Zero;
}
}
public class TextIndexer
{
static readonly List<int> emptyList = new List<int> ();
static readonly int [] emptyArray = new int [0];
int [] indexToByteIndex;
List<int> byteIndexToIndex;
public TextIndexer (string text)
{
SetupTables (text);
}
public int IndexToByteIndex (int i)
{
if (i >= indexToByteIndex.Length)
// if the index exceeds the byte index range, return the last byte index + 1
// telling pango to span the attribute to the end of the string
// this happens if the string contains multibyte characters
return indexToByteIndex[indexToByteIndex.Length-1] + 1;
return indexToByteIndex[i];
}
public int ByteIndexToIndex (int i)
{
return byteIndexToIndex[i];
}
public void SetupTables (string text)
{
if (string.IsNullOrEmpty (text)) {
this.indexToByteIndex = emptyArray;
this.byteIndexToIndex = emptyList;
return;
}
int byteIndex = 0;
int [] indexToByteIndex = new int [text.Length];
var byteIndexToIndex = new System.Collections.Generic.List<int> (text.Length);
unsafe {
fixed (char* p = text) {
for (int i = 0; i < text.Length; i++) {
indexToByteIndex[i] = byteIndex;
byteIndex += System.Text.Encoding.UTF8.GetByteCount (p + i, 1);
while (byteIndexToIndex.Count < byteIndex)
byteIndexToIndex.Add (i);
}
}
}
this.indexToByteIndex = indexToByteIndex;
this.byteIndexToIndex = byteIndexToIndex;
}
}
}
| |
// Copyright (c) 2015, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Collections;
using System.Reflection;
namespace CertEnrollInterop
{
[ComImport, Guid("728AB307-217D-11DA-B2A4-000E7BBB2B09"), CompilerGenerated, InterfaceType(ComInterfaceType.InterfaceIsDual), CoClass(typeof(object))]
public interface CCspInformation : ICspInformation
{
}
[ComImport, Guid("728AB308-217D-11DA-B2A4-000E7BBB2B09"), CompilerGenerated, CoClass(typeof(object)), InterfaceType(ComInterfaceType.InterfaceIsDual)]
public interface CCspInformations : ICspInformations, IEnumerable
{
}
public enum CERTENROLL_OBJECTID
{
XCN_OID_ANSI_X942 = 0x35,
XCN_OID_ANSI_X942_DH = 0x36,
XCN_OID_ANY_APPLICATION_POLICY = 0xd8,
XCN_OID_ANY_CERT_POLICY = 180,
XCN_OID_APPLICATION_CERT_POLICIES = 0xe5,
XCN_OID_APPLICATION_POLICY_CONSTRAINTS = 0xe7,
XCN_OID_APPLICATION_POLICY_MAPPINGS = 230,
XCN_OID_ARCHIVED_KEY_ATTR = 0xe8,
XCN_OID_ARCHIVED_KEY_CERT_HASH = 0xeb,
XCN_OID_AUTHORITY_INFO_ACCESS = 0xcc,
XCN_OID_AUTHORITY_KEY_IDENTIFIER = 0xa9,
XCN_OID_AUTHORITY_KEY_IDENTIFIER2 = 0xb5,
XCN_OID_AUTHORITY_REVOCATION_LIST = 0x9c,
XCN_OID_AUTO_ENROLL_CTL_USAGE = 0xd9,
XCN_OID_BACKGROUND_OTHER_LOGOTYPE = 0x147,
XCN_OID_BASIC_CONSTRAINTS = 0xaf,
XCN_OID_BASIC_CONSTRAINTS2 = 0xb2,
XCN_OID_BIOMETRIC_EXT = 0xcd,
XCN_OID_BUSINESS_CATEGORY = 0x85,
XCN_OID_CA_CERTIFICATE = 0x9b,
XCN_OID_CERT_EXTENSIONS = 0xcf,
XCN_OID_CERT_ISSUER_SERIAL_NUMBER_MD5_HASH_PROP_ID = 0x153,
XCN_OID_CERT_KEY_IDENTIFIER_PROP_ID = 0x152,
XCN_OID_CERT_MANIFOLD = 0xdb,
XCN_OID_CERT_MD5_HASH_PROP_ID = 0x155,
XCN_OID_CERT_POLICIES = 0xb3,
XCN_OID_CERT_POLICIES_95 = 0xab,
XCN_OID_CERT_POLICIES_95_QUALIFIER1 = 0x119,
XCN_OID_CERT_PROP_ID_PREFIX = 0x151,
XCN_OID_CERT_SUBJECT_NAME_MD5_HASH_PROP_ID = 340,
XCN_OID_CERTIFICATE_REVOCATION_LIST = 0x9d,
XCN_OID_CERTIFICATE_TEMPLATE = 0xe2,
XCN_OID_CERTSRV_CA_VERSION = 220,
XCN_OID_CERTSRV_CROSSCA_VERSION = 240,
XCN_OID_CERTSRV_PREVIOUS_CERT_HASH = 0xdd,
XCN_OID_CMC = 0x130,
XCN_OID_CMC_ADD_ATTRIBUTES = 0x145,
XCN_OID_CMC_ADD_EXTENSIONS = 0x138,
XCN_OID_CMC_DATA_RETURN = 0x134,
XCN_OID_CMC_DECRYPTED_POP = 0x13a,
XCN_OID_CMC_ENCRYPTED_POP = 0x139,
XCN_OID_CMC_GET_CERT = 0x13c,
XCN_OID_CMC_GET_CRL = 0x13d,
XCN_OID_CMC_ID_CONFIRM_CERT_ACCEPTANCE = 0x144,
XCN_OID_CMC_ID_POP_LINK_RANDOM = 0x142,
XCN_OID_CMC_ID_POP_LINK_WITNESS = 0x143,
XCN_OID_CMC_IDENTIFICATION = 0x132,
XCN_OID_CMC_IDENTITY_PROOF = 0x133,
XCN_OID_CMC_LRA_POP_WITNESS = 0x13b,
XCN_OID_CMC_QUERY_PENDING = 0x141,
XCN_OID_CMC_RECIPIENT_NONCE = 0x137,
XCN_OID_CMC_REG_INFO = 0x13f,
XCN_OID_CMC_RESPONSE_INFO = 320,
XCN_OID_CMC_REVOKE_REQUEST = 0x13e,
XCN_OID_CMC_SENDER_NONCE = 310,
XCN_OID_CMC_STATUS_INFO = 0x131,
XCN_OID_CMC_TRANSACTION_ID = 0x135,
XCN_OID_COMMON_NAME = 0x79,
XCN_OID_COUNTRY_NAME = 0x7c,
XCN_OID_CRL_DIST_POINTS = 0xbb,
XCN_OID_CRL_NEXT_PUBLISH = 0xdf,
XCN_OID_CRL_NUMBER = 0xbd,
XCN_OID_CRL_REASON_CODE = 0xb9,
XCN_OID_CRL_SELF_CDP = 0xe9,
XCN_OID_CRL_VIRTUAL_BASE = 0xde,
XCN_OID_CROSS_CERT_DIST_POINTS = 210,
XCN_OID_CROSS_CERTIFICATE_PAIR = 0x9e,
XCN_OID_CT_PKI_DATA = 0x12d,
XCN_OID_CT_PKI_RESPONSE = 0x12e,
XCN_OID_CTL = 0xd3,
XCN_OID_DELTA_CRL_INDICATOR = 190,
XCN_OID_DESCRIPTION = 0x83,
XCN_OID_DESTINATION_INDICATOR = 0x91,
XCN_OID_DEVICE_SERIAL_NUMBER = 0x7b,
XCN_OID_DN_QUALIFIER = 0xa1,
XCN_OID_DOMAIN_COMPONENT = 0xa2,
XCN_OID_DRM = 0x111,
XCN_OID_DRM_INDIVIDUALIZATION = 0x112,
XCN_OID_DS = 0x3a,
XCN_OID_DS_EMAIL_REPLICATION = 0xed,
XCN_OID_DSALG = 0x3b,
XCN_OID_DSALG_CRPT = 60,
XCN_OID_DSALG_HASH = 0x3d,
XCN_OID_DSALG_RSA = 0x3f,
XCN_OID_DSALG_SIGN = 0x3e,
XCN_OID_ECC_PUBLIC_KEY = 0x15d,
XCN_OID_ECDSA_SHA1 = 0x162,
XCN_OID_ECDSA_SPECIFIED = 0x162,
XCN_OID_EFS_RECOVERY = 260,
XCN_OID_EMBEDDED_NT_CRYPTO = 0x108,
XCN_OID_ENCRYPTED_KEY_HASH = 0xef,
XCN_OID_ENHANCED_KEY_USAGE = 0xbc,
XCN_OID_ENROLL_CERTTYPE_EXTENSION = 0xda,
XCN_OID_ENROLLMENT_AGENT = 0xc9,
XCN_OID_ENROLLMENT_CSP_PROVIDER = 0xc7,
XCN_OID_ENROLLMENT_NAME_VALUE_PAIR = 0xc6,
XCN_OID_ENTERPRISE_OID_ROOT = 0xe3,
XCN_OID_FACSIMILE_TELEPHONE_NUMBER = 0x8d,
XCN_OID_FRESHEST_CRL = 0xc0,
XCN_OID_GIVEN_NAME = 0x9f,
XCN_OID_INFOSEC = 0x63,
XCN_OID_INFOSEC_mosaicConfidentiality = 0x67,
XCN_OID_INFOSEC_mosaicIntegrity = 0x69,
XCN_OID_INFOSEC_mosaicKeyManagement = 0x6d,
XCN_OID_INFOSEC_mosaicKMandSig = 0x6f,
XCN_OID_INFOSEC_mosaicKMandUpdSig = 0x77,
XCN_OID_INFOSEC_mosaicSignature = 0x65,
XCN_OID_INFOSEC_mosaicTokenProtection = 0x6b,
XCN_OID_INFOSEC_mosaicUpdatedInteg = 120,
XCN_OID_INFOSEC_mosaicUpdatedSig = 0x76,
XCN_OID_INFOSEC_sdnsConfidentiality = 0x66,
XCN_OID_INFOSEC_sdnsIntegrity = 0x68,
XCN_OID_INFOSEC_sdnsKeyManagement = 0x6c,
XCN_OID_INFOSEC_sdnsKMandSig = 110,
XCN_OID_INFOSEC_sdnsSignature = 100,
XCN_OID_INFOSEC_sdnsTokenProtection = 0x6a,
XCN_OID_INFOSEC_SuiteAConfidentiality = 0x71,
XCN_OID_INFOSEC_SuiteAIntegrity = 0x72,
XCN_OID_INFOSEC_SuiteAKeyManagement = 0x74,
XCN_OID_INFOSEC_SuiteAKMandSig = 0x75,
XCN_OID_INFOSEC_SuiteASignature = 0x70,
XCN_OID_INFOSEC_SuiteATokenProtection = 0x73,
XCN_OID_INITIALS = 160,
XCN_OID_INTERNATIONAL_ISDN_NUMBER = 0x8f,
XCN_OID_IPSEC_KP_IKE_INTERMEDIATE = 0xfe,
XCN_OID_ISSUED_CERT_HASH = 0xec,
XCN_OID_ISSUER_ALT_NAME = 0xae,
XCN_OID_ISSUER_ALT_NAME2 = 0xb8,
XCN_OID_ISSUING_DIST_POINT = 0xbf,
XCN_OID_KEY_ATTRIBUTES = 170,
XCN_OID_KEY_USAGE = 0xb0,
XCN_OID_KEY_USAGE_RESTRICTION = 0xac,
XCN_OID_KEYID_RDN = 0xa8,
XCN_OID_KP_CA_EXCHANGE = 0xe0,
XCN_OID_KP_CSP_SIGNATURE = 0x110,
XCN_OID_KP_CTL_USAGE_SIGNING = 0xff,
XCN_OID_KP_DOCUMENT_SIGNING = 0x10c,
XCN_OID_KP_EFS = 0x103,
XCN_OID_KP_KEY_RECOVERY = 0x10b,
XCN_OID_KP_KEY_RECOVERY_AGENT = 0xe1,
XCN_OID_KP_LIFETIME_SIGNING = 0x10d,
XCN_OID_KP_MOBILE_DEVICE_SOFTWARE = 270,
XCN_OID_KP_QUALIFIED_SUBORDINATION = 0x10a,
XCN_OID_KP_SMART_DISPLAY = 0x10f,
XCN_OID_KP_SMARTCARD_LOGON = 0x115,
XCN_OID_KP_TIME_STAMP_SIGNING = 0x100,
XCN_OID_LEGACY_POLICY_MAPPINGS = 0xc3,
XCN_OID_LICENSE_SERVER = 0x114,
XCN_OID_LICENSES = 0x113,
XCN_OID_LOCAL_MACHINE_KEYSET = 0xa6,
XCN_OID_LOCALITY_NAME = 0x7d,
XCN_OID_LOGOTYPE_EXT = 0xce,
XCN_OID_LOYALTY_OTHER_LOGOTYPE = 0x146,
XCN_OID_MEMBER = 0x95,
XCN_OID_NAME_CONSTRAINTS = 0xc1,
XCN_OID_NETSCAPE = 0x121,
XCN_OID_NETSCAPE_BASE_URL = 0x124,
XCN_OID_NETSCAPE_CA_POLICY_URL = 0x128,
XCN_OID_NETSCAPE_CA_REVOCATION_URL = 0x126,
XCN_OID_NETSCAPE_CERT_EXTENSION = 290,
XCN_OID_NETSCAPE_CERT_RENEWAL_URL = 0x127,
XCN_OID_NETSCAPE_CERT_SEQUENCE = 300,
XCN_OID_NETSCAPE_CERT_TYPE = 0x123,
XCN_OID_NETSCAPE_COMMENT = 0x12a,
XCN_OID_NETSCAPE_DATA_TYPE = 0x12b,
XCN_OID_NETSCAPE_REVOCATION_URL = 0x125,
XCN_OID_NETSCAPE_SSL_SERVER_NAME = 0x129,
XCN_OID_NEXT_UPDATE_LOCATION = 0xd0,
XCN_OID_NIST_sha256 = 0x159,
XCN_OID_NIST_sha384 = 0x15a,
XCN_OID_NIST_sha512 = 0x15b,
XCN_OID_NONE = 0,
XCN_OID_NT_PRINCIPAL_NAME = 0xd6,
XCN_OID_NT5_CRYPTO = 0x106,
XCN_OID_NTDS_REPLICATION = 0xf1,
XCN_OID_OEM_WHQL_CRYPTO = 0x107,
XCN_OID_OIW = 0x40,
XCN_OID_OIWDIR = 0x5d,
XCN_OID_OIWDIR_CRPT = 0x5e,
XCN_OID_OIWDIR_HASH = 0x5f,
XCN_OID_OIWDIR_md2 = 0x61,
XCN_OID_OIWDIR_md2RSA = 0x62,
XCN_OID_OIWDIR_SIGN = 0x60,
XCN_OID_OIWSEC = 0x41,
XCN_OID_OIWSEC_desCBC = 70,
XCN_OID_OIWSEC_desCFB = 0x48,
XCN_OID_OIWSEC_desECB = 0x45,
XCN_OID_OIWSEC_desEDE = 80,
XCN_OID_OIWSEC_desMAC = 0x49,
XCN_OID_OIWSEC_desOFB = 0x47,
XCN_OID_OIWSEC_dhCommMod = 0x4f,
XCN_OID_OIWSEC_dsa = 0x4b,
XCN_OID_OIWSEC_dsaComm = 0x53,
XCN_OID_OIWSEC_dsaCommSHA = 0x54,
XCN_OID_OIWSEC_dsaCommSHA1 = 0x5b,
XCN_OID_OIWSEC_dsaSHA1 = 90,
XCN_OID_OIWSEC_keyHashSeal = 0x56,
XCN_OID_OIWSEC_md2RSASign = 0x57,
XCN_OID_OIWSEC_md4RSA = 0x42,
XCN_OID_OIWSEC_md4RSA2 = 0x44,
XCN_OID_OIWSEC_md5RSA = 0x43,
XCN_OID_OIWSEC_md5RSASign = 0x58,
XCN_OID_OIWSEC_mdc2 = 0x52,
XCN_OID_OIWSEC_mdc2RSA = 0x4d,
XCN_OID_OIWSEC_rsaSign = 0x4a,
XCN_OID_OIWSEC_rsaXchg = 0x55,
XCN_OID_OIWSEC_sha = 0x51,
XCN_OID_OIWSEC_sha1 = 0x59,
XCN_OID_OIWSEC_sha1RSASign = 0x5c,
XCN_OID_OIWSEC_shaDSA = 0x4c,
XCN_OID_OIWSEC_shaRSA = 0x4e,
XCN_OID_ORGANIZATION_NAME = 0x80,
XCN_OID_ORGANIZATIONAL_UNIT_NAME = 0x81,
XCN_OID_OS_VERSION = 200,
XCN_OID_OWNER = 150,
XCN_OID_PHYSICAL_DELIVERY_OFFICE_NAME = 0x89,
XCN_OID_PKCS = 2,
XCN_OID_PKCS_1 = 5,
XCN_OID_PKCS_10 = 14,
XCN_OID_PKCS_12 = 15,
XCN_OID_PKCS_12_EXTENDED_ATTRIBUTES = 0xa7,
XCN_OID_PKCS_12_FRIENDLY_NAME_ATTR = 0xa3,
XCN_OID_PKCS_12_KEY_PROVIDER_NAME_ATTR = 0xa5,
XCN_OID_PKCS_12_LOCAL_KEY_ID = 0xa4,
XCN_OID_PKCS_2 = 6,
XCN_OID_PKCS_3 = 7,
XCN_OID_PKCS_4 = 8,
XCN_OID_PKCS_5 = 9,
XCN_OID_PKCS_6 = 10,
XCN_OID_PKCS_7 = 11,
XCN_OID_PKCS_7_DATA = 0x149,
XCN_OID_PKCS_7_DIGESTED = 0x14d,
XCN_OID_PKCS_7_ENCRYPTED = 0x14e,
XCN_OID_PKCS_7_ENVELOPED = 0x14b,
XCN_OID_PKCS_7_SIGNED = 330,
XCN_OID_PKCS_7_SIGNEDANDENVELOPED = 0x14c,
XCN_OID_PKCS_8 = 12,
XCN_OID_PKCS_9 = 13,
XCN_OID_PKCS_9_CONTENT_TYPE = 0x14f,
XCN_OID_PKCS_9_MESSAGE_DIGEST = 0x150,
XCN_OID_PKIX = 0xca,
XCN_OID_PKIX_ACC_DESCR = 0x11a,
XCN_OID_PKIX_CA_ISSUERS = 0x11c,
XCN_OID_PKIX_KP = 0xf3,
XCN_OID_PKIX_KP_CLIENT_AUTH = 0xf5,
XCN_OID_PKIX_KP_CODE_SIGNING = 0xf6,
XCN_OID_PKIX_KP_EMAIL_PROTECTION = 0xf7,
XCN_OID_PKIX_KP_IPSEC_END_SYSTEM = 0xf8,
XCN_OID_PKIX_KP_IPSEC_TUNNEL = 0xf9,
XCN_OID_PKIX_KP_IPSEC_USER = 250,
XCN_OID_PKIX_KP_OCSP_SIGNING = 0xfc,
XCN_OID_PKIX_KP_SERVER_AUTH = 0xf4,
XCN_OID_PKIX_KP_TIMESTAMP_SIGNING = 0xfb,
XCN_OID_PKIX_NO_SIGNATURE = 0x12f,
XCN_OID_PKIX_OCSP = 0x11b,
XCN_OID_PKIX_OCSP_BASIC_SIGNED_RESPONSE = 0x148,
XCN_OID_PKIX_OCSP_NOCHECK = 0xfd,
XCN_OID_PKIX_PE = 0xcb,
XCN_OID_PKIX_POLICY_QUALIFIER_CPS = 0x117,
XCN_OID_PKIX_POLICY_QUALIFIER_USERNOTICE = 280,
XCN_OID_POLICY_CONSTRAINTS = 0xc4,
XCN_OID_POLICY_MAPPINGS = 0xc2,
XCN_OID_POST_OFFICE_BOX = 0x88,
XCN_OID_POSTAL_ADDRESS = 0x86,
XCN_OID_POSTAL_CODE = 0x87,
XCN_OID_PREFERRED_DELIVERY_METHOD = 0x92,
XCN_OID_PRESENTATION_ADDRESS = 0x93,
XCN_OID_PRIVATEKEY_USAGE_PERIOD = 0xb1,
XCN_OID_PRODUCT_UPDATE = 0xd7,
XCN_OID_RDN_DUMMY_SIGNER = 0xe4,
XCN_OID_REASON_CODE_HOLD = 0xba,
XCN_OID_REGISTERED_ADDRESS = 0x90,
XCN_OID_REMOVE_CERTIFICATE = 0xd1,
XCN_OID_RENEWAL_CERTIFICATE = 0xc5,
XCN_OID_REQUEST_CLIENT_INFO = 0xee,
XCN_OID_REQUIRE_CERT_CHAIN_POLICY = 0xea,
XCN_OID_ROLE_OCCUPANT = 0x97,
XCN_OID_ROOT_LIST_SIGNER = 0x109,
XCN_OID_RSA = 1,
XCN_OID_RSA_certExtensions = 0x27,
XCN_OID_RSA_challengePwd = 0x24,
XCN_OID_RSA_contentType = 0x20,
XCN_OID_RSA_counterSign = 0x23,
XCN_OID_RSA_data = 0x17,
XCN_OID_RSA_DES_EDE3_CBC = 0x33,
XCN_OID_RSA_DH = 0x16,
XCN_OID_RSA_digestedData = 0x1b,
XCN_OID_RSA_emailAddr = 30,
XCN_OID_RSA_ENCRYPT = 4,
XCN_OID_RSA_encryptedData = 0x1d,
XCN_OID_RSA_envelopedData = 0x19,
XCN_OID_RSA_extCertAttrs = 0x26,
XCN_OID_RSA_HASH = 3,
XCN_OID_RSA_hashedData = 0x1c,
XCN_OID_RSA_MD2 = 0x2e,
XCN_OID_RSA_MD2RSA = 0x11,
XCN_OID_RSA_MD4 = 0x2f,
XCN_OID_RSA_MD4RSA = 0x12,
XCN_OID_RSA_MD5 = 0x30,
XCN_OID_RSA_MD5RSA = 0x13,
XCN_OID_RSA_messageDigest = 0x21,
XCN_OID_RSA_MGF1 = 0x15c,
XCN_OID_RSA_preferSignedData = 0x29,
XCN_OID_RSA_RC2CBC = 0x31,
XCN_OID_RSA_RC4 = 50,
XCN_OID_RSA_RC5_CBCPad = 0x34,
XCN_OID_RSA_RSA = 0x10,
XCN_OID_RSA_SETOAEP_RSA = 0x15,
XCN_OID_RSA_SHA1RSA = 20,
XCN_OID_RSA_SHA256RSA = 0x156,
XCN_OID_RSA_SHA384RSA = 0x157,
XCN_OID_RSA_SHA512RSA = 0x158,
XCN_OID_RSA_signedData = 0x18,
XCN_OID_RSA_signEnvData = 0x1a,
XCN_OID_RSA_signingTime = 0x22,
XCN_OID_RSA_SMIMEalg = 0x2a,
XCN_OID_RSA_SMIMEalgCMS3DESwrap = 0x2c,
XCN_OID_RSA_SMIMEalgCMSRC2wrap = 0x2d,
XCN_OID_RSA_SMIMEalgESDH = 0x2b,
XCN_OID_RSA_SMIMECapabilities = 40,
XCN_OID_RSA_SSA_PSS = 0x161,
XCN_OID_RSA_unstructAddr = 0x25,
XCN_OID_RSA_unstructName = 0x1f,
XCN_OID_SEARCH_GUIDE = 0x84,
XCN_OID_SEE_ALSO = 0x98,
XCN_OID_SERIALIZED = 0xd5,
XCN_OID_SERVER_GATED_CRYPTO = 0x101,
XCN_OID_SGC_NETSCAPE = 0x102,
XCN_OID_SORTED_CTL = 0xd4,
XCN_OID_STATE_OR_PROVINCE_NAME = 0x7e,
XCN_OID_STREET_ADDRESS = 0x7f,
XCN_OID_SUBJECT_ALT_NAME = 0xad,
XCN_OID_SUBJECT_ALT_NAME2 = 0xb7,
XCN_OID_SUBJECT_DIR_ATTRS = 0xf2,
XCN_OID_SUBJECT_KEY_IDENTIFIER = 0xb6,
XCN_OID_SUPPORTED_APPLICATION_CONTEXT = 0x94,
XCN_OID_SUR_NAME = 0x7a,
XCN_OID_TELEPHONE_NUMBER = 0x8a,
XCN_OID_TELETEXT_TERMINAL_IDENTIFIER = 140,
XCN_OID_TELEX_NUMBER = 0x8b,
XCN_OID_TITLE = 130,
XCN_OID_USER_CERTIFICATE = 0x9a,
XCN_OID_USER_PASSWORD = 0x99,
XCN_OID_VERISIGN_BITSTRING_6_13 = 0x11f,
XCN_OID_VERISIGN_ISS_STRONG_CRYPTO = 0x120,
XCN_OID_VERISIGN_ONSITE_JURISDICTION_HASH = 0x11e,
XCN_OID_VERISIGN_PRIVATE_6_9 = 0x11d,
XCN_OID_WHQL_CRYPTO = 0x105,
XCN_OID_X21_ADDRESS = 0x8e,
XCN_OID_X957 = 0x37,
XCN_OID_X957_DSA = 0x38,
XCN_OID_X957_SHA1DSA = 0x39,
XCN_OID_YESNO_TRUST_ATTR = 0x116
}
[ComImport, CoClass(typeof(object)), CompilerGenerated, Guid("728AB300-217D-11DA-B2A4-000E7BBB2B09"), InterfaceType(ComInterfaceType.InterfaceIsDual)]
public interface CObjectId : IObjectId
{
}
[ComImport, CompilerGenerated, CoClass(typeof(object)), InterfaceType(ComInterfaceType.InterfaceIsDual), Guid("728AB301-217D-11DA-B2A4-000E7BBB2B09")]
public interface CObjectIds : IObjectIds, IEnumerable
{
}
[ComImport, CoClass(typeof(object)), CompilerGenerated, InterfaceType(ComInterfaceType.InterfaceIsDual), Guid("728AB303-217D-11DA-B2A4-000E7BBB2B09")]
public interface CX500DistinguishedName : IX500DistinguishedName
{
}
[ComImport, CoClass(typeof(object)), Guid("728AB35B-217D-11DA-B2A4-000E7BBB2B09"), CompilerGenerated, InterfaceType(ComInterfaceType.InterfaceIsDual)]
public interface CX509CertificateRequestPkcs10 : IX509CertificateRequestPkcs10V2, IX509CertificateRequestPkcs10, IX509CertificateRequest
{
}
[ComImport, InterfaceType(ComInterfaceType.InterfaceIsDual), CompilerGenerated, Guid("728AB350-217D-11DA-B2A4-000E7BBB2B09"), CoClass(typeof(object))]
public interface CX509Enrollment : IX509Enrollment2, IX509Enrollment
{
}
[ComImport, Guid("728AB30D-217D-11DA-B2A4-000E7BBB2B09"), CoClass(typeof(object)), CompilerGenerated, InterfaceType(ComInterfaceType.InterfaceIsDual)]
public interface CX509Extension : IX509Extension
{
}
[ComImport, Guid("728AB310-217D-11DA-B2A4-000E7BBB2B09"), CompilerGenerated, CoClass(typeof(object)), InterfaceType(ComInterfaceType.InterfaceIsDual)]
public interface CX509ExtensionEnhancedKeyUsage : IX509ExtensionEnhancedKeyUsage, IX509Extension
{
}
[ComImport, InterfaceType(ComInterfaceType.InterfaceIsDual), Guid("728AB30F-217D-11DA-B2A4-000E7BBB2B09"), CoClass(typeof(object)), CompilerGenerated]
public interface CX509ExtensionKeyUsage : IX509ExtensionKeyUsage, IX509Extension
{
}
[ComImport, InterfaceType(ComInterfaceType.InterfaceIsDual), Guid("728AB30E-217D-11DA-B2A4-000E7BBB2B09"), CompilerGenerated, CoClass(typeof(object))]
public interface CX509Extensions : IX509Extensions, IEnumerable
{
}
[ComImport, InterfaceType(ComInterfaceType.InterfaceIsDual), CompilerGenerated, Guid("728AB30C-217D-11DA-B2A4-000E7BBB2B09"), CoClass(typeof(object))]
public interface CX509PrivateKey : IX509PrivateKey
{
}
//[InterfaceType(ComInterfaceType.InterfaceIsDual)("728ab348-217d-11da-b2a4-000e7bbb2b09", "CERTENROLLLib.EncodingType"), CompilerGenerated]
public enum EncodingType
{
XCN_CRYPT_STRING_ANY = 7,
XCN_CRYPT_STRING_BASE64 = 1,
XCN_CRYPT_STRING_BASE64_ANY = 6,
XCN_CRYPT_STRING_BASE64HEADER = 0,
XCN_CRYPT_STRING_BASE64REQUESTHEADER = 3,
XCN_CRYPT_STRING_BASE64X509CRLHEADER = 9,
XCN_CRYPT_STRING_BINARY = 2,
XCN_CRYPT_STRING_HASHDATA = 0x10000000,
XCN_CRYPT_STRING_HEX = 4,
XCN_CRYPT_STRING_HEX_ANY = 8,
XCN_CRYPT_STRING_HEXADDR = 10,
XCN_CRYPT_STRING_HEXASCII = 5,
XCN_CRYPT_STRING_HEXASCIIADDR = 11,
XCN_CRYPT_STRING_HEXRAW = 12,
XCN_CRYPT_STRING_NOCR = -2147483648,
XCN_CRYPT_STRING_NOCRLF = 0x40000000,
XCN_CRYPT_STRING_STRICT = 0x20000000
}
[ComImport, Guid("728AB307-217D-11DA-B2A4-000E7BBB2B09"), InterfaceType(ComInterfaceType.InterfaceIsDual), CompilerGenerated]
public interface ICspInformation
{
[DispId(0x60020000)]
void InitializeFromName([In, MarshalAs(UnmanagedType.BStr)] string strName);
}
[ComImport, Guid("728AB308-217D-11DA-B2A4-000E7BBB2B09"), CompilerGenerated, DefaultMember("ItemByIndex"), InterfaceType(ComInterfaceType.InterfaceIsDual)]
public interface ICspInformations : IEnumerable
{
void _VtblGap1_3();
[DispId(2)]
void Add([In, MarshalAs(UnmanagedType.Interface)] CCspInformation pVal);
}
public enum InstallResponseRestrictionFlags
{
AllowNone = 0,
AllowNoOutstandingRequest = 1,
AllowUntrustedCertificate = 2,
AllowUntrustedRoot = 4
}
[ComImport, InterfaceType(ComInterfaceType.InterfaceIsDual), Guid("728AB300-217D-11DA-B2A4-000E7BBB2B09"), CompilerGenerated]
public interface IObjectId
{
[DispId(0x60020000)]
void InitializeFromName([In] CERTENROLL_OBJECTID Name);
}
[ComImport, DefaultMember("ItemByIndex"), CompilerGenerated, InterfaceType(ComInterfaceType.InterfaceIsDual), Guid("728AB301-217D-11DA-B2A4-000E7BBB2B09")]
public interface IObjectIds : IEnumerable
{
void _VtblGap1_3();
[DispId(2)]
void Add([In, MarshalAs(UnmanagedType.Interface)] CObjectId pVal);
}
[ComImport, CompilerGenerated, Guid("728AB303-217D-11DA-B2A4-000E7BBB2B09"), InterfaceType(ComInterfaceType.InterfaceIsDual)]
public interface IX500DistinguishedName
{
void _VtblGap1_1();
[DispId(0x60020001)]
void Encode([In, MarshalAs(UnmanagedType.BStr)] string strName, [In, Optional] X500NameFlags NameFlags);
}
[ComImport, Guid("728AB341-217D-11DA-B2A4-000E7BBB2B09"), CompilerGenerated, InterfaceType(ComInterfaceType.InterfaceIsDual)]
public interface IX509CertificateRequest
{
}
[ComImport, Guid("728AB342-217D-11DA-B2A4-000E7BBB2B09"), InterfaceType(ComInterfaceType.InterfaceIsDual), CompilerGenerated]
public interface IX509CertificateRequestPkcs10 : IX509CertificateRequest
{
}
[ComImport, Guid("728AB35B-217D-11DA-B2A4-000E7BBB2B09"), CompilerGenerated, InterfaceType(ComInterfaceType.InterfaceIsDual)]
public interface IX509CertificateRequestPkcs10V2 : IX509CertificateRequestPkcs10, IX509CertificateRequest
{
void _VtblGap1_26();
[DispId(0x60030001)]
void InitializeFromPrivateKey([In] X509CertificateEnrollmentContext Context, [In, MarshalAs(UnmanagedType.Interface)] CX509PrivateKey pPrivateKey, [In, MarshalAs(UnmanagedType.BStr)] string strTemplateName);
void _VtblGap2_11();
CX500DistinguishedName Subject { [return: MarshalAs(UnmanagedType.Interface)] [DispId(0x6003000d)] get; [param: In, MarshalAs(UnmanagedType.Interface)] [DispId(0x6003000d)] set; }
void _VtblGap3_1();
bool SmimeCapabilities { [DispId(0x60030010)] get; [param: In] [DispId(0x60030010)] set; }
void _VtblGap4_4();
CX509Extensions X509Extensions { [return: MarshalAs(UnmanagedType.Interface)] [DispId(0x60030016)] get; }
}
[ComImport, Guid("728AB346-217D-11DA-B2A4-000E7BBB2B09"), CompilerGenerated, InterfaceType(ComInterfaceType.InterfaceIsDual)]
public interface IX509Enrollment
{
}
[ComImport, Guid("728AB350-217D-11DA-B2A4-000E7BBB2B09"), CompilerGenerated, InterfaceType(ComInterfaceType.InterfaceIsDual)]
public interface IX509Enrollment2 : IX509Enrollment
{
[DispId(0x60020000)]
void Initialize([In] X509CertificateEnrollmentContext Context);
void _VtblGap1_1();
[DispId(0x60020002)]
void InitializeFromRequest([In, MarshalAs(UnmanagedType.Interface)] IX509CertificateRequest pRequest);
[return: MarshalAs(UnmanagedType.BStr)]
[DispId(0x60020003)]
string CreateRequest([In, Optional] EncodingType Encoding);
void _VtblGap2_1();
[DispId(0x60020005)]
void InstallResponse([In] InstallResponseRestrictionFlags Restrictions, [In, MarshalAs(UnmanagedType.BStr)] string strResponse, [In] EncodingType Encoding, [In, MarshalAs(UnmanagedType.BStr)] string strPassword);
void _VtblGap3_11();
string CertificateFriendlyName { [return: MarshalAs(UnmanagedType.BStr)] [DispId(0x60020011)] get; [param: In, MarshalAs(UnmanagedType.BStr)] [DispId(0x60020011)] set; }
}
[ComImport, Guid("728AB30D-217D-11DA-B2A4-000E7BBB2B09"), CompilerGenerated, InterfaceType(ComInterfaceType.InterfaceIsDual)]
public interface IX509Extension
{
}
[ComImport, CompilerGenerated, Guid("728AB310-217D-11DA-B2A4-000E7BBB2B09"), InterfaceType(ComInterfaceType.InterfaceIsDual)]
public interface IX509ExtensionEnhancedKeyUsage : IX509Extension
{
void _VtblGap1_5();
[DispId(0x60030000)]
void InitializeEncode([In, MarshalAs(UnmanagedType.Interface)] CObjectIds pValue);
}
[ComImport, InterfaceType(ComInterfaceType.InterfaceIsDual), Guid("728AB30F-217D-11DA-B2A4-000E7BBB2B09"), CompilerGenerated]
public interface IX509ExtensionKeyUsage : IX509Extension
{
void _VtblGap1_5();
[DispId(0x60030000)]
void InitializeEncode([In] X509KeyUsageFlags UsageFlags);
}
[ComImport, InterfaceType(ComInterfaceType.InterfaceIsDual), DefaultMember("ItemByIndex"), Guid("728AB30E-217D-11DA-B2A4-000E7BBB2B09"), CompilerGenerated]
public interface IX509Extensions : IEnumerable
{
void _VtblGap1_3();
[DispId(2)]
void Add([In, MarshalAs(UnmanagedType.Interface)] CX509Extension pVal);
}
[ComImport, Guid("728AB30C-217D-11DA-B2A4-000E7BBB2B09"), InterfaceType(ComInterfaceType.InterfaceIsDual), CompilerGenerated]
public interface IX509PrivateKey
{
void _VtblGap1_1();
[DispId(0x60020001)]
void Create();
void _VtblGap2_12();
CCspInformations CspInformations { [return: MarshalAs(UnmanagedType.Interface)] [DispId(0x6002000e)] get; [param: In, MarshalAs(UnmanagedType.Interface)] [DispId(0x6002000e)] set; }
void _VtblGap3_10();
X509KeySpec KeySpec { [DispId(0x6002001a)] get; [param: In] [DispId(0x6002001a)] set; }
int Length { [DispId(0x6002001c)] get; [param: In] [DispId(0x6002001c)] set; }
X509PrivateKeyExportFlags ExportPolicy { [DispId(0x6002001e)] get; [param: In] [DispId(0x6002001e)] set; }
X509PrivateKeyUsageFlags KeyUsage { [DispId(0x60020020)] get; [param: In] [DispId(0x60020020)] set; }
void _VtblGap4_2();
bool MachineContext { [DispId(0x60020024)] get; [param: In] [DispId(0x60020024)] set; }
}
public enum X500NameFlags
{
XCN_CERT_NAME_STR_COMMA_FLAG = 0x4000000,
XCN_CERT_NAME_STR_CRLF_FLAG = 0x8000000,
XCN_CERT_NAME_STR_DISABLE_IE4_UTF8_FLAG = 0x10000,
XCN_CERT_NAME_STR_DISABLE_UTF8_DIR_STR_FLAG = 0x100000,
XCN_CERT_NAME_STR_ENABLE_PUNYCODE_FLAG = 0x200000,
XCN_CERT_NAME_STR_ENABLE_T61_UNICODE_FLAG = 0x20000,
XCN_CERT_NAME_STR_ENABLE_UTF8_UNICODE_FLAG = 0x40000,
XCN_CERT_NAME_STR_FORCE_UTF8_DIR_STR_FLAG = 0x80000,
XCN_CERT_NAME_STR_FORWARD_FLAG = 0x1000000,
XCN_CERT_NAME_STR_NO_PLUS_FLAG = 0x20000000,
XCN_CERT_NAME_STR_NO_QUOTING_FLAG = 0x10000000,
XCN_CERT_NAME_STR_NONE = 0,
XCN_CERT_NAME_STR_REVERSE_FLAG = 0x2000000,
XCN_CERT_NAME_STR_SEMICOLON_FLAG = 0x40000000,
XCN_CERT_OID_NAME_STR = 2,
XCN_CERT_SIMPLE_NAME_STR = 1,
XCN_CERT_X500_NAME_STR = 3,
XCN_CERT_XML_NAME_STR = 4
}
public enum X509CertificateEnrollmentContext
{
ContextAdministratorForceMachine = 3,
ContextMachine = 2,
ContextUser = 1
}
public enum X509KeySpec
{
XCN_AT_NONE,
XCN_AT_KEYEXCHANGE,
XCN_AT_SIGNATURE
}
public enum X509KeyUsageFlags
{
XCN_CERT_CRL_SIGN_KEY_USAGE = 2,
XCN_CERT_DATA_ENCIPHERMENT_KEY_USAGE = 0x10,
XCN_CERT_DECIPHER_ONLY_KEY_USAGE = 0x8000,
XCN_CERT_DIGITAL_SIGNATURE_KEY_USAGE = 0x80,
XCN_CERT_ENCIPHER_ONLY_KEY_USAGE = 1,
XCN_CERT_KEY_AGREEMENT_KEY_USAGE = 8,
XCN_CERT_KEY_CERT_SIGN_KEY_USAGE = 4,
XCN_CERT_KEY_ENCIPHERMENT_KEY_USAGE = 0x20,
XCN_CERT_NO_KEY_USAGE = 0,
XCN_CERT_NON_REPUDIATION_KEY_USAGE = 0x40,
XCN_CERT_OFFLINE_CRL_SIGN_KEY_USAGE = 2
}
public enum X509PrivateKeyExportFlags
{
XCN_NCRYPT_ALLOW_ARCHIVING_FLAG = 4,
XCN_NCRYPT_ALLOW_EXPORT_FLAG = 1,
XCN_NCRYPT_ALLOW_EXPORT_NONE = 0,
XCN_NCRYPT_ALLOW_PLAINTEXT_ARCHIVING_FLAG = 8,
XCN_NCRYPT_ALLOW_PLAINTEXT_EXPORT_FLAG = 2
}
public enum X509PrivateKeyUsageFlags
{
XCN_NCRYPT_ALLOW_ALL_USAGES = 0xffffff,
XCN_NCRYPT_ALLOW_DECRYPT_FLAG = 1,
XCN_NCRYPT_ALLOW_KEY_AGREEMENT_FLAG = 4,
XCN_NCRYPT_ALLOW_SIGNING_FLAG = 2,
XCN_NCRYPT_ALLOW_USAGES_NONE = 0
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Reflection;
using Xunit;
namespace System.Threading.Tasks.Tests
{
public class UnwrapTests
{
/// <summary>Tests unwrap argument validation.</summary>
[Fact]
public void ArgumentValidation()
{
Assert.Throws<ArgumentNullException>(() => { ((Task<Task>)null).Unwrap(); });
Assert.Throws<ArgumentNullException>(() => { ((Task<Task<int>>)null).Unwrap(); });
Assert.Throws<ArgumentNullException>(() => { ((Task<Task<string>>)null).Unwrap(); });
}
/// <summary>
/// Tests Unwrap when both the outer task and non-generic inner task have completed by the time Unwrap is called.
/// </summary>
/// <param name="inner">Will be run with a RanToCompletion, Faulted, and Canceled task.</param>
[Theory]
[MemberData(nameof(CompletedNonGenericTasks))]
public void NonGeneric_Completed_Completed(Task inner)
{
Task<Task> outer = Task.FromResult(inner);
Task unwrappedInner = outer.Unwrap();
Assert.True(unwrappedInner.IsCompleted);
AssertTasksAreEqual(inner, unwrappedInner);
}
/// <summary>
/// Tests Unwrap when both the outer task and non-generic inner task have completed by the time Unwrap is called.
/// </summary>
/// <param name="inner">Will be run with a RanToCompletion, Faulted, and Canceled task.</param>
[Theory]
[MemberData(nameof(CompletedNonGenericTasks))]
public void NonGeneric_Completed_Completed_OptimizeToUseSameInner(Task inner)
{
Task<Task> outer = Task.FromResult(inner);
Task unwrappedInner = outer.Unwrap();
Assert.True(unwrappedInner.IsCompleted);
Assert.Same(inner, unwrappedInner);
}
/// <summary>
/// Tests Unwrap when both the outer task and generic inner task have completed by the time Unwrap is called.
/// </summary>
/// <param name="inner">The inner task.</param>
[Theory]
[MemberData(nameof(CompletedStringTasks))]
public void Generic_Completed_Completed(Task<string> inner)
{
Task<Task<string>> outer = Task.FromResult(inner);
Task<string> unwrappedInner = outer.Unwrap();
Assert.True(unwrappedInner.IsCompleted);
AssertTasksAreEqual(inner, unwrappedInner);
}
/// <summary>
/// Tests Unwrap when both the outer task and generic inner task have completed by the time Unwrap is called.
/// </summary>
/// <param name="inner">The inner task.</param>
[Theory]
[MemberData(nameof(CompletedStringTasks))]
public void Generic_Completed_Completed_OptimizeToUseSameInner(Task<string> inner)
{
Task<Task<string>> outer = Task.FromResult(inner);
Task<string> unwrappedInner = outer.Unwrap();
Assert.True(unwrappedInner.IsCompleted);
Assert.Same(inner, unwrappedInner);
}
/// <summary>
/// Tests Unwrap when the non-generic inner task has completed but the outer task has not completed by the time Unwrap is called.
/// </summary>
/// <param name="inner">The inner task.</param>
[Theory]
[MemberData(nameof(CompletedNonGenericTasks))]
public void NonGeneric_NotCompleted_Completed(Task inner)
{
var outerTcs = new TaskCompletionSource<Task>();
Task<Task> outer = outerTcs.Task;
Task unwrappedInner = outer.Unwrap();
Assert.False(unwrappedInner.IsCompleted);
outerTcs.SetResult(inner);
AssertTasksAreEqual(inner, unwrappedInner);
}
/// <summary>
/// Tests Unwrap when the generic inner task has completed but the outer task has not completed by the time Unwrap is called.
/// </summary>
/// <param name="inner">The inner task.</param>
[Theory]
[MemberData(nameof(CompletedStringTasks))]
public void Generic_NotCompleted_Completed(Task<string> inner)
{
var outerTcs = new TaskCompletionSource<Task<string>>();
Task<Task<string>> outer = outerTcs.Task;
Task<string> unwrappedInner = outer.Unwrap();
Assert.False(unwrappedInner.IsCompleted);
outerTcs.SetResult(inner);
AssertTasksAreEqual(inner, unwrappedInner);
}
/// <summary>
/// Tests Unwrap when the non-generic inner task has not yet completed but the outer task has completed by the time Unwrap is called.
/// </summary>
/// <param name="innerStatus">How the inner task should be completed.</param>
[Theory]
[InlineData(TaskStatus.RanToCompletion)]
[InlineData(TaskStatus.Faulted)]
[InlineData(TaskStatus.Canceled)]
public void NonGeneric_Completed_NotCompleted(TaskStatus innerStatus)
{
var innerTcs = new TaskCompletionSource<bool>();
Task inner = innerTcs.Task;
Task<Task> outer = Task.FromResult(inner);
Task unwrappedInner = outer.Unwrap();
Assert.False(unwrappedInner.IsCompleted);
switch (innerStatus)
{
case TaskStatus.RanToCompletion:
innerTcs.SetResult(true);
break;
case TaskStatus.Faulted:
innerTcs.SetException(new InvalidProgramException());
break;
case TaskStatus.Canceled:
innerTcs.SetCanceled();
break;
}
AssertTasksAreEqual(inner, unwrappedInner);
}
/// <summary>
/// Tests Unwrap when the non-generic inner task has not yet completed but the outer task has completed by the time Unwrap is called.
/// </summary>
/// <param name="innerStatus">How the inner task should be completed.</param>
[Theory]
[InlineData(TaskStatus.RanToCompletion)]
[InlineData(TaskStatus.Faulted)]
[InlineData(TaskStatus.Canceled)]
public void Generic_Completed_NotCompleted(TaskStatus innerStatus)
{
var innerTcs = new TaskCompletionSource<int>();
Task<int> inner = innerTcs.Task;
Task<Task<int>> outer = Task.FromResult(inner);
Task<int> unwrappedInner = outer.Unwrap();
Assert.False(unwrappedInner.IsCompleted);
switch (innerStatus)
{
case TaskStatus.RanToCompletion:
innerTcs.SetResult(42);
break;
case TaskStatus.Faulted:
innerTcs.SetException(new InvalidProgramException());
break;
case TaskStatus.Canceled:
innerTcs.SetCanceled();
break;
}
AssertTasksAreEqual(inner, unwrappedInner);
}
/// <summary>
/// Tests Unwrap when neither the non-generic inner task nor the outer task has completed by the time Unwrap is called.
/// </summary>
/// <param name="outerCompletesFirst">Whether the outer task or the inner task completes first.</param>
/// <param name="innerStatus">How the inner task should be completed.</param>
[Theory]
[InlineData(true, TaskStatus.RanToCompletion)]
[InlineData(true, TaskStatus.Canceled)]
[InlineData(true, TaskStatus.Faulted)]
[InlineData(false, TaskStatus.RanToCompletion)]
[InlineData(false, TaskStatus.Canceled)]
[InlineData(false, TaskStatus.Faulted)]
public void NonGeneric_NotCompleted_NotCompleted(bool outerCompletesFirst, TaskStatus innerStatus)
{
var innerTcs = new TaskCompletionSource<bool>();
Task inner = innerTcs.Task;
var outerTcs = new TaskCompletionSource<Task>();
Task<Task> outer = outerTcs.Task;
Task unwrappedInner = outer.Unwrap();
Assert.False(unwrappedInner.IsCompleted);
if (outerCompletesFirst)
{
outerTcs.SetResult(inner);
Assert.False(unwrappedInner.IsCompleted);
}
switch (innerStatus)
{
case TaskStatus.RanToCompletion:
innerTcs.SetResult(true);
break;
case TaskStatus.Faulted:
innerTcs.SetException(new InvalidOperationException());
break;
case TaskStatus.Canceled:
innerTcs.TrySetCanceled(CreateCanceledToken());
break;
}
if (!outerCompletesFirst)
{
Assert.False(unwrappedInner.IsCompleted);
outerTcs.SetResult(inner);
}
AssertTasksAreEqual(inner, unwrappedInner);
}
/// <summary>
/// Tests Unwrap when neither the generic inner task nor the outer task has completed by the time Unwrap is called.
/// </summary>
/// <param name="outerCompletesFirst">Whether the outer task or the inner task completes first.</param>
/// <param name="innerStatus">How the inner task should be completed.</param>
[Theory]
[InlineData(true, TaskStatus.RanToCompletion)]
[InlineData(true, TaskStatus.Canceled)]
[InlineData(true, TaskStatus.Faulted)]
[InlineData(false, TaskStatus.RanToCompletion)]
[InlineData(false, TaskStatus.Canceled)]
[InlineData(false, TaskStatus.Faulted)]
public void Generic_NotCompleted_NotCompleted(bool outerCompletesFirst, TaskStatus innerStatus)
{
var innerTcs = new TaskCompletionSource<int>();
Task<int> inner = innerTcs.Task;
var outerTcs = new TaskCompletionSource<Task<int>>();
Task<Task<int>> outer = outerTcs.Task;
Task<int> unwrappedInner = outer.Unwrap();
Assert.False(unwrappedInner.IsCompleted);
if (outerCompletesFirst)
{
outerTcs.SetResult(inner);
Assert.False(unwrappedInner.IsCompleted);
}
switch (innerStatus)
{
case TaskStatus.RanToCompletion:
innerTcs.SetResult(42);
break;
case TaskStatus.Faulted:
innerTcs.SetException(new InvalidOperationException());
break;
case TaskStatus.Canceled:
innerTcs.TrySetCanceled(CreateCanceledToken());
break;
}
if (!outerCompletesFirst)
{
Assert.False(unwrappedInner.IsCompleted);
outerTcs.SetResult(inner);
}
AssertTasksAreEqual(inner, unwrappedInner);
}
/// <summary>
/// Tests Unwrap when the outer task for a non-generic inner fails in some way.
/// </summary>
/// <param name="outerCompletesFirst">Whether the outer task completes before Unwrap is called.</param>
/// <param name="outerStatus">How the outer task should be completed (RanToCompletion means returning null).</param>
[Theory]
[InlineData(true, TaskStatus.RanToCompletion)]
[InlineData(true, TaskStatus.Faulted)]
[InlineData(true, TaskStatus.Canceled)]
[InlineData(false, TaskStatus.RanToCompletion)]
[InlineData(false, TaskStatus.Faulted)]
[InlineData(false, TaskStatus.Canceled)]
public void NonGeneric_UnsuccessfulOuter(bool outerCompletesBeforeUnwrap, TaskStatus outerStatus)
{
var outerTcs = new TaskCompletionSource<Task>();
Task<Task> outer = outerTcs.Task;
Task unwrappedInner = null;
if (!outerCompletesBeforeUnwrap)
unwrappedInner = outer.Unwrap();
switch (outerStatus)
{
case TaskStatus.RanToCompletion:
outerTcs.SetResult(null);
break;
case TaskStatus.Canceled:
outerTcs.TrySetCanceled(CreateCanceledToken());
break;
case TaskStatus.Faulted:
outerTcs.SetException(new InvalidCastException());
break;
}
if (outerCompletesBeforeUnwrap)
unwrappedInner = outer.Unwrap();
WaitNoThrow(unwrappedInner);
switch (outerStatus)
{
case TaskStatus.RanToCompletion:
Assert.True(unwrappedInner.IsCanceled);
break;
default:
AssertTasksAreEqual(outer, unwrappedInner);
break;
}
}
/// <summary>
/// Tests Unwrap when the outer task for a generic inner fails in some way.
/// </summary>
/// <param name="outerCompletesFirst">Whether the outer task completes before Unwrap is called.</param>
/// <param name="outerStatus">How the outer task should be completed (RanToCompletion means returning null).</param>
[Theory]
[InlineData(true, TaskStatus.RanToCompletion)]
[InlineData(true, TaskStatus.Faulted)]
[InlineData(true, TaskStatus.Canceled)]
[InlineData(false, TaskStatus.RanToCompletion)]
[InlineData(false, TaskStatus.Faulted)]
[InlineData(false, TaskStatus.Canceled)]
public void Generic_UnsuccessfulOuter(bool outerCompletesBeforeUnwrap, TaskStatus outerStatus)
{
var outerTcs = new TaskCompletionSource<Task<int>>();
Task<Task<int>> outer = outerTcs.Task;
Task<int> unwrappedInner = null;
if (!outerCompletesBeforeUnwrap)
unwrappedInner = outer.Unwrap();
switch (outerStatus)
{
case TaskStatus.RanToCompletion:
outerTcs.SetResult(null); // cancellation
break;
case TaskStatus.Canceled:
outerTcs.TrySetCanceled(CreateCanceledToken());
break;
case TaskStatus.Faulted:
outerTcs.SetException(new InvalidCastException());
break;
}
if (outerCompletesBeforeUnwrap)
unwrappedInner = outer.Unwrap();
WaitNoThrow(unwrappedInner);
switch (outerStatus)
{
case TaskStatus.RanToCompletion:
Assert.True(unwrappedInner.IsCanceled);
break;
default:
AssertTasksAreEqual(outer, unwrappedInner);
break;
}
}
/// <summary>
/// Test Unwrap when the outer task for a non-generic inner task is marked as AttachedToParent.
/// </summary>
[Fact]
public void NonGeneric_AttachedToParent()
{
Exception error = new InvalidTimeZoneException();
Task parent = Task.Factory.StartNew(() =>
{
var outerTcs = new TaskCompletionSource<Task>(TaskCreationOptions.AttachedToParent);
Task<Task> outer = outerTcs.Task;
Task inner = Task.FromException(error);
Task unwrappedInner = outer.Unwrap();
Assert.Equal(TaskCreationOptions.AttachedToParent, unwrappedInner.CreationOptions);
outerTcs.SetResult(inner);
AssertTasksAreEqual(inner, unwrappedInner);
}, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default);
WaitNoThrow(parent);
Assert.Equal(TaskStatus.Faulted, parent.Status);
Assert.Same(error, parent.Exception.Flatten().InnerException);
}
/// <summary>
/// Test Unwrap when the outer task for a generic inner task is marked as AttachedToParent.
/// </summary>
[Fact]
public void Generic_AttachedToParent()
{
Exception error = new InvalidTimeZoneException();
Task parent = Task.Factory.StartNew(() =>
{
var outerTcs = new TaskCompletionSource<Task<object>>(TaskCreationOptions.AttachedToParent);
Task<Task<object>> outer = outerTcs.Task;
Task<object> inner = Task.FromException<object>(error);
Task<object> unwrappedInner = outer.Unwrap();
Assert.Equal(TaskCreationOptions.AttachedToParent, unwrappedInner.CreationOptions);
outerTcs.SetResult(inner);
AssertTasksAreEqual(inner, unwrappedInner);
}, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default);
WaitNoThrow(parent);
Assert.Equal(TaskStatus.Faulted, parent.Status);
Assert.Same(error, parent.Exception.Flatten().InnerException);
}
/// <summary>
/// Test that Unwrap with a non-generic task doesn't use TaskScheduler.Current.
/// </summary>
[Fact]
public void NonGeneric_DefaultSchedulerUsed()
{
var scheduler = new CountingScheduler();
Task.Factory.StartNew(() =>
{
int initialCallCount = scheduler.QueueTaskCalls;
Task<Task> outer = Task.Factory.StartNew(() => Task.Run(() => { }),
CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default);
Task unwrappedInner = outer.Unwrap();
unwrappedInner.Wait();
Assert.Equal(initialCallCount, scheduler.QueueTaskCalls);
}, CancellationToken.None, TaskCreationOptions.None, scheduler).GetAwaiter().GetResult();
}
/// <summary>
/// Test that Unwrap with a generic task doesn't use TaskScheduler.Current.
/// </summary>
[Fact]
public void Generic_DefaultSchedulerUsed()
{
var scheduler = new CountingScheduler();
Task.Factory.StartNew(() =>
{
int initialCallCount = scheduler.QueueTaskCalls;
Task<Task<int>> outer = Task.Factory.StartNew(() => Task.Run(() => 42),
CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default);
Task<int> unwrappedInner = outer.Unwrap();
unwrappedInner.Wait();
Assert.Equal(initialCallCount, scheduler.QueueTaskCalls);
}, CancellationToken.None, TaskCreationOptions.None, scheduler).GetAwaiter().GetResult();
}
/// <summary>
/// Test that a long chain of Unwraps can execute without overflowing the stack.
/// </summary>
[Fact]
public void RunStackGuardTests()
{
const int DiveDepth = 12000;
Func<int, Task<int>> func = null;
func = count =>
++count < DiveDepth ?
Task.Factory.StartNew(() => func(count), CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap() :
Task.FromResult(count);
// This test will overflow if it fails.
Assert.Equal(DiveDepth, func(0).Result);
}
/// <summary>Gets an enumerable of already completed non-generic tasks.</summary>
public static IEnumerable<object[]> CompletedNonGenericTasks
{
get
{
yield return new object[] { Task.CompletedTask };
yield return new object[] { Task.FromCanceled(CreateCanceledToken()) };
yield return new object[] { Task.FromException(new FormatException()) };
var tcs = new TaskCompletionSource<int>();
tcs.SetCanceled(); // cancel task without a token
yield return new object[] { tcs.Task };
}
}
/// <summary>Gets an enumerable of already completed generic tasks.</summary>
public static IEnumerable<object[]> CompletedStringTasks
{
get
{
yield return new object[] { Task.FromResult("Tasks") };
yield return new object[] { Task.FromCanceled<string>(CreateCanceledToken()) };
yield return new object[] { Task.FromException<string>(new FormatException()) };
var tcs = new TaskCompletionSource<string>();
tcs.SetCanceled(); // cancel task without a token
yield return new object[] { tcs.Task };
}
}
/// <summary>Asserts that two non-generic tasks are logically equal with regards to completion status.</summary>
private static void AssertTasksAreEqual(Task expected, Task actual)
{
Assert.NotNull(actual);
WaitNoThrow(actual);
Assert.Equal(expected.Status, actual.Status);
switch (expected.Status)
{
case TaskStatus.Faulted:
Assert.Equal((IEnumerable<Exception>)expected.Exception.InnerExceptions, actual.Exception.InnerExceptions);
break;
case TaskStatus.Canceled:
Assert.Equal(GetCanceledTaskToken(expected), GetCanceledTaskToken(actual));
break;
}
}
/// <summary>Asserts that two non-generic tasks are logically equal with regards to completion status.</summary>
private static void AssertTasksAreEqual<T>(Task<T> expected, Task<T> actual)
{
AssertTasksAreEqual((Task)expected, actual);
if (expected.Status == TaskStatus.RanToCompletion)
{
if (typeof(T).GetTypeInfo().IsValueType)
Assert.Equal(expected.Result, actual.Result);
else
Assert.Same((object)expected.Result, (object)actual.Result);
}
}
/// <summary>Creates an already canceled token.</summary>
private static CancellationToken CreateCanceledToken()
{
// Create an already canceled token. We construct a new CTS rather than
// just using CT's Boolean ctor in order to better validate the right
// token ends up in the resulting unwrapped task.
var cts = new CancellationTokenSource();
cts.Cancel();
return cts.Token;
}
/// <summary>Waits for a task to complete without throwing any exceptions.</summary>
private static void WaitNoThrow(Task task)
{
((IAsyncResult)task).AsyncWaitHandle.WaitOne();
}
/// <summary>Extracts the CancellationToken associated with a task.</summary>
private static CancellationToken GetCanceledTaskToken(Task task)
{
Assert.True(task.IsCanceled);
try
{
task.GetAwaiter().GetResult();
Assert.False(true, "Canceled task should have thrown from GetResult");
return default(CancellationToken);
}
catch (OperationCanceledException oce)
{
return oce.CancellationToken;
}
}
private sealed class CountingScheduler : TaskScheduler
{
public int QueueTaskCalls = 0;
protected override void QueueTask(Task task)
{
Interlocked.Increment(ref QueueTaskCalls);
Task.Run(() => TryExecuteTask(task));
}
protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued) { return false; }
protected override IEnumerable<Task> GetScheduledTasks() { return null; }
}
}
}
| |
using System;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Orleans;
using Orleans.Internal;
using Orleans.Runtime;
using Orleans.Streams;
using Orleans.TestingHost.Utils;
using Tester;
using TestExtensions;
using UnitTests.GrainInterfaces;
using UnitTests.Grains;
using Xunit;
namespace UnitTests.StreamingTests
{
public class SingleStreamTestRunner
{
public const string SMS_STREAM_PROVIDER_NAME = StreamTestsConstants.SMS_STREAM_PROVIDER_NAME;
public const string SMS_STREAM_PROVIDER_NAME_DO_NOT_OPTIMIZE_FOR_IMMUTABLE_DATA = "SMSProviderDoNotOptimizeForImmutableData";
public const string AQ_STREAM_PROVIDER_NAME = StreamTestsConstants.AZURE_QUEUE_STREAM_PROVIDER_NAME;
private static readonly TimeSpan _timeout = TimeSpan.FromSeconds(30);
private ProducerProxy producer;
private ConsumerProxy consumer;
private const int Many = 3;
private const int ItemCount = 10;
private ILogger logger;
private readonly string streamProviderName;
private readonly int testNumber;
private readonly bool runFullTest;
private readonly SafeRandom random;
private readonly IInternalClusterClient client;
internal SingleStreamTestRunner(IInternalClusterClient client, string streamProvider, int testNum = 0, bool fullTest = true)
{
this.client = client;
this.streamProviderName = streamProvider;
this.logger = TestingUtils.CreateDefaultLoggerFactory($"{this.GetType().Name}.log").CreateLogger<SingleStreamTestRunner>();
this.testNumber = testNum;
this.runFullTest = fullTest;
this.random = TestConstants.random;
}
private void Heading(string testName)
{
logger.Info("\n\n************************ {0} {1}_{2} ********************************* \n\n", testNumber, streamProviderName, testName);
}
//------------------------ One to One ----------------------//
public async Task StreamTest_01_OneProducerGrainOneConsumerGrain()
{
Heading("StreamTest_01_ConsumerJoinsFirstProducerLater");
Guid streamId = Guid.NewGuid();
// consumer joins first, producer later
this.consumer = await ConsumerProxy.NewConsumerGrainsAsync(streamId, this.streamProviderName, this.logger, this.client);
this.producer = await ProducerProxy.NewProducerGrainsAsync(streamId, this.streamProviderName, null, this.logger, this.client);
await BasicTestAsync();
await StopProxies();
streamId = Guid.NewGuid();
// produce joins first, consumer later
this.producer = await ProducerProxy.NewProducerGrainsAsync(streamId, this.streamProviderName, null, this.logger, this.client);
this.consumer = await ConsumerProxy.NewConsumerGrainsAsync(streamId, this.streamProviderName, this.logger, this.client);
await BasicTestAsync();
await StopProxies();
}
public async Task StreamTest_02_OneProducerGrainOneConsumerClient()
{
Heading("StreamTest_02_OneProducerGrainOneConsumerClient");
Guid streamId = Guid.NewGuid();
consumer = await ConsumerProxy.NewConsumerClientObjectsAsync(streamId, streamProviderName, logger, this.client);
this.producer = await ProducerProxy.NewProducerGrainsAsync(streamId, this.streamProviderName, null, this.logger, this.client);
await BasicTestAsync();
await StopProxies();
streamId = Guid.NewGuid();
this.producer = await ProducerProxy.NewProducerGrainsAsync(streamId, this.streamProviderName, null, this.logger, this.client);
consumer = await ConsumerProxy.NewConsumerClientObjectsAsync(streamId, streamProviderName, logger, this.client);
await BasicTestAsync();
await StopProxies();
}
public async Task StreamTest_03_OneProducerClientOneConsumerGrain()
{
Heading("StreamTest_03_OneProducerClientOneConsumerGrain");
Guid streamId = Guid.NewGuid();
this.consumer = await ConsumerProxy.NewConsumerGrainsAsync(streamId, this.streamProviderName, this.logger, this.client);
producer = await ProducerProxy.NewProducerClientObjectsAsync(streamId, streamProviderName, null, logger, this.client);
await BasicTestAsync();
await StopProxies();
streamId = Guid.NewGuid();
producer = await ProducerProxy.NewProducerClientObjectsAsync(streamId, streamProviderName, null, logger, this.client);
this.consumer = await ConsumerProxy.NewConsumerGrainsAsync(streamId, this.streamProviderName, this.logger, this.client);
await BasicTestAsync();
await StopProxies();
}
public async Task StreamTest_04_OneProducerClientOneConsumerClient()
{
Heading("StreamTest_04_OneProducerClientOneConsumerClient");
Guid streamId = Guid.NewGuid();
consumer = await ConsumerProxy.NewConsumerClientObjectsAsync(streamId, streamProviderName, logger, this.client);
producer = await ProducerProxy.NewProducerClientObjectsAsync(streamId, streamProviderName, null, logger, this.client);
await BasicTestAsync();
await StopProxies();
streamId = Guid.NewGuid();
producer = await ProducerProxy.NewProducerClientObjectsAsync(streamId, streamProviderName, null, logger, this.client);
consumer = await ConsumerProxy.NewConsumerClientObjectsAsync(streamId, streamProviderName, logger, this.client);
await BasicTestAsync();
await StopProxies();
}
//------------------------ MANY to Many different grains ----------------------//
public async Task StreamTest_05_ManyDifferent_ManyProducerGrainsManyConsumerGrains()
{
Heading("StreamTest_05_ManyDifferent_ManyProducerGrainsManyConsumerGrains");
Guid streamId = Guid.NewGuid();
this.consumer = await ConsumerProxy.NewConsumerGrainsAsync(streamId, this.streamProviderName, this.logger, this.client, null, Many);
this.producer = await ProducerProxy.NewProducerGrainsAsync(streamId, this.streamProviderName, null, this.logger, this.client, null, Many);
await BasicTestAsync();
await StopProxies();
}
public async Task StreamTest_06_ManyDifferent_ManyProducerGrainManyConsumerClients()
{
Heading("StreamTest_06_ManyDifferent_ManyProducerGrainManyConsumerClients");
Guid streamId = Guid.NewGuid();
consumer = await ConsumerProxy.NewConsumerClientObjectsAsync(streamId, streamProviderName, logger, this.client, Many);
this.producer = await ProducerProxy.NewProducerGrainsAsync(streamId, this.streamProviderName, null, this.logger, this.client, null, Many);
await BasicTestAsync();
await StopProxies();
}
public async Task StreamTest_07_ManyDifferent_ManyProducerClientsManyConsumerGrains()
{
Heading("StreamTest_07_ManyDifferent_ManyProducerClientsManyConsumerGrains");
Guid streamId = Guid.NewGuid();
this.consumer = await ConsumerProxy.NewConsumerGrainsAsync(streamId, this.streamProviderName, this.logger, this.client, null, Many);
producer = await ProducerProxy.NewProducerClientObjectsAsync(streamId, streamProviderName, null, logger, this.client, Many);
await BasicTestAsync();
await StopProxies();
}
public async Task StreamTest_08_ManyDifferent_ManyProducerClientsManyConsumerClients()
{
Heading("StreamTest_08_ManyDifferent_ManyProducerClientsManyConsumerClients");
Guid streamId = Guid.NewGuid();
consumer = await ConsumerProxy.NewConsumerClientObjectsAsync(streamId, streamProviderName, logger, this.client, Many);
producer = await ProducerProxy.NewProducerClientObjectsAsync(streamId, streamProviderName, null, logger, this.client, Many);
await BasicTestAsync();
await StopProxies();
}
//------------------------ MANY to Many Same grains ----------------------//
public async Task StreamTest_09_ManySame_ManyProducerGrainsManyConsumerGrains()
{
Heading("StreamTest_09_ManySame_ManyProducerGrainsManyConsumerGrains");
Guid streamId = Guid.NewGuid();
Guid grain1 = Guid.NewGuid();
Guid grain2 = Guid.NewGuid();
Guid[] consumerGrainIds = new Guid[] { grain1, grain1, grain1 };
Guid[] producerGrainIds = new Guid[] { grain2, grain2, grain2 };
// producer joins first, consumer later
this.producer = await ProducerProxy.NewProducerGrainsAsync(streamId, this.streamProviderName, null, this.logger, this.client, producerGrainIds);
this.consumer = await ConsumerProxy.NewConsumerGrainsAsync(streamId, this.streamProviderName, this.logger, this.client, consumerGrainIds);
await BasicTestAsync();
await StopProxies();
}
public async Task StreamTest_10_ManySame_ManyConsumerGrainsManyProducerGrains()
{
Heading("StreamTest_10_ManySame_ManyConsumerGrainsManyProducerGrains");
Guid streamId = Guid.NewGuid();
Guid grain1 = Guid.NewGuid();
Guid grain2 = Guid.NewGuid();
Guid[] consumerGrainIds = new Guid[] { grain1, grain1, grain1 };
Guid[] producerGrainIds = new Guid[] { grain2, grain2, grain2 };
// consumer joins first, producer later
this.consumer = await ConsumerProxy.NewConsumerGrainsAsync(streamId, this.streamProviderName, this.logger, this.client, consumerGrainIds);
this.producer = await ProducerProxy.NewProducerGrainsAsync(streamId, this.streamProviderName, null, this.logger, this.client, producerGrainIds);
await BasicTestAsync();
await StopProxies();
}
public async Task StreamTest_11_ManySame_ManyProducerGrainsManyConsumerClients()
{
Heading("StreamTest_11_ManySame_ManyProducerGrainsManyConsumerClients");
Guid streamId = Guid.NewGuid();
Guid grain1 = Guid.NewGuid();
Guid[] producerGrainIds = new Guid[] { grain1, grain1, grain1, grain1 };
this.producer = await ProducerProxy.NewProducerGrainsAsync(streamId, this.streamProviderName, null, this.logger, this.client, producerGrainIds);
consumer = await ConsumerProxy.NewConsumerClientObjectsAsync(streamId, streamProviderName, logger, this.client, Many);
await BasicTestAsync();
await StopProxies();
}
public async Task StreamTest_12_ManySame_ManyProducerClientsManyConsumerGrains()
{
Heading("StreamTest_12_ManySame_ManyProducerClientsManyConsumerGrains");
Guid streamId = Guid.NewGuid();
Guid grain1 = Guid.NewGuid();
Guid[] consumerGrainIds = new Guid[] { grain1, grain1, grain1 };
this.consumer = await ConsumerProxy.NewConsumerGrainsAsync(streamId, this.streamProviderName, this.logger, this.client, consumerGrainIds);
producer = await ProducerProxy.NewProducerClientObjectsAsync(streamId, streamProviderName, null, logger, this.client, Many);
await BasicTestAsync();
await StopProxies();
}
//------------------------ MANY to Many producer consumer same grain ----------------------//
public async Task StreamTest_13_SameGrain_ConsumerFirstProducerLater(bool useReentrantGrain)
{
Heading("StreamTest_13_SameGrain_ConsumerFirstProducerLater");
Guid streamId = Guid.NewGuid();
int grain1 = random.Next();
int[] grainIds = new int[] { grain1 };
// consumer joins first, producer later
this.consumer = await ConsumerProxy.NewProducerConsumerGrainsAsync(streamId, this.streamProviderName, this.logger, grainIds, useReentrantGrain, this.client);
this.producer = await ProducerProxy.NewProducerConsumerGrainsAsync(streamId, this.streamProviderName, this.logger, grainIds, useReentrantGrain, this.client);
await BasicTestAsync();
await StopProxies();
}
public async Task StreamTest_14_SameGrain_ProducerFirstConsumerLater(bool useReentrantGrain)
{
Heading("StreamTest_14_SameGrain_ProducerFirstConsumerLater");
Guid streamId = Guid.NewGuid();
int grain1 = random.Next();
int[] grainIds = new int[] { grain1 };
// produce joins first, consumer later
this.producer = await ProducerProxy.NewProducerConsumerGrainsAsync(streamId, this.streamProviderName, this.logger, grainIds, useReentrantGrain, this.client);
this.consumer = await ConsumerProxy.NewProducerConsumerGrainsAsync(streamId, this.streamProviderName, this.logger, grainIds, useReentrantGrain, this.client);
await BasicTestAsync();
await StopProxies();
}
//----------------------------------------------//
public async Task StreamTest_15_ConsumeAtProducersRequest()
{
Heading("StreamTest_15_ConsumeAtProducersRequest");
Guid streamId = Guid.NewGuid();
// this reproduces a scenario was discovered to not work (deadlock) by the Halo team. the scenario is that
// where a producer calls a consumer, which subscribes to the calling producer.
this.producer = await ProducerProxy.NewProducerGrainsAsync(streamId, this.streamProviderName, null, this.logger, this.client);
Guid consumerGrainId = await producer.AddNewConsumerGrain();
this.consumer = ConsumerProxy.NewConsumerGrainAsync_WithoutBecomeConsumer(consumerGrainId, this.logger, this.client);
await BasicTestAsync();
await StopProxies();
}
internal async Task StreamTest_Create_OneProducerGrainOneConsumerGrain()
{
Guid streamId = Guid.NewGuid();
this.consumer = await ConsumerProxy.NewConsumerGrainsAsync(streamId, this.streamProviderName, this.logger, this.client);
this.producer = await ProducerProxy.NewProducerGrainsAsync(streamId, this.streamProviderName, null, this.logger, this.client);
}
public async Task StreamTest_16_Deactivation_OneProducerGrainOneConsumerGrain()
{
Heading("StreamTest_16_Deactivation_OneProducerGrainOneConsumerGrain");
Guid streamId = Guid.NewGuid();
Guid[] consumerGrainIds = { Guid.NewGuid() };
Guid[] producerGrainIds = { Guid.NewGuid() };
// consumer joins first, producer later
this.consumer = await ConsumerProxy.NewConsumerGrainsAsync(streamId, this.streamProviderName, this.logger, this.client, consumerGrainIds);
this.producer = await ProducerProxy.NewProducerGrainsAsync(streamId, this.streamProviderName, null, this.logger, this.client, producerGrainIds);
await BasicTestAsync(false);
//await consumer.StopBeingConsumer();
await StopProxies();
await consumer.DeactivateOnIdle();
await producer.DeactivateOnIdle();
await TestingUtils.WaitUntilAsync(lastTry => CheckGrainsDeactivated(null, consumer, false), _timeout);
await TestingUtils.WaitUntilAsync(lastTry => CheckGrainsDeactivated(producer, null, false), _timeout);
logger.Info("\n\n\n*******************************************************************\n\n\n");
this.consumer = await ConsumerProxy.NewConsumerGrainsAsync(streamId, this.streamProviderName, this.logger, this.client, consumerGrainIds);
this.producer = await ProducerProxy.NewProducerGrainsAsync(streamId, this.streamProviderName, null, this.logger, this.client, producerGrainIds);
await BasicTestAsync(false);
await StopProxies();
}
//public async Task StreamTest_17_Persistence_OneProducerGrainOneConsumerGrain()
//{
// Heading("StreamTest_17_Persistence_OneProducerGrainOneConsumerGrain");
// StreamId streamId = StreamId.NewRandomStreamId();
// // consumer joins first, producer later
// consumer = await ConsumerProxy.NewConsumerGrainsAsync(streamId, streamProviderName, logger);
// producer = await ProducerProxy.NewProducerGrainsAsync(streamId, streamProviderName, logger);
// await BasicTestAsync(false);
// await consumer.DeactivateOnIdle();
// await producer.DeactivateOnIdle();
// await UnitTestBase.WaitUntilAsync(() => CheckGrainsDeactivated(null, consumer, assertAreEqual: false), _timeout);
// await UnitTestBase.WaitUntilAsync(() => CheckGrainsDeactivated(producer, null, assertAreEqual: false), _timeout);
// logger.Info("*******************************************************************");
// //await BasicTestAsync(false);
// //await StopProxies();
//}
public async Task StreamTest_19_ConsumerImplicitlySubscribedToProducerClient()
{
Heading("StreamTest_19_ConsumerImplicitlySubscribedToProducerClient");
string consumerTypeName = typeof(Streaming_ImplicitlySubscribedConsumerGrain).FullName;
Guid streamGuid = Guid.NewGuid();
producer = await ProducerProxy.NewProducerClientObjectsAsync(streamGuid, streamProviderName, "TestNamespace1", logger, this.client);
this.consumer = ConsumerProxy.NewConsumerGrainAsync_WithoutBecomeConsumer(streamGuid, this.logger, this.client, consumerTypeName);
logger.Info("\n** Starting Test {0}.\n", testNumber);
var producerCount = await producer.ProducerCount;
logger.Info("\n** Test {0} BasicTestAsync: producerCount={1}.\n", testNumber, producerCount);
Func<bool, Task<bool>> waitUntilFunc =
async lastTry =>
0 < await TestUtils.GetActivationCount(this.client, consumerTypeName) && await this.CheckCounters(this.producer, this.consumer, false);
await producer.ProduceSequentialSeries(ItemCount);
await TestingUtils.WaitUntilAsync(waitUntilFunc, _timeout);
await CheckCounters(producer, consumer);
await StopProxies();
}
public async Task StreamTest_20_ConsumerImplicitlySubscribedToProducerGrain()
{
Heading("StreamTest_20_ConsumerImplicitlySubscribedToProducerGrain");
string consumerTypeName = typeof(Streaming_ImplicitlySubscribedConsumerGrain).FullName;
Guid streamGuid = Guid.NewGuid();
this.producer = await ProducerProxy.NewProducerGrainsAsync(streamGuid, this.streamProviderName, "TestNamespace1", this.logger, this.client);
this.consumer = ConsumerProxy.NewConsumerGrainAsync_WithoutBecomeConsumer(streamGuid, this.logger, this.client, consumerTypeName);
logger.Info("\n** Starting Test {0}.\n", testNumber);
var producerCount = await producer.ProducerCount;
logger.Info("\n** Test {0} BasicTestAsync: producerCount={1}.\n", testNumber, producerCount);
Func<bool, Task<bool>> waitUntilFunc =
async lastTry =>
0 < await TestUtils.GetActivationCount(this.client, consumerTypeName) && await this.CheckCounters(this.producer, this.consumer, false);
await producer.ProduceSequentialSeries(ItemCount);
await TestingUtils.WaitUntilAsync(waitUntilFunc, _timeout);
await CheckCounters(producer, consumer);
await StopProxies();
}
public async Task StreamTest_21_GenericConsumerImplicitlySubscribedToProducerGrain()
{
Heading("StreamTest_21_GenericConsumerImplicitlySubscribedToProducerGrain");
//ToDo in migrate: the following consumer grain is not implemented in VSO and all tests depend on it fail.
string consumerTypeName = "UnitTests.Grains.Streaming_ImplicitlySubscribedGenericConsumerGrain";//typeof(Streaming_ImplicitlySubscribedGenericConsumerGrain).FullName;
Guid streamGuid = Guid.NewGuid();
this.producer = await ProducerProxy.NewProducerGrainsAsync(streamGuid, this.streamProviderName, "TestNamespace1", this.logger, this.client);
this.consumer = ConsumerProxy.NewConsumerGrainAsync_WithoutBecomeConsumer(streamGuid, this.logger, this.client, consumerTypeName);
logger.Info("\n** Starting Test {0}.\n", testNumber);
var producerCount = await producer.ProducerCount;
logger.Info("\n** Test {0} BasicTestAsync: producerCount={1}.\n", testNumber, producerCount);
Func<bool, Task<bool>> waitUntilFunc =
async lastTry =>
0 < await TestUtils.GetActivationCount(this.client, consumerTypeName) && await this.CheckCounters(this.producer, this.consumer, false);
await producer.ProduceSequentialSeries(ItemCount);
await TestingUtils.WaitUntilAsync(waitUntilFunc, _timeout);
await CheckCounters(producer, consumer);
await StopProxies();
}
public async Task StreamTest_22_TestImmutabilityDuringStreaming()
{
Heading("StreamTest_22_TestImmutabilityDuringStreaming");
IStreamingImmutabilityTestGrain itemProducer = this.client.GetGrain<IStreamingImmutabilityTestGrain>(Guid.NewGuid());
string producerSilo = await itemProducer.GetSiloIdentifier();
// Obtain consumer in silo of item producer
IStreamingImmutabilityTestGrain consumerSameSilo = null;
do
{
var itemConsumer = this.client.GetGrain<IStreamingImmutabilityTestGrain>(Guid.NewGuid());
var consumerSilo = await itemConsumer.GetSiloIdentifier();
if (consumerSilo == producerSilo)
consumerSameSilo = itemConsumer;
} while (consumerSameSilo == null);
// Test behavior if immutability is enabled
await consumerSameSilo.SubscribeToStream(itemProducer.GetPrimaryKey(), SMS_STREAM_PROVIDER_NAME);
await itemProducer.SetTestObjectStringProperty("VALUE_IN_IMMUTABLE_STREAM");
await itemProducer.SendTestObject(SMS_STREAM_PROVIDER_NAME);
Assert.Equal("VALUE_IN_IMMUTABLE_STREAM", await consumerSameSilo.GetTestObjectStringProperty());
// Now violate immutability by updating the property in the consumer.
await consumerSameSilo.SetTestObjectStringProperty("ILLEGAL_CHANGE");
Assert.Equal("ILLEGAL_CHANGE", await itemProducer.GetTestObjectStringProperty());
await consumerSameSilo.UnsubscribeFromStream();
// Test behavior if immutability is disabled
itemProducer = this.client.GetGrain<IStreamingImmutabilityTestGrain>(Guid.NewGuid());
await consumerSameSilo.SubscribeToStream(itemProducer.GetPrimaryKey(), SMS_STREAM_PROVIDER_NAME_DO_NOT_OPTIMIZE_FOR_IMMUTABLE_DATA);
await itemProducer.SetTestObjectStringProperty("VALUE_IN_MUTABLE_STREAM");
await itemProducer.SendTestObject(SMS_STREAM_PROVIDER_NAME_DO_NOT_OPTIMIZE_FOR_IMMUTABLE_DATA);
Assert.Equal("VALUE_IN_MUTABLE_STREAM", await consumerSameSilo.GetTestObjectStringProperty());
// Modify the items property and check it has no impact
await consumerSameSilo.SetTestObjectStringProperty("ALLOWED_CHANGE");
Assert.Equal("ALLOWED_CHANGE", await consumerSameSilo.GetTestObjectStringProperty());
Assert.Equal("VALUE_IN_MUTABLE_STREAM", await itemProducer.GetTestObjectStringProperty());
await consumerSameSilo.UnsubscribeFromStream();
}
//-----------------------------------------------------------------------------//
public async Task BasicTestAsync(bool fullTest = true)
{
logger.Info("\n** Starting Test {0} BasicTestAsync.\n", testNumber);
var producerCount = await producer.ProducerCount;
var consumerCount = await consumer.ConsumerCount;
logger.Info("\n** Test {0} BasicTestAsync: producerCount={1}, consumerCount={2}.\n", testNumber, producerCount, consumerCount);
await producer.ProduceSequentialSeries(ItemCount);
await TestingUtils.WaitUntilAsync(lastTry => CheckCounters(producer, consumer, false), _timeout);
await CheckCounters(producer, consumer);
if (runFullTest)
{
await producer.ProduceParallelSeries(ItemCount);
await TestingUtils.WaitUntilAsync(lastTry => CheckCounters(producer, consumer, false), _timeout);
await CheckCounters(producer, consumer);
await producer.ProducePeriodicSeries(ItemCount);
await TestingUtils.WaitUntilAsync(lastTry => CheckCounters(producer, consumer, false), _timeout);
await CheckCounters(producer, consumer);
}
await ValidatePubSub(producer.StreamId, producer.ProviderName);
}
public async Task StopProxies()
{
await producer.StopBeingProducer();
await AssertProducerCount(0, producer.ProviderName, producer.StreamId);
await consumer.StopBeingConsumer();
}
private async Task<bool> CheckCounters(ProducerProxy producer, ConsumerProxy consumer, bool assertAreEqual = true)
{
var consumerCount = await consumer.ConsumerCount;
Assert.NotEqual(0, consumerCount); // "no consumers were detected."
var producerCount = await producer.ProducerCount;
var numProduced = await producer.ExpectedItemsProduced;
var expectConsumed = numProduced * consumerCount;
var numConsumed = await consumer.ItemsConsumed;
logger.Info("Test {0} CheckCounters: numProduced = {1}, expectConsumed = {2}, numConsumed = {3}", testNumber, numProduced, expectConsumed, numConsumed);
if (assertAreEqual)
{
Assert.Equal(expectConsumed, numConsumed); // String.Format("expectConsumed = {0}, numConsumed = {1}", expectConsumed, numConsumed));
return true;
}
else
{
return expectConsumed == numConsumed;
}
}
private async Task AssertProducerCount(int expectedCount, string providerName, Guid streamId)
{
// currently, we only support checking the producer count on the SMS rendezvous grain.
if (providerName == SMS_STREAM_PROVIDER_NAME)
{
var actualCount = await StreamTestUtils.GetStreamPubSub(this.client).ProducerCount(streamId, providerName, StreamTestsConstants.DefaultStreamNamespace);
logger.Info("StreamingTestRunner.AssertProducerCount: expected={0} actual (SMSStreamRendezvousGrain.ProducerCount)={1} streamId={2}", expectedCount, actualCount, streamId);
Assert.Equal(expectedCount, actualCount);
}
}
private Task ValidatePubSub(Guid streamId, string providerName)
{
var rendez = this.client.GetGrain<IPubSubRendezvousGrain>(streamId, providerName, null);
return rendez.Validate();
}
private async Task<bool> CheckGrainsDeactivated(ProducerProxy producer, ConsumerProxy consumer, bool assertAreEqual = true)
{
var activationCount = 0;
string str = "";
if (producer != null)
{
str = "Producer";
activationCount = await producer.GetNumActivations(this.client);
}
else if (consumer != null)
{
str = "Consumer";
activationCount = await consumer.GetNumActivations(this.client);
}
var expectActivationCount = 0;
logger.Info(
"Test {testNumber} CheckGrainsDeactivated: {type}ActivationCount = {activationCount}, Expected{type}ActivationCount = {expectActivationCount}",
testNumber,
str,
activationCount,
str,
expectActivationCount);
if (assertAreEqual)
{
Assert.Equal(expectActivationCount, activationCount); // String.Format("Expected{0}ActivationCount = {1}, {0}ActivationCount = {2}", str, expectActivationCount, activationCount));
}
return expectActivationCount == activationCount;
}
}
}
//public async Task AQ_1_ConsumerJoinsFirstProducerLater()
//{
// logger.Info("\n\n ************************ AQ_1_ConsumerJoinsFirstProducerLater ********************************* \n\n");
// streamId = StreamId.NewRandomStreamId();
// streamProviderName = AQ_STREAM_PROVIDER_NAME;
// // consumer joins first, producer later
// var consumer = await ConsumerProxy.NewConsumerGrainsAsync(streamId, streamProviderName, logger);
// var producer = await ProducerProxy.NewProducerGrainsAsync(streamId, streamProviderName, logger);
// await BasicTestAsync(producer, consumer);
//}
//public async Task AQ_2_ProducerJoinsFirstConsumerLater()
//{
// logger.Info("\n\n ************************ AQ_2_ProducerJoinsFirstConsumerLater ********************************* \n\n");
// streamId = StreamId.NewRandomStreamId();
// streamProviderName = AQ_STREAM_PROVIDER_NAME;
// // produce joins first, consumer later
// var producer = await ProducerProxy.NewProducerGrainsAsync(streamId, streamProviderName, logger);
// var consumer = await ConsumerProxy.NewConsumerGrainsAsync(streamId, streamProviderName, logger);
// await BasicTestAsync(producer, consumer);
//}
//[Fact, TestCategory("BVT"), TestCategory("Streaming")]
//public async Task StreamTest_2_ProducerJoinsFirstConsumerLater()
//{
// logger.Info("\n\n ************************ StreamTest_2_ProducerJoinsFirstConsumerLater ********************************* \n\n");
// streamId = Guid.NewGuid();
// streamProviderName = StreamTest_STREAM_PROVIDER_NAME;
// // produce joins first, consumer later
// var producer = await ProducerProxy.NewProducerGrainsAsync(streamId, streamProviderName, logger);
// var consumer = await ConsumerProxy.NewConsumerGrainsAsync(streamId, streamProviderName, logger);
// await BasicTestAsync(producer, consumer);
//}
//[Fact, TestCategory("BVT"), TestCategory("Streaming")]
//public async Task StreamTestProducerOnly()
//{
// streamId = Guid.NewGuid();
// this.streamProviderName = StreamTest_STREAM_PROVIDER_NAME;
// await TestGrainProducerOnlyAsync(streamId, this.streamProviderName);
//}
//[Fact, TestCategory("BVT"), TestCategory("Streaming")]
//public void AQProducerOnly()
//{
// streamId = Guid.NewGuid();
// this.streamProviderName = AQ_STREAM_PROVIDER_NAME;
// TestGrainProducerOnlyAsync(streamId, this.streamProviderName).Wait();
//}
//private async Task TestGrainProducerOnlyAsync(Guid streamId, string streamProvider)
//{
// // no consumers, one producer
// var producer = await ProducerProxy.NewProducerGrainsAsync(streamId, streamProvider, logger);
// await producer.ProduceSequentialSeries(0, ItemsPerSeries);
// var numProduced = await producer.NumberProduced;
// logger.Info("numProduced = " + numProduced);
// Assert.Equal(numProduced, ItemsPerSeries);
// // note that the value returned from successive calls to Do...Production() methods is a cumulative total.
// await producer.ProduceParallelSeries(ItemsPerSeries, ItemsPerSeries);
// numProduced = await producer.NumberProduced;
// logger.Info("numProduced = " + numProduced);
// Assert.Equal(numProduced, ItemsPerSeries * 2);
//}
////------------------------ MANY to One ----------------------//
//[Fact, TestCategory("BVT"), TestCategory("Streaming")]
//public async Task StreamTest_Many_5_ManyProducerGrainsOneConsumerGrain()
//{
// logger.Info("\n\n ************************ StreamTest_6_ManyProducerGrainsOneConsumerGrain ********************************* \n\n");
// streamId = Guid.NewGuid();
// this.streamProviderName = StreamTest_STREAM_PROVIDER_NAME;
// var consumer = await ConsumerProxy.NewConsumerGrainsAsync(streamId, streamProviderName, logger);
// var producer = await ProducerProxy.NewProducerGrainsAsync(streamId, streamProviderName, logger, Many);
// await BasicTestAsync(producer, consumer);
//}
//[Fact, TestCategory("BVT"), TestCategory("Streaming")]
//public async Task StreamTest_Many6_OneProducerGrainManyConsumerGrains()
//{
// logger.Info("\n\n ************************ StreamTest_7_OneProducerGrainManyConsumerGrains ********************************* \n\n");
// streamId = Guid.NewGuid();
// this.streamProviderName = StreamTest_STREAM_PROVIDER_NAME;
// var consumer = await ConsumerProxy.NewConsumerGrainsAsync(streamId, streamProviderName, logger, Many);
// var producer = await ProducerProxy.NewProducerGrainsAsync(streamId, streamProviderName, logger);
// await BasicTestAsync(producer, consumer);
//}
//[Fact, TestCategory("Streaming")]
//public async Task StreamTest_Many_8_ManyProducerGrainsOneConsumerClient()
//{
// streamId = Guid.NewGuid();
// this.streamProviderName = StreamTest_STREAM_PROVIDER_NAME;
// var consumer = await ConsumerProxy.NewConsumerClientObjectsAsync(streamId, streamProviderName, logger);
// var producer = await ProducerProxy.NewProducerGrainsAsync(streamId, streamProviderName, logger, Many);
// await BasicTestAsync(producer, consumer);
//}
//// note: this test currently fails intermittently due to synchronization issues in the StreamTest provider. it has been
//// removed from nightly builds until this has been addressed.
//[Fact, TestCategory("Streaming")]
//public async Task _StreamTestManyProducerClientsOneConsumerGrain()
//{
// streamId = Guid.NewGuid();
// this.streamProviderName = StreamTest_STREAM_PROVIDER_NAME;
// var consumer = await ConsumerProxy.NewConsumerGrainsAsync(streamId, streamProviderName, logger);
// var producer = await ProducerProxy.NewProducerClientObjectsAsync(streamId, streamProviderName, logger, Many);
// await BasicTestAsync(producer, consumer);
//}
//// note: this test currently fails intermittently due to synchronization issues in the StreamTest provider. it has been
//// removed from nightly builds until this has been addressed.
//[Fact, TestCategory("Streaming")]
//public async Task _StreamTestManyProducerClientsOneConsumerClient()
//{
// streamId = Guid.NewGuid();
// this.streamProviderName = StreamTest_STREAM_PROVIDER_NAME;
// var consumer = await ConsumerProxy.NewConsumerClientObjectsAsync(streamId, streamProviderName, logger);
// var producer = await ProducerProxy.NewProducerClientObjectsAsync(streamId, streamProviderName, logger, Many);
// await BasicTestAsync(producer, consumer);
//}
//[Fact, TestCategory("Streaming")]
//public async Task _StreamTestOneProducerGrainManyConsumerClients()
//{
// streamId = Guid.NewGuid();
// this.streamProviderName = StreamTest_STREAM_PROVIDER_NAME;
// var consumer = await ConsumerProxy.NewConsumerClientObjectsAsync(streamId, streamProviderName, logger, Many);
// var producer = await ProducerProxy.NewProducerGrainsAsync(streamId, streamProviderName, logger);
// await BasicTestAsync(producer, consumer);
//}
//[Fact, TestCategory("Streaming")]
//public async Task _StreamTestOneProducerClientManyConsumerGrains()
//{
// streamId = Guid.NewGuid();
// this.streamProviderName = StreamTest_STREAM_PROVIDER_NAME;
// var consumer = await ConsumerProxy.NewConsumerGrainsAsync(streamId, streamProviderName, logger, Many);
// var producer = await ProducerProxy.NewProducerClientObjectsAsync(streamId, streamProviderName, logger);
// await BasicTestAsync(producer, consumer);
//}
//[Fact, TestCategory("Streaming")]
//public async Task _StreamTestOneProducerClientManyConsumerClients()
//{
// streamId = Guid.NewGuid();
// this.streamProviderName = StreamTest_STREAM_PROVIDER_NAME;
// var consumer = await ConsumerProxy.NewConsumerClientObjectsAsync(streamId, streamProviderName, logger, Many);
// var producer = await ProducerProxy.NewProducerClientObjectsAsync(streamId, streamProviderName, logger);
// await BasicTestAsync(producer, consumer);
//}
| |
//-----------------------------------------------------------------------
// <copyright file="ArcFile.cs" company="None">
// Copyright (c) Brandon Wallace and Jesse Calhoun. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
namespace TQVaultData
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Text;
/// <summary>
/// Reads and decodes a Titan Quest ARC file.
/// </summary>
public class ArcFile
{
/// <summary>
/// Signifies that the file has been read into memory.
/// </summary>
private bool fileHasBeenRead;
/// <summary>
/// Dictionary of the directory entries.
/// </summary>
private Dictionary<string, ARCDirEntry> directoryEntries;
/// <summary>
/// Holds the keys for the directoryEntries dictionary.
/// </summary>
private string[] keys;
/// <summary>
/// Initializes a new instance of the ArcFile class.
/// </summary>
/// <param name="fileName">File Name of the ARC file to be read.</param>
public ArcFile(string fileName)
{
this.FileName = fileName;
}
/// <summary>
/// Gets the ARC file name.
/// </summary>
public string FileName { get; private set; }
/// <summary>
/// Gets the number of Directory entries
/// </summary>
public int Count
{
get
{
return this.directoryEntries.Count;
}
}
/// <summary>
/// Gets the sorted list of directoryEntries.
/// </summary>
/// <returns>string array holding the sorted list</returns>
public string[] GetKeyTable()
{
if (this.keys == null || this.keys.Length == 0)
{
this.BuildKeyTable();
}
return (string[])this.keys.Clone();
}
#region ArcFile Public Methods
/// <summary>
/// Reads the ARC file table of contents to determine if the file is readable.
/// </summary>
/// <returns>True if able to read the ToC</returns>
public bool Read()
{
try
{
if (!this.fileHasBeenRead)
{
this.ReadARCToC();
}
return this.directoryEntries != null;
}
catch (IOException exception)
{
if (!TQDebug.DebugEnabled)
{
TQDebug.DebugEnabled = true;
}
// Write the exception to the debug log.
TQDebug.DebugWriteLine(exception.ToString());
return false;
}
}
/// <summary>
/// Writes a record to a file.
/// </summary>
/// <param name="baseFolder">string holding the base folder path</param>
/// <param name="record">Record we are writing</param>
/// <param name="destinationFileName">Filename for the new file.</param>
public void Write(string baseFolder, string record, string destinationFileName)
{
try
{
if (!this.fileHasBeenRead)
{
this.ReadARCToC();
}
string dataID = string.Concat(Path.GetFileNameWithoutExtension(this.FileName), "\\", record);
byte[] data = this.GetData(dataID);
if (data == null)
{
return;
}
string destination = baseFolder;
if (!destination.EndsWith("\\", StringComparison.OrdinalIgnoreCase))
{
destination = string.Concat(destination, "\\");
}
destination = string.Concat(destination, destinationFileName);
// If there is a sub directory in the arc file then we need to create it.
if (!Directory.Exists(Path.GetDirectoryName(destination)))
{
Directory.CreateDirectory(Path.GetDirectoryName(destination));
}
using (FileStream outStream = new FileStream(destination, FileMode.Create, FileAccess.Write))
{
outStream.Write(data, 0, data.Length);
}
}
catch (IOException exception)
{
if (!TQDebug.DebugEnabled)
{
TQDebug.DebugEnabled = true;
}
TQDebug.DebugWriteLine(exception.ToString());
return;
}
}
/// <summary>
/// Reads data from an ARC file and puts it into a Byte array (or NULL if not found)
/// </summary>
/// <param name="dataId">The string ID for the data which we are retieving.</param>
/// <returns>Returns byte array of the data corresponding to the string ID.</returns>
public byte[] GetData(string dataId)
{
if (TQDebug.ArcFileDebugLevel > 0)
{
TQDebug.DebugWriteLine(string.Format(CultureInfo.InvariantCulture, "ARCFile.GetData({0})", dataId));
}
if (!this.fileHasBeenRead)
{
this.ReadARCToC();
}
if (this.directoryEntries == null)
{
if (TQDebug.ArcFileDebugLevel > 1)
{
TQDebug.DebugWriteLine(string.Format(CultureInfo.InvariantCulture, "Error - Could not read {0}", this.FileName));
}
// could not read the file
return null;
}
// First normalize the filename
dataId = TQData.NormalizeRecordPath(dataId);
if (TQDebug.ArcFileDebugLevel > 1)
{
TQDebug.DebugWriteLine(string.Format(CultureInfo.InvariantCulture, "Normalized dataID = {0}", dataId));
}
// Find our file in the toc.
// First strip off the leading folder since it is just the ARC name
int firstPathDelim = dataId.IndexOf('\\');
if (firstPathDelim != -1)
{
dataId = dataId.Substring(firstPathDelim + 1);
}
// Now see if this file is in the toc.
ARCDirEntry directoryEntry;
try
{
directoryEntry = this.directoryEntries[dataId];
}
catch (KeyNotFoundException)
{
// record not found
if (TQDebug.ArcFileDebugLevel > 1)
{
TQDebug.DebugWriteLine(string.Format(CultureInfo.InvariantCulture, "Error - {0} not found.", dataId));
}
return null;
}
// Now open the ARC file and read in the record.
using (FileStream arcFile = new FileStream(this.FileName, FileMode.Open, FileAccess.Read))
{
// Allocate memory for the uncompressed data
byte[] data = new byte[directoryEntry.RealSize];
// Now process each part of this record
int startPosition = 0;
// First see if the data was just stored without compression.
if ((directoryEntry.StorageType == 1) && (directoryEntry.CompressedSize == directoryEntry.RealSize))
{
if (TQDebug.ArcFileDebugLevel > 1)
{
TQDebug.DebugWriteLine(string.Format(
CultureInfo.InvariantCulture,
"Offset={0} Size={1}",
directoryEntry.FileOffset,
directoryEntry.RealSize));
}
arcFile.Seek(directoryEntry.FileOffset, SeekOrigin.Begin);
arcFile.Read(data, 0, directoryEntry.RealSize);
}
else
{
// The data was compressed so we attempt to decompress it.
foreach (ARCPartEntry partEntry in directoryEntry.Parts)
{
// seek to the part we want
arcFile.Seek(partEntry.FileOffset, SeekOrigin.Begin);
// Ignore the zlib compression method.
arcFile.ReadByte();
// Ignore the zlib compression flags.
arcFile.ReadByte();
// Create a deflate stream.
using (DeflateStream deflate = new DeflateStream(arcFile, CompressionMode.Decompress, true))
{
int bytesRead;
int partLength = 0;
while ((bytesRead = deflate.Read(data, startPosition, data.Length - startPosition)) > 0)
{
startPosition += bytesRead;
partLength += bytesRead;
// break out of the read loop if we have processed this part completely.
if (partLength >= partEntry.RealSize)
{
break;
}
}
}
}
}
if (TQDebug.ArcFileDebugLevel > 0)
{
TQDebug.DebugWriteLine("Exiting ARCFile.GetData()");
}
return data;
}
}
/// <summary>
/// Extracts the decoded ARC file contents into a folder.
/// </summary>
/// <param name="destination">Destination folder for the files.</param>
/// <returns>true if successful, false on error.</returns>
public bool ExtractArcFile(string destination)
{
try
{
if (TQDebug.ArcFileDebugLevel > 0)
{
TQDebug.DebugWriteLine("ARCFile.ReadARCFile()");
}
if (!this.fileHasBeenRead)
{
this.ReadARCToC();
}
foreach (ARCDirEntry dirEntry in this.directoryEntries.Values)
{
string dataID = string.Concat(Path.GetFileNameWithoutExtension(this.FileName), "\\", dirEntry.FileName);
if (TQDebug.ArcFileDebugLevel > 1)
{
TQDebug.DebugWriteLine(string.Concat("Directory Filename = ", dirEntry.FileName));
TQDebug.DebugWriteLine(string.Concat("dataID = ", dataID));
}
byte[] data = this.GetData(dataID);
string filename = destination;
if (!filename.EndsWith("\\", StringComparison.Ordinal))
{
filename = string.Concat(filename, "\\");
}
filename = string.Concat(filename, dirEntry.FileName);
// If there is a sub directory in the arc file then we need to create it.
if (!Directory.Exists(Path.GetDirectoryName(filename)))
{
Directory.CreateDirectory(Path.GetDirectoryName(filename));
}
if (TQDebug.ArcFileDebugLevel > 1)
{
TQDebug.DebugWriteLine(string.Concat("Creating File - ", filename));
}
using (FileStream outStream = new FileStream(filename, FileMode.Create, FileAccess.Write))
{
outStream.Write(data, 0, data.Length);
}
}
if (TQDebug.ArcFileDebugLevel > 0)
{
TQDebug.DebugWriteLine("Exiting ARCFile.ReadARCFile()");
}
return true;
}
catch (IOException exception)
{
// Turn on debugging
if (!TQDebug.DebugEnabled)
{
TQDebug.DebugEnabled = true;
}
// Write the errors to the debug log.
TQDebug.DebugWriteLine("ARCFile.ReadARCFile() - Error reading arcfile");
TQDebug.DebugWriteLine(exception.ToString());
return false;
}
}
#endregion ArcFile Public Methods
#region ArcFile Private Methods
/// <summary>
/// Builds a sorted list of entries in the directoryEntries dictionary. Used to build a tree structure of the names.
/// </summary>
private void BuildKeyTable()
{
if (this.directoryEntries == null || this.directoryEntries.Count == 0)
{
return;
}
int index = 0;
this.keys = new string[this.directoryEntries.Count];
foreach (string filename in this.directoryEntries.Keys)
{
this.keys[index] = filename;
index++;
}
Array.Sort(this.keys);
}
/// <summary>
/// Read the table of contents of the ARC file
/// </summary>
private void ReadARCToC()
{
// Format of an ARC file
// 0x08 - 4 bytes = # of files
// 0x0C - 4 bytes = # of parts
// 0x18 - 4 bytes = offset to directory structure
//
// Format of directory structure
// 4-byte int = offset in file where this part begins
// 4-byte int = size of compressed part
// 4-byte int = size of uncompressed part
// these triplets repeat for each part in the arc file
// After these triplets are a bunch of null-terminated strings
// which are the sub filenames.
// After the subfilenames comes the subfile data:
// 4-byte int = 3 == indicates start of subfile item (maybe compressed flag??)
// 1 == maybe uncompressed flag??
// 4-byte int = offset in file where first part of this subfile begins
// 4-byte int = compressed size of this file
// 4-byte int = uncompressed size of this file
// 4-byte crap
// 4-byte crap
// 4-byte crap
// 4-byte int = numParts this file uses
// 4-byte int = part# of first part for this file (starting at 0).
// 4-byte int = length of filename string
// 4-byte int = offset in directory structure for filename
this.fileHasBeenRead = true;
if (TQDebug.ArcFileDebugLevel > 0)
{
TQDebug.DebugWriteLine(string.Format(CultureInfo.InvariantCulture, "ARCFile.ReadARCToC({0})", this.FileName));
}
try
{
using (FileStream arcFile = new FileStream(this.FileName, FileMode.Open, FileAccess.Read))
{
using (BinaryReader reader = new BinaryReader(arcFile))
{
if (TQDebug.ArcFileDebugLevel > 1)
{
TQDebug.DebugWriteLine(string.Format(CultureInfo.InvariantCulture, "File Length={0}", arcFile.Length));
}
// check the file header
if (reader.ReadByte() != 0x41)
{
return;
}
if (reader.ReadByte() != 0x52)
{
return;
}
if (reader.ReadByte() != 0x43)
{
return;
}
if (arcFile.Length < 0x21)
{
return;
}
reader.BaseStream.Seek(0x08, SeekOrigin.Begin);
int numEntries = reader.ReadInt32();
int numParts = reader.ReadInt32();
if (TQDebug.ArcFileDebugLevel > 1)
{
TQDebug.DebugWriteLine(string.Format(CultureInfo.InvariantCulture, "numEntries={0}, numParts={1}", numEntries, numParts));
}
ARCPartEntry[] parts = new ARCPartEntry[numParts];
ARCDirEntry[] records = new ARCDirEntry[numEntries];
if (TQDebug.ArcFileDebugLevel > 2)
{
TQDebug.DebugWriteLine("Seeking to tocOffset location");
}
reader.BaseStream.Seek(0x18, SeekOrigin.Begin);
int tocOffset = reader.ReadInt32();
if (TQDebug.ArcFileDebugLevel > 1)
{
TQDebug.DebugWriteLine(string.Format(CultureInfo.InvariantCulture, "tocOffset = {0}", tocOffset));
}
// Make sure all 3 entries exist for the toc entry.
if (arcFile.Length < (tocOffset + 12))
{
return;
}
// Read in all of the part data
reader.BaseStream.Seek(tocOffset, SeekOrigin.Begin);
int i;
for (i = 0; i < numParts; ++i)
{
parts[i] = new ARCPartEntry();
parts[i].FileOffset = reader.ReadInt32();
parts[i].CompressedSize = reader.ReadInt32();
parts[i].RealSize = reader.ReadInt32();
if (TQDebug.ArcFileDebugLevel > 2)
{
TQDebug.DebugWriteLine(string.Format(CultureInfo.InvariantCulture, "parts[{0}]", i));
TQDebug.DebugWriteLine(string.Format(
CultureInfo.InvariantCulture,
" fileOffset={0}, compressedSize={1}, realSize={2}",
parts[i].FileOffset,
parts[i].CompressedSize,
parts[i].RealSize));
}
}
// Now record this offset so we can come back and read in the filenames
// after we have read in the file records
int fileNamesOffset = (int)arcFile.Position;
// Now seek to the location where the file record data is
// This offset is from the end of the file.
int fileRecordOffset = 44 * numEntries;
if (TQDebug.ArcFileDebugLevel > 1)
{
TQDebug.DebugWriteLine(string.Format(
CultureInfo.InvariantCulture,
"fileNamesOffset = {0}. Seeking to {1} to read file record data.",
fileNamesOffset,
fileRecordOffset));
}
arcFile.Seek(-1 * fileRecordOffset, SeekOrigin.End);
for (i = 0; i < numEntries; ++i)
{
records[i] = new ARCDirEntry();
// storageType = 3 - compressed / 1- non compressed
int storageType = reader.ReadInt32();
if (TQDebug.ArcFileDebugLevel > 2)
{
TQDebug.DebugWriteLine(string.Format(CultureInfo.InvariantCulture, "StorageType={0}", storageType));
}
// Added by VillageIdiot to support stored types
records[i].StorageType = storageType;
records[i].FileOffset = reader.ReadInt32();
records[i].CompressedSize = reader.ReadInt32();
records[i].RealSize = reader.ReadInt32();
int crap = reader.ReadInt32(); // crap
if (TQDebug.ArcFileDebugLevel > 2)
{
TQDebug.DebugWriteLine(string.Format(CultureInfo.InvariantCulture, "Crap2={0}", crap));
}
crap = reader.ReadInt32(); // crap
if (TQDebug.ArcFileDebugLevel > 2)
{
TQDebug.DebugWriteLine(string.Format(CultureInfo.InvariantCulture, "Crap3={0}", crap));
}
crap = reader.ReadInt32(); // crap
if (TQDebug.ArcFileDebugLevel > 2)
{
TQDebug.DebugWriteLine(string.Format(CultureInfo.InvariantCulture, "Crap4={0}", crap));
}
int numberOfParts = reader.ReadInt32();
if (numberOfParts < 1)
{
records[i].Parts = null;
if (TQDebug.ArcFileDebugLevel > 2)
{
TQDebug.DebugWriteLine(string.Format(CultureInfo.InvariantCulture, "File {0} is not compressed.", i));
}
}
else
{
records[i].Parts = new ARCPartEntry[numberOfParts];
}
int firstPart = reader.ReadInt32();
crap = reader.ReadInt32(); // filename length
if (TQDebug.ArcFileDebugLevel > 2)
{
TQDebug.DebugWriteLine(string.Format(CultureInfo.InvariantCulture, "Filename Length={0}", crap));
}
crap = reader.ReadInt32(); // filename offset
if (TQDebug.ArcFileDebugLevel > 2)
{
TQDebug.DebugWriteLine(string.Format(CultureInfo.InvariantCulture, "Filename Offset={0}", crap));
TQDebug.DebugWriteLine(string.Format(CultureInfo.InvariantCulture, "record[{0}]", i));
TQDebug.DebugWriteLine(string.Format(
CultureInfo.InvariantCulture,
" offset={0} compressedSize={1} realSize={2}",
records[i].FileOffset,
records[i].CompressedSize,
records[i].RealSize));
if (storageType != 1 && records[i].IsActive)
{
TQDebug.DebugWriteLine(string.Format(
CultureInfo.InvariantCulture,
" numParts={0} firstPart={1} lastPart={2}",
records[i].Parts.Length,
firstPart,
firstPart + records[i].Parts.Length - 1));
}
else
{
TQDebug.DebugWriteLine(string.Format(CultureInfo.InvariantCulture, " INACTIVE firstPart={0}", firstPart));
}
}
if (storageType != 1 && records[i].IsActive)
{
for (int ip = 0; ip < records[i].Parts.Length; ++ip)
{
records[i].Parts[ip] = parts[ip + firstPart];
}
}
}
// Now read in the record names
arcFile.Seek(fileNamesOffset, SeekOrigin.Begin);
byte[] buffer = new byte[2048];
ASCIIEncoding ascii = new ASCIIEncoding();
for (i = 0; i < numEntries; ++i)
{
// only Active files have a filename entry
if (records[i].IsActive)
{
// For each string, read bytes until I hit a 0x00 byte.
if (TQDebug.ArcFileDebugLevel > 2)
{
TQDebug.DebugWriteLine(string.Format(CultureInfo.InvariantCulture, "Reading entry name {0:n0}", i));
}
int bufferSize = 0;
while ((buffer[bufferSize++] = reader.ReadByte()) != 0x00)
{
if (buffer[bufferSize - 1] == 0x03)
{
// File is null?
arcFile.Seek(-1, SeekOrigin.Current); // backup
bufferSize--;
buffer[bufferSize] = 0x00;
if (TQDebug.ArcFileDebugLevel > 2)
{
TQDebug.DebugWriteLine("Null file - inactive?");
}
break;
}
if (bufferSize >= buffer.Length)
{
TQDebug.DebugWriteLine("ARCFile.ReadARCToC() Error - Buffer size of 2048 has been exceeded.");
if (TQDebug.ArcFileDebugLevel > 2)
{
TQDebug.DebugWriteLine("Buffer contents:\n");
for (int j = 0; j < bufferSize; ++j)
{
TQDebug.DebugWrite(string.Format(CultureInfo.InvariantCulture, "0x{0:X}", buffer[j]));
}
TQDebug.DebugWriteLine(String.Empty);
}
}
}
if (TQDebug.ArcFileDebugLevel > 2)
{
TQDebug.DebugWriteLine(string.Format(
CultureInfo.InvariantCulture,
"Read {0:n0} bytes for name. Converting to string.",
bufferSize));
}
string newfile;
if (bufferSize >= 1)
{
// Now convert the buffer to a string
char[] chars = new char[ascii.GetCharCount(buffer, 0, bufferSize - 1)];
ascii.GetChars(buffer, 0, bufferSize - 1, chars, 0);
newfile = new string(chars);
}
else
{
newfile = string.Format(CultureInfo.InvariantCulture, "Null File {0}", i);
}
records[i].FileName = TQData.NormalizeRecordPath(newfile);
if (TQDebug.ArcFileDebugLevel > 2)
{
TQDebug.DebugWriteLine(string.Format(CultureInfo.InvariantCulture, "Name {0:n0} = '{1}'", i, records[i].FileName));
}
}
}
// Now convert the array of records into a Dictionary.
Dictionary<string, ARCDirEntry> dictionary = new Dictionary<string, ARCDirEntry>(numEntries);
if (TQDebug.ArcFileDebugLevel > 1)
{
TQDebug.DebugWriteLine("Creating Dictionary");
}
for (i = 0; i < numEntries; ++i)
{
if (records[i].IsActive)
{
dictionary.Add(records[i].FileName, records[i]);
}
}
this.directoryEntries = dictionary;
if (TQDebug.ArcFileDebugLevel > 0)
{
TQDebug.DebugWriteLine("Exiting ARCFile.ReadARCToC()");
}
}
}
}
catch (IOException exception)
{
// Turn on debugging.
if (!TQDebug.DebugEnabled)
{
TQDebug.DebugEnabled = true;
}
// Write the errors to the debug log.
TQDebug.DebugWriteLine("ARCFile.ReadARCToC() - Error reading arcfile");
TQDebug.DebugWriteLine(exception.ToString());
}
}
#endregion ArcFile Private Methods
#region ARCPartEntry
/// <summary>
/// Holds data about a file stored in an ARC file.
/// </summary>
private class ARCPartEntry
{
/// <summary>
/// Gets or sets the offset of this part entry within the file.
/// </summary>
public int FileOffset { get; set; }
/// <summary>
/// Gets or sets the compressed size of this part entry.
/// </summary>
public int CompressedSize { get; set; }
/// <summary>
/// Gets or sets the real size of this part entry.
/// </summary>
public int RealSize { get; set; }
}
#endregion ARCPartEntry
#region ARCDirEntry
/// <summary>
/// Holds information about the directory entry.
/// </summary>
private class ARCDirEntry
{
/// <summary>
/// Gets or sets the filename.
/// </summary>
public string FileName { get; set; }
/// <summary>
/// Gets or sets the storage type.
/// Data is either compressed (3) or stored (1)
/// </summary>
public int StorageType { get; set; }
/// <summary>
/// Gets or sets the offset within the file.
/// </summary>
public int FileOffset { get; set; }
/// <summary>
/// Gets or sets the compressed size of this entry.
/// </summary>
public int CompressedSize { get; set; }
/// <summary>
/// Gets or sets the real size of this entry.
/// </summary>
public int RealSize { get; set; }
/// <summary>
/// Gets or sets the part data
/// </summary>
public ARCPartEntry[] Parts { get; set; }
/// <summary>
/// Gets a value indicating whether this part is active.
/// </summary>
public bool IsActive
{
get
{
if (this.StorageType == 1)
{
return true;
}
else
{
return this.Parts != null;
}
}
}
}
#endregion ARCDirEntry
}
}
| |
/*
* Swaggy Jenkins
*
* Jenkins API clients generated from Swagger / Open API specification
*
* The version of the OpenAPI document: 1.1.2-pre.0
* Contact: blah@cliffano.com
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter;
namespace Org.OpenAPITools.Model
{
/// <summary>
/// InputStepImpl
/// </summary>
[DataContract]
public partial class InputStepImpl : IEquatable<InputStepImpl>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="InputStepImpl" /> class.
/// </summary>
/// <param name="_class">_class.</param>
/// <param name="links">links.</param>
/// <param name="id">id.</param>
/// <param name="message">message.</param>
/// <param name="ok">ok.</param>
/// <param name="parameters">parameters.</param>
/// <param name="submitter">submitter.</param>
public InputStepImpl(string _class = default(string), InputStepImpllinks links = default(InputStepImpllinks), string id = default(string), string message = default(string), string ok = default(string), List<StringParameterDefinition> parameters = default(List<StringParameterDefinition>), string submitter = default(string))
{
this.Class = _class;
this.Links = links;
this.Id = id;
this.Message = message;
this.Ok = ok;
this.Parameters = parameters;
this.Submitter = submitter;
}
/// <summary>
/// Gets or Sets Class
/// </summary>
[DataMember(Name="_class", EmitDefaultValue=false)]
public string Class { get; set; }
/// <summary>
/// Gets or Sets Links
/// </summary>
[DataMember(Name="_links", EmitDefaultValue=false)]
public InputStepImpllinks Links { get; set; }
/// <summary>
/// Gets or Sets Id
/// </summary>
[DataMember(Name="id", EmitDefaultValue=false)]
public string Id { get; set; }
/// <summary>
/// Gets or Sets Message
/// </summary>
[DataMember(Name="message", EmitDefaultValue=false)]
public string Message { get; set; }
/// <summary>
/// Gets or Sets Ok
/// </summary>
[DataMember(Name="ok", EmitDefaultValue=false)]
public string Ok { get; set; }
/// <summary>
/// Gets or Sets Parameters
/// </summary>
[DataMember(Name="parameters", EmitDefaultValue=false)]
public List<StringParameterDefinition> Parameters { get; set; }
/// <summary>
/// Gets or Sets Submitter
/// </summary>
[DataMember(Name="submitter", EmitDefaultValue=false)]
public string Submitter { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class InputStepImpl {\n");
sb.Append(" Class: ").Append(Class).Append("\n");
sb.Append(" Links: ").Append(Links).Append("\n");
sb.Append(" Id: ").Append(Id).Append("\n");
sb.Append(" Message: ").Append(Message).Append("\n");
sb.Append(" Ok: ").Append(Ok).Append("\n");
sb.Append(" Parameters: ").Append(Parameters).Append("\n");
sb.Append(" Submitter: ").Append(Submitter).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public virtual string ToJson()
{
return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="input">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object input)
{
return this.Equals(input as InputStepImpl);
}
/// <summary>
/// Returns true if InputStepImpl instances are equal
/// </summary>
/// <param name="input">Instance of InputStepImpl to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(InputStepImpl input)
{
if (input == null)
return false;
return
(
this.Class == input.Class ||
(this.Class != null &&
this.Class.Equals(input.Class))
) &&
(
this.Links == input.Links ||
(this.Links != null &&
this.Links.Equals(input.Links))
) &&
(
this.Id == input.Id ||
(this.Id != null &&
this.Id.Equals(input.Id))
) &&
(
this.Message == input.Message ||
(this.Message != null &&
this.Message.Equals(input.Message))
) &&
(
this.Ok == input.Ok ||
(this.Ok != null &&
this.Ok.Equals(input.Ok))
) &&
(
this.Parameters == input.Parameters ||
this.Parameters != null &&
input.Parameters != null &&
this.Parameters.SequenceEqual(input.Parameters)
) &&
(
this.Submitter == input.Submitter ||
(this.Submitter != null &&
this.Submitter.Equals(input.Submitter))
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
if (this.Class != null)
hashCode = hashCode * 59 + this.Class.GetHashCode();
if (this.Links != null)
hashCode = hashCode * 59 + this.Links.GetHashCode();
if (this.Id != null)
hashCode = hashCode * 59 + this.Id.GetHashCode();
if (this.Message != null)
hashCode = hashCode * 59 + this.Message.GetHashCode();
if (this.Ok != null)
hashCode = hashCode * 59 + this.Ok.GetHashCode();
if (this.Parameters != null)
hashCode = hashCode * 59 + this.Parameters.GetHashCode();
if (this.Submitter != null)
hashCode = hashCode * 59 + this.Submitter.GetHashCode();
return hashCode;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| |
// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Cloud.Dataproc.V1.Tests
{
using Google.Api.Gax;
using Google.Api.Gax.Grpc;
using apis = Google.Cloud.Dataproc.V1;
using Google.Protobuf.WellKnownTypes;
using Grpc.Core;
using Moq;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
/// <summary>Generated unit tests</summary>
public class GeneratedJobControllerClientTest
{
[Fact]
public void SubmitJob()
{
Mock<JobController.JobControllerClient> mockGrpcClient = new Mock<JobController.JobControllerClient>(MockBehavior.Strict);
SubmitJobRequest expectedRequest = new SubmitJobRequest
{
ProjectId = "projectId-1969970175",
Region = "region-934795532",
Job = new Job(),
};
Job expectedResponse = new Job
{
DriverOutputResourceUri = "driverOutputResourceUri-542229086",
DriverControlFilesUri = "driverControlFilesUri207057643",
};
mockGrpcClient.Setup(x => x.SubmitJob(expectedRequest, It.IsAny<CallOptions>()))
.Returns(expectedResponse);
JobControllerClient client = new JobControllerClientImpl(mockGrpcClient.Object, null);
string projectId = "projectId-1969970175";
string region = "region-934795532";
Job job = new Job();
Job response = client.SubmitJob(projectId, region, job);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public async Task SubmitJobAsync()
{
Mock<JobController.JobControllerClient> mockGrpcClient = new Mock<JobController.JobControllerClient>(MockBehavior.Strict);
SubmitJobRequest expectedRequest = new SubmitJobRequest
{
ProjectId = "projectId-1969970175",
Region = "region-934795532",
Job = new Job(),
};
Job expectedResponse = new Job
{
DriverOutputResourceUri = "driverOutputResourceUri-542229086",
DriverControlFilesUri = "driverControlFilesUri207057643",
};
mockGrpcClient.Setup(x => x.SubmitJobAsync(expectedRequest, It.IsAny<CallOptions>()))
.Returns(new Grpc.Core.AsyncUnaryCall<Job>(Task.FromResult(expectedResponse), null, null, null, null));
JobControllerClient client = new JobControllerClientImpl(mockGrpcClient.Object, null);
string projectId = "projectId-1969970175";
string region = "region-934795532";
Job job = new Job();
Job response = await client.SubmitJobAsync(projectId, region, job);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public void SubmitJob2()
{
Mock<JobController.JobControllerClient> mockGrpcClient = new Mock<JobController.JobControllerClient>(MockBehavior.Strict);
SubmitJobRequest request = new SubmitJobRequest
{
ProjectId = "projectId-1969970175",
Region = "region-934795532",
Job = new Job(),
};
Job expectedResponse = new Job
{
DriverOutputResourceUri = "driverOutputResourceUri-542229086",
DriverControlFilesUri = "driverControlFilesUri207057643",
};
mockGrpcClient.Setup(x => x.SubmitJob(request, It.IsAny<CallOptions>()))
.Returns(expectedResponse);
JobControllerClient client = new JobControllerClientImpl(mockGrpcClient.Object, null);
Job response = client.SubmitJob(request);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public async Task SubmitJobAsync2()
{
Mock<JobController.JobControllerClient> mockGrpcClient = new Mock<JobController.JobControllerClient>(MockBehavior.Strict);
SubmitJobRequest request = new SubmitJobRequest
{
ProjectId = "projectId-1969970175",
Region = "region-934795532",
Job = new Job(),
};
Job expectedResponse = new Job
{
DriverOutputResourceUri = "driverOutputResourceUri-542229086",
DriverControlFilesUri = "driverControlFilesUri207057643",
};
mockGrpcClient.Setup(x => x.SubmitJobAsync(request, It.IsAny<CallOptions>()))
.Returns(new Grpc.Core.AsyncUnaryCall<Job>(Task.FromResult(expectedResponse), null, null, null, null));
JobControllerClient client = new JobControllerClientImpl(mockGrpcClient.Object, null);
Job response = await client.SubmitJobAsync(request);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public void GetJob()
{
Mock<JobController.JobControllerClient> mockGrpcClient = new Mock<JobController.JobControllerClient>(MockBehavior.Strict);
GetJobRequest expectedRequest = new GetJobRequest
{
ProjectId = "projectId-1969970175",
Region = "region-934795532",
JobId = "jobId-1154752291",
};
Job expectedResponse = new Job
{
DriverOutputResourceUri = "driverOutputResourceUri-542229086",
DriverControlFilesUri = "driverControlFilesUri207057643",
};
mockGrpcClient.Setup(x => x.GetJob(expectedRequest, It.IsAny<CallOptions>()))
.Returns(expectedResponse);
JobControllerClient client = new JobControllerClientImpl(mockGrpcClient.Object, null);
string projectId = "projectId-1969970175";
string region = "region-934795532";
string jobId = "jobId-1154752291";
Job response = client.GetJob(projectId, region, jobId);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public async Task GetJobAsync()
{
Mock<JobController.JobControllerClient> mockGrpcClient = new Mock<JobController.JobControllerClient>(MockBehavior.Strict);
GetJobRequest expectedRequest = new GetJobRequest
{
ProjectId = "projectId-1969970175",
Region = "region-934795532",
JobId = "jobId-1154752291",
};
Job expectedResponse = new Job
{
DriverOutputResourceUri = "driverOutputResourceUri-542229086",
DriverControlFilesUri = "driverControlFilesUri207057643",
};
mockGrpcClient.Setup(x => x.GetJobAsync(expectedRequest, It.IsAny<CallOptions>()))
.Returns(new Grpc.Core.AsyncUnaryCall<Job>(Task.FromResult(expectedResponse), null, null, null, null));
JobControllerClient client = new JobControllerClientImpl(mockGrpcClient.Object, null);
string projectId = "projectId-1969970175";
string region = "region-934795532";
string jobId = "jobId-1154752291";
Job response = await client.GetJobAsync(projectId, region, jobId);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public void GetJob2()
{
Mock<JobController.JobControllerClient> mockGrpcClient = new Mock<JobController.JobControllerClient>(MockBehavior.Strict);
GetJobRequest request = new GetJobRequest
{
ProjectId = "projectId-1969970175",
Region = "region-934795532",
JobId = "jobId-1154752291",
};
Job expectedResponse = new Job
{
DriverOutputResourceUri = "driverOutputResourceUri-542229086",
DriverControlFilesUri = "driverControlFilesUri207057643",
};
mockGrpcClient.Setup(x => x.GetJob(request, It.IsAny<CallOptions>()))
.Returns(expectedResponse);
JobControllerClient client = new JobControllerClientImpl(mockGrpcClient.Object, null);
Job response = client.GetJob(request);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public async Task GetJobAsync2()
{
Mock<JobController.JobControllerClient> mockGrpcClient = new Mock<JobController.JobControllerClient>(MockBehavior.Strict);
GetJobRequest request = new GetJobRequest
{
ProjectId = "projectId-1969970175",
Region = "region-934795532",
JobId = "jobId-1154752291",
};
Job expectedResponse = new Job
{
DriverOutputResourceUri = "driverOutputResourceUri-542229086",
DriverControlFilesUri = "driverControlFilesUri207057643",
};
mockGrpcClient.Setup(x => x.GetJobAsync(request, It.IsAny<CallOptions>()))
.Returns(new Grpc.Core.AsyncUnaryCall<Job>(Task.FromResult(expectedResponse), null, null, null, null));
JobControllerClient client = new JobControllerClientImpl(mockGrpcClient.Object, null);
Job response = await client.GetJobAsync(request);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public void UpdateJob()
{
Mock<JobController.JobControllerClient> mockGrpcClient = new Mock<JobController.JobControllerClient>(MockBehavior.Strict);
UpdateJobRequest request = new UpdateJobRequest
{
ProjectId = "projectId-1969970175",
Region = "region-934795532",
JobId = "jobId-1154752291",
Job = new Job(),
UpdateMask = new FieldMask(),
};
Job expectedResponse = new Job
{
DriverOutputResourceUri = "driverOutputResourceUri-542229086",
DriverControlFilesUri = "driverControlFilesUri207057643",
};
mockGrpcClient.Setup(x => x.UpdateJob(request, It.IsAny<CallOptions>()))
.Returns(expectedResponse);
JobControllerClient client = new JobControllerClientImpl(mockGrpcClient.Object, null);
Job response = client.UpdateJob(request);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public async Task UpdateJobAsync()
{
Mock<JobController.JobControllerClient> mockGrpcClient = new Mock<JobController.JobControllerClient>(MockBehavior.Strict);
UpdateJobRequest request = new UpdateJobRequest
{
ProjectId = "projectId-1969970175",
Region = "region-934795532",
JobId = "jobId-1154752291",
Job = new Job(),
UpdateMask = new FieldMask(),
};
Job expectedResponse = new Job
{
DriverOutputResourceUri = "driverOutputResourceUri-542229086",
DriverControlFilesUri = "driverControlFilesUri207057643",
};
mockGrpcClient.Setup(x => x.UpdateJobAsync(request, It.IsAny<CallOptions>()))
.Returns(new Grpc.Core.AsyncUnaryCall<Job>(Task.FromResult(expectedResponse), null, null, null, null));
JobControllerClient client = new JobControllerClientImpl(mockGrpcClient.Object, null);
Job response = await client.UpdateJobAsync(request);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public void CancelJob()
{
Mock<JobController.JobControllerClient> mockGrpcClient = new Mock<JobController.JobControllerClient>(MockBehavior.Strict);
CancelJobRequest expectedRequest = new CancelJobRequest
{
ProjectId = "projectId-1969970175",
Region = "region-934795532",
JobId = "jobId-1154752291",
};
Job expectedResponse = new Job
{
DriverOutputResourceUri = "driverOutputResourceUri-542229086",
DriverControlFilesUri = "driverControlFilesUri207057643",
};
mockGrpcClient.Setup(x => x.CancelJob(expectedRequest, It.IsAny<CallOptions>()))
.Returns(expectedResponse);
JobControllerClient client = new JobControllerClientImpl(mockGrpcClient.Object, null);
string projectId = "projectId-1969970175";
string region = "region-934795532";
string jobId = "jobId-1154752291";
Job response = client.CancelJob(projectId, region, jobId);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public async Task CancelJobAsync()
{
Mock<JobController.JobControllerClient> mockGrpcClient = new Mock<JobController.JobControllerClient>(MockBehavior.Strict);
CancelJobRequest expectedRequest = new CancelJobRequest
{
ProjectId = "projectId-1969970175",
Region = "region-934795532",
JobId = "jobId-1154752291",
};
Job expectedResponse = new Job
{
DriverOutputResourceUri = "driverOutputResourceUri-542229086",
DriverControlFilesUri = "driverControlFilesUri207057643",
};
mockGrpcClient.Setup(x => x.CancelJobAsync(expectedRequest, It.IsAny<CallOptions>()))
.Returns(new Grpc.Core.AsyncUnaryCall<Job>(Task.FromResult(expectedResponse), null, null, null, null));
JobControllerClient client = new JobControllerClientImpl(mockGrpcClient.Object, null);
string projectId = "projectId-1969970175";
string region = "region-934795532";
string jobId = "jobId-1154752291";
Job response = await client.CancelJobAsync(projectId, region, jobId);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public void CancelJob2()
{
Mock<JobController.JobControllerClient> mockGrpcClient = new Mock<JobController.JobControllerClient>(MockBehavior.Strict);
CancelJobRequest request = new CancelJobRequest
{
ProjectId = "projectId-1969970175",
Region = "region-934795532",
JobId = "jobId-1154752291",
};
Job expectedResponse = new Job
{
DriverOutputResourceUri = "driverOutputResourceUri-542229086",
DriverControlFilesUri = "driverControlFilesUri207057643",
};
mockGrpcClient.Setup(x => x.CancelJob(request, It.IsAny<CallOptions>()))
.Returns(expectedResponse);
JobControllerClient client = new JobControllerClientImpl(mockGrpcClient.Object, null);
Job response = client.CancelJob(request);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public async Task CancelJobAsync2()
{
Mock<JobController.JobControllerClient> mockGrpcClient = new Mock<JobController.JobControllerClient>(MockBehavior.Strict);
CancelJobRequest request = new CancelJobRequest
{
ProjectId = "projectId-1969970175",
Region = "region-934795532",
JobId = "jobId-1154752291",
};
Job expectedResponse = new Job
{
DriverOutputResourceUri = "driverOutputResourceUri-542229086",
DriverControlFilesUri = "driverControlFilesUri207057643",
};
mockGrpcClient.Setup(x => x.CancelJobAsync(request, It.IsAny<CallOptions>()))
.Returns(new Grpc.Core.AsyncUnaryCall<Job>(Task.FromResult(expectedResponse), null, null, null, null));
JobControllerClient client = new JobControllerClientImpl(mockGrpcClient.Object, null);
Job response = await client.CancelJobAsync(request);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public void DeleteJob()
{
Mock<JobController.JobControllerClient> mockGrpcClient = new Mock<JobController.JobControllerClient>(MockBehavior.Strict);
DeleteJobRequest expectedRequest = new DeleteJobRequest
{
ProjectId = "projectId-1969970175",
Region = "region-934795532",
JobId = "jobId-1154752291",
};
Empty expectedResponse = new Empty();
mockGrpcClient.Setup(x => x.DeleteJob(expectedRequest, It.IsAny<CallOptions>()))
.Returns(expectedResponse);
JobControllerClient client = new JobControllerClientImpl(mockGrpcClient.Object, null);
string projectId = "projectId-1969970175";
string region = "region-934795532";
string jobId = "jobId-1154752291";
client.DeleteJob(projectId, region, jobId);
mockGrpcClient.VerifyAll();
}
[Fact]
public async Task DeleteJobAsync()
{
Mock<JobController.JobControllerClient> mockGrpcClient = new Mock<JobController.JobControllerClient>(MockBehavior.Strict);
DeleteJobRequest expectedRequest = new DeleteJobRequest
{
ProjectId = "projectId-1969970175",
Region = "region-934795532",
JobId = "jobId-1154752291",
};
Empty expectedResponse = new Empty();
mockGrpcClient.Setup(x => x.DeleteJobAsync(expectedRequest, It.IsAny<CallOptions>()))
.Returns(new Grpc.Core.AsyncUnaryCall<Empty>(Task.FromResult(expectedResponse), null, null, null, null));
JobControllerClient client = new JobControllerClientImpl(mockGrpcClient.Object, null);
string projectId = "projectId-1969970175";
string region = "region-934795532";
string jobId = "jobId-1154752291";
await client.DeleteJobAsync(projectId, region, jobId);
mockGrpcClient.VerifyAll();
}
[Fact]
public void DeleteJob2()
{
Mock<JobController.JobControllerClient> mockGrpcClient = new Mock<JobController.JobControllerClient>(MockBehavior.Strict);
DeleteJobRequest request = new DeleteJobRequest
{
ProjectId = "projectId-1969970175",
Region = "region-934795532",
JobId = "jobId-1154752291",
};
Empty expectedResponse = new Empty();
mockGrpcClient.Setup(x => x.DeleteJob(request, It.IsAny<CallOptions>()))
.Returns(expectedResponse);
JobControllerClient client = new JobControllerClientImpl(mockGrpcClient.Object, null);
client.DeleteJob(request);
mockGrpcClient.VerifyAll();
}
[Fact]
public async Task DeleteJobAsync2()
{
Mock<JobController.JobControllerClient> mockGrpcClient = new Mock<JobController.JobControllerClient>(MockBehavior.Strict);
DeleteJobRequest request = new DeleteJobRequest
{
ProjectId = "projectId-1969970175",
Region = "region-934795532",
JobId = "jobId-1154752291",
};
Empty expectedResponse = new Empty();
mockGrpcClient.Setup(x => x.DeleteJobAsync(request, It.IsAny<CallOptions>()))
.Returns(new Grpc.Core.AsyncUnaryCall<Empty>(Task.FromResult(expectedResponse), null, null, null, null));
JobControllerClient client = new JobControllerClientImpl(mockGrpcClient.Object, null);
await client.DeleteJobAsync(request);
mockGrpcClient.VerifyAll();
}
}
}
| |
//---------------------------------------------------------------------------
//
// Copyright (C) Microsoft Corporation. All rights reserved.
//
// File: PtsHelper.cs
//
// Description: Helper services to query PTS objects.
//
// History:
// 05/05/2003 : [....] - moving from Avalon branch.
//
//---------------------------------------------------------------------------
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Security;
using System.Windows;
using System.Windows.Media;
using System.Windows.Documents;
using MS.Internal.Text;
using MS.Internal.Documents;
using MS.Internal.PtsHost.UnsafeNativeMethods;
namespace MS.Internal.PtsHost
{
// ----------------------------------------------------------------------
// Helper services to query PTS objects.
// ----------------------------------------------------------------------
internal static class PtsHelper
{
// ------------------------------------------------------------------
//
// Visual Helpers
//
// ------------------------------------------------------------------
#region Visual Helpers
// ------------------------------------------------------------------
// Update mirroring transform.
// ------------------------------------------------------------------
internal static void UpdateMirroringTransform(FlowDirection parentFD, FlowDirection childFD, ContainerVisual visualChild, double width)
{
// Set mirroring transform if necessary, or clear it just in case it was set in the previous
// format process.
if (parentFD != childFD)
{
MatrixTransform transform = new MatrixTransform(-1.0, 0.0, 0.0, 1.0, width, 0.0);
visualChild.Transform = transform;
visualChild.SetValue(FrameworkElement.FlowDirectionProperty, childFD);
}
else
{
visualChild.Transform = null;
visualChild.ClearValue(FrameworkElement.FlowDirectionProperty);
}
}
// ------------------------------------------------------------------
// Clips visual children to a specified rect
// ------------------------------------------------------------------
internal static void ClipChildrenToRect(ContainerVisual visual, Rect rect)
{
VisualCollection visualChildren = visual.Children;
for(int index = 0; index < visualChildren.Count; index++)
{
((ContainerVisual)visualChildren[index]).Clip = new RectangleGeometry(rect);
}
}
// ------------------------------------------------------------------
// Syncs a floating element para list with a visual collection
// ------------------------------------------------------------------
internal static void UpdateFloatingElementVisuals(ContainerVisual visual, List<BaseParaClient> floatingElementList)
{
VisualCollection visualChildren = visual.Children;
int visualIndex = 0;
if(floatingElementList == null || floatingElementList.Count == 0)
{
visualChildren.Clear();
}
else
{
for(int index = 0; index < floatingElementList.Count; index++)
{
Visual paraVisual = floatingElementList[index].Visual;
while(visualIndex < visualChildren.Count && visualChildren[visualIndex] != paraVisual)
{
visualChildren.RemoveAt(visualIndex);
}
if(visualIndex == visualChildren.Count)
{
visualChildren.Add(paraVisual);
}
visualIndex++;
}
if(visualChildren.Count > floatingElementList.Count)
{
visualChildren.RemoveRange(floatingElementList.Count, visualChildren.Count - floatingElementList.Count);
}
}
}
#endregion Visual Helpers
// ------------------------------------------------------------------
//
// Arrange Helpers
//
// ------------------------------------------------------------------
#region Arrange Helpers
//-------------------------------------------------------------------
// Arrange PTS track.
//-------------------------------------------------------------------
/// <SecurityNote>
/// Critical:
/// a) calls Critical function PTS.FsQueryTrackDetails.
/// b) calls Critical functions: ParaListFromTrack and ArrangeParaList.
/// </SecurityNote>
[SecurityCritical]
internal static void ArrangeTrack(
PtsContext ptsContext,
ref PTS.FSTRACKDESCRIPTION trackDesc,
uint fswdirTrack)
{
// There is possibility to get empty track. (example: large figures)
if (trackDesc.pfstrack != IntPtr.Zero)
{
// Get track details
PTS.FSTRACKDETAILS trackDetails;
PTS.Validate(PTS.FsQueryTrackDetails(ptsContext.Context, trackDesc.pfstrack, out trackDetails));
// There is possibility to get empty track.
if (trackDetails.cParas != 0)
{
// Get list of paragraphs
PTS.FSPARADESCRIPTION[] arrayParaDesc;
ParaListFromTrack(ptsContext, trackDesc.pfstrack, ref trackDetails, out arrayParaDesc);
// Arrange paragraphs
ArrangeParaList(ptsContext, trackDesc.fsrc, arrayParaDesc, fswdirTrack);
}
}
}
// ------------------------------------------------------------------
// Arrange para list.
// ------------------------------------------------------------------
/// <SecurityNote>
/// Critical, because:
/// a) calls Critical function BaseParaClient.Arrange.
/// b) calls Critical function PTS.FsTransformRectangle
/// </SecurityNote>
[SecurityCritical]
internal static void ArrangeParaList(
PtsContext ptsContext,
PTS.FSRECT rcTrackContent,
PTS.FSPARADESCRIPTION [] arrayParaDesc,
uint fswdirTrack)
{
// For each paragraph, do following:
// (1) Retrieve ParaClient object
// (2) Arrange and update paragraph metrics
int dvrPara = 0;
for (int index = 0; index < arrayParaDesc.Length; index++)
{
// (1) Retrieve ParaClient object
BaseParaClient paraClient = ptsContext.HandleToObject(arrayParaDesc[index].pfsparaclient) as BaseParaClient;
PTS.ValidateHandle(paraClient);
// Convert to appropriate page coordinates.
if(index == 0)
{
uint fswdirPage = PTS.FlowDirectionToFswdir(paraClient.PageFlowDirection);
if(fswdirTrack != fswdirPage)
{
PTS.FSRECT pageRect = paraClient.Paragraph.StructuralCache.CurrentArrangeContext.PageContext.PageRect;
PTS.Validate(PTS.FsTransformRectangle(fswdirTrack, ref pageRect, ref rcTrackContent, fswdirPage, out rcTrackContent));
}
}
// (2) Arrange and update paragraph metrics
int dvrTopSpace = arrayParaDesc[index].dvrTopSpace;
PTS.FSRECT rcPara = rcTrackContent;
rcPara.v += dvrPara + dvrTopSpace;
rcPara.dv = arrayParaDesc[index].dvrUsed - dvrTopSpace;
paraClient.Arrange(arrayParaDesc[index].pfspara, rcPara, dvrTopSpace, fswdirTrack);
dvrPara += arrayParaDesc[index].dvrUsed;
}
}
#endregion Arrange Helpers
// ------------------------------------------------------------------
//
// Update Visual Helpers
//
// ------------------------------------------------------------------
#region Update Visual Helpers
//-------------------------------------------------------------------
// Update PTS track (column) visuals.
//-------------------------------------------------------------------
/// <SecurityNote>
/// Critical:
/// a) calls Critical function PTS.FsQueryTrackDetails.
/// b) calls Critical function ParaListFromTrack.
/// </SecurityNote>
[SecurityCritical]
internal static void UpdateTrackVisuals(
PtsContext ptsContext,
VisualCollection visualCollection,
PTS.FSKUPDATE fskupdInherited,
ref PTS.FSTRACKDESCRIPTION trackDesc)
{
PTS.FSKUPDATE fskupd = trackDesc.fsupdinf.fskupd;
if (trackDesc.fsupdinf.fskupd == PTS.FSKUPDATE.fskupdInherited)
{
fskupd = fskupdInherited;
}
// If there is no change, visual information is valid
if (fskupd == PTS.FSKUPDATE.fskupdNoChange) { return; }
ErrorHandler.Assert(fskupd != PTS.FSKUPDATE.fskupdShifted, ErrorHandler.UpdateShiftedNotValid);
bool emptyTrack = (trackDesc.pfstrack == IntPtr.Zero);
if (!emptyTrack)
{
// Get track details
PTS.FSTRACKDETAILS trackDetails;
PTS.Validate(PTS.FsQueryTrackDetails(ptsContext.Context, trackDesc.pfstrack, out trackDetails));
emptyTrack = (trackDetails.cParas == 0);
if (!emptyTrack)
{
// Get list of paragraphs
PTS.FSPARADESCRIPTION[] arrayParaDesc;
ParaListFromTrack(ptsContext, trackDesc.pfstrack, ref trackDetails, out arrayParaDesc);
// Update visuals for list of paragraphs
UpdateParaListVisuals(ptsContext, visualCollection, fskupd, arrayParaDesc);
}
}
// There is possibility to get empty track. (example: large figures)
if (emptyTrack)
{
// There is no content, remove all existing children visuals.
visualCollection.Clear();
}
}
// ------------------------------------------------------------------
// Update visuals for list of paragraphs.
// ------------------------------------------------------------------
internal static void UpdateParaListVisuals(
PtsContext ptsContext,
VisualCollection visualCollection,
PTS.FSKUPDATE fskupdInherited,
PTS.FSPARADESCRIPTION [] arrayParaDesc)
{
// For each paragraph, do following:
// (1) Retrieve ParaClient object
// (3) Update visual, if necessary
for (int index = 0; index < arrayParaDesc.Length; index++)
{
// (1) Retrieve ParaClient object
BaseParaClient paraClient = ptsContext.HandleToObject(arrayParaDesc[index].pfsparaclient) as BaseParaClient;
PTS.ValidateHandle(paraClient);
// (2) Update visual, if necessary
PTS.FSKUPDATE fskupd = arrayParaDesc[index].fsupdinf.fskupd;
if (fskupd == PTS.FSKUPDATE.fskupdInherited)
{
fskupd = fskupdInherited;
}
if (fskupd == PTS.FSKUPDATE.fskupdNew)
{
// Disconnect visual from its old parent, if necessary.
Visual currentParent = VisualTreeHelper.GetParent(paraClient.Visual) as Visual;
if(currentParent != null)
{
ContainerVisual parent = currentParent as ContainerVisual;
Invariant.Assert(parent != null, "parent should always derives from ContainerVisual");
parent.Children.Remove(paraClient.Visual);
}
// New paragraph - insert new visual node
visualCollection.Insert(index, paraClient.Visual);
paraClient.ValidateVisual(fskupd);
}
else
{
// Remove visuals for non-existing paragraphs
while (visualCollection[index] != paraClient.Visual)
{
visualCollection.RemoveAt(index);
Invariant.Assert(index < visualCollection.Count);
}
if(fskupd == PTS.FSKUPDATE.fskupdChangeInside || fskupd == PTS.FSKUPDATE.fskupdShifted)
{
paraClient.ValidateVisual(fskupd);
}
}
}
// Remove obsolete visuals
if (arrayParaDesc.Length < visualCollection.Count)
{
visualCollection.RemoveRange(arrayParaDesc.Length, visualCollection.Count - arrayParaDesc.Length);
}
}
#endregion Update Visual Helpers
#region Update Viewport Helpers
//-------------------------------------------------------------------
// Update viewport for track
//-------------------------------------------------------------------
/// <SecurityNote>
/// Critical:
/// a) calls Critical function PTS.FsQueryTrackDetails.
/// b) calls Critical function ParaListFromTrack.
/// </SecurityNote>
[SecurityCritical]
internal static void UpdateViewportTrack(
PtsContext ptsContext,
ref PTS.FSTRACKDESCRIPTION trackDesc,
ref PTS.FSRECT viewport)
{
// There is possibility to get empty track. (example: large figures)
if (trackDesc.pfstrack != IntPtr.Zero)
{
// Get track details
PTS.FSTRACKDETAILS trackDetails;
PTS.Validate(PTS.FsQueryTrackDetails(ptsContext.Context, trackDesc.pfstrack, out trackDetails));
// There is possibility to get empty track.
if (trackDetails.cParas != 0)
{
// Get list of paragraphs
PTS.FSPARADESCRIPTION[] arrayParaDesc;
ParaListFromTrack(ptsContext, trackDesc.pfstrack, ref trackDetails, out arrayParaDesc);
// Arrange paragraphs
UpdateViewportParaList(ptsContext, arrayParaDesc, ref viewport);
}
}
}
// ------------------------------------------------------------------
// Update viewport for para list
// ------------------------------------------------------------------
internal static void UpdateViewportParaList(
PtsContext ptsContext,
PTS.FSPARADESCRIPTION [] arrayParaDesc,
ref PTS.FSRECT viewport)
{
for (int index = 0; index < arrayParaDesc.Length; index++)
{
// (1) Retrieve ParaClient object
BaseParaClient paraClient = ptsContext.HandleToObject(arrayParaDesc[index].pfsparaclient) as BaseParaClient;
PTS.ValidateHandle(paraClient);
paraClient.UpdateViewport(ref viewport);
}
}
#endregion Arrange Helpers
// ------------------------------------------------------------------
//
// HitTest Helpers
//
// ------------------------------------------------------------------
#region HitTest Helpers
// ------------------------------------------------------------------
// Hit tests to the correct IInputElement within the track that the
// mouse is over.
// ------------------------------------------------------------------
/// <SecurityNote>
/// Critical:
/// a) calls Critical function PTS.FsQueryTrackDetails.
/// b) calls Critical function ParaListFromTrack.
/// </SecurityNote>
[SecurityCritical]
internal static IInputElement InputHitTestTrack(
PtsContext ptsContext,
PTS.FSPOINT pt,
ref PTS.FSTRACKDESCRIPTION trackDesc)
{
// There is possibility to get empty track. (example: large figures)
if (trackDesc.pfstrack == IntPtr.Zero) { return null; }
IInputElement ie = null;
// Get track details
PTS.FSTRACKDETAILS trackDetails;
PTS.Validate(PTS.FsQueryTrackDetails(ptsContext.Context, trackDesc.pfstrack, out trackDetails));
// There might be possibility to get empty track, skip the track
// in such case.
if (trackDetails.cParas != 0)
{
// Get list of paragraphs
PTS.FSPARADESCRIPTION[] arrayParaDesc;
ParaListFromTrack(ptsContext, trackDesc.pfstrack, ref trackDetails, out arrayParaDesc);
// Hittest list of paragraphs
ie = InputHitTestParaList(ptsContext, pt, ref trackDesc.fsrc, arrayParaDesc);
}
return ie;
}
// ------------------------------------------------------------------
// Hit tests to the correct IInputElement within the list of
// paragraphs that the mouse is over.
// ------------------------------------------------------------------
internal static IInputElement InputHitTestParaList(
PtsContext ptsContext,
PTS.FSPOINT pt,
ref PTS.FSRECT rcTrack, // track's rectangle
PTS.FSPARADESCRIPTION [] arrayParaDesc)
{
IInputElement ie = null;
for (int index = 0; index < arrayParaDesc.Length && ie == null; index++)
{
BaseParaClient paraClient = ptsContext.HandleToObject(arrayParaDesc[index].pfsparaclient) as BaseParaClient;
PTS.ValidateHandle(paraClient);
if(paraClient.Rect.Contains(pt))
{
ie = paraClient.InputHitTest(pt);
}
}
return ie;
}
#endregion HitTest Helpers
// ------------------------------------------------------------------
//
// GetRectangles Helpers
//
// ------------------------------------------------------------------
#region GetRectangles Helpers
// ------------------------------------------------------------------
// Returns ArrayList of rectangles for the ContentElement e within
// the specified track. If e is not found or if track contains nothing,
// returns empty list
//
// start: int representing start offset of e
// length: int representing number of positions occupied by e
// ------------------------------------------------------------------
/// <SecurityNote>
/// Critical:
/// a) calls Critical function PTS.FsQueryTrackDetails.
/// b) calls Critical function ParaListFromTrack.
/// </SecurityNote>
[SecurityCritical]
internal static List<Rect> GetRectanglesInTrack(
PtsContext ptsContext,
ContentElement e,
int start,
int length,
ref PTS.FSTRACKDESCRIPTION trackDesc)
{
List<Rect> rectangles = new List<Rect>();
// There is possibility to get empty track. (example: large figures)
if (trackDesc.pfstrack == IntPtr.Zero)
{
// TRack is empty. Return empty list.
return rectangles;
}
// Get track details
PTS.FSTRACKDETAILS trackDetails;
PTS.Validate(PTS.FsQueryTrackDetails(ptsContext.Context, trackDesc.pfstrack, out trackDetails));
// There might be possibility to get empty track, skip the track
// in such case.
if (trackDetails.cParas != 0)
{
// Get list of paragraphs
PTS.FSPARADESCRIPTION[] arrayParaDesc;
ParaListFromTrack(ptsContext, trackDesc.pfstrack, ref trackDetails, out arrayParaDesc);
// Check list of paragraphs for element
rectangles = GetRectanglesInParaList(ptsContext, e, start, length, arrayParaDesc);
}
return rectangles;
}
// ------------------------------------------------------------------
// Returns ArrayList of rectangles for the ContentElement e within the
// list of paragraphs. If the element is not found, returns empty list.
// start: int representing start offset of e
// length: int representing number of positions occupied by e
// ------------------------------------------------------------------
internal static List<Rect> GetRectanglesInParaList(
PtsContext ptsContext,
ContentElement e,
int start,
int length,
PTS.FSPARADESCRIPTION[] arrayParaDesc)
{
List<Rect> rectangles = new List<Rect>();
for (int index = 0; index < arrayParaDesc.Length; index++)
{
BaseParaClient paraClient = ptsContext.HandleToObject(arrayParaDesc[index].pfsparaclient) as BaseParaClient;
PTS.ValidateHandle(paraClient);
if (start < paraClient.Paragraph.ParagraphEndCharacterPosition)
{
// Element lies within the paraClient boundaries.
rectangles = paraClient.GetRectangles(e, start, length);
// Rectangles collection should not be null for consistency
Invariant.Assert(rectangles != null);
if (rectangles.Count != 0)
{
// Element cannot span more than one para client in the same track, so we stop
// if the element is found and the rectangles are calculated
break;
}
}
}
return rectangles;
}
// ------------------------------------------------------------------
// Returns List of rectangles offset by x/y values.
// ------------------------------------------------------------------
internal static List<Rect> OffsetRectangleList(List<Rect> rectangleList, double xOffset, double yOffset)
{
List<Rect> offsetRectangles = new List<Rect>(rectangleList.Count);
for(int index = 0; index < rectangleList.Count; index++)
{
Rect rect = rectangleList[index];
rect.X += xOffset;
rect.Y += yOffset;
offsetRectangles.Add(rect);
}
return offsetRectangles;
}
#endregion GetRectangles Helpers
// ------------------------------------------------------------------
//
// Query Helpers
//
// ------------------------------------------------------------------
#region Query Helpers
// ------------------------------------------------------------------
// Retrieve section list from page.
// ------------------------------------------------------------------
/// <SecurityNote>
/// Critical, because:
/// a) calls Critical function PTS.FsQueryPageSectionList,
/// b) it is unsafe method.
/// </SecurityNote>
[SecurityCritical]
internal static unsafe void SectionListFromPage(
PtsContext ptsContext,
IntPtr page,
ref PTS.FSPAGEDETAILS pageDetails,
out PTS.FSSECTIONDESCRIPTION [] arraySectionDesc)
{
arraySectionDesc = new PTS.FSSECTIONDESCRIPTION [pageDetails.u.complex.cSections];
int sectionCount;
fixed (PTS.FSSECTIONDESCRIPTION* rgSectionDesc = arraySectionDesc)
{
PTS.Validate(PTS.FsQueryPageSectionList(ptsContext.Context, page, pageDetails.u.complex.cSections,
rgSectionDesc, out sectionCount));
}
ErrorHandler.Assert(pageDetails.u.complex.cSections == sectionCount, ErrorHandler.PTSObjectsCountMismatch);
}
// ------------------------------------------------------------------
// Retrieve track (column) list from subpage.
// ------------------------------------------------------------------
///<SecurityNote>
/// Critical, because:
/// a) calls Critical function PTS.FsQuerySubpageBasicColumnList,
/// b) it is unsafe method.
/// </SecurityNote>
[SecurityCritical]
internal static unsafe void TrackListFromSubpage(
PtsContext ptsContext,
IntPtr subpage,
ref PTS.FSSUBPAGEDETAILS subpageDetails,
out PTS.FSTRACKDESCRIPTION [] arrayTrackDesc)
{
arrayTrackDesc = new PTS.FSTRACKDESCRIPTION [subpageDetails.u.complex.cBasicColumns];
int trackCount;
fixed (PTS.FSTRACKDESCRIPTION* rgTrackDesc = arrayTrackDesc)
{
PTS.Validate(PTS.FsQuerySubpageBasicColumnList(ptsContext.Context, subpage, subpageDetails.u.complex.cBasicColumns,
rgTrackDesc, out trackCount));
}
ErrorHandler.Assert(subpageDetails.u.complex.cBasicColumns == trackCount, ErrorHandler.PTSObjectsCountMismatch);
}
// ------------------------------------------------------------------
// Retrieve track (column) list from section.
// ------------------------------------------------------------------
/// <SecurityNote>
/// Critical, because:
/// a) calls Critical function PTS.FsQuerySectionBasicColumnList,
/// b) it is unsafe method.
/// </SecurityNote>
[SecurityCritical]
internal static unsafe void TrackListFromSection(
PtsContext ptsContext,
IntPtr section,
ref PTS.FSSECTIONDETAILS sectionDetails,
out PTS.FSTRACKDESCRIPTION [] arrayTrackDesc)
{
//
Debug.Assert(sectionDetails.u.withpagenotes.cSegmentDefinedColumnSpanAreas == 0);
Debug.Assert(sectionDetails.u.withpagenotes.cHeightDefinedColumnSpanAreas == 0);
arrayTrackDesc = new PTS.FSTRACKDESCRIPTION[sectionDetails.u.withpagenotes.cBasicColumns];
int trackCount;
fixed (PTS.FSTRACKDESCRIPTION* rgTrackDesc = arrayTrackDesc)
{
PTS.Validate(PTS.FsQuerySectionBasicColumnList(ptsContext.Context, section, sectionDetails.u.withpagenotes.cBasicColumns,
rgTrackDesc, out trackCount));
}
ErrorHandler.Assert(sectionDetails.u.withpagenotes.cBasicColumns == trackCount, ErrorHandler.PTSObjectsCountMismatch);
}
// ------------------------------------------------------------------
// Retrieve paragraph list from the track.
// ------------------------------------------------------------------
/// <SecurityNote>
/// Critical, because:
/// a) calls Critical function PTS.FsQueryTrackParaList,
/// b) it is unsafe method.
/// </SecurityNote>
[SecurityCritical]
internal static unsafe void ParaListFromTrack(
PtsContext ptsContext,
IntPtr track,
ref PTS.FSTRACKDETAILS trackDetails,
out PTS.FSPARADESCRIPTION [] arrayParaDesc)
{
arrayParaDesc = new PTS.FSPARADESCRIPTION [trackDetails.cParas];
int paraCount;
fixed (PTS.FSPARADESCRIPTION* rgParaDesc = arrayParaDesc)
{
PTS.Validate(PTS.FsQueryTrackParaList(ptsContext.Context, track, trackDetails.cParas,
rgParaDesc, out paraCount));
}
ErrorHandler.Assert(trackDetails.cParas == paraCount, ErrorHandler.PTSObjectsCountMismatch);
}
// ------------------------------------------------------------------
// Retrieve paragraph list from the track.
// ------------------------------------------------------------------
/// <SecurityNote>
/// Critical, because:
/// a) calls Critical function PTS.FsQuerySubtrackParaList,
/// b) it is unsafe method.
/// </SecurityNote>
[SecurityCritical]
internal static unsafe void ParaListFromSubtrack(
PtsContext ptsContext,
IntPtr subtrack,
ref PTS.FSSUBTRACKDETAILS subtrackDetails,
out PTS.FSPARADESCRIPTION [] arrayParaDesc)
{
arrayParaDesc = new PTS.FSPARADESCRIPTION [subtrackDetails.cParas];
int paraCount;
fixed (PTS.FSPARADESCRIPTION* rgParaDesc = arrayParaDesc)
{
PTS.Validate(PTS.FsQuerySubtrackParaList(ptsContext.Context, subtrack, subtrackDetails.cParas,
rgParaDesc, out paraCount));
}
ErrorHandler.Assert(subtrackDetails.cParas == paraCount, ErrorHandler.PTSObjectsCountMismatch);
}
// ------------------------------------------------------------------
// Retrieve simple line list from the full text paragraph.
// ------------------------------------------------------------------
/// <SecurityNote>
/// Critical, because:
/// a) calls Critical function PTS.FsQueryLineListSingle,
/// b) it is unsafe method.
/// </SecurityNote>
[SecurityCritical]
internal static unsafe void LineListSimpleFromTextPara(
PtsContext ptsContext,
IntPtr para,
ref PTS.FSTEXTDETAILSFULL textDetails,
out PTS.FSLINEDESCRIPTIONSINGLE [] arrayLineDesc)
{
arrayLineDesc = new PTS.FSLINEDESCRIPTIONSINGLE [textDetails.cLines];
int lineCount;
fixed (PTS.FSLINEDESCRIPTIONSINGLE* rgLineDesc = arrayLineDesc)
{
PTS.Validate(PTS.FsQueryLineListSingle(ptsContext.Context, para, textDetails.cLines,
rgLineDesc, out lineCount));
}
ErrorHandler.Assert(textDetails.cLines == lineCount, ErrorHandler.PTSObjectsCountMismatch);
}
// ------------------------------------------------------------------
// Retrieve composite line list from the full text paragraph.
// ------------------------------------------------------------------
/// <SecurityNote>
/// Critical, because:
/// a) calls Critical function PTS.FsQueryLineListComposite,
/// b) it is unsafe method.
/// </SecurityNote>
[SecurityCritical]
internal static unsafe void LineListCompositeFromTextPara(
PtsContext ptsContext,
IntPtr para,
ref PTS.FSTEXTDETAILSFULL textDetails,
out PTS.FSLINEDESCRIPTIONCOMPOSITE [] arrayLineDesc)
{
arrayLineDesc = new PTS.FSLINEDESCRIPTIONCOMPOSITE [textDetails.cLines];
int lineCount;
fixed (PTS.FSLINEDESCRIPTIONCOMPOSITE* rgLineDesc = arrayLineDesc)
{
PTS.Validate(PTS.FsQueryLineListComposite(ptsContext.Context, para, textDetails.cLines,
rgLineDesc, out lineCount));
}
ErrorHandler.Assert(textDetails.cLines == lineCount, ErrorHandler.PTSObjectsCountMismatch);
}
// ------------------------------------------------------------------
// Retrieve line elements list from the composite line.
// ------------------------------------------------------------------
/// <SecurityNote>
/// Critical, because:
/// a) calls Critical function PTS.FsQueryLineCompositeElementList,
/// b) it is unsafe method.
/// </SecurityNote>
[SecurityCritical]
internal static unsafe void LineElementListFromCompositeLine(
PtsContext ptsContext,
ref PTS.FSLINEDESCRIPTIONCOMPOSITE lineDesc,
out PTS.FSLINEELEMENT [] arrayLineElement)
{
arrayLineElement = new PTS.FSLINEELEMENT [lineDesc.cElements];
int lineElementCount;
fixed (PTS.FSLINEELEMENT* rgLineElement = arrayLineElement)
{
PTS.Validate(PTS.FsQueryLineCompositeElementList(ptsContext.Context, lineDesc.pline, lineDesc.cElements,
rgLineElement, out lineElementCount));
}
ErrorHandler.Assert(lineDesc.cElements == lineElementCount, ErrorHandler.PTSObjectsCountMismatch);
}
// ------------------------------------------------------------------
// Retrieve attached object list from the paragraph.
// ------------------------------------------------------------------
/// <SecurityNote>
/// Critical, because:
/// a) calls Critical function PTS.FsQueryAttachedObjectList,
/// b) it is unsafe method.
/// </SecurityNote>
[SecurityCritical]
internal static unsafe void AttachedObjectListFromParagraph(
PtsContext ptsContext,
IntPtr para,
int cAttachedObject,
out PTS.FSATTACHEDOBJECTDESCRIPTION [] arrayAttachedObjectDesc)
{
arrayAttachedObjectDesc = new PTS.FSATTACHEDOBJECTDESCRIPTION [cAttachedObject];
int attachedObjectCount;
fixed (PTS.FSATTACHEDOBJECTDESCRIPTION* rgAttachedObjectDesc = arrayAttachedObjectDesc)
{
PTS.Validate(PTS.FsQueryAttachedObjectList(ptsContext.Context, para, cAttachedObject, rgAttachedObjectDesc, out attachedObjectCount));
}
ErrorHandler.Assert(cAttachedObject == attachedObjectCount, ErrorHandler.PTSObjectsCountMismatch);
}
#endregion Query Helpers
// ------------------------------------------------------------------
//
// Misc Helpers
//
// ------------------------------------------------------------------
#region Misc Helpers
// ------------------------------------------------------------------
// Retrieve TextContentRange from PTS track.
// ------------------------------------------------------------------
/// <SecurityNote>
/// Critical:
/// a) calls Critical function PTS.FsQueryTrackDetails.
/// b) calls Critical function ParaListFromTrack.
/// </SecurityNote>
[SecurityCritical]
internal static TextContentRange TextContentRangeFromTrack(
PtsContext ptsContext,
IntPtr pfstrack)
{
// Get track details
PTS.FSTRACKDETAILS trackDetails;
PTS.Validate(PTS.FsQueryTrackDetails(ptsContext.Context, pfstrack, out trackDetails));
// Combine ranges from all nested paragraphs.
TextContentRange textContentRange = new TextContentRange();
if (trackDetails.cParas != 0)
{
PTS.FSPARADESCRIPTION[] arrayParaDesc;
PtsHelper.ParaListFromTrack(ptsContext, pfstrack, ref trackDetails, out arrayParaDesc);
// Merge TextContentRanges for all paragraphs
BaseParaClient paraClient;
for (int i = 0; i < arrayParaDesc.Length; i++)
{
paraClient = ptsContext.HandleToObject(arrayParaDesc[i].pfsparaclient) as BaseParaClient;
PTS.ValidateHandle(paraClient);
textContentRange.Merge(paraClient.GetTextContentRange());
}
}
return textContentRange;
}
// ------------------------------------------------------------------
// Calculates a page margin adjustment to eliminate free space if column width is not flexible
// ------------------------------------------------------------------
internal static double CalculatePageMarginAdjustment(StructuralCache structuralCache, double pageMarginWidth)
{
double pageMarginAdjustment = 0.0;
DependencyObject o = structuralCache.Section.Element;
if(o is FlowDocument)
{
ColumnPropertiesGroup columnProperties = new ColumnPropertiesGroup(o);
if(!columnProperties.IsColumnWidthFlexible)
{
double lineHeight = DynamicPropertyReader.GetLineHeightValue(o);
double pageFontSize = (double)structuralCache.PropertyOwner.GetValue(Block.FontSizeProperty);
FontFamily pageFontFamily = (FontFamily)structuralCache.PropertyOwner.GetValue(Block.FontFamilyProperty);
int ccol = PtsHelper.CalculateColumnCount(columnProperties, lineHeight, pageMarginWidth, pageFontSize, pageFontFamily, true);
double columnWidth;
double freeSpace;
double gap;
GetColumnMetrics(columnProperties, pageMarginWidth,
pageFontSize, pageFontFamily, true, ccol,
ref lineHeight, out columnWidth, out freeSpace, out gap);
pageMarginAdjustment = freeSpace;
}
}
return pageMarginAdjustment;
}
// ------------------------------------------------------------------
// Calculate column count based on column properties.
// If column width is Auto column count is calculated by assuming
// ColumnWidth as 20*FontSize
// ------------------------------------------------------------------
internal static int CalculateColumnCount(
ColumnPropertiesGroup columnProperties,
double lineHeight,
double pageWidth,
double pageFontSize,
FontFamily pageFontFamily,
bool enableColumns)
{
int columns = 1;
double gap;
double rule = columnProperties.ColumnRuleWidth;
if (enableColumns)
{
if (columnProperties.ColumnGapAuto)
{
gap = 1 * lineHeight;
}
else
{
gap = columnProperties.ColumnGap;
}
if (!columnProperties.ColumnWidthAuto)
{
// Column count is ignored in this case
double column = columnProperties.ColumnWidth;
columns = (int)((pageWidth + gap) / (column + gap));
}
else
{
// Column width is assumed to be 20*FontSize
double column = 20 * pageFontSize;
columns = (int)((pageWidth + gap) / (column + gap));
}
}
return Math.Max(1, Math.Min(PTS.Restrictions.tscColumnRestriction-1, columns)); // at least 1 column is required
}
// ------------------------------------------------------------------
// GetColumnMetrics
// ------------------------------------------------------------------
internal static void GetColumnMetrics(ColumnPropertiesGroup columnProperties,
double pageWidth,
double pageFontSize,
FontFamily pageFontFamily,
bool enableColumns,
int cColumns,
ref double lineHeight,
out double columnWidth,
out double freeSpace,
out double gapSpace)
{
double rule = columnProperties.ColumnRuleWidth;
if (!enableColumns)
{
Invariant.Assert(cColumns == 1);
columnWidth = pageWidth;
gapSpace = 0;
lineHeight = 0;
freeSpace = 0;
}
else
{
// For FlowDocument, calculate default column width
if (columnProperties.ColumnWidthAuto)
{
columnWidth = 20 * pageFontSize;
}
else
{
columnWidth = columnProperties.ColumnWidth;
}
if (columnProperties.ColumnGapAuto)
{
gapSpace = 1 * lineHeight;
}
else
{
gapSpace = columnProperties.ColumnGap;
}
}
columnWidth = Math.Max(1, Math.Min(columnWidth, pageWidth));
freeSpace = pageWidth - (cColumns * columnWidth) - (cColumns - 1) * gapSpace;
freeSpace = Math.Max(0, freeSpace);
}
// ------------------------------------------------------------------
// Get columns info
// ------------------------------------------------------------------
/// <SecurityNote>
/// Critical, because it is unsafe method.
/// </SecurityNote>
[SecurityCritical]
internal static unsafe void GetColumnsInfo(
ColumnPropertiesGroup columnProperties,
double lineHeight,
double pageWidth,
double pageFontSize,
FontFamily pageFontFamily,
int cColumns,
PTS.FSCOLUMNINFO* pfscolinfo,
bool enableColumns)
{
Debug.Assert(cColumns > 0, "At least one column is required.");
double columnWidth;
double freeSpace;
double gap;
double rule = columnProperties.ColumnRuleWidth;
GetColumnMetrics(columnProperties, pageWidth,
pageFontSize, pageFontFamily, enableColumns, cColumns,
ref lineHeight, out columnWidth, out freeSpace, out gap);
// Set columns information
if (!columnProperties.IsColumnWidthFlexible)
{
// All columns have the declared width
// ColumnGap is flexible and is increased based on ColumnSpaceDistribution policy
// (ColumnGap is effectively min)
for (int i = 0; i < cColumns; i++)
{
// Today there is no way to change the default value of ColumnSpaceDistribution.
// If column widths are not flexible, always allocate unused space on the right side.
pfscolinfo[i].durBefore = TextDpi.ToTextDpi((i == 0) ? 0 : gap);
pfscolinfo[i].durWidth = TextDpi.ToTextDpi(columnWidth);
// ColumnWidth has to be > 0 and SpaceBefore has to be >= 0
pfscolinfo[i].durBefore = Math.Max(0, pfscolinfo[i].durBefore);
pfscolinfo[i].durWidth = Math.Max(1, pfscolinfo[i].durWidth);
}
}
else
{
// ColumnGap is honored
// ColumnWidth is effectively min, and space is distributed according to ColumnSpaceDistribution policy
for (int i = 0; i < cColumns; i++)
{
if (columnProperties.ColumnSpaceDistribution == ColumnSpaceDistribution.Right)
{
pfscolinfo[i].durWidth = TextDpi.ToTextDpi((i == cColumns - 1) ? columnWidth + freeSpace : columnWidth);
}
else if (columnProperties.ColumnSpaceDistribution == ColumnSpaceDistribution.Left)
{
pfscolinfo[i].durWidth = TextDpi.ToTextDpi((i == 0) ? columnWidth + freeSpace : columnWidth);
}
else
{
pfscolinfo[i].durWidth = TextDpi.ToTextDpi(columnWidth + (freeSpace / cColumns));
}
// If calculated column width is greater than the page width, set it to page width to
// avoid clipping
if (pfscolinfo[i].durWidth > TextDpi.ToTextDpi(pageWidth))
{
pfscolinfo[i].durWidth = TextDpi.ToTextDpi(pageWidth);
}
pfscolinfo[i].durBefore = TextDpi.ToTextDpi((i == 0) ? 0 : gap);
// ColumnWidth has to be > 0 and SpaceBefore has to be >= 0
pfscolinfo[i].durBefore = Math.Max(0, pfscolinfo[i].durBefore);
pfscolinfo[i].durWidth = Math.Max(1, pfscolinfo[i].durWidth);
}
}
}
#endregion Misc Helpers
}
}
| |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Threading;
using System.Linq.Expressions;
/// <summary>
/// The type WorkbookChartDataLabelsRequest.
/// </summary>
public partial class WorkbookChartDataLabelsRequest : BaseRequest, IWorkbookChartDataLabelsRequest
{
/// <summary>
/// Constructs a new WorkbookChartDataLabelsRequest.
/// </summary>
/// <param name="requestUrl">The URL for the built request.</param>
/// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param>
/// <param name="options">Query and header option name value pairs for the request.</param>
public WorkbookChartDataLabelsRequest(
string requestUrl,
IBaseClient client,
IEnumerable<Option> options)
: base(requestUrl, client, options)
{
}
/// <summary>
/// Creates the specified WorkbookChartDataLabels using POST.
/// </summary>
/// <param name="workbookChartDataLabelsToCreate">The WorkbookChartDataLabels to create.</param>
/// <returns>The created WorkbookChartDataLabels.</returns>
public System.Threading.Tasks.Task<WorkbookChartDataLabels> CreateAsync(WorkbookChartDataLabels workbookChartDataLabelsToCreate)
{
return this.CreateAsync(workbookChartDataLabelsToCreate, CancellationToken.None);
}
/// <summary>
/// Creates the specified WorkbookChartDataLabels using POST.
/// </summary>
/// <param name="workbookChartDataLabelsToCreate">The WorkbookChartDataLabels to create.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The created WorkbookChartDataLabels.</returns>
public async System.Threading.Tasks.Task<WorkbookChartDataLabels> CreateAsync(WorkbookChartDataLabels workbookChartDataLabelsToCreate, CancellationToken cancellationToken)
{
this.ContentType = "application/json";
this.Method = "POST";
var newEntity = await this.SendAsync<WorkbookChartDataLabels>(workbookChartDataLabelsToCreate, cancellationToken).ConfigureAwait(false);
this.InitializeCollectionProperties(newEntity);
return newEntity;
}
/// <summary>
/// Deletes the specified WorkbookChartDataLabels.
/// </summary>
/// <returns>The task to await.</returns>
public System.Threading.Tasks.Task DeleteAsync()
{
return this.DeleteAsync(CancellationToken.None);
}
/// <summary>
/// Deletes the specified WorkbookChartDataLabels.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The task to await.</returns>
public async System.Threading.Tasks.Task DeleteAsync(CancellationToken cancellationToken)
{
this.Method = "DELETE";
await this.SendAsync<WorkbookChartDataLabels>(null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets the specified WorkbookChartDataLabels.
/// </summary>
/// <returns>The WorkbookChartDataLabels.</returns>
public System.Threading.Tasks.Task<WorkbookChartDataLabels> GetAsync()
{
return this.GetAsync(CancellationToken.None);
}
/// <summary>
/// Gets the specified WorkbookChartDataLabels.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The WorkbookChartDataLabels.</returns>
public async System.Threading.Tasks.Task<WorkbookChartDataLabels> GetAsync(CancellationToken cancellationToken)
{
this.Method = "GET";
var retrievedEntity = await this.SendAsync<WorkbookChartDataLabels>(null, cancellationToken).ConfigureAwait(false);
this.InitializeCollectionProperties(retrievedEntity);
return retrievedEntity;
}
/// <summary>
/// Updates the specified WorkbookChartDataLabels using PATCH.
/// </summary>
/// <param name="workbookChartDataLabelsToUpdate">The WorkbookChartDataLabels to update.</param>
/// <returns>The updated WorkbookChartDataLabels.</returns>
public System.Threading.Tasks.Task<WorkbookChartDataLabels> UpdateAsync(WorkbookChartDataLabels workbookChartDataLabelsToUpdate)
{
return this.UpdateAsync(workbookChartDataLabelsToUpdate, CancellationToken.None);
}
/// <summary>
/// Updates the specified WorkbookChartDataLabels using PATCH.
/// </summary>
/// <param name="workbookChartDataLabelsToUpdate">The WorkbookChartDataLabels to update.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The updated WorkbookChartDataLabels.</returns>
public async System.Threading.Tasks.Task<WorkbookChartDataLabels> UpdateAsync(WorkbookChartDataLabels workbookChartDataLabelsToUpdate, CancellationToken cancellationToken)
{
this.ContentType = "application/json";
this.Method = "PATCH";
var updatedEntity = await this.SendAsync<WorkbookChartDataLabels>(workbookChartDataLabelsToUpdate, cancellationToken).ConfigureAwait(false);
this.InitializeCollectionProperties(updatedEntity);
return updatedEntity;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="value">The expand value.</param>
/// <returns>The request object to send.</returns>
public IWorkbookChartDataLabelsRequest Expand(string value)
{
this.QueryOptions.Add(new QueryOption("$expand", value));
return this;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="expandExpression">The expression from which to calculate the expand value.</param>
/// <returns>The request object to send.</returns>
public IWorkbookChartDataLabelsRequest Expand(Expression<Func<WorkbookChartDataLabels, object>> expandExpression)
{
if (expandExpression == null)
{
throw new ArgumentNullException(nameof(expandExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(expandExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$expand", value));
}
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="value">The select value.</param>
/// <returns>The request object to send.</returns>
public IWorkbookChartDataLabelsRequest Select(string value)
{
this.QueryOptions.Add(new QueryOption("$select", value));
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="selectExpression">The expression from which to calculate the select value.</param>
/// <returns>The request object to send.</returns>
public IWorkbookChartDataLabelsRequest Select(Expression<Func<WorkbookChartDataLabels, object>> selectExpression)
{
if (selectExpression == null)
{
throw new ArgumentNullException(nameof(selectExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(selectExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$select", value));
}
return this;
}
/// <summary>
/// Initializes any collection properties after deserialization, like next requests for paging.
/// </summary>
/// <param name="workbookChartDataLabelsToInitialize">The <see cref="WorkbookChartDataLabels"/> with the collection properties to initialize.</param>
private void InitializeCollectionProperties(WorkbookChartDataLabels workbookChartDataLabelsToInitialize)
{
}
}
}
| |
//
// (C) Copyright 2003-2011 by Autodesk, Inc.
//
// Permission to use, copy, modify, and distribute this software in
// object code form for any purpose and without fee is hereby granted,
// provided that the above copyright notice appears in all copies and
// that both that copyright notice and the limited warranty and
// restricted rights notice below appear in all supporting
// documentation.
//
// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC.
// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
// UNINTERRUPTED OR ERROR FREE.
//
// Use, duplication, or disclosure by the U.S. Government is subject to
// restrictions set forth in FAR 52.227-19 (Commercial Computer
// Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii)
// (Rights in Technical Data and Computer Software), as applicable.
//
namespace Revit.SDK.Samples.ViewPrinter.CS
{
partial class PrintSetupForm
{
/// <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.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.printerNameLabel = new System.Windows.Forms.Label();
this.printSetupsComboBox = new System.Windows.Forms.ComboBox();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.paperSourceComboBox = new System.Windows.Forms.ComboBox();
this.paperSizeComboBox = new System.Windows.Forms.ComboBox();
this.label4 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.groupBox2 = new System.Windows.Forms.GroupBox();
this.landscapeRadioButton = new System.Windows.Forms.RadioButton();
this.portraitRadioButton = new System.Windows.Forms.RadioButton();
this.groupBox3 = new System.Windows.Forms.GroupBox();
this.label6 = new System.Windows.Forms.Label();
this.label5 = new System.Windows.Forms.Label();
this.userDefinedMarginYTextBox = new System.Windows.Forms.TextBox();
this.userDefinedMarginXTextBox = new System.Windows.Forms.TextBox();
this.marginTypeComboBox = new System.Windows.Forms.ComboBox();
this.offsetRadioButton = new System.Windows.Forms.RadioButton();
this.centerRadioButton = new System.Windows.Forms.RadioButton();
this.groupBox4 = new System.Windows.Forms.GroupBox();
this.rasterRadioButton = new System.Windows.Forms.RadioButton();
this.vectorRadioButton = new System.Windows.Forms.RadioButton();
this.label7 = new System.Windows.Forms.Label();
this.groupBox5 = new System.Windows.Forms.GroupBox();
this.zoomPercentNumericUpDown = new System.Windows.Forms.NumericUpDown();
this.label8 = new System.Windows.Forms.Label();
this.zoomRadioButton = new System.Windows.Forms.RadioButton();
this.fitToPageRadioButton = new System.Windows.Forms.RadioButton();
this.groupBox6 = new System.Windows.Forms.GroupBox();
this.label10 = new System.Windows.Forms.Label();
this.colorsComboBox = new System.Windows.Forms.ComboBox();
this.rasterQualityComboBox = new System.Windows.Forms.ComboBox();
this.label9 = new System.Windows.Forms.Label();
this.groupBox7 = new System.Windows.Forms.GroupBox();
this.hideCropBoundariesCheckBox = new System.Windows.Forms.CheckBox();
this.hideScopeBoxedCheckBox = new System.Windows.Forms.CheckBox();
this.hideUnreferencedViewTagsCheckBox = new System.Windows.Forms.CheckBox();
this.hideRefWorkPlanesCheckBox = new System.Windows.Forms.CheckBox();
this.ViewLinksInBlueCheckBox = new System.Windows.Forms.CheckBox();
this.okButton = new System.Windows.Forms.Button();
this.cancelButton = new System.Windows.Forms.Button();
this.saveButton = new System.Windows.Forms.Button();
this.saveAsButton = new System.Windows.Forms.Button();
this.revertButton = new System.Windows.Forms.Button();
this.renameButton = new System.Windows.Forms.Button();
this.deleteButton = new System.Windows.Forms.Button();
this.groupBox1.SuspendLayout();
this.groupBox2.SuspendLayout();
this.groupBox3.SuspendLayout();
this.groupBox4.SuspendLayout();
this.groupBox5.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.zoomPercentNumericUpDown)).BeginInit();
this.groupBox6.SuspendLayout();
this.groupBox7.SuspendLayout();
this.SuspendLayout();
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(12, 9);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(40, 13);
this.label1.TabIndex = 0;
this.label1.Text = "Printer:";
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(12, 35);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(38, 13);
this.label2.TabIndex = 0;
this.label2.Text = "Name:";
//
// printerNameLabel
//
this.printerNameLabel.AutoSize = true;
this.printerNameLabel.Location = new System.Drawing.Point(58, 9);
this.printerNameLabel.Name = "printerNameLabel";
this.printerNameLabel.Size = new System.Drawing.Size(33, 13);
this.printerNameLabel.TabIndex = 0;
this.printerNameLabel.Text = "blank";
//
// printSetupsComboBox
//
this.printSetupsComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.printSetupsComboBox.FormattingEnabled = true;
this.printSetupsComboBox.Location = new System.Drawing.Point(56, 32);
this.printSetupsComboBox.Name = "printSetupsComboBox";
this.printSetupsComboBox.Size = new System.Drawing.Size(358, 21);
this.printSetupsComboBox.TabIndex = 1;
//
// groupBox1
//
this.groupBox1.Controls.Add(this.paperSourceComboBox);
this.groupBox1.Controls.Add(this.paperSizeComboBox);
this.groupBox1.Controls.Add(this.label4);
this.groupBox1.Controls.Add(this.label3);
this.groupBox1.Location = new System.Drawing.Point(15, 75);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(200, 77);
this.groupBox1.TabIndex = 2;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Paper";
//
// paperSourceComboBox
//
this.paperSourceComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.paperSourceComboBox.FormattingEnabled = true;
this.paperSourceComboBox.Location = new System.Drawing.Point(73, 44);
this.paperSourceComboBox.Name = "paperSourceComboBox";
this.paperSourceComboBox.Size = new System.Drawing.Size(121, 21);
this.paperSourceComboBox.TabIndex = 1;
//
// paperSizeComboBox
//
this.paperSizeComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.paperSizeComboBox.FormattingEnabled = true;
this.paperSizeComboBox.Location = new System.Drawing.Point(73, 20);
this.paperSizeComboBox.Name = "paperSizeComboBox";
this.paperSizeComboBox.Size = new System.Drawing.Size(121, 21);
this.paperSizeComboBox.TabIndex = 1;
//
// label4
//
this.label4.AutoSize = true;
this.label4.Location = new System.Drawing.Point(6, 47);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(44, 13);
this.label4.TabIndex = 0;
this.label4.Text = "S&ource:";
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(6, 23);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(30, 13);
this.label3.TabIndex = 0;
this.label3.Text = "Size:";
//
// groupBox2
//
this.groupBox2.Controls.Add(this.landscapeRadioButton);
this.groupBox2.Controls.Add(this.portraitRadioButton);
this.groupBox2.Location = new System.Drawing.Point(221, 75);
this.groupBox2.Name = "groupBox2";
this.groupBox2.Size = new System.Drawing.Size(200, 77);
this.groupBox2.TabIndex = 2;
this.groupBox2.TabStop = false;
this.groupBox2.Text = "Orientation";
//
// landscapeRadioButton
//
this.landscapeRadioButton.AutoSize = true;
this.landscapeRadioButton.Location = new System.Drawing.Point(108, 48);
this.landscapeRadioButton.Name = "landscapeRadioButton";
this.landscapeRadioButton.Size = new System.Drawing.Size(78, 17);
this.landscapeRadioButton.TabIndex = 0;
this.landscapeRadioButton.TabStop = true;
this.landscapeRadioButton.Text = "&Landscape";
this.landscapeRadioButton.UseVisualStyleBackColor = true;
//
// portraitRadioButton
//
this.portraitRadioButton.AutoSize = true;
this.portraitRadioButton.Location = new System.Drawing.Point(108, 24);
this.portraitRadioButton.Name = "portraitRadioButton";
this.portraitRadioButton.Size = new System.Drawing.Size(58, 17);
this.portraitRadioButton.TabIndex = 0;
this.portraitRadioButton.TabStop = true;
this.portraitRadioButton.Text = "&Portrait";
this.portraitRadioButton.UseVisualStyleBackColor = true;
//
// groupBox3
//
this.groupBox3.Controls.Add(this.label6);
this.groupBox3.Controls.Add(this.label5);
this.groupBox3.Controls.Add(this.userDefinedMarginYTextBox);
this.groupBox3.Controls.Add(this.userDefinedMarginXTextBox);
this.groupBox3.Controls.Add(this.marginTypeComboBox);
this.groupBox3.Controls.Add(this.offsetRadioButton);
this.groupBox3.Controls.Add(this.centerRadioButton);
this.groupBox3.Location = new System.Drawing.Point(15, 158);
this.groupBox3.Name = "groupBox3";
this.groupBox3.Size = new System.Drawing.Size(200, 100);
this.groupBox3.TabIndex = 2;
this.groupBox3.TabStop = false;
this.groupBox3.Text = "Paper Placement";
//
// label6
//
this.label6.AutoSize = true;
this.label6.Location = new System.Drawing.Point(176, 72);
this.label6.Name = "label6";
this.label6.Size = new System.Drawing.Size(18, 13);
this.label6.TabIndex = 3;
this.label6.Text = "=y";
//
// label5
//
this.label5.AutoSize = true;
this.label5.Location = new System.Drawing.Point(114, 72);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(18, 13);
this.label5.TabIndex = 3;
this.label5.Text = "=x";
//
// userDefinedMarginYTextBox
//
this.userDefinedMarginYTextBox.Location = new System.Drawing.Point(138, 69);
this.userDefinedMarginYTextBox.Name = "userDefinedMarginYTextBox";
this.userDefinedMarginYTextBox.Size = new System.Drawing.Size(35, 20);
this.userDefinedMarginYTextBox.TabIndex = 2;
this.userDefinedMarginYTextBox.Text = "0.000";
//
// userDefinedMarginXTextBox
//
this.userDefinedMarginXTextBox.Location = new System.Drawing.Point(73, 69);
this.userDefinedMarginXTextBox.Name = "userDefinedMarginXTextBox";
this.userDefinedMarginXTextBox.Size = new System.Drawing.Size(35, 20);
this.userDefinedMarginXTextBox.TabIndex = 2;
this.userDefinedMarginXTextBox.Text = "0.000";
//
// marginTypeComboBox
//
this.marginTypeComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.marginTypeComboBox.FormattingEnabled = true;
this.marginTypeComboBox.Location = new System.Drawing.Point(73, 42);
this.marginTypeComboBox.Name = "marginTypeComboBox";
this.marginTypeComboBox.Size = new System.Drawing.Size(121, 21);
this.marginTypeComboBox.TabIndex = 1;
//
// offsetRadioButton
//
this.offsetRadioButton.AutoSize = true;
this.offsetRadioButton.Location = new System.Drawing.Point(73, 19);
this.offsetRadioButton.Name = "offsetRadioButton";
this.offsetRadioButton.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.offsetRadioButton.Size = new System.Drawing.Size(109, 17);
this.offsetRadioButton.TabIndex = 0;
this.offsetRadioButton.TabStop = true;
this.offsetRadioButton.Text = "Offset fro&m corner";
this.offsetRadioButton.UseVisualStyleBackColor = true;
//
// centerRadioButton
//
this.centerRadioButton.AutoSize = true;
this.centerRadioButton.Location = new System.Drawing.Point(9, 19);
this.centerRadioButton.Name = "centerRadioButton";
this.centerRadioButton.Size = new System.Drawing.Size(56, 17);
this.centerRadioButton.TabIndex = 0;
this.centerRadioButton.TabStop = true;
this.centerRadioButton.Text = "&Center";
this.centerRadioButton.UseVisualStyleBackColor = true;
//
// groupBox4
//
this.groupBox4.Controls.Add(this.rasterRadioButton);
this.groupBox4.Controls.Add(this.vectorRadioButton);
this.groupBox4.Controls.Add(this.label7);
this.groupBox4.Location = new System.Drawing.Point(221, 158);
this.groupBox4.Name = "groupBox4";
this.groupBox4.Size = new System.Drawing.Size(200, 100);
this.groupBox4.TabIndex = 2;
this.groupBox4.TabStop = false;
this.groupBox4.Text = "Hidden Line Views";
//
// rasterRadioButton
//
this.rasterRadioButton.AutoSize = true;
this.rasterRadioButton.Location = new System.Drawing.Point(9, 68);
this.rasterRadioButton.Name = "rasterRadioButton";
this.rasterRadioButton.Size = new System.Drawing.Size(111, 17);
this.rasterRadioButton.TabIndex = 1;
this.rasterRadioButton.TabStop = true;
this.rasterRadioButton.Text = "Raster Processin&g";
this.rasterRadioButton.UseVisualStyleBackColor = true;
//
// vectorRadioButton
//
this.vectorRadioButton.AutoSize = true;
this.vectorRadioButton.Location = new System.Drawing.Point(9, 42);
this.vectorRadioButton.Name = "vectorRadioButton";
this.vectorRadioButton.Size = new System.Drawing.Size(146, 17);
this.vectorRadioButton.TabIndex = 1;
this.vectorRadioButton.TabStop = true;
this.vectorRadioButton.Text = "V&ector Processing (faster)";
this.vectorRadioButton.UseVisualStyleBackColor = true;
//
// label7
//
this.label7.AutoSize = true;
this.label7.Location = new System.Drawing.Point(6, 21);
this.label7.Name = "label7";
this.label7.Size = new System.Drawing.Size(102, 13);
this.label7.TabIndex = 0;
this.label7.Text = "Remove lines using:";
//
// groupBox5
//
this.groupBox5.Controls.Add(this.zoomPercentNumericUpDown);
this.groupBox5.Controls.Add(this.label8);
this.groupBox5.Controls.Add(this.zoomRadioButton);
this.groupBox5.Controls.Add(this.fitToPageRadioButton);
this.groupBox5.Location = new System.Drawing.Point(15, 264);
this.groupBox5.Name = "groupBox5";
this.groupBox5.Size = new System.Drawing.Size(200, 100);
this.groupBox5.TabIndex = 2;
this.groupBox5.TabStop = false;
this.groupBox5.Text = "Zoom";
//
// zoomPercentNumericUpDown
//
this.zoomPercentNumericUpDown.Location = new System.Drawing.Point(86, 42);
this.zoomPercentNumericUpDown.Maximum = new decimal(new int[] {
100000,
0,
0,
0});
this.zoomPercentNumericUpDown.Minimum = new decimal(new int[] {
1,
0,
0,
0});
this.zoomPercentNumericUpDown.Name = "zoomPercentNumericUpDown";
this.zoomPercentNumericUpDown.Size = new System.Drawing.Size(46, 20);
this.zoomPercentNumericUpDown.TabIndex = 3;
this.zoomPercentNumericUpDown.Value = new decimal(new int[] {
100,
0,
0,
0});
this.zoomPercentNumericUpDown.ValueChanged += new System.EventHandler(this.zoomPercentNumericUpDown_ValueChanged);
//
// label8
//
this.label8.AutoSize = true;
this.label8.Location = new System.Drawing.Point(138, 44);
this.label8.Name = "label8";
this.label8.Size = new System.Drawing.Size(36, 13);
this.label8.TabIndex = 2;
this.label8.Text = "% size";
//
// zoomRadioButton
//
this.zoomRadioButton.AutoSize = true;
this.zoomRadioButton.Location = new System.Drawing.Point(6, 42);
this.zoomRadioButton.Name = "zoomRadioButton";
this.zoomRadioButton.Size = new System.Drawing.Size(55, 17);
this.zoomRadioButton.TabIndex = 0;
this.zoomRadioButton.TabStop = true;
this.zoomRadioButton.Text = "&Zoom:";
this.zoomRadioButton.UseVisualStyleBackColor = true;
//
// fitToPageRadioButton
//
this.fitToPageRadioButton.AutoSize = true;
this.fitToPageRadioButton.Location = new System.Drawing.Point(6, 19);
this.fitToPageRadioButton.Name = "fitToPageRadioButton";
this.fitToPageRadioButton.Size = new System.Drawing.Size(75, 17);
this.fitToPageRadioButton.TabIndex = 0;
this.fitToPageRadioButton.TabStop = true;
this.fitToPageRadioButton.Text = "&Fit to page";
this.fitToPageRadioButton.UseVisualStyleBackColor = true;
//
// groupBox6
//
this.groupBox6.Controls.Add(this.label10);
this.groupBox6.Controls.Add(this.colorsComboBox);
this.groupBox6.Controls.Add(this.rasterQualityComboBox);
this.groupBox6.Controls.Add(this.label9);
this.groupBox6.Location = new System.Drawing.Point(221, 264);
this.groupBox6.Name = "groupBox6";
this.groupBox6.Size = new System.Drawing.Size(200, 100);
this.groupBox6.TabIndex = 2;
this.groupBox6.TabStop = false;
this.groupBox6.Text = "Appearance";
//
// label10
//
this.label10.AutoSize = true;
this.label10.Location = new System.Drawing.Point(6, 56);
this.label10.Name = "label10";
this.label10.Size = new System.Drawing.Size(39, 13);
this.label10.TabIndex = 2;
this.label10.Text = "Colo&rs:";
//
// colorsComboBox
//
this.colorsComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.colorsComboBox.FormattingEnabled = true;
this.colorsComboBox.Location = new System.Drawing.Point(9, 72);
this.colorsComboBox.Name = "colorsComboBox";
this.colorsComboBox.Size = new System.Drawing.Size(121, 21);
this.colorsComboBox.TabIndex = 1;
//
// rasterQualityComboBox
//
this.rasterQualityComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.rasterQualityComboBox.FormattingEnabled = true;
this.rasterQualityComboBox.Location = new System.Drawing.Point(9, 32);
this.rasterQualityComboBox.Name = "rasterQualityComboBox";
this.rasterQualityComboBox.Size = new System.Drawing.Size(121, 21);
this.rasterQualityComboBox.TabIndex = 1;
//
// label9
//
this.label9.AutoSize = true;
this.label9.Location = new System.Drawing.Point(6, 16);
this.label9.Name = "label9";
this.label9.Size = new System.Drawing.Size(74, 13);
this.label9.TabIndex = 0;
this.label9.Text = "Raster &quality:";
//
// groupBox7
//
this.groupBox7.Controls.Add(this.hideCropBoundariesCheckBox);
this.groupBox7.Controls.Add(this.hideScopeBoxedCheckBox);
this.groupBox7.Controls.Add(this.hideUnreferencedViewTagsCheckBox);
this.groupBox7.Controls.Add(this.hideRefWorkPlanesCheckBox);
this.groupBox7.Controls.Add(this.ViewLinksInBlueCheckBox);
this.groupBox7.Location = new System.Drawing.Point(15, 370);
this.groupBox7.Name = "groupBox7";
this.groupBox7.Size = new System.Drawing.Size(406, 100);
this.groupBox7.TabIndex = 2;
this.groupBox7.TabStop = false;
this.groupBox7.Text = "Options";
//
// hideCropBoundariesCheckBox
//
this.hideCropBoundariesCheckBox.AutoSize = true;
this.hideCropBoundariesCheckBox.Location = new System.Drawing.Point(206, 42);
this.hideCropBoundariesCheckBox.Name = "hideCropBoundariesCheckBox";
this.hideCropBoundariesCheckBox.Size = new System.Drawing.Size(127, 17);
this.hideCropBoundariesCheckBox.TabIndex = 4;
this.hideCropBoundariesCheckBox.Text = "Hide crop &boundaries";
this.hideCropBoundariesCheckBox.UseVisualStyleBackColor = true;
//
// hideScopeBoxedCheckBox
//
this.hideScopeBoxedCheckBox.AutoSize = true;
this.hideScopeBoxedCheckBox.Location = new System.Drawing.Point(206, 19);
this.hideScopeBoxedCheckBox.Name = "hideScopeBoxedCheckBox";
this.hideScopeBoxedCheckBox.Size = new System.Drawing.Size(112, 17);
this.hideScopeBoxedCheckBox.TabIndex = 4;
this.hideScopeBoxedCheckBox.Text = "Hide scope bo&xed";
this.hideScopeBoxedCheckBox.UseVisualStyleBackColor = true;
//
// hideUnreferencedViewTagsCheckBox
//
this.hideUnreferencedViewTagsCheckBox.AutoSize = true;
this.hideUnreferencedViewTagsCheckBox.Location = new System.Drawing.Point(6, 65);
this.hideUnreferencedViewTagsCheckBox.Name = "hideUnreferencedViewTagsCheckBox";
this.hideUnreferencedViewTagsCheckBox.Size = new System.Drawing.Size(162, 17);
this.hideUnreferencedViewTagsCheckBox.TabIndex = 4;
this.hideUnreferencedViewTagsCheckBox.Text = "Hide &unreferenced view tags";
this.hideUnreferencedViewTagsCheckBox.UseVisualStyleBackColor = true;
//
// hideRefWorkPlanesCheckBox
//
this.hideRefWorkPlanesCheckBox.AutoSize = true;
this.hideRefWorkPlanesCheckBox.Location = new System.Drawing.Point(6, 42);
this.hideRefWorkPlanesCheckBox.Name = "hideRefWorkPlanesCheckBox";
this.hideRefWorkPlanesCheckBox.Size = new System.Drawing.Size(125, 17);
this.hideRefWorkPlanesCheckBox.TabIndex = 4;
this.hideRefWorkPlanesCheckBox.Text = "Hide ref/&work planes";
this.hideRefWorkPlanesCheckBox.UseVisualStyleBackColor = true;
//
// ViewLinksInBlueCheckBox
//
this.ViewLinksInBlueCheckBox.AutoSize = true;
this.ViewLinksInBlueCheckBox.Location = new System.Drawing.Point(6, 19);
this.ViewLinksInBlueCheckBox.Name = "ViewLinksInBlueCheckBox";
this.ViewLinksInBlueCheckBox.Size = new System.Drawing.Size(107, 17);
this.ViewLinksInBlueCheckBox.TabIndex = 4;
this.ViewLinksInBlueCheckBox.Text = "View lin&ks in blue";
this.ViewLinksInBlueCheckBox.UseVisualStyleBackColor = true;
//
// okButton
//
this.okButton.DialogResult = System.Windows.Forms.DialogResult.OK;
this.okButton.Location = new System.Drawing.Point(388, 487);
this.okButton.Name = "okButton";
this.okButton.Size = new System.Drawing.Size(75, 23);
this.okButton.TabIndex = 3;
this.okButton.Text = "OK";
this.okButton.UseVisualStyleBackColor = true;
//
// cancelButton
//
this.cancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.cancelButton.Location = new System.Drawing.Point(469, 487);
this.cancelButton.Name = "cancelButton";
this.cancelButton.Size = new System.Drawing.Size(75, 23);
this.cancelButton.TabIndex = 3;
this.cancelButton.Text = "Cancel";
this.cancelButton.UseVisualStyleBackColor = true;
//
// saveButton
//
this.saveButton.Location = new System.Drawing.Point(469, 35);
this.saveButton.Name = "saveButton";
this.saveButton.Size = new System.Drawing.Size(75, 23);
this.saveButton.TabIndex = 3;
this.saveButton.Text = "&Save";
this.saveButton.UseVisualStyleBackColor = true;
this.saveButton.Click += new System.EventHandler(this.saveButton_Click);
//
// saveAsButton
//
this.saveAsButton.Location = new System.Drawing.Point(469, 64);
this.saveAsButton.Name = "saveAsButton";
this.saveAsButton.Size = new System.Drawing.Size(75, 23);
this.saveAsButton.TabIndex = 3;
this.saveAsButton.Text = "Sa&veAs...";
this.saveAsButton.UseVisualStyleBackColor = true;
this.saveAsButton.Click += new System.EventHandler(this.saveAsButton_Click);
//
// revertButton
//
this.revertButton.Enabled = false;
this.revertButton.Location = new System.Drawing.Point(469, 93);
this.revertButton.Name = "revertButton";
this.revertButton.Size = new System.Drawing.Size(75, 23);
this.revertButton.TabIndex = 3;
this.revertButton.Text = "Rever&t";
this.revertButton.UseVisualStyleBackColor = true;
this.revertButton.Click += new System.EventHandler(this.revertButton_Click);
//
// renameButton
//
this.renameButton.Location = new System.Drawing.Point(469, 122);
this.renameButton.Name = "renameButton";
this.renameButton.Size = new System.Drawing.Size(75, 23);
this.renameButton.TabIndex = 3;
this.renameButton.Text = "Ren&ame";
this.renameButton.UseVisualStyleBackColor = true;
this.renameButton.Click += new System.EventHandler(this.renameButton_Click);
//
// deleteButton
//
this.deleteButton.Location = new System.Drawing.Point(469, 151);
this.deleteButton.Name = "deleteButton";
this.deleteButton.Size = new System.Drawing.Size(75, 23);
this.deleteButton.TabIndex = 3;
this.deleteButton.Text = "&Delete";
this.deleteButton.UseVisualStyleBackColor = true;
this.deleteButton.Click += new System.EventHandler(this.deleteButton_Click);
//
// PrintSetupForm
//
this.AcceptButton = this.okButton;
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.CancelButton = this.cancelButton;
this.ClientSize = new System.Drawing.Size(556, 522);
this.Controls.Add(this.cancelButton);
this.Controls.Add(this.deleteButton);
this.Controls.Add(this.renameButton);
this.Controls.Add(this.revertButton);
this.Controls.Add(this.saveAsButton);
this.Controls.Add(this.saveButton);
this.Controls.Add(this.okButton);
this.Controls.Add(this.groupBox2);
this.Controls.Add(this.groupBox6);
this.Controls.Add(this.groupBox7);
this.Controls.Add(this.groupBox5);
this.Controls.Add(this.groupBox4);
this.Controls.Add(this.groupBox3);
this.Controls.Add(this.groupBox1);
this.Controls.Add(this.printSetupsComboBox);
this.Controls.Add(this.label2);
this.Controls.Add(this.printerNameLabel);
this.Controls.Add(this.label1);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "PrintSetupForm";
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "Print Setup";
this.Load += new System.EventHandler(this.PrintSetupForm_Load);
this.groupBox1.ResumeLayout(false);
this.groupBox1.PerformLayout();
this.groupBox2.ResumeLayout(false);
this.groupBox2.PerformLayout();
this.groupBox3.ResumeLayout(false);
this.groupBox3.PerformLayout();
this.groupBox4.ResumeLayout(false);
this.groupBox4.PerformLayout();
this.groupBox5.ResumeLayout(false);
this.groupBox5.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.zoomPercentNumericUpDown)).EndInit();
this.groupBox6.ResumeLayout(false);
this.groupBox6.PerformLayout();
this.groupBox7.ResumeLayout(false);
this.groupBox7.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label printerNameLabel;
private System.Windows.Forms.ComboBox printSetupsComboBox;
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.GroupBox groupBox2;
private System.Windows.Forms.GroupBox groupBox3;
private System.Windows.Forms.GroupBox groupBox4;
private System.Windows.Forms.GroupBox groupBox5;
private System.Windows.Forms.GroupBox groupBox6;
private System.Windows.Forms.GroupBox groupBox7;
private System.Windows.Forms.Button okButton;
private System.Windows.Forms.Button cancelButton;
private System.Windows.Forms.Button saveButton;
private System.Windows.Forms.Button saveAsButton;
private System.Windows.Forms.Button revertButton;
private System.Windows.Forms.Button renameButton;
private System.Windows.Forms.Button deleteButton;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.ComboBox paperSourceComboBox;
private System.Windows.Forms.ComboBox paperSizeComboBox;
private System.Windows.Forms.RadioButton landscapeRadioButton;
private System.Windows.Forms.RadioButton portraitRadioButton;
private System.Windows.Forms.RadioButton centerRadioButton;
private System.Windows.Forms.Label label6;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.TextBox userDefinedMarginYTextBox;
private System.Windows.Forms.TextBox userDefinedMarginXTextBox;
private System.Windows.Forms.ComboBox marginTypeComboBox;
private System.Windows.Forms.RadioButton offsetRadioButton;
private System.Windows.Forms.RadioButton rasterRadioButton;
private System.Windows.Forms.RadioButton vectorRadioButton;
private System.Windows.Forms.Label label7;
private System.Windows.Forms.RadioButton zoomRadioButton;
private System.Windows.Forms.RadioButton fitToPageRadioButton;
private System.Windows.Forms.Label label8;
private System.Windows.Forms.Label label10;
private System.Windows.Forms.ComboBox colorsComboBox;
private System.Windows.Forms.ComboBox rasterQualityComboBox;
private System.Windows.Forms.Label label9;
private System.Windows.Forms.CheckBox hideCropBoundariesCheckBox;
private System.Windows.Forms.CheckBox hideScopeBoxedCheckBox;
private System.Windows.Forms.CheckBox hideUnreferencedViewTagsCheckBox;
private System.Windows.Forms.CheckBox hideRefWorkPlanesCheckBox;
private System.Windows.Forms.CheckBox ViewLinksInBlueCheckBox;
private System.Windows.Forms.NumericUpDown zoomPercentNumericUpDown;
}
}
| |
// 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.Globalization;
using System.Text;
using System.Runtime.InteropServices;
using System.Diagnostics;
namespace System
{
public partial class Uri
{
//
// All public ctors go through here
//
private void CreateThis(string uri, bool dontEscape, UriKind uriKind)
{
// if (!Enum.IsDefined(typeof(UriKind), uriKind)) -- We currently believe that Enum.IsDefined() is too slow
// to be used here.
if ((int)uriKind < (int)UriKind.RelativeOrAbsolute || (int)uriKind > (int)UriKind.Relative)
{
throw new ArgumentException(SR.Format(SR.net_uri_InvalidUriKind, uriKind));
}
_string = uri == null ? string.Empty : uri;
if (dontEscape)
_flags |= Flags.UserEscaped;
ParsingError err = ParseScheme(_string, ref _flags, ref _syntax);
UriFormatException e;
InitializeUri(err, uriKind, out e);
if (e != null)
throw e;
}
private void InitializeUri(ParsingError err, UriKind uriKind, out UriFormatException e)
{
if (err == ParsingError.None)
{
if (IsImplicitFile)
{
// V1 compat
// A relative Uri wins over implicit UNC path unless the UNC path is of the form "\\something" and
// uriKind != Absolute
if (NotAny(Flags.DosPath) &&
uriKind != UriKind.Absolute &&
(uriKind == UriKind.Relative || (_string.Length >= 2 && (_string[0] != '\\' || _string[1] != '\\'))))
{
_syntax = null; //make it be relative Uri
_flags &= Flags.UserEscaped; // the only flag that makes sense for a relative uri
e = null;
return;
// Otheriwse an absolute file Uri wins when it's of the form "\\something"
}
//
// V1 compat issue
// We should support relative Uris of the form c:\bla or c:/bla
//
else if (uriKind == UriKind.Relative && InFact(Flags.DosPath))
{
_syntax = null; //make it be relative Uri
_flags &= Flags.UserEscaped; // the only flag that makes sense for a relative uri
e = null;
return;
// Otheriwse an absolute file Uri wins when it's of the form "c:\something"
}
}
}
else if (err > ParsingError.LastRelativeUriOkErrIndex)
{
//This is a fatal error based solely on scheme name parsing
_string = null; // make it be invalid Uri
e = GetException(err);
return;
}
bool hasUnicode = false;
_iriParsing = (s_IriParsing && ((_syntax == null) || _syntax.InFact(UriSyntaxFlags.AllowIriParsing)));
if (_iriParsing &&
(CheckForUnicode(_string) || CheckForEscapedUnreserved(_string)))
{
_flags |= Flags.HasUnicode;
hasUnicode = true;
// switch internal strings
_originalUnicodeString = _string; // original string location changed
}
if (_syntax != null)
{
if (_syntax.IsSimple)
{
if ((err = PrivateParseMinimal()) != ParsingError.None)
{
if (uriKind != UriKind.Absolute && err <= ParsingError.LastRelativeUriOkErrIndex)
{
// RFC 3986 Section 5.4.2 - http:(relativeUri) may be considered a valid relative Uri.
_syntax = null; // convert to relative uri
e = null;
_flags &= Flags.UserEscaped; // the only flag that makes sense for a relative uri
}
else
e = GetException(err);
}
else if (uriKind == UriKind.Relative)
{
// Here we know that we can create an absolute Uri, but the user has requested only a relative one
e = GetException(ParsingError.CannotCreateRelative);
}
else
e = null;
// will return from here
if (_iriParsing && hasUnicode)
{
// In this scenario we need to parse the whole string
EnsureParseRemaining();
}
}
else
{
// offer custom parser to create a parsing context
_syntax = _syntax.InternalOnNewUri();
// incase they won't call us
_flags |= Flags.UserDrivenParsing;
// Ask a registered type to validate this uri
_syntax.InternalValidate(this, out e);
if (e != null)
{
// Can we still take it as a relative Uri?
if (uriKind != UriKind.Absolute && err != ParsingError.None
&& err <= ParsingError.LastRelativeUriOkErrIndex)
{
_syntax = null; // convert it to relative
e = null;
_flags &= Flags.UserEscaped; // the only flag that makes sense for a relative uri
}
}
else // e == null
{
if (err != ParsingError.None || InFact(Flags.ErrorOrParsingRecursion))
{
// User parser took over on an invalid Uri
SetUserDrivenParsing();
}
else if (uriKind == UriKind.Relative)
{
// Here we know that custom parser can create an absolute Uri, but the user has requested only a
// relative one
e = GetException(ParsingError.CannotCreateRelative);
}
if (_iriParsing && hasUnicode)
{
// In this scenario we need to parse the whole string
EnsureParseRemaining();
}
}
// will return from here
}
}
// If we encountered any parsing errors that indicate this may be a relative Uri,
// and we'll allow relative Uri's, then create one.
else if (err != ParsingError.None && uriKind != UriKind.Absolute
&& err <= ParsingError.LastRelativeUriOkErrIndex)
{
e = null;
_flags &= (Flags.UserEscaped | Flags.HasUnicode); // the only flags that makes sense for a relative uri
if (_iriParsing && hasUnicode)
{
// Iri'ze and then normalize relative uris
_string = EscapeUnescapeIri(_originalUnicodeString, 0, _originalUnicodeString.Length,
(UriComponents)0);
}
}
else
{
_string = null; // make it be invalid Uri
e = GetException(err);
}
}
//
// Unescapes entire string and checks if it has unicode chars
//
private bool CheckForUnicode(string data)
{
bool hasUnicode = false;
char[] chars = new char[data.Length];
int count = 0;
chars = UriHelper.UnescapeString(data, 0, data.Length, chars, ref count, c_DummyChar, c_DummyChar,
c_DummyChar, UnescapeMode.Unescape | UnescapeMode.UnescapeAll, null, false);
for (int i = 0; i < count; ++i)
{
if (chars[i] > '\x7f')
{
// Unicode
hasUnicode = true;
break;
}
}
return hasUnicode;
}
// Does this string have any %6A sequences that are 3986 Unreserved characters? These should be un-escaped.
private unsafe bool CheckForEscapedUnreserved(string data)
{
fixed (char* tempPtr = data)
{
for (int i = 0; i < data.Length - 2; ++i)
{
if (tempPtr[i] == '%' && IsHexDigit(tempPtr[i + 1]) && IsHexDigit(tempPtr[i + 2])
&& tempPtr[i + 1] >= '0' && tempPtr[i + 1] <= '7') // max 0x7F
{
char ch = UriHelper.EscapedAscii(tempPtr[i + 1], tempPtr[i + 2]);
if (ch != c_DummyChar && UriHelper.Is3986Unreserved(ch))
{
return true;
}
}
}
}
return false;
}
//
// Returns true if the string represents a valid argument to the Uri ctor
// If uriKind != AbsoluteUri then certain parsing erros are ignored but Uri usage is limited
//
public static bool TryCreate(string uriString, UriKind uriKind, out Uri result)
{
if ((object)uriString == null)
{
result = null;
return false;
}
UriFormatException e = null;
result = CreateHelper(uriString, false, uriKind, ref e);
return (object)e == null && result != null;
}
public static bool TryCreate(Uri baseUri, string relativeUri, out Uri result)
{
Uri relativeLink;
if (TryCreate(relativeUri, UriKind.RelativeOrAbsolute, out relativeLink))
{
if (!relativeLink.IsAbsoluteUri)
return TryCreate(baseUri, relativeLink, out result);
result = relativeLink;
return true;
}
result = null;
return false;
}
public static bool TryCreate(Uri baseUri, Uri relativeUri, out Uri result)
{
result = null;
//TODO: Work out the baseUri==null case
if ((object)baseUri == null || (object)relativeUri == null)
return false;
if (baseUri.IsNotAbsoluteUri)
return false;
UriFormatException e;
string newUriString = null;
bool dontEscape;
if (baseUri.Syntax.IsSimple)
{
dontEscape = relativeUri.UserEscaped;
result = ResolveHelper(baseUri, relativeUri, ref newUriString, ref dontEscape, out e);
}
else
{
dontEscape = false;
newUriString = baseUri.Syntax.InternalResolve(baseUri, relativeUri, out e);
}
if (e != null)
return false;
if ((object)result == null)
result = CreateHelper(newUriString, dontEscape, UriKind.Absolute, ref e);
return (object)e == null && result != null && result.IsAbsoluteUri;
}
public string GetComponents(UriComponents components, UriFormat format)
{
if (((components & UriComponents.SerializationInfoString) != 0) && components != UriComponents.SerializationInfoString)
throw new ArgumentOutOfRangeException(nameof(components), components, SR.net_uri_NotJustSerialization);
if ((format & ~UriFormat.SafeUnescaped) != 0)
throw new ArgumentOutOfRangeException(nameof(format));
if (IsNotAbsoluteUri)
{
if (components == UriComponents.SerializationInfoString)
return GetRelativeSerializationString(format);
else
throw new InvalidOperationException(SR.net_uri_NotAbsolute);
}
if (Syntax.IsSimple)
return GetComponentsHelper(components, format);
return Syntax.InternalGetComponents(this, components, format);
}
//
// This is for languages that do not support == != operators overloading
//
// Note that Uri.Equals will get an optimized path but is limited to true/fasle result only
//
public static int Compare(Uri uri1, Uri uri2, UriComponents partsToCompare, UriFormat compareFormat,
StringComparison comparisonType)
{
if ((object)uri1 == null)
{
if (uri2 == null)
return 0; // Equal
return -1; // null < non-null
}
if ((object)uri2 == null)
return 1; // non-null > null
// a relative uri is always less than an absolute one
if (!uri1.IsAbsoluteUri || !uri2.IsAbsoluteUri)
return uri1.IsAbsoluteUri ? 1 : uri2.IsAbsoluteUri ? -1 : string.Compare(uri1.OriginalString,
uri2.OriginalString, comparisonType);
return string.Compare(
uri1.GetParts(partsToCompare, compareFormat),
uri2.GetParts(partsToCompare, compareFormat),
comparisonType
);
}
public bool IsWellFormedOriginalString()
{
if (IsNotAbsoluteUri || Syntax.IsSimple)
return InternalIsWellFormedOriginalString();
return Syntax.InternalIsWellFormedOriginalString(this);
}
// TODO: (perf) Making it to not create a Uri internally
public static bool IsWellFormedUriString(string uriString, UriKind uriKind)
{
Uri result;
if (!Uri.TryCreate(uriString, uriKind, out result))
return false;
return result.IsWellFormedOriginalString();
}
//
// Internal stuff
//
// Returns false if OriginalString value
// (1) is not correctly escaped as per URI spec excluding intl UNC name case
// (2) or is an absolute Uri that represents implicit file Uri "c:\dir\file"
// (3) or is an absolute Uri that misses a slash before path "file://c:/dir/file"
// (4) or contains unescaped backslashes even if they will be treated
// as forward slashes like http:\\host/path\file or file:\\\c:\path
//
internal unsafe bool InternalIsWellFormedOriginalString()
{
if (UserDrivenParsing)
throw new InvalidOperationException(SR.Format(SR.net_uri_UserDrivenParsing, this.GetType().ToString()));
fixed (char* str = _string)
{
ushort idx = 0;
//
// For a relative Uri we only care about escaping and backslashes
//
if (!IsAbsoluteUri)
{
// my:scheme/path?query is not well formed because the colon is ambiguous
if (CheckForColonInFirstPathSegment(_string))
{
return false;
}
return (CheckCanonical(str, ref idx, (ushort)_string.Length, c_EOL)
& (Check.BackslashInPath | Check.EscapedCanonical)) == Check.EscapedCanonical;
}
//
// (2) or is an absolute Uri that represents implicit file Uri "c:\dir\file"
//
if (IsImplicitFile)
return false;
//This will get all the offsets, a Host name will be checked separatelly below
EnsureParseRemaining();
Flags nonCanonical = (_flags & (Flags.E_CannotDisplayCanonical | Flags.IriCanonical));
// User, Path, Query or Fragment may have some non escaped characters
if (((nonCanonical & Flags.E_CannotDisplayCanonical & (Flags.E_UserNotCanonical | Flags.E_PathNotCanonical |
Flags.E_QueryNotCanonical | Flags.E_FragmentNotCanonical)) != Flags.Zero) &&
(!_iriParsing || (_iriParsing &&
(((nonCanonical & Flags.E_UserNotCanonical) == 0) || ((nonCanonical & Flags.UserIriCanonical) == 0)) &&
(((nonCanonical & Flags.E_PathNotCanonical) == 0) || ((nonCanonical & Flags.PathIriCanonical) == 0)) &&
(((nonCanonical & Flags.E_QueryNotCanonical) == 0) || ((nonCanonical & Flags.QueryIriCanonical) == 0)) &&
(((nonCanonical & Flags.E_FragmentNotCanonical) == 0) || ((nonCanonical & Flags.FragmentIriCanonical) == 0)))))
{
return false;
}
// checking on scheme:\\ or file:////
if (InFact(Flags.AuthorityFound))
{
idx = (ushort)(_info.Offset.Scheme + _syntax.SchemeName.Length + 2);
if (idx >= _info.Offset.User || _string[idx - 1] == '\\' || _string[idx] == '\\')
return false;
if (InFact(Flags.UncPath | Flags.DosPath))
{
while (++idx < _info.Offset.User && (_string[idx] == '/' || _string[idx] == '\\'))
return false;
}
}
// (3) or is an absolute Uri that misses a slash before path "file://c:/dir/file"
// Note that for this check to be more general we assert that if Path is non empty and if it requires a first slash
// (which looks absent) then the method has to fail.
// Today it's only possible for a Dos like path, i.e. file://c:/bla would fail below check.
if (InFact(Flags.FirstSlashAbsent) && _info.Offset.Query > _info.Offset.Path)
return false;
// (4) or contains unescaped backslashes even if they will be treated
// as forward slashes like http:\\host/path\file or file:\\\c:\path
// Note we do not check for Flags.ShouldBeCompressed i.e. allow // /./ and alike as valid
if (InFact(Flags.BackslashInPath))
return false;
// Capturing a rare case like file:///c|/dir
if (IsDosPath && _string[_info.Offset.Path + SecuredPathIndex - 1] == '|')
return false;
//
// May need some real CPU processing to anwser the request
//
//
// Check escaping for authority
//
// IPv6 hosts cannot be properly validated by CheckCannonical
if ((_flags & Flags.CanonicalDnsHost) == 0 && HostType != Flags.IPv6HostType)
{
idx = _info.Offset.User;
Check result = CheckCanonical(str, ref idx, (ushort)_info.Offset.Path, '/');
if (((result & (Check.ReservedFound | Check.BackslashInPath | Check.EscapedCanonical))
!= Check.EscapedCanonical)
&& (!_iriParsing || (_iriParsing
&& ((result & (Check.DisplayCanonical | Check.FoundNonAscii | Check.NotIriCanonical))
!= (Check.DisplayCanonical | Check.FoundNonAscii)))))
{
return false;
}
}
// Want to ensure there are slashes after the scheme
if ((_flags & (Flags.SchemeNotCanonical | Flags.AuthorityFound))
== (Flags.SchemeNotCanonical | Flags.AuthorityFound))
{
idx = (ushort)_syntax.SchemeName.Length;
while (str[idx++] != ':') ;
if (idx + 1 >= _string.Length || str[idx] != '/' || str[idx + 1] != '/')
return false;
}
}
//
// May be scheme, host, port or path need some canonicalization but still the uri string is found to be a
// "well formed" one
//
return true;
}
public static string UnescapeDataString(string stringToUnescape)
{
if ((object)stringToUnescape == null)
throw new ArgumentNullException(nameof(stringToUnescape));
if (stringToUnescape.Length == 0)
return string.Empty;
unsafe
{
fixed (char* pStr = stringToUnescape)
{
int position;
for (position = 0; position < stringToUnescape.Length; ++position)
if (pStr[position] == '%')
break;
if (position == stringToUnescape.Length)
return stringToUnescape;
UnescapeMode unescapeMode = UnescapeMode.Unescape | UnescapeMode.UnescapeAll;
position = 0;
char[] dest = new char[stringToUnescape.Length];
dest = UriHelper.UnescapeString(stringToUnescape, 0, stringToUnescape.Length, dest, ref position,
c_DummyChar, c_DummyChar, c_DummyChar, unescapeMode, null, false);
return new string(dest, 0, position);
}
}
}
//
// Where stringToEscape is intented to be a completely unescaped URI string.
// This method will escape any character that is not a reserved or unreserved character, including percent signs.
// Note that EscapeUriString will also do not escape a '#' sign.
//
public static string EscapeUriString(string stringToEscape)
{
if ((object)stringToEscape == null)
throw new ArgumentNullException(nameof(stringToEscape));
if (stringToEscape.Length == 0)
return string.Empty;
int position = 0;
char[] dest = UriHelper.EscapeString(stringToEscape, 0, stringToEscape.Length, null, ref position, true,
c_DummyChar, c_DummyChar, c_DummyChar);
if ((object)dest == null)
return stringToEscape;
return new string(dest, 0, position);
}
//
// Where stringToEscape is intended to be URI data, but not an entire URI.
// This method will escape any character that is not an unreserved character, including percent signs.
//
public static string EscapeDataString(string stringToEscape)
{
if ((object)stringToEscape == null)
throw new ArgumentNullException(nameof(stringToEscape));
if (stringToEscape.Length == 0)
return string.Empty;
int position = 0;
char[] dest = UriHelper.EscapeString(stringToEscape, 0, stringToEscape.Length, null, ref position, false,
c_DummyChar, c_DummyChar, c_DummyChar);
if (dest == null)
return stringToEscape;
return new string(dest, 0, position);
}
//
// Cleans up the specified component according to Iri rules
// a) Chars allowed by iri in a component are unescaped if found escaped
// b) Bidi chars are stripped
//
// should be called only if IRI parsing is switched on
internal unsafe string EscapeUnescapeIri(string input, int start, int end, UriComponents component)
{
fixed (char* pInput = input)
{
return IriHelper.EscapeUnescapeIri(pInput, start, end, component);
}
}
// Should never be used except by the below method
private Uri(Flags flags, UriParser uriParser, string uri)
{
_flags = flags;
_syntax = uriParser;
_string = uri;
}
//
// a Uri.TryCreate() method goes through here.
//
internal static Uri CreateHelper(string uriString, bool dontEscape, UriKind uriKind, ref UriFormatException e)
{
// if (!Enum.IsDefined(typeof(UriKind), uriKind)) -- We currently believe that Enum.IsDefined() is too slow
// to be used here.
if ((int)uriKind < (int)UriKind.RelativeOrAbsolute || (int)uriKind > (int)UriKind.Relative)
{
throw new ArgumentException(SR.Format(SR.net_uri_InvalidUriKind, uriKind));
}
UriParser syntax = null;
Flags flags = Flags.Zero;
ParsingError err = ParseScheme(uriString, ref flags, ref syntax);
if (dontEscape)
flags |= Flags.UserEscaped;
// We won't use User factory for these errors
if (err != ParsingError.None)
{
// If it looks as a relative Uri, custom factory is ignored
if (uriKind != UriKind.Absolute && err <= ParsingError.LastRelativeUriOkErrIndex)
return new Uri((flags & Flags.UserEscaped), null, uriString);
return null;
}
// Cannot be relative Uri if came here
Uri result = new Uri(flags, syntax, uriString);
// Validate instance using ether built in or a user Parser
try
{
result.InitializeUri(err, uriKind, out e);
if (e == null)
return result;
return null;
}
catch (UriFormatException ee)
{
Debug.Assert(!syntax.IsSimple, "A UriPraser threw on InitializeAndValidate.");
e = ee;
// A precaution since custom Parser should never throw in this case.
return null;
}
}
//
// Resolves into either baseUri or relativeUri according to conditions OR if not possible it uses newUriString
// to return combined URI strings from both Uris
// otherwise if e != null on output the operation has failed
//
internal static Uri ResolveHelper(Uri baseUri, Uri relativeUri, ref string newUriString, ref bool userEscaped,
out UriFormatException e)
{
Debug.Assert(!baseUri.IsNotAbsoluteUri && !baseUri.UserDrivenParsing, "Uri::ResolveHelper()|baseUri is not Absolute or is controlled by User Parser.");
e = null;
string relativeStr = string.Empty;
if ((object)relativeUri != null)
{
if (relativeUri.IsAbsoluteUri)
return relativeUri;
relativeStr = relativeUri.OriginalString;
userEscaped = relativeUri.UserEscaped;
}
else
relativeStr = string.Empty;
// Here we can assert that passed "relativeUri" is indeed a relative one
if (relativeStr.Length > 0 && (IsLWS(relativeStr[0]) || IsLWS(relativeStr[relativeStr.Length - 1])))
relativeStr = relativeStr.Trim(s_WSchars);
if (relativeStr.Length == 0)
{
newUriString = baseUri.GetParts(UriComponents.AbsoluteUri,
baseUri.UserEscaped ? UriFormat.UriEscaped : UriFormat.SafeUnescaped);
return null;
}
// Check for a simple fragment in relative part
if (relativeStr[0] == '#' && !baseUri.IsImplicitFile && baseUri.Syntax.InFact(UriSyntaxFlags.MayHaveFragment))
{
newUriString = baseUri.GetParts(UriComponents.AbsoluteUri & ~UriComponents.Fragment,
UriFormat.UriEscaped) + relativeStr;
return null;
}
// Check for a simple query in relative part
if (relativeStr[0] == '?' && !baseUri.IsImplicitFile && baseUri.Syntax.InFact(UriSyntaxFlags.MayHaveQuery))
{
newUriString = baseUri.GetParts(UriComponents.AbsoluteUri & ~UriComponents.Query & ~UriComponents.Fragment,
UriFormat.UriEscaped) + relativeStr;
return null;
}
// Check on the DOS path in the relative Uri (a special case)
if (relativeStr.Length >= 3
&& (relativeStr[1] == ':' || relativeStr[1] == '|')
&& IsAsciiLetter(relativeStr[0])
&& (relativeStr[2] == '\\' || relativeStr[2] == '/'))
{
if (baseUri.IsImplicitFile)
{
// It could have file:/// prepended to the result but we want to keep it as *Implicit* File Uri
newUriString = relativeStr;
return null;
}
else if (baseUri.Syntax.InFact(UriSyntaxFlags.AllowDOSPath))
{
// The scheme is not changed just the path gets replaced
string prefix;
if (baseUri.InFact(Flags.AuthorityFound))
prefix = baseUri.Syntax.InFact(UriSyntaxFlags.PathIsRooted) ? ":///" : "://";
else
prefix = baseUri.Syntax.InFact(UriSyntaxFlags.PathIsRooted) ? ":/" : ":";
newUriString = baseUri.Scheme + prefix + relativeStr;
return null;
}
// If we are here then input like "http://host/path/" + "C:\x" will produce the result http://host/path/c:/x
}
ParsingError err = GetCombinedString(baseUri, relativeStr, userEscaped, ref newUriString);
if (err != ParsingError.None)
{
e = GetException(err);
return null;
}
if ((object)newUriString == (object)baseUri._string)
return baseUri;
return null;
}
private unsafe string GetRelativeSerializationString(UriFormat format)
{
if (format == UriFormat.UriEscaped)
{
if (_string.Length == 0)
return string.Empty;
int position = 0;
char[] dest = UriHelper.EscapeString(_string, 0, _string.Length, null, ref position, true,
c_DummyChar, c_DummyChar, '%');
if ((object)dest == null)
return _string;
return new string(dest, 0, position);
}
else if (format == UriFormat.Unescaped)
return UnescapeDataString(_string);
else if (format == UriFormat.SafeUnescaped)
{
if (_string.Length == 0)
return string.Empty;
char[] dest = new char[_string.Length];
int position = 0;
dest = UriHelper.UnescapeString(_string, 0, _string.Length, dest, ref position, c_DummyChar,
c_DummyChar, c_DummyChar, UnescapeMode.EscapeUnescape, null, false);
return new string(dest, 0, position);
}
else
throw new ArgumentOutOfRangeException(nameof(format));
}
//
// UriParser helpers methods
//
internal string GetComponentsHelper(UriComponents uriComponents, UriFormat uriFormat)
{
if (uriComponents == UriComponents.Scheme)
return _syntax.SchemeName;
// A serialzation info is "almost" the same as AbsoluteUri except for IPv6 + ScopeID hostname case
if ((uriComponents & UriComponents.SerializationInfoString) != 0)
uriComponents |= UriComponents.AbsoluteUri;
//This will get all the offsets, HostString will be created below if needed
EnsureParseRemaining();
if ((uriComponents & UriComponents.NormalizedHost) != 0)
{
// Down the path we rely on Host to be ON for NormalizedHost
uriComponents |= UriComponents.Host;
}
//Check to see if we need the host/authotity string
if ((uriComponents & UriComponents.Host) != 0)
EnsureHostString(true);
//This, single Port request is always processed here
if (uriComponents == UriComponents.Port || uriComponents == UriComponents.StrongPort)
{
if (((_flags & Flags.NotDefaultPort) != 0) || (uriComponents == UriComponents.StrongPort
&& _syntax.DefaultPort != UriParser.NoDefaultPort))
{
// recreate string from the port value
return _info.Offset.PortValue.ToString(CultureInfo.InvariantCulture);
}
return string.Empty;
}
if ((uriComponents & UriComponents.StrongPort) != 0)
{
// Down the path we rely on Port to be ON for StrongPort
uriComponents |= UriComponents.Port;
}
//This request sometime is faster to process here
if (uriComponents == UriComponents.Host && (uriFormat == UriFormat.UriEscaped
|| ((_flags & (Flags.HostNotCanonical | Flags.E_HostNotCanonical)) == 0)))
{
EnsureHostString(false);
return _info.Host;
}
switch (uriFormat)
{
case UriFormat.UriEscaped:
return GetEscapedParts(uriComponents);
case V1ToStringUnescape:
case UriFormat.SafeUnescaped:
case UriFormat.Unescaped:
return GetUnescapedParts(uriComponents, uriFormat);
default:
throw new ArgumentOutOfRangeException(nameof(uriFormat));
}
}
public bool IsBaseOf(Uri uri)
{
if ((object)uri == null)
throw new ArgumentNullException(nameof(uri));
if (!IsAbsoluteUri)
return false;
if (Syntax.IsSimple)
return IsBaseOfHelper(uri);
return Syntax.InternalIsBaseOf(this, uri);
}
internal bool IsBaseOfHelper(Uri uriLink)
{
if (!IsAbsoluteUri || UserDrivenParsing)
return false;
if (!uriLink.IsAbsoluteUri)
{
//a relative uri could have quite tricky form, it's better to fix it now.
string newUriString = null;
UriFormatException e;
bool dontEscape = false;
uriLink = ResolveHelper(this, uriLink, ref newUriString, ref dontEscape, out e);
if (e != null)
return false;
if ((object)uriLink == null)
uriLink = CreateHelper(newUriString, dontEscape, UriKind.Absolute, ref e);
if (e != null)
return false;
}
if (Syntax.SchemeName != uriLink.Syntax.SchemeName)
return false;
// Canonicalize and test for substring match up to the last path slash
string self = GetParts(UriComponents.AbsoluteUri & ~UriComponents.Fragment, UriFormat.SafeUnescaped);
string other = uriLink.GetParts(UriComponents.AbsoluteUri & ~UriComponents.Fragment, UriFormat.SafeUnescaped);
unsafe
{
fixed (char* selfPtr = self)
{
fixed (char* otherPtr = other)
{
return UriHelper.TestForSubPath(selfPtr, (ushort)self.Length, otherPtr, (ushort)other.Length,
IsUncOrDosPath || uriLink.IsUncOrDosPath);
}
}
}
}
//
// Only a ctor time call
//
private void CreateThisFromUri(Uri otherUri)
{
// Clone the other guy but develop own UriInfo member
_info = null;
_flags = otherUri._flags;
if (InFact(Flags.MinimalUriInfoSet))
{
_flags &= ~(Flags.MinimalUriInfoSet | Flags.AllUriInfoSet | Flags.IndexMask);
// Port / Path offset
int portIndex = otherUri._info.Offset.Path;
if (InFact(Flags.NotDefaultPort))
{
// Find the start of the port. Account for non-canonical ports like :00123
while (otherUri._string[portIndex] != ':' && portIndex > otherUri._info.Offset.Host)
{
portIndex--;
}
if (otherUri._string[portIndex] != ':')
{
// Something wrong with the NotDefaultPort flag. Reset to path index
Debug.Assert(false, "Uri failed to locate custom port at index: " + portIndex);
portIndex = otherUri._info.Offset.Path;
}
}
_flags |= (Flags)portIndex; // Port or path
}
_syntax = otherUri._syntax;
_string = otherUri._string;
_iriParsing = otherUri._iriParsing;
if (otherUri.OriginalStringSwitched)
{
_originalUnicodeString = otherUri._originalUnicodeString;
}
if (otherUri.AllowIdn && (otherUri.InFact(Flags.IdnHost) || otherUri.InFact(Flags.UnicodeHost)))
{
_dnsSafeHost = otherUri._dnsSafeHost;
}
}
}
}
| |
/// This code was generated by
/// \ / _ _ _| _ _
/// | (_)\/(_)(_|\/| |(/_ v1.0.0
/// / /
using System;
using System.Collections.Generic;
using Twilio.Base;
using Twilio.Converters;
namespace Twilio.Rest.Media.V1
{
/// <summary>
/// CreateMediaProcessorOptions
/// </summary>
public class CreateMediaProcessorOptions : IOptions<MediaProcessorResource>
{
/// <summary>
/// The Media Extension name or URL
/// </summary>
public string Extension { get; }
/// <summary>
/// The Media Extension context
/// </summary>
public string ExtensionContext { get; }
/// <summary>
/// The Media Extension environment
/// </summary>
public object ExtensionEnvironment { get; set; }
/// <summary>
/// The URL to send MediaProcessor event updates to your application
/// </summary>
public Uri StatusCallback { get; set; }
/// <summary>
/// The HTTP method Twilio should use to call the `status_callback` URL
/// </summary>
public Twilio.Http.HttpMethod StatusCallbackMethod { get; set; }
/// <summary>
/// Maximum MediaProcessor duration in minutes
/// </summary>
public int? MaxDuration { get; set; }
/// <summary>
/// Construct a new CreateMediaProcessorOptions
/// </summary>
/// <param name="extension"> The Media Extension name or URL </param>
/// <param name="extensionContext"> The Media Extension context </param>
public CreateMediaProcessorOptions(string extension, string extensionContext)
{
Extension = extension;
ExtensionContext = extensionContext;
}
/// <summary>
/// Generate the necessary parameters
/// </summary>
public List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
if (Extension != null)
{
p.Add(new KeyValuePair<string, string>("Extension", Extension));
}
if (ExtensionContext != null)
{
p.Add(new KeyValuePair<string, string>("ExtensionContext", ExtensionContext));
}
if (ExtensionEnvironment != null)
{
p.Add(new KeyValuePair<string, string>("ExtensionEnvironment", Serializers.JsonObject(ExtensionEnvironment)));
}
if (StatusCallback != null)
{
p.Add(new KeyValuePair<string, string>("StatusCallback", Serializers.Url(StatusCallback)));
}
if (StatusCallbackMethod != null)
{
p.Add(new KeyValuePair<string, string>("StatusCallbackMethod", StatusCallbackMethod.ToString()));
}
if (MaxDuration != null)
{
p.Add(new KeyValuePair<string, string>("MaxDuration", MaxDuration.ToString()));
}
return p;
}
}
/// <summary>
/// Returns a single MediaProcessor resource identified by a SID.
/// </summary>
public class FetchMediaProcessorOptions : IOptions<MediaProcessorResource>
{
/// <summary>
/// The SID that identifies the resource to fetch
/// </summary>
public string PathSid { get; }
/// <summary>
/// Construct a new FetchMediaProcessorOptions
/// </summary>
/// <param name="pathSid"> The SID that identifies the resource to fetch </param>
public FetchMediaProcessorOptions(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>
/// Updates a MediaProcessor resource identified by a SID.
/// </summary>
public class UpdateMediaProcessorOptions : IOptions<MediaProcessorResource>
{
/// <summary>
/// The SID that identifies the resource to update
/// </summary>
public string PathSid { get; }
/// <summary>
/// The status of the MediaProcessor
/// </summary>
public MediaProcessorResource.UpdateStatusEnum Status { get; }
/// <summary>
/// Construct a new UpdateMediaProcessorOptions
/// </summary>
/// <param name="pathSid"> The SID that identifies the resource to update </param>
/// <param name="status"> The status of the MediaProcessor </param>
public UpdateMediaProcessorOptions(string pathSid, MediaProcessorResource.UpdateStatusEnum status)
{
PathSid = pathSid;
Status = status;
}
/// <summary>
/// Generate the necessary parameters
/// </summary>
public List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
if (Status != null)
{
p.Add(new KeyValuePair<string, string>("Status", Status.ToString()));
}
return p;
}
}
/// <summary>
/// Returns a list of MediaProcessors.
/// </summary>
public class ReadMediaProcessorOptions : ReadOptions<MediaProcessorResource>
{
/// <summary>
/// The sort order of the list
/// </summary>
public MediaProcessorResource.OrderEnum Order { get; set; }
/// <summary>
/// Status to filter by
/// </summary>
public MediaProcessorResource.StatusEnum Status { get; set; }
/// <summary>
/// Generate the necessary parameters
/// </summary>
public override List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
if (Order != null)
{
p.Add(new KeyValuePair<string, string>("Order", Order.ToString()));
}
if (Status != null)
{
p.Add(new KeyValuePair<string, string>("Status", Status.ToString()));
}
if (PageSize != null)
{
p.Add(new KeyValuePair<string, string>("PageSize", PageSize.ToString()));
}
return p;
}
}
}
| |
using Lucene.Net.Documents;
using Lucene.Net.Support;
using System;
using System.Collections.Generic;
namespace Lucene.Net.Index
{
using NUnit.Framework;
using Codec = Lucene.Net.Codecs.Codec;
using Directory = Lucene.Net.Store.Directory;
using Document = Documents.Document;
using Field = Field;
using IndexInput = Lucene.Net.Store.IndexInput;
using IndexOutput = Lucene.Net.Store.IndexOutput;
using LuceneTestCase = Lucene.Net.Util.LuceneTestCase;
/*
* 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 MockAnalyzer = Lucene.Net.Analysis.MockAnalyzer;
using MockDirectoryWrapper = Lucene.Net.Store.MockDirectoryWrapper;
/*
Verify we can read the pre-2.1 file format, do searches
against it, and add documents to it.
*/
[TestFixture]
public class TestIndexFileDeleter : LuceneTestCase
{
[Test]
public virtual void TestDeleteLeftoverFiles()
{
Directory dir = NewDirectory();
if (dir is MockDirectoryWrapper)
{
((MockDirectoryWrapper)dir).PreventDoubleWrite = false;
}
MergePolicy mergePolicy = NewLogMergePolicy(true, 10);
// this test expects all of its segments to be in CFS
mergePolicy.NoCFSRatio = 1.0;
mergePolicy.MaxCFSSegmentSizeMB = double.PositiveInfinity;
IndexWriter writer = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetMaxBufferedDocs(10).SetMergePolicy(mergePolicy).SetUseCompoundFile(true));
int i;
for (i = 0; i < 35; i++)
{
AddDoc(writer, i);
}
writer.Config.MergePolicy.NoCFSRatio = 0.0;
writer.Config.SetUseCompoundFile(false);
for (; i < 45; i++)
{
AddDoc(writer, i);
}
writer.Dispose();
// Delete one doc so we get a .del file:
writer = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetMergePolicy(NoMergePolicy.NO_COMPOUND_FILES).SetUseCompoundFile(true));
Term searchTerm = new Term("id", "7");
writer.DeleteDocuments(searchTerm);
writer.Dispose();
// Now, artificially create an extra .del file & extra
// .s0 file:
string[] files = dir.ListAll();
/*
for(int j=0;j<files.Length;j++) {
System.out.println(j + ": " + files[j]);
}
*/
// TODO: fix this test better
string ext = Codec.Default.Name.Equals("SimpleText") ? ".liv" : ".del";
// Create a bogus separate del file for a
// segment that already has a separate del file:
CopyFile(dir, "_0_1" + ext, "_0_2" + ext);
// Create a bogus separate del file for a
// segment that does not yet have a separate del file:
CopyFile(dir, "_0_1" + ext, "_1_1" + ext);
// Create a bogus separate del file for a
// non-existent segment:
CopyFile(dir, "_0_1" + ext, "_188_1" + ext);
// Create a bogus segment file:
CopyFile(dir, "_0.cfs", "_188.cfs");
// Create a bogus fnm file when the CFS already exists:
CopyFile(dir, "_0.cfs", "_0.fnm");
// Create some old segments file:
CopyFile(dir, "segments_2", "segments");
CopyFile(dir, "segments_2", "segments_1");
// Create a bogus cfs file shadowing a non-cfs segment:
// TODO: assert is bogus (relies upon codec-specific filenames)
Assert.IsTrue(SlowFileExists(dir, "_3.fdt") || SlowFileExists(dir, "_3.fld"));
Assert.IsTrue(!SlowFileExists(dir, "_3.cfs"));
CopyFile(dir, "_1.cfs", "_3.cfs");
string[] filesPre = dir.ListAll();
// Open & close a writer: it should delete the above 4
// files and nothing more:
writer = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetOpenMode(OpenMode.APPEND));
writer.Dispose();
string[] files2 = dir.ListAll();
dir.Dispose();
Array.Sort(files);
Array.Sort(files2);
HashSet<string> dif = DifFiles(files, files2);
if (!Arrays.Equals(files, files2))
{
Assert.Fail("IndexFileDeleter failed to delete unreferenced extra files: should have deleted " + (filesPre.Length - files.Length) + " files but only deleted " + (filesPre.Length - files2.Length) + "; expected files:\n " + AsString(files) + "\n actual files:\n " + AsString(files2) + "\ndiff: " + dif);
}
}
private static HashSet<string> DifFiles(string[] files1, string[] files2)
{
HashSet<string> set1 = new HashSet<string>();
HashSet<string> set2 = new HashSet<string>();
HashSet<string> extra = new HashSet<string>();
for (int x = 0; x < files1.Length; x++)
{
set1.Add(files1[x]);
}
for (int x = 0; x < files2.Length; x++)
{
set2.Add(files2[x]);
}
IEnumerator<string> i1 = set1.GetEnumerator();
while (i1.MoveNext())
{
string o = i1.Current;
if (!set2.Contains(o))
{
extra.Add(o);
}
}
IEnumerator<string> i2 = set2.GetEnumerator();
while (i2.MoveNext())
{
string o = i2.Current;
if (!set1.Contains(o))
{
extra.Add(o);
}
}
return extra;
}
private string AsString(string[] l)
{
string s = "";
for (int i = 0; i < l.Length; i++)
{
if (i > 0)
{
s += "\n ";
}
s += l[i];
}
return s;
}
public virtual void CopyFile(Directory dir, string src, string dest)
{
IndexInput @in = dir.OpenInput(src, NewIOContext(Random()));
IndexOutput @out = dir.CreateOutput(dest, NewIOContext(Random()));
var b = new byte[1024];
long remainder = @in.Length;
while (remainder > 0)
{
int len = (int)Math.Min(b.Length, remainder);
@in.ReadBytes(b, 0, len);
@out.WriteBytes(b, len);
remainder -= len;
}
@in.Dispose();
@out.Dispose();
}
private void AddDoc(IndexWriter writer, int id)
{
Document doc = new Document();
doc.Add(NewTextField("content", "aaa", Field.Store.NO));
doc.Add(NewStringField("id", Convert.ToString(id), Field.Store.NO));
writer.AddDocument(doc);
}
}
}
| |
using DevExpress.Mvvm;
using DevExpress.Mvvm.UI;
using DevExpress.Mvvm.Native;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Reflection;
using System.Windows.Data;
using System.ComponentModel;
using System.Windows.Controls;
using System.Collections.ObjectModel;
using DevExpress.Mvvm.UI.Interactivity;
using DevExpress.Mvvm.UI.Native;
#if SILVERLIGHT
using WindowBase = DevExpress.Xpf.Core.DXWindowBase;
#else
using WindowBase = System.Windows.Window;
#endif
namespace DevExpress.Mvvm.UI {
[TargetTypeAttribute(typeof(UserControl))]
[TargetTypeAttribute(typeof(Window))]
public class WindowedDocumentUIService : DocumentUIServiceBase, IDocumentManagerService, IDocumentOwner {
public class WindowDocument : IDocument, IDocumentInfo {
public readonly object documentContentView;
bool destroyOnClose = true;
readonly WindowedDocumentUIService owner;
DocumentState state = DocumentState.Hidden;
string documentType;
public WindowDocument(WindowedDocumentUIService owner, IWindowSurrogate window, object documentContentView, string documentType) {
this.owner = owner;
Window = window;
this.documentContentView = documentContentView;
this.documentType = documentType;
Window.Closing += window_Closing;
Window.Closed += window_Closed;
}
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
public IWindowSurrogate Window { get; private set; }
void window_Closed(object sender, EventArgs e) {
RemoveFromWindowsList();
Window.Closing -= window_Closing;
Window.Closed -= window_Closed;
DocumentViewModelHelper.OnDestroy(GetContent());
}
bool onClosing = false;
void window_Closing(object sender, CancelEventArgs e) {
onClosing = true;
DocumentViewModelHelper.OnClose(GetContent(), e);
if(!destroyOnClose && !e.Cancel) {
e.Cancel = true;
Window.Hide();
}
onClosing = false;
}
void IDocument.Close(bool force) {
if(!force) {
if(!onClosing) {
Window.Close();
}
return;
}
Window.Closing -= window_Closing;
if(!destroyOnClose) {
if(!onClosing) {
Window.Hide();
}
state = DocumentState.Hidden;
} else {
if(!onClosing) {
Window.Close();
}
state = DocumentState.Destroyed;
}
}
public bool DestroyOnClose {
get { return destroyOnClose; }
set { destroyOnClose = value; }
}
void IDocument.Show() {
switch(owner.DocumentShowMode) {
case WindowShowMode.Dialog:
Window.ShowDialog();
break;
default:
Window.Show();
break;
}
state = DocumentState.Visible;
}
void IDocument.Hide() {
Window.Hide();
state = DocumentState.Hidden;
}
public object Id {
get;
set;
}
public object Title {
get { return Window.RealWindow.Title; }
set { Window.RealWindow.Title = Convert.ToString(value); }
}
public object Content {
get { return GetContent(); }
}
DocumentState IDocumentInfo.State { get { return state; } }
void RemoveFromWindowsList() {
owner.windows.Remove(Window);
}
object GetContent() {
return ViewHelper.GetViewModelFromView(documentContentView);
}
string IDocumentInfo.DocumentType {
get { return documentType; }
}
}
public static readonly DependencyProperty WindowStartupLocationProperty =
DependencyProperty.Register("WindowStartupLocation", typeof(WindowStartupLocation), typeof(WindowedDocumentUIService), new PropertyMetadata(WindowStartupLocation.CenterScreen));
public static readonly DependencyProperty WindowStyleProperty =
DependencyProperty.Register("WindowStyle", typeof(Style), typeof(WindowedDocumentUIService), new PropertyMetadata(null));
#if !SILVERLIGHT
public static readonly DependencyProperty WindowStyleSelectorProperty =
DependencyProperty.Register("WindowStyleSelector", typeof(StyleSelector), typeof(WindowedDocumentUIService), new PropertyMetadata(null));
public static readonly DependencyProperty SetWindowOwnerProperty =
DependencyProperty.Register("SetWindowOwner", typeof(bool), typeof(WindowedDocumentUIService), new PropertyMetadata(true));
#endif
public static readonly DependencyProperty WindowTypeProperty =
DependencyProperty.Register("WindowType", typeof(Type), typeof(WindowedDocumentUIService), new PropertyMetadata(typeof(Window)));
public static readonly DependencyProperty DocumentShowModeProperty =
DependencyProperty.Register("DocumentShowMode", typeof(WindowShowMode), typeof(WindowedDocumentUIService),
new PropertyMetadata(WindowShowMode.Default));
public static readonly DependencyProperty ActiveDocumentProperty =
DependencyProperty.Register("ActiveDocument", typeof(IDocument), typeof(WindowedDocumentUIService),
new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, (d, e) => ((WindowedDocumentUIService)d).OnActiveDocumentChanged(e.OldValue as IDocument, e.NewValue as IDocument)));
static readonly DependencyPropertyKey ActiveViewPropertyKey =
DependencyProperty.RegisterReadOnly("ActiveView", typeof(object), typeof(WindowedDocumentUIService), new PropertyMetadata(null));
public static readonly DependencyProperty ActiveViewProperty = ActiveViewPropertyKey.DependencyProperty;
public WindowStartupLocation WindowStartupLocation {
get { return (WindowStartupLocation)GetValue(WindowStartupLocationProperty); }
set { SetValue(WindowStartupLocationProperty, value); }
}
public Style WindowStyle {
get { return (Style)GetValue(WindowStyleProperty); }
set { SetValue(WindowStyleProperty, value); }
}
public IDocument ActiveDocument {
get { return (IDocument)GetValue(ActiveDocumentProperty); }
set { SetValue(ActiveDocumentProperty, value); }
}
public object ActiveView {
get { return GetValue(ActiveViewProperty); }
private set { SetValue(ActiveViewPropertyKey, value); }
}
#if !SILVERLIGHT
public StyleSelector WindowStyleSelector {
get { return (StyleSelector)GetValue(WindowStyleSelectorProperty); }
set { SetValue(WindowStyleSelectorProperty, value); }
}
public bool SetWindowOwner {
get { return (bool)GetValue(SetWindowOwnerProperty); }
set { SetValue(SetWindowOwnerProperty, value); }
}
#endif
public Type WindowType {
get { return (Type)GetValue(WindowTypeProperty); }
set { SetValue(WindowTypeProperty, value); }
}
public WindowShowMode DocumentShowMode {
get { return (WindowShowMode)GetValue(DocumentShowModeProperty); }
set { SetValue(DocumentShowModeProperty, value); }
}
protected virtual IWindowSurrogate CreateWindow(object view) {
IWindowSurrogate window = WindowProxy.GetWindowSurrogate(Activator.CreateInstance(WindowType));
UpdateThemeName(window.RealWindow);
window.RealWindow.Content = view;
#if SILVERLIGHT
window.RealWindow.Style = WindowStyle;
#else
if(SetWindowOwner) window.RealWindow.Owner = Window.GetWindow(AssociatedObject);
window.RealWindow.Style = GetDocumentContainerStyle(window.RealWindow, view, WindowStyle, WindowStyleSelector);
window.RealWindow.WindowStartupLocation = this.WindowStartupLocation;
#endif
return window;
}
IDocument IDocumentManagerService.CreateDocument(string documentType, object viewModel, object parameter, object parentViewModel) {
object view = CreateAndInitializeView(documentType, viewModel, parameter, parentViewModel, this);
IWindowSurrogate window = CreateWindow(view);
windows.Add(window);
SubscribeWindow(window);
IDocument document = new WindowDocument(this, window, view, documentType);
SetDocument(window.RealWindow, document);
SetTitleBinding(view, WindowBase.TitleProperty, window.RealWindow, true);
return document;
}
void IDocumentOwner.Close(IDocumentContent documentContent, bool force) {
CloseDocument(this, documentContent, force);
}
IList<IWindowSurrogate> windows = new List<IWindowSurrogate>();
public IEnumerable<IDocument> Documents { get { return windows.Select(w => GetDocument(w.RealWindow)); } }
public event ActiveDocumentChangedEventHandler ActiveDocumentChanged;
void SubscribeWindow(IWindowSurrogate window) {
window.Activated += OnWindowActivated;
#if !SILVERLIGHT
window.Deactivated += OnWindowDeactivated;
#endif
window.Closed += OnWindowClosed;
}
void UnsubscribeWindow(IWindowSurrogate window) {
window.Activated -= OnWindowActivated;
#if !SILVERLIGHT
window.Deactivated -= OnWindowDeactivated;
#endif
window.Closed -= OnWindowClosed;
}
void OnWindowClosed(object sender, EventArgs e) {
if(windows.Count == 1)
ActiveDocument = null;
UnsubscribeWindow(WindowProxy.GetWindowSurrogate(sender));
}
void OnWindowActivated(object sender, EventArgs e) {
ActiveDocument = GetDocument((WindowBase)sender);
}
#if !SILVERLIGHT
void OnWindowDeactivated(object sender, EventArgs e) {
if(ActiveDocument == GetDocument((Window)sender))
ActiveDocument = null;
}
#endif
void OnActiveDocumentChanged(IDocument oldValue, IDocument newValue) {
WindowDocument newDocument = (WindowDocument)newValue;
if(newDocument != null)
newDocument.Window.Activate();
ActiveView = newDocument.With(x => x.documentContentView);
if(ActiveDocumentChanged != null)
ActiveDocumentChanged(this, new ActiveDocumentChangedEventArgs(oldValue, newValue));
}
}
}
| |
/*
* Copyright (c) 2007, Second Life Reverse Engineering Team
* 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.
* - Neither the name of the Second Life Reverse Engineering Team nor the names
* of its contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using libsecondlife.Packets;
namespace libsecondlife
{
public class TerrainManager
{
public enum LayerType : byte
{
Land = 0x4C,
Water = 0x57,
Wind = 0x37,
Cloud = 0x38
}
public struct GroupHeader
{
public int Stride;
public int PatchSize;
public LayerType Type;
}
public struct PatchHeader
{
public float DCOffset;
public int Range;
public int QuantWBits;
public int PatchIDs;
public uint WordBits;
}
public class Patch
{
public float[] Heightmap;
}
/// <summary>
///
/// </summary>
/// <param name="simulator"></param>
/// <param name="x"></param>
/// <param name="y"></param>
/// <param name="width"></param>
/// <param name="data"></param>
public delegate void LandPatchCallback(Simulator simulator, int x, int y, int width, float[] data);
/// <summary>
///
/// </summary>
public event LandPatchCallback OnLandPatch;
public InternalDictionary<ulong, Patch[]> SimPatches = new InternalDictionary<ulong, Patch[]>();
private const int PATCHES_PER_EDGE = 16;
private const float OO_SQRT2 = 0.7071067811865475244008443621049f;
private const int STRIDE = 264;
// Bit packing codes
private const int ZERO_CODE = 0x0;
private const int ZERO_EOB = 0x2;
private const int POSITIVE_VALUE = 0x6;
private const int NEGATIVE_VALUE = 0x7;
private const int END_OF_PATCHES = 97;
private SecondLife Client;
private float[] DequantizeTable16 = new float[16 * 16];
private float[] DequantizeTable32 = new float[32 * 32];
private float[] CosineTable16 = new float[16 * 16];
private float[] CosineTable32 = new float[32 * 32];
private int[] CopyMatrix16 = new int[16 * 16];
private int[] CopyMatrix32 = new int[32 * 32];
// Not used by clients
private float[] QuantizeTable16 = new float[16 * 16];
/// <summary>
///
/// </summary>
/// <param name="client"></param>
public TerrainManager(SecondLife client)
{
Client = client;
// Initialize the decompression tables
BuildDequantizeTable16();
BuildDequantizeTable32();
SetupCosines16();
SetupCosines32();
BuildCopyMatrix16();
BuildCopyMatrix32();
// Not used by clients
BuildQuantizeTable16();
Client.Network.RegisterCallback(PacketType.LayerData, new NetworkManager.PacketCallback(LayerDataHandler));
}
/// <summary>
/// Retrieve the terrain height at a given coordinate
/// </summary>
/// <param name="regionHandle">The region that the point of interest is in</param>
/// <param name="x">Sim X coordinate, valid range is from 0 to 255</param>
/// <param name="y">Sim Y coordinate, valid range is from 0 to 255</param>
/// <param name="height">The terrain height at the given point if the
/// lookup was successful, otherwise 0.0f</param>
/// <returns>True if the lookup was successful, otherwise false</returns>
public bool TerrainHeightAtPoint(ulong regionHandle, int x, int y, out float height)
{
if (x >= 0 && x < 256 && y >= 0 && y < 256)
{
lock (SimPatches)
{
if (SimPatches.ContainsKey(regionHandle))
{
int patchX = x / 16;
int patchY = y / 16;
x = x % 16;
y = y % 16;
if (SimPatches[regionHandle][patchY * 16 + patchX] != null)
{
height = SimPatches[regionHandle][patchY * 16 + patchX].Heightmap[y * 16 + x];
return true;
}
}
}
}
height = 0.0f;
return false;
}
/// <summary>
/// Creates a LayerData packet for compressed land data given a full
/// simulator heightmap and an array of indices of patches to compress
/// </summary>
/// <param name="heightmap">A 256 * 256 array of floating point values
/// specifying the height at each meter in the simulator</param>
/// <param name="patches">Array of indexes in the 16x16 grid of patches
/// for this simulator. For example if 1 and 17 are specified, patches
/// x=1,y=0 and x=1,y=1 are sent</param>
/// <returns></returns>
public LayerDataPacket CreateLandPacket(float[] heightmap, int[] patches)
{
LayerDataPacket layer = new LayerDataPacket();
layer.LayerID.Type = (byte)LayerType.Land;
GroupHeader header = new GroupHeader();
header.Stride = STRIDE;
header.PatchSize = 16;
header.Type = LayerType.Land;
byte[] data = new byte[1536];
BitPack bitpack = new BitPack(data, 0);
bitpack.PackBits(header.Stride, 16);
bitpack.PackBits(header.PatchSize, 8);
bitpack.PackBits((int)header.Type, 8);
for (int i = 0; i < patches.Length; i++)
{
CreatePatch(bitpack, heightmap, patches[i] % 16, (patches[i] - (patches[i] % 16)) / 16);
}
bitpack.PackBits(END_OF_PATCHES, 8);
layer.LayerData.Data = new byte[bitpack.BytePos + 1];
Buffer.BlockCopy(bitpack.Data, 0, layer.LayerData.Data, 0, bitpack.BytePos + 1);
return layer;
}
/// <summary>
/// Add a patch of terrain to a BitPacker
/// </summary>
/// <param name="output">BitPacker to write the patch to</param>
/// <param name="heightmap">Heightmap of the simulator, must be a 256 *
/// 256 float array</param>
/// <param name="x">X offset of the patch to create, valid values are
/// from 0 to 15</param>
/// <param name="y">Y offset of the patch to create, valid values are
/// from 0 to 15</param>
public void CreatePatch(BitPack output, float[] heightmap, int x, int y)
{
if (heightmap.Length != 256 * 256)
{
Logger.Log("Invalid heightmap value of " + heightmap.Length + " passed to CreatePatch()",
Helpers.LogLevel.Error, Client);
return;
}
if (x < 0 || x > 15 || y < 0 || y > 15)
{
Logger.Log("Invalid x or y patch offset passed to CreatePatch(), x=" + x + ", y=" + y,
Helpers.LogLevel.Error, Client);
return;
}
PatchHeader header = PrescanPatch(heightmap, x, y);
header.QuantWBits = 136;
header.PatchIDs = (y & 0x1F);
header.PatchIDs += (x << 5);
// TODO: What is prequant?
int[] patch = CompressPatch(heightmap, x, y, header, 10);
int wbits = EncodePatchHeader(output, header, patch);
// TODO: What is postquant?
EncodePatch(output, patch, 0, wbits);
}
private void BuildDequantizeTable16()
{
for (int j = 0; j < 16; j++)
{
for (int i = 0; i < 16; i++)
{
DequantizeTable16[j * 16 + i] = 1.0f + 2.0f * (float)(i + j);
}
}
}
private void BuildDequantizeTable32()
{
for (int j = 0; j < 32; j++)
{
for (int i = 0; i < 32; i++)
{
DequantizeTable32[j * 32 + i] = 1.0f + 2.0f * (float)(i + j);
}
}
}
private void BuildQuantizeTable16()
{
for (int j = 0; j < 16; j++)
{
for (int i = 0; i < 16; i++)
{
QuantizeTable16[j * 16 + i] = 1.0f / (1.0f + 2.0f * ((float)i + (float)j));
}
}
}
private void SetupCosines16()
{
const float hposz = (float)Math.PI * 0.5f / 16.0f;
for (int u = 0; u < 16; u++)
{
for (int n = 0; n < 16; n++)
{
CosineTable16[u * 16 + n] = (float)Math.Cos((2.0f * (float)n + 1.0f) * (float)u * hposz);
}
}
}
private void SetupCosines32()
{
const float hposz = (float)Math.PI * 0.5f / 32.0f;
for (int u = 0; u < 32; u++)
{
for (int n = 0; n < 32; n++)
{
CosineTable32[u * 32 + n] = (float)Math.Cos((2.0f * (float)n + 1.0f) * (float)u * hposz);
}
}
}
private void BuildCopyMatrix16()
{
bool diag = false;
bool right = true;
int i = 0;
int j = 0;
int count = 0;
while (i < 16 && j < 16)
{
CopyMatrix16[j * 16 + i] = count++;
if (!diag)
{
if (right)
{
if (i < 16 - 1) i++;
else j++;
right = false;
diag = true;
}
else
{
if (j < 16 - 1) j++;
else i++;
right = true;
diag = true;
}
}
else
{
if (right)
{
i++;
j--;
if (i == 16 - 1 || j == 0) diag = false;
}
else
{
i--;
j++;
if (j == 16 - 1 || i == 0) diag = false;
}
}
}
}
private void BuildCopyMatrix32()
{
bool diag = false;
bool right = true;
int i = 0;
int j = 0;
int count = 0;
while (i < 32 && j < 32)
{
CopyMatrix32[j * 32 + i] = count++;
if (!diag)
{
if (right)
{
if (i < 32 - 1) i++;
else j++;
right = false;
diag = true;
}
else
{
if (j < 32 - 1) j++;
else i++;
right = true;
diag = true;
}
}
else
{
if (right)
{
i++;
j--;
if (i == 32 - 1 || j == 0) diag = false;
}
else
{
i--;
j++;
if (j == 32 - 1 || i == 0) diag = false;
}
}
}
}
private PatchHeader PrescanPatch(float[] heightmap, int patchX, int patchY)
{
PatchHeader header = new PatchHeader();
float zmax = -99999999.0f;
float zmin = 99999999.0f;
for (int j = patchY * 16; j < (patchY + 1) * 16; j++)
{
for (int i = patchX * 16; i < (patchX + 1) * 16; i++)
{
if (heightmap[j * 256 + i] > zmax) zmax = heightmap[j * 256 + i];
if (heightmap[j * 256 + i] < zmin) zmin = heightmap[j * 256 + i];
}
}
header.DCOffset = zmin;
header.Range = (int)((zmax - zmin) + 1.0f);
return header;
}
private PatchHeader DecodePatchHeader(BitPack bitpack)
{
PatchHeader header = new PatchHeader();
// Quantized word bits
header.QuantWBits = bitpack.UnpackBits(8);
if (header.QuantWBits == END_OF_PATCHES)
return header;
// DC offset
header.DCOffset = bitpack.UnpackFloat();
// Range
header.Range = bitpack.UnpackBits(16);
// Patch IDs (10 bits)
header.PatchIDs = bitpack.UnpackBits(10);
// Word bits
header.WordBits = (uint)((header.QuantWBits & 0x0f) + 2);
return header;
}
/// <summary>
///
/// </summary>
/// <param name="output"></param>
/// <param name="header"></param>
/// <param name="patch"></param>
/// <returns>wbits</returns>
private int EncodePatchHeader(BitPack output, PatchHeader header, int[] patch)
{
int temp;
int wbits = (header.QuantWBits & 0x0f) + 2;
uint maxWbits = (uint)wbits + 5;
uint minWbits = ((uint)wbits >> 1);
wbits = (int)minWbits;
for (int i = 0; i < patch.Length; i++)
{
temp = patch[i];
if (temp != 0)
{
// Get the absolute value
if (temp < 0) temp *= -1;
for (int j = (int)maxWbits; j > (int)minWbits; j--)
{
if ((temp & (1 << j)) != 0)
{
if (j > wbits) wbits = j;
break;
}
}
}
}
wbits += 1;
header.QuantWBits &= 0xf0;
if (wbits > 17 || wbits < 2)
{
Logger.Log("Bits needed per word in EncodePatchHeader() are outside the allowed range",
Helpers.LogLevel.Error, Client);
}
header.QuantWBits |= (wbits - 2);
output.PackBits(header.QuantWBits, 8);
output.PackFloat(header.DCOffset);
output.PackBits(header.Range, 16);
output.PackBits(header.PatchIDs, 10);
return wbits;
}
private void IDCTColumn16(float[] linein, float[] lineout, int column)
{
float total;
int usize;
for (int n = 0; n < 16; n++)
{
total = OO_SQRT2 * linein[column];
for (int u = 1; u < 16; u++)
{
usize = u * 16;
total += linein[usize + column] * CosineTable16[usize + n];
}
lineout[16 * n + column] = total;
}
}
/* private void IDCTColumn32(float[] linein, float[] lineout, int column)
{
float total;
int usize;
for (int n = 0; n < 32; n++)
{
total = OO_SQRT2 * linein[column];
for (int u = 1; u < 32; u++)
{
usize = u * 32;
total += linein[usize + column] * CosineTable32[usize + n];
}
lineout[32 * n + column] = total;
}
}
*/
private void IDCTLine16(float[] linein, float[] lineout, int line)
{
const float oosob = 2.0f / 16.0f;
int lineSize = line * 16;
float total;
for (int n = 0; n < 16; n++)
{
total = OO_SQRT2 * linein[lineSize];
for (int u = 1; u < 16; u++)
{
total += linein[lineSize + u] * CosineTable16[u * 16 + n];
}
lineout[lineSize + n] = total * oosob;
}
}
/* private void IDCTLine32(float[] linein, float[] lineout, int line)
{
const float oosob = 2.0f / 32.0f;
int lineSize = line * 32;
float total;
for (int n = 0; n < 32; n++)
{
total = OO_SQRT2 * linein[lineSize];
for (int u = 1; u < 32; u++)
{
total += linein[lineSize + u] * CosineTable32[u * 32 + n];
}
lineout[lineSize + n] = total * oosob;
}
} */
private void DCTLine16(float[] linein, float[] lineout, int line)
{
float total = 0.0f;
int lineSize = line * 16;
for (int n = 0; n < 16; n++)
{
total += linein[lineSize + n];
}
lineout[lineSize] = OO_SQRT2 * total;
for (int u = 1; u < 16; u++)
{
total = 0.0f;
for (int n = 0; n < 16; n++)
{
total += linein[lineSize + n] * CosineTable16[u * 16 + n];
}
lineout[lineSize + u] = total;
}
}
private void DCTColumn16(float[] linein, int[] lineout, int column)
{
float total = 0.0f;
const float oosob = 2.0f / 16.0f;
for (int n = 0; n < 16; n++)
{
total += linein[16 * n + column];
}
lineout[CopyMatrix16[column]] = (int)(OO_SQRT2 * total * oosob * QuantizeTable16[column]);
for (int u = 1; u < 16; u++)
{
total = 0.0f;
for (int n = 0; n < 16; n++)
{
total += linein[16 * n + column] * CosineTable16[u * 16 + n];
}
lineout[CopyMatrix16[16 * u + column]] = (int)(total * oosob * QuantizeTable16[16 * u + column]);
}
}
private void DecodePatch(int[] patches, BitPack bitpack, PatchHeader header, int size)
{
int temp;
for (int n = 0; n < size * size; n++)
{
// ?
temp = bitpack.UnpackBits(1);
if (temp != 0)
{
// Value or EOB
temp = bitpack.UnpackBits(1);
if (temp != 0)
{
// Value
temp = bitpack.UnpackBits(1);
if (temp != 0)
{
// Negative
temp = bitpack.UnpackBits((int)header.WordBits);
patches[n] = temp * -1;
}
else
{
// Positive
temp = bitpack.UnpackBits((int)header.WordBits);
patches[n] = temp;
}
}
else
{
// Set the rest to zero
// TODO: This might not be necessary
for (int o = n; o < size * size; o++)
{
patches[o] = 0;
}
break;
}
}
else
{
patches[n] = 0;
}
}
}
private void EncodePatch(BitPack output, int[] patch, int postquant, int wbits)
{
int temp;
bool eob;
if (postquant > 16 * 16 || postquant < 0)
{
Logger.Log("Postquant is outside the range of allowed values in EncodePatch()", Helpers.LogLevel.Error, Client);
return;
}
if (postquant != 0) patch[16 * 16 - postquant] = 0;
for (int i = 0; i < 16 * 16; i++)
{
eob = false;
temp = patch[i];
if (temp == 0)
{
eob = true;
for (int j = i; j < 16 * 16 - postquant; j++)
{
if (patch[j] != 0)
{
eob = false;
break;
}
}
if (eob)
{
output.PackBits(ZERO_EOB, 2);
return;
}
else
{
output.PackBits(ZERO_CODE, 1);
}
}
else
{
if (temp < 0)
{
temp *= -1;
if (temp > (1 << wbits)) temp = (1 << wbits);
output.PackBits(NEGATIVE_VALUE, 3);
output.PackBits(temp, wbits);
}
else
{
if (temp > (1 << wbits)) temp = (1 << wbits);
output.PackBits(POSITIVE_VALUE, 3);
output.PackBits(temp, wbits);
}
}
}
}
private float[] DecompressPatch(int[] patches, PatchHeader header, GroupHeader group)
{
float[] block = new float[group.PatchSize * group.PatchSize];
float[] output = new float[group.PatchSize * group.PatchSize];
int prequant = (header.QuantWBits >> 4) + 2;
int quantize = 1 << prequant;
float ooq = 1.0f / (float)quantize;
float mult = ooq * (float)header.Range;
float addval = mult * (float)(1 << (prequant - 1)) + header.DCOffset;
if (group.PatchSize == 16)
{
for (int n = 0; n < 16 * 16; n++)
{
block[n] = patches[CopyMatrix16[n]] * DequantizeTable16[n];
}
float[] ftemp = new float[16 * 16];
for (int o = 0; o < 16; o++)
IDCTColumn16(block, ftemp, o);
for (int o = 0; o < 16; o++)
IDCTLine16(ftemp, block, o);
}
else
{
for (int n = 0; n < 32 * 32; n++)
{
block[n] = patches[CopyMatrix32[n]] * DequantizeTable32[n];
}
Logger.Log("Implement IDCTPatchLarge", Helpers.LogLevel.Error, Client);
}
for (int j = 0; j < block.Length; j++)
{
output[j] = block[j] * mult + addval;
}
return output;
}
private int[] CompressPatch(float[] heightmap, int patchX, int patchY, PatchHeader header, int prequant)
{
float[] block = new float[16 * 16];
int wordsize = prequant;
float oozrange = 1.0f / (float)header.Range;
float range = (float)(1 << prequant);
float premult = oozrange * range;
float sub = (float)(1 << (prequant - 1)) + header.DCOffset * premult;
header.QuantWBits = wordsize - 2;
header.QuantWBits |= (prequant - 2) << 4;
int k = 0;
for (int j = patchY * 16; j < (patchY + 1) * 16; j++)
{
for (int i = patchX * 16; i < (patchX + 1) * 16; i++)
{
block[k++] = heightmap[j * 256 + i] * premult - sub;
}
}
float[] ftemp = new float[16 * 16];
int[] itemp = new int[16 * 16];
for (int o = 0; o < 16; o++)
DCTLine16(block, ftemp, o);
for (int o = 0; o < 16; o++)
DCTColumn16(ftemp, itemp, o);
return itemp;
}
private void DecompressLand(Simulator simulator, BitPack bitpack, GroupHeader group)
{
int x;
int y;
int[] patches = new int[32 * 32];
int count = 0;
while (true)
{
PatchHeader header = DecodePatchHeader(bitpack);
if (header.QuantWBits == END_OF_PATCHES)
break;
x = header.PatchIDs >> 5;
y = header.PatchIDs & 0x1F;
if (x >= PATCHES_PER_EDGE || y >= PATCHES_PER_EDGE)
{
Logger.Log("Invalid LayerData land packet, x = " + x + ", y = " + y + ", dc_offset = " +
header.DCOffset + ", range = " + header.Range + ", quant_wbits = " + header.QuantWBits +
", patchids = " + header.PatchIDs + ", count = " + count, Helpers.LogLevel.Warning, Client);
return;
}
// Decode this patch
DecodePatch(patches, bitpack, header, group.PatchSize);
// Decompress this patch
float[] heightmap = DecompressPatch(patches, header, group);
count++;
if (OnLandPatch != null)
{
try { OnLandPatch(simulator, x, y, group.PatchSize, heightmap); }
catch (Exception e) { Logger.Log(e.Message, Helpers.LogLevel.Error, Client, e); }
}
if (Client.Settings.STORE_LAND_PATCHES)
{
lock (SimPatches)
{
if (!SimPatches.ContainsKey(simulator.Handle))
SimPatches.Add(simulator.Handle, new Patch[16 * 16]);
SimPatches[simulator.Handle][y * 16 + x] = new Patch();
SimPatches[simulator.Handle][y * 16 + x].Heightmap = heightmap;
}
}
}
}
private void DecompressWind(Simulator simulator, BitPack bitpack, GroupHeader group)
{
;
}
private void DecompressCloud(Simulator simulator, BitPack bitpack, GroupHeader group)
{
;
}
private void LayerDataHandler(Packet packet, Simulator simulator)
{
LayerDataPacket layer = (LayerDataPacket)packet;
BitPack bitpack = new BitPack(layer.LayerData.Data, 0);
GroupHeader header = new GroupHeader();
LayerType type = (LayerType)layer.LayerID.Type;
// Stride
header.Stride = bitpack.UnpackBits(16);
// Patch size
header.PatchSize = bitpack.UnpackBits(8);
// Layer type
header.Type = (LayerType)bitpack.UnpackBits(8);
switch (type)
{
case LayerType.Land:
if (OnLandPatch != null || Client.Settings.STORE_LAND_PATCHES)
DecompressLand(simulator, bitpack, header);
break;
case LayerType.Water:
Logger.Log("Got a Water LayerData packet, implement me!", Helpers.LogLevel.Error, Client);
break;
case LayerType.Wind:
DecompressWind(simulator, bitpack, header);
break;
case LayerType.Cloud:
DecompressCloud(simulator, bitpack, header);
break;
default:
Logger.Log("Unrecognized LayerData type " + type.ToString(), Helpers.LogLevel.Warning, Client);
break;
}
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
extern alias WORKSPACES;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Ipc;
using System.Runtime.Remoting.Messaging;
using System.Runtime.Serialization.Formatters;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.CodeAnalysis.Scripting;
using Microsoft.CodeAnalysis.Scripting.Hosting;
using Roslyn.Utilities;
using RuntimeMetadataReferenceResolver = WORKSPACES::Microsoft.CodeAnalysis.Scripting.Hosting.RuntimeMetadataReferenceResolver;
using NuGetPackageResolver = WORKSPACES::Microsoft.CodeAnalysis.Scripting.Hosting.NuGetPackageResolver;
using GacFileResolver = WORKSPACES::Microsoft.CodeAnalysis.Scripting.Hosting.GacFileResolver;
namespace Microsoft.CodeAnalysis.Interactive
{
internal partial class InteractiveHost
{
/// <summary>
/// A remote singleton server-activated object that lives in the interactive host process and controls it.
/// </summary>
internal sealed class Service : MarshalByRefObject, IDisposable
{
private static readonly ManualResetEventSlim s_clientExited = new ManualResetEventSlim(false);
private static TaskScheduler s_UIThreadScheduler;
private readonly InteractiveAssemblyLoader _assemblyLoader;
private readonly MetadataShadowCopyProvider _metadataFileProvider;
private ReplServiceProvider _replServiceProvider;
private readonly InteractiveHostObject _hostObject;
private ObjectFormattingOptions _formattingOptions;
// Session is not thread-safe by itself, and the compilation
// and execution of scripts are asynchronous operations.
// However since the operations are executed serially, it
// is sufficient to lock when creating the async tasks.
private readonly object _lastTaskGuard = new object();
private Task<EvaluationState> _lastTask;
private struct EvaluationState
{
internal ImmutableArray<string> SourceSearchPaths;
internal ImmutableArray<string> ReferenceSearchPaths;
internal string WorkingDirectory;
internal readonly ScriptState<object> ScriptStateOpt;
internal readonly ScriptOptions ScriptOptions;
internal EvaluationState(
ScriptState<object> scriptState,
ScriptOptions scriptOptions,
ImmutableArray<string> sourceSearchPaths,
ImmutableArray<string> referenceSearchPaths,
string workingDirectory)
{
ScriptStateOpt = scriptState;
ScriptOptions = scriptOptions;
SourceSearchPaths = sourceSearchPaths;
ReferenceSearchPaths = referenceSearchPaths;
WorkingDirectory = workingDirectory;
}
internal EvaluationState WithScriptState(ScriptState<object> state)
{
return new EvaluationState(
state,
ScriptOptions,
SourceSearchPaths,
ReferenceSearchPaths,
WorkingDirectory);
}
internal EvaluationState WithOptions(ScriptOptions options)
{
return new EvaluationState(
ScriptStateOpt,
options,
SourceSearchPaths,
ReferenceSearchPaths,
WorkingDirectory);
}
}
private static readonly ImmutableArray<string> s_systemNoShadowCopyDirectories = ImmutableArray.Create(
FileUtilities.NormalizeDirectoryPath(Environment.GetFolderPath(Environment.SpecialFolder.Windows)),
FileUtilities.NormalizeDirectoryPath(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles)),
FileUtilities.NormalizeDirectoryPath(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86)),
FileUtilities.NormalizeDirectoryPath(RuntimeEnvironment.GetRuntimeDirectory()));
#region Setup
public Service()
{
// TODO (tomat): we should share the copied files with the host
_metadataFileProvider = new MetadataShadowCopyProvider(
Path.Combine(Path.GetTempPath(), "InteractiveHostShadow"),
noShadowCopyDirectories: s_systemNoShadowCopyDirectories);
_assemblyLoader = new InteractiveAssemblyLoader(_metadataFileProvider);
_formattingOptions = new ObjectFormattingOptions(
memberFormat: MemberDisplayFormat.Inline,
quoteStrings: true,
useHexadecimalNumbers: false,
maxOutputLength: 200,
memberIndentation: " ");
_hostObject = new InteractiveHostObject();
var initialState = new EvaluationState(
scriptState: null,
scriptOptions: ScriptOptions.Default,
sourceSearchPaths: ImmutableArray<string>.Empty,
referenceSearchPaths: ImmutableArray<string>.Empty,
workingDirectory: Directory.GetCurrentDirectory());
_lastTask = Task.FromResult(initialState);
Console.OutputEncoding = Encoding.UTF8;
// We want to be sure to delete the shadow-copied files when the process goes away. Frankly
// there's nothing we can do if the process is forcefully quit or goes down in a completely
// uncontrolled manner (like a stack overflow). When the process goes down in a controlled
// manned, we should generally expect this event to be called.
AppDomain.CurrentDomain.ProcessExit += HandleProcessExit;
}
private void HandleProcessExit(object sender, EventArgs e)
{
Dispose();
AppDomain.CurrentDomain.ProcessExit -= HandleProcessExit;
}
public void Dispose()
{
_metadataFileProvider.Dispose();
}
public override object InitializeLifetimeService()
{
return null;
}
public void Initialize(Type replServiceProviderType)
{
Contract.ThrowIfNull(replServiceProviderType);
_replServiceProvider = (ReplServiceProvider)Activator.CreateInstance(replServiceProviderType);
}
private MetadataReferenceResolver CreateMetadataReferenceResolver(ImmutableArray<string> searchPaths, string baseDirectory)
{
return new RuntimeMetadataReferenceResolver(
new RelativePathResolver(searchPaths, baseDirectory),
null, // TODO
new GacFileResolver(
architectures: GacFileResolver.Default.Architectures, // TODO (tomat)
preferredCulture: CultureInfo.CurrentCulture), // TODO (tomat)
(path, properties) => _metadataFileProvider.GetReference(path, properties));
}
private SourceReferenceResolver CreateSourceReferenceResolver(ImmutableArray<string> searchPaths, string baseDirectory)
{
return new SourceFileResolver(searchPaths, baseDirectory);
}
private static bool AttachToClientProcess(int clientProcessId)
{
Process clientProcess;
try
{
clientProcess = Process.GetProcessById(clientProcessId);
}
catch (ArgumentException)
{
return false;
}
clientProcess.EnableRaisingEvents = true;
clientProcess.Exited += new EventHandler((_, __) =>
{
s_clientExited.Set();
});
return clientProcess.IsAlive();
}
// for testing purposes
public void EmulateClientExit()
{
s_clientExited.Set();
}
internal static void RunServer(string[] args)
{
if (args.Length != 3)
{
throw new ArgumentException("Expecting arguments: <server port> <semaphore name> <client process id>");
}
RunServer(args[0], args[1], int.Parse(args[2], CultureInfo.InvariantCulture));
}
/// <summary>
/// Implements remote server.
/// </summary>
private static void RunServer(string serverPort, string semaphoreName, int clientProcessId)
{
if (!AttachToClientProcess(clientProcessId))
{
return;
}
// Disables Windows Error Reporting for the process, so that the process fails fast.
// Unfortunately, this doesn't work on Windows Server 2008 (OS v6.0), Vista (OS v6.0) and XP (OS v5.1)
// Note that GetErrorMode is not available on XP at all.
if (Environment.OSVersion.Version >= new Version(6, 1, 0, 0))
{
SetErrorMode(GetErrorMode() | ErrorMode.SEM_FAILCRITICALERRORS | ErrorMode.SEM_NOOPENFILEERRORBOX | ErrorMode.SEM_NOGPFAULTERRORBOX);
}
IpcServerChannel serverChannel = null;
IpcClientChannel clientChannel = null;
try
{
using (var semaphore = Semaphore.OpenExisting(semaphoreName))
{
// DEBUG: semaphore.WaitOne();
var serverProvider = new BinaryServerFormatterSinkProvider();
serverProvider.TypeFilterLevel = TypeFilterLevel.Full;
var clientProvider = new BinaryClientFormatterSinkProvider();
clientChannel = new IpcClientChannel(GenerateUniqueChannelLocalName(), clientProvider);
ChannelServices.RegisterChannel(clientChannel, ensureSecurity: false);
serverChannel = new IpcServerChannel(GenerateUniqueChannelLocalName(), serverPort, serverProvider);
ChannelServices.RegisterChannel(serverChannel, ensureSecurity: false);
RemotingConfiguration.RegisterWellKnownServiceType(
typeof(Service),
ServiceName,
WellKnownObjectMode.Singleton);
using (var resetEvent = new ManualResetEventSlim(false))
{
var uiThread = new Thread(() =>
{
var c = new Control();
c.CreateControl();
s_UIThreadScheduler = TaskScheduler.FromCurrentSynchronizationContext();
resetEvent.Set();
Application.Run();
});
uiThread.SetApartmentState(ApartmentState.STA);
uiThread.IsBackground = true;
uiThread.Start();
resetEvent.Wait();
}
// the client can instantiate interactive host now:
semaphore.Release();
}
s_clientExited.Wait();
}
finally
{
if (serverChannel != null)
{
ChannelServices.UnregisterChannel(serverChannel);
}
if (clientChannel != null)
{
ChannelServices.UnregisterChannel(clientChannel);
}
}
// force exit even if there are foreground threads running:
Environment.Exit(0);
}
internal static string ServiceName
{
get { return typeof(Service).Name; }
}
private static string GenerateUniqueChannelLocalName()
{
return typeof(Service).FullName + Guid.NewGuid();
}
#endregion
#region Remote Async Entry Points
// Used by ResetInteractive - consider improving (we should remember the parameters for auto-reset, e.g.)
[OneWay]
public void SetPathsAsync(
RemoteAsyncOperation<RemoteExecutionResult> operation,
string[] referenceSearchPaths,
string[] sourceSearchPaths,
string baseDirectory)
{
Debug.Assert(operation != null);
Debug.Assert(referenceSearchPaths != null);
Debug.Assert(sourceSearchPaths != null);
Debug.Assert(baseDirectory != null);
lock (_lastTaskGuard)
{
_lastTask = SetPathsAsync(_lastTask, operation, referenceSearchPaths, sourceSearchPaths, baseDirectory);
}
}
private async Task<EvaluationState> SetPathsAsync(
Task<EvaluationState> lastTask,
RemoteAsyncOperation<RemoteExecutionResult> operation,
string[] referenceSearchPaths,
string[] sourceSearchPaths,
string baseDirectory)
{
var state = await ReportUnhandledExceptionIfAny(lastTask).ConfigureAwait(false);
try
{
Directory.SetCurrentDirectory(baseDirectory);
_hostObject.ReferencePaths.Clear();
_hostObject.ReferencePaths.AddRange(referenceSearchPaths);
_hostObject.SourcePaths.Clear();
_hostObject.SourcePaths.AddRange(sourceSearchPaths);
}
finally
{
state = CompleteExecution(state, operation, success: true);
}
return state;
}
/// <summary>
/// Reads given initialization file (.rsp) and loads and executes all assembly references and files, respectively specified in it.
/// Execution is performed on the UI thread.
/// </summary>
[OneWay]
public void InitializeContextAsync(RemoteAsyncOperation<RemoteExecutionResult> operation, string initializationFile, bool isRestarting)
{
Debug.Assert(operation != null);
lock (_lastTaskGuard)
{
_lastTask = InitializeContextAsync(_lastTask, operation, initializationFile, isRestarting);
}
}
/// <summary>
/// Adds an assembly reference to the current session.
/// </summary>
[OneWay]
public void AddReferenceAsync(RemoteAsyncOperation<bool> operation, string reference)
{
Debug.Assert(operation != null);
Debug.Assert(reference != null);
lock (_lastTaskGuard)
{
_lastTask = AddReferenceAsync(_lastTask, operation, reference);
}
}
private async Task<EvaluationState> AddReferenceAsync(Task<EvaluationState> lastTask, RemoteAsyncOperation<bool> operation, string reference)
{
var state = await ReportUnhandledExceptionIfAny(lastTask).ConfigureAwait(false);
bool success = false;
try
{
var resolvedReferences = state.ScriptOptions.MetadataResolver.ResolveReference(reference, baseFilePath: null, properties: MetadataReferenceProperties.Assembly);
if (!resolvedReferences.IsDefaultOrEmpty)
{
state = state.WithOptions(state.ScriptOptions.AddReferences(resolvedReferences));
success = true;
}
else
{
Console.Error.WriteLine(string.Format(FeaturesResources.CannotResolveReference, reference));
}
}
catch (Exception e)
{
ReportUnhandledException(e);
}
finally
{
operation.Completed(success);
}
return state;
}
/// <summary>
/// Executes given script snippet on the UI thread in the context of the current session.
/// </summary>
[OneWay]
public void ExecuteAsync(RemoteAsyncOperation<RemoteExecutionResult> operation, string text)
{
Debug.Assert(operation != null);
Debug.Assert(text != null);
lock (_lastTaskGuard)
{
_lastTask = ExecuteAsync(_lastTask, operation, text);
}
}
private async Task<EvaluationState> ExecuteAsync(Task<EvaluationState> lastTask, RemoteAsyncOperation<RemoteExecutionResult> operation, string text)
{
var state = await ReportUnhandledExceptionIfAny(lastTask).ConfigureAwait(false);
bool success = false;
try
{
Script<object> script = TryCompile(state.ScriptStateOpt?.Script, text, null, state.ScriptOptions);
if (script != null)
{
// successful if compiled
success = true;
var newScriptState = await ExecuteOnUIThread(script, state.ScriptStateOpt).ConfigureAwait(false);
if (newScriptState != null)
{
DisplaySubmissionResult(newScriptState);
state = state.WithScriptState(newScriptState);
}
}
}
catch (Exception e)
{
ReportUnhandledException(e);
}
finally
{
state = CompleteExecution(state, operation, success);
}
return state;
}
private void DisplaySubmissionResult(ScriptState<object> state)
{
bool hasValue;
var resultType = state.Script.GetCompilation().GetSubmissionResultType(out hasValue);
if (hasValue)
{
if (resultType != null && resultType.SpecialType == SpecialType.System_Void)
{
Console.Out.WriteLine(_replServiceProvider.ObjectFormatter.VoidDisplayString);
}
else
{
Console.Out.WriteLine(_replServiceProvider.ObjectFormatter.FormatObject(state.ReturnValue, _formattingOptions));
}
}
}
/// <summary>
/// Executes given script file on the UI thread in the context of the current session.
/// </summary>
[OneWay]
public void ExecuteFileAsync(RemoteAsyncOperation<RemoteExecutionResult> operation, string path)
{
Debug.Assert(operation != null);
Debug.Assert(path != null);
lock (_lastTaskGuard)
{
_lastTask = ExecuteFileAsync(operation, _lastTask, path);
}
}
private EvaluationState CompleteExecution(EvaluationState state, RemoteAsyncOperation<RemoteExecutionResult> operation, bool success)
{
// send any updates to the host object and current directory back to the client:
var currentSourcePaths = _hostObject.SourcePaths.List.ToArray();
var currentReferencePaths = _hostObject.ReferencePaths.List.ToArray();
var currentWorkingDirectory = Directory.GetCurrentDirectory();
var changedSourcePaths = currentSourcePaths.SequenceEqual(state.SourceSearchPaths) ? null : currentSourcePaths;
var changedReferencePaths = currentSourcePaths.SequenceEqual(state.ReferenceSearchPaths) ? null : currentReferencePaths;
var changedWorkingDirectory = currentWorkingDirectory == state.WorkingDirectory ? null : currentWorkingDirectory;
operation.Completed(new RemoteExecutionResult(success, changedSourcePaths, changedReferencePaths, changedWorkingDirectory));
// no changes in resolvers:
if (changedReferencePaths == null && changedSourcePaths == null && changedWorkingDirectory == null)
{
return state;
}
var newSourcePaths = ImmutableArray.CreateRange(currentSourcePaths);
var newReferencePaths = ImmutableArray.CreateRange(currentReferencePaths);
var newWorkingDirectory = currentWorkingDirectory;
ScriptOptions newOptions = state.ScriptOptions;
if (changedReferencePaths != null || changedWorkingDirectory != null)
{
newOptions = newOptions.WithCustomMetadataResolution(CreateMetadataReferenceResolver(newReferencePaths, newWorkingDirectory));
}
if (changedSourcePaths != null || changedWorkingDirectory != null)
{
newOptions = newOptions.WithCustomSourceResolution(CreateSourceReferenceResolver(newSourcePaths, newWorkingDirectory));
}
return new EvaluationState(
state.ScriptStateOpt,
newOptions,
newSourcePaths,
newReferencePaths,
workingDirectory: newWorkingDirectory);
}
private static async Task<EvaluationState> ReportUnhandledExceptionIfAny(Task<EvaluationState> lastTask)
{
try
{
return await lastTask.ConfigureAwait(false);
}
catch (Exception e)
{
ReportUnhandledException(e);
return lastTask.Result;
}
}
private static void ReportUnhandledException(Exception e)
{
Console.Error.WriteLine("Unexpected error:");
Console.Error.WriteLine(e);
Debug.Fail("Unexpected error");
Debug.WriteLine(e);
}
#endregion
#region Operations
// TODO (tomat): testing only
public void SetTestObjectFormattingOptions()
{
_formattingOptions = new ObjectFormattingOptions(
memberFormat: MemberDisplayFormat.Inline,
quoteStrings: true,
useHexadecimalNumbers: false,
maxOutputLength: int.MaxValue,
memberIndentation: " ");
}
/// <summary>
/// Loads references, set options and execute files specified in the initialization file.
/// Also prints logo unless <paramref name="isRestarting"/> is true.
/// </summary>
private async Task<EvaluationState> InitializeContextAsync(
Task<EvaluationState> lastTask,
RemoteAsyncOperation<RemoteExecutionResult> operation,
string initializationFileOpt,
bool isRestarting)
{
Debug.Assert(initializationFileOpt == null || PathUtilities.IsAbsolute(initializationFileOpt));
var state = await ReportUnhandledExceptionIfAny(lastTask).ConfigureAwait(false);
try
{
// TODO (tomat): this is also done in CommonInteractiveEngine, perhaps we can pass the parsed command lines to here?
if (!isRestarting)
{
Console.Out.WriteLine(_replServiceProvider.Logo);
}
if (File.Exists(initializationFileOpt))
{
Console.Out.WriteLine(string.Format(FeaturesResources.LoadingContextFrom, Path.GetFileName(initializationFileOpt)));
var parser = _replServiceProvider.CommandLineParser;
// The base directory for relative paths is the directory that contains the .rsp file.
// Note that .rsp files included by this .rsp file will share the base directory (Dev10 behavior of csc/vbc).
var rspDirectory = Path.GetDirectoryName(initializationFileOpt);
var args = parser.Parse(new[] { "@" + initializationFileOpt }, rspDirectory, RuntimeEnvironment.GetRuntimeDirectory(), null /* TODO: pass a valid value*/);
foreach (var error in args.Errors)
{
var writer = (error.Severity == DiagnosticSeverity.Error) ? Console.Error : Console.Out;
writer.WriteLine(error.GetMessage(CultureInfo.CurrentCulture));
}
if (args.Errors.Length == 0)
{
// TODO (tomat): other arguments
// TODO (tomat): parse options
var metadataResolver = CreateMetadataReferenceResolver(args.ReferencePaths, rspDirectory);
_hostObject.ReferencePaths.Clear();
_hostObject.ReferencePaths.AddRange(args.ReferencePaths);
_hostObject.SourcePaths.Clear();
var metadataReferences = new List<PortableExecutableReference>();
foreach (CommandLineReference cmdLineReference in args.MetadataReferences)
{
// interactive command line parser doesn't accept modules or linked assemblies
Debug.Assert(cmdLineReference.Properties.Kind == MetadataImageKind.Assembly && !cmdLineReference.Properties.EmbedInteropTypes);
var resolvedReferences = metadataResolver.ResolveReference(cmdLineReference.Reference, baseFilePath: null, properties: MetadataReferenceProperties.Assembly);
if (!resolvedReferences.IsDefaultOrEmpty)
{
metadataReferences.AddRange(resolvedReferences);
}
}
// only search for scripts next to the .rsp file:
var sourceSearchPaths = ImmutableArray<string>.Empty;
var rspState = new EvaluationState(
state.ScriptStateOpt,
state.ScriptOptions.AddReferences(metadataReferences),
sourceSearchPaths,
args.ReferencePaths,
rspDirectory);
foreach (CommandLineSourceFile file in args.SourceFiles)
{
// execute all files as scripts (matches csi/vbi semantics)
string fullPath = ResolveRelativePath(file.Path, rspDirectory, sourceSearchPaths, displayPath: true);
if (fullPath != null)
{
var newScriptState = await ExecuteFileAsync(rspState, fullPath).ConfigureAwait(false);
if (newScriptState != null)
{
rspState = rspState.WithScriptState(newScriptState);
}
}
}
state = new EvaluationState(
rspState.ScriptStateOpt,
rspState.ScriptOptions,
ImmutableArray<string>.Empty,
args.ReferencePaths,
state.WorkingDirectory);
}
}
if (!isRestarting)
{
Console.Out.WriteLine(FeaturesResources.TypeHelpForMoreInformation);
}
}
catch (Exception e)
{
ReportUnhandledException(e);
}
finally
{
state = CompleteExecution(state, operation, success: true);
}
return state;
}
private string ResolveRelativePath(string path, string baseDirectory, ImmutableArray<string> searchPaths, bool displayPath)
{
List<string> attempts = new List<string>();
Func<string, bool> fileExists = file =>
{
attempts.Add(file);
return File.Exists(file);
};
string fullPath = FileUtilities.ResolveRelativePath(path, null, baseDirectory, searchPaths, fileExists);
if (fullPath == null)
{
if (displayPath)
{
Console.Error.WriteLine(FeaturesResources.SpecifiedFileNotFoundFormat, path);
}
else
{
Console.Error.WriteLine(FeaturesResources.SpecifiedFileNotFound);
}
if (attempts.Count > 0)
{
DisplaySearchPaths(Console.Error, attempts);
}
}
return fullPath;
}
private void LoadReference(PortableExecutableReference resolvedReference, bool suppressWarnings)
{
AssemblyLoadResult result;
try
{
result = _assemblyLoader.LoadFromPath(resolvedReference.FilePath);
}
catch (FileNotFoundException e)
{
Console.Error.WriteLine(e.Message);
return;
}
catch (ArgumentException e)
{
Console.Error.WriteLine((e.InnerException ?? e).Message);
return;
}
catch (TargetInvocationException e)
{
// The user might have hooked AssemblyResolve event, which might have thrown an exception.
// Display stack trace in this case.
Console.Error.WriteLine(e.InnerException.ToString());
return;
}
if (!result.IsSuccessful && !suppressWarnings)
{
Console.Out.WriteLine(string.Format(CultureInfo.CurrentCulture, FeaturesResources.RequestedAssemblyAlreadyLoaded, result.OriginalPath));
}
}
private Script<object> TryCompile(Script previousScript, string code, string path, ScriptOptions options)
{
Script script;
var scriptOptions = options.WithPath(path).WithIsInteractive(path == null);
if (previousScript != null)
{
script = previousScript.ContinueWith(code, scriptOptions);
}
else
{
script = _replServiceProvider.CreateScript<object>(code, scriptOptions, _hostObject.GetType(), _assemblyLoader);
}
// force build so exception is thrown now if errors are found.
try
{
script.Build();
}
catch (CompilationErrorException e)
{
DisplayInteractiveErrors(e.Diagnostics, Console.Error);
return null;
}
// TODO: Do we want to do this?
// Pros: immediate feedback for assemblies that can't be loaded.
// Cons: maybe we won't need them
//foreach (PortableExecutableReference reference in script.GetCompilation().DirectiveReferences)
//{
// LoadReference(reference, suppressWarnings: false);
//}
return (Script<object>)script;
}
private async Task<EvaluationState> ExecuteFileAsync(
RemoteAsyncOperation<RemoteExecutionResult> operation,
Task<EvaluationState> lastTask,
string path)
{
var state = await ReportUnhandledExceptionIfAny(lastTask).ConfigureAwait(false);
var success = false;
try
{
var fullPath = ResolveRelativePath(path, state.WorkingDirectory, state.SourceSearchPaths, displayPath: false);
var newScriptState = await ExecuteFileAsync(state, fullPath).ConfigureAwait(false);
if (newScriptState != null)
{
success = true;
state = state.WithScriptState(newScriptState);
}
}
finally
{
state = CompleteExecution(state, operation, success);
}
return state;
}
/// <summary>
/// Executes specified script file as a submission.
/// </summary>
/// <returns>True if the code has been executed. False if the code doesn't compile.</returns>
/// <remarks>
/// All errors are written to the error output stream.
/// Uses source search paths to resolve unrooted paths.
/// </remarks>
private async Task<ScriptState<object>> ExecuteFileAsync(EvaluationState state, string fullPath)
{
string content = null;
if (fullPath != null)
{
Debug.Assert(PathUtilities.IsAbsolute(fullPath));
try
{
content = File.ReadAllText(fullPath);
}
catch (Exception e)
{
Console.Error.WriteLine(e.Message);
}
}
ScriptState<object> newScriptState = null;
if (content != null)
{
Script<object> script = TryCompile(state.ScriptStateOpt?.Script, content, fullPath, state.ScriptOptions);
if (script != null)
{
newScriptState = await ExecuteOnUIThread(script, state.ScriptStateOpt).ConfigureAwait(false);
}
}
return newScriptState;
}
private static void DisplaySearchPaths(TextWriter writer, List<string> attemptedFilePaths)
{
var directories = attemptedFilePaths.Select(path => Path.GetDirectoryName(path)).ToArray();
var uniqueDirectories = new HashSet<string>(directories);
writer.WriteLine(uniqueDirectories.Count == 1 ?
FeaturesResources.SearchedInDirectory :
FeaturesResources.SearchedInDirectories);
foreach (string directory in directories)
{
if (uniqueDirectories.Remove(directory))
{
writer.Write(" ");
writer.WriteLine(directory);
}
}
}
private async Task<ScriptState<object>> ExecuteOnUIThread(Script<object> script, ScriptState<object> stateOpt)
{
return await Task.Factory.StartNew(async () =>
{
try
{
var task = (stateOpt == null) ?
script.RunAsync(_hostObject, CancellationToken.None) :
script.ContinueAsync(stateOpt, CancellationToken.None);
return await task.ConfigureAwait(false);
}
catch (Exception e)
{
// TODO (tomat): format exception
Console.Error.WriteLine(e);
return null;
}
},
CancellationToken.None,
TaskCreationOptions.None,
s_UIThreadScheduler).Unwrap().ConfigureAwait(false);
}
private void DisplayInteractiveErrors(ImmutableArray<Diagnostic> diagnostics, TextWriter output)
{
var displayedDiagnostics = new List<Diagnostic>();
const int MaxErrorCount = 5;
for (int i = 0, n = Math.Min(diagnostics.Length, MaxErrorCount); i < n; i++)
{
displayedDiagnostics.Add(diagnostics[i]);
}
displayedDiagnostics.Sort((d1, d2) => d1.Location.SourceSpan.Start - d2.Location.SourceSpan.Start);
var formatter = _replServiceProvider.DiagnosticFormatter;
foreach (var diagnostic in displayedDiagnostics)
{
output.WriteLine(formatter.Format(diagnostic, output.FormatProvider as CultureInfo));
}
if (diagnostics.Length > MaxErrorCount)
{
int notShown = diagnostics.Length - MaxErrorCount;
output.WriteLine(string.Format(output.FormatProvider, FeaturesResources.PlusAdditional, notShown, (notShown == 1) ? "error" : "errors"));
}
}
#endregion
#region Win32 API
[DllImport("kernel32", PreserveSig = true)]
internal static extern ErrorMode SetErrorMode(ErrorMode mode);
[DllImport("kernel32", PreserveSig = true)]
internal static extern ErrorMode GetErrorMode();
[Flags]
internal enum ErrorMode : int
{
/// <summary>
/// Use the system default, which is to display all error dialog boxes.
/// </summary>
SEM_FAILCRITICALERRORS = 0x0001,
/// <summary>
/// The system does not display the critical-error-handler message box. Instead, the system sends the error to the calling process.
/// Best practice is that all applications call the process-wide SetErrorMode function with a parameter of SEM_FAILCRITICALERRORS at startup.
/// This is to prevent error mode dialogs from hanging the application.
/// </summary>
SEM_NOGPFAULTERRORBOX = 0x0002,
/// <summary>
/// The system automatically fixes memory alignment faults and makes them invisible to the application.
/// It does this for the calling process and any descendant processes. This feature is only supported by
/// certain processor architectures. For more information, see the Remarks section.
/// After this value is set for a process, subsequent attempts to clear the value are ignored.
/// </summary>
SEM_NOALIGNMENTFAULTEXCEPT = 0x0004,
/// <summary>
/// The system does not display a message box when it fails to find a file. Instead, the error is returned to the calling process.
/// </summary>
SEM_NOOPENFILEERRORBOX = 0x8000,
}
#endregion
#region Testing
// TODO(tomat): remove when the compiler supports events
// For testing purposes only!
public void HookMaliciousAssemblyResolve()
{
AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler((_, __) =>
{
int i = 0;
while (true)
{
if (i < 10)
{
i = i + 1;
}
else if (i == 10)
{
Console.Error.WriteLine("in the loop");
i = i + 1;
}
}
});
}
public void RemoteConsoleWrite(byte[] data, bool isError)
{
using (var stream = isError ? Console.OpenStandardError() : Console.OpenStandardOutput())
{
stream.Write(data, 0, data.Length);
stream.Flush();
}
}
public bool IsShadowCopy(string path)
{
return _metadataFileProvider.IsShadowCopy(path);
}
#endregion
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using Microsoft.Win32;
using SIL.IO;
using SIL.PlatformUtilities;
using SIL.Reflection;
namespace SIL.Reporting
{
public interface IErrorReporter
{
void ReportFatalException(Exception e);
ErrorResult NotifyUserOfProblem(IRepeatNoticePolicy policy,
string alternateButton1Label,
ErrorResult resultIfAlternateButtonPressed,
string message);
void ReportNonFatalException(Exception exception, IRepeatNoticePolicy policy);
void ReportNonFatalExceptionWithMessage(Exception error, string message, params object[] args);
void ReportNonFatalMessageWithStackTrace(string message, params object[] args);
void ReportFatalMessageWithStackTrace(string message, object[] args);
}
public enum ErrorResult
{
None,
OK,
Cancel,
Abort,
Retry,
Ignore,
Yes,
No
}
public class ErrorReport
{
#region Windows8PlusVersionReportingSupport
[DllImport("netapi32.dll", CharSet = CharSet.Auto)]
static extern int NetWkstaGetInfo(string server,
int level,
out IntPtr info);
[DllImport("netapi32.dll")]
static extern int NetApiBufferFree(IntPtr pBuf);
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
struct MachineInfo
{
public int platform_id;
[MarshalAs(UnmanagedType.LPWStr)]
public string _computerName;
[MarshalAs(UnmanagedType.LPWStr)]
public string _languageGroup;
public int _majorVersion;
public int _minorVersion;
}
/// <summary>
/// An application can avoid the need of this method by adding/modifying the application manifest to declare support for a
/// particular windows version. This code is still necessary to report usefully about versions of windows released after
/// the application has shipped.
/// </summary>
public static string GetWindowsVersionInfoFromNetworkAPI()
{
IntPtr pBuffer;
// Get the version information from the network api, passing null to get network info from this machine
var retval = NetWkstaGetInfo(null, 100, out pBuffer);
if(retval != 0)
return "Windows Unknown(unidentifiable)";
var info = (MachineInfo)Marshal.PtrToStructure(pBuffer, typeof(MachineInfo));
string windowsVersion = null;
if(info._majorVersion == 6)
{
if(info._minorVersion == 2)
windowsVersion = "Windows 8";
else if(info._minorVersion == 3)
windowsVersion = "Windows 8.1";
}
else if(info._majorVersion == 10 && info._minorVersion == 0)
{
windowsVersion = "Windows 10";
}
else
{
windowsVersion = string.Format("Windows Unknown({0}.{1})", info._majorVersion, info._minorVersion);
}
NetApiBufferFree(pBuffer);
return windowsVersion;
}
#endregion
private static IErrorReporter _errorReporter;
//We removed all references to Winforms from Palaso.dll but our error reporting relied heavily on it.
//Not wanting to break existing applications we have now added this class initializer which will
//look for a reference to SIL.Windows.Forms in the consuming app and if it exists instantiate the
//WinformsErrorReporter from there through Reflection. otherwise we will simply use a console
//error reporter
static ErrorReport()
{
_errorReporter = ExceptionHandler.GetObjectFromSilWindowsForms<IErrorReporter>() ?? new ConsoleErrorReporter();
}
/// <summary>
/// Use this method if you want to override the default IErrorReporter.
/// This method should normally be called only once at application startup.
/// </summary>
public static void SetErrorReporter(IErrorReporter reporter)
{
_errorReporter = reporter ?? new ConsoleErrorReporter();
}
protected static string s_emailAddress = null;
protected static string s_emailSubject = "Exception Report";
private static Action<Exception, string> s_onShowDetails;
private static bool s_justRecordNonFatalMessagesForTesting=false;
private static string s_previousNonFatalMessage;
private static Exception s_previousNonFatalException;
public static void Init(string emailAddress)
{
s_emailAddress = emailAddress;
ErrorReport.AddStandardProperties();
}
private static void UpdateEmailSubject(Exception error)
{
var subject = new StringBuilder();
subject.AppendFormat("Exception: {0}", error.Message);
try
{
subject.AppendFormat(" in {0}", error.Source);
}
catch {}
s_emailSubject = subject.ToString();
}
public static string GetExceptionText(Exception error)
{
UpdateEmailSubject(error);
return ExceptionHelper.GetExceptionText(error);
}
public static string GetVersionForErrorReporting()
{
return ReflectionHelper.LongVersionNumberString;
}
public static object GetAssemblyAttribute(Type attributeType)
{
Assembly assembly = Assembly.GetEntryAssembly();
if (assembly != null)
{
object[] attributes =
assembly.GetCustomAttributes(attributeType, false);
if (attributes != null && attributes.Length > 0)
{
return attributes[0];
}
}
return null;
}
public static string VersionNumberString => ReflectionHelper.VersionNumberString;
public static string UserFriendlyVersionString
{
get
{
var asm = Assembly.GetEntryAssembly();
var ver = asm.GetName().Version;
var file = PathHelper.StripFilePrefix(asm.CodeBase);
var fi = new FileInfo(file);
return $"Version {ver.Major}.{ver.Minor}.{ver.Build} Built on {fi.CreationTime:dd-MMM-yyyy}";
}
}
/// <remarks>
/// https://docs.microsoft.com/en-us/dotnet/framework/migration-guide/how-to-determine-which-versions-are-installed?view=netframework-4.8
/// Beginning with .NET 4.5, Environment.Version is all but deprecated. The recommended way to determine which .NET Framework versions are
/// installed is to query the registry for a key whose path contains "v4", ensuring that upgrading to .NET 5 will be a breaking change.
/// </remarks>
public static string DotNet4VersionFromWindowsRegistry()
{
if (!Platform.IsWindows)
return string.Empty;
using (var key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full"))
{
return key == null ? "(unable to determine)" : $"{key.GetValue("Version")} ({key.GetValue("Release")})";
}
}
/// <summary>
/// use this in unit tests to cleanly check that a message would have been shown.
/// E.g. using (new Palaso.Reporting.ErrorReport.NonFatalErrorReportExpected()) {...}
/// </summary>
public class NonFatalErrorReportExpected :IDisposable
{
private readonly bool previousJustRecordNonFatalMessagesForTesting;
public NonFatalErrorReportExpected()
{
previousJustRecordNonFatalMessagesForTesting = s_justRecordNonFatalMessagesForTesting;
s_justRecordNonFatalMessagesForTesting = true;
s_previousNonFatalMessage = null;//this is a static, so a previous unit test could have filled it with something (yuck)
}
public void Dispose()
{
s_justRecordNonFatalMessagesForTesting= previousJustRecordNonFatalMessagesForTesting;
if (s_previousNonFatalException == null && s_previousNonFatalMessage == null)
throw new Exception("Non Fatal Error Report was expected but wasn't generated.");
s_previousNonFatalMessage = null;
}
/// <summary>
/// use this to check the actual contents of the message that was triggered
/// </summary>
public string Message
{
get { return s_previousNonFatalMessage; }
}
}
/// <summary>
/// use this in unit tests to cleanly check that a message would have been shown.
/// E.g. using (new Palaso.Reporting.ErrorReport.NonFatalErrorReportExpected()) {...}
/// </summary>
public class NoNonFatalErrorReportExpected : IDisposable
{
private readonly bool previousJustRecordNonFatalMessagesForTesting;
public NoNonFatalErrorReportExpected()
{
previousJustRecordNonFatalMessagesForTesting = s_justRecordNonFatalMessagesForTesting;
s_justRecordNonFatalMessagesForTesting = true;
s_previousNonFatalMessage = null;//this is a static, so a previous unit test could have filled it with something (yuck)
s_previousNonFatalException = null;
}
public void Dispose()
{
s_justRecordNonFatalMessagesForTesting = previousJustRecordNonFatalMessagesForTesting;
if (s_previousNonFatalException != null || s_previousNonFatalMessage != null)
throw new Exception("Non Fatal Error Report was not expected but was generated: "+Message);
s_previousNonFatalMessage = null;
}
/// <summary>
/// use this to check the actual contents of the message that was triggered
/// </summary>
public string Message
{
get { return s_previousNonFatalMessage; }
}
}
/// <summary>
/// set this property if you want the dialog to offer to create an e-mail message.
/// </summary>
public static string EmailAddress
{
set { s_emailAddress = value; }
get { return s_emailAddress; }
}
/// <summary>
/// set this property if you want something other than the default e-mail subject
/// </summary>
public static string EmailSubject
{
set { s_emailSubject = value; }
get { return s_emailSubject; }
}
/// <summary>
/// a list of name, string value pairs that will be included in the details of the error report.
/// </summary>
public static Dictionary<string, string> Properties { get; set; } = new Dictionary<string, string>();
public static bool IsOkToInteractWithUser { get; set; } = true;
/// <summary>
/// Software using ErrorReport's NotifyUserOfProblem methods can set this to their own method
/// for handling when the user clicks the "Details" button.
/// </summary>
public static Action<Exception, string> OnShowDetails
{
get
{
return s_onShowDetails ?? (s_onShowDetails = ReportNonFatalExceptionWithMessage);
}
set
{
s_onShowDetails = value;
}
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// add a property that he would like included in any bug reports created by this application.
/// </summary>
/// ------------------------------------------------------------------------------------
public static void AddProperty(string label, string contents)
{
//avoid an error if the user changes the value of something,
//which happens in FieldWorks, for example, when you change the language project.
if (Properties.ContainsKey(label))
{
Properties.Remove(label);
}
Properties.Add(label, contents);
}
public static void AddStandardProperties()
{
AddProperty("Version", GetVersionForErrorReporting());
AddProperty("CommandLine", Environment.CommandLine);
AddProperty("CurrentDirectory", Environment.CurrentDirectory);
AddProperty("MachineName", Environment.MachineName);
AddProperty("OSVersion", GetOperatingSystemLabel());
if (Platform.IsUnix)
AddProperty("DesktopEnvironment", Platform.DesktopEnvironmentInfoString);
if (Platform.IsMono)
AddProperty("MonoVersion", Platform.MonoVersion);
else
AddProperty("DotNetVersion", DotNet4VersionFromWindowsRegistry());
// https://docs.microsoft.com/en-us/dotnet/api/system.environment.version?view=netframework-4.8 warns that using the Version property is
// no longer recommended for .NET Framework 4.5 or later. I'm leaving it in in hope that it may once again become useful. Note that, as
// of .NET Framework 4.8, it is *not* marked as deprecated.
// https://www.mono-project.com/docs/about-mono/versioning/#framework-versioning (accessed 2020-04-02) states that
// "Mono's System.Environment.Version property [. . .] should be the same version number that .NET would return."
AddProperty("CLR Version (deprecated)", Environment.Version.ToString());
AddProperty("WorkingSet", Environment.WorkingSet.ToString());
AddProperty("UserDomainName", Environment.UserDomainName);
AddProperty("UserName", Environment.UserName);
AddProperty("Culture", CultureInfo.CurrentCulture.ToString());
}
/// <summary>
/// Get the standard properties in a form suitable for other uses
/// (such as analytics).
/// </summary>
public static Dictionary<string, string> GetStandardProperties()
{
var props = new Dictionary<string,string>();
props.Add("Version", GetVersionForErrorReporting());
props.Add("CommandLine", Environment.CommandLine);
props.Add("CurrentDirectory", Environment.CurrentDirectory);
props.Add("MachineName", Environment.MachineName);
props.Add("OSVersion", GetOperatingSystemLabel());
if (Platform.IsUnix)
props.Add("DesktopEnvironment", Platform.DesktopEnvironmentInfoString);
if (Platform.IsMono)
props.Add("MonoVersion", Platform.MonoVersion);
else
props.Add("DotNetVersion", DotNet4VersionFromWindowsRegistry());
props.Add("CLR Version (deprecated)", Environment.Version.ToString());
props.Add("WorkingSet", Environment.WorkingSet.ToString());
props.Add("UserDomainName", Environment.UserDomainName);
props.Add("UserName", Environment.UserName);
props.Add("Culture", CultureInfo.CurrentCulture.ToString());
return props;
}
class Version
{
private readonly PlatformID _platform;
private readonly int _major;
private readonly int _minor;
public string Label { get; private set; }
public Version(PlatformID platform, int major, int minor, string label)
{
_platform = platform;
_major = major;
_minor = minor;
Label = label;
}
public bool Match(OperatingSystem os)
{
return os.Version.Minor == _minor &&
os.Version.Major == _major &&
os.Platform == _platform;
}
}
public static string GetOperatingSystemLabel()
{
if (Environment.OSVersion.Platform == PlatformID.Unix)
{
var startInfo = new ProcessStartInfo("lsb_release", "-si -sr -sc");
startInfo.RedirectStandardOutput = true;
startInfo.UseShellExecute = false;
var proc = new Process { StartInfo = startInfo };
try
{
proc.Start();
proc.WaitForExit(500);
if(proc.ExitCode == 0)
{
var si = proc.StandardOutput.ReadLine();
var sr = proc.StandardOutput.ReadLine();
var sc = proc.StandardOutput.ReadLine();
return String.Format("{0} {1} {2}", si, sr, sc);
}
}
catch (Exception)
{
// lsb_release should work on all supported versions but fall back to the OSVersion.VersionString
}
}
else
{
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms724832%28v=vs.85%29.aspx
var list = new List<Version>();
list.Add(new Version(PlatformID.Win32NT, 5, 0, "Windows 2000"));
list.Add(new Version(PlatformID.Win32NT, 5, 1, "Windows XP"));
list.Add(new Version(PlatformID.Win32NT, 6, 0, "Vista"));
list.Add(new Version(PlatformID.Win32NT, 6, 1, "Windows 7"));
// After Windows 8 the Environment.OSVersion started misreporting information unless
// your app has a manifest which says it supports the OS it is running on. This is not
// helpful if someone starts using an app built before the OS is released. Anything that
// reports its self as Windows 8 is suspect, and must get the version info another way.
list.Add(new Version(PlatformID.Win32NT, 6, 3, "Windows 8.1"));
list.Add(new Version(PlatformID.Win32NT, 10, 0, "Windows 10"));
foreach (var version in list)
{
if (version.Match(Environment.OSVersion))
return version.Label + " " + Environment.OSVersion.ServicePack;
}
// Handle any as yet unrecognized (possibly unmanifested) versions, or anything that reported its self as Windows 8.
if(Environment.OSVersion.Platform == PlatformID.Win32NT)
{
return GetWindowsVersionInfoFromNetworkAPI() + " " + Environment.OSVersion.ServicePack;
}
}
return Environment.OSVersion.VersionString;
}
public static string GetHiearchicalExceptionInfo(Exception error, ref Exception innerMostException)
{
UpdateEmailSubject(error);
return ExceptionHelper.GetHiearchicalExceptionInfo(error, ref innerMostException);
}
public static void ReportFatalException(Exception error)
{
UsageReporter.ReportException(true, null, error, null);
_errorReporter.ReportFatalException(error);
}
/// <summary>
/// Put up a message box, unless OkToInteractWithUser is false, in which case throw an Appliciation Exception.
/// This will not report the problem to the developer. Use one of the "report" methods for that.
/// </summary>
public static void NotifyUserOfProblem(string message, params object[] args)
{
NotifyUserOfProblem(new ShowAlwaysPolicy(), message, args);
}
public static ErrorResult NotifyUserOfProblem(IRepeatNoticePolicy policy, string messageFmt, params object[] args)
{
return NotifyUserOfProblem(policy, null, default(ErrorResult), messageFmt, args);
}
public static void NotifyUserOfProblem(Exception error, string messageFmt, params object[] args)
{
NotifyUserOfProblem(new ShowAlwaysPolicy(), error, messageFmt, args);
}
public static void NotifyUserOfProblem(IRepeatNoticePolicy policy, Exception error, string messageFmt, params object[] args)
{
var result = NotifyUserOfProblem(policy, "Details", ErrorResult.Yes, messageFmt, args);
if (result == ErrorResult.Yes)
{
OnShowDetails(error, string.Format(messageFmt, args));
}
UsageReporter.ReportException(false, null, error, String.Format(messageFmt, args));
}
public static ErrorResult NotifyUserOfProblem(IRepeatNoticePolicy policy,
string alternateButton1Label,
ErrorResult resultIfAlternateButtonPressed,
string messageFmt,
params object[] args)
{
var message = string.Format(messageFmt, args);
if (s_justRecordNonFatalMessagesForTesting)
{
s_previousNonFatalMessage = message;
return ErrorResult.OK;
}
return _errorReporter.NotifyUserOfProblem(policy, alternateButton1Label, resultIfAlternateButtonPressed, message);
}
/// <summary>
/// Bring up a "yellow box" that let's them send in a report, then return to the program.
/// This version assumes the message has already been formatted with any arguments.
/// </summary>
public static void ReportNonFatalExceptionWithMessage(Exception error, string message)
{
s_previousNonFatalMessage = message;
s_previousNonFatalException = error;
_errorReporter.ReportNonFatalExceptionWithMessage(error, message);
}
/// <summary>
/// Bring up a "yellow box" that let's them send in a report, then return to the program.
/// </summary>
public static void ReportNonFatalExceptionWithMessage(Exception error, string message, params object[] args)
{
s_previousNonFatalMessage = message;
s_previousNonFatalException = error;
_errorReporter.ReportNonFatalExceptionWithMessage(error, message, args);
}
/// <summary>
/// Bring up a "yellow box" that let's them send in a report, then return to the program.
/// Use this one only when you don't have an exception (else you're not reporting the exception's message)
/// </summary>
public static void ReportNonFatalMessageWithStackTrace(string message, params object[] args)
{
s_previousNonFatalMessage = message;
_errorReporter.ReportNonFatalMessageWithStackTrace(message, args);
}
/// <summary>
/// Bring up a "green box" that let's them send in a report, then exit.
/// </summary>
public static void ReportFatalMessageWithStackTrace(string message, params object[] args)
{
_errorReporter.ReportFatalMessageWithStackTrace(message, args);
}
/// <summary>
/// Bring up a "yellow box" that lets them send in a report, then return to the program.
/// </summary>
public static void ReportNonFatalException(Exception exception)
{
ReportNonFatalException(exception, new ShowAlwaysPolicy());
}
/// <summary>
/// Allow user to report an exception even though the program doesn't need to exit
/// </summary>
public static void ReportNonFatalException(Exception exception, IRepeatNoticePolicy policy)
{
if (s_justRecordNonFatalMessagesForTesting)
{
ErrorReport.s_previousNonFatalException = exception;
return;
}
_errorReporter.ReportNonFatalException(exception, policy);
UsageReporter.ReportException(false, null, exception, null);
}
/// <summary>
/// this is for interacting with test code which doesn't want to allow an actual UI
/// </summary>
public class ProblemNotificationSentToUserException : ApplicationException
{
public ProblemNotificationSentToUserException(string message) : base(message) {}
}
/// <summary>
/// this is for interacting with test code which doesn't want to allow an actual UI
/// </summary>
public class NonFatalExceptionWouldHaveBeenMessageShownToUserException : ApplicationException
{
public NonFatalExceptionWouldHaveBeenMessageShownToUserException(Exception e) : base(e.Message, e) { }
}
}
public interface IRepeatNoticePolicy
{
bool ShouldShowErrorReportDialog(Exception exception);
bool ShouldShowMessage(string message);
string ReoccurenceMessage
{ get;
}
}
public class ShowAlwaysPolicy :IRepeatNoticePolicy
{
public bool ShouldShowErrorReportDialog(Exception exception)
{
return true;
}
public bool ShouldShowMessage(string message)
{
return true;
}
public string ReoccurenceMessage
{
get { return string.Empty; }
}
}
public class ShowOncePerSessionBasedOnExactMessagePolicy :IRepeatNoticePolicy
{
private static List<string> _alreadyReportedMessages = new List<string>();
public bool ShouldShowErrorReportDialog(Exception exception)
{
return ShouldShowMessage(exception.Message);
}
public bool ShouldShowMessage(string message)
{
if(_alreadyReportedMessages.Contains(message))
return false;
_alreadyReportedMessages.Add(message);
return true;
}
public string ReoccurenceMessage
{
get { return "This message will not be shown again this session."; }
}
public static void Reset()
{
_alreadyReportedMessages.Clear();
}
}
}
| |
#region Disclaimer/Info
///////////////////////////////////////////////////////////////////////////////////////////////////
// Subtext WebLog
//
// Subtext is an open source weblog system that is a fork of the .TEXT
// weblog system.
//
// For updated news and information please visit http://subtextproject.com/
// Subtext is hosted at Google Code at http://code.google.com/p/subtext/
// The development mailing list is at subtext@googlegroups.com
//
// This project is licensed under the BSD license. See the License.txt file for more information.
///////////////////////////////////////////////////////////////////////////////////////////////////
#endregion
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Web.UI.WebControls;
using Subtext.Extensibility.Interfaces;
using Subtext.Framework;
using Subtext.Framework.Components;
using Subtext.Framework.Configuration;
using Subtext.Web.Admin.Commands;
using Subtext.Web.Properties;
namespace Subtext.Web.Admin.Pages
{
// TODO: import - reconcile duplicates
// TODO: CheckAll client-side, confirm bulk delete (add cmd)
public partial class EditLinks : AdminPage
{
private const string VSKEY_LINKID = "LinkID";
private bool _isListHidden = false;
protected CheckBoxList cklCategories;
private int _resultsPageNumber = 0;
public EditLinks()
{
TabSectionId = "Links";
}
private int? filterCategoryID
{
get
{
if (ViewState["filterCategoryID"] == null)
{
return null;
}
else
{
return (int)ViewState["filterCategoryID"];
}
}
set { ViewState["filterCategoryID"] = value; }
}
public int LinkID
{
get
{
if (ViewState[VSKEY_LINKID] != null)
{
return (int)ViewState[VSKEY_LINKID];
}
else
{
return NullValue.NullInt32;
}
}
set { ViewState[VSKEY_LINKID] = value; }
}
protected void Page_Load(object sender, EventArgs e)
{
rprSelectionList.Visible = true;
headerLiteral.Visible = true;
BindLocalUI();
if (!IsPostBack)
{
if (Request.QueryString[Keys.QRYSTR_PAGEINDEX] != null)
{
_resultsPageNumber = Convert.ToInt32(Request.QueryString[Keys.QRYSTR_PAGEINDEX]);
}
if (Request.QueryString[Keys.QRYSTR_CATEGORYID] != null)
{
filterCategoryID = Convert.ToInt32(Request.QueryString[Keys.QRYSTR_CATEGORYID]);
}
resultsPager.PageSize = Preferences.ListingItemCount;
resultsPager.PageIndex = _resultsPageNumber;
if (filterCategoryID != null)
{
resultsPager.UrlFormat += string.Format(CultureInfo.InvariantCulture, "&{0}={1}",
Keys.QRYSTR_CATEGORYID, filterCategoryID);
}
BindList();
}
}
private void BindLocalUI()
{
LinkButton lkbNewLink = Utilities.CreateLinkButton("New Link");
lkbNewLink.Click += lkbNewLink_Click;
lkbNewLink.CausesValidation = false;
AdminMasterPage.AddToActions(lkbNewLink);
HyperLink lnkEditCategories = Utilities.CreateHyperLink(Resources.Label_EditCategories,
string.Format(CultureInfo.InvariantCulture,
"{0}?{1}={2}",
Constants.URL_EDITCATEGORIES,
Keys.QRYSTR_CATEGORYTYPE,
CategoryType.LinkCollection));
AdminMasterPage.AddToActions(lnkEditCategories);
}
private void BindList()
{
Edit.Visible = false;
IPagedCollection<Link> selectionList = Repository.GetPagedLinks(filterCategoryID, _resultsPageNumber,
resultsPager.PageSize, true);
if (selectionList.Count > 0)
{
resultsPager.ItemCount = selectionList.MaxItems;
rprSelectionList.DataSource = selectionList;
rprSelectionList.DataBind();
}
else
{
// TODO: no existing items handling. add label and indicate no existing items. pop open edit.
}
}
private void BindLinkEdit()
{
Link currentLink = Repository.GetLink(LinkID);
rprSelectionList.Visible = false;
headerLiteral.Visible = false;
// ImportExport.Visible = false;
Edit.Visible = true;
lblEntryID.Text = currentLink.Id.ToString(CultureInfo.InvariantCulture);
txbTitle.Text = currentLink.Title;
txbUrl.Text = currentLink.Url;
txbRss.Text = currentLink.Rss;
txtXfn.Text = currentLink.Relation;
ckbIsActive.Checked = currentLink.IsActive;
BindLinkCategories();
ddlCategories.Items.FindByValue(currentLink.CategoryId.ToString(CultureInfo.InvariantCulture)).Selected =
true;
if (AdminMasterPage != null)
{
string title = string.Format(CultureInfo.InvariantCulture, "Editing Link \"{0}\"", currentLink.Title);
AdminMasterPage.Title = title;
}
}
public void BindLinkCategories()
{
ICollection<LinkCategory> selectionList = Repository.GetCategories(CategoryType.LinkCollection, ActiveFilter.None);
if (selectionList != null && selectionList.Count != 0)
{
ddlCategories.DataSource = selectionList;
ddlCategories.DataValueField = "Id";
ddlCategories.DataTextField = "Title";
ddlCategories.DataBind();
}
else
{
Messages.ShowError(Resources.EditLinks_NeedToAddCategoryFirst);
Edit.Visible = false;
}
}
private void UpdateLink()
{
string successMessage = Constants.RES_SUCCESSNEW;
try
{
var link = new Link
{
Title = txbTitle.Text,
Url = txbUrl.Text,
Rss = txbRss.Text,
IsActive = ckbIsActive.Checked,
CategoryId = Convert.ToInt32(ddlCategories.SelectedItem.Value),
Id = Config.CurrentBlog.Id,
Relation = txtXfn.Text
};
if (LinkID > 0)
{
successMessage = Constants.RES_SUCCESSEDIT;
link.Id = LinkID;
Repository.UpdateLink(link);
}
else
{
LinkID = Repository.CreateLink(link);
}
if (LinkID > 0)
{
BindList();
Messages.ShowMessage(successMessage);
}
else
{
Messages.ShowError(Constants.RES_FAILUREEDIT
+ " There was a baseline problem posting your link.");
}
}
catch (Exception ex)
{
Messages.ShowError(String.Format(Constants.RES_EXCEPTION,
Constants.RES_FAILUREEDIT, ex.Message));
}
finally
{
rprSelectionList.Visible = true;
headerLiteral.Visible = true;
}
}
private void ResetPostEdit(bool showEdit)
{
LinkID = NullValue.NullInt32;
rprSelectionList.Visible = !showEdit;
headerLiteral.Visible = !showEdit;
Edit.Visible = showEdit;
lblEntryID.Text = String.Empty;
txbTitle.Text = String.Empty;
txbUrl.Text = String.Empty;
txbRss.Text = String.Empty;
ckbIsActive.Checked = Preferences.AlwaysCreateIsActive;
if (showEdit)
{
BindLinkCategories();
}
ddlCategories.SelectedIndex = -1;
}
private void ConfirmDelete(int linkID, string linkTitle)
{
var command = new DeleteLinkCommand(Repository, linkID, linkTitle)
{
ExecuteSuccessMessage = String.Format(CultureInfo.CurrentCulture, "Link '{0}' deleted", linkTitle)
};
Messages.ShowMessage(command.Execute());
BindList();
}
private void ImportOpml()
{
if (OpmlImportFile.PostedFile.FileName.Trim().Length > 0)
{
OpmlItemCollection importedLinks = OpmlProvider.Import(OpmlImportFile.PostedFile.InputStream);
if (importedLinks.Count > 0)
{
var command = new ImportLinksCommand(Repository, importedLinks,
Int32.Parse(ddlImportExportCategories.SelectedItem.Value));
Messages.ShowMessage(command.Execute());
}
BindList();
}
}
// REFACTOR
public string CheckHiddenStyle()
{
if (_isListHidden)
{
return Constants.CSSSTYLE_HIDDEN;
}
else
{
return String.Empty;
}
}
override protected void OnInit(EventArgs e)
{
rprSelectionList.ItemCommand += new RepeaterCommandEventHandler(rprSelectionList_ItemCommand);
base.OnInit(e);
}
protected void lkbImportOpml_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
ImportOpml();
}
}
private void rprSelectionList_ItemCommand(object source, RepeaterCommandEventArgs e)
{
switch (e.CommandName.ToLower(CultureInfo.InvariantCulture))
{
case "edit":
LinkID = Convert.ToInt32(e.CommandArgument);
BindLinkEdit();
break;
case "delete":
int id = Convert.ToInt32(e.CommandArgument);
Link link = Repository.GetLink(id);
ConfirmDelete(id, link.Title);
break;
default:
break;
}
}
protected void lkbCancel_Click(object sender, EventArgs e)
{
ResetPostEdit(false);
}
protected void lkbPost_Click(object sender, EventArgs e)
{
UpdateLink();
}
private void lkbNewLink_Click(object sender, EventArgs e)
{
ResetPostEdit(true);
}
}
}
| |
using System.Linq;
using FluentNHibernate.MappingModel;
using FluentNHibernate.Testing.DomainModel;
using FluentNHibernate.Testing.DomainModel.Mapping;
using NUnit.Framework;
namespace FluentNHibernate.Testing.FluentInterfaceTests
{
[TestFixture]
public class AnyMutablePropertyModelGenerationTests : BaseModelFixture
{
[Test]
public void AccessSetsModelAccessPropertyToValue()
{
Any<SecondMappedObject>()
.Mapping(m => m
.IdentityType<int>()
.EntityIdentifierColumn("col")
.EntityTypeColumn("col2")
.Access.Field())
.ModelShouldMatch(x => x.Access.ShouldEqual("field"));
}
[Test]
public void CascadeSetsModelCascadePropertyToValue()
{
Any<SecondMappedObject>()
.Mapping(m => m
.IdentityType<int>()
.EntityIdentifierColumn("col")
.EntityTypeColumn("col2")
.Cascade.All())
.ModelShouldMatch(x => x.Cascade.ShouldEqual("all"));
}
[Test]
public void IdentityTypeSetsModelIdTypePropertyToPropertyTypeName()
{
Any<SecondMappedObject>()
.Mapping(m => m
.IdentityType(x => x.Id)
.EntityIdentifierColumn("col")
.EntityTypeColumn("col2"))
.ModelShouldMatch(x => x.IdType.ShouldEqual(typeof(long).AssemblyQualifiedName));
}
[Test]
public void IdentityTypeSetsModelIdTypePropertyToTypeName()
{
Any<SecondMappedObject>()
.Mapping(m => m
.IdentityType<int>()
.EntityIdentifierColumn("col")
.EntityTypeColumn("col2"))
.ModelShouldMatch(x => x.IdType.ShouldEqual(typeof(int).AssemblyQualifiedName));
}
[Test]
public void InsertSetsModelInsertPropertyToTrue()
{
Any<SecondMappedObject>()
.Mapping(m => m
.IdentityType<int>()
.EntityIdentifierColumn("col")
.EntityTypeColumn("col2")
.Insert())
.ModelShouldMatch(x => x.Insert.ShouldBeTrue());
}
[Test]
public void NotInsertSetsModelInsertPropertyToFalse()
{
Any<SecondMappedObject>()
.Mapping(m => m
.IdentityType<int>()
.EntityIdentifierColumn("col")
.EntityTypeColumn("col2")
.Not.Insert())
.ModelShouldMatch(x => x.Insert.ShouldBeFalse());
}
[Test]
public void UpdateSetsModelUpdatePropertyToTrue()
{
Any<SecondMappedObject>()
.Mapping(m => m
.IdentityType<int>()
.EntityIdentifierColumn("col")
.EntityTypeColumn("col2")
.Update())
.ModelShouldMatch(x => x.Update.ShouldBeTrue());
}
[Test]
public void NotUpdateSetsModelUpdatePropertyToFalse()
{
Any<SecondMappedObject>()
.Mapping(m => m
.IdentityType<int>()
.EntityIdentifierColumn("col")
.EntityTypeColumn("col2")
.Not.Update())
.ModelShouldMatch(x => x.Update.ShouldBeFalse());
}
[Test]
public void ReadOnlySetsModelInsertPropertyToFalse()
{
Any<SecondMappedObject>()
.Mapping(m => m
.IdentityType<int>()
.EntityIdentifierColumn("col")
.EntityTypeColumn("col2")
.ReadOnly())
.ModelShouldMatch(x => x.Insert.ShouldBeFalse());
}
[Test]
public void NotReadOnlySetsModelInsertPropertyToTrue()
{
Any<SecondMappedObject>()
.Mapping(m => m
.IdentityType<int>()
.EntityIdentifierColumn("col")
.EntityTypeColumn("col2")
.Not.ReadOnly())
.ModelShouldMatch(x => x.Insert.ShouldBeTrue());
}
[Test]
public void ReadOnlySetsModelUpdatePropertyToFalse()
{
Any<SecondMappedObject>()
.Mapping(m => m
.IdentityType<int>()
.EntityIdentifierColumn("col")
.EntityTypeColumn("col2")
.ReadOnly())
.ModelShouldMatch(x => x.Update.ShouldBeFalse());
}
[Test]
public void NotReadOnlySetsModelUpdatePropertyToTrue()
{
Any<SecondMappedObject>()
.Mapping(m => m
.IdentityType<int>()
.EntityIdentifierColumn("col")
.EntityTypeColumn("col2")
.Not.ReadOnly())
.ModelShouldMatch(x => x.Update.ShouldBeTrue());
}
[Test]
public void LazyLoadSetsModelLazyPropertyToTrue()
{
Any<SecondMappedObject>()
.Mapping(m => m
.IdentityType<int>()
.EntityIdentifierColumn("col")
.EntityTypeColumn("col2")
.LazyLoad())
.ModelShouldMatch(x => x.Lazy.ShouldBeTrue());
}
[Test]
public void NotLazyLoadSetsModelLazyPropertyToFalse()
{
Any<SecondMappedObject>()
.Mapping(m => m
.IdentityType<int>()
.EntityIdentifierColumn("col")
.EntityTypeColumn("col2")
.Not.LazyLoad())
.ModelShouldMatch(x => x.Lazy.ShouldBeFalse());
}
[Test]
public void OptimisticLockSetsModelOptimisticLockPropertyToTrue()
{
Any<SecondMappedObject>()
.Mapping(m => m
.IdentityType<int>()
.EntityIdentifierColumn("col")
.EntityTypeColumn("col2")
.OptimisticLock())
.ModelShouldMatch(x => x.OptimisticLock.ShouldBeTrue());
}
[Test]
public void NotOptimisticLockSetsModelOptimisticLockPropertyToFalse()
{
Any<SecondMappedObject>()
.Mapping(m => m
.IdentityType<int>()
.EntityIdentifierColumn("col")
.EntityTypeColumn("col2")
.Not.OptimisticLock())
.ModelShouldMatch(x => x.OptimisticLock.ShouldBeFalse());
}
[Test]
public void MetaTypePropertyShouldBeSetToPropertyTypeIfNoMetaValuesSet()
{
Any<SecondMappedObject>()
.Mapping(m => m
.IdentityType<int>()
.EntityIdentifierColumn("col")
.EntityTypeColumn("col2"))
.ModelShouldMatch(x => x.MetaType.ShouldEqual(new TypeReference(typeof(SecondMappedObject))));
}
[Test]
public void MetaTypePropertyShouldBeSetToStringIfMetaValuesSet()
{
Any<SecondMappedObject>()
.Mapping(m => m
.IdentityType<int>()
.EntityIdentifierColumn("col")
.EntityTypeColumn("col2")
.AddMetaValue<Record>("Rec"))
.ModelShouldMatch(x => x.MetaType.ShouldEqual(new TypeReference(typeof(string))));
}
[Test]
public void NamePropertyShouldBeSetToPropertyName()
{
Any<SecondMappedObject>()
.Mapping(m => m
.IdentityType<int>()
.EntityIdentifierColumn("col")
.EntityTypeColumn("col2"))
.ModelShouldMatch(x => x.Name.ShouldEqual("Parent"));
}
[Test]
public void EntityIdentifierColumnShouldAddToModelColumnsCollection()
{
Any<SecondMappedObject>()
.Mapping(m => m
.IdentityType<int>()
.EntityIdentifierColumn("col")
.EntityTypeColumn("col2"))
.ModelShouldMatch(x => x.IdentifierColumns.Count().ShouldEqual(1));
}
[Test]
public void EntityTypeColumnShouldAddToModelColumnsCollection()
{
Any<SecondMappedObject>()
.Mapping(m => m
.IdentityType<int>()
.EntityIdentifierColumn("col")
.EntityTypeColumn("col2"))
.ModelShouldMatch(x => x.TypeColumns.Count().ShouldEqual(1));
}
[Test]
public void AddMetaValueShouldAddToModelMetaValuesCollection()
{
Any<SecondMappedObject>()
.Mapping(m => m
.IdentityType<int>()
.EntityIdentifierColumn("col")
.EntityTypeColumn("col2")
.AddMetaValue<Record>("Rec"))
.ModelShouldMatch(x => x.MetaValues.Count().ShouldEqual(1));
}
}
}
| |
/*
* 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 copyrightD
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using OpenSim.Framework;
using OpenSim.Region.PhysicsModules.SharedBase;
using OMV = OpenMetaverse;
namespace OpenSim.Region.PhysicsModule.BulletS
{
public class BSActorAvatarMove : BSActor
{
BSVMotor m_velocityMotor;
// Set to true if we think we're going up stairs.
// This state is remembered because collisions will turn on and off as we go up stairs.
int m_walkingUpStairs;
// The amount the step up is applying. Used to smooth stair walking.
float m_lastStepUp;
// There are times the velocity is set but we don't want to inforce stationary until the
// real velocity drops.
bool m_waitingForLowVelocityForStationary = false;
public BSActorAvatarMove(BSScene physicsScene, BSPhysObject pObj, string actorName)
: base(physicsScene, pObj, actorName)
{
m_velocityMotor = null;
m_walkingUpStairs = 0;
m_physicsScene.DetailLog("{0},BSActorAvatarMove,constructor", m_controllingPrim.LocalID);
}
// BSActor.isActive
public override bool isActive
{
get { return Enabled && m_controllingPrim.IsPhysicallyActive; }
}
// Release any connections and resources used by the actor.
// BSActor.Dispose()
public override void Dispose()
{
base.SetEnabled(false);
DeactivateAvatarMove();
}
// Called when physical parameters (properties set in Bullet) need to be re-applied.
// Called at taint-time.
// BSActor.Refresh()
public override void Refresh()
{
m_physicsScene.DetailLog("{0},BSActorAvatarMove,refresh", m_controllingPrim.LocalID);
// If the object is physically active, add the hoverer prestep action
if (isActive)
{
ActivateAvatarMove();
}
else
{
DeactivateAvatarMove();
}
}
// The object's physical representation is being rebuilt so pick up any physical dependencies (constraints, ...).
// Register a prestep action to restore physical requirements before the next simulation step.
// Called at taint-time.
// BSActor.RemoveDependencies()
public override void RemoveDependencies()
{
// Nothing to do for the hoverer since it is all software at pre-step action time.
}
// Usually called when target velocity changes to set the current velocity and the target
// into the movement motor.
public void SetVelocityAndTarget(OMV.Vector3 vel, OMV.Vector3 targ, bool inTaintTime)
{
m_physicsScene.TaintedObject(inTaintTime, m_controllingPrim.LocalID, "BSActorAvatarMove.setVelocityAndTarget", delegate()
{
if (m_velocityMotor != null)
{
m_velocityMotor.Reset();
m_velocityMotor.SetTarget(targ);
m_velocityMotor.SetCurrent(vel);
m_velocityMotor.Enabled = true;
m_physicsScene.DetailLog("{0},BSCharacter.MoveMotor,SetVelocityAndTarget,vel={1}, targ={2}",
m_controllingPrim.LocalID, vel, targ);
m_waitingForLowVelocityForStationary = false;
}
});
}
public void SuppressStationayCheckUntilLowVelocity()
{
m_waitingForLowVelocityForStationary = true;
}
// If a movement motor has not been created, create one and start the movement
private void ActivateAvatarMove()
{
if (m_velocityMotor == null)
{
// Infinite decay and timescale values so motor only changes current to target values.
m_velocityMotor = new BSVMotor("BSCharacter.Velocity",
0.2f, // time scale
BSMotor.Infinite, // decay time scale
1f // efficiency
);
m_velocityMotor.ErrorZeroThreshold = BSParam.AvatarStopZeroThreshold;
// m_velocityMotor.PhysicsScene = m_controllingPrim.PhysScene; // DEBUG DEBUG so motor will output detail log messages.
SetVelocityAndTarget(m_controllingPrim.RawVelocity, m_controllingPrim.TargetVelocity, true /* inTaintTime */);
m_physicsScene.BeforeStep += Mover;
m_controllingPrim.OnPreUpdateProperty += Process_OnPreUpdateProperty;
m_walkingUpStairs = 0;
m_waitingForLowVelocityForStationary = false;
}
}
private void DeactivateAvatarMove()
{
if (m_velocityMotor != null)
{
m_controllingPrim.OnPreUpdateProperty -= Process_OnPreUpdateProperty;
m_physicsScene.BeforeStep -= Mover;
m_velocityMotor = null;
}
}
// Called just before the simulation step.
private void Mover(float timeStep)
{
// Don't do movement while the object is selected.
if (!isActive)
return;
// TODO: Decide if the step parameters should be changed depending on the avatar's
// state (flying, colliding, ...). There is code in ODE to do this.
// COMMENTARY: when the user is making the avatar walk, except for falling, the velocity
// specified for the avatar is the one that should be used. For falling, if the avatar
// is not flying and is not colliding then it is presumed to be falling and the Z
// component is not fooled with (thus allowing gravity to do its thing).
// When the avatar is standing, though, the user has specified a velocity of zero and
// the avatar should be standing. But if the avatar is pushed by something in the world
// (raising elevator platform, moving vehicle, ...) the avatar should be allowed to
// move. Thus, the velocity cannot be forced to zero. The problem is that small velocity
// errors can creap in and the avatar will slowly float off in some direction.
// So, the problem is that, when an avatar is standing, we cannot tell creaping error
// from real pushing.
// The code below uses whether the collider is static or moving to decide whether to zero motion.
m_velocityMotor.Step(timeStep);
m_controllingPrim.IsStationary = false;
// If we're not supposed to be moving, make sure things are zero.
if (m_velocityMotor.ErrorIsZero() && m_velocityMotor.TargetValue == OMV.Vector3.Zero)
{
// The avatar shouldn't be moving
m_velocityMotor.Zero();
if (m_controllingPrim.IsColliding)
{
// if colliding with something stationary and we're not doing volume detect .
if (!m_controllingPrim.ColliderIsMoving && !m_controllingPrim.ColliderIsVolumeDetect)
{
if (m_waitingForLowVelocityForStationary)
{
// if waiting for velocity to drop and it has finally dropped, we can be stationary
if (m_controllingPrim.RawVelocity.LengthSquared() < BSParam.AvatarStopZeroThresholdSquared)
{
m_waitingForLowVelocityForStationary = false;
}
}
if (!m_waitingForLowVelocityForStationary)
{
m_physicsScene.DetailLog("{0},BSCharacter.MoveMotor,collidingWithStationary,zeroingMotion", m_controllingPrim.LocalID);
m_controllingPrim.IsStationary = true;
m_controllingPrim.ZeroMotion(true /* inTaintTime */);
}
else
{
m_physicsScene.DetailLog("{0},BSCharacter.MoveMotor,waitingForLowVel,rawvel={1}",
m_controllingPrim.LocalID, m_controllingPrim.RawVelocity.Length());
}
}
// Standing has more friction on the ground
if (m_controllingPrim.Friction != BSParam.AvatarStandingFriction)
{
m_controllingPrim.Friction = BSParam.AvatarStandingFriction;
m_physicsScene.PE.SetFriction(m_controllingPrim.PhysBody, m_controllingPrim.Friction);
}
}
else
{
if (m_controllingPrim.Flying)
{
// Flying and not colliding and velocity nearly zero.
m_controllingPrim.ZeroMotion(true /* inTaintTime */);
}
else
{
//We are falling but are not touching any keys make sure not falling too fast
if (m_controllingPrim.RawVelocity.Z < BSParam.AvatarTerminalVelocity)
{
OMV.Vector3 slowingForce = new OMV.Vector3(0f, 0f, BSParam.AvatarTerminalVelocity - m_controllingPrim.RawVelocity.Z) * m_controllingPrim.Mass;
m_physicsScene.PE.ApplyCentralImpulse(m_controllingPrim.PhysBody, slowingForce);
}
}
}
m_physicsScene.DetailLog("{0},BSCharacter.MoveMotor,taint,stopping,target={1},colliding={2},isStationary={3}",
m_controllingPrim.LocalID, m_velocityMotor.TargetValue, m_controllingPrim.IsColliding,m_controllingPrim.IsStationary);
}
else
{
// Supposed to be moving.
OMV.Vector3 stepVelocity = m_velocityMotor.CurrentValue;
if (m_controllingPrim.Friction != BSParam.AvatarFriction)
{
// Probably starting to walk. Set friction to moving friction.
m_controllingPrim.Friction = BSParam.AvatarFriction;
m_physicsScene.PE.SetFriction(m_controllingPrim.PhysBody, m_controllingPrim.Friction);
}
// 'm_velocityMotor is used for walking, flying, and jumping and will thus have the correct values
// for Z. But in come cases it must be over-ridden. Like when falling or jumping.
float realVelocityZ = m_controllingPrim.RawVelocity.Z;
// If not flying and falling, we over-ride the stepping motor so we can fall to the ground
if (!m_controllingPrim.Flying && realVelocityZ < 0)
{
// Can't fall faster than this
if (realVelocityZ < BSParam.AvatarTerminalVelocity)
{
realVelocityZ = BSParam.AvatarTerminalVelocity;
}
stepVelocity.Z = realVelocityZ;
}
// m_physicsScene.DetailLog("{0},BSCharacter.MoveMotor,DEBUG,motorCurrent={1},realZ={2},flying={3},collid={4},jFrames={5}",
// m_controllingPrim.LocalID, m_velocityMotor.CurrentValue, realVelocityZ, m_controllingPrim.Flying, m_controllingPrim.IsColliding, m_jumpFrames);
//Alicia: Maintain minimum height when flying.
// SL has a flying effect that keeps the avatar flying above the ground by some margin
if (m_controllingPrim.Flying)
{
float hover_height = m_physicsScene.TerrainManager.GetTerrainHeightAtXYZ(m_controllingPrim.RawPosition)
+ BSParam.AvatarFlyingGroundMargin;
if( m_controllingPrim.Position.Z < hover_height)
{
m_physicsScene.DetailLog("{0},BSCharacter.MoveMotor,addingUpforceForGroundMargin,height={1},hoverHeight={2}",
m_controllingPrim.LocalID, m_controllingPrim.Position.Z, hover_height);
stepVelocity.Z += BSParam.AvatarFlyingGroundUpForce;
}
}
// 'stepVelocity' is now the speed we'd like the avatar to move in. Turn that into an instantanous force.
OMV.Vector3 moveForce = (stepVelocity - m_controllingPrim.RawVelocity) * m_controllingPrim.Mass;
// Add special movement force to allow avatars to walk up stepped surfaces.
moveForce += WalkUpStairs();
m_physicsScene.DetailLog("{0},BSCharacter.MoveMotor,move,stepVel={1},vel={2},mass={3},moveForce={4}",
m_controllingPrim.LocalID, stepVelocity, m_controllingPrim.RawVelocity, m_controllingPrim.Mass, moveForce);
m_physicsScene.PE.ApplyCentralImpulse(m_controllingPrim.PhysBody, moveForce);
}
}
// Called just as the property update is received from the physics engine.
// Do any mode necessary for avatar movement.
private void Process_OnPreUpdateProperty(ref EntityProperties entprop)
{
// Don't change position if standing on a stationary object.
if (m_controllingPrim.IsStationary)
{
entprop.Position = m_controllingPrim.RawPosition;
entprop.Velocity = OMV.Vector3.Zero;
m_physicsScene.PE.SetTranslation(m_controllingPrim.PhysBody, entprop.Position, entprop.Rotation);
}
}
// Decide if the character is colliding with a low object and compute a force to pop the
// avatar up so it can walk up and over the low objects.
private OMV.Vector3 WalkUpStairs()
{
OMV.Vector3 ret = OMV.Vector3.Zero;
m_physicsScene.DetailLog("{0},BSCharacter.WalkUpStairs,IsColliding={1},flying={2},targSpeed={3},collisions={4},avHeight={5}",
m_controllingPrim.LocalID, m_controllingPrim.IsColliding, m_controllingPrim.Flying,
m_controllingPrim.TargetVelocitySpeed, m_controllingPrim.CollisionsLastTick.Count, m_controllingPrim.Size.Z);
// Check for stairs climbing if colliding, not flying and moving forward
if ( m_controllingPrim.IsColliding
&& !m_controllingPrim.Flying
&& m_controllingPrim.TargetVelocitySpeed > 0.1f )
{
// The range near the character's feet where we will consider stairs
// float nearFeetHeightMin = m_controllingPrim.RawPosition.Z - (m_controllingPrim.Size.Z / 2f) + 0.05f;
// Note: there is a problem with the computation of the capsule height. Thus RawPosition is off
// from the height. Revisit size and this computation when height is scaled properly.
float nearFeetHeightMin = m_controllingPrim.RawPosition.Z - (m_controllingPrim.Size.Z / 2f) - BSParam.AvatarStepGroundFudge;
float nearFeetHeightMax = nearFeetHeightMin + BSParam.AvatarStepHeight;
// Look for a collision point that is near the character's feet and is oriented the same as the charactor is.
// Find the highest 'good' collision.
OMV.Vector3 highestTouchPosition = OMV.Vector3.Zero;
foreach (KeyValuePair<uint, ContactPoint> kvp in m_controllingPrim.CollisionsLastTick.m_objCollisionList)
{
// Don't care about collisions with the terrain
if (kvp.Key > m_physicsScene.TerrainManager.HighestTerrainID)
{
BSPhysObject collisionObject;
if (m_physicsScene.PhysObjects.TryGetValue(kvp.Key, out collisionObject))
{
if (!collisionObject.IsVolumeDetect)
{
OMV.Vector3 touchPosition = kvp.Value.Position;
m_physicsScene.DetailLog("{0},BSCharacter.WalkUpStairs,min={1},max={2},touch={3}",
m_controllingPrim.LocalID, nearFeetHeightMin, nearFeetHeightMax, touchPosition);
if (touchPosition.Z >= nearFeetHeightMin && touchPosition.Z <= nearFeetHeightMax)
{
// This contact is within the 'near the feet' range.
// The step is presumed to be more or less vertical. Thus the Z component should
// be nearly horizontal.
OMV.Vector3 directionFacing = OMV.Vector3.UnitX * m_controllingPrim.RawOrientation;
OMV.Vector3 touchNormal = OMV.Vector3.Normalize(kvp.Value.SurfaceNormal);
const float PIOver2 = 1.571f; // Used to make unit vector axis into approx radian angles
// m_physicsScene.DetailLog("{0},BSCharacter.WalkUpStairs,avNormal={1},colNormal={2},diff={3}",
// m_controllingPrim.LocalID, directionFacing, touchNormal,
// Math.Abs(OMV.Vector3.Distance(directionFacing, touchNormal)) );
if ((Math.Abs(directionFacing.Z) * PIOver2) < BSParam.AvatarStepAngle
&& (Math.Abs(touchNormal.Z) * PIOver2) < BSParam.AvatarStepAngle)
{
// The normal should be our contact point to the object so it is pointing away
// thus the difference between our facing orientation and the normal should be small.
float diff = Math.Abs(OMV.Vector3.Distance(directionFacing, touchNormal));
if (diff < BSParam.AvatarStepApproachFactor)
{
if (highestTouchPosition.Z < touchPosition.Z)
highestTouchPosition = touchPosition;
}
}
}
}
}
}
}
m_walkingUpStairs = 0;
// If there is a good step sensing, move the avatar over the step.
if (highestTouchPosition != OMV.Vector3.Zero)
{
// Remember that we are going up stairs. This is needed because collisions
// will stop when we move up so this smoothes out that effect.
m_walkingUpStairs = BSParam.AvatarStepSmoothingSteps;
m_lastStepUp = highestTouchPosition.Z - nearFeetHeightMin;
ret = ComputeStairCorrection(m_lastStepUp);
m_physicsScene.DetailLog("{0},BSCharacter.WalkUpStairs,touchPos={1},nearFeetMin={2},ret={3}",
m_controllingPrim.LocalID, highestTouchPosition, nearFeetHeightMin, ret);
}
}
else
{
// If we used to be going up stairs but are not now, smooth the case where collision goes away while
// we are bouncing up the stairs.
if (m_walkingUpStairs > 0)
{
m_walkingUpStairs--;
ret = ComputeStairCorrection(m_lastStepUp);
}
}
return ret;
}
private OMV.Vector3 ComputeStairCorrection(float stepUp)
{
OMV.Vector3 ret = OMV.Vector3.Zero;
OMV.Vector3 displacement = OMV.Vector3.Zero;
if (stepUp > 0f)
{
// Found the stairs contact point. Push up a little to raise the character.
if (BSParam.AvatarStepForceFactor > 0f)
{
float upForce = stepUp * m_controllingPrim.Mass * BSParam.AvatarStepForceFactor;
ret = new OMV.Vector3(0f, 0f, upForce);
}
// Also move the avatar up for the new height
if (BSParam.AvatarStepUpCorrectionFactor > 0f)
{
// Move the avatar up related to the height of the collision
displacement = new OMV.Vector3(0f, 0f, stepUp * BSParam.AvatarStepUpCorrectionFactor);
m_controllingPrim.ForcePosition = m_controllingPrim.RawPosition + displacement;
}
else
{
if (BSParam.AvatarStepUpCorrectionFactor < 0f)
{
// Move the avatar up about the specified step height
displacement = new OMV.Vector3(0f, 0f, BSParam.AvatarStepHeight);
m_controllingPrim.ForcePosition = m_controllingPrim.RawPosition + displacement;
}
}
m_physicsScene.DetailLog("{0},BSCharacter.WalkUpStairs.ComputeStairCorrection,stepUp={1},isp={2},force={3}",
m_controllingPrim.LocalID, stepUp, displacement, ret);
}
return ret;
}
}
}
| |
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
namespace Microsoft.Zelig.Runtime
{
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using TS = Microsoft.Zelig.Runtime.TypeSystem;
[ImplicitInstance]
[ForceDevirtualization]
public abstract class TypeSystemManager
{
class EmptyManager : TypeSystemManager
{
[NoInline]
public override Object AllocateObject(TS.VTable vTable)
{
return null;
}
[NoInline]
public override Object AllocateReferenceCountingObject(TS.VTable vTable)
{
return null;
}
[NoInline]
public override Object AllocateObjectWithExtensions(TS.VTable vTable)
{
return null;
}
[NoInline]
public override Array AllocateArray(TS.VTable vTable,
uint length)
{
return null;
}
[NoInline]
public override Array AllocateReferenceCountingArray(TS.VTable vTable,
uint length)
{
return null;
}
[NoInline]
public override Array AllocateArrayNoClear(TS.VTable vTable,
uint length)
{
return null;
}
[NoInline]
public override String AllocateString(TS.VTable vTable,
int length)
{
return null;
}
[NoInline]
public override String AllocateReferenceCountingString(TS.VTable vTable,
int length)
{
return null;
}
}
//
// Helper Methods
//
public virtual void InitializeTypeSystemManager()
{
InvokeStaticConstructors();
}
[Inline]
[TS.DisableAutomaticReferenceCounting]
public object InitializeObject( UIntPtr memory,
TS.VTable vTable,
bool referenceCounting)
{
ObjectHeader oh = ObjectHeader.CastAsObjectHeader(memory);
oh.VirtualTable = vTable;
if (referenceCounting)
{
oh.MultiUseWord = (int)((1 << ObjectHeader.ReferenceCountShift) | (int)ObjectHeader.GarbageCollectorFlags.NormalObject | (int)ObjectHeader.GarbageCollectorFlags.Unmarked);
#if REFCOUNT_STAT
ObjectHeader.s_RefCountedObjectsAllocated++;
#endif
#if DEBUG_REFCOUNT
BugCheck.Log( "InitRC (0x%x), new count = 1 +", (int)oh.ToPointer( ) );
#endif
}
else
{
oh.MultiUseWord = (int)(ObjectHeader.GarbageCollectorFlags.NormalObject | ObjectHeader.GarbageCollectorFlags.Unmarked);
}
return oh.Pack();
}
[Inline]
[TS.DisableAutomaticReferenceCounting]
public object InitializeObjectWithExtensions(UIntPtr memory,
TS.VTable vTable)
{
ObjectHeader oh = ObjectHeader.CastAsObjectHeader(memory);
oh.VirtualTable = vTable;
oh.MultiUseWord = (int)(ObjectHeader.GarbageCollectorFlags.SpecialHandlerObject | ObjectHeader.GarbageCollectorFlags.Unmarked);
return oh.Pack();
}
[Inline]
[TS.DisableAutomaticReferenceCounting]
public Array InitializeArray( UIntPtr memory,
TS.VTable vTable,
uint length,
bool referenceCounting)
{
object obj = InitializeObject(memory, vTable, referenceCounting);
ArrayImpl array = ArrayImpl.CastAsArray(obj);
array.m_numElements = length;
return array.CastThisAsArray();
}
[Inline]
[TS.DisableAutomaticReferenceCounting]
public String InitializeString(UIntPtr memory,
TS.VTable vTable,
int length,
bool referenceCounting)
{
object obj = InitializeObject(memory, vTable, referenceCounting);
StringImpl str = StringImpl.CastAsString(obj);
str.m_arrayLength = length;
return str.CastThisAsString();
}
[TS.WellKnownMethod("TypeSystemManager_AllocateObject")]
[TS.DisableAutomaticReferenceCounting]
public abstract Object AllocateObject(TS.VTable vTable);
[TS.WellKnownMethod("TypeSystemManager_AllocateReferenceCountingObject")]
[TS.DisableAutomaticReferenceCounting]
public abstract Object AllocateReferenceCountingObject(TS.VTable vTable);
[TS.WellKnownMethod("TypeSystemManager_AllocateObjectWithExtensions")]
[TS.DisableAutomaticReferenceCounting]
public abstract Object AllocateObjectWithExtensions(TS.VTable vTable);
[TS.WellKnownMethod("TypeSystemManager_AllocateArray")]
[TS.DisableAutomaticReferenceCounting]
public abstract Array AllocateArray(TS.VTable vTable, uint length);
[TS.WellKnownMethod("TypeSystemManager_AllocateReferenceCountingArray")]
[TS.DisableAutomaticReferenceCounting]
public abstract Array AllocateReferenceCountingArray(TS.VTable vTable, uint length);
[TS.WellKnownMethod("TypeSystemManager_AllocateArrayNoClear")]
[TS.DisableAutomaticReferenceCounting]
public abstract Array AllocateArrayNoClear(TS.VTable vTable, uint length);
[TS.WellKnownMethod("TypeSystemManager_AllocateString")]
[TS.DisableAutomaticReferenceCounting]
public abstract String AllocateString(TS.VTable vTable, int length);
[TS.DisableAutomaticReferenceCounting]
public abstract String AllocateReferenceCountingString(TS.VTable vTable, int length);
//--//
[Inline]
public static T AtomicAllocator<T>(ref T obj) where T : class, new()
{
if (obj == null)
{
return AtomicAllocatorSlow(ref obj);
}
return obj;
}
[NoInline]
private static T AtomicAllocatorSlow<T>(ref T obj) where T : class, new()
{
T newObj = new T();
System.Threading.Interlocked.CompareExchange(ref obj, newObj, default(T));
return obj;
}
//--//
public static System.Reflection.MethodInfo CodePointerToMethodInfo(TS.CodePointer ptr)
{
throw new NotImplementedException();
}
//--//
[NoInline]
[TS.WellKnownMethod("TypeSystemManager_InvokeStaticConstructors")]
private void InvokeStaticConstructors()
{
//
// WARNING!
// WARNING! Keep this method empty!!!!
// WARNING!
//
// We need a way to inject calls to the static constructors that are reachable.
// This is the empty vessel for those calls.
//
// WARNING!
// WARNING! Keep this method empty!!!!
// WARNING!
//
}
[TS.WellKnownMethod("TypeSystemManager_CastToType")]
public static object CastToType(object obj, TS.VTable expected)
{
if (obj != null)
{
obj = CastToTypeNoThrow(obj, expected);
if (obj == null)
{
throw new InvalidCastException();
}
}
return obj;
}
[TS.WellKnownMethod("TypeSystemManager_CastToTypeNoThrow")]
public static object CastToTypeNoThrow(object obj, TS.VTable expected)
{
if (obj != null)
{
TS.VTable got = TS.VTable.Get(obj);
if (expected.CanBeAssignedFrom(got) == false)
{
return null;
}
}
return obj;
}
//--//
[TS.WellKnownMethod("TypeSystemManager_CastToSealedType")]
public static object CastToSealedType(object obj, TS.VTable expected)
{
if (obj != null)
{
obj = CastToSealedTypeNoThrow(obj, expected);
if (obj == null)
{
throw new InvalidCastException();
}
}
return obj;
}
[TS.WellKnownMethod("TypeSystemManager_CastToSealedTypeNoThrow")]
public static object CastToSealedTypeNoThrow(object obj, TS.VTable expected)
{
if (obj != null)
{
TS.VTable got = TS.VTable.Get(obj);
if (got != expected)
{
return null;
}
}
return obj;
}
//--//
[TS.WellKnownMethod("TypeSystemManager_CastToInterface")]
public static object CastToInterface(object obj, TS.VTable expected)
{
if (obj != null)
{
obj = CastToInterfaceNoThrow(obj, expected);
if (obj == null)
{
throw new InvalidCastException();
}
}
return obj;
}
[TS.WellKnownMethod("TypeSystemManager_CastToInterfaceNoThrow")]
public static object CastToInterfaceNoThrow(object obj, TS.VTable expected)
{
if (obj != null)
{
TS.VTable got = TS.VTable.Get(obj);
if (got.ImplementsInterface(expected))
{
return obj;
}
}
return null;
}
//--//
[NoReturn]
[NoInline]
[TS.WellKnownMethod("TypeSystemManager_Throw")]
public virtual void Throw(Exception obj)
{
ThreadImpl.CurrentThread.CurrentException = obj;
UIntPtr exception = Unwind.LLOS_AllocateException(obj, Unwind.ExceptionClass);
Unwind.LLOS_Unwind_RaiseException(exception);
}
[NoReturn]
[NoInline]
[TS.WellKnownMethod("TypeSystemManager_Rethrow")]
public virtual void Rethrow()
{
MemoryManager.Instance.DumpMemory( );
Throw(ThreadImpl.CurrentThread.CurrentException);
}
//
// Access Methods
//
public static extern TypeSystemManager Instance
{
[TS.WellKnownMethod("TypeSystemManager_get_Instance")]
[SingletonFactory(Fallback = typeof(EmptyManager))]
[MethodImpl(MethodImplOptions.InternalCall)]
get;
}
}
}
| |
/**************************************************************************\
Copyright Microsoft Corporation. All Rights Reserved.
\**************************************************************************/
// This file contains general utilities to aid in development.
// Classes here generally shouldn't be exposed publicly since
// they're not particular to any library functionality.
// Because the classes here are internal, it's likely this file
// might be included in multiple assemblies.
namespace Standard
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Cryptography;
using System.Text;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
internal static partial class Utility
{
private static readonly Version _osVersion = Environment.OSVersion.Version;
private static readonly Version _presentationFrameworkVersion = Assembly.GetAssembly(typeof(Window)).GetName().Version;
/// <summary>Convert a native integer that represent a color with an alpha channel into a Color struct.</summary>
/// <param name="color">The integer that represents the color. Its bits are of the format 0xAARRGGBB.</param>
/// <returns>A Color representation of the parameter.</returns>
public static Color ColorFromArgbDword(uint color)
{
return Color.FromArgb(
(byte)((color & 0xFF000000) >> 24),
(byte)((color & 0x00FF0000) >> 16),
(byte)((color & 0x0000FF00) >> 8),
(byte)((color & 0x000000FF) >> 0));
}
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
public static int GET_X_LPARAM(IntPtr lParam)
{
return LOWORD(lParam.ToInt32());
}
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
public static int GET_Y_LPARAM(IntPtr lParam)
{
return HIWORD(lParam.ToInt32());
}
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
public static int HIWORD(int i)
{
return (short)(i >> 16);
}
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
public static int LOWORD(int i)
{
return (short)(i & 0xFFFF);
}
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
public static bool IsFlagSet(int value, int mask)
{
return 0 != (value & mask);
}
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
public static bool IsFlagSet(uint value, uint mask)
{
return 0 != (value & mask);
}
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
public static bool IsFlagSet(long value, long mask)
{
return 0 != (value & mask);
}
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
public static bool IsFlagSet(ulong value, ulong mask)
{
return 0 != (value & mask);
}
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
public static bool IsOSVistaOrNewer
{
get { return _osVersion >= new Version(6, 0); }
}
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
public static bool IsOSWindows7OrNewer
{
get { return _osVersion >= new Version(6, 1); }
}
/// <summary>
/// Is this using WPF4?
/// </summary>
/// <remarks>
/// There are a few specific bugs in Window in 3.5SP1 and below that require workarounds
/// when handling WM_NCCALCSIZE on the HWND.
/// </remarks>
public static bool IsPresentationFrameworkVersionLessThan4
{
get { return _presentationFrameworkVersion < new Version(4, 0); }
}
public static BitmapFrame GetBestMatch(IList<BitmapFrame> frames, int width, int height)
{
return _GetBestMatch(frames, _GetBitDepth(), width, height);
}
private static int _MatchImage(BitmapFrame frame, int bitDepth, int width, int height, int bpp)
{
int score = 2 * _WeightedAbs(bpp, bitDepth, false) +
_WeightedAbs(frame.PixelWidth, width, true) +
_WeightedAbs(frame.PixelHeight, height, true);
return score;
}
private static int _WeightedAbs(int valueHave, int valueWant, bool fPunish)
{
int diff = (valueHave - valueWant);
if (diff < 0)
{
diff = (fPunish ? -2 : -1) * diff;
}
return diff;
}
/// From a list of BitmapFrames find the one that best matches the requested dimensions.
/// The methods used here are copied from Win32 sources. We want to be consistent with
/// system behaviors.
private static BitmapFrame _GetBestMatch(IList<BitmapFrame> frames, int bitDepth, int width, int height)
{
int bestScore = int.MaxValue;
int bestBpp = 0;
int bestIndex = 0;
bool isBitmapIconDecoder = frames[0].Decoder is IconBitmapDecoder;
for (int i = 0; i < frames.Count && bestScore != 0; ++i)
{
int currentIconBitDepth = isBitmapIconDecoder ? frames[i].Thumbnail.Format.BitsPerPixel : frames[i].Format.BitsPerPixel;
if (currentIconBitDepth == 0)
{
currentIconBitDepth = 8;
}
int score = _MatchImage(frames[i], bitDepth, width, height, currentIconBitDepth);
if (score < bestScore)
{
bestIndex = i;
bestBpp = currentIconBitDepth;
bestScore = score;
}
else if (score == bestScore)
{
// Tie breaker: choose the higher color depth. If that fails, choose first one.
if (bestBpp < currentIconBitDepth)
{
bestIndex = i;
bestBpp = currentIconBitDepth;
}
}
}
return frames[bestIndex];
}
// This can be cached. It's not going to change under reasonable circumstances.
private static int s_bitDepth; // = 0;
/// <SecurityNote>
/// Critical : Calls critical methods to obtain desktop bits per pixel
/// Safe : BPP is considered safe information in partial trust
/// </SecurityNote>
[SecuritySafeCritical]
private static int _GetBitDepth()
{
if (s_bitDepth == 0)
{
using (SafeDC dc = SafeDC.GetDesktop())
{
s_bitDepth = NativeMethods.GetDeviceCaps(dc, DeviceCap.BITSPIXEL) * NativeMethods.GetDeviceCaps(dc, DeviceCap.PLANES);
}
}
return s_bitDepth;
}
/// <summary>GDI's DeleteObject</summary>
/// <SecurityNote>
/// Critical : Calls critical methods
/// <SecurityNote>
[SecurityCritical]
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
public static void SafeDeleteObject(ref IntPtr gdiObject)
{
IntPtr p = gdiObject;
gdiObject = IntPtr.Zero;
if (IntPtr.Zero != p)
{
NativeMethods.DeleteObject(p);
}
}
/// <SecurityNote>
/// Critical : Calls critical methods
/// <SecurityNote>
[SecurityCritical]
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
public static void SafeDestroyWindow(ref IntPtr hwnd)
{
IntPtr p = hwnd;
hwnd = IntPtr.Zero;
if (NativeMethods.IsWindow(p))
{
NativeMethods.DestroyWindow(p);
}
}
/// <SecurityNote>
/// Critical : Calls critical methods
/// <SecurityNote>
[SecurityCritical]
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands")]
public static void SafeRelease<T>(ref T comObject) where T : class
{
T t = comObject;
comObject = default(T);
if (null != t)
{
Assert.IsTrue(Marshal.IsComObject(t));
Marshal.ReleaseComObject(t);
}
}
public static void AddDependencyPropertyChangeListener(object component, DependencyProperty property, EventHandler listener)
{
if (component == null)
{
return;
}
Assert.IsNotNull(property);
Assert.IsNotNull(listener);
DependencyPropertyDescriptor dpd = DependencyPropertyDescriptor.FromProperty(property, component.GetType());
dpd.AddValueChanged(component, listener);
}
public static void RemoveDependencyPropertyChangeListener(object component, DependencyProperty property, EventHandler listener)
{
if (component == null)
{
return;
}
Assert.IsNotNull(property);
Assert.IsNotNull(listener);
DependencyPropertyDescriptor dpd = DependencyPropertyDescriptor.FromProperty(property, component.GetType());
dpd.RemoveValueChanged(component, listener);
}
#region Extension Methods
public static bool IsThicknessNonNegative(Thickness thickness)
{
if (!IsDoubleFiniteAndNonNegative(thickness.Top))
{
return false;
}
if (!IsDoubleFiniteAndNonNegative(thickness.Left))
{
return false;
}
if (!IsDoubleFiniteAndNonNegative(thickness.Bottom))
{
return false;
}
if (!IsDoubleFiniteAndNonNegative(thickness.Right))
{
return false;
}
return true;
}
public static bool IsCornerRadiusValid(CornerRadius cornerRadius)
{
if (!IsDoubleFiniteAndNonNegative(cornerRadius.TopLeft))
{
return false;
}
if (!IsDoubleFiniteAndNonNegative(cornerRadius.TopRight))
{
return false;
}
if (!IsDoubleFiniteAndNonNegative(cornerRadius.BottomLeft))
{
return false;
}
if (!IsDoubleFiniteAndNonNegative(cornerRadius.BottomRight))
{
return false;
}
return true;
}
public static bool IsDoubleFiniteAndNonNegative(double d)
{
if (double.IsNaN(d) || double.IsInfinity(d) || d < 0)
{
return false;
}
return true;
}
#endregion
}
}
| |
//
// DapSource.cs
//
// Author:
// Gabriel Burt <gburt@novell.com>
// Aaron Bockover <abockover@novell.com>
//
// Copyright (C) 2008 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Linq;
using System.IO;
using System.Collections.Generic;
using System.Threading;
using Mono.Unix;
using Hyena;
using Hyena.Data.Sqlite;
using Banshee.Base;
using Banshee.ServiceStack;
using Banshee.Sources;
using Banshee.Collection;
using Banshee.Playlist;
using Banshee.Collection.Database;
using Banshee.Hardware;
using Banshee.MediaEngine;
using Banshee.MediaProfiles;
using Banshee.Preferences;
using Banshee.Dap.Gui;
namespace Banshee.Dap
{
public abstract class DapSource : RemovableSource, IDisposable
{
private DapSync sync;
private DapInfoBar dap_info_bar;
private Page page;
// private DapPropertiesDisplay dap_properties_display;
private IDevice device;
internal IDevice Device {
get { return device; }
}
private string addin_id;
internal string AddinId {
get { return addin_id; }
set { addin_id = value; }
}
private MediaGroupSource music_group_source;
protected MediaGroupSource MusicGroupSource {
get { return music_group_source; }
}
private MediaGroupSource video_group_source;
protected MediaGroupSource VideoGroupSource {
get { return video_group_source; }
}
private MediaGroupSource podcast_group_source;
protected MediaGroupSource PodcastGroupSource {
get { return podcast_group_source; }
}
protected DapSource ()
{
}
public virtual void DeviceInitialize (IDevice device)
{
this.device = device;
TypeUniqueId = device.Uuid;
}
public override void Dispose ()
{
PurgeTemporaryPlaylists ();
PurgeTracks ();
if (dap_info_bar != null) {
dap_info_bar.Destroy ();
dap_info_bar = null;
}
Properties.Remove ("Nereid.SourceContents.FooterWidget");
/*Properties.Remove ("Nereid.SourceContents");
dap_properties_display.Destroy ();
dap_properties_display = null;*/
if (sync != null)
sync.Dispose ();
}
private void PurgeTemporaryPlaylists ()
{
ServiceManager.DbConnection.Execute (new HyenaSqliteCommand (@"
BEGIN TRANSACTION;
DELETE FROM CoreSmartPlaylistEntries WHERE SmartPlaylistID IN
(SELECT SmartPlaylistID FROM CoreSmartPlaylists WHERE PrimarySourceID = ?);
DELETE FROM CoreSmartPlaylists WHERE PrimarySourceID = ?;
COMMIT TRANSACTION",
DbId, DbId
));
ServiceManager.DbConnection.Execute (new HyenaSqliteCommand (@"
BEGIN TRANSACTION;
DELETE FROM CorePlaylistEntries WHERE PlaylistID IN
(SELECT PlaylistID FROM CorePlaylists WHERE PrimarySourceID = ?);
DELETE FROM CorePlaylists WHERE PrimarySourceID = ?;
COMMIT TRANSACTION",
DbId, DbId
));
}
internal void RaiseUpdated ()
{
OnUpdated ();
}
public virtual void SyncPlaylists ()
{
}
public override void Rename (string newName)
{
Name = newName;
base.Rename (newName);
}
private bool supports_video = true;
public bool SupportsVideo {
get { return supports_video; }
protected set { supports_video = value; }
}
private bool supports_podcasts = true;
public bool SupportsPodcasts {
get { return supports_podcasts; }
protected set { supports_podcasts = value; }
}
#region Source
protected override void Initialize ()
{
PurgeTemporaryPlaylists ();
base.Initialize ();
Expanded = true;
Properties.SetStringList ("Icon.Name", GetIconNames ());
Properties.Set<string> ("SourcePropertiesActionLabel", Catalog.GetString ("Device Properties"));
Properties.Set<OpenPropertiesDelegate> ("SourceProperties.GuiHandler", delegate {
new DapPropertiesDialog (this).RunDialog ();
});
Properties.Set<bool> ("Nereid.SourceContents.HeaderVisible", false);
Properties.Set<System.Reflection.Assembly> ("ActiveSourceUIResource.Assembly", System.Reflection.Assembly.GetExecutingAssembly ());
Properties.SetString ("ActiveSourceUIResource", "ActiveSourceUI.xml");
sync = new DapSync (this);
dap_info_bar = new DapInfoBar (this);
Properties.Set<Gtk.Widget> ("Nereid.SourceContents.FooterWidget", dap_info_bar);
/*dap_properties_display = new DapPropertiesDisplay (this);
Properties.Set<Banshee.Sources.Gui.ISourceContents> ("Nereid.SourceContents", dap_properties_display);*/
if (String.IsNullOrEmpty (GenericName)) {
GenericName = Catalog.GetString ("Media Player");
}
if (String.IsNullOrEmpty (Name)) {
Name = device.Name;
}
AddDapProperty (Catalog.GetString ("Product"), device.Product);
AddDapProperty (Catalog.GetString ("Vendor"), device.Vendor);
if (acceptable_mimetypes == null) {
acceptable_mimetypes = HasMediaCapabilities ? MediaCapabilities.PlaybackMimeTypes : null;
if (acceptable_mimetypes == null || acceptable_mimetypes.Length == 0) {
acceptable_mimetypes = new string [] { "taglib/mp3" };
}
}
AddChildSource (music_group_source = new MusicGroupSource (this));
if (SupportsVideo) {
video_group_source = new VideoGroupSource (this);
}
if (SupportsPodcasts) {
podcast_group_source = new PodcastGroupSource (this);
}
BuildPreferences ();
ThreadAssist.ProxyToMain (delegate {
Properties.Set<Banshee.Sources.Gui.ISourceContents> ("Nereid.SourceContents", new DapContent (this));
});
}
private void BuildPreferences ()
{
page = new Page ();
Section main_section = new Section ();
main_section.Order = -1;
space_for_data = CreateSchema<long> ("space_for_data", 0, "How much space, in bytes, to reserve for data on the device.", "");
main_section.Add (space_for_data);
page.Add (main_section);
foreach (Section section in sync.PreferenceSections) {
page.Add (section);
}
}
// Force to zero so that count doesn't show up
public override int Count {
get { return 0; }
}
public override bool HasProperties {
get { return true; }
}
public override void SetStatus (string message, bool can_close, bool is_spinning, string icon_name)
{
base.SetStatus (message, can_close, is_spinning, icon_name);
foreach (Source child in Children) {
child.SetStatus (message, can_close, is_spinning, icon_name);
}
}
public override void HideStatus ()
{
base.HideStatus ();
foreach (Source child in Children) {
child.HideStatus ();
}
}
#endregion
#region Track Management/Syncing
public void LoadDeviceContents ()
{
ThreadPool.QueueUserWorkItem (ThreadedLoadDeviceContents);
}
private void ThreadedLoadDeviceContents (object state)
{
try {
PurgeTracks ();
SetStatus (String.Format (Catalog.GetString ("Loading {0}"), Name), false);
LoadFromDevice ();
HideStatus ();
sync.DapLoaded ();
sync.CalculateSync ();
if (sync.AutoSync) {
sync.Sync ();
}
} catch (Exception e) {
Log.Exception (e);
}
}
public void RemovePlaylists ()
{
// First remove any playlists on the device
List<Source> children = new List<Source> (sync.Dap.Children);
foreach (Source child in children) {
if (child is AbstractPlaylistSource && !(child is MediaGroupSource)) {
(child as IUnmapableSource).Unmap ();
}
}
}
protected virtual void LoadFromDevice ()
{
}
protected override void Eject ()
{
if (!Sync.Enabled) {
// If sync isn't enabled, then make sure we've written saved our playlists
// Track transfers happen immediately, but playlists saves don't
SyncPlaylists ();
}
}
HyenaSqliteCommand track_on_dap_query = new HyenaSqliteCommand (
"SELECT TrackID FROM CoreTracks WHERE PrimarySourceID = ? AND MetadataHash = ? LIMIT 1");
private void AttemptToAddTrackToDevice (DatabaseTrackInfo track, SafeUri fromUri)
{
if (!Banshee.IO.File.Exists (fromUri)) {
throw new FileNotFoundException (Catalog.GetString ("File not found"), fromUri.ToString ());
}
// Ensure there's enough space
if (BytesAvailable - Banshee.IO.File.GetSize (fromUri) >= 0) {
// Ensure it's not already on the device
if (ServiceManager.DbConnection.Query<int> (track_on_dap_query, DbId, track.MetadataHash) == 0) {
AddTrackToDevice (track, fromUri);
}
}
}
protected abstract void AddTrackToDevice (DatabaseTrackInfo track, SafeUri fromUri);
protected bool TrackNeedsTranscoding (TrackInfo track)
{
foreach (string mimetype in AcceptableMimeTypes) {
if (ServiceManager.MediaProfileManager.GetExtensionForMimeType (track.MimeType) ==
ServiceManager.MediaProfileManager.GetExtensionForMimeType (mimetype)) {
return false;
}
}
return true;
}
public struct DapProperty {
public string Name;
public string Value;
public DapProperty (string k, string v) { Name = k; Value = v; }
}
private List<DapProperty> dap_properties = new List<DapProperty> ();
protected void AddDapProperty (string key, string val)
{
dap_properties.Add (new DapProperty (key, val));
}
protected void AddYesNoDapProperty (string key, bool val)
{
AddDapProperty (key, val ? Catalog.GetString ("Yes") : Catalog.GetString ("No"));
}
public IEnumerable<DapProperty> DapProperties {
get { return dap_properties; }
}
protected override void AddTrackAndIncrementCount (DatabaseTrackInfo track)
{
if (!TrackNeedsTranscoding (track)) {
AttemptToAddTrackToDevice (track, track.Uri);
IncrementAddedTracks ();
return;
}
// If it's a video and needs transcoding, we don't support that yet
// TODO have preferred profiles for Audio and Video separately
if (PreferredConfiguration == null || (track.MediaAttributes & TrackMediaAttributes.VideoStream) != 0) {
string format = System.IO.Path.GetExtension (track.Uri.LocalPath);
format = String.IsNullOrEmpty (format) ? Catalog.GetString ("Unknown") : format.Substring (1);
throw new ApplicationException (String.Format (Catalog.GetString (
"The {0} format is not supported by the device, and no converter was found to convert it"), format));
}
TranscoderService transcoder = ServiceManager.Get<TranscoderService> ();
if (transcoder == null) {
throw new ApplicationException (Catalog.GetString (
"File format conversion support is not available"));
}
transcoder.Enqueue (track, PreferredConfiguration, OnTrackTranscoded, OnTrackTranscodeCancelled, OnTrackTranscodeError);
}
private void OnTrackTranscoded (TrackInfo track, SafeUri outputUri)
{
AddTrackJob.Status = String.Format ("{0} - {1}", track.ArtistName, track.TrackTitle);
try {
AttemptToAddTrackToDevice ((DatabaseTrackInfo)track, outputUri);
} catch (Exception e) {
Log.Exception (e);
}
IncrementAddedTracks ();
}
private void OnTrackTranscodeCancelled ()
{
IncrementAddedTracks ();
}
private void OnTrackTranscodeError (TrackInfo track)
{
ErrorSource.AddMessage (Catalog.GetString ("Error converting file"), track.Uri.ToString ());
IncrementAddedTracks ();
}
#endregion
#region Device Properties
protected virtual string [] GetIconNames ()
{
string vendor = device.Vendor;
string product = device.Product;
vendor = vendor != null ? vendor.Trim () : null;
product = product != null ? product.Trim () : null;
if (!String.IsNullOrEmpty (vendor) && !String.IsNullOrEmpty (product)) {
return new string [] {
String.Format ("multimedia-player-{0}-{1}", vendor, product).Replace (' ', '-').ToLower (),
FallbackIcon
};
} else {
return new string [] { FallbackIcon };
}
}
public static string FallbackIcon {
get { return "multimedia-player"; }
}
protected virtual bool HasMediaCapabilities {
get { return MediaCapabilities != null; }
}
protected virtual IDeviceMediaCapabilities MediaCapabilities {
get { return device.MediaCapabilities; }
}
public Page Preferences {
get { return page; }
}
public DapSync Sync {
get { return sync; }
}
private ProfileConfiguration preferred_config;
private ProfileConfiguration PreferredConfiguration {
get {
if (preferred_config != null) {
return preferred_config;
}
MediaProfileManager manager = ServiceManager.MediaProfileManager;
if (manager == null) {
return null;
}
preferred_config = manager.GetActiveProfileConfiguration (UniqueId, acceptable_mimetypes);
return preferred_config;
}
}
internal protected virtual bool CanHandleDeviceCommand (DeviceCommand command)
{
return false;
}
private string [] acceptable_mimetypes;
public string [] AcceptableMimeTypes {
get { return acceptable_mimetypes; }
protected set { acceptable_mimetypes = value; }
}
public long BytesVideo {
get { return VideoGroupSource == null ? 0 : VideoGroupSource.BytesUsed; }
}
public long BytesMusic {
get { return MusicGroupSource == null ? 0 : MusicGroupSource.BytesUsed; }
}
public long BytesData {
get { return BytesUsed - BytesVideo - BytesMusic; }
}
public long BytesReserved {
get { return space_for_data.Get (); }
set { space_for_data.Set (value); }
}
public override long BytesAvailable {
get { return BytesCapacity - BytesUsed - Math.Max (0, BytesReserved - BytesData); }
}
public override bool CanRemoveTracks {
get { return base.CanRemoveTracks; }
}
public override bool CanDeleteTracks {
get { return base.CanDeleteTracks; }
}
public override bool CanAddTracks {
get { return base.CanAddTracks; }
}
public override bool PlaylistsReadOnly {
get { return IsReadOnly; }
}
private Banshee.Configuration.SchemaEntry<long> space_for_data;
#endregion
}
}
| |
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq.Expressions;
using System.Runtime.InteropServices;
using Erwine.Leonard.T.GDIPlus.Palette.Helpers.Pixels;
using Erwine.Leonard.T.GDIPlus.Palette.Helpers.Pixels.Indexed;
using Erwine.Leonard.T.GDIPlus.Palette.Helpers.Pixels.NonIndexed;
namespace Erwine.Leonard.T.GDIPlus.Palette.Helpers
{
/// <summary>
/// This is a pixel format independent pixel.
/// </summary>
public class Pixel : IDisposable
{
#region | Constants |
internal const Byte Zero = 0;
internal const Byte One = 1;
internal const Byte Two = 2;
internal const Byte Four = 4;
internal const Byte Eight = 8;
internal const Byte NibbleMask = 0xF;
internal const Byte ByteMask = 0xFF;
internal const Int32 AlphaShift = 24;
internal const Int32 RedShift = 16;
internal const Int32 GreenShift = 8;
internal const Int32 BlueShift = 0;
internal const Int32 AlphaMask = ByteMask << AlphaShift;
internal const Int32 RedGreenBlueMask = 0xFFFFFF;
#endregion
#region | Fields |
private Type pixelType;
private Int32 bitOffset;
private Object pixelData;
private IntPtr pixelDataPointer;
#endregion
#region | Properties |
/// <summary>
/// Gets the X.
/// </summary>
public Int32 X { get; private set; }
/// <summary>
/// Gets the Y.
/// </summary>
public Int32 Y { get; private set; }
/// <summary>
/// Gets the parent buffer.
/// </summary>
public ImageBuffer Parent { get; private set; }
#endregion
#region | Calculated properties |
/// <summary>
/// Gets or sets the index.
/// </summary>
/// <value>The index.</value>
public Byte Index
{
get { return ((IIndexedPixel) pixelData).GetIndex(bitOffset); }
set { ((IIndexedPixel) pixelData).SetIndex(bitOffset, value); }
}
/// <summary>
/// Gets or sets the color.
/// </summary>
/// <value>The color.</value>
public Color Color
{
get { return ((INonIndexedPixel) pixelData).GetColor(); }
set { ((INonIndexedPixel) pixelData).SetColor(value); }
}
/// <summary>
/// Gets a value indicating whether this instance is indexed.
/// </summary>
/// <value>
/// <c>true</c> if this instance is indexed; otherwise, <c>false</c>.
/// </value>
public Boolean IsIndexed
{
get { return Parent.IsIndexed; }
}
#endregion
#region | Constructors |
/// <summary>
/// Initializes a new instance of the <see cref="Pixel"/> struct.
/// </summary>
public Pixel(ImageBuffer parent)
{
Parent = parent;
Initialize();
}
private void Initialize()
{
// creates pixel data
pixelType = IsIndexed ? GetIndexedType(Parent.PixelFormat) : GetNonIndexedType(Parent.PixelFormat);
NewExpression newType = Expression.New(pixelType);
UnaryExpression convertNewType = Expression.Convert(newType, typeof (Object));
Expression<Func<Object>> indexedExpression = Expression.Lambda<Func<Object>>(convertNewType);
pixelData = indexedExpression.Compile().Invoke();
pixelDataPointer = MarshalToPointer(pixelData);
}
#endregion
#region | Methods |
/// <summary>
/// Gets the type of the indexed pixel format.
/// </summary>
internal Type GetIndexedType(PixelFormat pixelFormat)
{
switch (pixelFormat)
{
case PixelFormat.Format1bppIndexed: return typeof(PixelData1Indexed);
case PixelFormat.Format4bppIndexed: return typeof(PixelData4Indexed);
case PixelFormat.Format8bppIndexed: return typeof(PixelData8Indexed);
default:
String message = String.Format("This pixel format '{0}' is either non-indexed, or not supported.", pixelFormat);
throw new NotSupportedException(message);
}
}
/// <summary>
/// Gets the type of the non-indexed pixel format.
/// </summary>
internal Type GetNonIndexedType(PixelFormat pixelFormat)
{
switch (pixelFormat)
{
case PixelFormat.Format16bppArgb1555: return typeof(PixelDataArgb1555);
case PixelFormat.Format16bppGrayScale: return typeof(PixelDataGray16);
case PixelFormat.Format16bppRgb555: return typeof(PixelDataRgb555);
case PixelFormat.Format16bppRgb565: return typeof(PixelDataRgb565);
case PixelFormat.Format24bppRgb: return typeof(PixelDataRgb888);
case PixelFormat.Format32bppRgb: return typeof(PixelDataRgb8888);
case PixelFormat.Format32bppArgb: return typeof(PixelDataArgb8888);
case PixelFormat.Format48bppRgb: return typeof(PixelDataRgb48);
case PixelFormat.Format64bppArgb: return typeof(PixelDataArgb64);
default:
String message = String.Format("This pixel format '{0}' is either indexed, or not supported.", pixelFormat);
throw new NotSupportedException(message);
}
}
private static IntPtr MarshalToPointer(Object data)
{
Int32 size = Marshal.SizeOf(data);
IntPtr pointer = Marshal.AllocHGlobal(size);
Marshal.StructureToPtr(data, pointer, false);
return pointer;
}
#endregion
#region | Update methods |
/// <param name="x">The X coordinate.</param>
/// <param name="y">The Y coordinate.</param>
public void Update(Int32 x, Int32 y)
{
X = x;
Y = y;
bitOffset = Parent.GetBitOffset(x);
}
/// <summary>
/// Reads the raw data.
/// </summary>
/// <param name="imagePointer">The image pointer.</param>
public void ReadRawData(IntPtr imagePointer)
{
pixelData = Marshal.PtrToStructure(imagePointer, pixelType);
}
/// <summary>
/// Reads the data.
/// </summary>
/// <param name="buffer">The buffer.</param>
/// <param name="offset">The offset.</param>
public void ReadData(Byte[] buffer, Int32 offset)
{
Marshal.Copy(buffer, offset, pixelDataPointer, Parent.BytesPerPixel);
pixelData = Marshal.PtrToStructure(pixelDataPointer, pixelType);
}
/// <summary>
/// Writes the raw data.
/// </summary>
/// <param name="imagePointer">The image pointer.</param>
public void WriteRawData(IntPtr imagePointer)
{
Marshal.StructureToPtr(pixelData, imagePointer, false);
}
/// <summary>
/// Writes the data.
/// </summary>
/// <param name="buffer">The buffer.</param>
/// <param name="offset">The offset.</param>
public void WriteData(Byte[] buffer, Int32 offset)
{
Marshal.Copy(pixelDataPointer, buffer, offset, Parent.BytesPerPixel);
}
#endregion
#region << IDisposable >>
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
Marshal.FreeHGlobal(pixelDataPointer);
}
#endregion
}
}
| |
// Copyright (C) 2014 dot42
//
// Original filename: Android.Net.Http.cs
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma warning disable 1717
namespace Android.Net.Http
{
/// <summary>
/// <para>SSL certificate info (certificate details) class </para>
/// </summary>
/// <java-name>
/// android/net/http/SslCertificate
/// </java-name>
[Dot42.DexImport("android/net/http/SslCertificate", AccessFlags = 33)]
public partial class SslCertificate
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V", AccessFlags = 1)]
public SslCertificate(string @string, string string1, string string2, string string3) /* MethodBuilder.Create */
{
}
[Dot42.DexImport("<init>", "(Ljava/lang/String;Ljava/lang/String;Ljava/util/Date;Ljava/util/Date;)V", AccessFlags = 1)]
public SslCertificate(string @string, string string1, global::Java.Util.Date date, global::Java.Util.Date date1) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Creates a new SSL certificate object from an X509 certificate </para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/security/cert/X509Certificate;)V", AccessFlags = 1)]
public SslCertificate(global::Java.Security.Cert.X509Certificate certificate) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Saves the certificate state to a bundle </para>
/// </summary>
/// <returns>
/// <para>A bundle with the certificate stored in it or null if fails </para>
/// </returns>
/// <java-name>
/// saveState
/// </java-name>
[Dot42.DexImport("saveState", "(Landroid/net/http/SslCertificate;)Landroid/os/Bundle;", AccessFlags = 9)]
public static global::Android.Os.Bundle SaveState(global::Android.Net.Http.SslCertificate certificate) /* MethodBuilder.Create */
{
return default(global::Android.Os.Bundle);
}
/// <summary>
/// <para>Restores the certificate stored in the bundle </para>
/// </summary>
/// <returns>
/// <para>The SSL certificate stored in the bundle or null if fails </para>
/// </returns>
/// <java-name>
/// restoreState
/// </java-name>
[Dot42.DexImport("restoreState", "(Landroid/os/Bundle;)Landroid/net/http/SslCertificate;", AccessFlags = 9)]
public static global::Android.Net.Http.SslCertificate RestoreState(global::Android.Os.Bundle bundle) /* MethodBuilder.Create */
{
return default(global::Android.Net.Http.SslCertificate);
}
/// <summary>
/// <para></para>
/// </summary>
/// <returns>
/// <para>Not-before date from the certificate validity period or "" if none has been set </para>
/// </returns>
/// <java-name>
/// getValidNotBeforeDate
/// </java-name>
[Dot42.DexImport("getValidNotBeforeDate", "()Ljava/util/Date;", AccessFlags = 1)]
public virtual global::Java.Util.Date GetValidNotBeforeDate() /* MethodBuilder.Create */
{
return default(global::Java.Util.Date);
}
/// <summary>
/// <para><xrefsect><xreftitle>Deprecated</xreftitle><xrefdescription><para>Use getValidNotBeforeDate() </para></xrefdescription></xrefsect></para>
/// </summary>
/// <returns>
/// <para>Not-before date from the certificate validity period in ISO 8601 format or "" if none has been set</para>
/// </returns>
/// <java-name>
/// getValidNotBefore
/// </java-name>
[Dot42.DexImport("getValidNotBefore", "()Ljava/lang/String;", AccessFlags = 1)]
public virtual string GetValidNotBefore() /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para></para>
/// </summary>
/// <returns>
/// <para>Not-after date from the certificate validity period or "" if none has been set </para>
/// </returns>
/// <java-name>
/// getValidNotAfterDate
/// </java-name>
[Dot42.DexImport("getValidNotAfterDate", "()Ljava/util/Date;", AccessFlags = 1)]
public virtual global::Java.Util.Date GetValidNotAfterDate() /* MethodBuilder.Create */
{
return default(global::Java.Util.Date);
}
/// <summary>
/// <para><xrefsect><xreftitle>Deprecated</xreftitle><xrefdescription><para>Use getValidNotAfterDate() </para></xrefdescription></xrefsect></para>
/// </summary>
/// <returns>
/// <para>Not-after date from the certificate validity period in ISO 8601 format or "" if none has been set</para>
/// </returns>
/// <java-name>
/// getValidNotAfter
/// </java-name>
[Dot42.DexImport("getValidNotAfter", "()Ljava/lang/String;", AccessFlags = 1)]
public virtual string GetValidNotAfter() /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para></para>
/// </summary>
/// <returns>
/// <para>Issued-to distinguished name or null if none has been set </para>
/// </returns>
/// <java-name>
/// getIssuedTo
/// </java-name>
[Dot42.DexImport("getIssuedTo", "()Landroid/net/http/SslCertificate$DName;", AccessFlags = 1)]
public virtual global::Android.Net.Http.SslCertificate.DName GetIssuedTo() /* MethodBuilder.Create */
{
return default(global::Android.Net.Http.SslCertificate.DName);
}
/// <summary>
/// <para></para>
/// </summary>
/// <returns>
/// <para>Issued-by distinguished name or null if none has been set </para>
/// </returns>
/// <java-name>
/// getIssuedBy
/// </java-name>
[Dot42.DexImport("getIssuedBy", "()Landroid/net/http/SslCertificate$DName;", AccessFlags = 1)]
public virtual global::Android.Net.Http.SslCertificate.DName GetIssuedBy() /* MethodBuilder.Create */
{
return default(global::Android.Net.Http.SslCertificate.DName);
}
/// <summary>
/// <para></para>
/// </summary>
/// <returns>
/// <para>A string representation of this certificate for debugging </para>
/// </returns>
/// <java-name>
/// toString
/// </java-name>
[Dot42.DexImport("toString", "()Ljava/lang/String;", AccessFlags = 1)]
public override string ToString() /* MethodBuilder.Create */
{
return default(string);
}
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
internal SslCertificate() /* TypeBuilder.AddDefaultConstructor */
{
}
/// <summary>
/// <para></para>
/// </summary>
/// <returns>
/// <para>Not-before date from the certificate validity period or "" if none has been set </para>
/// </returns>
/// <java-name>
/// getValidNotBeforeDate
/// </java-name>
public global::Java.Util.Date ValidNotBeforeDate
{
[Dot42.DexImport("getValidNotBeforeDate", "()Ljava/util/Date;", AccessFlags = 1)]
get{ return GetValidNotBeforeDate(); }
}
/// <summary>
/// <para><xrefsect><xreftitle>Deprecated</xreftitle><xrefdescription><para>Use getValidNotBeforeDate() </para></xrefdescription></xrefsect></para>
/// </summary>
/// <returns>
/// <para>Not-before date from the certificate validity period in ISO 8601 format or "" if none has been set</para>
/// </returns>
/// <java-name>
/// getValidNotBefore
/// </java-name>
public string ValidNotBefore
{
[Dot42.DexImport("getValidNotBefore", "()Ljava/lang/String;", AccessFlags = 1)]
get{ return GetValidNotBefore(); }
}
/// <summary>
/// <para></para>
/// </summary>
/// <returns>
/// <para>Not-after date from the certificate validity period or "" if none has been set </para>
/// </returns>
/// <java-name>
/// getValidNotAfterDate
/// </java-name>
public global::Java.Util.Date ValidNotAfterDate
{
[Dot42.DexImport("getValidNotAfterDate", "()Ljava/util/Date;", AccessFlags = 1)]
get{ return GetValidNotAfterDate(); }
}
/// <summary>
/// <para><xrefsect><xreftitle>Deprecated</xreftitle><xrefdescription><para>Use getValidNotAfterDate() </para></xrefdescription></xrefsect></para>
/// </summary>
/// <returns>
/// <para>Not-after date from the certificate validity period in ISO 8601 format or "" if none has been set</para>
/// </returns>
/// <java-name>
/// getValidNotAfter
/// </java-name>
public string ValidNotAfter
{
[Dot42.DexImport("getValidNotAfter", "()Ljava/lang/String;", AccessFlags = 1)]
get{ return GetValidNotAfter(); }
}
/// <summary>
/// <para></para>
/// </summary>
/// <returns>
/// <para>Issued-to distinguished name or null if none has been set </para>
/// </returns>
/// <java-name>
/// getIssuedTo
/// </java-name>
public global::Android.Net.Http.SslCertificate.DName IssuedTo
{
[Dot42.DexImport("getIssuedTo", "()Landroid/net/http/SslCertificate$DName;", AccessFlags = 1)]
get{ return GetIssuedTo(); }
}
/// <summary>
/// <para></para>
/// </summary>
/// <returns>
/// <para>Issued-by distinguished name or null if none has been set </para>
/// </returns>
/// <java-name>
/// getIssuedBy
/// </java-name>
public global::Android.Net.Http.SslCertificate.DName IssuedBy
{
[Dot42.DexImport("getIssuedBy", "()Landroid/net/http/SslCertificate$DName;", AccessFlags = 1)]
get{ return GetIssuedBy(); }
}
/// <summary>
/// <para>A distinguished name helper class: a 3-tuple of: <ul><li><para>the most specific common name (CN) </para></li><li><para>the most specific organization (O) </para></li><li><para>the most specific organizational unit (OU) <ul><li></li></ul></para></li></ul></para>
/// </summary>
/// <java-name>
/// android/net/http/SslCertificate$DName
/// </java-name>
[Dot42.DexImport("android/net/http/SslCertificate$DName", AccessFlags = 1)]
public partial class DName
/* scope: __dot42__ */
{
/// <java-name>
/// this$0
/// </java-name>
[Dot42.DexImport("this$0", "Landroid/net/http/SslCertificate;", AccessFlags = 4112)]
internal readonly global::Android.Net.Http.SslCertificate This_0;
[Dot42.DexImport("<init>", "(Landroid/net/http/SslCertificate;Ljava/lang/String;)V", AccessFlags = 1)]
public DName(global::Android.Net.Http.SslCertificate sslCertificate, string @string) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para></para>
/// </summary>
/// <returns>
/// <para>The distinguished name (normally includes CN, O, and OU names) </para>
/// </returns>
/// <java-name>
/// getDName
/// </java-name>
[Dot42.DexImport("getDName", "()Ljava/lang/String;", AccessFlags = 1)]
public virtual string GetDName() /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para></para>
/// </summary>
/// <returns>
/// <para>The most specific Common-name (CN) component of this name </para>
/// </returns>
/// <java-name>
/// getCName
/// </java-name>
[Dot42.DexImport("getCName", "()Ljava/lang/String;", AccessFlags = 1)]
public virtual string GetCName() /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para></para>
/// </summary>
/// <returns>
/// <para>The most specific Organization (O) component of this name </para>
/// </returns>
/// <java-name>
/// getOName
/// </java-name>
[Dot42.DexImport("getOName", "()Ljava/lang/String;", AccessFlags = 1)]
public virtual string GetOName() /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para></para>
/// </summary>
/// <returns>
/// <para>The most specific Organizational Unit (OU) component of this name </para>
/// </returns>
/// <java-name>
/// getUName
/// </java-name>
[Dot42.DexImport("getUName", "()Ljava/lang/String;", AccessFlags = 1)]
public virtual string GetUName() /* MethodBuilder.Create */
{
return default(string);
}
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
internal DName() /* TypeBuilder.AddDefaultConstructor */
{
}
/// <summary>
/// <para></para>
/// </summary>
/// <returns>
/// <para>The most specific Common-name (CN) component of this name </para>
/// </returns>
/// <java-name>
/// getCName
/// </java-name>
public string CName
{
[Dot42.DexImport("getCName", "()Ljava/lang/String;", AccessFlags = 1)]
get{ return GetCName(); }
}
/// <summary>
/// <para></para>
/// </summary>
/// <returns>
/// <para>The most specific Organization (O) component of this name </para>
/// </returns>
/// <java-name>
/// getOName
/// </java-name>
public string OName
{
[Dot42.DexImport("getOName", "()Ljava/lang/String;", AccessFlags = 1)]
get{ return GetOName(); }
}
/// <summary>
/// <para></para>
/// </summary>
/// <returns>
/// <para>The most specific Organizational Unit (OU) component of this name </para>
/// </returns>
/// <java-name>
/// getUName
/// </java-name>
public string UName
{
[Dot42.DexImport("getUName", "()Ljava/lang/String;", AccessFlags = 1)]
get{ return GetUName(); }
}
}
}
/// <summary>
/// <para>This class represents a set of one or more SSL errors and the associated SSL certificate. </para>
/// </summary>
/// <java-name>
/// android/net/http/SslError
/// </java-name>
[Dot42.DexImport("android/net/http/SslError", AccessFlags = 33)]
public partial class SslError
/* scope: __dot42__ */
{
/// <summary>
/// <para>Individual SSL errors (in the order from the least to the most severe): The certificate is not yet valid </para>
/// </summary>
/// <java-name>
/// SSL_NOTYETVALID
/// </java-name>
[Dot42.DexImport("SSL_NOTYETVALID", "I", AccessFlags = 25)]
public const int SSL_NOTYETVALID = 0;
/// <summary>
/// <para>The certificate has expired </para>
/// </summary>
/// <java-name>
/// SSL_EXPIRED
/// </java-name>
[Dot42.DexImport("SSL_EXPIRED", "I", AccessFlags = 25)]
public const int SSL_EXPIRED = 1;
/// <summary>
/// <para>Hostname mismatch </para>
/// </summary>
/// <java-name>
/// SSL_IDMISMATCH
/// </java-name>
[Dot42.DexImport("SSL_IDMISMATCH", "I", AccessFlags = 25)]
public const int SSL_IDMISMATCH = 2;
/// <summary>
/// <para>The certificate authority is not trusted </para>
/// </summary>
/// <java-name>
/// SSL_UNTRUSTED
/// </java-name>
[Dot42.DexImport("SSL_UNTRUSTED", "I", AccessFlags = 25)]
public const int SSL_UNTRUSTED = 3;
/// <summary>
/// <para>The number of different SSL errors. <xrefsect><xreftitle>Deprecated</xreftitle><xrefdescription><para>This constant is not necessary for using the SslError API and can change from release to release. </para></xrefdescription></xrefsect></para>
/// </summary>
/// <java-name>
/// SSL_MAX_ERROR
/// </java-name>
[Dot42.DexImport("SSL_MAX_ERROR", "I", AccessFlags = 25)]
public const int SSL_MAX_ERROR = 4;
/// <summary>
/// <para>Creates a new SslError object using the supplied error and certificate. The URL will be set to the empty string. <xrefsect><xreftitle>Deprecated</xreftitle><xrefdescription><para>Use SslError(int, SslCertificate, String) </para></xrefdescription></xrefsect></para>
/// </summary>
[Dot42.DexImport("<init>", "(ILandroid/net/http/SslCertificate;)V", AccessFlags = 1)]
public SslError(int error, global::Android.Net.Http.SslCertificate certificate) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Creates a new SslError object using the supplied error and certificate. The URL will be set to the empty string. <xrefsect><xreftitle>Deprecated</xreftitle><xrefdescription><para>Use SslError(int, SslCertificate, String) </para></xrefdescription></xrefsect></para>
/// </summary>
[Dot42.DexImport("<init>", "(ILjava/security/cert/X509Certificate;)V", AccessFlags = 1)]
public SslError(int error, global::Java.Security.Cert.X509Certificate certificate) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Gets the SSL certificate associated with this object. </para>
/// </summary>
/// <returns>
/// <para>The SSL certificate, non-null. </para>
/// </returns>
/// <java-name>
/// getCertificate
/// </java-name>
[Dot42.DexImport("getCertificate", "()Landroid/net/http/SslCertificate;", AccessFlags = 1)]
public virtual global::Android.Net.Http.SslCertificate GetCertificate() /* MethodBuilder.Create */
{
return default(global::Android.Net.Http.SslCertificate);
}
/// <summary>
/// <para>Adds the supplied SSL error to the set. </para>
/// </summary>
/// <returns>
/// <para>True if the error being added is a known SSL error, otherwise false. </para>
/// </returns>
/// <java-name>
/// addError
/// </java-name>
[Dot42.DexImport("addError", "(I)Z", AccessFlags = 1)]
public virtual bool AddError(int error) /* MethodBuilder.Create */
{
return default(bool);
}
/// <summary>
/// <para>Determines whether this object includes the supplied error. </para>
/// </summary>
/// <returns>
/// <para>True if this object includes the error, otherwise false. </para>
/// </returns>
/// <java-name>
/// hasError
/// </java-name>
[Dot42.DexImport("hasError", "(I)Z", AccessFlags = 1)]
public virtual bool HasError(int error) /* MethodBuilder.Create */
{
return default(bool);
}
/// <summary>
/// <para>Gets the most severe SSL error in this object's set of errors. Returns -1 if the set is empty. </para>
/// </summary>
/// <returns>
/// <para>The most severe SSL error, or -1 if the set is empty. </para>
/// </returns>
/// <java-name>
/// getPrimaryError
/// </java-name>
[Dot42.DexImport("getPrimaryError", "()I", AccessFlags = 1)]
public virtual int GetPrimaryError() /* MethodBuilder.Create */
{
return default(int);
}
/// <summary>
/// <para>Returns a string representation of this object. </para>
/// </summary>
/// <returns>
/// <para>A String representation of this object. </para>
/// </returns>
/// <java-name>
/// toString
/// </java-name>
[Dot42.DexImport("toString", "()Ljava/lang/String;", AccessFlags = 1)]
public override string ToString() /* MethodBuilder.Create */
{
return default(string);
}
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
internal SslError() /* TypeBuilder.AddDefaultConstructor */
{
}
/// <summary>
/// <para>Gets the SSL certificate associated with this object. </para>
/// </summary>
/// <returns>
/// <para>The SSL certificate, non-null. </para>
/// </returns>
/// <java-name>
/// getCertificate
/// </java-name>
public global::Android.Net.Http.SslCertificate Certificate
{
[Dot42.DexImport("getCertificate", "()Landroid/net/http/SslCertificate;", AccessFlags = 1)]
get{ return GetCertificate(); }
}
/// <summary>
/// <para>Gets the most severe SSL error in this object's set of errors. Returns -1 if the set is empty. </para>
/// </summary>
/// <returns>
/// <para>The most severe SSL error, or -1 if the set is empty. </para>
/// </returns>
/// <java-name>
/// getPrimaryError
/// </java-name>
public int PrimaryError
{
[Dot42.DexImport("getPrimaryError", "()I", AccessFlags = 1)]
get{ return GetPrimaryError(); }
}
}
/// <summary>
/// <para>Implementation of the Apache DefaultHttpClient that is configured with reasonable default settings and registered schemes for Android. Don't create this directly, use the newInstance factory method.</para><para>This client processes cookies but does not retain them by default. To retain cookies, simply add a cookie store to the HttpContext:</para><para><pre>context.setAttribute(ClientContext.COOKIE_STORE, cookieStore);</pre> </para>
/// </summary>
/// <java-name>
/// android/net/http/AndroidHttpClient
/// </java-name>
[Dot42.DexImport("android/net/http/AndroidHttpClient", AccessFlags = 49)]
public sealed partial class AndroidHttpClient : global::Org.Apache.Http.Client.IHttpClient
/* scope: __dot42__ */
{
/// <java-name>
/// DEFAULT_SYNC_MIN_GZIP_BYTES
/// </java-name>
[Dot42.DexImport("DEFAULT_SYNC_MIN_GZIP_BYTES", "J", AccessFlags = 9)]
public static long DEFAULT_SYNC_MIN_GZIP_BYTES;
[Dot42.DexImport("<init>", "()V", AccessFlags = 0)]
internal AndroidHttpClient() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Create a new HttpClient with reasonable defaults (which you can update).</para><para></para>
/// </summary>
/// <returns>
/// <para>AndroidHttpClient for you to use for all your requests. </para>
/// </returns>
/// <java-name>
/// newInstance
/// </java-name>
[Dot42.DexImport("newInstance", "(Ljava/lang/String;Landroid/content/Context;)Landroid/net/http/AndroidHttpClient;" +
"", AccessFlags = 9)]
public static global::Android.Net.Http.AndroidHttpClient NewInstance(string userAgent, global::Android.Content.Context context) /* MethodBuilder.Create */
{
return default(global::Android.Net.Http.AndroidHttpClient);
}
/// <summary>
/// <para>Create a new HttpClient with reasonable defaults (which you can update). </para>
/// </summary>
/// <returns>
/// <para>AndroidHttpClient for you to use for all your requests. </para>
/// </returns>
/// <java-name>
/// newInstance
/// </java-name>
[Dot42.DexImport("newInstance", "(Ljava/lang/String;)Landroid/net/http/AndroidHttpClient;", AccessFlags = 9)]
public static global::Android.Net.Http.AndroidHttpClient NewInstance(string userAgent) /* MethodBuilder.Create */
{
return default(global::Android.Net.Http.AndroidHttpClient);
}
/// <java-name>
/// finalize
/// </java-name>
[Dot42.DexImport("finalize", "()V", AccessFlags = 4)]
extern ~AndroidHttpClient() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Modifies a request to indicate to the server that we would like a gzipped response. (Uses the "Accept-Encoding" HTTP header.) <para>getUngzippedContent </para></para>
/// </summary>
/// <java-name>
/// modifyRequestToAcceptGzipResponse
/// </java-name>
[Dot42.DexImport("modifyRequestToAcceptGzipResponse", "(Lorg/apache/http/HttpRequest;)V", AccessFlags = 9)]
public static void ModifyRequestToAcceptGzipResponse(global::Org.Apache.Http.IHttpRequest request) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Gets the input stream from a response entity. If the entity is gzipped then this will get a stream over the uncompressed data.</para><para></para>
/// </summary>
/// <returns>
/// <para>the input stream to read from </para>
/// </returns>
/// <java-name>
/// getUngzippedContent
/// </java-name>
[Dot42.DexImport("getUngzippedContent", "(Lorg/apache/http/HttpEntity;)Ljava/io/InputStream;", AccessFlags = 9)]
public static global::Java.Io.InputStream GetUngzippedContent(global::Org.Apache.Http.IHttpEntity entity) /* MethodBuilder.Create */
{
return default(global::Java.Io.InputStream);
}
/// <summary>
/// <para>Release resources associated with this client. You must call this, or significant resources (sockets and memory) may be leaked. </para>
/// </summary>
/// <java-name>
/// close
/// </java-name>
[Dot42.DexImport("close", "()V", AccessFlags = 1)]
public void Close() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Obtains the parameters for this client. These parameters will become defaults for all requests being executed with this client, and for the parameters of dependent objects in this client.</para><para></para>
/// </summary>
/// <returns>
/// <para>the default parameters </para>
/// </returns>
/// <java-name>
/// getParams
/// </java-name>
[Dot42.DexImport("getParams", "()Lorg/apache/http/params/HttpParams;", AccessFlags = 1)]
public global::Org.Apache.Http.Params.IHttpParams GetParams() /* MethodBuilder.Create */
{
return default(global::Org.Apache.Http.Params.IHttpParams);
}
/// <summary>
/// <para>Obtains the connection manager used by this client.</para><para></para>
/// </summary>
/// <returns>
/// <para>the connection manager </para>
/// </returns>
/// <java-name>
/// getConnectionManager
/// </java-name>
[Dot42.DexImport("getConnectionManager", "()Lorg/apache/http/conn/ClientConnectionManager;", AccessFlags = 1)]
public global::Org.Apache.Http.Conn.IClientConnectionManager GetConnectionManager() /* MethodBuilder.Create */
{
return default(global::Org.Apache.Http.Conn.IClientConnectionManager);
}
/// <summary>
/// <para>Executes a request using the default context.</para><para></para>
/// </summary>
/// <returns>
/// <para>the response to the request. This is always a final response, never an intermediate response with an 1xx status code. Whether redirects or authentication challenges will be returned or handled automatically depends on the implementation and configuration of this client. </para>
/// </returns>
/// <java-name>
/// execute
/// </java-name>
[Dot42.DexImport("execute", "(Lorg/apache/http/client/methods/HttpUriRequest;)Lorg/apache/http/HttpResponse;", AccessFlags = 1)]
public global::Org.Apache.Http.IHttpResponse Execute(global::Org.Apache.Http.Client.Methods.IHttpUriRequest request) /* MethodBuilder.Create */
{
return default(global::Org.Apache.Http.IHttpResponse);
}
/// <summary>
/// <para>Executes a request using the given context. The route to the target will be determined by the HTTP client.</para><para></para>
/// </summary>
/// <returns>
/// <para>the response to the request. This is always a final response, never an intermediate response with an 1xx status code. Whether redirects or authentication challenges will be returned or handled automatically depends on the implementation and configuration of this client. </para>
/// </returns>
/// <java-name>
/// execute
/// </java-name>
[Dot42.DexImport("execute", "(Lorg/apache/http/client/methods/HttpUriRequest;Lorg/apache/http/protocol/HttpCon" +
"text;)Lorg/apache/http/HttpResponse;", AccessFlags = 1)]
public global::Org.Apache.Http.IHttpResponse Execute(global::Org.Apache.Http.Client.Methods.IHttpUriRequest request, global::Org.Apache.Http.Protocol.IHttpContext context) /* MethodBuilder.Create */
{
return default(global::Org.Apache.Http.IHttpResponse);
}
/// <summary>
/// <para>Executes a request using the given context. The route to the target will be determined by the HTTP client.</para><para></para>
/// </summary>
/// <returns>
/// <para>the response to the request. This is always a final response, never an intermediate response with an 1xx status code. Whether redirects or authentication challenges will be returned or handled automatically depends on the implementation and configuration of this client. </para>
/// </returns>
/// <java-name>
/// execute
/// </java-name>
[Dot42.DexImport("execute", "(Lorg/apache/http/HttpHost;Lorg/apache/http/HttpRequest;)Lorg/apache/http/HttpRes" +
"ponse;", AccessFlags = 1)]
public global::Org.Apache.Http.IHttpResponse Execute(global::Org.Apache.Http.HttpHost request, global::Org.Apache.Http.IHttpRequest context) /* MethodBuilder.Create */
{
return default(global::Org.Apache.Http.IHttpResponse);
}
/// <summary>
/// <para>Executes a request to the target using the given context.</para><para></para>
/// </summary>
/// <returns>
/// <para>the response to the request. This is always a final response, never an intermediate response with an 1xx status code. Whether redirects or authentication challenges will be returned or handled automatically depends on the implementation and configuration of this client. </para>
/// </returns>
/// <java-name>
/// execute
/// </java-name>
[Dot42.DexImport("execute", "(Lorg/apache/http/HttpHost;Lorg/apache/http/HttpRequest;Lorg/apache/http/protocol" +
"/HttpContext;)Lorg/apache/http/HttpResponse;", AccessFlags = 1)]
public global::Org.Apache.Http.IHttpResponse Execute(global::Org.Apache.Http.HttpHost target, global::Org.Apache.Http.IHttpRequest request, global::Org.Apache.Http.Protocol.IHttpContext context) /* MethodBuilder.Create */
{
return default(global::Org.Apache.Http.IHttpResponse);
}
/// <summary>
/// <para>Executes a request using the given context. The route to the target will be determined by the HTTP client.</para><para></para>
/// </summary>
/// <returns>
/// <para>the response to the request. This is always a final response, never an intermediate response with an 1xx status code. Whether redirects or authentication challenges will be returned or handled automatically depends on the implementation and configuration of this client. </para>
/// </returns>
/// <java-name>
/// execute
/// </java-name>
[Dot42.DexImport("execute", "(Lorg/apache/http/client/methods/HttpUriRequest;Lorg/apache/http/client/ResponseH" +
"andler;)Ljava/lang/Object;", AccessFlags = 1, Signature = "<T:Ljava/lang/Object;>(Lorg/apache/http/client/methods/HttpUriRequest;Lorg/apache" +
"/http/client/ResponseHandler<+TT;>;)TT;")]
public T Execute<T>(global::Org.Apache.Http.Client.Methods.IHttpUriRequest request, global::Org.Apache.Http.Client.IResponseHandler<T> context) /* MethodBuilder.Create */
{
return default(T);
}
/// <summary>
/// <para>Executes a request to the target using the given context.</para><para></para>
/// </summary>
/// <returns>
/// <para>the response to the request. This is always a final response, never an intermediate response with an 1xx status code. Whether redirects or authentication challenges will be returned or handled automatically depends on the implementation and configuration of this client. </para>
/// </returns>
/// <java-name>
/// execute
/// </java-name>
[Dot42.DexImport("execute", "(Lorg/apache/http/client/methods/HttpUriRequest;Lorg/apache/http/client/ResponseH" +
"andler;Lorg/apache/http/protocol/HttpContext;)Ljava/lang/Object;", AccessFlags = 1, Signature = "<T:Ljava/lang/Object;>(Lorg/apache/http/client/methods/HttpUriRequest;Lorg/apache" +
"/http/client/ResponseHandler<+TT;>;Lorg/apache/http/protocol/HttpContext;)TT;")]
public T Execute<T>(global::Org.Apache.Http.Client.Methods.IHttpUriRequest target, global::Org.Apache.Http.Client.IResponseHandler<T> request, global::Org.Apache.Http.Protocol.IHttpContext context) /* MethodBuilder.Create */
{
return default(T);
}
/// <summary>
/// <para>Executes a request to the target using the given context.</para><para></para>
/// </summary>
/// <returns>
/// <para>the response to the request. This is always a final response, never an intermediate response with an 1xx status code. Whether redirects or authentication challenges will be returned or handled automatically depends on the implementation and configuration of this client. </para>
/// </returns>
/// <java-name>
/// execute
/// </java-name>
[Dot42.DexImport("execute", "(Lorg/apache/http/HttpHost;Lorg/apache/http/HttpRequest;Lorg/apache/http/client/R" +
"esponseHandler;)Ljava/lang/Object;", AccessFlags = 1, Signature = "<T:Ljava/lang/Object;>(Lorg/apache/http/HttpHost;Lorg/apache/http/HttpRequest;Lor" +
"g/apache/http/client/ResponseHandler<+TT;>;)TT;")]
public T Execute<T>(global::Org.Apache.Http.HttpHost target, global::Org.Apache.Http.IHttpRequest request, global::Org.Apache.Http.Client.IResponseHandler<T> context) /* MethodBuilder.Create */
{
return default(T);
}
/// <summary>
/// <para>Executes a request to the target using the given context and processes the response using the given response handler.</para><para></para>
/// </summary>
/// <returns>
/// <para>the response object as generated by the response handler. </para>
/// </returns>
/// <java-name>
/// execute
/// </java-name>
[Dot42.DexImport("execute", "(Lorg/apache/http/HttpHost;Lorg/apache/http/HttpRequest;Lorg/apache/http/client/R" +
"esponseHandler;Lorg/apache/http/protocol/HttpContext;)Ljava/lang/Object;", AccessFlags = 1, Signature = "<T:Ljava/lang/Object;>(Lorg/apache/http/HttpHost;Lorg/apache/http/HttpRequest;Lor" +
"g/apache/http/client/ResponseHandler<+TT;>;Lorg/apache/http/protocol/HttpContext" +
";)TT;")]
public T Execute<T>(global::Org.Apache.Http.HttpHost target, global::Org.Apache.Http.IHttpRequest request, global::Org.Apache.Http.Client.IResponseHandler<T> responseHandler, global::Org.Apache.Http.Protocol.IHttpContext context) /* MethodBuilder.Create */
{
return default(T);
}
/// <summary>
/// <para>Compress data to send to server. Creates a Http Entity holding the gzipped data. The data will not be compressed if it is too short. </para>
/// </summary>
/// <returns>
/// <para>Entity holding the data </para>
/// </returns>
/// <java-name>
/// getCompressedEntity
/// </java-name>
[Dot42.DexImport("getCompressedEntity", "([BLandroid/content/ContentResolver;)Lorg/apache/http/entity/AbstractHttpEntity;", AccessFlags = 9)]
public static global::Org.Apache.Http.Entity.AbstractHttpEntity GetCompressedEntity(sbyte[] data, global::Android.Content.ContentResolver resolver) /* MethodBuilder.Create */
{
return default(global::Org.Apache.Http.Entity.AbstractHttpEntity);
}
/// <summary>
/// <para>Compress data to send to server. Creates a Http Entity holding the gzipped data. The data will not be compressed if it is too short. </para>
/// </summary>
/// <returns>
/// <para>Entity holding the data </para>
/// </returns>
/// <java-name>
/// getCompressedEntity
/// </java-name>
[Dot42.DexImport("getCompressedEntity", "([BLandroid/content/ContentResolver;)Lorg/apache/http/entity/AbstractHttpEntity;", AccessFlags = 9, IgnoreFromJava = true)]
public static global::Org.Apache.Http.Entity.AbstractHttpEntity GetCompressedEntity(byte[] data, global::Android.Content.ContentResolver resolver) /* MethodBuilder.Create */
{
return default(global::Org.Apache.Http.Entity.AbstractHttpEntity);
}
/// <summary>
/// <para>Retrieves the minimum size for compressing data. Shorter data will not be compressed. </para>
/// </summary>
/// <java-name>
/// getMinGzipSize
/// </java-name>
[Dot42.DexImport("getMinGzipSize", "(Landroid/content/ContentResolver;)J", AccessFlags = 9)]
public static long GetMinGzipSize(global::Android.Content.ContentResolver resolver) /* MethodBuilder.Create */
{
return default(long);
}
/// <summary>
/// <para>Enables cURL request logging for this client.</para><para></para>
/// </summary>
/// <java-name>
/// enableCurlLogging
/// </java-name>
[Dot42.DexImport("enableCurlLogging", "(Ljava/lang/String;I)V", AccessFlags = 1)]
public void EnableCurlLogging(string name, int level) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Disables cURL logging for this client. </para>
/// </summary>
/// <java-name>
/// disableCurlLogging
/// </java-name>
[Dot42.DexImport("disableCurlLogging", "()V", AccessFlags = 1)]
public void DisableCurlLogging() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Returns the date of the given HTTP date string. This method can identify and parse the date formats emitted by common HTTP servers, such as , , , and .</para><para></para>
/// </summary>
/// <returns>
/// <para>the number of milliseconds since Jan. 1, 1970, midnight GMT. </para>
/// </returns>
/// <java-name>
/// parseDate
/// </java-name>
[Dot42.DexImport("parseDate", "(Ljava/lang/String;)J", AccessFlags = 9)]
public static long ParseDate(string dateString) /* MethodBuilder.Create */
{
return default(long);
}
/// <summary>
/// <para>Obtains the parameters for this client. These parameters will become defaults for all requests being executed with this client, and for the parameters of dependent objects in this client.</para><para></para>
/// </summary>
/// <returns>
/// <para>the default parameters </para>
/// </returns>
/// <java-name>
/// getParams
/// </java-name>
public global::Org.Apache.Http.Params.IHttpParams Params
{
[Dot42.DexImport("getParams", "()Lorg/apache/http/params/HttpParams;", AccessFlags = 1)]
get{ return GetParams(); }
}
/// <summary>
/// <para>Obtains the connection manager used by this client.</para><para></para>
/// </summary>
/// <returns>
/// <para>the connection manager </para>
/// </returns>
/// <java-name>
/// getConnectionManager
/// </java-name>
public global::Org.Apache.Http.Conn.IClientConnectionManager ConnectionManager
{
[Dot42.DexImport("getConnectionManager", "()Lorg/apache/http/conn/ClientConnectionManager;", AccessFlags = 1)]
get{ return GetConnectionManager(); }
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using Xunit;
using Should;
using System.Linq;
namespace AutoMapper.UnitTests
{
namespace ArraysAndLists
{
public class When_mapping_to_a_concrete_non_generic_ienumerable : AutoMapperSpecBase
{
private Destination _destination;
public class Source
{
public int[] Values { get; set; }
public List<int> Values2 { get; set; }
}
public class Destination
{
public IEnumerable Values { get; set; }
public IEnumerable Values2 { get; set; }
}
protected override void Establish_context()
{
Mapper.CreateMap<Source, Destination>();
}
protected override void Because_of()
{
_destination = Mapper.Map<Source, Destination>(new Source { Values = new[] { 1, 2, 3, 4 }, Values2 = new List<int> { 9, 8, 7, 6 } });
}
[Fact]
public void Should_map_the_list_of_source_items()
{
_destination.Values.ShouldNotBeNull();
_destination.Values.ShouldContain(1);
_destination.Values.ShouldContain(2);
_destination.Values.ShouldContain(3);
_destination.Values.ShouldContain(4);
}
[Fact]
public void Should_map_from_the_generic_list_of_values()
{
_destination.Values2.ShouldNotBeNull();
_destination.Values2.ShouldContain(9);
_destination.Values2.ShouldContain(8);
_destination.Values2.ShouldContain(7);
_destination.Values2.ShouldContain(6);
}
}
public class When_mapping_to_a_concrete_generic_ienumerable : AutoMapperSpecBase
{
private Destination _destination;
public class Source
{
public int[] Values { get; set; }
public List<int> Values2 { get; set; }
}
public class Destination
{
public IEnumerable<int> Values { get; set; }
public IEnumerable<string> Values2 { get; set; }
}
protected override void Establish_context()
{
Mapper.CreateMap<Source, Destination>();
}
protected override void Because_of()
{
_destination = Mapper.Map<Source, Destination>(new Source { Values = new[] { 1, 2, 3, 4 }, Values2 = new List<int> { 9, 8, 7, 6 } });
}
[Fact]
public void Should_map_the_list_of_source_items()
{
_destination.Values.ShouldNotBeNull();
_destination.Values.ShouldContain(1);
_destination.Values.ShouldContain(2);
_destination.Values.ShouldContain(3);
_destination.Values.ShouldContain(4);
}
[Fact]
public void Should_map_from_the_generic_list_of_values_with_formatting()
{
_destination.Values2.ShouldNotBeNull();
_destination.Values2.ShouldContain("9");
_destination.Values2.ShouldContain("8");
_destination.Values2.ShouldContain("7");
_destination.Values2.ShouldContain("6");
}
}
public class When_mapping_to_a_concrete_non_generic_icollection : AutoMapperSpecBase
{
private Destination _destination;
public class Source
{
public int[] Values { get; set; }
public List<int> Values2 { get; set; }
}
public class Destination
{
public ICollection Values { get; set; }
public ICollection Values2 { get; set; }
}
protected override void Establish_context()
{
Mapper.CreateMap<Source, Destination>();
}
protected override void Because_of()
{
_destination = Mapper.Map<Source, Destination>(new Source { Values = new[] { 1, 2, 3, 4 }, Values2 = new List<int> { 9, 8, 7, 6 } });
}
[Fact]
public void Should_map_the_list_of_source_items()
{
_destination.Values.ShouldNotBeNull();
_destination.Values.ShouldContain(1);
_destination.Values.ShouldContain(2);
_destination.Values.ShouldContain(3);
_destination.Values.ShouldContain(4);
}
[Fact]
public void Should_map_from_a_non_array_source()
{
_destination.Values2.ShouldNotBeNull();
_destination.Values2.ShouldContain(9);
_destination.Values2.ShouldContain(8);
_destination.Values2.ShouldContain(7);
_destination.Values2.ShouldContain(6);
}
}
public class When_mapping_to_a_concrete_generic_icollection : AutoMapperSpecBase
{
private Destination _destination;
public class Source
{
public int[] Values { get; set; }
}
public class Destination
{
public ICollection<string> Values { get; set; }
}
protected override void Establish_context()
{
Mapper.CreateMap<Source, Destination>();
}
protected override void Because_of()
{
_destination = Mapper.Map<Source, Destination>(new Source { Values = new[] { 1, 2, 3, 4 } });
}
[Fact]
public void Should_map_the_list_of_source_items()
{
_destination.Values.ShouldNotBeNull();
_destination.Values.ShouldContain("1");
_destination.Values.ShouldContain("2");
_destination.Values.ShouldContain("3");
_destination.Values.ShouldContain("4");
}
}
public class When_mapping_to_a_concrete_ilist : AutoMapperSpecBase
{
private Destination _destination;
public class Source
{
public int[] Values { get; set; }
}
public class Destination
{
public IList Values { get; set; }
}
protected override void Establish_context()
{
Mapper.CreateMap<Source, Destination>();
}
protected override void Because_of()
{
_destination = Mapper.Map<Source, Destination>(new Source { Values = new[] { 1, 2, 3, 4 } });
}
[Fact]
public void Should_map_the_list_of_source_items()
{
_destination.Values.ShouldNotBeNull();
_destination.Values.ShouldContain(1);
_destination.Values.ShouldContain(2);
_destination.Values.ShouldContain(3);
_destination.Values.ShouldContain(4);
}
}
public class When_mapping_to_a_concrete_generic_ilist : AutoMapperSpecBase
{
private Destination _destination;
public class Source
{
public int[] Values { get; set; }
}
public class Destination
{
public IList<string> Values { get; set; }
}
protected override void Establish_context()
{
Mapper.CreateMap<Source, Destination>();
}
protected override void Because_of()
{
_destination = Mapper.Map<Source, Destination>(new Source { Values = new[] { 1, 2, 3, 4 } });
}
[Fact]
public void Should_map_the_list_of_source_items()
{
_destination.Values.ShouldNotBeNull();
_destination.Values.ShouldContain("1");
_destination.Values.ShouldContain("2");
_destination.Values.ShouldContain("3");
_destination.Values.ShouldContain("4");
}
}
public class When_mapping_to_a_custom_list_with_the_same_type : AutoMapperSpecBase
{
private Destination _destination;
private Source _source;
public class ValueCollection : Collection<int>
{
}
public class Source
{
public ValueCollection Values { get; set; }
}
public class Destination
{
public ValueCollection Values { get; set; }
}
protected override void Establish_context()
{
Mapper.CreateMap<Source, Destination>();
}
protected override void Because_of()
{
_source = new Source { Values = new ValueCollection { 1, 2, 3, 4 } };
_destination = Mapper.Map<Source, Destination>(_source);
}
[Fact]
public void Should_assign_the_value_directly()
{
_source.Values.ShouldEqual(_destination.Values);
}
}
public class When_mapping_to_a_custom_collection_with_the_same_type_not_implementing_IList : SpecBase
{
private Source _source;
private Destination _destination;
public class ValueCollection : IEnumerable<int>
{
private List<int> implementation = new List<int>();
public ValueCollection(IEnumerable<int> items)
{
implementation = items.ToList();
}
public IEnumerator<int> GetEnumerator()
{
return implementation.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return ((IEnumerable)implementation).GetEnumerator();
}
}
public class Source
{
public ValueCollection Values { get; set; }
}
public class Destination
{
public ValueCollection Values { get; set; }
}
protected override void Establish_context()
{
Mapper.CreateMap<Source, Destination>();
_source = new Source { Values = new ValueCollection(new[] { 1, 2, 3, 4 }) };
}
protected override void Because_of()
{
_destination = Mapper.Map<Source, Destination>(_source);
}
[Fact]
public void Should_map_the_list_of_source_items()
{
// here not the EnumerableMapper is used, but just the AssignableMapper!
_destination.Values.ShouldBeSameAs(_source.Values);
_destination.Values.ShouldNotBeNull();
_destination.Values.ShouldContain(1);
_destination.Values.ShouldContain(2);
_destination.Values.ShouldContain(3);
_destination.Values.ShouldContain(4);
}
}
public class When_mapping_to_a_collection_with_instantiation_managed_by_the_destination : AutoMapperSpecBase
{
private Destination _destination;
private Source _source;
public class SourceItem
{
public int Value { get; set; }
}
public class DestItem
{
public int Value { get; set; }
}
public class Source
{
public List<SourceItem> Values { get; set; }
}
public class Destination
{
private List<DestItem> _values = new List<DestItem>();
public List<DestItem> Values
{
get { return _values; }
}
}
protected override void Establish_context()
{
Mapper.CreateMap<Source, Destination>()
.ForMember(dest => dest.Values, opt => opt.UseDestinationValue());
Mapper.CreateMap<SourceItem, DestItem>();
}
protected override void Because_of()
{
_source = new Source { Values = new List<SourceItem> { new SourceItem { Value = 5 }, new SourceItem { Value = 10 } } };
_destination = Mapper.Map<Source, Destination>(_source);
}
[Fact]
public void Should_assign_the_value_directly()
{
_destination.Values.Count.ShouldEqual(2);
_destination.Values[0].Value.ShouldEqual(5);
_destination.Values[1].Value.ShouldEqual(10);
}
}
public class When_mapping_to_an_existing_list_with_existing_items : SpecBase
{
private Destination _destination;
private Source _source;
public class SourceItem
{
public int Value { get; set; }
}
public class DestItem
{
public int Value { get; set; }
}
public class Source
{
public List<SourceItem> Values { get; set; }
}
public class Destination
{
private List<DestItem> _values = new List<DestItem>();
public List<DestItem> Values
{
get { return _values; }
}
}
protected override void Establish_context()
{
Mapper.CreateMap<Source, Destination>()
.ForMember(dest => dest.Values, opt => opt.UseDestinationValue());
Mapper.CreateMap<SourceItem, DestItem>();
}
protected override void Because_of()
{
_source = new Source { Values = new List<SourceItem> { new SourceItem { Value = 5 }, new SourceItem { Value = 10 } } };
_destination = new Destination();
_destination.Values.Add(new DestItem());
Mapper.Map(_source, _destination);
}
[Fact]
public void Should_clear_the_list_before_mapping()
{
_destination.Values.Count.ShouldEqual(2);
}
}
public class When_mapping_a_collection_with_null_members : AutoMapperSpecBase
{
const string FirstString = null;
private IEnumerable<string> _strings;
private List<string> _mappedStrings;
protected override void Establish_context()
{
Mapper.Initialize(x => x.AllowNullDestinationValues = true);
_strings = new List<string> { FirstString };
_mappedStrings = new List<string>();
}
protected override void Because_of()
{
_mappedStrings = Mapper.Map<IEnumerable<string>, List<string>>(_strings);
}
[Fact]
public void Should_map_correctly()
{
_mappedStrings.ShouldNotBeNull();
_mappedStrings.Count.ShouldEqual(1);
_mappedStrings[0].ShouldBeNull();
}
}
#if !SILVERLIGHT && !NETFX_CORE
public class When_destination_collection_is_only_a_list_source_and_not_IList : SpecBase
{
private Destination _destination;
public class CustomCollection : IListSource, IEnumerable<int>
{
private List<int> _customList = new List<int>();
public IList GetList()
{
return _customList;
}
public bool ContainsListCollection
{
get { return true; }
}
IEnumerator<int> IEnumerable<int>.GetEnumerator()
{
return _customList.GetEnumerator();
}
public IEnumerator GetEnumerator()
{
return _customList.GetEnumerator();
}
}
public class Source
{
public int[] Values { get; set; }
}
public class Destination
{
public CustomCollection Values { get; set; }
}
protected override void Establish_context()
{
Mapper.CreateMap<Source, Destination>();
}
protected override void Because_of()
{
_destination = Mapper.Map<Source, Destination>(new Source { Values = new[] { 1, 2, 3 } });
}
[Fact]
public void Should_use_the_underlying_list_to_add_values()
{
_destination.Values.Count().ShouldEqual(3);
}
}
#endif
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using Xunit;
namespace System.Linq.Expressions.Tests
{
public static class ConstantTests
{
#region Test methods
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckBoolConstantTest(bool useInterpreter)
{
foreach (bool value in new bool[] { true, false })
{
VerifyBoolConstant(value, useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckByteConstantTest(bool useInterpreter)
{
foreach (byte value in new byte[] { 0, 1, byte.MaxValue })
{
VerifyByteConstant(value, useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckCustomConstantTest(bool useInterpreter)
{
foreach (C value in new C[] { null, new C(), new D(), new D(0), new D(5) })
{
VerifyCustomConstant(value, useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckCharConstantTest(bool useInterpreter)
{
foreach (char value in new char[] { '\0', '\b', 'A', '\uffff' })
{
VerifyCharConstant(value, useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckCustom2ConstantTest(bool useInterpreter)
{
foreach (D value in new D[] { null, new D(), new D(0), new D(5) })
{
VerifyCustom2Constant(value, useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckDecimalConstantTest(bool useInterpreter)
{
foreach (decimal value in new decimal[] { decimal.Zero, decimal.One, decimal.MinusOne, decimal.MinValue, decimal.MaxValue })
{
VerifyDecimalConstant(value, useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckDelegateConstantTest(bool useInterpreter)
{
foreach (Delegate value in new Delegate[] { null, (Func<object>)delegate () { return null; }, (Func<int, int>)delegate (int i) { return i + 1; }, (Action<object>)delegate { } })
{
VerifyDelegateConstant(value, useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckDoubleConstantTest(bool useInterpreter)
{
foreach (double value in new double[] { 0, 1, -1, double.MinValue, double.MaxValue, double.Epsilon, double.NegativeInfinity, double.PositiveInfinity, double.NaN })
{
VerifyDoubleConstant(value, useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckEnumConstantTest(bool useInterpreter)
{
foreach (E value in new E[] { (E)0, E.A, E.B, (E)int.MaxValue, (E)int.MinValue })
{
VerifyEnumConstant(value, useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckEnumLongConstantTest(bool useInterpreter)
{
foreach (El value in new El[] { (El)0, El.A, El.B, (El)long.MaxValue, (El)long.MinValue })
{
VerifyEnumLongConstant(value, useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckFloatConstantTest(bool useInterpreter)
{
foreach (float value in new float[] { 0, 1, -1, float.MinValue, float.MaxValue, float.Epsilon, float.NegativeInfinity, float.PositiveInfinity, float.NaN })
{
VerifyFloatConstant(value, useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckFuncOfObjectConstantTest(bool useInterpreter)
{
foreach (Func<object> value in new Func<object>[] { null, (Func<object>)delegate () { return null; } })
{
VerifyFuncOfObjectConstant(value, useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckInterfaceConstantTest(bool useInterpreter)
{
foreach (I value in new I[] { null, new C(), new D(), new D(0), new D(5) })
{
VerifyInterfaceConstant(value, useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckIEquatableOfCustomConstantTest(bool useInterpreter)
{
foreach (IEquatable<C> value in new IEquatable<C>[] { null, new C(), new D(), new D(0), new D(5) })
{
VerifyIEquatableOfCustomConstant(value, useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckIEquatableOfCustom2ConstantTest(bool useInterpreter)
{
foreach (IEquatable<D> value in new IEquatable<D>[] { null, new D(), new D(0), new D(5) })
{
VerifyIEquatableOfCustom2Constant(value, useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckIntConstantTest(bool useInterpreter)
{
foreach (int value in new int[] { 0, 1, -1, int.MinValue, int.MaxValue })
{
VerifyIntConstant(value, useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckLongConstantTest(bool useInterpreter)
{
foreach (long value in new long[] { 0, 1, -1, long.MinValue, long.MaxValue })
{
VerifyLongConstant(value, useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckObjectConstantTest(bool useInterpreter)
{
foreach (object value in new object[] { null, new object(), new C(), new D(3) })
{
VerifyObjectConstant(value, useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckStructConstantTest(bool useInterpreter)
{
foreach (S value in new S[] { default(S), new S() })
{
VerifyStructConstant(value, useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckSByteConstantTest(bool useInterpreter)
{
foreach (sbyte value in new sbyte[] { 0, 1, -1, sbyte.MinValue, sbyte.MaxValue })
{
VerifySByteConstant(value, useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckStructWithStringConstantTest(bool useInterpreter)
{
foreach (Sc value in new Sc[] { default(Sc), new Sc(), new Sc(null) })
{
VerifyStructWithStringConstant(value, useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckStructWithStringAndFieldConstantTest(bool useInterpreter)
{
foreach (Scs value in new Scs[] { default(Scs), new Scs(), new Scs(null, new S()) })
{
VerifyStructWithStringAndFieldConstant(value, useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckShortConstantTest(bool useInterpreter)
{
foreach (short value in new short[] { 0, 1, -1, short.MinValue, short.MaxValue })
{
VerifyShortConstant(value, useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckStructWithTwoValuesConstantTest(bool useInterpreter)
{
foreach (Sp value in new Sp[] { default(Sp), new Sp(), new Sp(5, 5.0) })
{
VerifyStructWithTwoValuesConstant(value, useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckStructWithValueConstantTest(bool useInterpreter)
{
foreach (Ss value in new Ss[] { default(Ss), new Ss(), new Ss(new S()) })
{
VerifyStructWithValueConstant(value, useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckStringConstantTest(bool useInterpreter)
{
foreach (string value in new string[] { null, "", "a", "foo" })
{
VerifyStringConstant(value, useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckUIntConstantTest(bool useInterpreter)
{
foreach (uint value in new uint[] { 0, 1, uint.MaxValue })
{
VerifyUIntConstant(value, useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckULongConstantTest(bool useInterpreter)
{
foreach (ulong value in new ulong[] { 0, 1, ulong.MaxValue })
{
VerifyULongConstant(value, useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckUShortConstantTest(bool useInterpreter)
{
foreach (ushort value in new ushort[] { 0, 1, ushort.MaxValue })
{
VerifyUShortConstant(value, useInterpreter);
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckGenericWithStructRestrictionWithEnumConstantTest(bool useInterpreter)
{
CheckGenericWithStructRestrictionConstantHelper<E>(useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckGenericWithStructRestrictionWithStructConstantTest(bool useInterpreter)
{
CheckGenericWithStructRestrictionConstantHelper<S>(useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckGenericWithStructRestrictionWithStructWithStringAndValueConstantTest(bool useInterpreter)
{
CheckGenericWithStructRestrictionConstantHelper<Scs>(useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckGenericWithCustomTest(bool useInterpreter)
{
CheckGenericHelper<C>(useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckGenericWithEnumTest(bool useInterpreter)
{
CheckGenericHelper<E>(useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckGenericWithObjectTest(bool useInterpreter)
{
CheckGenericHelper<object>(useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckGenericWithStructTest(bool useInterpreter)
{
CheckGenericHelper<S>(useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckGenericWithStructWithStringAndValueTest(bool useInterpreter)
{
CheckGenericHelper<Scs>(useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckGenericWithClassRestrictionWithCustomTest(bool useInterpreter)
{
CheckGenericWithClassRestrictionHelper<C>(useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckGenericWithClassRestrictionWithObjectTest(bool useInterpreter)
{
CheckGenericWithClassRestrictionHelper<object>(useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckGenericWithClassAndNewRestrictionWithCustomTest(bool useInterpreter)
{
CheckGenericWithClassAndNewRestrictionHelper<C>(useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckGenericWithClassAndNewRestrictionWithObjectTest(bool useInterpreter)
{
CheckGenericWithClassAndNewRestrictionHelper<object>(useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckGenericWithSubClassRestrictionTest(bool useInterpreter)
{
CheckGenericWithSubClassRestrictionHelper<C>(useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckGenericWithSubClassAndNewRestrictionTest(bool useInterpreter)
{
CheckGenericWithSubClassAndNewRestrictionHelper<C>(useInterpreter);
}
#endregion
#region Generic helpers
public static void CheckGenericWithStructRestrictionConstantHelper<Ts>(bool useInterpreter) where Ts : struct
{
foreach (Ts value in new Ts[] { default(Ts), new Ts() })
{
VerifyGenericWithStructRestriction<Ts>(value, useInterpreter);
}
}
public static void CheckGenericHelper<T>(bool useInterpreter)
{
foreach (T value in new T[] { default(T) })
{
VerifyGeneric<T>(value, useInterpreter);
}
}
public static void CheckGenericWithClassRestrictionHelper<Tc>(bool useInterpreter) where Tc : class
{
foreach (Tc value in new Tc[] { null, default(Tc) })
{
VerifyGenericWithClassRestriction<Tc>(value, useInterpreter);
}
}
public static void CheckGenericWithClassAndNewRestrictionHelper<Tcn>(bool useInterpreter) where Tcn : class, new()
{
foreach (Tcn value in new Tcn[] { null, default(Tcn), new Tcn() })
{
VerifyGenericWithClassAndNewRestriction<Tcn>(value, useInterpreter);
}
}
public static void CheckGenericWithSubClassRestrictionHelper<TC>(bool useInterpreter) where TC : C
{
foreach (TC value in new TC[] { null, default(TC), (TC)new C() })
{
VerifyGenericWithSubClassRestriction<TC>(value, useInterpreter);
}
}
public static void CheckGenericWithSubClassAndNewRestrictionHelper<TCn>(bool useInterpreter) where TCn : C, new()
{
foreach (TCn value in new TCn[] { null, default(TCn), new TCn(), (TCn)new C() })
{
VerifyGenericWithSubClassAndNewRestriction<TCn>(value, useInterpreter);
}
}
#endregion
#region Test verifiers
private static void VerifyBoolConstant(bool value, bool useInterpreter)
{
Expression<Func<bool>> e =
Expression.Lambda<Func<bool>>(
Expression.Constant(value, typeof(bool)),
Enumerable.Empty<ParameterExpression>());
Func<bool> f = e.Compile(useInterpreter);
Assert.Equal(value, f());
}
private static void VerifyByteConstant(byte value, bool useInterpreter)
{
Expression<Func<byte>> e =
Expression.Lambda<Func<byte>>(
Expression.Constant(value, typeof(byte)),
Enumerable.Empty<ParameterExpression>());
Func<byte> f = e.Compile(useInterpreter);
Assert.Equal(value, f());
}
private static void VerifyCustomConstant(C value, bool useInterpreter)
{
Expression<Func<C>> e =
Expression.Lambda<Func<C>>(
Expression.Constant(value, typeof(C)),
Enumerable.Empty<ParameterExpression>());
Func<C> f = e.Compile(useInterpreter);
Assert.Equal(value, f());
}
private static void VerifyCharConstant(char value, bool useInterpreter)
{
Expression<Func<char>> e =
Expression.Lambda<Func<char>>(
Expression.Constant(value, typeof(char)),
Enumerable.Empty<ParameterExpression>());
Func<char> f = e.Compile(useInterpreter);
Assert.Equal(value, f());
}
private static void VerifyCustom2Constant(D value, bool useInterpreter)
{
Expression<Func<D>> e =
Expression.Lambda<Func<D>>(
Expression.Constant(value, typeof(D)),
Enumerable.Empty<ParameterExpression>());
Func<D> f = e.Compile(useInterpreter);
Assert.Equal(value, f());
}
private static void VerifyDecimalConstant(decimal value, bool useInterpreter)
{
Expression<Func<decimal>> e =
Expression.Lambda<Func<decimal>>(
Expression.Constant(value, typeof(decimal)),
Enumerable.Empty<ParameterExpression>());
Func<decimal> f = e.Compile(useInterpreter);
Assert.Equal(value, f());
}
private static void VerifyDelegateConstant(Delegate value, bool useInterpreter)
{
Expression<Func<Delegate>> e =
Expression.Lambda<Func<Delegate>>(
Expression.Constant(value, typeof(Delegate)),
Enumerable.Empty<ParameterExpression>());
Func<Delegate> f = e.Compile(useInterpreter);
Assert.Equal(value, f());
}
private static void VerifyDoubleConstant(double value, bool useInterpreter)
{
Expression<Func<double>> e =
Expression.Lambda<Func<double>>(
Expression.Constant(value, typeof(double)),
Enumerable.Empty<ParameterExpression>());
Func<double> f = e.Compile(useInterpreter);
Assert.Equal(value, f());
}
private static void VerifyEnumConstant(E value, bool useInterpreter)
{
Expression<Func<E>> e =
Expression.Lambda<Func<E>>(
Expression.Constant(value, typeof(E)),
Enumerable.Empty<ParameterExpression>());
Func<E> f = e.Compile(useInterpreter);
Assert.Equal(value, f());
}
private static void VerifyEnumLongConstant(El value, bool useInterpreter)
{
Expression<Func<El>> e =
Expression.Lambda<Func<El>>(
Expression.Constant(value, typeof(El)),
Enumerable.Empty<ParameterExpression>());
Func<El> f = e.Compile(useInterpreter);
Assert.Equal(value, f());
}
private static void VerifyFloatConstant(float value, bool useInterpreter)
{
Expression<Func<float>> e =
Expression.Lambda<Func<float>>(
Expression.Constant(value, typeof(float)),
Enumerable.Empty<ParameterExpression>());
Func<float> f = e.Compile(useInterpreter);
Assert.Equal(value, f());
}
private static void VerifyFuncOfObjectConstant(Func<object> value, bool useInterpreter)
{
Expression<Func<Func<object>>> e =
Expression.Lambda<Func<Func<object>>>(
Expression.Constant(value, typeof(Func<object>)),
Enumerable.Empty<ParameterExpression>());
Func<Func<object>> f = e.Compile(useInterpreter);
Assert.Equal(value, f());
}
private static void VerifyInterfaceConstant(I value, bool useInterpreter)
{
Expression<Func<I>> e =
Expression.Lambda<Func<I>>(
Expression.Constant(value, typeof(I)),
Enumerable.Empty<ParameterExpression>());
Func<I> f = e.Compile(useInterpreter);
Assert.Equal(value, f());
}
private static void VerifyIEquatableOfCustomConstant(IEquatable<C> value, bool useInterpreter)
{
Expression<Func<IEquatable<C>>> e =
Expression.Lambda<Func<IEquatable<C>>>(
Expression.Constant(value, typeof(IEquatable<C>)),
Enumerable.Empty<ParameterExpression>());
Func<IEquatable<C>> f = e.Compile(useInterpreter);
Assert.Equal(value, f());
}
private static void VerifyIEquatableOfCustom2Constant(IEquatable<D> value, bool useInterpreter)
{
Expression<Func<IEquatable<D>>> e =
Expression.Lambda<Func<IEquatable<D>>>(
Expression.Constant(value, typeof(IEquatable<D>)),
Enumerable.Empty<ParameterExpression>());
Func<IEquatable<D>> f = e.Compile(useInterpreter);
Assert.Equal(value, f());
}
private static void VerifyIntConstant(int value, bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.Constant(value, typeof(int)),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(value, f());
}
private static void VerifyLongConstant(long value, bool useInterpreter)
{
Expression<Func<long>> e =
Expression.Lambda<Func<long>>(
Expression.Constant(value, typeof(long)),
Enumerable.Empty<ParameterExpression>());
Func<long> f = e.Compile(useInterpreter);
Assert.Equal(value, f());
}
private static void VerifyObjectConstant(object value, bool useInterpreter)
{
Expression<Func<object>> e =
Expression.Lambda<Func<object>>(
Expression.Constant(value, typeof(object)),
Enumerable.Empty<ParameterExpression>());
Func<object> f = e.Compile(useInterpreter);
Assert.Equal(value, f());
}
private static void VerifyStructConstant(S value, bool useInterpreter)
{
Expression<Func<S>> e =
Expression.Lambda<Func<S>>(
Expression.Constant(value, typeof(S)),
Enumerable.Empty<ParameterExpression>());
Func<S> f = e.Compile(useInterpreter);
Assert.Equal(value, f());
}
private static void VerifySByteConstant(sbyte value, bool useInterpreter)
{
Expression<Func<sbyte>> e =
Expression.Lambda<Func<sbyte>>(
Expression.Constant(value, typeof(sbyte)),
Enumerable.Empty<ParameterExpression>());
Func<sbyte> f = e.Compile(useInterpreter);
Assert.Equal(value, f());
}
private static void VerifyStructWithStringConstant(Sc value, bool useInterpreter)
{
Expression<Func<Sc>> e =
Expression.Lambda<Func<Sc>>(
Expression.Constant(value, typeof(Sc)),
Enumerable.Empty<ParameterExpression>());
Func<Sc> f = e.Compile(useInterpreter);
Assert.Equal(value, f());
}
private static void VerifyStructWithStringAndFieldConstant(Scs value, bool useInterpreter)
{
Expression<Func<Scs>> e =
Expression.Lambda<Func<Scs>>(
Expression.Constant(value, typeof(Scs)),
Enumerable.Empty<ParameterExpression>());
Func<Scs> f = e.Compile(useInterpreter);
Assert.Equal(value, f());
}
private static void VerifyShortConstant(short value, bool useInterpreter)
{
Expression<Func<short>> e =
Expression.Lambda<Func<short>>(
Expression.Constant(value, typeof(short)),
Enumerable.Empty<ParameterExpression>());
Func<short> f = e.Compile(useInterpreter);
Assert.Equal(value, f());
}
private static void VerifyStructWithTwoValuesConstant(Sp value, bool useInterpreter)
{
Expression<Func<Sp>> e =
Expression.Lambda<Func<Sp>>(
Expression.Constant(value, typeof(Sp)),
Enumerable.Empty<ParameterExpression>());
Func<Sp> f = e.Compile(useInterpreter);
Assert.Equal(value, f());
}
private static void VerifyStructWithValueConstant(Ss value, bool useInterpreter)
{
Expression<Func<Ss>> e =
Expression.Lambda<Func<Ss>>(
Expression.Constant(value, typeof(Ss)),
Enumerable.Empty<ParameterExpression>());
Func<Ss> f = e.Compile(useInterpreter);
Assert.Equal(value, f());
}
private static void VerifyStringConstant(string value, bool useInterpreter)
{
Expression<Func<string>> e =
Expression.Lambda<Func<string>>(
Expression.Constant(value, typeof(string)),
Enumerable.Empty<ParameterExpression>());
Func<string> f = e.Compile(useInterpreter);
Assert.Equal(value, f());
}
private static void VerifyUIntConstant(uint value, bool useInterpreter)
{
Expression<Func<uint>> e =
Expression.Lambda<Func<uint>>(
Expression.Constant(value, typeof(uint)),
Enumerable.Empty<ParameterExpression>());
Func<uint> f = e.Compile(useInterpreter);
Assert.Equal(value, f());
}
private static void VerifyULongConstant(ulong value, bool useInterpreter)
{
Expression<Func<ulong>> e =
Expression.Lambda<Func<ulong>>(
Expression.Constant(value, typeof(ulong)),
Enumerable.Empty<ParameterExpression>());
Func<ulong> f = e.Compile(useInterpreter);
Assert.Equal(value, f());
}
private static void VerifyUShortConstant(ushort value, bool useInterpreter)
{
Expression<Func<ushort>> e =
Expression.Lambda<Func<ushort>>(
Expression.Constant(value, typeof(ushort)),
Enumerable.Empty<ParameterExpression>());
Func<ushort> f = e.Compile(useInterpreter);
Assert.Equal(value, f());
}
private static void VerifyGenericWithStructRestriction<Ts>(Ts value, bool useInterpreter) where Ts : struct
{
Expression<Func<Ts>> e =
Expression.Lambda<Func<Ts>>(
Expression.Constant(value, typeof(Ts)),
Enumerable.Empty<ParameterExpression>());
Func<Ts> f = e.Compile(useInterpreter);
Assert.Equal(value, f());
}
private static void VerifyGeneric<T>(T value, bool useInterpreter)
{
Expression<Func<T>> e =
Expression.Lambda<Func<T>>(
Expression.Constant(value, typeof(T)),
Enumerable.Empty<ParameterExpression>());
Func<T> f = e.Compile(useInterpreter);
Assert.Equal(value, f());
}
private static void VerifyGenericWithClassRestriction<Tc>(Tc value, bool useInterpreter) where Tc : class
{
Expression<Func<Tc>> e =
Expression.Lambda<Func<Tc>>(
Expression.Constant(value, typeof(Tc)),
Enumerable.Empty<ParameterExpression>());
Func<Tc> f = e.Compile(useInterpreter);
Assert.Equal(value, f());
}
private static void VerifyGenericWithClassAndNewRestriction<Tcn>(Tcn value, bool useInterpreter) where Tcn : class, new()
{
Expression<Func<Tcn>> e =
Expression.Lambda<Func<Tcn>>(
Expression.Constant(value, typeof(Tcn)),
Enumerable.Empty<ParameterExpression>());
Func<Tcn> f = e.Compile(useInterpreter);
Assert.Equal(value, f());
}
private static void VerifyGenericWithSubClassRestriction<TC>(TC value, bool useInterpreter) where TC : C
{
Expression<Func<TC>> e =
Expression.Lambda<Func<TC>>(
Expression.Constant(value, typeof(TC)),
Enumerable.Empty<ParameterExpression>());
Func<TC> f = e.Compile(useInterpreter);
Assert.Equal(value, f());
}
private static void VerifyGenericWithSubClassAndNewRestriction<TCn>(TCn value, bool useInterpreter) where TCn : C, new()
{
Expression<Func<TCn>> e =
Expression.Lambda<Func<TCn>>(
Expression.Constant(value, typeof(TCn)),
Enumerable.Empty<ParameterExpression>());
Func<TCn> f = e.Compile(useInterpreter);
Assert.Equal(value, f());
}
#endregion
[Fact]
public static void InvalidTypeValueType()
{
// implicit cast, but not reference assignable.
Assert.Throws<ArgumentException>(() => Expression.Constant(0, typeof(long)));
}
[Fact]
public static void InvalidTypeReferenceType()
{
Assert.Throws<ArgumentException>(() => Expression.Constant("hello", typeof(Expression)));
}
}
}
| |
/********************************************************************
The Multiverse Platform is made available under the MIT License.
Copyright (c) 2012 The Multiverse Foundation
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify,
merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
OR OTHER DEALINGS IN THE SOFTWARE.
*********************************************************************/
namespace Multiverse.Tools.TerrainGenerator
{
partial class NewHeightmapDialog
{
/// <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.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.heightmapDefaultHeightUpDown = new System.Windows.Forms.NumericUpDown();
this.heightmapWidthUpDown = new System.Windows.Forms.NumericUpDown();
this.heightmapHeightUpDown = new System.Windows.Forms.NumericUpDown();
this.heightmapCancelButton = new System.Windows.Forms.Button();
this.heightmapCreateButton = new System.Windows.Forms.Button();
this.centerHeightmapCheckbox = new System.Windows.Forms.CheckBox();
this.heightmapMetersPerSampleLabel = new System.Windows.Forms.Label();
this.heightmapMetersPerSampleUpDown = new System.Windows.Forms.NumericUpDown();
((System.ComponentModel.ISupportInitialize)(this.heightmapDefaultHeightUpDown)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.heightmapWidthUpDown)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.heightmapHeightUpDown)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.heightmapMetersPerSampleUpDown)).BeginInit();
this.SuspendLayout();
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(29, 29);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(151, 13);
this.label1.TabIndex = 0;
this.label1.Text = "Heightmap X Size (East/West)";
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(29, 65);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(159, 13);
this.label2.TabIndex = 1;
this.label2.Text = "Heightmap Z Size (North/South)";
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(29, 99);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(105, 13);
this.label3.TabIndex = 4;
this.label3.Text = "Default Height Value";
//
// heightmapDefaultHeightUpDown
//
this.heightmapDefaultHeightUpDown.DecimalPlaces = 2;
this.heightmapDefaultHeightUpDown.Increment = new decimal(new int[] {
1,
0,
0,
131072});
this.heightmapDefaultHeightUpDown.Location = new System.Drawing.Point(218, 97);
this.heightmapDefaultHeightUpDown.Maximum = new decimal(new int[] {
1,
0,
0,
0});
this.heightmapDefaultHeightUpDown.Name = "heightmapDefaultHeightUpDown";
this.heightmapDefaultHeightUpDown.Size = new System.Drawing.Size(120, 20);
this.heightmapDefaultHeightUpDown.TabIndex = 5;
//
// heightmapWidthUpDown
//
this.heightmapWidthUpDown.Location = new System.Drawing.Point(218, 27);
this.heightmapWidthUpDown.Name = "heightmapWidthUpDown";
this.heightmapWidthUpDown.Size = new System.Drawing.Size(120, 20);
this.heightmapWidthUpDown.TabIndex = 6;
this.heightmapWidthUpDown.Value = new decimal(new int[] {
50,
0,
0,
0});
//
// heightmapHeightUpDown
//
this.heightmapHeightUpDown.Location = new System.Drawing.Point(218, 63);
this.heightmapHeightUpDown.Name = "heightmapHeightUpDown";
this.heightmapHeightUpDown.Size = new System.Drawing.Size(120, 20);
this.heightmapHeightUpDown.TabIndex = 7;
this.heightmapHeightUpDown.Value = new decimal(new int[] {
80,
0,
0,
0});
//
// heightmapCancelButton
//
this.heightmapCancelButton.Location = new System.Drawing.Point(263, 205);
this.heightmapCancelButton.Name = "heightmapCancelButton";
this.heightmapCancelButton.Size = new System.Drawing.Size(75, 23);
this.heightmapCancelButton.TabIndex = 8;
this.heightmapCancelButton.Text = "Cancel";
this.heightmapCancelButton.UseVisualStyleBackColor = true;
this.heightmapCancelButton.Click += new System.EventHandler(this.heightmapCancelButton_Click);
//
// heightmapCreateButton
//
this.heightmapCreateButton.Location = new System.Drawing.Point(158, 205);
this.heightmapCreateButton.Name = "heightmapCreateButton";
this.heightmapCreateButton.Size = new System.Drawing.Size(75, 23);
this.heightmapCreateButton.TabIndex = 9;
this.heightmapCreateButton.Text = "Create";
this.heightmapCreateButton.UseVisualStyleBackColor = true;
this.heightmapCreateButton.Click += new System.EventHandler(this.heightmapCreateButton_Click);
//
// centerHeightmapCheckbox
//
this.centerHeightmapCheckbox.AutoSize = true;
this.centerHeightmapCheckbox.Checked = true;
this.centerHeightmapCheckbox.CheckState = System.Windows.Forms.CheckState.Checked;
this.centerHeightmapCheckbox.Location = new System.Drawing.Point(32, 169);
this.centerHeightmapCheckbox.Name = "centerHeightmapCheckbox";
this.centerHeightmapCheckbox.Size = new System.Drawing.Size(156, 17);
this.centerHeightmapCheckbox.TabIndex = 11;
this.centerHeightmapCheckbox.Text = "Center Heightmap on Origin";
this.centerHeightmapCheckbox.UseVisualStyleBackColor = true;
//
// heightmapMetersPerSampleLabel
//
this.heightmapMetersPerSampleLabel.AutoSize = true;
this.heightmapMetersPerSampleLabel.Location = new System.Drawing.Point(29, 134);
this.heightmapMetersPerSampleLabel.Name = "heightmapMetersPerSampleLabel";
this.heightmapMetersPerSampleLabel.Size = new System.Drawing.Size(150, 13);
this.heightmapMetersPerSampleLabel.TabIndex = 12;
this.heightmapMetersPerSampleLabel.Text = "Heightmap Meters Per Sample";
//
// heightmapMetersPerSampleUpDown
//
this.heightmapMetersPerSampleUpDown.Location = new System.Drawing.Point(218, 132);
this.heightmapMetersPerSampleUpDown.Maximum = new decimal(new int[] {
512,
0,
0,
0});
this.heightmapMetersPerSampleUpDown.Name = "heightmapMetersPerSampleUpDown";
this.heightmapMetersPerSampleUpDown.Size = new System.Drawing.Size(120, 20);
this.heightmapMetersPerSampleUpDown.TabIndex = 13;
this.heightmapMetersPerSampleUpDown.Value = new decimal(new int[] {
128,
0,
0,
0});
//
// NewHeightmapDialog
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(371, 254);
this.Controls.Add(this.heightmapMetersPerSampleUpDown);
this.Controls.Add(this.heightmapMetersPerSampleLabel);
this.Controls.Add(this.centerHeightmapCheckbox);
this.Controls.Add(this.heightmapCreateButton);
this.Controls.Add(this.heightmapCancelButton);
this.Controls.Add(this.heightmapHeightUpDown);
this.Controls.Add(this.heightmapWidthUpDown);
this.Controls.Add(this.heightmapDefaultHeightUpDown);
this.Controls.Add(this.label3);
this.Controls.Add(this.label2);
this.Controls.Add(this.label1);
this.Name = "NewHeightmapDialog";
this.ShowInTaskbar = false;
this.Text = "Create a new Seed Heightmap";
((System.ComponentModel.ISupportInitialize)(this.heightmapDefaultHeightUpDown)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.heightmapWidthUpDown)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.heightmapHeightUpDown)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.heightmapMetersPerSampleUpDown)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.NumericUpDown heightmapDefaultHeightUpDown;
private System.Windows.Forms.NumericUpDown heightmapWidthUpDown;
private System.Windows.Forms.NumericUpDown heightmapHeightUpDown;
private System.Windows.Forms.Button heightmapCancelButton;
private System.Windows.Forms.Button heightmapCreateButton;
private System.Windows.Forms.CheckBox centerHeightmapCheckbox;
private System.Windows.Forms.Label heightmapMetersPerSampleLabel;
private System.Windows.Forms.NumericUpDown heightmapMetersPerSampleUpDown;
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections;
using System.Collections.Specialized;
using System.Text;
using gov.va.medora.mdo.dao;
using gov.va.medora.mdo.exceptions;
namespace gov.va.medora.mdo
{
public class HospitalLocation
{
string id;
string name;
string abbr;
string type;
KeyValuePair<string, string> typeExtension;
KeyValuePair<string, string> institution;
KeyValuePair<string, string> division;
KeyValuePair<string, string> module;
string dispositionAction;
string visitLocation;
KeyValuePair<string, string> stopCode;
KeyValuePair<string, string> department;
KeyValuePair<string, string> service;
KeyValuePair<string, string> specialty;
string physicalLocation;
KeyValuePair<string, string> wardLocation;
KeyValuePair<string, string> principalClinic;
Site facility;
string building;
string floor;
string room;
string bed;
string status;
string phone;
string appointmentTimestamp;
bool _askForCheckIn; // file 44 field 24
string _appointmentLength; // file 44 field 1912
string _clinicDisplayStartTime; // file 44, field 1914
string _displayIncrements; // file 44, field 1917
IList<TimeSlot> _availability;
const string DAO_NAME = "ILocationDao";
public IList<TimeSlot> Availability
{
get { return _availability; }
set { _availability = value; }
}
public string ClinicDisplayStartTime
{
get { return _clinicDisplayStartTime; }
set { _clinicDisplayStartTime = value; }
}
public string DisplayIncrements
{
get { return _displayIncrements; }
set { _displayIncrements = value; }
}
public string AppointmentLength
{
get { return _appointmentLength; }
set { _appointmentLength = value; }
}
public bool AskForCheckIn
{
get { return _askForCheckIn; }
set { _askForCheckIn = value; }
}
public HospitalLocation(string id, string name)
{
Id = id;
Name = name;
}
public HospitalLocation() {}
public string Id
{
get { return id; }
set { id = value; }
}
public string Name
{
get { return name; }
set { name = value; }
}
public string Abbr
{
get { return abbr; }
set { abbr = value; }
}
public string Type
{
get { return type; }
set { type = value; }
}
public KeyValuePair<string, string> TypeExtension
{
get { return typeExtension; }
set { typeExtension = value; }
}
public KeyValuePair<string, string> Institution
{
get { return institution; }
set { institution = value; }
}
public KeyValuePair<string, string> Division
{
get { return division; }
set { division = value; }
}
public KeyValuePair<string, string> Module
{
get { return module; }
set { module = value; }
}
public string DispositionAction
{
get { return dispositionAction; }
set { dispositionAction = value; }
}
public string VisitLocation
{
get { return visitLocation; }
set { visitLocation = value; }
}
public KeyValuePair<string, string> StopCode
{
get { return stopCode; }
set { stopCode = value; }
}
public KeyValuePair<string, string> Department
{
get { return department; }
set { department = value; }
}
public KeyValuePair<string, string> Service
{
get { return service; }
set { service = value; }
}
public KeyValuePair<string, string> Specialty
{
get { return specialty; }
set { specialty = value; }
}
public string PhysicalLocation
{
get { return physicalLocation; }
set { physicalLocation = value; }
}
public KeyValuePair<string, string> WardLocation
{
get { return wardLocation; }
set { wardLocation = value; }
}
public KeyValuePair<string, string> PrincipalClinic
{
get { return principalClinic; }
set { principalClinic = value; }
}
public Site Facility
{
get { return facility; }
set { facility = value; }
}
public string Building
{
get { return building; }
set { building = value; }
}
public string Floor
{
get { return floor; }
set { floor = value; }
}
public string Room
{
get { return room; }
set { room = value; }
}
public string Bed
{
get { return bed; }
set { bed = value; }
}
public string Status
{
get { return status; }
set { status = value; }
}
public string Phone
{
get { return phone; }
set { phone = value; }
}
public string AppointmentTimestamp
{
get { return appointmentTimestamp; }
set { appointmentTimestamp = value; }
}
internal static ILocationDao getDao(AbstractConnection cxn)
{
if (!cxn.IsConnected)
{
throw new MdoException(MdoExceptionCode.USAGE_NO_CONNECTION, "Unable to instantiate DAO: unconnected");
}
AbstractDaoFactory f = AbstractDaoFactory.getDaoFactory(AbstractDaoFactory.getConstant(cxn.DataSource.Protocol));
return f.getLocationDao(cxn);
}
public static List<SiteId> getSitesForStation(AbstractConnection cxn)
{
return getDao(cxn).getSitesForStation();
}
public static OrderedDictionary getClinicsByName(AbstractConnection cxn, string name)
{
return getDao(cxn).getClinicsByName(name);
}
public static List<Site> getAllInstitutions(AbstractConnection cxn)
{
return getDao(cxn).getAllInstitutions();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Baseline;
using LamarCodeGeneration;
namespace Marten.Events.TestSupport
{
public partial class ProjectionScenario
{
/// <summary>
/// Make any number of append event operations in the scenario sequence
/// </summary>
/// <param name="description">Descriptive explanation of the action in case of failures</param>
/// <param name="appendAction"></param>
public void AppendEvents(string description, Action<IEventOperations> appendAction)
{
action(appendAction).Description = description;
}
/// <summary>
/// Make any number of append event operations in the scenario sequence
/// </summary>
/// <param name="appendAction"></param>
public void AppendEvents(Action<IEventOperations> appendAction)
{
AppendEvents("Appending events...", appendAction);
}
public StreamAction Append(Guid stream, IEnumerable<object> events)
{
var step = action(e => e.Append(stream, events));
if (events.Count() > 3)
{
step.Description = $"Append({stream}, events)";
}
else
{
step.Description = $"Append({stream}, {events.Select(x => x.ToString()).Join(", ")})";
}
return StreamAction.Append(_store.Events, stream, events);
}
public StreamAction Append(Guid stream, params object[] events)
{
var step = action(e => e.Append(stream, events));
if (events.Count() > 3)
{
step.Description = $"Append({stream}, events)";
}
else
{
step.Description = $"Append({stream}, {events.Select(x => x.ToString()).Join(", ")})";
}
return StreamAction.Append(_store.Events, stream, events);
}
public StreamAction Append(string stream, IEnumerable<object> events)
{
var step = action(e => e.Append(stream, events));
if (events.Count() > 3)
{
step.Description = $"Append('{stream}', events)";
}
else
{
step.Description = $"Append('{stream}', {events.Select(x => x.ToString()).Join(", ")})";
}
return StreamAction.Append(_store.Events, stream, events);
}
public StreamAction Append(string stream, params object[] events)
{
var step = action(e => e.Append(stream, events));
if (events.Count() > 3)
{
step.Description = $"Append('{stream}', events)";
}
else
{
step.Description = $"Append('{stream}', {events.Select(x => x.ToString()).Join(", ")})";
}
return StreamAction.Append(_store.Events, stream, events);
}
public StreamAction Append(Guid stream, long expectedVersion, params object[] events)
{
var step = action(e => e.Append(stream, expectedVersion, events));
if (events.Count() > 3)
{
step.Description = $"Append({stream}, {expectedVersion}, events)";
}
else
{
step.Description =
$"Append({stream}, {expectedVersion}, {events.Select(x => x.ToString()).Join(", ")})";
}
return StreamAction.Append(_store.Events, stream, events);
}
public StreamAction Append(string stream, long expectedVersion, IEnumerable<object> events)
{
var step = action(e => e.Append(stream, expectedVersion, events));
if (events.Count() > 3)
{
step.Description = $"Append(\"{stream}\", {expectedVersion}, events)";
}
else
{
step.Description =
$"Append(\"{stream}\", {expectedVersion}, {events.Select(x => x.ToString()).Join(", ")})";
}
return StreamAction.Append(_store.Events, stream, events);
}
public StreamAction Append(string stream, long expectedVersion, params object[] events)
{
var step = action(e => e.Append(stream, expectedVersion, events));
if (events.Count() > 3)
{
step.Description = $"Append(\"{stream}\", {expectedVersion}, events)";
}
else
{
step.Description =
$"Append(\"{stream}\", {expectedVersion}, {events.Select(x => x.ToString()).Join(", ")})";
}
return StreamAction.Append(_store.Events, stream, events);
}
public StreamAction StartStream<TAggregate>(Guid id, params object[] events) where TAggregate : class
{
var step = action(e => e.StartStream<TAggregate>(id, events));
if (events.Count() > 3)
{
step.Description = $"StartStream<{typeof(TAggregate).FullNameInCode()}>({id}, events)";
}
else
{
step.Description =
$"StartStream<{typeof(TAggregate).FullNameInCode()}>({id}, {events.Select(x => x.ToString()).Join(", ")})";
}
return StreamAction.Start(_store.Events, id, events);
}
public StreamAction StartStream(Type aggregateType, Guid id, IEnumerable<object> events)
{
var step = action(e => e.StartStream(aggregateType, id, events));
if (events.Count() > 3)
{
step.Description = $"StartStream({aggregateType.FullNameInCode()}>({id}, events)";
}
else
{
step.Description =
$"StartStream({aggregateType.FullNameInCode()}, {id}, {events.Select(x => x.ToString()).Join(", ")})";
}
return StreamAction.Start(_store.Events, id, events);
}
public StreamAction StartStream(Type aggregateType, Guid id, params object[] events)
{
var step = action(e => e.StartStream(aggregateType, id, events));
if (events.Count() > 3)
{
step.Description = $"StartStream({aggregateType.FullNameInCode()}>({id}, events)";
}
else
{
step.Description =
$"StartStream({aggregateType.FullNameInCode()}, {id}, {events.Select(x => x.ToString()).Join(", ")})";
}
return StreamAction.Start(_store.Events, id, events);
}
public StreamAction StartStream<TAggregate>(string streamKey, IEnumerable<object> events)
where TAggregate : class
{
var step = action(e => e.StartStream<TAggregate>(streamKey, events));
if (events.Count() > 3)
{
step.Description = $"StartStream<{typeof(TAggregate).FullNameInCode()}>(\"{streamKey}\", events)";
}
else
{
step.Description =
$"StartStream<{typeof(TAggregate).FullNameInCode()}>(\"{streamKey}\", {events.Select(x => x.ToString()).Join(", ")})";
}
return StreamAction.Start(_store.Events, streamKey, events);
}
public StreamAction StartStream<TAggregate>(string streamKey, params object[] events) where TAggregate : class
{
var step = action(e => e.StartStream<TAggregate>(streamKey, events));
if (events.Count() > 3)
{
step.Description = $"StartStream<{typeof(TAggregate).FullNameInCode()}>(\"{streamKey}\", events)";
}
else
{
step.Description =
$"StartStream<{typeof(TAggregate).FullNameInCode()}>(\"{streamKey}\", {events.Select(x => x.ToString()).Join(", ")})";
}
return StreamAction.Start(_store.Events, streamKey, events);
}
public StreamAction StartStream(Type aggregateType, string streamKey, IEnumerable<object> events)
{
var step = action(e => e.StartStream(aggregateType, streamKey, events));
if (events.Count() > 3)
{
step.Description = $"StartStream({aggregateType.FullNameInCode()}>(\"{streamKey}\", events)";
}
else
{
step.Description =
$"StartStream({aggregateType.FullNameInCode()}, \"{streamKey}\", {events.Select(x => x.ToString()).Join(", ")})";
}
return StreamAction.Start(_store.Events, streamKey, events);
}
public StreamAction StartStream(Type aggregateType, string streamKey, params object[] events)
{
var step = action(e => e.StartStream(aggregateType, streamKey, events));
if (events.Count() > 3)
{
step.Description = $"StartStream({aggregateType.FullNameInCode()}>(\"{streamKey}\", events)";
}
else
{
step.Description =
$"StartStream({aggregateType.FullNameInCode()}, \"{streamKey}\", {events.Select(x => x.ToString()).Join(", ")})";
}
return StreamAction.Start(_store.Events, streamKey, events);
}
public StreamAction StartStream(Guid id, IEnumerable<object> events)
{
var step = action(e => e.StartStream(id, events));
if (events.Count() > 3)
{
step.Description = $"StartStream({id}, events)";
}
else
{
step.Description = $"StartStream({id}, {events.Select(x => x.ToString()).Join(", ")})";
}
return StreamAction.Start(_store.Events, id, events);
}
public StreamAction StartStream(Guid id, params object[] events)
{
var step = action(e => e.StartStream(id, events));
if (events.Count() > 3)
{
step.Description = $"StartStream({id}, events)";
}
else
{
step.Description = $"StartStream({id}, {events.Select(x => x.ToString()).Join(", ")})";
}
return StreamAction.Start(_store.Events, id, events);
}
public StreamAction StartStream(string streamKey, IEnumerable<object> events)
{
var step = action(e => e.StartStream(streamKey, events));
if (events.Count() > 3)
{
step.Description = $"StartStream(\"{streamKey}\", events)";
}
else
{
step.Description = $"StartStream(\"{streamKey}\", {events.Select(x => x.ToString()).Join(", ")})";
}
return StreamAction.Start(_store.Events, streamKey, events);
}
public StreamAction StartStream(string streamKey, params object[] events)
{
var step = action(e => e.StartStream(streamKey, events));
if (events.Count() > 3)
{
step.Description = $"StartStream(\"{streamKey}\", events)";
}
else
{
step.Description = $"StartStream(\"{streamKey}\", {events.Select(x => x.ToString()).Join(", ")})";
}
return StreamAction.Start(_store.Events, streamKey, events);
}
public StreamAction StartStream<TAggregate>(IEnumerable<object> events) where TAggregate : class
{
var streamId = Guid.NewGuid();
var step = action(e => e.StartStream<TAggregate>(streamId, events));
if (events.Count() > 3)
{
step.Description = $"StartStream<{typeof(TAggregate).FullNameInCode()}>(events)";
}
else
{
step.Description =
$"StartStream<{typeof(TAggregate).FullNameInCode()}>({events.Select(x => x.ToString()).Join(", ")})";
}
return StreamAction.Start(_store.Events, streamId, events);
}
public StreamAction StartStream<TAggregate>(params object[] events) where TAggregate : class
{
var streamId = Guid.NewGuid();
var step = action(e => e.StartStream<TAggregate>(streamId, events));
if (events.Count() > 3)
{
step.Description = $"StartStream<{typeof(TAggregate).FullNameInCode()}>(events)";
}
else
{
step.Description =
$"StartStream<{typeof(TAggregate).FullNameInCode()}>({events.Select(x => x.ToString()).Join(", ")})";
}
return StreamAction.Start(_store.Events, streamId, events);
}
public StreamAction StartStream(Type aggregateType, IEnumerable<object> events)
{
var streamId = Guid.NewGuid();
var step = action(e => e.StartStream(aggregateType, streamId, events));
if (events.Count() > 3)
{
step.Description = $"StartStream({aggregateType.FullNameInCode()}>(events)";
}
else
{
step.Description =
$"StartStream({aggregateType.FullNameInCode()}, {events.Select(x => x.ToString()).Join(", ")})";
}
return StreamAction.Start(_store.Events, streamId, events);
}
public StreamAction StartStream(Type aggregateType, params object[] events)
{
var streamId = Guid.NewGuid();
var step = action(e => e.StartStream(aggregateType, streamId, events));
if (events.Count() > 3)
{
step.Description = $"StartStream({aggregateType.FullNameInCode()}>(events)";
}
else
{
step.Description =
$"StartStream({aggregateType.FullNameInCode()}, {events.Select(x => x.ToString()).Join(", ")})";
}
return StreamAction.Start(_store.Events, streamId, events);
}
public StreamAction StartStream(IEnumerable<object> events)
{
var streamId = Guid.NewGuid();
var step = action(e => e.StartStream(streamId, events));
if (events.Count() > 3)
{
step.Description = "StartStream(events)";
}
else
{
step.Description = $"StartStream({events.Select(x => x.ToString()).Join(", ")})";
}
return StreamAction.Start(_store.Events, streamId, events);
}
public StreamAction StartStream(params object[] events)
{
var streamId = Guid.NewGuid();
var step = action(e => e.StartStream(streamId, events));
if (events.Count() > 3)
{
step.Description = "StartStream(events)";
}
else
{
step.Description = $"StartStream({events.Select(x => x.ToString()).Join(", ")})";
}
return StreamAction.Start(_store.Events, streamId, events);
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Microsoft.Win32;
using Microsoft.Win32.SafeHandles;
using System;
using System.Runtime.InteropServices;
using System.Text;
internal static partial class Interop
{
internal const int KEY_QUERY_VALUE = 0x0001;
internal const int KEY_SET_VALUE = 0x0002;
internal const int KEY_CREATE_SUB_KEY = 0x0004;
internal const int KEY_ENUMERATE_SUB_KEYS = 0x0008;
internal const int KEY_NOTIFY = 0x0010;
internal const int KEY_CREATE_LINK = 0x0020;
internal const int KEY_READ = ((STANDARD_RIGHTS_READ |
KEY_QUERY_VALUE |
KEY_ENUMERATE_SUB_KEYS |
KEY_NOTIFY)
&
(~SYNCHRONIZE));
internal const int KEY_WRITE = ((STANDARD_RIGHTS_WRITE |
KEY_SET_VALUE |
KEY_CREATE_SUB_KEY)
&
(~SYNCHRONIZE));
internal const int KEY_WOW64_64KEY = 0x0100;
internal const int KEY_WOW64_32KEY = 0x0200;
internal const int REG_OPTION_NON_VOLATILE = 0x0000; // (default) keys are persisted beyond reboot/unload
internal const int REG_OPTION_VOLATILE = 0x0001; // All keys created by the function are volatile
internal const int REG_OPTION_CREATE_LINK = 0x0002; // They key is a symbolic link
internal const int REG_OPTION_BACKUP_RESTORE = 0x0004; // Use SE_BACKUP_NAME process special privileges
internal const int REG_NONE = 0; // No value type
internal const int REG_SZ = 1; // Unicode nul terminated string
internal const int REG_EXPAND_SZ = 2; // Unicode nul terminated string
// (with environment variable references)
internal const int REG_BINARY = 3; // Free form binary
internal const int REG_DWORD = 4; // 32-bit number
internal const int REG_DWORD_LITTLE_ENDIAN = 4; // 32-bit number (same as REG_DWORD)
internal const int REG_DWORD_BIG_ENDIAN = 5; // 32-bit number
internal const int REG_LINK = 6; // Symbolic Link (unicode)
internal const int REG_MULTI_SZ = 7; // Multiple Unicode strings
internal const int REG_QWORD = 11; // 64-bit number
// Win32 ACL-related constants:
internal const int READ_CONTROL = 0x00020000;
internal const int SYNCHRONIZE = 0x00100000;
internal const int STANDARD_RIGHTS_READ = READ_CONTROL;
internal const int STANDARD_RIGHTS_WRITE = READ_CONTROL;
internal const String LOCALIZATION_L1_APISET = "api-ms-win-core-localization-l1-2-0.dll";
internal const String REGISTRY_L1_APISET = "api-ms-win-core-registry-l1-1-0.dll";
internal const String REGISTRY_L2_APISET = "api-ms-win-core-registry-l2-1-0.dll";
internal const String PROCESSENVIRONMENT_L1_APISET = "api-ms-win-core-processenvironment-l1-1-0.dll";
// From WinBase.h
internal const int SEM_FAILCRITICALERRORS = 1;
private const int FORMAT_MESSAGE_IGNORE_INSERTS = 0x00000200;
private const int FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000;
private const int FORMAT_MESSAGE_ARGUMENT_ARRAY = 0x00002000;
// Error codes from WinError.h
internal const int ERROR_SUCCESS = 0x0;
internal const int ERROR_FILE_NOT_FOUND = 0x2;
internal const int ERROR_ACCESS_DENIED = 0x5;
internal const int ERROR_INVALID_HANDLE = 0x6;
internal const int ERROR_FILENAME_EXCED_RANGE = 0xCE; // filename too long.
internal const int ERROR_MORE_DATA = 0xEA;
internal const int ERROR_DLL_INIT_FAILED = 0x45A;
internal const int ERROR_BAD_IMPERSONATION_LEVEL = 0x542;
// Error codes from ntstatus.h
internal const uint STATUS_ACCESS_DENIED = 0xC0000022;
internal static partial class mincore
{
// Gets an error message for a Win32 error code.
internal static String GetMessage(int errorCode)
{
char[] buffer = new char[512];
uint result = Interop.mincore.FormatMessage(FORMAT_MESSAGE_IGNORE_INSERTS |
FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ARGUMENT_ARRAY,
IntPtr.Zero, (uint)errorCode, 0, buffer, (uint)buffer.Length, IntPtr.Zero);
if (result != 0)
{
return new string(buffer, 0, (int)result);
}
else
{
return SR.Format(SR.UnknownError_Num, errorCode);
}
}
[DllImport(REGISTRY_L2_APISET, CharSet = CharSet.Unicode, BestFitMapping = false, EntryPoint = "RegConnectRegistryW")]
internal static extern int RegConnectRegistry(String machineName,
SafeRegistryHandle key, out SafeRegistryHandle result);
// Note: RegCreateKeyEx won't set the last error on failure - it returns
// an error code if it fails.
[DllImport(REGISTRY_L1_APISET, CharSet = CharSet.Unicode, BestFitMapping = false, EntryPoint = "RegCreateKeyExW")]
internal static extern int RegCreateKeyEx(SafeRegistryHandle hKey, String lpSubKey,
int Reserved, String lpClass, int dwOptions,
int samDesired, ref SECURITY_ATTRIBUTES secAttrs,
out SafeRegistryHandle hkResult, out int lpdwDisposition);
[DllImport(REGISTRY_L1_APISET, CharSet = CharSet.Unicode, BestFitMapping = false, EntryPoint = "RegDeleteKeyExW")]
internal static extern int RegDeleteKeyEx(SafeRegistryHandle hKey, String lpSubKey,
int samDesired, int Reserved);
[DllImport(REGISTRY_L1_APISET, CharSet = CharSet.Unicode, BestFitMapping = false, EntryPoint = "RegDeleteValueW")]
internal static extern int RegDeleteValue(SafeRegistryHandle hKey, String lpValueName);
[DllImport(REGISTRY_L1_APISET, CharSet = CharSet.Unicode, BestFitMapping = false, EntryPoint = "RegEnumKeyExW")]
internal unsafe static extern int RegEnumKeyEx(SafeRegistryHandle hKey, int dwIndex,
char* lpName, ref int lpcbName, int[] lpReserved,
[Out]StringBuilder lpClass, int[] lpcbClass,
long[] lpftLastWriteTime);
[DllImport(REGISTRY_L1_APISET, CharSet = CharSet.Unicode, BestFitMapping = false, EntryPoint = "RegEnumValueW")]
internal unsafe static extern int RegEnumValue(SafeRegistryHandle hKey, int dwIndex,
char* lpValueName, ref int lpcbValueName,
IntPtr lpReserved_MustBeZero, int[] lpType, byte[] lpData,
int[] lpcbData);
[DllImport(REGISTRY_L1_APISET)]
internal static extern int RegFlushKey(SafeRegistryHandle hKey);
[DllImport(REGISTRY_L1_APISET, CharSet = CharSet.Unicode, BestFitMapping = false, EntryPoint = "RegOpenKeyExW")]
internal static extern int RegOpenKeyEx(SafeRegistryHandle hKey, String lpSubKey,
int ulOptions, int samDesired, out SafeRegistryHandle hkResult);
[DllImport(REGISTRY_L1_APISET, CharSet = CharSet.Unicode, BestFitMapping = false, EntryPoint = "RegOpenKeyExW")]
internal static extern int RegOpenKeyEx(IntPtr hKey, String lpSubKey,
int ulOptions, int samDesired, out SafeRegistryHandle hkResult);
[DllImport(REGISTRY_L1_APISET, CharSet = CharSet.Unicode, BestFitMapping = false, EntryPoint = "RegQueryInfoKeyW")]
internal static extern int RegQueryInfoKey(SafeRegistryHandle hKey, [Out]StringBuilder lpClass,
int[] lpcbClass, IntPtr lpReserved_MustBeZero, ref int lpcSubKeys,
int[] lpcbMaxSubKeyLen, int[] lpcbMaxClassLen,
ref int lpcValues, int[] lpcbMaxValueNameLen,
int[] lpcbMaxValueLen, int[] lpcbSecurityDescriptor,
int[] lpftLastWriteTime);
[DllImport(REGISTRY_L1_APISET, CharSet = CharSet.Unicode, BestFitMapping = false, EntryPoint = "RegQueryValueExW")]
internal static extern int RegQueryValueEx(SafeRegistryHandle hKey, String lpValueName,
int[] lpReserved, ref int lpType, [Out] byte[] lpData,
ref int lpcbData);
[DllImport(REGISTRY_L1_APISET, CharSet = CharSet.Unicode, BestFitMapping = false, EntryPoint = "RegQueryValueExW")]
internal static extern int RegQueryValueEx(SafeRegistryHandle hKey, String lpValueName,
int[] lpReserved, ref int lpType, ref int lpData,
ref int lpcbData);
[DllImport(REGISTRY_L1_APISET, CharSet = CharSet.Unicode, BestFitMapping = false, EntryPoint = "RegQueryValueExW")]
internal static extern int RegQueryValueEx(SafeRegistryHandle hKey, String lpValueName,
int[] lpReserved, ref int lpType, ref long lpData,
ref int lpcbData);
[DllImport(REGISTRY_L1_APISET, CharSet = CharSet.Unicode, BestFitMapping = false, EntryPoint = "RegQueryValueExW")]
internal static extern int RegQueryValueEx(SafeRegistryHandle hKey, String lpValueName,
int[] lpReserved, ref int lpType, [Out] char[] lpData,
ref int lpcbData);
[DllImport(REGISTRY_L1_APISET, CharSet = CharSet.Unicode, BestFitMapping = false, EntryPoint = "RegQueryValueExW")]
internal static extern int RegQueryValueEx(SafeRegistryHandle hKey, String lpValueName,
int[] lpReserved, ref int lpType, [Out]StringBuilder lpData,
ref int lpcbData);
[DllImport(REGISTRY_L1_APISET, CharSet = CharSet.Unicode, BestFitMapping = false, EntryPoint = "RegSetValueExW")]
internal static extern int RegSetValueEx(SafeRegistryHandle hKey, String lpValueName,
int Reserved, RegistryValueKind dwType, byte[] lpData, int cbData);
[DllImport(REGISTRY_L1_APISET, CharSet = CharSet.Unicode, BestFitMapping = false, EntryPoint = "RegSetValueExW")]
internal static extern int RegSetValueEx(SafeRegistryHandle hKey, String lpValueName,
int Reserved, RegistryValueKind dwType, char[] lpData, int cbData);
[DllImport(REGISTRY_L1_APISET, CharSet = CharSet.Unicode, BestFitMapping = false, EntryPoint = "RegSetValueExW")]
internal static extern int RegSetValueEx(SafeRegistryHandle hKey, String lpValueName,
int Reserved, RegistryValueKind dwType, ref int lpData, int cbData);
[DllImport(REGISTRY_L1_APISET, CharSet = CharSet.Unicode, BestFitMapping = false, EntryPoint = "RegSetValueExW")]
internal static extern int RegSetValueEx(SafeRegistryHandle hKey, String lpValueName,
int Reserved, RegistryValueKind dwType, ref long lpData, int cbData);
[DllImport(REGISTRY_L1_APISET, CharSet = CharSet.Unicode, BestFitMapping = false, EntryPoint = "RegSetValueExW")]
internal static extern int RegSetValueEx(SafeRegistryHandle hKey, String lpValueName,
int Reserved, RegistryValueKind dwType, String lpData, int cbData);
[DllImport(PROCESSENVIRONMENT_L1_APISET, CharSet = CharSet.Unicode, SetLastError = true, BestFitMapping = false, EntryPoint = "ExpandEnvironmentStringsW")]
internal static extern int ExpandEnvironmentStrings(String lpSrc, [Out]StringBuilder lpDst, int nSize);
[DllImport(REGISTRY_L1_APISET)]
internal extern static int RegCloseKey(IntPtr hKey);
[DllImport(LOCALIZATION_L1_APISET, EntryPoint = "FormatMessageW", SetLastError = true, CharSet = CharSet.Unicode)]
internal extern static uint FormatMessage(
uint dwFlags,
IntPtr lpSource,
uint dwMessageId,
uint dwLanguageId,
char[] lpBuffer,
uint nSize,
IntPtr Arguments);
}
internal struct SECURITY_ATTRIBUTES
{
public uint nLength;
public IntPtr lpSecurityDescriptor;
public bool bInheritHandle;
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
using System.Threading;
using System.Threading.Tasks;
namespace System.IO.Tests
{
public class UmsTests
{
internal static void UmsInvariants(UnmanagedMemoryStream stream)
{
Assert.False(stream.CanTimeout);
}
internal static void ReadUmsInvariants(UnmanagedMemoryStream stream)
{
UmsInvariants(stream);
Assert.True(stream.CanRead);
Assert.False(stream.CanWrite);
Assert.True(stream.CanSeek);
Assert.Throws<NotSupportedException>(() => stream.SetLength(1000));
}
internal static void WriteUmsInvariants(UnmanagedMemoryStream stream)
{
UmsInvariants(stream);
Assert.False(stream.CanRead);
Assert.True(stream.CanWrite);
Assert.True(stream.CanSeek);
}
internal static void ReadWriteUmsInvariants(UnmanagedMemoryStream stream)
{
UmsInvariants(stream);
Assert.True(stream.CanRead);
Assert.True(stream.CanWrite);
Assert.True(stream.CanSeek);
}
[Fact]
public static void PositionTests()
{
using (var manager = new UmsManager(FileAccess.ReadWrite, 1000))
{
UnmanagedMemoryStream stream = manager.Stream;
UmsTests.ReadWriteUmsInvariants(stream);
Assert.Throws<ArgumentOutOfRangeException>(() => { stream.Position = -1; }); // "Non-negative number required."
Assert.Throws<ArgumentOutOfRangeException>(() => { stream.Position = unchecked(Int64.MaxValue + 1); });
Assert.Throws<ArgumentOutOfRangeException>(() => { stream.Position = Int32.MinValue; });
stream.Position = stream.Length;
Assert.Equal(stream.Position, stream.Length);
stream.Position = stream.Capacity;
Assert.Equal(stream.Position, stream.Capacity);
int mid = (int)stream.Length / 2;
stream.Position = mid;
Assert.Equal(stream.Position, mid);
}
}
[Fact]
public static void LengthTests()
{
using (var manager = new UmsManager(FileAccess.ReadWrite, 1000))
{
UnmanagedMemoryStream stream = manager.Stream;
UmsTests.ReadWriteUmsInvariants(stream);
Assert.Throws<IOException>(() => stream.SetLength(1001));
Assert.Throws<ArgumentOutOfRangeException>(() => stream.SetLength(SByte.MinValue));
const long expectedLength = 500;
stream.Position = 501;
stream.SetLength(expectedLength);
Assert.Equal(expectedLength, stream.Length);
Assert.Equal(expectedLength, stream.Position);
}
}
[Fact]
public static void SeekTests()
{
const int length = 1000;
using (var manager = new UmsManager(FileAccess.ReadWrite, length))
{
UnmanagedMemoryStream stream = manager.Stream;
UmsTests.ReadWriteUmsInvariants(stream);
Assert.Throws<IOException>(() => stream.Seek(unchecked(Int32.MaxValue + 1), SeekOrigin.Begin));
Assert.Throws<IOException>(() => stream.Seek(Int64.MinValue, SeekOrigin.End));
AssertExtensions.Throws<ArgumentException>(null, () => stream.Seek(0, (SeekOrigin)7)); // Invalid seek origin
stream.Seek(10, SeekOrigin.Begin);
Assert.Equal(10, stream.Position);
Assert.Throws<IOException>(() => stream.Seek(-1, SeekOrigin.Begin)); // An attempt was made to move the position before the beginning of the stream
Assert.Equal(10, stream.Position);
Assert.Throws<IOException>(() => stream.Seek(-(stream.Position + 1), SeekOrigin.Current)); // An attempt was made to move the position before the beginning of the stream
Assert.Equal(10, stream.Position);
Assert.Throws<IOException>(() => stream.Seek(-(stream.Length + 1), SeekOrigin.End)); // "An attempt was made to move the position before the beginning of the stream."
Assert.Equal(10, stream.Position);
// Seek from SeekOrigin.Begin
stream.Seek(0, SeekOrigin.Begin);
for (int position = 0; position < stream.Length; position++)
{
stream.Seek(position, SeekOrigin.Begin);
Assert.Equal(position, stream.Position);
}
for (int position = (int)stream.Length; position >= 0; position--)
{
stream.Seek(position, SeekOrigin.Begin);
Assert.Equal(position, stream.Position);
}
stream.Seek(0, SeekOrigin.Begin);
// Seek from SeekOrigin.End
for (int position = 0; position < stream.Length; position++)
{
stream.Seek(-position, SeekOrigin.End);
Assert.Equal(length - position, stream.Position);
}
for (int position = (int)stream.Length; position >= 0; position--)
{
stream.Seek(-position, SeekOrigin.End);
Assert.Equal(length - position, stream.Position);
}
// Seek from SeekOrigin.Current
stream.Seek(0, SeekOrigin.Begin);
for (int position = 0; position < stream.Length; position++)
{
stream.Seek(1, SeekOrigin.Current);
Assert.Equal(position + 1, stream.Position);
}
for (int position = (int)stream.Length; position > 0; position--)
{
stream.Seek(-1, SeekOrigin.Current);
Assert.Equal(position - 1, stream.Position);
}
}
}
[Fact]
public static void CannotUseStreamAfterDispose()
{
using (var manager = new UmsManager(FileAccess.ReadWrite, 1000))
{
UnmanagedMemoryStream stream = manager.Stream;
UmsTests.ReadWriteUmsInvariants(stream);
stream.Dispose();
Assert.False(stream.CanRead);
Assert.False(stream.CanWrite);
Assert.False(stream.CanSeek);
Assert.Throws<ObjectDisposedException>(() => { long x = stream.Capacity; });
Assert.Throws<ObjectDisposedException>(() => { long y = stream.Length; });
Assert.Throws<ObjectDisposedException>(() => { stream.SetLength(2); });
Assert.Throws<ObjectDisposedException>(() => { long z = stream.Position; });
Assert.Throws<ObjectDisposedException>(() => { stream.Position = 2; });
Assert.Throws<ObjectDisposedException>(() => stream.Seek(0, SeekOrigin.Begin));
Assert.Throws<ObjectDisposedException>(() => stream.Seek(0, SeekOrigin.Current));
Assert.Throws<ObjectDisposedException>(() => stream.Seek(0, SeekOrigin.End));
Assert.Throws<ObjectDisposedException>(() => stream.Flush());
Assert.Throws<ObjectDisposedException>(() => stream.FlushAsync(CancellationToken.None).GetAwaiter().GetResult());
byte[] buffer = ArrayHelpers.CreateByteArray(10);
Assert.Throws<ObjectDisposedException>(() => stream.Read(buffer, 0, buffer.Length));
Assert.Throws<ObjectDisposedException>(() => stream.ReadAsync(buffer, 0, buffer.Length).GetAwaiter().GetResult());
Assert.Throws<ObjectDisposedException>(() => stream.ReadByte());
Assert.Throws<ObjectDisposedException>(() => stream.WriteByte(0));
Assert.Throws<ObjectDisposedException>(() => stream.Write(buffer, 0, buffer.Length));
Assert.Throws<ObjectDisposedException>(() => stream.WriteAsync(buffer, 0, buffer.Length).GetAwaiter().GetResult());
}
}
[Fact]
public static void CopyToTest()
{
byte[] testData = ArrayHelpers.CreateByteArray(8192);
using (var manager = new UmsManager(FileAccess.Read, testData))
{
UnmanagedMemoryStream ums = manager.Stream;
UmsTests.ReadUmsInvariants(ums);
MemoryStream destination = new MemoryStream();
destination.Position = 0;
ums.CopyTo(destination);
Assert.Equal(testData, destination.ToArray());
destination.Position = 0;
ums.CopyTo(destination, 1);
Assert.Equal(testData, destination.ToArray());
}
// copy to disposed stream should throw
using (var manager = new UmsManager(FileAccess.Read, testData))
{
UnmanagedMemoryStream ums = manager.Stream;
UmsTests.ReadUmsInvariants(ums);
MemoryStream destination = new MemoryStream();
destination.Dispose();
Assert.Throws<ObjectDisposedException>(() => ums.CopyTo(destination));
}
// copy from disposed stream should throw
using (var manager = new UmsManager(FileAccess.Read, testData))
{
UnmanagedMemoryStream ums = manager.Stream;
UmsTests.ReadUmsInvariants(ums);
ums.Dispose();
MemoryStream destination = new MemoryStream();
Assert.Throws<ObjectDisposedException>(() => ums.CopyTo(destination));
}
// copying to non-writable stream should throw
using (var manager = new UmsManager(FileAccess.Read, testData))
{
UnmanagedMemoryStream ums = manager.Stream;
UmsTests.ReadUmsInvariants(ums);
MemoryStream destination = new MemoryStream(new byte[0], false);
Assert.Throws<NotSupportedException>(() => ums.CopyTo(destination));
}
// copying from non-readable stream should throw
using (var manager = new UmsManager(FileAccess.Write, testData))
{
UnmanagedMemoryStream ums = manager.Stream;
UmsTests.WriteUmsInvariants(ums);
MemoryStream destination = new MemoryStream(new byte[0], false);
Assert.Throws<NotSupportedException>(() => ums.CopyTo(destination));
}
}
[Fact]
public static async Task CopyToAsyncTest()
{
byte[] testData = ArrayHelpers.CreateByteArray(8192);
using (var manager = new UmsManager(FileAccess.Read, testData))
{
UnmanagedMemoryStream ums = manager.Stream;
UmsTests.ReadUmsInvariants(ums);
MemoryStream destination = new MemoryStream();
destination.Position = 0;
await ums.CopyToAsync(destination);
Assert.Equal(testData, destination.ToArray());
destination.Position = 0;
await ums.CopyToAsync(destination, 2);
Assert.Equal(testData, destination.ToArray());
destination.Position = 0;
await ums.CopyToAsync(destination, 0x1000, new CancellationTokenSource().Token);
Assert.Equal(testData, destination.ToArray());
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => ums.CopyToAsync(destination, 0x1000, new CancellationToken(true)));
}
// copy to disposed stream should throw
using (var manager = new UmsManager(FileAccess.Read, testData))
{
UnmanagedMemoryStream ums = manager.Stream;
UmsTests.ReadUmsInvariants(ums);
MemoryStream destination = new MemoryStream();
destination.Dispose();
await Assert.ThrowsAsync<ObjectDisposedException>(() => ums.CopyToAsync(destination));
}
// copy from disposed stream should throw
using (var manager = new UmsManager(FileAccess.Read, testData))
{
UnmanagedMemoryStream ums = manager.Stream;
UmsTests.ReadUmsInvariants(ums);
ums.Dispose();
MemoryStream destination = new MemoryStream();
await Assert.ThrowsAsync<ObjectDisposedException>(() => ums.CopyToAsync(destination));
}
// copying to non-writable stream should throw
using (var manager = new UmsManager(FileAccess.Read, testData))
{
UnmanagedMemoryStream ums = manager.Stream;
UmsTests.ReadUmsInvariants(ums);
MemoryStream destination = new MemoryStream(new byte[0], false);
await Assert.ThrowsAsync<NotSupportedException>(() => ums.CopyToAsync(destination));
}
// copying from non-readable stream should throw
using (var manager = new UmsManager(FileAccess.Write, testData))
{
UnmanagedMemoryStream ums = manager.Stream;
UmsTests.WriteUmsInvariants(ums);
MemoryStream destination = new MemoryStream(new byte[0], false);
await Assert.ThrowsAsync<NotSupportedException>(() => ums.CopyToAsync(destination));
}
}
}
}
| |
using System.Net;
using System.Net.Http;
using System.Net.Security;
using System.Net.Sockets;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
using k8s.Exceptions;
using k8s.Autorest;
namespace k8s
{
public partial class Kubernetes
{
/// <summary>
/// Timeout of REST calls to Kubernetes server
/// Does not apply to watch related api
/// </summary>
/// <value>timeout</value>
public TimeSpan HttpClientTimeout { get; set; } = TimeSpan.FromSeconds(100);
/// <summary>
/// Initializes a new instance of the <see cref="Kubernetes" /> class.
/// </summary>
/// <param name='config'>
/// The kube config to use.
/// </param>
/// <param name="handlers">
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
public Kubernetes(KubernetesClientConfiguration config, params DelegatingHandler[] handlers)
{
Initialize();
ValidateConfig(config);
CaCerts = config.SslCaCerts;
SkipTlsVerify = config.SkipTlsVerify;
CreateHttpClient(handlers, config);
InitializeFromConfig(config);
HttpClientTimeout = config.HttpClientTimeout;
}
private void ValidateConfig(KubernetesClientConfiguration config)
{
if (config == null)
{
throw new KubeConfigException("KubeConfig must be provided");
}
if (string.IsNullOrWhiteSpace(config.Host))
{
throw new KubeConfigException("Host url must be set");
}
try
{
BaseUri = new Uri(config.Host);
}
catch (UriFormatException e)
{
throw new KubeConfigException("Bad host url", e);
}
}
private void InitializeFromConfig(KubernetesClientConfiguration config)
{
if (BaseUri.Scheme == "https")
{
if (config.SkipTlsVerify)
{
#if NET5_0_OR_GREATER
HttpClientHandler.SslOptions.RemoteCertificateValidationCallback =
#else
HttpClientHandler.ServerCertificateCustomValidationCallback =
#endif
(sender, certificate, chain, sslPolicyErrors) => true;
}
else
{
if (CaCerts == null)
{
throw new KubeConfigException("A CA must be set when SkipTlsVerify === false");
}
#if NET5_0_OR_GREATER
HttpClientHandler.SslOptions.RemoteCertificateValidationCallback =
#else
HttpClientHandler.ServerCertificateCustomValidationCallback =
#endif
(sender, certificate, chain, sslPolicyErrors) =>
{
return CertificateValidationCallBack(sender, CaCerts, certificate, chain,
sslPolicyErrors);
};
}
}
// set credentails for the kubernetes client
SetCredentials(config);
var clientCert = CertUtils.GetClientCert(config);
if (clientCert != null)
{
#if NET5_0_OR_GREATER
HttpClientHandler.SslOptions.ClientCertificates.Add(clientCert);
#else
HttpClientHandler.ClientCertificates.Add(clientCert);
#endif
}
}
private X509Certificate2Collection CaCerts { get; }
private X509Certificate2 ClientCert { get; }
private bool SkipTlsVerify { get; }
// NOTE: this method replicates the logic that the base ServiceClient uses except that it doesn't insert the RetryDelegatingHandler
// and it does insert the WatcherDelegatingHandler. we don't want the RetryDelegatingHandler because it has a very broad definition
// of what requests have failed. it considers everything outside 2xx to be failed, including 1xx (e.g. 101 Switching Protocols) and
// 3xx. in particular, this prevents upgraded connections and certain generic/custom requests from working.
private void CreateHttpClient(DelegatingHandler[] handlers, KubernetesClientConfiguration config)
{
#if NET5_0_OR_GREATER
FirstMessageHandler = HttpClientHandler = new SocketsHttpHandler
{
KeepAlivePingPolicy = HttpKeepAlivePingPolicy.WithActiveRequests,
KeepAlivePingDelay = TimeSpan.FromMinutes(3),
KeepAlivePingTimeout = TimeSpan.FromSeconds(30),
};
HttpClientHandler.SslOptions.ClientCertificates = new X509Certificate2Collection();
#else
FirstMessageHandler = HttpClientHandler = new HttpClientHandler();
#endif
if (handlers != null)
{
for (int i = handlers.Length - 1; i >= 0; i--)
{
DelegatingHandler handler = handlers[i];
while (handler.InnerHandler is DelegatingHandler d)
{
handler = d;
}
handler.InnerHandler = FirstMessageHandler;
FirstMessageHandler = handlers[i];
}
}
HttpClient = new HttpClient(FirstMessageHandler, false)
{
Timeout = Timeout.InfiniteTimeSpan,
};
}
/// <summary>
/// Set credentials for the Client
/// </summary>
/// <param name="config">k8s client configuration</param>
private void SetCredentials(KubernetesClientConfiguration config) => Credentials = CreateCredentials(config);
/// <summary>
/// SSl Cert Validation Callback
/// </summary>
/// <param name="sender">sender</param>
/// <param name="caCerts">client ca</param>
/// <param name="certificate">client certificate</param>
/// <param name="chain">chain</param>
/// <param name="sslPolicyErrors">ssl policy errors</param>
/// <returns>true if valid cert</returns>
public static bool CertificateValidationCallBack(
object sender,
X509Certificate2Collection caCerts,
X509Certificate certificate,
X509Chain chain,
SslPolicyErrors sslPolicyErrors)
{
if (caCerts == null)
{
throw new ArgumentNullException(nameof(caCerts));
}
if (chain == null)
{
throw new ArgumentNullException(nameof(chain));
}
// If the certificate is a valid, signed certificate, return true.
if (sslPolicyErrors == SslPolicyErrors.None)
{
return true;
}
// If there are errors in the certificate chain, look at each error to determine the cause.
if ((sslPolicyErrors & SslPolicyErrors.RemoteCertificateChainErrors) != 0)
{
chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
// Added our trusted certificates to the chain
//
chain.ChainPolicy.ExtraStore.AddRange(caCerts);
chain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllowUnknownCertificateAuthority;
var isValid = chain.Build((X509Certificate2)certificate);
var isTrusted = false;
var rootCert = chain.ChainElements[chain.ChainElements.Count - 1].Certificate;
// Make sure that one of our trusted certs exists in the chain provided by the server.
//
foreach (var cert in caCerts)
{
if (rootCert.RawData.SequenceEqual(cert.RawData))
{
isTrusted = true;
break;
}
}
return isValid && isTrusted;
}
// In all other cases, return false.
return false;
}
/// <summary>
/// Creates <see cref="ServiceClientCredentials"/> based on the given config, or returns null if no such credentials are needed.
/// </summary>
/// <param name="config">kubenetes config object</param>
/// <returns>instance of <see cref="ServiceClientCredentials"/></returns>
public static ServiceClientCredentials CreateCredentials(KubernetesClientConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException(nameof(config));
}
if (config.TokenProvider != null)
{
return new TokenCredentials(config.TokenProvider);
}
else if (!string.IsNullOrEmpty(config.AccessToken))
{
return new TokenCredentials(config.AccessToken);
}
else if (!string.IsNullOrEmpty(config.Username))
{
return new BasicAuthenticationCredentials() { UserName = config.Username, Password = config.Password };
}
return null;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Diagnostics;
using AForge.Video;
using AForge.Video.DirectShow;
using AForge.Imaging;
using AForge.Imaging.Filters;
using AForge.Vision.Motion;
namespace ES.Software.Video
{
class Camera
{
//Declare class variables:
private Grayscale objGrayscale = null; //AForge filter object, used to convert image from color to gray scale.
private VideoCaptureDevice videosource = null; //Video device to be used.
private Pen p = new Pen(Color.Black, 2); //Black pen with with line width 2.
private Pen objPenGreen2 = new Pen(Color.Green, 2); //Green pen with with line width 2.
private SolidBrush[] sb = { new SolidBrush(Color.FromArgb(50, Color.Blue)), new SolidBrush(Color.FromArgb(70, Color.Red)), new SolidBrush(Color.FromArgb(70, Color.Green)) }; //Declare brush object.
private MotionDetection MD = new MotionDetection(); //Creating object, responsible for motion detection.
public delegate void FrameEventHandler(object Camera, Bitmap image); //Public delegate. It describeswhat parameters return by event.
public event FrameEventHandler FrameEvent; //Public event for the class.
private int curr_FramesSecond=DateTime.Now.Second; //Save current second for frame.
private int curr_FramesAmount=0; //Updating frames amount.
private int curr_FramesAmountToShow=0; //Updating frames amount / second, that will be show.
public int conf_DisplayVideoTyype=0; //Define what video to display.
private MotionDetector objMotionDetector = new MotionDetector(new TwoFramesDifferenceDetector( ),new MotionAreaHighlighting( ) ); //Create motion detector.
private float current_MotionLevel = 0; //Amount of motion, which is provided MotionLevel property.
private MotionDetector objSimpleBackgroundModelingDetector = new MotionDetector(new SimpleBackgroundModelingDetector( ),new MotionAreaHighlighting());
private MotionDetector objCustomFrameDifferenceDetector = new MotionDetector(new CustomFrameDifferenceDetector( ),new MotionAreaHighlighting() );
private MotionDetector objMotionAreaHighlighting = new MotionDetector(new TwoFramesDifferenceDetector( ),new MotionAreaHighlighting());
private MotionDetector objMotionBorderHighlighting = new MotionDetector(new TwoFramesDifferenceDetector(),new MotionBorderHighlighting( ) );
private static IMotionDetector objTwoFramesDifferenceDetector = new TwoFramesDifferenceDetector();//Create instance of motion detection algorithm
private static GridMotionAreaProcessing objGridMotionAreaProcessing = new GridMotionAreaProcessing(16,16 );//Create instance of motion processing algorithm
private MotionDetector objMotionDetector2 = new MotionDetector(objTwoFramesDifferenceDetector, objGridMotionAreaProcessing );// create motion detector
private static BlobCountingObjectsProcessing objBlobCountingObjectsProcessing = new BlobCountingObjectsProcessing( );// create instance of motion processing algorithm
private MotionDetector objMotionDetector3 = new MotionDetector( objTwoFramesDifferenceDetector, objBlobCountingObjectsProcessing ); // create motion detector
private int current_MotionObjectsCount = 0;
/// <summary>
///New frame event handler.
/// </summary>
private void videosource_NewFrame(object sender, NewFrameEventArgs eventArgs)
{
//0 - Default video display type, it will simple show video, that got fromcamera:
if (conf_DisplayVideoTyype == 0)
{
VideoSourceViewDefaultVideo(eventArgs);
}
//1 - View default video with added some information about it:
if (conf_DisplayVideoTyype == 1)
{
VideoSourceViewDefaultVideoWithAdditionalInfo(eventArgs);
}
//2 - View default video with simple motion detection logic:
if (conf_DisplayVideoTyype == 2)
{
VideoSourceViewDefaultVideoWithSimpleMotionDetection(eventArgs);
}
//3 - View grayscale video:
if (conf_DisplayVideoTyype == 3)
{
//VideoSourceViewDefaultVideoInGrayScale(eventArgs);
VideoSourceViewDefaultVideoInGrayScale2(eventArgs);
}
//4 - Two frames difference motion detector:
if (conf_DisplayVideoTyype == 4)
{
MotionTwoFramesDifferenceDetector(eventArgs);
}
//5 - Simple background modeling motion detector:
if (conf_DisplayVideoTyype == 5)
{
MotionSimpleBackgroundModelingDetector(eventArgs);
}
//6 - Custom frame difference motion detector:
if (conf_DisplayVideoTyype == 6)
{
CustomFrameDifferenceMotionDetector(eventArgs);
}
//7 - Motion area highlighting:
if (conf_DisplayVideoTyype == 7)
{
MotionAreaHighlighting(eventArgs);
}
//8 - Motion border highlighting:
if (conf_DisplayVideoTyype == 8)
{
MotionBorderHighlighting(eventArgs);
}
//9 - Grid motion area processing:
if (conf_DisplayVideoTyype == 9)
{
GridMotionAreaProcessing(eventArgs);
}
//10 - Blob counting objects processing:
if (conf_DisplayVideoTyype == 10)
{
BlobCountingObjectsProcessing(eventArgs);
}
}
/// <summary>
/// PROPERTY, that will return speed in Frm/sec.
/// </summary>
public int FramesAmountSec
{
get { return curr_FramesAmountToShow; }
}
/// <summary>
/// PROPERTY, that will return motion level.
/// </summary>
public float MotionLevel
{
get { return current_MotionLevel; }
}
/// <summary>
/// PROPERTY, return objects in motion amount.
/// </summary>
public int MotionObjectsCount
{
get { return current_MotionObjectsCount; }
}
/// <summary>
/// Set default brush parameters.
/// </summary>
public void Restore_brush()
{
sb[0] = new SolidBrush(Color.FromArgb(50, Color.Blue));
sb[1] = new SolidBrush(Color.FromArgb(70, Color.Red));
sb[2] = new SolidBrush(Color.FromArgb(70, Color.Green));
}
/// <summary>
/// This method updating brush style by enetred integer number.
/// </summary>
public void Update_brush(int i)
{
//brushes_updated = true;
if (i == 1)
{
sb[0] = new SolidBrush(Color.Blue);
}
else if (i == 2)
{
sb[1] = new SolidBrush(Color.Red);
}
else
{
sb[2] = new SolidBrush(Color.YellowGreen);
}
}
/// <summary>
/// Camera class constructor.
/// </summary>
public Camera(string MonikerString)
{
//Set what camera as video source will be used:
videosource = new VideoCaptureDevice(MonikerString);
//Declare motion event method:
MD.MotionEvent += new MotionDetection.MotionEventHandler(MD_MotionEvent);
//Set processing threshold:
MD.threshold = 15;
//Construct filter object:
objGrayscale = new Grayscale(0.2125, 0.7154, 0.0721);
}
/// <summary>
/// Event firing method.
/// </summary>
// constructor
public void OnFraneEvent(object Camera, Bitmap image)
{
// Check if there are any Subscribers
if (FrameEvent != null)
{
// Call the Event. Disposing event:
FrameEvent(Camera, image);
}
}
/// <summary>
/// Motion event in picture occured.
/// </summary>
void MD_MotionEvent(object MotionDetection, EventArgs eventArgs)
{
}
/// <summary>
///Stop the camera source.
/// </summary>
public void Stop_Camera()
{
if (videosource.IsRunning)
{
videosource.Stop();
}
}
/// <summary>
///Start the camera source.
/// </summary>
public void Start_Camera()
{
if (!videosource.IsRunning)
{
videosource.NewFrame += new NewFrameEventHandler(videosource_NewFrame);
videosource.Start();
}
}
/// <summary>
/// This method calculating speed.
/// </summary>
private void UpdateSpeedParameters()
{
//Calculate speed (Frames/second):
if (curr_FramesSecond==DateTime.Now.Second){curr_FramesAmount++;}else
{
curr_FramesAmountToShow=curr_FramesAmount;
curr_FramesAmount=1;
curr_FramesSecond=DateTime.Now.Second;
}
}
/// <summary>
/// This method will generate and view simple video,
/// that got from camera.
/// </summary>
void VideoSourceViewDefaultVideo(NewFrameEventArgs eventArgs)
{
//Prepare image for display:
Bitmap Image = new Bitmap(eventArgs.Frame.Width, eventArgs.Frame.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
Graphics _copy = Graphics.FromImage(Image);
_copy.DrawImage(eventArgs.Frame, new Point(0, 0));
_copy.Dispose();
//Update speed parameters:
UpdateSpeedParameters();
//Event firing method:
OnFraneEvent(this, Image);
}
/// <summary>
/// This method will generate and view simple video,
/// that got from camera with additional information about this video.
/// </summary>
void VideoSourceViewDefaultVideoWithAdditionalInfo(NewFrameEventArgs eventArgs)
{
//Declare and set local variables:
Bitmap Image = new Bitmap(eventArgs.Frame.Width, eventArgs.Frame.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
Graphics _copy = Graphics.FromImage(Image);
_copy.DrawImage(eventArgs.Frame, new Point(0, 0));
_copy.Dispose();
Bitmap Image_percentile_motion=new Bitmap(eventArgs.Frame.Width, eventArgs.Frame.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
int curr_percentile_motion=0;
int curr_percentile_motion_diffrence=0;
Rectangle cloneRect = new Rectangle(0, 0, eventArgs.Frame.Width, eventArgs.Frame.Height);
//Calculate speed (Frames/second):
if (curr_FramesSecond==DateTime.Now.Second){curr_FramesAmount++;}else
{
curr_FramesAmountToShow=curr_FramesAmount;
curr_FramesAmount=1;
curr_FramesSecond=DateTime.Now.Second;
}
//Close image:
Image_percentile_motion = (Bitmap)Image.Clone(cloneRect, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
//Get motion percentile:
curr_percentile_motion = MD.Process(Image_percentile_motion);
//Get percentile motion diffrence:
curr_percentile_motion_diffrence=MD.average_motion_percentage;
//Creates a new Graphics from the specified Image:
Graphics g = Graphics.FromImage(Image);
//Add to camera picture black rectangle:
//g.DrawRectangle(objPenGreen2, 10, 10, 100, 100);//Add rectangle.
//Add text with information about Frames/Second:
g.DrawString("Speed: " + curr_FramesAmountToShow.ToString() + " Frm/sec",new Font("Verdana",12),new SolidBrush(Color.Black),5,5);//Color.Tomato
//Percentile motion show:
g.DrawString("Percentile motion: " + curr_percentile_motion.ToString() + " %" ,new Font("Verdana",12),new SolidBrush(Color.Black),5,25);
//Percentile motion diffrence show:
g.DrawString("Percentile motion diffrence: " + curr_percentile_motion_diffrence.ToString() + " %" ,new Font("Verdana",12),new SolidBrush(Color.Black),5,45);
//Show image size:
g.DrawString("Image size: " + eventArgs.Frame.Width.ToString() + " x " + eventArgs.Frame.Height.ToString(),new Font("Verdana",12),new SolidBrush(Color.Black),5,65);
//Clean graphics object:
g.Dispose();
//Event firing method:
OnFraneEvent(this, Image);
}
/// <summary>
/// This method will generate and view simple video,
/// that arounf motion area will put green rectangle.
/// </summary>
void VideoSourceViewDefaultVideoWithSimpleMotionDetection(NewFrameEventArgs eventArgs)
{
//Declare and set local variables:
Bitmap Image = new Bitmap(eventArgs.Frame.Width, eventArgs.Frame.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
Graphics _copy = Graphics.FromImage(Image);
_copy.DrawImage(eventArgs.Frame, new Point(0, 0));
_copy.Dispose();
Bitmap Image_percentile_motion=new Bitmap(eventArgs.Frame.Width, eventArgs.Frame.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
int curr_percentile_motion=0;
int curr_percentile_motion_diffrence=0;
Rectangle cloneRect = new Rectangle(0, 0, eventArgs.Frame.Width, eventArgs.Frame.Height);
//Calculate speed (Frames/second):
if (curr_FramesSecond==DateTime.Now.Second){curr_FramesAmount++;}else
{
curr_FramesAmountToShow=curr_FramesAmount;
curr_FramesAmount=1;
curr_FramesSecond=DateTime.Now.Second;
}
//Close image:
Image_percentile_motion = (Bitmap)Image.Clone(cloneRect, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
//Get motion percentile:
curr_percentile_motion = MD.Process(Image_percentile_motion);
//Get percentile motion diffrence:
curr_percentile_motion_diffrence=MD.average_motion_percentage;
//Creates a new Graphics from the specified Image:
Graphics g = Graphics.FromImage(Image);
//Draw motion pixels:
if (MD.motion_pixel_x.Count > 0)
{
//Put rectangle around motion position:
int x=0;
int y=0;
if (MD.motion_smallest_x > 50) { x= MD.motion_smallest_x-50;}
if (MD.motion_smallest_y > 50) { y= MD.motion_smallest_y-50;}
g.DrawRectangle(objPenGreen2, x, y, 100, 100);
}
//Clean graphics object:
g.Dispose();
//Event firing method:
OnFraneEvent(this, Image);
}
/// <summary>
/// View video in grayscale.
/// </summary>
void VideoSourceViewDefaultVideoInGrayScale(NewFrameEventArgs eventArgs)
{
//Prepare image for display:
Bitmap Image = new Bitmap(eventArgs.Frame.Width, eventArgs.Frame.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
Graphics _copy = Graphics.FromImage(Image);
_copy.DrawImage(eventArgs.Frame, new Point(0, 0));
_copy.Dispose();
//Prepare grayscale image (slow method):
Rectangle cloneRect = new Rectangle(0, 0, eventArgs.Frame.Width, eventArgs.Frame.Height);
Bitmap ImageGray=new Bitmap(eventArgs.Frame.Width, eventArgs.Frame.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
ImageGray = (Bitmap)Image.Clone(cloneRect, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
ImageMatrix temp = new ImageMatrix(ImageGray);
ImageGray = temp.ToImage();
//Event firing method:
OnFraneEvent(this, ImageGray);
}
/// <summary>
/// View video in grayscale.
/// </summary>
void VideoSourceViewDefaultVideoInGrayScale1(NewFrameEventArgs eventArgs)
{
//Prepare image for display:
Bitmap Image = new Bitmap(eventArgs.Frame.Width, eventArgs.Frame.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
Graphics _copy = Graphics.FromImage(Image);
_copy.DrawImage(eventArgs.Frame, new Point(0, 0));
_copy.Dispose();
//Prepare grayscale image (slow method):
Rectangle cloneRect = new Rectangle(0, 0, eventArgs.Frame.Width, eventArgs.Frame.Height);
Bitmap ImageGray=new Bitmap(eventArgs.Frame.Width, eventArgs.Frame.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
ImageGray = Extensions.MakeGrayscale3((Bitmap)Image.Clone(cloneRect, System.Drawing.Imaging.PixelFormat.Format32bppArgb));
//Event firing method:
OnFraneEvent(this, ImageGray);
}
/// <summary>
/// View video in grayscale.
/// </summary>
private void VideoSourceViewDefaultVideoInGrayScale2(NewFrameEventArgs eventArgs)
{
//Prepare image for display:
Bitmap Image = new Bitmap(eventArgs.Frame.Width, eventArgs.Frame.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
Graphics _copy = Graphics.FromImage(Image);
_copy.DrawImage(eventArgs.Frame, new Point(0, 0));
_copy.Dispose();
Rectangle cloneRect = new Rectangle(0, 0, eventArgs.Frame.Width, eventArgs.Frame.Height);
//Update speed parameters:
UpdateSpeedParameters();
//Invoke object:
Bitmap ImageGray = objGrayscale.Apply((Bitmap)Image.Clone(cloneRect, System.Drawing.Imaging.PixelFormat.Format32bppArgb));
//Event firing method:
OnFraneEvent(this, ImageGray);
}
/// <summary>
/// Two frames difference motion detector.
/// This type of motion detector is the simplest one and the quickest one.
/// The idea of this detector is based on finding amount of difference in
/// two consequent frames of video stream. The greater is difference,
/// It does not suite very well those tasks, where it is required to precisely
/// highlight moving object. However it has recommended itself very well for
/// those tasks, which just require motion detection.
/// </summary>
private void MotionTwoFramesDifferenceDetector(NewFrameEventArgs eventArgs)
{
//Process new video frame and set motion level:
current_MotionLevel=objMotionDetector.ProcessFrame(eventArgs.Frame);
//if ( detector.ProcessFrame( videoFrame ) > 0.02 ) //Do some job.
//Prepare image for display:
Bitmap Image = new Bitmap(eventArgs.Frame.Width, eventArgs.Frame.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
Graphics _copy = Graphics.FromImage(Image);
_copy.DrawImage(eventArgs.Frame, new Point(0, 0));
_copy.Dispose();
Rectangle cloneRect = new Rectangle(0, 0, eventArgs.Frame.Width, eventArgs.Frame.Height);
//Update speed parameters:
UpdateSpeedParameters();
//Event firing method:
OnFraneEvent(this, Image);
}
/// <summary>
/// Simple background modeling motion detector.
/// In contrast to the above mentioned motion detector, this motion detector is
/// based on finding difference between current video frame and a frame representing
/// background. This motion detector tries to use simple techniques of modeling scene's
/// background and updating it through time to get into account scene's changes. The
/// background modeling feature of this motion detector gives the ability of more precise
/// highlighting of motion regions.
/// </summary>
private void MotionSimpleBackgroundModelingDetector(NewFrameEventArgs eventArgs)
{
//Process new video frame and set motion level:
current_MotionLevel=objSimpleBackgroundModelingDetector.ProcessFrame(eventArgs.Frame);
//if ( detector.ProcessFrame( videoFrame ) > 0.02 ) //Do some job.
//Prepare image for display:
Bitmap Image = new Bitmap(eventArgs.Frame.Width, eventArgs.Frame.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
Graphics _copy = Graphics.FromImage(Image);
_copy.DrawImage(eventArgs.Frame, new Point(0, 0));
_copy.Dispose();
Rectangle cloneRect = new Rectangle(0, 0, eventArgs.Frame.Width, eventArgs.Frame.Height);
//Update speed parameters:
UpdateSpeedParameters();
//Event firing method:
OnFraneEvent(this, Image);
}
/// <summary>
/// Custom frame difference motion detector.
/// This class implements motion detection algorithm, which is based on the difference of
/// current video frame with predefined background frame, which puts it in-between of the two
/// above classes. On the one hand this motion detector is based on simple differencing as
/// the two frames difference motion detector, which makes it fast. On the other hand it does
/// differencing of current video frame with background frame, which may allow finding moving
/// objects, but not areas of changes (like in simple background modeling motion detector).
/// However, user needs to specify background frame on his own (or the algorithm will take first
/// video frame as a background frame) and the algorithm will never try to update it, which
/// means no adaptation to scene changes.
/// </summary>
private void CustomFrameDifferenceMotionDetector(NewFrameEventArgs eventArgs)
{
//Process new video frame and set motion level:
current_MotionLevel=objCustomFrameDifferenceDetector.ProcessFrame(eventArgs.Frame);
//if ( detector.ProcessFrame( videoFrame ) > 0.02 ) //Do some job.
//Prepare image for display:
Bitmap Image = new Bitmap(eventArgs.Frame.Width, eventArgs.Frame.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
Graphics _copy = Graphics.FromImage(Image);
_copy.DrawImage(eventArgs.Frame, new Point(0, 0));
_copy.Dispose();
Rectangle cloneRect = new Rectangle(0, 0, eventArgs.Frame.Width, eventArgs.Frame.Height);
//Update speed parameters:
UpdateSpeedParameters();
//Event firing method:
OnFraneEvent(this, Image);
}
/// <summary>
/// Motion area highlighting.
/// This motion processing algorithm is aimed just to highlight motion areas found by motion detection
/// algorithm with specified color. All of the above screenshots demonstrate the work of motion are
/// highlighting.
/// </summary>
private void MotionAreaHighlighting(NewFrameEventArgs eventArgs)
{
//Process new video frame and set motion level:
objMotionAreaHighlighting.ProcessFrame(eventArgs.Frame);
//Prepare image for display:
Bitmap Image = new Bitmap(eventArgs.Frame.Width, eventArgs.Frame.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
Graphics _copy = Graphics.FromImage(Image);
_copy.DrawImage(eventArgs.Frame, new Point(0, 0));
_copy.Dispose();
Rectangle cloneRect = new Rectangle(0, 0, eventArgs.Frame.Width, eventArgs.Frame.Height);
//Update speed parameters:
UpdateSpeedParameters();
//Event firing method:
OnFraneEvent(this, Image);
}
/// <summary>
/// Motion border highlighting.
/// This motion processing algorithm is aimed to highlight only borders of motion areas found by motion
/// detection algorithm. It is supposed to be used only with those motion detection algorithms, which may
/// accurately locate moving objects.
/// </summary>
private void MotionBorderHighlighting(NewFrameEventArgs eventArgs)
{
//Process new video frame and set motion level:
objMotionBorderHighlighting.ProcessFrame(eventArgs.Frame);
//Prepare image for display:
Bitmap Image = new Bitmap(eventArgs.Frame.Width, eventArgs.Frame.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
Graphics _copy = Graphics.FromImage(Image);
_copy.DrawImage(eventArgs.Frame, new Point(0, 0));
_copy.Dispose();
Rectangle cloneRect = new Rectangle(0, 0, eventArgs.Frame.Width, eventArgs.Frame.Height);
//Update speed parameters:
UpdateSpeedParameters();
//Event firing method:
OnFraneEvent(this, Image);
}
/// <summary>
/// Grid motion area processing
/// This motion processing algorithm allows to do grid processing of motion frame. This means that entire motion
/// frame can be divided by a grid into certain amount of cells and motion level can be calculated for each cell
/// individually, so you may know which part of the video frame had more motion. In addition this motion processing
/// algorithm provides highlighting, which may be enabled or disable. User may specify threshold for cells' motion
/// level to highlight.
/// </summary>
private void GridMotionAreaProcessing(NewFrameEventArgs eventArgs)
{
//Process new video frame and set motion level:
objMotionDetector2.ProcessFrame(eventArgs.Frame);
//Check motion level in 5th row 8th column:
if (objGridMotionAreaProcessing.MotionGrid[5, 8] > 0.15 )
{
// ...
}
//Prepare image for display:
Bitmap Image = new Bitmap(eventArgs.Frame.Width, eventArgs.Frame.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
Graphics _copy = Graphics.FromImage(Image);
_copy.DrawImage(eventArgs.Frame, new Point(0, 0));
_copy.Dispose();
Rectangle cloneRect = new Rectangle(0, 0, eventArgs.Frame.Width, eventArgs.Frame.Height);
//Update speed parameters:
UpdateSpeedParameters();
//Event firing method:
OnFraneEvent(this, Image);
}
/// <summary>
/// Blob counting objects processing
/// This motion processing algorithm allows counting separate objects in the motion frame, which is provided by motion detection
/// algorithm. In addition it may also highlight detected objects with a rectangle of specified color. The algorithm counts and
/// highlights only those objects, which size satisfies specified limits - it is possible to configure this motion processing
/// algorithm to ignore objects smaller than specified size.
///
/// This motion processing algorithm is supposed to be used only with those motion detection algorithms, which may accurately
/// locate moving objects.
/// </summary>
private void BlobCountingObjectsProcessing(NewFrameEventArgs eventArgs)
{
//Process new video frame and set motion level:
current_MotionLevel=objMotionDetector3.ProcessFrame(eventArgs.Frame);
//Get objects amount:
current_MotionObjectsCount = objBlobCountingObjectsProcessing.ObjectsCount;
//Prepare image for display:
Bitmap Image = new Bitmap(eventArgs.Frame.Width, eventArgs.Frame.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
Graphics _copy = Graphics.FromImage(Image);
_copy.DrawImage(eventArgs.Frame, new Point(0, 0));
_copy.Dispose();
Rectangle cloneRect = new Rectangle(0, 0, eventArgs.Frame.Width, eventArgs.Frame.Height);
//Update speed parameters:
UpdateSpeedParameters();
//Event firing method:
OnFraneEvent(this, Image);
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Management.Compute.Models;
namespace Microsoft.WindowsAzure.Management.Compute
{
/// <summary>
/// The Service Management API includes operations for managing the hosted
/// services beneath your subscription. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/ee460812.aspx for
/// more information)
/// </summary>
public partial interface IHostedServiceOperations
{
/// <summary>
/// The Add Extension operation adds an available extension to your
/// cloud service. In Azure, a process can run as an extension of a
/// cloud service. For example, Remote Desktop Access or the Azure
/// Diagnostics Agent can run as extensions to the cloud service. You
/// can find the available extension by using the List Available
/// Extensions operation. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/dn169558.aspx
/// for more information)
/// </summary>
/// <param name='serviceName'>
/// The name of the cloud service.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the Add Extension operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request and error information regarding
/// the failure.
/// </returns>
Task<OperationStatusResponse> AddExtensionAsync(string serviceName, HostedServiceAddExtensionParameters parameters, CancellationToken cancellationToken);
/// <summary>
/// The Begin Adding Extension operation adds an available extension to
/// your cloud service. In Azure, a process can run as an extension of
/// a cloud service. For example, Remote Desktop Access or the Azure
/// Diagnostics Agent can run as extensions to the cloud service. You
/// can find the available extension by using the List Available
/// Extensions operation. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/dn169558.aspx
/// for more information)
/// </summary>
/// <param name='serviceName'>
/// The name of the cloud service.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the Begin Adding Extension operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
Task<OperationResponse> BeginAddingExtensionAsync(string serviceName, HostedServiceAddExtensionParameters parameters, CancellationToken cancellationToken);
/// <summary>
/// The DeleteAll Hosted Service operation deletes the specified cloud
/// service as well as operating system disk, attached data disks, and
/// the source blobs for the disks from storage from Microsoft Azure.
/// (see
/// 'http://msdn.microsoft.com/en-us/library/windowsazure/gg441305.aspx'
/// for more information)
/// </summary>
/// <param name='serviceName'>
/// The name of the cloud service.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
Task<OperationResponse> BeginDeletingAllAsync(string serviceName, CancellationToken cancellationToken);
/// <summary>
/// The Begin Deleting Extension operation deletes the specified
/// extension from a cloud service. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/dn169560.aspx
/// for more information)
/// </summary>
/// <param name='serviceName'>
/// The name of the cloud service.
/// </param>
/// <param name='extensionId'>
/// The identifier that was assigned to the extension when it was added
/// to the cloud service
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
Task<OperationResponse> BeginDeletingExtensionAsync(string serviceName, string extensionId, CancellationToken cancellationToken);
/// <summary>
/// The Check Hosted Service Name Availability operation checks for the
/// availability of the specified cloud service name. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/jj154116.aspx
/// for more information)
/// </summary>
/// <param name='serviceName'>
/// The cloud service name that you would like to use.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The Check Hosted Service Name Availability operation response.
/// </returns>
Task<HostedServiceCheckNameAvailabilityResponse> CheckNameAvailabilityAsync(string serviceName, CancellationToken cancellationToken);
/// <summary>
/// The Create Hosted Service operation creates a new cloud service in
/// Azure. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/gg441304.aspx
/// for more information)
/// </summary>
/// <param name='parameters'>
/// Parameters supplied to the Create Hosted Service operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
Task<OperationResponse> CreateAsync(HostedServiceCreateParameters parameters, CancellationToken cancellationToken);
/// <summary>
/// The Delete Hosted Service operation deletes the specified cloud
/// service from Azure. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/gg441305.aspx
/// for more information)
/// </summary>
/// <param name='serviceName'>
/// The name of the cloud service.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
Task<OperationResponse> DeleteAsync(string serviceName, CancellationToken cancellationToken);
/// <summary>
/// The DeleteAll Hosted Service operation deletes the specified cloud
/// service as well as operating system disk, attached data disks, and
/// the source blobs for the disks from storage from Microsoft Azure.
/// (see
/// 'http://msdn.microsoft.com/en-us/library/windowsazure/gg441305.aspx'
/// for more information)
/// </summary>
/// <param name='serviceName'>
/// The name of the cloud service.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request and error information regarding
/// the failure.
/// </returns>
Task<OperationStatusResponse> DeleteAllAsync(string serviceName, CancellationToken cancellationToken);
/// <summary>
/// The Delete Extension operation deletes the specified extension from
/// a cloud service. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/dn169560.aspx
/// for more information)
/// </summary>
/// <param name='serviceName'>
/// The name of the cloud service.
/// </param>
/// <param name='extensionId'>
/// The identifier that was assigned to the extension when it was added
/// to the cloud service
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request and error information regarding
/// the failure.
/// </returns>
Task<OperationStatusResponse> DeleteExtensionAsync(string serviceName, string extensionId, CancellationToken cancellationToken);
/// <summary>
/// The Get Hosted Service Properties operation retrieves system
/// properties for the specified cloud service. These properties
/// include the service name and service type; and the name of the
/// affinity group to which the service belongs, or its location if it
/// is not part of an affinity group. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/ee460806.aspx
/// for more information)
/// </summary>
/// <param name='serviceName'>
/// The name of the cloud service.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The Get Hosted Service operation response.
/// </returns>
Task<HostedServiceGetResponse> GetAsync(string serviceName, CancellationToken cancellationToken);
/// <summary>
/// The Get Detailed Hosted Service Properties operation retrieves
/// system properties for the specified cloud service. These
/// properties include the service name and service type; the name of
/// the affinity group to which the service belongs, or its location
/// if it is not part of an affinity group; and information on the
/// deployments of the service. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/ee460806.aspx
/// for more information)
/// </summary>
/// <param name='serviceName'>
/// The name of the cloud service.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The detailed Get Hosted Service operation response.
/// </returns>
Task<HostedServiceGetDetailedResponse> GetDetailedAsync(string serviceName, CancellationToken cancellationToken);
/// <summary>
/// The Get Extension operation retrieves information about a specified
/// extension that was added to a cloud service. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/dn169557.aspx
/// for more information)
/// </summary>
/// <param name='serviceName'>
/// The name of the cloud service.
/// </param>
/// <param name='extensionId'>
/// The identifier that was assigned to the extension when it was added
/// to the cloud service
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The Get Extension operation response.
/// </returns>
Task<HostedServiceGetExtensionResponse> GetExtensionAsync(string serviceName, string extensionId, CancellationToken cancellationToken);
/// <summary>
/// The List Hosted Services operation lists the cloud services
/// available under the current subscription. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/ee460781.aspx
/// for more information)
/// </summary>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The List Hosted Service operation response.
/// </returns>
Task<HostedServiceListResponse> ListAsync(CancellationToken cancellationToken);
/// <summary>
/// The List Available Extensions operation lists the extensions that
/// are available to add to your cloud service. In Windows Azure, a
/// process can run as an extension of a cloud service. For example,
/// Remote Desktop Access or the Azure Diagnostics Agent can run as
/// extensions to the cloud service. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/dn169559.aspx
/// for more information)
/// </summary>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The List Available Extensions operation response.
/// </returns>
Task<HostedServiceListAvailableExtensionsResponse> ListAvailableExtensionsAsync(CancellationToken cancellationToken);
/// <summary>
/// The List Extensions operation lists all of the extensions that were
/// added to a cloud service. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/dn169561.aspx
/// for more information)
/// </summary>
/// <param name='serviceName'>
/// The name of the cloud service.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The List Extensions operation response.
/// </returns>
Task<HostedServiceListExtensionsResponse> ListExtensionsAsync(string serviceName, CancellationToken cancellationToken);
/// <summary>
/// The List Extension Versions operation lists the versions of an
/// extension that are available to add to a cloud service. In Azure,
/// a process can run as an extension of a cloud service. For example,
/// Remote Desktop Access or the Azure Diagnostics Agent can run as
/// extensions to the cloud service. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/dn495437.aspx
/// for more information)
/// </summary>
/// <param name='providerNamespace'>
/// The provider namespace.
/// </param>
/// <param name='extensionType'>
/// The extension type name.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The List Available Extensions operation response.
/// </returns>
Task<HostedServiceListAvailableExtensionsResponse> ListExtensionVersionsAsync(string providerNamespace, string extensionType, CancellationToken cancellationToken);
/// <summary>
/// The Update Hosted Service operation can update the label or
/// description of a cloud service in Azure. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/gg441303.aspx
/// for more information)
/// </summary>
/// <param name='serviceName'>
/// The name of the cloud service.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the Update Hosted Service operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
Task<OperationResponse> UpdateAsync(string serviceName, HostedServiceUpdateParameters parameters, CancellationToken cancellationToken);
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// See the LICENSE file in the project root for more information.
// Copyright (C) 2005 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System.ComponentModel;
namespace System.Data.Tests
{
using Xunit;
public class DataViewTest_IBindingList
{
private DataTable _dt = new DataTable();
public DataViewTest_IBindingList()
{
_dt.Columns.Add("id", typeof(int));
_dt.Columns[0].AutoIncrement = true;
_dt.Columns[0].AutoIncrementSeed = 5;
_dt.Columns[0].AutoIncrementStep = 5;
_dt.Columns.Add("name", typeof(string));
_dt.Rows.Add(new object[] { null, "mono test 1" });
_dt.Rows.Add(new object[] { null, "mono test 3" });
_dt.Rows.Add(new object[] { null, "mono test 2" });
_dt.Rows.Add(new object[] { null, "mono test 4" });
}
[Fact]
public void PropertyTest()
{
DataView dv = new DataView(_dt);
IBindingList ib = dv;
Assert.True(ib.AllowEdit);
Assert.True(ib.AllowNew);
Assert.True(ib.AllowRemove);
Assert.False(ib.IsSorted);
Assert.Equal(ListSortDirection.Ascending, ib.SortDirection);
Assert.True(ib.SupportsChangeNotification);
Assert.True(ib.SupportsSearching);
Assert.True(ib.SupportsSorting);
Assert.Null(ib.SortProperty);
}
[Fact]
public void AddNewTest()
{
DataView dv = new DataView(_dt);
IBindingList ib = dv;
ib.ListChanged += new ListChangedEventHandler(OnListChanged);
try
{
_args = null;
object o = ib.AddNew();
Assert.Equal(typeof(DataRowView), o.GetType());
Assert.Equal(ListChangedType.ItemAdded, _args.ListChangedType);
Assert.Equal(4, _args.NewIndex);
Assert.Equal(-1, _args.OldIndex);
DataRowView r = (DataRowView)o;
Assert.Equal(25, r["id"]);
Assert.Equal(DBNull.Value, r["name"]);
Assert.Equal(5, dv.Count);
_args = null;
r.CancelEdit();
Assert.Equal(ListChangedType.ItemDeleted, _args.ListChangedType);
Assert.Equal(4, _args.NewIndex);
Assert.Equal(-1, _args.OldIndex);
Assert.Equal(4, dv.Count);
}
finally
{
ib.ListChanged -= new ListChangedEventHandler(OnListChanged);
}
}
private ListChangedEventArgs _args = null;
public void OnListChanged(object sender, ListChangedEventArgs args)
{
_args = args;
}
[Fact]
public void SortTest()
{
DataView dv = new DataView(_dt);
IBindingList ib = dv;
ib.ListChanged += new ListChangedEventHandler(OnListChanged);
try
{
_args = null;
dv.Sort = "[id] DESC";
Assert.Equal(ListChangedType.Reset, _args.ListChangedType);
Assert.Equal(-1, _args.NewIndex);
Assert.Equal(-1, _args.OldIndex);
Assert.True(ib.IsSorted);
Assert.NotNull(ib.SortProperty);
Assert.Equal(ListSortDirection.Descending, ib.SortDirection);
_args = null;
dv.Sort = null;
Assert.Equal(ListChangedType.Reset, _args.ListChangedType);
Assert.Equal(-1, _args.NewIndex);
Assert.Equal(-1, _args.OldIndex);
Assert.False(ib.IsSorted);
Assert.Null(ib.SortProperty);
PropertyDescriptorCollection pds = ((ITypedList)dv).GetItemProperties(null);
PropertyDescriptor pd = pds.Find("id", false);
_args = null;
ib.ApplySort(pd, ListSortDirection.Ascending);
Assert.Equal(ListChangedType.Reset, _args.ListChangedType);
Assert.Equal(-1, _args.NewIndex);
Assert.Equal(-1, _args.OldIndex);
Assert.True(ib.IsSorted);
Assert.NotNull(ib.SortProperty);
Assert.Equal("[id]", dv.Sort);
_args = null;
ib.RemoveSort();
Assert.Equal(ListChangedType.Reset, _args.ListChangedType);
Assert.Equal(-1, _args.NewIndex);
Assert.Equal(-1, _args.OldIndex);
Assert.False(ib.IsSorted);
Assert.Null(ib.SortProperty);
Assert.Equal(string.Empty, dv.Sort);
_args = null;
// descending
_args = null;
ib.ApplySort(pd, ListSortDirection.Descending);
Assert.Equal(20, dv[0][0]);
Assert.Equal("[id] DESC", dv.Sort);
_args = null;
}
finally
{
ib.ListChanged -= new ListChangedEventHandler(OnListChanged);
}
}
[Fact]
public void FindTest()
{
DataView dv = new DataView(_dt);
IBindingList ib = dv;
ib.ListChanged += new ListChangedEventHandler(OnListChanged);
try
{
_args = null;
dv.Sort = "id DESC";
PropertyDescriptorCollection pds = ((ITypedList)dv).GetItemProperties(null);
PropertyDescriptor pd = pds.Find("id", false);
int index = ib.Find(pd, 15);
Assert.Equal(1, index);
// negative search
index = ib.Find(pd, 44);
Assert.Equal(-1, index);
}
finally
{
ib.ListChanged -= new ListChangedEventHandler(OnListChanged);
}
}
[Fact]
public void TestIfCorrectIndexIsUsed()
{
DataTable table = new DataTable();
table.Columns.Add("id", typeof(int));
table.Rows.Add(new object[] { 1 });
table.Rows.Add(new object[] { 2 });
table.Rows.Add(new object[] { 3 });
table.Rows.Add(new object[] { 4 });
DataView dv = new DataView(table);
dv.Sort = "[id] DESC";
// for the new view, the index thats chosen, shud be different from the one
// created for the older view.
dv = new DataView(table);
IBindingList ib = dv;
PropertyDescriptorCollection pds = ((ITypedList)dv).GetItemProperties(null);
PropertyDescriptor pd = pds.Find("id", false);
int index = ib.Find(pd, 4);
Assert.Equal(3, index);
}
}
}
| |
using System;
using System.Windows.Forms;
using System.Drawing;
using System.Runtime.InteropServices;
using System.ComponentModel;
namespace WeifenLuo.WinFormsUI.Docking
{
[ToolboxItem(false)]
public partial class DockWindow : Panel, INestedPanesContainer, ISplitterDragSource
{
private DockPanel m_dockPanel;
private DockState m_dockState;
private SplitterControl m_splitter;
private NestedPaneCollection m_nestedPanes;
internal DockWindow(DockPanel dockPanel, DockState dockState)
{
m_nestedPanes = new NestedPaneCollection(this);
m_dockPanel = dockPanel;
m_dockState = dockState;
Visible = false;
SuspendLayout();
if (DockState == DockState.DockLeft || DockState == DockState.DockRight ||
DockState == DockState.DockTop || DockState == DockState.DockBottom)
{
m_splitter = new SplitterControl();
Controls.Add(m_splitter);
}
if (DockState == DockState.DockLeft)
{
Dock = DockStyle.Left;
m_splitter.Dock = DockStyle.Right;
}
else if (DockState == DockState.DockRight)
{
Dock = DockStyle.Right;
m_splitter.Dock = DockStyle.Left;
}
else if (DockState == DockState.DockTop)
{
Dock = DockStyle.Top;
m_splitter.Dock = DockStyle.Bottom;
}
else if (DockState == DockState.DockBottom)
{
Dock = DockStyle.Bottom;
m_splitter.Dock = DockStyle.Top;
}
else if (DockState == DockState.Document)
{
Dock = DockStyle.Fill;
}
ResumeLayout();
}
public VisibleNestedPaneCollection VisibleNestedPanes
{
get { return NestedPanes.VisibleNestedPanes; }
}
public NestedPaneCollection NestedPanes
{
get { return m_nestedPanes; }
}
public DockPanel DockPanel
{
get { return m_dockPanel; }
}
public DockState DockState
{
get { return m_dockState; }
}
public bool IsFloat
{
get { return DockState == DockState.Float; }
}
internal DockPane DefaultPane
{
get { return VisibleNestedPanes.Count == 0 ? null : VisibleNestedPanes[0]; }
}
public virtual Rectangle DisplayingRectangle
{
get
{
Rectangle rect = ClientRectangle;
// if DockWindow is document, exclude the border
if (DockState == DockState.Document)
{
rect.X += 1;
rect.Y += 1;
rect.Width -= 2;
rect.Height -= 2;
}
// exclude the splitter
else if (DockState == DockState.DockLeft)
rect.Width -= Measures.SplitterSize;
else if (DockState == DockState.DockRight)
{
rect.X += Measures.SplitterSize;
rect.Width -= Measures.SplitterSize;
}
else if (DockState == DockState.DockTop)
rect.Height -= Measures.SplitterSize;
else if (DockState == DockState.DockBottom)
{
rect.Y += Measures.SplitterSize;
rect.Height -= Measures.SplitterSize;
}
return rect;
}
}
protected override void OnPaint(PaintEventArgs e)
{
// if DockWindow is document, draw the border
if (DockState == DockState.Document)
e.Graphics.DrawRectangle(SystemPens.ControlDark, ClientRectangle.X, ClientRectangle.Y, ClientRectangle.Width - 1, ClientRectangle.Height - 1);
base.OnPaint(e);
}
protected override void OnLayout(LayoutEventArgs levent)
{
VisibleNestedPanes.Refresh();
if (VisibleNestedPanes.Count == 0)
{
if (Visible)
Visible = false;
}
else if (!Visible)
{
Visible = true;
VisibleNestedPanes.Refresh();
}
base.OnLayout (levent);
}
#region ISplitterDragSource Members
void ISplitterDragSource.BeginDrag(Rectangle rectSplitter)
{
}
void ISplitterDragSource.EndDrag()
{
}
bool ISplitterDragSource.IsVertical
{
get { return (DockState == DockState.DockLeft || DockState == DockState.DockRight); }
}
Rectangle ISplitterDragSource.DragLimitBounds
{
get
{
Rectangle rectLimit = DockPanel.DockArea;
Point location;
if ((Control.ModifierKeys & Keys.Shift) == 0)
location = Location;
else
location = DockPanel.DockArea.Location;
if (((ISplitterDragSource)this).IsVertical)
{
rectLimit.X += MeasurePane.MinSize;
rectLimit.Width -= 2 * MeasurePane.MinSize;
rectLimit.Y = location.Y;
if ((Control.ModifierKeys & Keys.Shift) == 0)
rectLimit.Height = Height;
}
else
{
rectLimit.Y += MeasurePane.MinSize;
rectLimit.Height -= 2 * MeasurePane.MinSize;
rectLimit.X = location.X;
if ((Control.ModifierKeys & Keys.Shift) == 0)
rectLimit.Width = Width;
}
return DockPanel.RectangleToScreen(rectLimit);
}
}
void ISplitterDragSource.MoveSplitter(int offset)
{
if ((Control.ModifierKeys & Keys.Shift) != 0)
SendToBack();
Rectangle rectDockArea = DockPanel.DockArea;
if (DockState == DockState.DockLeft && rectDockArea.Width > 0)
{
if (DockPanel.DockLeftPortion > 1)
DockPanel.DockLeftPortion = Width + offset;
else
DockPanel.DockLeftPortion += ((double)offset) / (double)rectDockArea.Width;
}
else if (DockState == DockState.DockRight && rectDockArea.Width > 0)
{
if (DockPanel.DockRightPortion > 1)
DockPanel.DockRightPortion = Width - offset;
else
DockPanel.DockRightPortion -= ((double)offset) / (double)rectDockArea.Width;
}
else if (DockState == DockState.DockBottom && rectDockArea.Height > 0)
{
if (DockPanel.DockBottomPortion > 1)
DockPanel.DockBottomPortion = Height - offset;
else
DockPanel.DockBottomPortion -= ((double)offset) / (double)rectDockArea.Height;
}
else if (DockState == DockState.DockTop && rectDockArea.Height > 0)
{
if (DockPanel.DockTopPortion > 1)
DockPanel.DockTopPortion = Height + offset;
else
DockPanel.DockTopPortion += ((double)offset) / (double)rectDockArea.Height;
}
}
#region IDragSource Members
Control IDragSource.DragControl
{
get { return this; }
}
#endregion
#endregion
}
}
| |
using System;
using System.IO;
using BigMath;
using Raksha.Crypto;
using Raksha.Crypto.IO;
using Raksha.Crypto.Parameters;
using Raksha.Math;
using Raksha.Security;
using Raksha.Utilities.IO;
namespace Raksha.Bcpg.OpenPgp
{
/// <remarks>A public key encrypted data object.</remarks>
public class PgpPublicKeyEncryptedData
: PgpEncryptedData
{
private PublicKeyEncSessionPacket keyData;
internal PgpPublicKeyEncryptedData(
PublicKeyEncSessionPacket keyData,
InputStreamPacket encData)
: base(encData)
{
this.keyData = keyData;
}
private static IBufferedCipher GetKeyCipher(
PublicKeyAlgorithmTag algorithm)
{
try
{
switch (algorithm)
{
case PublicKeyAlgorithmTag.RsaEncrypt:
case PublicKeyAlgorithmTag.RsaGeneral:
return CipherUtilities.GetCipher("RSA//PKCS1Padding");
case PublicKeyAlgorithmTag.ElGamalEncrypt:
case PublicKeyAlgorithmTag.ElGamalGeneral:
return CipherUtilities.GetCipher("ElGamal/ECB/PKCS1Padding");
default:
throw new PgpException("unknown asymmetric algorithm: " + algorithm);
}
}
catch (PgpException e)
{
throw e;
}
catch (Exception e)
{
throw new PgpException("Exception creating cipher", e);
}
}
private bool ConfirmCheckSum(
byte[] sessionInfo)
{
int check = 0;
for (int i = 1; i != sessionInfo.Length - 2; i++)
{
check += sessionInfo[i] & 0xff;
}
return (sessionInfo[sessionInfo.Length - 2] == (byte)(check >> 8))
&& (sessionInfo[sessionInfo.Length - 1] == (byte)(check));
}
/// <summary>The key ID for the key used to encrypt the data.</summary>
public long KeyId
{
get { return keyData.KeyId; }
}
/// <summary>
/// Return the algorithm code for the symmetric algorithm used to encrypt the data.
/// </summary>
public SymmetricKeyAlgorithmTag GetSymmetricAlgorithm(
PgpPrivateKey privKey)
{
byte[] plain = fetchSymmetricKeyData(privKey);
return (SymmetricKeyAlgorithmTag) plain[0];
}
/// <summary>Return the decrypted data stream for the packet.</summary>
public Stream GetDataStream(
PgpPrivateKey privKey)
{
byte[] plain = fetchSymmetricKeyData(privKey);
IBufferedCipher c2;
string cipherName = PgpUtilities.GetSymmetricCipherName((SymmetricKeyAlgorithmTag) plain[0]);
string cName = cipherName;
try
{
if (encData is SymmetricEncIntegrityPacket)
{
cName += "/CFB/NoPadding";
}
else
{
cName += "/OpenPGPCFB/NoPadding";
}
c2 = CipherUtilities.GetCipher(cName);
}
catch (PgpException e)
{
throw e;
}
catch (Exception e)
{
throw new PgpException("exception creating cipher", e);
}
if (c2 == null)
return encData.GetInputStream();
try
{
KeyParameter key = ParameterUtilities.CreateKeyParameter(
cipherName, plain, 1, plain.Length - 3);
byte[] iv = new byte[c2.GetBlockSize()];
c2.Init(false, new ParametersWithIV(key, iv));
encStream = BcpgInputStream.Wrap(new CipherStream(encData.GetInputStream(), c2, null));
if (encData is SymmetricEncIntegrityPacket)
{
truncStream = new TruncatedStream(encStream);
string digestName = PgpUtilities.GetDigestName(HashAlgorithmTag.Sha1);
IDigest digest = DigestUtilities.GetDigest(digestName);
encStream = new DigestStream(truncStream, digest, null);
}
if (Streams.ReadFully(encStream, iv, 0, iv.Length) < iv.Length)
throw new EndOfStreamException("unexpected end of stream.");
int v1 = encStream.ReadByte();
int v2 = encStream.ReadByte();
if (v1 < 0 || v2 < 0)
throw new EndOfStreamException("unexpected end of stream.");
// Note: the oracle attack on the "quick check" bytes is deemed
// a security risk for typical public key encryption usages,
// therefore we do not perform the check.
// bool repeatCheckPassed =
// iv[iv.Length - 2] == (byte)v1
// && iv[iv.Length - 1] == (byte)v2;
//
// // Note: some versions of PGP appear to produce 0 for the extra
// // bytes rather than repeating the two previous bytes
// bool zeroesCheckPassed =
// v1 == 0
// && v2 == 0;
//
// if (!repeatCheckPassed && !zeroesCheckPassed)
// {
// throw new PgpDataValidationException("quick check failed.");
// }
return encStream;
}
catch (PgpException e)
{
throw e;
}
catch (Exception e)
{
throw new PgpException("Exception starting decryption", e);
}
}
private byte[] fetchSymmetricKeyData(
PgpPrivateKey privKey)
{
IBufferedCipher c1 = GetKeyCipher(keyData.Algorithm);
try
{
c1.Init(false, privKey.Key);
}
catch (InvalidKeyException e)
{
throw new PgpException("error setting asymmetric cipher", e);
}
BigInteger[] keyD = keyData.GetEncSessionKey();
if (keyData.Algorithm == PublicKeyAlgorithmTag.RsaEncrypt
|| keyData.Algorithm == PublicKeyAlgorithmTag.RsaGeneral)
{
c1.ProcessBytes(keyD[0].ToByteArrayUnsigned());
}
else
{
ElGamalPrivateKeyParameters k = (ElGamalPrivateKeyParameters)privKey.Key;
int size = (k.Parameters.P.BitLength + 7) / 8;
byte[] bi = keyD[0].ToByteArray();
int diff = bi.Length - size;
if (diff >= 0)
{
c1.ProcessBytes(bi, diff, size);
}
else
{
byte[] zeros = new byte[-diff];
c1.ProcessBytes(zeros);
c1.ProcessBytes(bi);
}
bi = keyD[1].ToByteArray();
diff = bi.Length - size;
if (diff >= 0)
{
c1.ProcessBytes(bi, diff, size);
}
else
{
byte[] zeros = new byte[-diff];
c1.ProcessBytes(zeros);
c1.ProcessBytes(bi);
}
}
byte[] plain;
try
{
plain = c1.DoFinal();
}
catch (Exception e)
{
throw new PgpException("exception decrypting secret key", e);
}
if (!ConfirmCheckSum(plain))
throw new PgpKeyValidationException("key checksum failed");
return plain;
}
}
}
| |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using AsyncRPGSharedLib.Environment;
public class WidgetGroup : IWidget, IWidgetEventListener
{
private IWidgetEventListener m_widgetEventListener;
private WidgetGroup m_parentWidgetGroup;
private List<IWidget> m_childWidgets;
private Point2d m_localPosition;
private Point2d m_worldPosition;
public WidgetGroup(WidgetGroup parentGroup, float width, float height, float x, float y)
{
m_widgetEventListener = null;
m_childWidgets = new List<IWidget>() { };
m_parentWidgetGroup = parentGroup;
m_localPosition = new Point2d();
m_worldPosition = new Point2d();
Width = width;
Height = height;
Visible = true;
if (m_parentWidgetGroup != null)
{
m_parentWidgetGroup.AddWidget(this);
}
SetLocalPosition(x, y);
}
public WidgetGroup ParentWidgetGroup
{
get { return m_parentWidgetGroup; }
}
public int ChildWidgetCount
{
get { return m_childWidgets.Count; }
}
public IWidget GetChildWidget(int index)
{
return m_childWidgets[index];
}
public void AddWidget(IWidget widget)
{
m_childWidgets.Add(widget);
}
public bool RemoveWidget(IWidget widget)
{
return m_childWidgets.Remove(widget);
}
public IWidget FindChildIWidgetContainingPoint(Point2d point)
{
IWidget containingWidget = null;
bool hasDegenerateSize = (this.Width <= 0.0f || this.Height <= 0.0f);
// Only consider this group if this group contains the point or if it's zero-sized
// AND if the group actually has children in it
if (m_childWidgets.Count > 0 &&
(this.ContainsWorldPositionPoint(point) || hasDegenerateSize))
{
// We go through the child list backwards because the last child is on top
for (int childWidgetIndex = m_childWidgets.Count - 1; childWidgetIndex >= 0; childWidgetIndex--)
{
IWidget childWidget = m_childWidgets[childWidgetIndex];
if (childWidget.Visible)
{
if (childWidget is WidgetGroup)
{
containingWidget = ((WidgetGroup)childWidget).FindChildIWidgetContainingPoint(point);
}
else if (childWidget.ContainsWorldPositionPoint(point))
{
containingWidget = childWidget;
}
}
if (containingWidget != null)
{
break;
}
}
// If no children contain the point, and this group is a window widget
// then say that this group contains the point
if (containingWidget == null && this is WindowWidget)
{
containingWidget = this;
}
}
return containingWidget;
}
// IWidgetEventListener
public void SetWidgetEventListener(IWidgetEventListener listener)
{
m_widgetEventListener = listener;
}
public virtual void OnWidgetEvent(WidgetEvent widgetEvent)
{
if (m_widgetEventListener != null)
{
m_widgetEventListener.OnWidgetEvent(widgetEvent);
}
else if (m_parentWidgetGroup != null)
{
m_parentWidgetGroup.OnWidgetEvent(widgetEvent);
}
}
// IWidget
public bool Visible { get; set; }
public float Width { get; set; }
public float Height { get; set; }
public Point2d LocalPosition
{
get { return new Point2d(m_localPosition); }
}
public float LocalX
{
get { return m_localPosition.x; }
}
public float LocalY
{
get { return m_localPosition.y; }
}
public void SetLocalPosition(float x, float y)
{
m_localPosition = new Point2d(x, y);
UpdateWorldPosition();
}
public Point2d WorldPosition
{
get { return new Point2d(m_worldPosition); }
}
public float WorldX
{
get { return m_worldPosition.x; }
}
public float WorldY
{
get { return m_worldPosition.y; }
}
public bool ContainsWorldPositionPoint(Point2d point)
{
float minX = this.WorldX;
float minY = this.WorldY;
float maxX = minX + this.Width;
float maxY = minY + this.Height;
bool containsPoint= (point.x > minX && point.x < maxX && point.y > minY && point.y < maxY);
return containsPoint;
}
public virtual void UpdateWorldPosition()
{
if (m_parentWidgetGroup != null)
{
m_worldPosition = m_parentWidgetGroup.WorldPosition.Offset(m_localPosition.x, m_localPosition.y);
}
else
{
m_worldPosition.Set(m_localPosition.x, m_localPosition.y);
}
for (int childIndex = 0; childIndex < m_childWidgets.Count; childIndex++ )
{
IWidget widget = m_childWidgets[childIndex];
widget.UpdateWorldPosition();
}
}
public virtual void OnGUI()
{
if (Visible)
{
foreach (IWidget widget in m_childWidgets)
{
widget.OnGUI();
}
}
}
public virtual void OnDestroy()
{
for (int childIndex = 0; childIndex < m_childWidgets.Count; childIndex++ )
{
IWidget widget = m_childWidgets[childIndex];
widget.OnDestroy();
}
// Clear references to the parent and children
m_parentWidgetGroup = null;
m_childWidgets = new List<IWidget>();
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Microsoft.Msagl.Core.DataStructures;
using Microsoft.Msagl.Core.Geometry;
using Microsoft.Msagl.Core.Geometry.Curves;
using Microsoft.Msagl.Core.Layout;
using Microsoft.Msagl.Layout.LargeGraphLayout;
using Microsoft.Msagl.Miscellaneous.LayoutEditing;
using Microsoft.Msagl.Routing;
using GeomNode = Microsoft.Msagl.Core.Layout.Node;
namespace Microsoft.Msagl.Miscellaneous.LayoutEditing
{
/// <summary>
///
/// </summary>
public class IncrementalDragger {
GeometryGraph graph { get; set; }
readonly double nodeSeparation;
readonly LayoutAlgorithmSettings layoutSettings;
List<BumperPusher> listOfPushers = new List<BumperPusher>();
readonly GeomNode[] pushingNodesArray;
/// <summary>
/// it is smaller graph that needs to be refreshed by the viewer
/// </summary>
public GeometryGraph ChangedGraph;
Dictionary<EdgeGeometry,LabelFixture> labelFixtures=new Dictionary<EdgeGeometry, LabelFixture>();
/// <summary>
///
/// </summary>
/// <param name="pushingNodes">the nodes are already at the correct positions</param>
/// <param name="graph"></param>
/// <param name="layoutSettings"></param>
public IncrementalDragger(IEnumerable<GeomNode> pushingNodes, GeometryGraph graph, LayoutAlgorithmSettings layoutSettings) {
this.graph = graph;
this.nodeSeparation = layoutSettings.NodeSeparation;
this.layoutSettings = layoutSettings;
pushingNodesArray = pushingNodes as GeomNode[] ?? pushingNodes.ToArray();
Debug.Assert(pushingNodesArray.All(n => DefaultClusterParent(n) == null) ||
(new Set<GeomNode>(pushingNodesArray.Select(n => n.ClusterParents.First()))).Count == 1,
"dragged nodes have to belong to the same cluster");
InitBumperPushers();
}
void InitBumperPushers() {
if (pushingNodesArray.Length == 0) return;
var cluster = DefaultClusterParent(pushingNodesArray[0]);
if (cluster == null)
listOfPushers.Add(new BumperPusher(graph.Nodes, nodeSeparation, pushingNodesArray));
else {
listOfPushers.Add( new BumperPusher(cluster.Nodes.Concat(cluster.Clusters), nodeSeparation,
pushingNodesArray));
do {
var pushingCluster = cluster;
cluster = DefaultClusterParent(cluster);
if (cluster == null) break;
listOfPushers.Add(new BumperPusher(cluster.Nodes.Concat(cluster.Clusters), nodeSeparation,
new[] {pushingCluster}));
} while (true);
}
}
static Cluster DefaultClusterParent(GeomNode n) {
return n.ClusterParents.FirstOrDefault();
}
void RunPushers() {
for (int i = 0; i < listOfPushers.Count;i++ ) {
var bumperPusher = listOfPushers[i];
bumperPusher.PushNodes();
var cluster = DefaultClusterParent(bumperPusher.FirstPushingNode());
if (cluster == null || cluster==graph.RootCluster) break;
var box = cluster.BoundaryCurve.BoundingBox;
cluster.CalculateBoundsFromChildren(layoutSettings.ClusterMargin);
Debug.Assert(cluster.Nodes.All(n => cluster.BoundingBox.Contains(n.BoundingBox)));
var newBox = cluster.BoundaryCurve.BoundingBox;
if (newBox == box) {
break;
}
listOfPushers[i + 1].UpdateRTreeByChangedNodeBox(cluster, box);
}
}
/// <summary>
///
/// </summary>
/// <param name="delta"></param>
public void Drag(Point delta) {
if(delta.Length>0)
foreach (var n in pushingNodesArray) {
n.Center += delta;
var cl = n as Cluster;
if (cl != null)
cl.DeepContentsTranslation(delta, true);
}
RunPushers();
RouteChangedEdges();
}
void RouteChangedEdges() {
ChangedGraph = GetChangedFlatGraph();
var changedClusteredGraph = LgInteractor.CreateClusteredSubgraphFromFlatGraph(ChangedGraph, graph);
InitLabelFixtures(changedClusteredGraph);
var router = new SplineRouter(changedClusteredGraph, layoutSettings.EdgeRoutingSettings.Padding,
layoutSettings.EdgeRoutingSettings.PolylinePadding,
layoutSettings.EdgeRoutingSettings.ConeAngle,
layoutSettings.EdgeRoutingSettings.BundlingSettings) {
ContinueOnOverlaps
= true
};
router.Run();
PositionLabels(changedClusteredGraph);
}
void PositionLabels(GeometryGraph changedClusteredGraph) {
foreach (var edge in changedClusteredGraph.Edges)
PositionEdge(edge);
}
void PositionEdge(Edge edge) {
LabelFixture lf;
if (!labelFixtures.TryGetValue(edge.EdgeGeometry, out lf)) return;
var curve = edge.Curve;
var lenAtLabelAttachment = curve.Length*lf.RelativeLengthOnCurve;
var par = curve.GetParameterAtLength(lenAtLabelAttachment);
var tang = curve.Derivative(par);
var norm = (lf.RightSide ? tang.Rotate90Cw() : tang.Rotate90Ccw()).Normalize()*lf.NormalLength;
edge.Label.Center = curve[par] + norm;
}
void InitLabelFixtures(GeometryGraph changedClusteredGraph) {
foreach (var edge in changedClusteredGraph.Edges)
InitLabelFixture(edge);
}
void InitLabelFixture(Edge edge) {
if (edge.Label == null) return;
if (labelFixtures.ContainsKey(edge.EdgeGeometry)) return;
var attachmentPar = edge.Curve.ClosestParameter(edge.Label.Center);
var curve = edge.Curve;
var tang = curve.Derivative(attachmentPar);
var normal = tang.Rotate90Cw();
var fromCurveToLabel = edge.Label.Center - curve[attachmentPar];
var fixture = new LabelFixture() {
RelativeLengthOnCurve = curve.LengthPartial(0, attachmentPar)/curve.Length,
NormalLength = fromCurveToLabel.Length,
RightSide = fromCurveToLabel*normal>0
};
labelFixtures[edge.EdgeGeometry] = fixture;
}
GeometryGraph GetChangedFlatGraph() {
var changedNodes = GetChangedNodes();
var changedEdges = GetChangedEdges(changedNodes);
foreach (var e in changedEdges) {
changedNodes.Insert(e.Source);
changedNodes.Insert(e.Target);
}
var changedGraph = new GeometryGraph {
Nodes = new SimpleNodeCollection(changedNodes),
Edges = new SimpleEdgeCollection(changedEdges)
};
return changedGraph;
}
List<Edge> GetChangedEdges(Set<Node> changedNodes) {
var list = new List<Edge>();
var box = Rectangle.CreateAnEmptyBox();
foreach(var node in changedNodes)
box.Add(node.BoundaryCurve.BoundingBox);
var boxPoly = box.Perimeter();
foreach (var e in graph.Edges)
if (EdgeNeedsRouting(ref box, e, boxPoly, changedNodes))
list.Add(e);
return list;
}
bool EdgeNeedsRouting(ref Rectangle box, Edge edge, Polyline boxPolyline, Set<Node> changedNodes) {
if (edge.Curve == null)
return true;
if (changedNodes.Contains(edge.Source) || changedNodes.Contains(edge.Target))
return true;
if (edge.Source.BoundaryCurve.BoundingBox.Intersects(box) ||
edge.Target.BoundaryCurve.BoundingBox.Intersects(box))
return true;
if (!edge.BoundingBox.Intersects(box))
return false;
return Curve.CurveCurveIntersectionOne(boxPolyline, edge.Curve, false) != null;
}
Set<Node> GetChangedNodes() {
return new Set<Node>(this.listOfPushers.SelectMany(p => p.FixedNodes));
}
}
}
| |
#region Copyright (C) 2005 Rob Blackwell & Active Web Solutions.
//
// L Sharp .NET, a powerful lisp-based scripting language for .NET.
// Copyright (C) 2005 Rob Blackwell & Active Web Solutions.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Library General Public
// License as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Library General Public License for more details.
//
// You should have received a copy of the GNU Library General Public
// License along with this library; if not, write to the Free
// Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
//
#endregion
using System;
using System.Reflection;
using System.IO;
namespace LSharp
{
[AttributeUsage(AttributeTargets.Assembly)]
public sealed class LSharpExtensionAttribute : Attribute
{
}
/// <summary>
/// Allows LSharp programs to be executed
/// </summary>
public sealed class Runtime
{
Runtime(){}
private static IProfiler profiler = new DefaultProfiler();
/// <summary>
/// Maps eval to a list of expressions
/// </summary>
/// <param name="list"></param>
/// <param name="environment"></param>
/// <returns></returns>
public static Cons EvalList(object list, Environment environment)
{
if (list == null)
return null;
object result = null;
foreach (object item in (Cons)list )
{
result = new Cons(Eval(item,environment) ,result);
}
return ((Cons)result).Reverse();
}
/// <summary>
/// Evaluates an expression in a given lexical environment
/// </summary>
/// <param name="form"></param>
/// <param name="environment"></param>
/// <returns></returns>
public static Object Eval (Object expression, Environment environment)
{
profiler.TraceCall (expression);
if (expression == Reader.EOFVALUE)
{
return profiler.TraceReturn(expression);
}
if (expression == null)
return profiler.TraceReturn(null);
// The expression is either an atom or a list
if (Primitives.IsAtom(expression))
{
// Number
if (expression is double)
return profiler.TraceReturn(expression);
if (expression is int)
return profiler.TraceReturn(expression);
// Character
if (expression is char)
return profiler.TraceReturn(expression);
// String
if (expression is string)
return profiler.TraceReturn(expression);
Symbol sym = expression as Symbol;
if (sym == Symbol.TRUE)
return profiler.TraceReturn(true);
if (sym == Symbol.FALSE)
return profiler.TraceReturn(false);
if (sym == Symbol.NULL)
return profiler.TraceReturn(null);
// If the symbol is bound to a value in this lexical environment
if (environment.Contains(sym))
// Then it's a variable so return it's value
return profiler.TraceReturn(environment.GetValue(sym));
else
{
// Otherwise symbols evaluate to themselves
return profiler.TraceReturn(expression);
}
}
else
{
// The expression must be a list
Cons cons = (Cons) expression;
// Lists are assumed to be of the form (function arguments)
// See if there is a binding to a function, clsoure, macro or special form
// in this lexical environment
object function = environment.GetValue((Symbol)cons.First());
// If there is no binding, then use the function name directly - it's probably
// the name of a .NET method
if (function == null)
function = cons.First();
// If it's a special form
if (function is SpecialForm)
{
return profiler.TraceReturn(((SpecialForm) function) ((Cons)cons.Cdr(),environment));
}
// If its a macro application
if (function is Macro)
{
object expansion = ((Macro) function).Expand((Cons)cons.Cdr());
return profiler.TraceReturn(Runtime.Eval(expansion, environment));
}
// It must be a function, closure or method invocation,
// so call apply
Object arguments = EvalList((Cons)cons.Cdr(),environment);
return profiler.TraceReturn(Runtime.Apply(function, arguments, environment));
}
}
/// <summary>
/// Makes a new instance of type type by calling the
/// appropriate constructor, passing the given arguments
/// </summary>
/// <param name="type">The type of object to create</param>
/// <param name="arguments">the arguments to the constructor</param>
/// <returns></returns>
public static object MakeInstance(Type type, object arguments)
{
Type[] types = new Type[0];
object[] paramters = new object[0];
if (arguments != null)
{
types = new Type[((Cons)arguments).Length()];
paramters = new object[((Cons)arguments).Length()];
int loop = 0;
foreach (object argument in (Cons)arguments)
{
types[loop] = argument.GetType();
paramters[loop] = argument;
loop++;
}
}
ConstructorInfo constructorInfo = type.GetConstructor(types);
if (constructorInfo == null)
throw new LSharpException(string.Format("No such constructor for {0}",type));
return constructorInfo.Invoke(paramters);
}
/// <summary>
/// Calls a .NET method.
/// The first argument is the object to which the method is attached.
/// Passes the rest of the arguments to the appropriate constructor
/// </summary>
/// <param name="method"></param>
/// <param name="arguments"></param>
/// <returns></returns>
public static object Call(String method, Cons arguments)
{
BindingFlags bindingFlags = BindingFlags.IgnoreCase
| BindingFlags.Public
| BindingFlags.NonPublic;
string methname = method;
string typename = string.Empty;
Type type = null;
int i = methname.LastIndexOf(".");
if (i >= 0)
{
methname = methname.Substring(i + 1);
typename = method.Substring(0, i);
type = TypeCache.FindType(typename);
}
// Is it a method on a static type or an object instance ?
if (type == null)
{
if (arguments.First() is Symbol)
{
bindingFlags = bindingFlags | BindingFlags.Static | BindingFlags.FlattenHierarchy;
// Find the type object from its name
type = TypeCache.FindType(arguments.First().ToString());
}
else
{
bindingFlags = bindingFlags | BindingFlags.Instance;
type = arguments.First().GetType();
}
}
else
{
bindingFlags = bindingFlags | BindingFlags.Instance;
}
if (type == null)
{
throw new LSharpException(string.Format("Call: No such type '{0}'. Did you forget a 'using'?", arguments.First()));
}
Type[] types = new Type[arguments.Length() -1];
object[] parameters = new object[arguments.Length() -1];
int loop = 0;
if (arguments.Rest() != null)
foreach (object argument in (Cons)arguments.Rest())
{
types[loop] = argument.GetType();
parameters[loop] = argument;
loop++;
}
// Start by looking for a method call
MethodInfo m = type.GetMethod(methname,
bindingFlags | BindingFlags.InvokeMethod
,null,types,null);
if (m != null)
return m.Invoke(arguments.First(),parameters);
// Now loook for a property get
PropertyInfo p = type.GetProperty(methname,bindingFlags | BindingFlags.GetProperty,
null,null, types,null);
if (p != null)
{
return p.GetGetMethod().Invoke(arguments.First(),parameters);
}
// Now look for a field get
FieldInfo f = type.GetField(methname,bindingFlags | BindingFlags.GetField);
if (f != null)
return f.GetValue(arguments.First());
// or an event ?
throw new LSharpException(string.Format("Call: No such method, property or field '{1}.{0}({2})'",
method.ToString(),type, TypeString(types, parameters)));
}
static string TypeString(Type[] ts, object[] parameters)
{
string[] tss = new string[ts.Length];
for (int i = 0; i < tss.Length; i++)
{
tss[i] = ts[i].Name + "=" + Printer.WriteToString(parameters[i]);
}
return string.Join(", ", tss);
}
/// <summary>
/// Applies a function to its arguments. The function can be a built in L Sharp function,
/// a closure or a .net method
/// </summary>
/// <param name="function"></param>
/// <param name="arguments"></param>
/// <param name="environment"></param>
/// <returns></returns>
public static object Apply (object function, object arguments, Environment environment)
{
if (function is Function)
{
return ((Function) function) ((Cons)arguments,environment);
}
// If function is an LSharp Closure, then invoke it
if (function is Closure)
{
if (arguments == null)
return ((Closure)function).Invoke();
else
return ((Closure)function).Invoke((Cons)arguments);
}
else
{
// It must be a .net method call
return Call(function.ToString(),(Cons)arguments);
}
}
public static object ReadString(string expression)
{
return ReadString(expression, new Environment());
}
public static object ReadString(string expression, Environment environment)
{
ReadTable readTable = (ReadTable) environment.GetValue(Symbol.FromName("*readtable*"));
object input = Reader.Read(new StringReader(expression), readTable);
return input;
}
public static object EvalString (string expression)
{
return EvalString(expression, new Environment());
}
public static object EvalString (string expression, Environment environment)
{
object input = ReadString(expression, environment);
object output = Runtime.Eval(input, environment);
return output;
}
public static object Import(string assembly, Environment environment)
{
string fn = Path.GetFullPath(assembly);
Assembly ass = AssemblyCache.LoadAssembly(fn);
ass = Import(ass);
if (ass != null)
{
environment.UpdateBindings();
return Path.GetFileName(fn);
}
else
{
return null;
}
}
public static Assembly Import(Assembly assembly)
{
if (assembly != null)
{
if (Attribute.IsDefined(assembly, typeof(LSharpExtensionAttribute)))
{
foreach (Type t in assembly.GetTypes())
{
if ( Attribute.IsDefined(t, typeof(FunctionAttribute)))
{
RegisterFunctionExtension(t);
}
else
if ( Attribute.IsDefined(t, typeof(SpecialFormAttribute)))
{
RegisterSpecialFormExtension(t);
}
else
if ( Attribute.IsDefined(t, typeof(MacroAttribute)))
{
RegisterMacroExtension(t);
}
}
}
}
return assembly;
}
public static void RegisterSpecialFormExtension(Type t)
{
Environment.RegisterExtension(t, typeof(SpecialForm));
}
public static void RegisterFunctionExtension(Type t)
{
Environment.RegisterExtension(t, typeof(Function));
}
public static void RegisterMacroExtension(Type t)
{
Environment.RegisterMacroExtension(t);
}
public static IProfiler Profiler
{
get
{
return profiler;
}
set
{
profiler = value;
}
}
public static object BackQuoteExpand(Object form, Environment environment)
{
if (!(form is Cons))
return form;
Cons expression = (Cons) form;
Cons result = null;
foreach (object item in expression)
{
if (item is Cons)
{
Cons list = (Cons)item;
Symbol sym = list.First() as Symbol;
if (sym == Symbol.BACKQUOTE)
{
result = new Cons(BackQuoteExpand(list.Second(),environment), result);
}
else if (sym == Symbol.UNQUOTE)
{
result = new Cons(Runtime.Eval(BackQuoteExpand(list.Second(),environment),environment), result);
}
else if (sym == Symbol.SPLICE)
{
Cons l = (Cons)Runtime.Eval(BackQuoteExpand(list.Second(),environment),environment);
foreach(object o in l)
{
result = new Cons(o, result);
}
}
else
{
result = new Cons(BackQuoteExpand(item,environment), result);
}
}
else
{
result = new Cons(item, result);
}
}
return result.Reverse();
}
}
}
| |
// 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.16.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.DevTestLabs
{
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Azure.OData;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// LabOperations operations.
/// </summary>
public partial interface ILabOperations
{
/// <summary>
/// List labs in a subscription.
/// </summary>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<IPage<Lab>>> ListBySubscriptionWithHttpMessagesAsync(ODataQuery<Lab> odataQuery = default(ODataQuery<Lab>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// List labs in a resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<IPage<Lab>>> ListByResourceGroupWithHttpMessagesAsync(string resourceGroupName, ODataQuery<Lab> odataQuery = default(ODataQuery<Lab>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get lab.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='name'>
/// The name of the lab.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<Lab>> GetResourceWithHttpMessagesAsync(string resourceGroupName, string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Create or replace an existing Lab. This operation can take a while
/// to complete.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='name'>
/// The name of the lab.
/// </param>
/// <param name='lab'>
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<Lab>> CreateOrUpdateResourceWithHttpMessagesAsync(string resourceGroupName, string name, Lab lab, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Create or replace an existing Lab. This operation can take a while
/// to complete.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='name'>
/// The name of the lab.
/// </param>
/// <param name='lab'>
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<Lab>> BeginCreateOrUpdateResourceWithHttpMessagesAsync(string resourceGroupName, string name, Lab lab, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Delete lab. This operation can take a while to complete.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='name'>
/// The name of the lab.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse> DeleteResourceWithHttpMessagesAsync(string resourceGroupName, string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Delete lab. This operation can take a while to complete.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='name'>
/// The name of the lab.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse> BeginDeleteResourceWithHttpMessagesAsync(string resourceGroupName, string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Modify properties of labs.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='name'>
/// The name of the lab.
/// </param>
/// <param name='lab'>
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<Lab>> PatchResourceWithHttpMessagesAsync(string resourceGroupName, string name, Lab lab, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Create virtual machines in a Lab. This operation can take a while
/// to complete.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='name'>
/// The name of the lab.
/// </param>
/// <param name='labVirtualMachine'>
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse> CreateEnvironmentWithHttpMessagesAsync(string resourceGroupName, string name, LabVirtualMachine labVirtualMachine, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Create virtual machines in a Lab. This operation can take a while
/// to complete.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='name'>
/// The name of the lab.
/// </param>
/// <param name='labVirtualMachine'>
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse> BeginCreateEnvironmentWithHttpMessagesAsync(string resourceGroupName, string name, LabVirtualMachine labVirtualMachine, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Generate a URI for uploading custom disk images to a Lab.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='name'>
/// The name of the lab.
/// </param>
/// <param name='generateUploadUriParameter'>
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<GenerateUploadUriResponse>> GenerateUploadUriWithHttpMessagesAsync(string resourceGroupName, string name, GenerateUploadUriParameter generateUploadUriParameter, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// List disk images available for custom image creation.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='name'>
/// The name of the lab.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<IPage<LabVhd>>> ListVhdsWithHttpMessagesAsync(string resourceGroupName, string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// List labs in a subscription.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<IPage<Lab>>> ListBySubscriptionNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// List labs in a resource group.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<IPage<Lab>>> ListByResourceGroupNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// List disk images available for custom image creation.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<IPage<LabVhd>>> ListVhdsNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
// Copyright 2011 Microsoft Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
namespace Microsoft.Data.OData.Json
{
#region Namespaces
using System;
using System.Diagnostics;
using o = Microsoft.Data.OData;
#endregion Namespaces
/// <summary>
/// Base class for all OData JSON serializers.
/// </summary>
internal class ODataJsonSerializer : ODataSerializer
{
/// <summary>
/// The JSON output context to write to.
/// </summary>
private readonly ODataJsonOutputContext jsonOutputContext;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="jsonOutputContext">The output context to write to.</param>
internal ODataJsonSerializer(ODataJsonOutputContext jsonOutputContext)
: base(jsonOutputContext)
{
DebugUtils.CheckNoExternalCallers();
Debug.Assert(jsonOutputContext != null, "jsonOutputContext != null");
this.jsonOutputContext = jsonOutputContext;
}
/// <summary>
/// Returns the <see cref="JsonWriter"/> which is to be used to write the content of the message.
/// </summary>
internal JsonWriter JsonWriter
{
get
{
DebugUtils.CheckNoExternalCallers();
return this.jsonOutputContext.JsonWriter;
}
}
/// <summary>
/// Writes the start of the entire JSON payload.
/// </summary>
internal void WritePayloadStart()
{
DebugUtils.CheckNoExternalCallers();
this.WritePayloadStart(/*disableResponseWrapper*/ false);
}
/// <summary>
/// Writes the start of the entire JSON payload.
/// </summary>
/// <param name="disableResponseWrapper">When set to true the "d" response wrapper won't be written even in responses</param>
internal void WritePayloadStart(bool disableResponseWrapper)
{
DebugUtils.CheckNoExternalCallers();
if (this.WritingResponse && !disableResponseWrapper)
{
// If we're writing a response payload the entire JSON should be wrapped in { "d": } to guard against XSS attacks
// it makes the payload a valid JSON but invalid JScript statement.
this.JsonWriter.StartObjectScope();
this.JsonWriter.WriteDataWrapper();
}
}
/// <summary>
/// Writes the end of the enitire JSON payload.
/// </summary>
internal void WritePayloadEnd()
{
DebugUtils.CheckNoExternalCallers();
this.WritePayloadEnd(/*disableResponseWrapper*/ false);
}
/// <summary>
/// Writes the end of the enitire JSON payload.
/// </summary>
/// <param name="disableResponseWrapper">When set to true the "d" response wrapper won't be written even in responses</param>
internal void WritePayloadEnd(bool disableResponseWrapper)
{
DebugUtils.CheckNoExternalCallers();
if (this.WritingResponse && !disableResponseWrapper)
{
// If we were writing a response payload the entire JSON is wrapped in an object scope, which we need to close here.
this.JsonWriter.EndObjectScope();
}
}
/// <summary>
/// Helper method to write the data wrapper around a JSON payload.
/// </summary>
/// <param name="payloadWriterAction">The action that writes the actual JSON payload that is being wrapped.</param>
internal void WriteTopLevelPayload(Action payloadWriterAction)
{
DebugUtils.CheckNoExternalCallers();
this.WriteTopLevelPayload(payloadWriterAction, /*disableResponseWrapper*/ false);
}
/// <summary>
/// Helper method to write the data wrapper around a JSON payload.
/// </summary>
/// <param name="payloadWriterAction">The action that writes the actual JSON payload that is being wrapped.</param>
/// <param name="disableResponseWrapper">When set to true the "d" response wrapper won't be written even in responses</param>
internal void WriteTopLevelPayload(Action payloadWriterAction, bool disableResponseWrapper)
{
DebugUtils.CheckNoExternalCallers();
Debug.Assert(payloadWriterAction != null, "payloadWriterAction != null");
this.WritePayloadStart(disableResponseWrapper);
payloadWriterAction();
this.WritePayloadEnd(disableResponseWrapper);
}
/// <summary>
/// Write a top-level error message.
/// </summary>
/// <param name="error">The error instance to write.</param>
/// <param name="includeDebugInformation">A flag indicating whether error details should be written (in debug mode only) or not.</param>
internal void WriteTopLevelError(ODataError error, bool includeDebugInformation)
{
DebugUtils.CheckNoExternalCallers();
Debug.Assert(error != null, "error != null");
// Top-level error payloads in JSON don't use the "d" wrapper even in responses!
this.WriteTopLevelPayload(
() => ODataJsonWriterUtils.WriteError(this.JsonWriter, error, includeDebugInformation, this.MessageWriterSettings.MessageQuotas.MaxNestingDepth),
/*disableResponseWrapper*/ true);
}
/// <summary>
/// Converts the specified URI into an absolute URI.
/// </summary>
/// <param name="uri">The uri to process.</param>
/// <returns>An absolute URI which is either the specified <paramref name="uri"/> if it was absolute,
/// or it's a combination of the BaseUri and the relative <paramref name="uri"/>.
/// The return value is the string representation of the URI.</returns>
/// <remarks>This method will fail if the specified <paramref name="uri"/> is relative and there's no base URI available.</remarks>
internal string UriToAbsoluteUriString(Uri uri)
{
DebugUtils.CheckNoExternalCallers();
Debug.Assert(uri != null, "uri != null");
return this.UriToUriString(uri, /*makeAbsolute*/ true);
}
/// <summary>
/// Returns the string representation of the URI; Converts the URI into an absolute URI if the <paramref name="makeAbsolute"/> parameter is set to true.
/// </summary>
/// <param name="uri">The uri to process.</param>
/// <param name="makeAbsolute">true, if the URI needs to be translated into an absolute URI; false otherwise.</param>
/// <returns>If the <paramref name="makeAbsolute"/> parameter is set to true, then a string representation of an absolute URI which is either the
/// specified <paramref name="uri"/> if it was absolute, or it's a combination of the BaseUri and the relative <paramref name="uri"/>;
/// otherwise a string representation of the specified <paramref name="uri"/>.
/// </returns>
/// <remarks>This method will fail if <paramref name="makeAbsolute"/> is set to true and the specified <paramref name="uri"/> is relative and there's no base URI available.</remarks>
internal string UriToUriString(Uri uri, bool makeAbsolute)
{
DebugUtils.CheckNoExternalCallers();
Debug.Assert(uri != null, "uri != null");
Uri resultUri;
if (this.UrlResolver != null)
{
// The resolver returns 'null' if no custom resolution is desired.
resultUri = this.UrlResolver.ResolveUrl(this.MessageWriterSettings.BaseUri, uri);
if (resultUri != null)
{
return UriUtilsCommon.UriToString(resultUri);
}
}
resultUri = uri;
if (!resultUri.IsAbsoluteUri)
{
if (makeAbsolute)
{
if (this.MessageWriterSettings.BaseUri == null)
{
throw new ODataException(o.Strings.ODataWriter_RelativeUriUsedWithoutBaseUriSpecified(UriUtilsCommon.UriToString(uri)));
}
resultUri = UriUtils.UriToAbsoluteUri(this.MessageWriterSettings.BaseUri, uri);
}
else
{
// NOTE: the only URIs that are allowed to be relative are metadata URIs
// in operations; for such metadata URIs there is no base URI.
resultUri = UriUtils.EnsureEscapedRelativeUri(resultUri);
}
}
return UriUtilsCommon.UriToString(resultUri);
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using LibGit2Sharp.Core;
using LibGit2Sharp.Core.Handles;
namespace LibGit2Sharp
{
/// <summary>
/// Provides access to configuration variables for a repository.
/// </summary>
public class Configuration : IDisposable,
IEnumerable<ConfigurationEntry<string>>
{
private readonly FilePath globalConfigPath;
private readonly FilePath xdgConfigPath;
private readonly FilePath systemConfigPath;
private readonly Repository repository;
private ConfigurationSafeHandle configHandle;
/// <summary>
/// Needed for mocking purposes.
/// </summary>
protected Configuration()
{ }
internal Configuration(Repository repository, string globalConfigurationFileLocation,
string xdgConfigurationFileLocation, string systemConfigurationFileLocation)
{
this.repository = repository;
globalConfigPath = globalConfigurationFileLocation ?? Proxy.git_config_find_global();
xdgConfigPath = xdgConfigurationFileLocation ?? Proxy.git_config_find_xdg();
systemConfigPath = systemConfigurationFileLocation ?? Proxy.git_config_find_system();
Init();
}
private void Init()
{
configHandle = Proxy.git_config_new();
if (repository != null)
{
//TODO: push back this logic into libgit2.
// As stated by @carlosmn "having a helper function to load the defaults and then allowing you
// to modify it before giving it to git_repository_open_ext() would be a good addition, I think."
// -- Agreed :)
string repoConfigLocation = Path.Combine(repository.Info.Path, "config");
Proxy.git_config_add_file_ondisk(configHandle, repoConfigLocation, ConfigurationLevel.Local);
Proxy.git_repository_set_config(repository.Handle, configHandle);
}
if (globalConfigPath != null)
{
Proxy.git_config_add_file_ondisk(configHandle, globalConfigPath, ConfigurationLevel.Global);
}
if (xdgConfigPath != null)
{
Proxy.git_config_add_file_ondisk(configHandle, xdgConfigPath, ConfigurationLevel.Xdg);
}
if (systemConfigPath != null)
{
Proxy.git_config_add_file_ondisk(configHandle, systemConfigPath, ConfigurationLevel.System);
}
}
/// <summary>
/// Access configuration values without a repository. Generally you want to access configuration via an instance of <see cref="Repository"/> instead.
/// </summary>
/// <param name="globalConfigurationFileLocation">Path to a Global configuration file. If null, the default path for a global configuration file will be probed.</param>
public Configuration(string globalConfigurationFileLocation)
: this(null, globalConfigurationFileLocation, null, null)
{ }
/// <summary>
/// Access configuration values without a repository. Generally you want to access configuration via an instance of <see cref="Repository"/> instead.
/// </summary>
/// <param name="globalConfigurationFileLocation">Path to a Global configuration file. If null, the default path for a global configuration file will be probed.</param>
/// <param name="xdgConfigurationFileLocation">Path to a XDG configuration file. If null, the default path for a XDG configuration file will be probed.</param>
public Configuration(string globalConfigurationFileLocation, string xdgConfigurationFileLocation)
: this(null, globalConfigurationFileLocation, xdgConfigurationFileLocation, null)
{ }
/// <summary>
/// Access configuration values without a repository. Generally you want to access configuration via an instance of <see cref="Repository"/> instead.
/// </summary>
/// <param name="globalConfigurationFileLocation">Path to a Global configuration file. If null, the default path for a global configuration file will be probed.</param>
/// <param name="xdgConfigurationFileLocation">Path to a XDG configuration file. If null, the default path for a XDG configuration file will be probed.</param>
/// <param name="systemConfigurationFileLocation">Path to a System configuration file. If null, the default path for a system configuration file will be probed.</param>
public Configuration(string globalConfigurationFileLocation, string xdgConfigurationFileLocation, string systemConfigurationFileLocation)
: this(null, globalConfigurationFileLocation, xdgConfigurationFileLocation, systemConfigurationFileLocation)
{
}
/// <summary>
/// Determines which configuration file has been found.
/// </summary>
public virtual bool HasConfig(ConfigurationLevel level)
{
using (ConfigurationSafeHandle snapshot = Snapshot ())
using (ConfigurationSafeHandle handle = RetrieveConfigurationHandle(level, false, snapshot))
{
return handle != null;
}
}
#region IDisposable Members
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// Saves any open configuration files.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
#endregion
/// <summary>
/// Unset a configuration variable (key and value) in the local configuration.
/// </summary>
/// <param name="key">The key to unset.</param>
public virtual void Unset(string key)
{
Unset(key, ConfigurationLevel.Local);
}
/// <summary>
/// Unset a configuration variable (key and value).
/// </summary>
/// <param name="key">The key to unset.</param>
/// <param name="level">The configuration file which should be considered as the target of this operation</param>
public virtual void Unset(string key, ConfigurationLevel level)
{
Ensure.ArgumentNotNullOrEmptyString(key, "key");
using (ConfigurationSafeHandle h = RetrieveConfigurationHandle(level, true, configHandle))
{
Proxy.git_config_delete(h, key);
}
}
internal void UnsetMultivar(string key, ConfigurationLevel level)
{
Ensure.ArgumentNotNullOrEmptyString(key, "key");
using (ConfigurationSafeHandle h = RetrieveConfigurationHandle(level, true, configHandle))
{
Proxy.git_config_delete_multivar(h, key);
}
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
protected virtual void Dispose(bool disposing)
{
configHandle.SafeDispose();
}
/// <summary>
/// Get a configuration value for a key. Keys are in the form 'section.name'.
/// <para>
/// The same escalation logic than in git.git will be used when looking for the key in the config files:
/// - local: the Git file in the current repository
/// - global: the Git file specific to the current interactive user (usually in `$HOME/.gitconfig`)
/// - xdg: another Git file specific to the current interactive user (usually in `$HOME/.config/git/config`)
/// - system: the system-wide Git file
///
/// The first occurence of the key will be returned.
/// </para>
/// <para>
/// For example in order to get the value for this in a .git\config file:
///
/// <code>
/// [core]
/// bare = true
/// </code>
///
/// You would call:
///
/// <code>
/// bool isBare = repo.Config.Get<bool>("core.bare").Value;
/// </code>
/// </para>
/// </summary>
/// <typeparam name="T">The configuration value type</typeparam>
/// <param name="key">The key</param>
/// <returns>The <see cref="ConfigurationEntry{T}"/>, or null if not set</returns>
public virtual ConfigurationEntry<T> Get<T>(string key)
{
Ensure.ArgumentNotNullOrEmptyString(key, "key");
using (ConfigurationSafeHandle snapshot = Snapshot())
{
return Proxy.git_config_get_entry<T>(snapshot, key);
}
}
/// <summary>
/// Get a configuration value for a key. Keys are in the form 'section.name'.
/// <para>
/// For example in order to get the value for this in a .git\config file:
///
/// <code>
/// [core]
/// bare = true
/// </code>
///
/// You would call:
///
/// <code>
/// bool isBare = repo.Config.Get<bool>("core.bare").Value;
/// </code>
/// </para>
/// </summary>
/// <typeparam name="T">The configuration value type</typeparam>
/// <param name="key">The key</param>
/// <param name="level">The configuration file into which the key should be searched for</param>
/// <returns>The <see cref="ConfigurationEntry{T}"/>, or null if not set</returns>
public virtual ConfigurationEntry<T> Get<T>(string key, ConfigurationLevel level)
{
Ensure.ArgumentNotNullOrEmptyString(key, "key");
using (ConfigurationSafeHandle snapshot = Snapshot())
using (ConfigurationSafeHandle handle = RetrieveConfigurationHandle(level, false, snapshot))
{
if (handle == null)
{
return null;
}
return Proxy.git_config_get_entry<T>(handle, key);
}
}
/// <summary>
/// Set a configuration value for a key in the local configuration. Keys are in the form 'section.name'.
/// <para>
/// For example in order to set the value for this in a .git\config file:
///
/// [test]
/// boolsetting = true
///
/// You would call:
///
/// repo.Config.Set("test.boolsetting", true);
/// </para>
/// </summary>
/// <typeparam name="T">The configuration value type</typeparam>
/// <param name="key">The key parts</param>
/// <param name="value">The value</param>
public virtual void Set<T>(string key, T value)
{
Set(key, value, ConfigurationLevel.Local);
}
/// <summary>
/// Set a configuration value for a key. Keys are in the form 'section.name'.
/// <para>
/// For example in order to set the value for this in a .git\config file:
///
/// [test]
/// boolsetting = true
///
/// You would call:
///
/// repo.Config.Set("test.boolsetting", true);
/// </para>
/// </summary>
/// <typeparam name="T">The configuration value type</typeparam>
/// <param name="key">The key parts</param>
/// <param name="value">The value</param>
/// <param name="level">The configuration file which should be considered as the target of this operation</param>
public virtual void Set<T>(string key, T value, ConfigurationLevel level)
{
Ensure.ArgumentNotNull(value, "value");
Ensure.ArgumentNotNullOrEmptyString(key, "key");
using (ConfigurationSafeHandle h = RetrieveConfigurationHandle(level, true, configHandle))
{
if (!configurationTypedUpdater.ContainsKey(typeof(T)))
{
throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "Generic Argument of type '{0}' is not supported.", typeof(T).FullName));
}
configurationTypedUpdater[typeof(T)](key, value, h);
}
}
/// <summary>
/// Find configuration entries matching <paramref name="regexp"/>.
/// </summary>
/// <param name="regexp">A regular expression.</param>
/// <returns>Matching entries.</returns>
public virtual IEnumerable<ConfigurationEntry<string>> Find(string regexp)
{
return Find(regexp, ConfigurationLevel.Local);
}
/// <summary>
/// Find configuration entries matching <paramref name="regexp"/>.
/// </summary>
/// <param name="regexp">A regular expression.</param>
/// <param name="level">The configuration file into which the key should be searched for.</param>
/// <returns>Matching entries.</returns>
public virtual IEnumerable<ConfigurationEntry<string>> Find(string regexp, ConfigurationLevel level)
{
Ensure.ArgumentNotNullOrEmptyString(regexp, "regexp");
using (ConfigurationSafeHandle snapshot = Snapshot())
using (ConfigurationSafeHandle h = RetrieveConfigurationHandle(level, true, snapshot))
{
return Proxy.git_config_iterator_glob(h, regexp, BuildConfigEntry).ToList();
}
}
private ConfigurationSafeHandle RetrieveConfigurationHandle(ConfigurationLevel level, bool throwIfStoreHasNotBeenFound, ConfigurationSafeHandle fromHandle)
{
ConfigurationSafeHandle handle = null;
if (fromHandle != null)
{
handle = Proxy.git_config_open_level(fromHandle, level);
}
if (handle == null && throwIfStoreHasNotBeenFound)
{
throw new LibGit2SharpException(
string.Format(CultureInfo.InvariantCulture, "No {0} configuration file has been found.",
Enum.GetName(typeof(ConfigurationLevel), level)));
}
return handle;
}
private static Action<string, object, ConfigurationSafeHandle> GetUpdater<T>(Action<ConfigurationSafeHandle, string, T> setter)
{
return (key, val, handle) => setter(handle, key, (T)val);
}
private readonly static IDictionary<Type, Action<string, object, ConfigurationSafeHandle>> configurationTypedUpdater = new Dictionary<Type, Action<string, object, ConfigurationSafeHandle>>
{
{ typeof(int), GetUpdater<int>(Proxy.git_config_set_int32) },
{ typeof(long), GetUpdater<long>(Proxy.git_config_set_int64) },
{ typeof(bool), GetUpdater<bool>(Proxy.git_config_set_bool) },
{ typeof(string), GetUpdater<string>(Proxy.git_config_set_string) },
};
/// <summary>
/// Returns an enumerator that iterates through the configuration entries.
/// </summary>
/// <returns>An <see cref="IEnumerator{T}"/> object that can be used to iterate through the configuration entries.</returns>
public virtual IEnumerator<ConfigurationEntry<string>> GetEnumerator()
{
return BuildConfigEntries().GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return ((IEnumerable<ConfigurationEntry<string>>)this).GetEnumerator();
}
private IEnumerable<ConfigurationEntry<string>> BuildConfigEntries()
{
return Proxy.git_config_foreach(configHandle, BuildConfigEntry);
}
private static ConfigurationEntry<string> BuildConfigEntry(IntPtr entryPtr)
{
var entry = entryPtr.MarshalAs<GitConfigEntry>();
return new ConfigurationEntry<string>(LaxUtf8Marshaler.FromNative(entry.namePtr),
LaxUtf8Marshaler.FromNative(entry.valuePtr),
(ConfigurationLevel)entry.level);
}
/// <summary>
/// Builds a <see cref="Signature"/> based on current configuration.
/// <para>
/// Name is populated from the user.name setting, and is "unknown" if unspecified.
/// Email is populated from the user.email setting, and is built from
/// <see cref="Environment.UserName"/> and <see cref="Environment.UserDomainName"/> if unspecified.
/// </para>
/// <para>
/// The same escalation logic than in git.git will be used when looking for the key in the config files:
/// - local: the Git file in the current repository
/// - global: the Git file specific to the current interactive user (usually in `$HOME/.gitconfig`)
/// - xdg: another Git file specific to the current interactive user (usually in `$HOME/.config/git/config`)
/// - system: the system-wide Git file
/// </para>
/// </summary>
/// <param name="now">The timestamp to use for the <see cref="Signature"/>.</param>
/// <returns>The signature.</returns>
public virtual Signature BuildSignature(DateTimeOffset now)
{
return BuildSignature(now, false);
}
internal Signature BuildSignature(DateTimeOffset now, bool shouldThrowIfNotFound)
{
const string userNameKey = "user.name";
var name = this.GetValueOrDefault<string>(userNameKey);
var normalizedName = NormalizeUserSetting(shouldThrowIfNotFound, userNameKey, name,
() => "unknown");
const string userEmailKey = "user.email";
var email = this.GetValueOrDefault<string>(userEmailKey);
var normalizedEmail = NormalizeUserSetting(shouldThrowIfNotFound, userEmailKey, email,
() => string.Format(
CultureInfo.InvariantCulture, "{0}@{1}", Environment.UserName, Environment.UserDomainName));
return new Signature(normalizedName, normalizedEmail, now);
}
private string NormalizeUserSetting(bool shouldThrowIfNotFound, string entryName, string currentValue, Func<string> defaultValue)
{
if (!string.IsNullOrEmpty(currentValue))
{
return currentValue;
}
string message = string.Format("Configuration value '{0}' is missing or invalid.", entryName);
if (shouldThrowIfNotFound)
{
throw new LibGit2SharpException(message);
}
Log.Write(LogLevel.Warning, message);
return defaultValue();
}
private ConfigurationSafeHandle Snapshot()
{
return Proxy.git_config_snapshot(configHandle);
}
}
}
| |
using System;
using System.Collections.Generic;
using Rynchodon.Attached;
using Rynchodon.Utility;
using Sandbox.Game.Entities;
using Sandbox.ModAPI;
using VRage.Game.Entity;
using VRage.Game.ModAPI;
using VRage.ModAPI;
using VRageMath;
namespace Rynchodon.Autopilot.Pathfinding
{
public class RotateChecker
{
private static Threading.ThreadManager Thread = new Threading.ThreadManager(threadName: "RotateChecker");
private readonly IMyCubeBlock m_block;
private readonly Func<List<MyEntity>, IEnumerable<MyEntity>> m_collector;
private readonly List<MyEntity> m_obstructions = new List<MyEntity>();
private ulong m_nextRunRotate;
private MyPlanet m_closestPlanet;
private bool m_planetObstruction;
private Logable Log { get { return new Logable(m_block); } }
public IMyEntity ObstructingEntity { get; private set; }
public RotateChecker(IMyCubeBlock block, Func<List<MyEntity>, IEnumerable<MyEntity>> collector)
{
this.m_block = block;
this.m_collector = collector;
}
public void TestRotate(Vector3 displacement)
{
if (Globals.UpdateCount < m_nextRunRotate)
return;
m_nextRunRotate = Globals.UpdateCount + 10ul;
displacement.Normalize();
Thread.EnqueueAction(() => in_TestRotate(displacement));
}
/// <summary>
/// Test if it is safe for the grid to rotate.
/// </summary>
/// <param name="axis">Normalized axis of rotation in world space.</param>
/// <returns>True iff the path is clear.</returns>
private bool in_TestRotate(Vector3 axis)
{
IMyCubeGrid myGrid = m_block.CubeGrid;
Vector3 centreOfMass = myGrid.Physics.CenterOfMassWorld;
float longestDim = myGrid.GetLongestDim();
// calculate height
Matrix toMyLocal = myGrid.WorldMatrixNormalizedInv;
Vector3 myLocalCoM = Vector3.Transform(centreOfMass, toMyLocal);
Vector3 myLocalAxis = Vector3.Transform(axis, toMyLocal.GetOrientation());
Vector3 myLocalCentre = myGrid.LocalAABB.Center; // CoM may not be on ship (it now considers mass from attached grids)
Ray upper = new Ray(myLocalCentre + myLocalAxis * longestDim * 2f, -myLocalAxis);
float? upperBound = myGrid.LocalAABB.Intersects(upper);
if (!upperBound.HasValue)
Log.AlwaysLog("Math fail, upperBound does not have a value", Logger.severity.FATAL);
Ray lower = new Ray(myLocalCentre - myLocalAxis * longestDim * 2f, myLocalAxis);
float? lowerBound = myGrid.LocalAABB.Intersects(lower);
if (!lowerBound.HasValue)
Log.AlwaysLog("Math fail, lowerBound does not have a value", Logger.severity.FATAL);
//Log.DebugLog("LocalAABB: " + myGrid.LocalAABB + ", centre: " + myLocalCentre + ", axis: " + myLocalAxis + ", longest dimension: " + longestDim + ", upper ray: " + upper + ", lower ray: " + lower);
float height = longestDim * 4f - upperBound.Value - lowerBound.Value;
float furthest = 0f;
foreach (IMyCubeGrid grid in AttachedGrid.AttachedGrids(myGrid, Attached.AttachedGrid.AttachmentKind.Physics, true))
{
CubeGridCache cache = CubeGridCache.GetFor(grid);
if (cache == null)
return false;
foreach (Vector3I cell in cache.OccupiedCells())
{
Vector3 rejection = Vector3.Reject(cell * myGrid.GridSize, myLocalAxis);
float cellDistSquared = Vector3.DistanceSquared(myLocalCoM, rejection);
if (cellDistSquared > furthest)
furthest = cellDistSquared;
}
}
float length = (float)Math.Sqrt(furthest) + myGrid.GridSize;
//Log.DebugLog("height: " + height + ", length: " + length);
BoundingSphereD surroundingSphere = new BoundingSphereD(centreOfMass, Math.Max(length, height) * MathHelper.Sqrt2);
m_obstructions.Clear();
MyGamePruningStructure.GetAllTopMostEntitiesInSphere(ref surroundingSphere, m_obstructions);
LineSegment axisSegment = new LineSegment();
m_closestPlanet = null;
foreach (MyEntity entity in m_collector.Invoke(m_obstructions))
{
if (entity is IMyVoxelBase)
{
IMyVoxelMap voxel = entity as IMyVoxelMap;
if (voxel != null)
{
if (voxel.GetIntersectionWithSphere(ref surroundingSphere))
{
Log.DebugLog("Too close to " + voxel.getBestName() + ", CoM: " + centreOfMass.ToGpsTag("Centre of Mass") + ", required distance: " + surroundingSphere.Radius);
ObstructingEntity = voxel;
return false;
}
continue;
}
if (m_closestPlanet == null)
{
MyPlanet planet = entity as MyPlanet;
if (planet == null)
continue;
double distToPlanetSq = Vector3D.DistanceSquared(centreOfMass, planet.PositionComp.GetPosition());
if (distToPlanetSq < planet.MaximumRadius * planet.MaximumRadius)
{
m_closestPlanet = planet;
if (m_planetObstruction)
{
Log.DebugLog("planet blocking");
ObstructingEntity = m_closestPlanet;
return false;
}
}
}
continue;
}
IMyCubeGrid grid = entity as IMyCubeGrid;
if (grid != null)
{
Matrix toLocal = grid.WorldMatrixNormalizedInv;
Vector3 localAxis = Vector3.Transform(axis, toLocal.GetOrientation());
Vector3 localCentre = Vector3.Transform(centreOfMass, toLocal);
axisSegment.From = localCentre - localAxis * height;
axisSegment.To = localCentre + localAxis * height;
CubeGridCache cache = CubeGridCache.GetFor(grid);
if (cache == null)
return false;
foreach (Vector3I cell in cache.OccupiedCells())
if (axisSegment.PointInCylinder(length, cell * grid.GridSize))
{
Log.DebugLog("axis segment: " + axisSegment.From + " to " + axisSegment.To + ", radius: " + length + ", hit " + grid.nameWithId() + " at " + cell);
ObstructingEntity = grid;
return false;
}
continue;
}
Log.DebugLog("No tests for object: " + entity.getBestName(), Logger.severity.INFO);
ObstructingEntity = entity;
return false;
}
MyAPIGateway.Utilities.TryInvokeOnGameThread(TestPlanet);
ObstructingEntity = null;
return true;
}
private void TestPlanet()
{
MyPlanet planet = m_closestPlanet;
if (planet == null)
return;
IMyCubeGrid grid = m_block.CubeGrid;
Vector3D myPos = grid.GetCentre();
Vector3D planetCentre = planet.GetCentre();
double distSqToPlanet = Vector3D.DistanceSquared(myPos, planetCentre);
if (distSqToPlanet > planet.MaximumRadius * planet.MaximumRadius)
{
Log.DebugLog("higher than planet maximum");
m_planetObstruction = false;
return;
}
Vector3D closestPoint = planet.GetClosestSurfacePointGlobal(ref myPos);
if (distSqToPlanet < Vector3D.DistanceSquared(closestPoint, planetCentre))
{
Log.DebugLog("below surface");
return;
}
float longest = grid.GetLongestDim();
if (Vector3D.DistanceSquared(myPos, closestPoint) < longest * longest)
{
Log.DebugLog("near surface");
m_planetObstruction = true;
return;
}
Log.DebugLog("clear");
m_planetObstruction = false;
return;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Linq;
using Xunit;
namespace System.Collections.Specialized.Tests
{
public static class BitVector32Tests
{
/// <summary>
/// Data used for testing setting/unsetting multiple bits at a time.
/// </summary>
/// Format is:
/// 1. Set data
/// 2. Unset data
/// 3. Bits to flip for transformation.
/// <returns>Row of data</returns>
public static IEnumerable<object[]> Mask_SetUnset_Multiple_Data()
{
yield return new object[] { 0, 0, new int[] { } };
yield return new object[] { 1, 0, new int[] { 1 } };
yield return new object[] { 2, 0, new int[] { 2 } };
yield return new object[] { int.MinValue, 0, new int[] { 32 } };
yield return new object[] { 6, 0, new int[] { 2, 3 } };
yield return new object[] { 6, 6, new int[] { 2, 3 } };
yield return new object[] { 31, 15, new int[] { 4 } };
yield return new object[] { 22, 16, new int[] { 2, 3 } };
yield return new object[] { -1, 0, new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32 } };
}
/// <summary>
/// Data used for testing creating sections.
/// </summary>
/// Format is:
/// 1. maximum value allowed
/// 2. resulting mask
/// <returns>Row of data</returns>
public static IEnumerable<object[]> Section_Create_Data()
{
yield return new object[] { 1, 1 };
yield return new object[] { 2, 3 };
yield return new object[] { 3, 3 };
yield return new object[] { 16, 31 };
yield return new object[] { byte.MaxValue, byte.MaxValue };
yield return new object[] { short.MaxValue, short.MaxValue };
yield return new object[] { short.MaxValue - 1, short.MaxValue };
}
/// <summary>
/// Data used for testing setting/unsetting via sections.
/// </summary>
/// Format is:
/// 1. value
/// 2. section
/// <returns>Row of data</returns>
public static IEnumerable<object[]> Section_Set_Data()
{
yield return new object[] { 0, BitVector32.CreateSection(1) };
yield return new object[] { 1, BitVector32.CreateSection(1) };
yield return new object[] { 0, BitVector32.CreateSection(short.MaxValue) };
yield return new object[] { short.MaxValue, BitVector32.CreateSection(short.MaxValue) };
yield return new object[] { 0, BitVector32.CreateSection(1, BitVector32.CreateSection(byte.MaxValue)) };
yield return new object[] { 1, BitVector32.CreateSection(1, BitVector32.CreateSection(byte.MaxValue)) };
yield return new object[] { 0, BitVector32.CreateSection(short.MaxValue, BitVector32.CreateSection(byte.MaxValue)) };
yield return new object[] { short.MaxValue, BitVector32.CreateSection(short.MaxValue, BitVector32.CreateSection(byte.MaxValue)) };
yield return new object[] { 16, BitVector32.CreateSection(short.MaxValue) };
yield return new object[] { 16, BitVector32.CreateSection(short.MaxValue, BitVector32.CreateSection(byte.MaxValue)) };
yield return new object[] { 31, BitVector32.CreateSection(short.MaxValue) };
yield return new object[] { 31, BitVector32.CreateSection(short.MaxValue, BitVector32.CreateSection(byte.MaxValue)) };
yield return new object[] { 16, BitVector32.CreateSection(byte.MaxValue) };
yield return new object[] { 16, BitVector32.CreateSection(byte.MaxValue, BitVector32.CreateSection(byte.MaxValue, BitVector32.CreateSection(short.MaxValue))) };
yield return new object[] { 31, BitVector32.CreateSection(byte.MaxValue) };
yield return new object[] { 31, BitVector32.CreateSection(byte.MaxValue, BitVector32.CreateSection(byte.MaxValue, BitVector32.CreateSection(short.MaxValue))) };
}
/// <summary>
/// Data used for testing equal sections.
/// </summary>
/// Format is:
/// 1. Section left
/// 2. Section right
/// <returns>Row of data</returns>
public static IEnumerable<object[]> Section_Equal_Data()
{
BitVector32.Section original = BitVector32.CreateSection(16);
BitVector32.Section nested = BitVector32.CreateSection(16, original);
yield return new object[] { original, original };
yield return new object[] { original, BitVector32.CreateSection(16) };
yield return new object[] { BitVector32.CreateSection(16), original };
// Since the max value is changed to an inclusive mask, equal to mask max value
yield return new object[] { original, BitVector32.CreateSection(31) };
yield return new object[] { nested, nested };
yield return new object[] { nested, BitVector32.CreateSection(16, original) };
yield return new object[] { BitVector32.CreateSection(16, original), nested };
yield return new object[] { nested, BitVector32.CreateSection(31, original) };
yield return new object[] { nested, BitVector32.CreateSection(16, BitVector32.CreateSection(16)) };
yield return new object[] { BitVector32.CreateSection(16, BitVector32.CreateSection(16)), nested };
yield return new object[] { nested, BitVector32.CreateSection(31, BitVector32.CreateSection(16)) };
// Because it only stores the offset, and not the previous section, later sections may be equal
yield return new object[] { nested, BitVector32.CreateSection(16, BitVector32.CreateSection(8, BitVector32.CreateSection(1))) };
yield return new object[] { BitVector32.CreateSection(16, BitVector32.CreateSection(8, BitVector32.CreateSection(1))), nested };
}
/// <summary>
/// Data used for testing unequal sections.
/// </summary>
/// Format is:
/// 1. Section left
/// 2. Section right
/// <returns>Row of data</returns>
public static IEnumerable<object[]> Section_Unequal_Data()
{
BitVector32.Section original = BitVector32.CreateSection(16);
BitVector32.Section nested = BitVector32.CreateSection(16, original);
yield return new object[] { original, BitVector32.CreateSection(1) };
yield return new object[] { BitVector32.CreateSection(1), original };
yield return new object[] { original, nested };
yield return new object[] { nested, original };
yield return new object[] { nested, BitVector32.CreateSection(1, BitVector32.CreateSection(short.MaxValue)) };
yield return new object[] { BitVector32.CreateSection(1, BitVector32.CreateSection(short.MaxValue)), nested };
yield return new object[] { nested, BitVector32.CreateSection(16, BitVector32.CreateSection(short.MaxValue)) };
yield return new object[] { BitVector32.CreateSection(16, BitVector32.CreateSection(short.MaxValue)), nested };
yield return new object[] { nested, BitVector32.CreateSection(1, original) };
yield return new object[] { BitVector32.CreateSection(1, original), nested };
}
[Fact]
public static void Constructor_DefaultTest()
{
BitVector32 bv = new BitVector32();
Assert.NotNull(bv);
Assert.Equal(0, bv.Data);
// Copy constructor results in item with same data.
BitVector32 copied = new BitVector32(bv);
Assert.NotNull(bv);
Assert.Equal(0, copied.Data);
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(2)]
[InlineData(7)]
[InlineData(99)]
[InlineData(byte.MaxValue)]
[InlineData(int.MaxValue / 2)]
[InlineData(int.MaxValue - 1)]
[InlineData(int.MaxValue)]
[InlineData(-1)]
[InlineData(-2)]
[InlineData(-7)]
[InlineData(-99)]
[InlineData(byte.MinValue)]
[InlineData(int.MinValue / 2)]
[InlineData(int.MinValue + 1)]
[InlineData(int.MinValue)]
public static void Constructor_DataTest(int data)
{
BitVector32 bv = new BitVector32(data);
Assert.NotNull(bv);
Assert.Equal(data, bv.Data);
// Copy constructor results in item with same data.
BitVector32 copied = new BitVector32(bv);
Assert.NotNull(bv);
Assert.Equal(data, copied.Data);
}
[Fact]
public static void Mask_DefaultTest()
{
Assert.Equal(1, BitVector32.CreateMask());
Assert.Equal(1, BitVector32.CreateMask(0));
}
[Theory]
[InlineData(2, 1)]
[InlineData(6, 3)]
[InlineData(short.MaxValue + 1, 1 << 14)]
[InlineData(-2, int.MaxValue)]
[InlineData(-2, -1)]
// Works even if the mask has multiple bits set, which probably wasn't the intended use.
public static void Mask_SeriesTest(int expected, int actual)
{
while (actual != int.MinValue)
{
actual = BitVector32.CreateMask(actual);
Assert.Equal(expected, actual);
expected <<= 1;
}
Assert.Equal(int.MinValue, actual);
}
[Fact]
public static void Mask_LastTest()
{
Assert.Throws<InvalidOperationException>(() => BitVector32.CreateMask(int.MinValue));
}
[Fact]
public static void Get_Mask_AllSetTest()
{
BitVector32 all = new BitVector32(-1);
int mask = 0;
for (int count = 0; count < 32; count++)
{
mask = BitVector32.CreateMask(mask);
Assert.True(all[mask]);
}
Assert.Equal(int.MinValue, mask);
}
[Fact]
public static void Get_Mask_NoneSetTest()
{
BitVector32 none = new BitVector32();
int mask = 0;
for (int count = 0; count < 32; count++)
{
mask = BitVector32.CreateMask(mask);
Assert.False(none[mask]);
}
Assert.Equal(int.MinValue, mask);
}
[Fact]
public static void Get_Mask_SomeSetTest()
{
// Constructs data with every even bit set.
int data = Enumerable.Range(0, 16).Sum(x => 1 << (x * 2));
BitVector32 some = new BitVector32(data);
int mask = 0;
for (int index = 0; index < 32; index++)
{
mask = BitVector32.CreateMask(mask);
Assert.Equal(index % 2 == 0, some[mask]);
}
Assert.Equal(int.MinValue, mask);
}
[Fact]
public static void Set_Mask_EmptyTest()
{
BitVector32 nothing = new BitVector32();
nothing[0] = true;
Assert.Equal(0, nothing.Data);
BitVector32 all = new BitVector32(-1);
all[0] = false;
Assert.Equal(-1, all.Data);
}
[Fact]
public static void Set_Mask_AllTest()
{
BitVector32 flip = new BitVector32();
int mask = 0;
for (int bit = 1; bit < 32 + 1; bit++)
{
mask = BitVector32.CreateMask(mask);
BitVector32 single = new BitVector32();
Assert.False(single[mask]);
single[mask] = true;
Assert.True(single[mask]);
Assert.Equal(1 << (bit - 1), single.Data);
flip[mask] = true;
}
Assert.Equal(-1, flip.Data);
Assert.Equal(int.MinValue, mask);
}
[Fact]
public static void Set_Mask_UnsetAllTest()
{
BitVector32 flip = new BitVector32(-1);
int mask = 0;
for (int bit = 1; bit < 32 + 1; bit++)
{
mask = BitVector32.CreateMask(mask);
BitVector32 single = new BitVector32(1 << (bit - 1));
Assert.True(single[mask]);
single[mask] = false;
Assert.False(single[mask]);
Assert.Equal(0, single.Data);
flip[mask] = false;
}
Assert.Equal(0, flip.Data);
Assert.Equal(int.MinValue, mask);
}
[Theory]
[MemberData(nameof(Mask_SetUnset_Multiple_Data))]
public static void Set_Mask_MultipleTest(int expected, int start, int[] maskPositions)
{
int mask = maskPositions.Sum(x => 1 << (x - 1));
BitVector32 blank = new BitVector32();
BitVector32 set = new BitVector32();
set[mask] = true;
for (int bit = 0; bit < 32; bit++)
{
Assert.False(blank[1 << bit]);
bool willSet = maskPositions.Contains(bit + 1);
blank[1 << bit] = willSet;
Assert.Equal(willSet, blank[1 << bit]);
Assert.Equal(willSet, set[1 << bit]);
}
Assert.Equal(set, blank);
}
[Theory]
[MemberData(nameof(Mask_SetUnset_Multiple_Data))]
public static void Set_Mask_Multiple_UnsetTest(int start, int expected, int[] maskPositions)
{
int mask = maskPositions.Sum(x => 1 << (x - 1));
BitVector32 set = new BitVector32();
set[mask] = true;
for (int bit = 0; bit < 32; bit++)
{
bool willUnset = maskPositions.Contains(bit + 1);
Assert.Equal(willUnset, set[1 << bit]);
set[1 << bit] = false;
Assert.False(set[1 << bit]);
}
Assert.Equal(set, new BitVector32());
}
[Theory]
[MemberData(nameof(Section_Set_Data))]
public static void Set_SectionTest(int value, BitVector32.Section section)
{
BitVector32 empty = new BitVector32();
empty[section] = value;
Assert.Equal(value, empty[section]);
Assert.Equal(value << section.Offset, empty.Data);
BitVector32 full = new BitVector32(-1);
full[section] = value;
Assert.Equal(value, full[section]);
int offsetMask = section.Mask << section.Offset;
Assert.Equal((-1 & ~offsetMask) | (value << section.Offset), full.Data);
}
[Theory]
[InlineData(short.MaxValue, int.MaxValue)]
[InlineData(1, 2)]
[InlineData(1, short.MaxValue)]
[InlineData(1, -1)]
[InlineData(short.MaxValue, short.MinValue)]
public static void Set_Section_OutOfRangeTest(short maximum, int value)
{
{
BitVector32 data = new BitVector32();
BitVector32.Section section = BitVector32.CreateSection(maximum);
data[section] = value;
Assert.Equal(maximum & value, data.Data);
Assert.NotEqual(value, data.Data);
Assert.Equal(maximum & value, data[section]);
Assert.NotEqual(value, data[section]);
}
{
BitVector32 data = new BitVector32();
BitVector32.Section nested = BitVector32.CreateSection(maximum, BitVector32.CreateSection(short.MaxValue));
data[nested] = value;
Assert.Equal((maximum & value) << 15, data.Data);
Assert.NotEqual(value << 15, data.Data);
Assert.Equal(maximum & value, data[nested]);
Assert.NotEqual(value, data[nested]);
}
}
[Theory]
[InlineData(4)]
[InlineData(5)]
[InlineData(short.MaxValue)]
[InlineData(byte.MaxValue)]
// Regardless of mask size, values will be truncated if they hang off the end
public static void Set_Section_OverflowTest(int value)
{
BitVector32 data = new BitVector32();
BitVector32.Section offset = BitVector32.CreateSection(short.MaxValue, BitVector32.CreateSection(short.MaxValue));
BitVector32.Section final = BitVector32.CreateSection(short.MaxValue, offset);
data[final] = value;
Assert.Equal((3 & value) << 30, data.Data);
Assert.NotEqual(value, data.Data);
Assert.Equal(3 & value, data[final]);
Assert.NotEqual(value, data[final]);
}
[Theory]
[MemberData(nameof(Section_Create_Data))]
public static void CreateSectionTest(short maximum, short mask)
{
BitVector32.Section section = BitVector32.CreateSection(maximum);
Assert.Equal(0, section.Offset);
Assert.Equal(mask, section.Mask);
}
[Theory]
[MemberData(nameof(Section_Create_Data))]
public static void CreateSection_NextTest(short maximum, short mask)
{
BitVector32.Section initial = BitVector32.CreateSection(short.MaxValue);
BitVector32.Section section = BitVector32.CreateSection(maximum, initial);
Assert.Equal(15, section.Offset);
Assert.Equal(mask, section.Mask);
}
[Theory]
[InlineData(short.MinValue)]
[InlineData(-1)]
[InlineData(0)]
public static void CreateSection_InvalidMaximumTest(short maxvalue)
{
AssertExtensions.Throws<ArgumentException>("maxValue", () => BitVector32.CreateSection(maxvalue));
BitVector32.Section valid = BitVector32.CreateSection(1);
AssertExtensions.Throws<ArgumentException>("maxValue", () => BitVector32.CreateSection(maxvalue, valid));
}
[Theory]
[InlineData(7, short.MaxValue)]
[InlineData(short.MaxValue, 7)]
[InlineData(short.MaxValue, short.MaxValue)]
[InlineData(byte.MaxValue, byte.MaxValue)]
public static void CreateSection_FullTest(short prior, short invalid)
{
// BV32 can hold just over 2 shorts, so fill most of the way first....
BitVector32.Section initial = BitVector32.CreateSection(short.MaxValue, BitVector32.CreateSection(short.MaxValue));
BitVector32.Section overflow = BitVector32.CreateSection(prior, initial);
// Final masked value can hang off the end
Assert.Equal(prior, overflow.Mask);
Assert.Equal(30, overflow.Offset);
// The next section would be created "off the end"
// - the current offset is 30, and the current mask requires more than the remaining 1 bit.
Assert.InRange(CountBitsRequired(overflow.Mask), 2, 15);
Assert.Throws<InvalidOperationException>(() => BitVector32.CreateSection(invalid, overflow));
}
[Theory]
[MemberData(nameof(Section_Equal_Data))]
public static void Section_EqualsTest(BitVector32.Section left, BitVector32.Section right)
{
Assert.True(left.Equals(left));
Assert.True(left.Equals(right));
Assert.True(right.Equals(left));
Assert.True(left.Equals((object)left));
Assert.True(left.Equals((object)right));
Assert.True(right.Equals((object)left));
Assert.True(left == right);
Assert.True(right == left);
Assert.False(left != right);
Assert.False(right != left);
}
[Theory]
[MemberData(nameof(Section_Unequal_Data))]
public static void Section_Unequal_EqualsTest(BitVector32.Section left, BitVector32.Section right)
{
Assert.False(left.Equals(right));
Assert.False(right.Equals(left));
Assert.False(left.Equals((object)right));
Assert.False(right.Equals((object)left));
Assert.False(left.Equals(new object()));
Assert.False(left == right);
Assert.False(right == left);
Assert.True(left != right);
Assert.True(right != left);
}
[Theory]
[MemberData(nameof(Section_Equal_Data))]
public static void Section_GetHashCodeTest(BitVector32.Section left, BitVector32.Section right)
{
Assert.Equal(left.GetHashCode(), left.GetHashCode());
Assert.Equal(left.GetHashCode(), right.GetHashCode());
}
public static void Section_ToStringTest()
{
Random random = new Random(-55);
short maxValue = (short)random.Next(1, short.MaxValue);
BitVector32.Section section1 = BitVector32.CreateSection(maxValue);
BitVector32.Section section2 = BitVector32.CreateSection(maxValue);
Assert.Equal(section1.ToString(), section2.ToString());
Assert.Equal(section1.ToString(), BitVector32.Section.ToString(section2));
}
[Fact]
public static void EqualsTest()
{
BitVector32 original = new BitVector32();
Assert.True(original.Equals(original));
Assert.True(new BitVector32().Equals(original));
Assert.True(original.Equals(new BitVector32()));
Assert.True(new BitVector32(0).Equals(original));
Assert.True(original.Equals(new BitVector32(0)));
BitVector32 other = new BitVector32(int.MaxValue / 2 - 1);
Assert.True(other.Equals(other));
Assert.True(new BitVector32(int.MaxValue / 2 - 1).Equals(other));
Assert.True(other.Equals(new BitVector32(int.MaxValue / 2 - 1)));
Assert.False(other.Equals(original));
Assert.False(original.Equals(other));
Assert.False(other.Equals(null));
Assert.False(original.Equals(null));
Assert.False(other.Equals(int.MaxValue / 2 - 1));
Assert.False(original.Equals(0));
}
[Fact]
public static void GetHashCodeTest()
{
BitVector32 original = new BitVector32();
Assert.Equal(original.GetHashCode(), original.GetHashCode());
Assert.Equal(new BitVector32().GetHashCode(), original.GetHashCode());
Assert.Equal(new BitVector32(0).GetHashCode(), original.GetHashCode());
BitVector32 other = new BitVector32(int.MaxValue / 2 - 1);
Assert.Equal(other.GetHashCode(), other.GetHashCode());
Assert.Equal(new BitVector32(int.MaxValue / 2 - 1).GetHashCode(), other.GetHashCode());
}
[Theory]
[InlineData(0, "BitVector32{00000000000000000000000000000000}")]
[InlineData(1, "BitVector32{00000000000000000000000000000001}")]
[InlineData(-1, "BitVector32{11111111111111111111111111111111}")]
[InlineData(16 - 2, "BitVector32{00000000000000000000000000001110}")]
[InlineData(-(16 - 2), "BitVector32{11111111111111111111111111110010}")]
[InlineData(int.MaxValue, "BitVector32{01111111111111111111111111111111}")]
[InlineData(int.MinValue, "BitVector32{10000000000000000000000000000000}")]
[InlineData(short.MaxValue, "BitVector32{00000000000000000111111111111111}")]
[InlineData(short.MinValue, "BitVector32{11111111111111111000000000000000}")]
public static void ToStringTest(int data, string expected)
{
Assert.Equal(expected, new BitVector32(data).ToString());
Assert.Equal(expected, BitVector32.ToString(new BitVector32(data)));
}
private static short CountBitsRequired(short value)
{
short required = 16;
while ((value & 0x8000) == 0)
{
required--;
value <<= 1;
}
return required;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Routing;
namespace MvcContrib.Routing
{
/// <summary>
/// This class can be used to create routes from a regular expression.
/// It is also bidirectional and can be used to generate urls from a given route.
/// </summary>
[Obsolete]
public class RegexRoute : RouteBase
{
private readonly RouteValueDictionary _defaults;
private readonly string[] _groupNames;
private readonly Regex _regex;
private readonly IRouteHandler _routeHandler;
private readonly Func<RequestContext, RouteValueDictionary, RegexRoute, VirtualPathData> _getVirtualPath;
private readonly string _urlGenerator;
/// <summary>
/// Initializes a new instance of the <see cref="RegexRoute"/> class given a regular expression and a route handler.
/// </summary>
/// <param name="regex">The regular expression that this route handler is supposed to handle.</param>
/// <param name="routeHandler">The route handler to handle this route.</param>
public RegexRoute(string regex, IRouteHandler routeHandler) : this(regex, (string)null, routeHandler) { }
/// <summary>
/// Initializes a new instance of the <see cref="RegexRoute"/> class given a regular expression and a route
/// handler and a url generator to use to generate urls that would be handled by this route.
/// </summary>
/// <param name="regex">The regular expression that this route handler is supposed to handle.</param>
/// <param name="urlGenerator">The URL generator; used to generate urls for this route.</param>
/// <param name="routeHandler">The route handler to handle this route.</param>
[SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings",
Justification = "The urlGenerator variable is used as a string to generate the mvc url; it is not itself a Uri.")]
public RegexRoute(string regex, string urlGenerator, IRouteHandler routeHandler) : this(regex, urlGenerator, null, routeHandler) { }
/// <summary>
/// Initializes a new instance of the <see cref="RegexRoute"/> class.
/// </summary>
/// <param name="regex">The regular expression that this route handler is supposed to handle.</param>
/// <param name="defaults">Default route values for this route.</param>
/// <param name="routeHandler">The route handler to handle this route.</param>
public RegexRoute(string regex, RouteValueDictionary defaults, IRouteHandler routeHandler) : this(regex, (string)null, defaults, routeHandler) { }
/// <summary>
/// Initializes a new instance of the <see cref="RegexRoute"/> class.
/// </summary>
/// <param name="regex">The regular expression that this route handler is supposed to handle.</param>
/// <param name="urlGenerator">The URL generator; used to generate urls for this route.</param>
/// <param name="defaults">Default route values for this route.</param>
/// <param name="routeHandler">The route handler to handle this route.</param>
[SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings")]
public RegexRoute(string regex, string urlGenerator, RouteValueDictionary defaults, IRouteHandler routeHandler) : this(regex, urlGenerator, RealGetVirtualPath, defaults, routeHandler) { }
/// <summary>
/// Initializes a new instance of the <see cref="RegexRoute"/> class.
/// </summary>
/// <param name="regex">The regular expression that this route handler is supposed to handle.</param>
/// <param name="getVirtualPath">A function to use to generate a virtual path given the request context, incoming route value dictionary and this <see cref="RegexRoute"/> instance.</param>
/// <param name="routeHandler">The route handler to handle this route.</param>
public RegexRoute(string regex, Func<RequestContext, RouteValueDictionary, RegexRoute, VirtualPathData> getVirtualPath, IRouteHandler routeHandler) : this(regex, getVirtualPath, null, routeHandler) { }
/// <summary>
/// Initializes a new instance of the <see cref="RegexRoute"/> class.
/// </summary>
/// <param name="regex">The regular expression that this route handler is supposed to handle.</param>
/// <param name="getVirtualPath">A function to use to generate a virtual path given the request context, incoming route value dictionary and this <see cref="RegexRoute"/> instance.</param>
/// <param name="defaults">Default route values for this route.</param>
/// <param name="routeHandler">The route handler to handle this route.</param>
public RegexRoute(string regex, Func<RequestContext, RouteValueDictionary, RegexRoute, VirtualPathData> getVirtualPath, RouteValueDictionary defaults, IRouteHandler routeHandler) : this(regex, null, getVirtualPath, defaults, routeHandler) { }
/// <summary>
/// Initializes a new instance of the <see cref="RegexRoute"/> class.
/// </summary>
/// <param name="regex">The regular expression that this route handler is supposed to handle.</param>
/// <param name="urlGenerator">The URL generator; used to generate urls for this route.</param>
/// <param name="getVirtualPath">A function to use to generate a virtual path given the request context, incoming route value dictionary and this <see cref="RegexRoute"/> instance.</param>
/// <param name="defaults">Default route values for this route.</param>
/// <param name="routeHandler">The route handler to handle this route.</param>
[SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings")]
protected RegexRoute(string regex, string urlGenerator, Func<RequestContext, RouteValueDictionary, RegexRoute, VirtualPathData> getVirtualPath, RouteValueDictionary defaults, IRouteHandler routeHandler)
{
_getVirtualPath = getVirtualPath ?? RealGetVirtualPath;
_urlGenerator = urlGenerator;
_defaults = defaults;
_routeHandler = routeHandler;
_regex = new Regex(regex, RegexOptions.IgnoreCase | RegexOptions.Compiled);
_groupNames = _regex.GetGroupNames();
}
/// <summary>
/// Gets the default route value dictionary containing the default route settings.
/// </summary>
/// <value>The default settings for this route.</value>
public RouteValueDictionary Defaults
{
get { return _defaults; }
}
/// <summary>
/// Gets the route handler handling this route.
/// </summary>
/// <value>The route handler that handles this route.</value>
public IRouteHandler RouteHandler
{
get { return _routeHandler; }
}
/// <summary>
/// Gets the string used to generate mvc urls for this route.
/// </summary>
/// <value>The string used to generate urls for this route.</value>
[SuppressMessage("Microsoft.Design", "CA1056:UriPropertiesShouldNotBeStrings")]
public string UrlGenerator
{
get { return _urlGenerator; }
}
/// <summary>
/// Used to get a virtual path for a given set of route settings.
/// If the combination of defaults/values doesn't satisfy the url generator tokens: null is returned,
/// signaling that this route isn't correct for the given values.
/// </summary>
/// <remarks>
/// This function is not used for figuring out the routes. It is only used for generating links for new routes.
/// </remarks>
/// <param name="requestContext">The request context.</param>
/// <param name="values">The settings to use to generate this virtual path.</param>
/// <returns>A virtual path that represents the given settings.</returns>
public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values)
{
return _getVirtualPath(requestContext, values, this);
}
private static VirtualPathData RealGetVirtualPath(RequestContext requestContext, RouteValueDictionary values, RegexRoute thisRoute)
{
var pathDictionary = new Dictionary<string, string>();
if (thisRoute.Defaults != null)
{
foreach (var pair in thisRoute.Defaults)
{
pathDictionary.Add(pair.Key, pair.Value.ToString());
}
}
if (values != null)
{
foreach (var pair in values)
{
pathDictionary[pair.Key] = pair.Value.ToString();
}
}
string newUrl = thisRoute.UrlGenerator;
foreach (var pair in pathDictionary)
{
newUrl = newUrl.Replace("{" + pair.Key + "}", pair.Value);
}
if (Regex.IsMatch(newUrl, @"\{\w+\}"))
{
return null;
}
return new VirtualPathData(thisRoute, newUrl);
}
/// <summary>
/// Gets the route data from an incoming request; parses the incoming virtual
/// path and returns the route data that was inside the url.
/// </summary>
/// <param name="httpContext">The HTTP context containing the url data.</param>
/// <returns>Route data gleaned from the context.</returns>
public override RouteData GetRouteData(HttpContextBase httpContext)
{
string requestUrl = httpContext.Request.AppRelativeCurrentExecutionFilePath.Substring(2) + httpContext.Request.PathInfo;
return GetRouteData(requestUrl);
}
/// <summary>
/// Gets the route data from the request portion of the url.
/// </summary>
/// <param name="request">The request string (the part after the virtual directory but before the query string).</param>
/// <returns>Route data gleaned from the context.</returns>
public virtual RouteData GetRouteData(string request)
{
Match match = _regex.Match(request);
if (!match.Success)
{
return null;
}
RouteData data = GenerateDefaultRouteData();
foreach (string groupName in _groupNames)
{
Group group = match.Groups[groupName];
if (group.Success)
{
if (!string.IsNullOrEmpty(groupName) && !char.IsNumber(groupName, 0))
{
data.Values[groupName] = group.Value;
}
}
}
return data;
}
private RouteData GenerateDefaultRouteData()
{
var data = new RouteData(this, RouteHandler);
if (Defaults != null)
{
foreach (var def in Defaults)
{
data.Values.Add(def.Key, def.Value);
}
}
return data;
}
}
}
| |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.
*/
/*
* Do not modify this file. This file is generated from the ec2-2014-10-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.EC2.Model
{
/// <summary>
/// Describes a volume.
/// </summary>
public partial class Volume
{
private List<VolumeAttachment> _attachments = new List<VolumeAttachment>();
private string _availabilityZone;
private DateTime? _createTime;
private bool? _encrypted;
private int? _iops;
private string _kmsKeyId;
private int? _size;
private string _snapshotId;
private VolumeState _state;
private List<Tag> _tags = new List<Tag>();
private string _volumeId;
private VolumeType _volumeType;
/// <summary>
/// Gets and sets the property Attachments.
/// </summary>
public List<VolumeAttachment> Attachments
{
get { return this._attachments; }
set { this._attachments = value; }
}
// Check to see if Attachments property is set
internal bool IsSetAttachments()
{
return this._attachments != null && this._attachments.Count > 0;
}
/// <summary>
/// Gets and sets the property AvailabilityZone.
/// <para>
/// The Availability Zone for the volume.
/// </para>
/// </summary>
public string AvailabilityZone
{
get { return this._availabilityZone; }
set { this._availabilityZone = value; }
}
// Check to see if AvailabilityZone property is set
internal bool IsSetAvailabilityZone()
{
return this._availabilityZone != null;
}
/// <summary>
/// Gets and sets the property CreateTime.
/// <para>
/// The time stamp when volume creation was initiated.
/// </para>
/// </summary>
public DateTime CreateTime
{
get { return this._createTime.GetValueOrDefault(); }
set { this._createTime = value; }
}
// Check to see if CreateTime property is set
internal bool IsSetCreateTime()
{
return this._createTime.HasValue;
}
/// <summary>
/// Gets and sets the property Encrypted.
/// <para>
/// Indicates whether the volume will be encrypted.
/// </para>
/// </summary>
public bool Encrypted
{
get { return this._encrypted.GetValueOrDefault(); }
set { this._encrypted = value; }
}
// Check to see if Encrypted property is set
internal bool IsSetEncrypted()
{
return this._encrypted.HasValue;
}
/// <summary>
/// Gets and sets the property Iops.
/// <para>
/// The number of I/O operations per second (IOPS) that the volume supports. For Provisioned
/// IOPS (SSD) volumes, this represents the number of IOPS that are provisioned for the
/// volume. For General Purpose (SSD) volumes, this represents the baseline performance
/// of the volume and the rate at which the volume accumulates I/O credits for bursting.
/// For more information on General Purpose (SSD) baseline performance, I/O credits, and
/// bursting, see <a href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSVolumeTypes.html">Amazon
/// EBS Volume Types</a> in the <i>Amazon Elastic Compute Cloud User Guide for Linux</i>.
/// </para>
///
/// <para>
/// Constraint: Range is 100 to 4000 for Provisioned IOPS (SSD) volumes and 3 to 3072
/// for General Purpose (SSD) volumes.
/// </para>
///
/// <para>
/// Condition: This parameter is required for requests to create <code>io1</code> volumes;
/// it is not used in requests to create <code>standard</code> or <code>gp2</code> volumes.
/// </para>
/// </summary>
public int Iops
{
get { return this._iops.GetValueOrDefault(); }
set { this._iops = value; }
}
// Check to see if Iops property is set
internal bool IsSetIops()
{
return this._iops.HasValue;
}
/// <summary>
/// Gets and sets the property KmsKeyId.
/// <para>
/// The full ARN of the AWS Key Management Service (KMS) master key that was used to protect
/// the volume encryption key for the volume.
/// </para>
/// </summary>
public string KmsKeyId
{
get { return this._kmsKeyId; }
set { this._kmsKeyId = value; }
}
// Check to see if KmsKeyId property is set
internal bool IsSetKmsKeyId()
{
return this._kmsKeyId != null;
}
/// <summary>
/// Gets and sets the property Size.
/// <para>
/// The size of the volume, in GiBs.
/// </para>
/// </summary>
public int Size
{
get { return this._size.GetValueOrDefault(); }
set { this._size = value; }
}
// Check to see if Size property is set
internal bool IsSetSize()
{
return this._size.HasValue;
}
/// <summary>
/// Gets and sets the property SnapshotId.
/// <para>
/// The snapshot from which the volume was created, if applicable.
/// </para>
/// </summary>
public string SnapshotId
{
get { return this._snapshotId; }
set { this._snapshotId = value; }
}
// Check to see if SnapshotId property is set
internal bool IsSetSnapshotId()
{
return this._snapshotId != null;
}
/// <summary>
/// Gets and sets the property State.
/// <para>
/// The volume state.
/// </para>
/// </summary>
public VolumeState State
{
get { return this._state; }
set { this._state = value; }
}
// Check to see if State property is set
internal bool IsSetState()
{
return this._state != null;
}
/// <summary>
/// Gets and sets the property Tags.
/// <para>
/// Any tags assigned to the volume.
/// </para>
/// </summary>
public List<Tag> Tags
{
get { return this._tags; }
set { this._tags = value; }
}
// Check to see if Tags property is set
internal bool IsSetTags()
{
return this._tags != null && this._tags.Count > 0;
}
/// <summary>
/// Gets and sets the property VolumeId.
/// <para>
/// The ID of the volume.
/// </para>
/// </summary>
public string VolumeId
{
get { return this._volumeId; }
set { this._volumeId = value; }
}
// Check to see if VolumeId property is set
internal bool IsSetVolumeId()
{
return this._volumeId != null;
}
/// <summary>
/// Gets and sets the property VolumeType.
/// <para>
/// The volume type. This can be <code>gp2</code> for General Purpose (SSD) volumes, <code>io1</code>
/// for Provisioned IOPS (SSD) volumes, or <code>standard</code> for Magnetic volumes.
/// </para>
/// </summary>
public VolumeType VolumeType
{
get { return this._volumeType; }
set { this._volumeType = value; }
}
// Check to see if VolumeType property is set
internal bool IsSetVolumeType()
{
return this._volumeType != null;
}
}
}
| |
namespace Microsoft.Protocols.TestSuites.MS_OXCROPS
{
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Runtime.InteropServices;
using Microsoft.Protocols.TestSuites.Common;
using Microsoft.Protocols.TestTools;
/// <summary>
/// MS-OXCROPS protocol adapter.
/// </summary>
public partial class MS_OXCROPSAdapter : ManagedAdapterBase, IMS_OXCROPSAdapter
{
#region Public Fields for consts definitions.
/// <summary>
/// Definition for several points in MS-OXCROPS referring 0xBABE.
/// </summary>
public const uint BufferSize = 0xBABE;
/// <summary>
/// This is used to set Flags of RPC_HEADER_EXT,which indicates it is compressed.
/// </summary>
public const ushort CompressedForFlagsOfHeader = 0x0001;
/// <summary>
/// Definition for default value of Output handle.
/// </summary>
public const uint DefaultOutputHandle = 0xFFFFFFFF;
/// <summary>
/// FolderId (8 bytes): 64-bit identifier. This field MUST be set to 0x0000000000000000
/// </summary>
public const ulong FolderIdForRopSynchronizationImportHierarchyChange = 0x0000000000000000;
/// <summary>
/// Server object handle value 0xFFFFFFFF is used to initialize unused entries of a Server object handle table.
/// </summary>
public const uint HandleValueForUnusedEntries = 0xFFFFFFFF;
/// <summary>
/// Definition for invalid input handle.
/// </summary>
public const uint InvalidInputHandle = 0xFFFFFFFF;
/// <summary>
/// This is used to set Flags of RPC_HEADER_EXT,which indicates that no other RPC_HEADER_EXT follows the data of the current RPC_HEADER_EXT.
/// </summary>
public const ushort LastForFlagsOfHeader = 0x0004;
/// <summary>
/// The maximum value of pcbOut
/// </summary>
public const uint MaxPcbOut = 0x40000;
/// <summary>
/// Definition for MaxrgbOut,which specifies the maximum size of the rgbOut buffer to place in Response
/// </summary>
public const int MaxRgbOut = 0x10008;
/// <summary>
/// MessageId (8 bytes): This field MUST be set to 0x0000000000000000.
/// </summary>
public const ulong MessageIdForRops = 0x0000000000000000;
/// <summary>
/// Definition for the Null-Terminating string.
/// </summary>
public const char NullTerminateCharacter = '\0';
/// <summary>
/// Definition for PayloadLen which indicates the length of the field that represents the length of payload.
/// </summary>
public const int PayloadLen = 0x2;
/// <summary>
/// This is used to set the max size of the rgbAuxOut.
/// </summary>
public const uint PcbAuxOut = 0x1008;
/// <summary>
/// This flags indicates client requests server to not compress or XOR payload of rgbOut and rgbAuxOut.
/// </summary>
public const uint PulFlags = 0x00000003;
/// <summary>
/// Unsigned 64-bit integer. This value specifies the number of bytes read from the source object or written to the destination object.
/// </summary>
public const ulong ReadOrWrittenByteCountForRopCopyToStream = 0x0000000000000000;
/// <summary>
/// Definition the one reserved byte: 0x00
/// </summary>
public const byte ReservedOneByte = 0x00;
/// <summary>
/// Definition the two reserved bytes: 0x0000
/// </summary>
public const ushort ReservedTwoBytes = 0x0000;
/// <summary>
/// Definition for ReturnValue of PulFlags,which MUST be set to 0x00000000.
/// </summary>
public const int ReturnValueForPulFlags = 0x00000000;
/// <summary>
/// Definition for the possible return value of RopFastTransferSourceGetBufferResponse: 0x00000480.
/// </summary>
public const uint ReturnValueForRopFastTransferSourceGetBufferResponse = 0x00000480;
/// <summary>
/// Definition for the possible return value of RopMoveFolderResponse and RopMoveCopyMessagesResponse: 0x00000503.
/// </summary>
public const uint ReturnValueForRopMoveFolderResponseAndMoveCopyMessage = 0x00000503;
/// <summary>
/// Definition for ReturnValue of RopQueryNamedProperties: 0x00040380.
/// </summary>
public const uint ReturnValueForRopQueryNamedProperties = 0x00040380;
/// <summary>
/// Definition for the possible return value of Redirect response: 0x00000478.
/// </summary>
public const uint WrongServer = 0x00000478;
/// <summary>
/// Definition for ReturnValue of ret, which MUST be set to 0x0.
/// </summary>
public const uint ReturnValueForRet = 0x0;
/// <summary>
/// Definition for ReturnValue of success response: 0x00000000.
/// </summary>
public const uint SuccessReturnValue = 0x00000000;
/// <summary>
/// Definition for RopSize which specifies the size of both this field and the RopsList field.
/// </summary>
public const ushort RopSize = 0x2;
/// <summary>
/// Definition for Version of RpcHeaderExt,this value MUST be set to 0x00.
/// </summary>
public const ushort VersionOfRpcHeaderExt = 0x00;
/// <summary>
/// This is used to set Flags of RPC_HEADER_EXT,which indicates it is obfuscated.
/// </summary>
public const ushort XorMagicForFlagsOfHeader = 0x0002;
#endregion
#region Private Fields
/// <summary>
/// Length of RPC_HEADER_EXT
/// </summary>
private static readonly int RPCHEADEREXTLEN = Marshal.SizeOf(typeof(RPC_HEADER_EXT));
/// <summary>
/// Whether import the common configuration file.
/// </summary>
private static bool commonConfigImported = false;
/// <summary>
/// The OxcropsClient instance.
/// </summary>
private OxcropsClient oxcropsClient;
/// <summary>
/// Status of connection.
/// </summary>
private bool isConnected;
#endregion
#region IMS_OXCROPSAdapter members
/// <summary>
/// Connect to the server for RPC calling.
/// This method is defined as a direct way to connect to server with specific parameters.
/// </summary>
/// <param name="server">Server to connect.</param>
/// <param name="connectionType">the type of connection</param>
/// <param name="userDN">User DN used to connect server</param>
/// <param name="domain">Domain name</param>
/// <param name="userName">User name used to logon</param>
/// <param name="password">User Password</param>
/// <returns>Result of connecting.</returns>
public bool RpcConnect(string server, ConnectionType connectionType, string userDN, string domain, string userName, string password)
{
bool ret = this.oxcropsClient.Connect(
server,
connectionType,
userDN,
domain,
userName,
password);
this.isConnected = ret;
return ret;
}
/// <summary>
/// Disconnect from the server.
/// </summary>
/// <returns>Result of disconnecting.</returns>
public bool RpcDisconnect()
{
if (this.isConnected)
{
// Disconnect the RPC link to server.
bool ret = this.oxcropsClient.Disconnect();
if (ret)
{
this.isConnected = false;
}
else
{
return false;
}
}
return true;
}
/// <summary>
/// Set auto redirect value in RPC context
/// If setting this to true, the RPC server will return EcWrongServer error (0x478). And the request will be redirected to designated server.
/// If setting this to false, the RPC server will return EcWrongServer error (0x478). But the request will not be redirected.
/// </summary>
/// <param name="option">true indicates enable auto redirect, false indicates disable auto redirect</param>
public void SetAutoRedirect(bool option)
{
this.oxcropsClient.MapiContext.AutoRedirect = option;
}
/// <summary>
/// Method which executes single ROP.
/// </summary>
/// <param name="ropRequest">ROP request objects.</param>
/// <param name="inputObjHandle">Server object handle in request.</param>
/// <param name="response">ROP response objects.</param>
/// <param name="rawData">The ROP response payload.</param>
/// <param name="expectedRopResponseType">ROP response type expected.</param>
/// <param name="returnValue">The return value of the ROP method.</param>
/// <returns>Server objects handles in response.</returns>
public List<List<uint>> ProcessSingleRopWithReturnValue(
ISerializable ropRequest,
uint inputObjHandle,
ref IDeserializable response,
ref byte[] rawData,
RopResponseType expectedRopResponseType,
out uint returnValue)
{
List<ISerializable> requestRops = null;
if (ropRequest != null)
{
requestRops = new List<ISerializable>
{
ropRequest
};
}
List<uint> requestSOH = new List<uint>
{
inputObjHandle
};
if (Common.IsOutputHandleInRopRequest(ropRequest))
{
// Add an element for server output object handle and set default value to 0xFFFFFFFF.
requestSOH.Add(DefaultOutputHandle);
}
if (this.IsInvalidInputHandleNeeded(ropRequest, expectedRopResponseType))
{
// Add an invalid input handle in request and set its value to 0xFFFFFFFF.
requestSOH.Add(InvalidInputHandle);
}
List<IDeserializable> responseRops = new List<IDeserializable>();
List<List<uint>> responseSOHs = new List<List<uint>>();
uint ret = this.RopCall(requestRops, requestSOH, ref responseRops, ref responseSOHs, ref rawData, MaxRgbOut);
returnValue = ret;
if (ret != OxcRpcErrorCode.ECNone && ret != 1726)
{
Site.Assert.AreEqual<RopResponseType>(RopResponseType.RPCError, expectedRopResponseType, "Unexpected RPC error {0} occurred.", ret);
return responseSOHs;
}
if (responseRops != null)
{
if (responseRops.Count > 0)
{
response = responseRops[0];
}
}
else
{
response = null;
}
if (ropRequest.GetType() == typeof(RopReleaseRequest))
{
return responseSOHs;
}
if (response.GetType() == typeof(RopSaveChangesMessageResponse) && ((RopSaveChangesMessageResponse)response).ReturnValue == 0x80040401)
{
return responseSOHs;
}
if (response != null)
{
try
{
this.VerifyAdapterCaptureCode(expectedRopResponseType, response, ropRequest);
}
catch (TargetInvocationException invocationEx)
{
Site.Log.Add(LogEntryKind.Debug, invocationEx.Message);
if (invocationEx.InnerException != null)
{
throw invocationEx.InnerException;
}
}
catch (NullReferenceException nullEx)
{
Site.Log.Add(LogEntryKind.Debug, nullEx.Message);
}
}
return responseSOHs;
}
/// <summary>
/// Method which executes single ROP.
/// </summary>
/// <param name="ropRequest">ROP request objects.</param>
/// <param name="inputObjHandle">Server object handle in request.</param>
/// <param name="response">ROP response objects.</param>
/// <param name="rawData">The ROP response payload.</param>
/// <param name="expectedRopResponseType">ROP response type expected.</param>
/// <returns>Server objects handles in response.</returns>
public List<List<uint>> ProcessSingleRop(
ISerializable ropRequest,
uint inputObjHandle,
ref IDeserializable response,
ref byte[] rawData,
RopResponseType expectedRopResponseType)
{
uint returnValue;
List<List<uint>> responseSOHs = this.ProcessSingleRopWithReturnValue(ropRequest, inputObjHandle, ref response, ref rawData, expectedRopResponseType, out returnValue);
if (returnValue == 1726)
{
Site.Assert.AreEqual<RopResponseType>(RopResponseType.RPCError, expectedRopResponseType, "Unexpected RPC error {0} occurred.", returnValue);
}
return responseSOHs;
}
/// <summary>
/// Method which executes single ROP operation with the maximum size of the rgbOut buffer set as pcbOut.
/// For more detail about rgbOut and pcbOut, see [MS-OXCRPC].
/// </summary>
/// <param name="ropRequest">ROP request objects.</param>
/// <param name="inputObjHandle">Server object handle in request.</param>
/// <param name="response">ROP response objects.</param>
/// <param name="rawData">The ROP response payload.</param>
/// <param name="expectedRopResponseType">ROP response type expected.</param>
/// <param name="pcbOut">The maximum size of the rgbOut buffer to place Response in.</param>
/// <returns>Server objects handles in response.</returns>
public List<List<uint>> ProcessSingleRopWithOptionResponseBufferSize(
ISerializable ropRequest,
uint inputObjHandle,
ref IDeserializable response,
ref byte[] rawData,
RopResponseType expectedRopResponseType,
uint pcbOut)
{
List<ISerializable> requestRops = new List<ISerializable>
{
ropRequest
};
List<uint> requestSOH = new List<uint>
{
inputObjHandle
};
if (Common.IsOutputHandleInRopRequest(ropRequest))
{
// Add an element for server output object handle and set default value to 0xFFFFFFFF.
requestSOH.Add(DefaultOutputHandle);
}
if (this.IsInvalidInputHandleNeeded(ropRequest, expectedRopResponseType))
{
// Add an invalid input handle in request and set its value to 0xFFFFFFFF.
requestSOH.Add(InvalidInputHandle);
}
List<IDeserializable> responseRops = new List<IDeserializable>();
List<List<uint>> responseSOHs = new List<List<uint>>();
uint ret = this.RopCall(requestRops, requestSOH, ref responseRops, ref responseSOHs, ref rawData, pcbOut);
if (ret != OxcRpcErrorCode.ECNone)
{
Site.Assert.AreEqual<RopResponseType>(RopResponseType.RPCError, expectedRopResponseType, "Unexpected RPC error {0} occurred.", ret);
return null;
}
if (responseRops != null)
{
if (responseRops.Count > 0)
{
response = responseRops[0];
}
}
else
{
response = null;
}
if (ropRequest.GetType() == typeof(RopReleaseRequest))
{
return responseSOHs;
}
try
{
this.VerifyAdapterCaptureCode(expectedRopResponseType, response, ropRequest);
}
catch (TargetInvocationException invocationEx)
{
Site.Log.Add(LogEntryKind.Debug, invocationEx.Message);
if (invocationEx.InnerException != null)
{
throw invocationEx.InnerException;
}
}
catch (NullReferenceException nullEx)
{
Site.Log.Add(LogEntryKind.Debug, nullEx.Message);
}
return responseSOHs;
}
/// <summary>
/// Method which executes multiple ROPs.
/// </summary>
/// <param name="requestRops">ROP request objects.</param>
/// <param name="inputObjHandles">Server object handles in request.</param>
/// <param name="responseRops">ROP response objects.</param>
/// <param name="rawData">The ROP response payload.</param>
/// <param name="expectedRopResponseType">The expected response type.</param>
/// <returns>Server objects handles in response.</returns>
public List<List<uint>> ProcessMutipleRops(
List<ISerializable> requestRops,
List<uint> inputObjHandles,
ref List<IDeserializable> responseRops,
ref byte[] rawData,
RopResponseType expectedRopResponseType)
{
List<uint> requestSOH = new List<uint>();
for (int i = 0; i < inputObjHandles.Count; i++)
{
requestSOH.Add(inputObjHandles[i]);
}
List<List<uint>> responseSOHs = new List<List<uint>>();
uint ret = this.RopCall(requestRops, requestSOH, ref responseRops, ref responseSOHs, ref rawData, MaxRgbOut);
if (ret != OxcRpcErrorCode.ECNone)
{
Site.Assert.AreEqual<RopResponseType>(RopResponseType.RPCError, expectedRopResponseType, "Unexpected RPC error {0} occurred.", ret);
return responseSOHs;
}
int numOfReqs = requestRops.Count;
int numOfRess = responseRops.Count;
for (int reqIndex = 0, resIndex = 0; reqIndex < numOfReqs && resIndex < numOfRess; resIndex++, reqIndex++)
{
while (requestRops[reqIndex].GetType() == typeof(RopReleaseRequest) && (reqIndex < numOfReqs - 1))
{
reqIndex++;
}
try
{
Type reqType = requestRops[reqIndex].GetType();
string resName = responseRops[resIndex].GetType().Name;
// The word "Response" takes 8 length.
string ropName = resName.Substring(0, resName.Length - 8);
Type adapterType = typeof(MS_OXCROPSAdapter);
// Call capture code using reflection mechanism
// The code followed is to construct the verify method name of capture code and then call this method through reflection.
MethodInfo method = null;
string verifyMethodName = "Verify" + ropName + "SuccessResponse";
method = adapterType.GetMethod(verifyMethodName, BindingFlags.NonPublic | BindingFlags.Instance);
if (method == null)
{
verifyMethodName = "Verify" + ropName + "FailureResponse";
method = adapterType.GetMethod(verifyMethodName, BindingFlags.NonPublic | BindingFlags.Instance);
}
if (method == null)
{
verifyMethodName = "Verify" + ropName + "Response";
method = adapterType.GetMethod(verifyMethodName, BindingFlags.NonPublic | BindingFlags.Instance);
}
if (method != null)
{
ParameterInfo[] paraInfos = method.GetParameters();
int paraNum = paraInfos.Length;
object[] paraObjects = new object[paraNum];
paraObjects[0] = responseRops[resIndex];
for (int i = 1; i < paraNum; i++)
{
FieldInfo fieldInReq = reqType.GetField(
paraInfos[i].Name,
BindingFlags.IgnoreCase
| BindingFlags.DeclaredOnly
| BindingFlags.Public
| BindingFlags.NonPublic
| BindingFlags.GetField
| BindingFlags.Instance);
if (fieldInReq == null)
{
foreach (ISerializable req in requestRops)
{
Type type = req.GetType();
fieldInReq = type.GetField(
paraInfos[i].Name,
BindingFlags.IgnoreCase
| BindingFlags.DeclaredOnly
| BindingFlags.Public
| BindingFlags.NonPublic
| BindingFlags.GetField
| BindingFlags.Instance);
if (fieldInReq != null)
{
paraObjects[i] = fieldInReq.GetValue(req);
}
}
}
else
{
paraObjects[i] = fieldInReq.GetValue(requestRops[reqIndex]);
}
}
method.Invoke(this, paraObjects);
}
}
catch (TargetInvocationException invocationEx)
{
Site.Log.Add(LogEntryKind.Debug, invocationEx.Message);
if (invocationEx.InnerException != null)
{
throw invocationEx.InnerException;
}
}
catch (NullReferenceException nullEx)
{
Site.Log.Add(LogEntryKind.Debug, nullEx.Message);
}
if (resIndex < numOfRess - 1)
{
if (responseRops[resIndex + 1].GetType() == typeof(RopNotifyResponse) || responseRops[resIndex + 1].GetType() == typeof(RopPendingResponse))
{
reqIndex--;
}
}
}
return responseSOHs;
}
/// <summary>
/// Method which executes single ROP with multiple server objects.
/// </summary>
/// <param name="ropRequest">ROP request object.</param>
/// <param name="inputObjHandles">Server object handles in request.</param>
/// <param name="response">ROP response object.</param>
/// <param name="rawData">The ROP response payload.</param>
/// <param name="expectedRopResponseType">ROP response type expected.</param>
/// <returns>Server objects handles in response.</returns>
public List<List<uint>> ProcessSingleRopWithMutipleServerObjects(
ISerializable ropRequest,
List<uint> inputObjHandles,
ref IDeserializable response,
ref byte[] rawData,
RopResponseType expectedRopResponseType)
{
List<ISerializable> requestRops = new List<ISerializable>
{
ropRequest
};
List<uint> requestSOH = new List<uint>();
for (int i = 0; i < inputObjHandles.Count; i++)
{
requestSOH.Add(inputObjHandles[i]);
}
if (Common.IsOutputHandleInRopRequest(ropRequest))
{
// Add an element for server output object handle, set default value to 0xFFFFFFFF
requestSOH.Add(DefaultOutputHandle);
}
List<IDeserializable> responseRops = new List<IDeserializable>();
List<List<uint>> responseSOHs = new List<List<uint>>();
uint ret = this.RopCall(requestRops, requestSOH, ref responseRops, ref responseSOHs, ref rawData, MaxRgbOut);
if (ret != OxcRpcErrorCode.ECNone)
{
Site.Assert.AreEqual<RopResponseType>(RopResponseType.RPCError, expectedRopResponseType, "Unexpected RPC error {0} occurred.", ret);
return responseSOHs;
}
if (responseRops != null)
{
if (responseRops.Count > 0)
{
response = responseRops[0];
}
}
else
{
response = null;
}
if (ropRequest.GetType() == typeof(RopReleaseRequest))
{
return responseSOHs;
}
try
{
this.VerifyAdapterCaptureCode(expectedRopResponseType, response, ropRequest);
}
catch (TargetInvocationException invocationEx)
{
Site.Log.Add(LogEntryKind.Debug, invocationEx.Message);
if (invocationEx.InnerException != null)
{
throw invocationEx.InnerException;
}
}
catch (NullReferenceException nullEx)
{
Site.Log.Add(LogEntryKind.Debug, nullEx.Message);
}
return responseSOHs;
}
#endregion
#region IAdapter members
/// <summary>
/// Initialize the adapter.
/// </summary>
/// <param name="testSite">Test site.</param>
public override void Initialize(ITestSite testSite)
{
base.Initialize(testSite);
Site.DefaultProtocolDocShortName = "MS-OXCROPS";
if (!commonConfigImported)
{
Common.MergeConfiguration(this.Site);
commonConfigImported = true;
}
// Initialize OxcropsClient instance.
this.oxcropsClient = new OxcropsClient(MapiContext.GetDefaultRpcContext(this.Site));
}
#endregion
#region Private Function
#region Functions for Adapter
/// <summary>
/// Check whether the array of byte is null terminated ASCII string.
/// </summary>
/// <param name="buffer">The array of byte which to be checked whether null terminated ASCII string</param>
/// <returns>A boolean type indicating whether the passed string is a null-terminated ASCII string.</returns>
private bool IsNullTerminatedASCIIStr(byte[] buffer)
{
int len = buffer.Length;
// Check null terminate.
bool isNullTerminated = buffer[len - 1] == 0x00;
bool isASCIIString = true;
for (int i = 0; i < buffer.Length; i++)
{
// ASCII between 0x00 and 0x7F
if (buffer[i] >= 0x00 && buffer[i] <= 0x7F)
{
continue;
}
else
{
isASCIIString = false;
break;
}
}
return isNullTerminated && isASCIIString;
}
/// <summary>
/// Verify whether the GUID bytes is GUID or not
/// </summary>
/// <param name="guidBytes">An array of bytes.</param>
/// <returns>If it is GUID, return true, else return false.</returns>
private bool IsGUID(byte[] guidBytes)
{
bool isGUID = false;
// Check GUID length with 16.
if (guidBytes.Length == 16)
{
Guid guid = new Guid(guidBytes);
// GUID format check regExpression.
string regexPatten = @"^(\{){0,1}[0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\"
+ @"-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}(\}){0,1}$";
System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(regexPatten);
string guidStr = guid.ToString();
isGUID = regex.IsMatch(guidStr);
}
return isGUID;
}
/// <summary>
/// Verify adapter capture code using reflection mechanism.
/// </summary>
/// <param name="expectedRopResponseType">The Expected ROP response type.</param>
/// <param name="response">ROP response object.</param>
/// <param name="ropRequest">ROP request object.</param>
private void VerifyAdapterCaptureCode(RopResponseType expectedRopResponseType, IDeserializable response, ISerializable ropRequest)
{
string resName = response.GetType().Name;
// The word "Response" takes 8 length.
string ropName = resName.Substring(0, resName.Length - 8);
Type adapterType = typeof(MS_OXCROPSAdapter);
// Call capture code using reflection mechanism
// The code followed is to construct the verify method name of capture code and then call this method through reflection.
string verifyMethodName = string.Empty;
if (expectedRopResponseType == RopResponseType.SuccessResponse)
{
verifyMethodName = "Verify" + ropName + "SuccessResponse";
}
else if (expectedRopResponseType == RopResponseType.FailureResponse)
{
verifyMethodName = "Verify" + ropName + "FailureResponse";
}
else if (expectedRopResponseType == RopResponseType.Response)
{
verifyMethodName = "Verify" + ropName + "Response";
}
else if (expectedRopResponseType == RopResponseType.NullDestinationFailureResponse)
{
verifyMethodName = "Verify" + ropName + "NullDestinationFailureResponse";
}
else if (expectedRopResponseType == RopResponseType.RedirectResponse)
{
verifyMethodName = "Verify" + ropName + "RedirectResponse";
}
Type reqType = ropRequest.GetType();
MethodInfo method = adapterType.GetMethod(verifyMethodName, BindingFlags.NonPublic | BindingFlags.Instance);
if (method == null)
{
if (expectedRopResponseType == RopResponseType.SuccessResponse || expectedRopResponseType == RopResponseType.FailureResponse)
{
verifyMethodName = "Verify" + ropName + "Response";
method = adapterType.GetMethod(verifyMethodName, BindingFlags.NonPublic | BindingFlags.Instance);
}
}
if (method != null)
{
ParameterInfo[] paraInfos = method.GetParameters();
int paraNum = paraInfos.Length;
object[] paraObjects = new object[paraNum];
paraObjects[0] = response;
for (int i = 1; i < paraNum; i++)
{
FieldInfo fieldInReq = reqType.GetField(
paraInfos[i].Name,
BindingFlags.IgnoreCase
| BindingFlags.DeclaredOnly
| BindingFlags.Public
| BindingFlags.NonPublic
| BindingFlags.GetField
| BindingFlags.Instance);
paraObjects[i] = fieldInReq.GetValue(ropRequest);
}
method.Invoke(this, paraObjects);
}
}
/// <summary>
/// Check whether the default invalid handle is needed.
/// </summary>
/// <param name="ropRequest">ROP request objects.</param>
/// <param name="expectedRopResponseType">The expected ROP response type.</param>
/// <returns>Return true if the default handle is needed in the request, otherwise return false.</returns>
private bool IsInvalidInputHandleNeeded(ISerializable ropRequest, RopResponseType expectedRopResponseType)
{
if (!Common.IsOutputHandleInRopRequest(ropRequest) && expectedRopResponseType == RopResponseType.FailureResponse)
{
byte[] request = ropRequest.Serialize();
// The default handle is also needed by some cases to verify the failure response caused by an invalid input handle.
// The input handle index is the third byte and its value is 1 in this test suite for this situation.
byte inputHandleIndex = request[2];
if (inputHandleIndex == 1)
{
return true;
}
}
return false;
}
#endregion
#region Functions for Process
/// <summary>
/// The method parses response buffer.
/// </summary>
/// <param name="rgbOut">The ROP response payload.</param>
/// <param name="rpcHeaderExts">RPC header extension.</param>
/// <param name="rops">ROPs in response.</param>
/// <param name="serverHandleObjectsTables">Server handle objects tables</param>
private void ParseResponseBuffer(byte[] rgbOut, out RPC_HEADER_EXT[] rpcHeaderExts, out byte[][] rops, out uint[][] serverHandleObjectsTables)
{
List<RPC_HEADER_EXT> rpcHeaderExtList = new List<RPC_HEADER_EXT>();
List<byte[]> ropList = new List<byte[]>();
List<uint[]> serverHandleObjectList = new List<uint[]>();
IntPtr ptr = IntPtr.Zero;
int index = 0;
bool end = false;
do
{
// Parse RPC header extension
RPC_HEADER_EXT rpcHeaderExt;
ptr = Marshal.AllocHGlobal(RPCHEADEREXTLEN);
try
{
Marshal.Copy(rgbOut, index, ptr, RPCHEADEREXTLEN);
rpcHeaderExt = (RPC_HEADER_EXT)Marshal.PtrToStructure(ptr, typeof(RPC_HEADER_EXT));
end = (rpcHeaderExt.Flags & LastForFlagsOfHeader) == LastForFlagsOfHeader;
rpcHeaderExtList.Add(rpcHeaderExt);
index += RPCHEADEREXTLEN;
}
finally
{
Marshal.FreeHGlobal(ptr);
}
#region Start parse payload
// Parse ropSize
ushort ropSize = BitConverter.ToUInt16(rgbOut, index);
index += sizeof(ushort);
if ((ropSize - sizeof(ushort)) > 0)
{
// Parse ROP
byte[] rop = new byte[ropSize - sizeof(ushort)];
Array.Copy(rgbOut, index, rop, 0, ropSize - sizeof(ushort));
ropList.Add(rop);
index += ropSize - sizeof(ushort);
}
// Parse server handle objects table
Site.Assert.IsTrue(
(rpcHeaderExt.Size - ropSize) % sizeof(uint) == 0, "server object handle should be uint32 array");
int count = (rpcHeaderExt.Size - ropSize) / sizeof(uint);
if (count > 0)
{
uint[] sohs = new uint[count];
for (int k = 0; k < count; k++)
{
sohs[k] = BitConverter.ToUInt32(rgbOut, index);
index += sizeof(uint);
}
serverHandleObjectList.Add(sohs);
}
#endregion
}
while (!end);
rpcHeaderExts = rpcHeaderExtList.ToArray();
rops = ropList.ToArray();
serverHandleObjectsTables = serverHandleObjectList.ToArray();
}
/// <summary>
/// The method creates ROPs request.
/// </summary>
/// <param name="requestROPs">ROPs in request.</param>
/// <param name="requestSOHTable">Server object handles table.</param>
/// <returns>The ROPs request.</returns>
private byte[] BuildRequestBuffer(List<ISerializable> requestROPs, List<uint> requestSOHTable)
{
// Definition for PayloadLen which indicates the length of the field that represents the length of payload.
int payloadLen = PayloadLen;
if (requestROPs != null)
{
foreach (ISerializable requestROP in requestROPs)
{
payloadLen += requestROP.Size();
}
}
Site.Assert.IsTrue(
payloadLen < ushort.MaxValue,
"The number of bytes in this field MUST be 2 bytes less than the value specified in the RopSize field.");
ushort ropSize = (ushort)payloadLen;
if (requestSOHTable != null)
{
payloadLen += requestSOHTable.Count * sizeof(uint);
}
byte[] requestBuffer = new byte[RPCHEADEREXTLEN + payloadLen];
int index = 0;
// Construct RPC header extension buffer
RPC_HEADER_EXT rpcHeaderExt = new RPC_HEADER_EXT
{
Version = VersionOfRpcHeaderExt, // There is only one version of the header at this time so this value MUST be set to 0x00.
Flags = LastForFlagsOfHeader, // Last (0x04) indicates that no other RPC_HEADER_EXT follows the data of the current RPC_HEADER_EXT.
Size = (ushort)payloadLen
};
rpcHeaderExt.SizeActual = rpcHeaderExt.Size;
IntPtr ptr = Marshal.AllocHGlobal(RPCHEADEREXTLEN);
try
{
Marshal.StructureToPtr(rpcHeaderExt, ptr, true);
Marshal.Copy(ptr, requestBuffer, index, RPCHEADEREXTLEN);
index += RPCHEADEREXTLEN;
}
finally
{
Marshal.FreeHGlobal(ptr);
}
// RopSize's type is ushort. So the offset will be 2.
Array.Copy(BitConverter.GetBytes(ropSize), 0, requestBuffer, index, 2);
index += 2;
if (requestROPs != null)
{
foreach (ISerializable requestROP in requestROPs)
{
Array.Copy(requestROP.Serialize(), 0, requestBuffer, index, requestROP.Size());
index += requestROP.Size();
}
}
if (requestSOHTable != null)
{
foreach (uint serverHandle in requestSOHTable)
{
Array.Copy(BitConverter.GetBytes(serverHandle), 0, requestBuffer, index, sizeof(uint));
index += sizeof(uint);
}
}
return requestBuffer;
}
/// <summary>
/// Do EcDoRPCExt2 call.
/// </summary>
/// <param name="requestROPs">ROP request objects.</param>
/// <param name="requestSOHTable">ROP request server object handle table.</param>
/// <param name="responseROPs">ROP response objects.</param>
/// <param name="responseSOHTable">ROP response server object handle table.</param>
/// <param name="rawData">The response payload bytes.</param>
/// <param name="pcbOut">The maximum size of the rgbOut buffer to place Response in.</param>
/// <returns>0 indicates success, other values indicate failure. </returns>
private uint RopCall(
List<ISerializable> requestROPs,
List<uint> requestSOHTable,
ref List<IDeserializable> responseROPs,
ref List<List<uint>> responseSOHTable,
ref byte[] rawData,
uint pcbOut)
{
byte[] rgbIn = this.BuildRequestBuffer(requestROPs, requestSOHTable);
uint ret = this.oxcropsClient.RopCall(requestROPs, requestSOHTable, ref responseROPs, ref responseSOHTable, ref rawData, pcbOut);
if (ret != OxcRpcErrorCode.ECNone)
{
// Verify error for RPC
if (this.oxcropsClient.IsReservedRopId(rgbIn[10]))
{
this.VerifyRPCErrorEncounterReservedRopIds(rgbIn[10], (uint)ret);
return ret;
}
else
{
// RopOpenFolder
if (rgbIn[10] == Convert.ToByte(RopId.RopOpenFolder))
{
if (ret == OxcRpcErrorCode.ECRpcFormat)
{
this.VerifyRPCErrorEncounterUnableParseRequest((uint)ret);
}
return ret;
}
// RopReadStream
if (rgbIn[10] == Convert.ToByte(RopId.RopReadStream))
{
if (ret == OxcRpcErrorCode.ECRpcFormat)
{
this.VerifyMaximumByteCountExceedError((uint)ret);
}
return ret;
}
}
}
if (ret == OxcRpcErrorCode.ECRpcFormat)
{
Site.Assert.Fail("Error RPC Format");
}
if (ret == OxcRpcErrorCode.ECResponseTooBig)
{
this.VerifyFailRPCForMaxPcbOut(ret);
this.VerifyFailRPCForInsufficientOutputBuffer(ret);
return ret;
}
Site.Assert.AreEqual<uint>(ReturnValueForRet, ret, "If the response is success, the return value is 0x0.");
this.VerifyTransport();
RPC_HEADER_EXT[] rpcHeaderExts;
byte[][] rops;
uint[][] serverHandleObjectsTables;
this.ParseResponseBuffer(rawData, out rpcHeaderExts, out rops, out serverHandleObjectsTables);
Site.Assert.AreEqual<int>(1, rpcHeaderExts.Length, "Support one rpc/payload only");
if (responseSOHTable.Count > 0)
{
ushort ropSize = BitConverter.ToUInt16(rawData, RPCHEADEREXTLEN);
// Verify each ROP response buffer structure
this.VerifyMessageSyntaxRequestAndResponseBuffer(ropSize, rops, responseSOHTable[0], rawData);
// Verify Message Processing Events and Sequencing Rules
this.VerifyMessageProcessingEventsAndSequencingRules(responseSOHTable[0]);
}
return ret;
}
#endregion
#endregion
}
}
| |
// (c) Copyright Microsoft Corporation.
// This source is subject to the Microsoft Permissive License.
// See http://www.microsoft.com/opensource/licenses.mspx#Ms-PL.
// All other rights reserved.
using System;
using System.CodeDom;
using System.Collections;
using System.Drawing;
using System.Globalization;
using System.Threading;
using System.Windows.Automation;
using System.Windows;
namespace Microsoft.Test.UIAutomation.Tests.Patterns
{
using InternalHelper;
using InternalHelper.Tests;
using InternalHelper.Enumerations;
using Microsoft.Test.UIAutomation;
using Microsoft.Test.UIAutomation.Core;
using Microsoft.Test.UIAutomation.TestManager;
using Microsoft.Test.UIAutomation.Interfaces;
/// -----------------------------------------------------------------------
/// <summary>
/// Table pattern test class
/// </summary>
/// -----------------------------------------------------------------------
public sealed class TableTests : PatternObject
{
#region Member variables
/// <summary>
/// Specific interface associated with this pattern
/// </summary>
TablePattern m_pattern = null;
#endregion Member variables
const string THIS = "TableTests";
/// -------------------------------------------------------------------
/// <summary>
/// TestSuite associtated for this class
/// </summary>
/// -------------------------------------------------------------------
public const string TestSuite = NAMESPACE + "." + THIS;
/// -------------------------------------------------------------------
/// <summary>
/// Pattern name for TablePattern
/// </summary>
/// -------------------------------------------------------------------
public static readonly string TestWhichPattern = Automation.PatternName(TablePattern.Pattern);
/// -------------------------------------------------------------------
/// <summary>
/// Get the tablepattern on the element
/// </summary>
/// -------------------------------------------------------------------
public TableTests(AutomationElement element, TestPriorities priority, string dirResults, bool testEvents, TypeOfControl typeOfControl, IApplicationCommands commands)
:
base(element, TestSuite, priority, typeOfControl, TypeOfPattern.Table, dirResults, testEvents, commands)
{
m_pattern = (TablePattern)GetPattern(m_le, m_useCurrent, TablePattern.Pattern);
if (m_pattern == null)
throw new Exception(Helpers.PatternNotSupported);
}
#region Tests
/// -------------------------------------------------------------------
/// <summary>
/// Test case for RowOrColumnMajor
/// </summary>
/// -------------------------------------------------------------------
[TestCaseAttribute("Table.RowOrColumnMajor",
TestSummary = "Get the RowOrColumnMajor and verify that it is one of the enums - RowOrColumnMajor",
Priority = TestPriorities.Pri0,
Status = TestStatus.Works,
ProblemDescription = "Testing the RowOrColumnMajor property",
TestCaseType = TestCaseType.Generic ,
Client = Client.ATG,
Author = "Microsoft Corp.",
Description = new string[] {
"Precondition: None",
"Step: Get the RowOrColumnMajor",
"Verify: The enum is on of the values in 'RowOrColumnMajor'"
})]
public void GetRowOrColumnMajor(TestCaseAttribute testCaseAtrribute)
{
HeaderComment(testCaseAtrribute);
RowOrColumnMajor retrievedRowOrColumnMajor;
//Step: Get the RowOrColumnMajor
TS_GetRowOrColumnMajor(out retrievedRowOrColumnMajor, CheckType.Verification);
if (retrievedRowOrColumnMajor == RowOrColumnMajor.RowMajor)
{
Comment("RowOrColumnMajor is RowMajor");
}
else if (retrievedRowOrColumnMajor == RowOrColumnMajor.ColumnMajor)
{
Comment("RowOrColumnMajor is ColumnMajor");
}
else if (retrievedRowOrColumnMajor == RowOrColumnMajor.Indeterminate)
{
Comment("RowOrColumnMajor is Indeterminate");
}
else
{
ThrowMe(CheckType.Verification, "{0} : returned for RowOrColumnMajor", retrievedRowOrColumnMajor);
}
}
/// -------------------------------------------------------------------
/// <summary>
/// Test case for RowCount property
/// </summary>
/// -------------------------------------------------------------------
[TestCaseAttribute("Table.RowCount",
TestSummary = "Get the RowCount and verify that it is >= 0",
Priority = TestPriorities.Pri0,
Status = TestStatus.Works,
ProblemDescription = "Testing the RowCount property",
TestCaseType = TestCaseType.Generic,
Client = Client.ATG,
Author = "Microsoft Corp.",
Description = new string[] {
"Precondition: None",
"Step: Get the RowCount",
"Verify: RowCount >= 0"
})]
public void GetRowCount(TestCaseAttribute testCaseAtrribute)
{
HeaderComment(testCaseAtrribute);
int retrievedRowCount;
//Step: Get the RowCount
TS_GetRowCount(out retrievedRowCount, CheckType.Verification);
Comment("RowCount is {0}", retrievedRowCount);
if (retrievedRowCount < 0)
{
ThrowMe(CheckType.Verification, "{0} : negative value returned for RowCount", retrievedRowCount);
}
}
/// -------------------------------------------------------------------
/// <summary>
/// Test case for ColumnCount property
/// </summary>
/// -------------------------------------------------------------------
[TestCaseAttribute("Table.ColumnCount",
TestSummary = "Get the ColumnCount and verify that it is >= 0",
Priority = TestPriorities.Pri0,
Status = TestStatus.Works,
ProblemDescription = "Testing the ColumnCount property",
TestCaseType = TestCaseType.Generic,
Client = Client.ATG,
Author = "Microsoft Corp.",
Description = new string[] {
"Precondition: None",
"Step: Get the ColumnCount",
"Verify: ColumnCount >= 0"
})]
public void GetColumnCount(TestCaseAttribute testCaseAtrribute)
{
HeaderComment(testCaseAtrribute);
int retrievedColumnCount;
//Step: Get the ColumnCount
TS_GetColumnCount(out retrievedColumnCount, CheckType.Verification);
Comment("ColumnCount is {0}", retrievedColumnCount);
if (retrievedColumnCount < 0)
{
ThrowMe(CheckType.Verification, "{0} : negative value returned for ColumnCount", retrievedColumnCount);
}
}
/// -------------------------------------------------------------------
/// <summary>
/// Test case for ColumnHeaders
/// </summary>
/// -------------------------------------------------------------------
[TestCaseAttribute("Table.GetColumnHeaders",
TestSummary = "Get the ColumnHeaders and verify that it is >= 0. Verify that they are header control type",
Priority = TestPriorities.Pri0,
Status = TestStatus.Works,
ProblemDescription = "Testing the GetColumnHeaders property",
TestCaseType = TestCaseType.Generic,
Client = Client.ATG,
Author = "Microsoft Corp.",
Description = new string[] {
"Precondition: None",
"Step: Get the Number of ColumnHeaders",
"Step: Get the Column Header control type",
"Verify: Number of Column headers >= 0",
"Verify: Control Type is header"
})]
public void GetColumnHeaders(TestCaseAttribute testCaseAtrribute)
{
HeaderComment(testCaseAtrribute);
AutomationElement[] tableColumnHeaders;
//Step: Get the ColumnHeaders
TS_GetColumnHeaders(out tableColumnHeaders, CheckType.Verification);
Comment("Number of ColumnHeaders: {0}", tableColumnHeaders.Length);
if (tableColumnHeaders.Length < 0)
{
ThrowMe(CheckType.Verification, "{0} : negative value returned for ColumnHeaders", tableColumnHeaders.Length);
}
foreach (AutomationElement header in tableColumnHeaders)
{
if (header.Current.ControlType == ControlType.HeaderItem)
{
Comment("Header Control Type verified for Column Header: {0}", header.Current.Name);
}
else
{
ThrowMe(CheckType.Verification, "{0} : Control Type on Column Header", header.Current.ControlType, header.Current.Name);
}
}
}
/// -------------------------------------------------------------------
/// <summary>
/// Test case for RowHeaders
/// </summary>
/// -------------------------------------------------------------------
[TestCaseAttribute("Table.GetRowHeaders",
TestSummary = "Get the RowHeaders and verify that it is >= 0. Verify that they are header control type",
Priority = TestPriorities.Pri0,
Status = TestStatus.Works,
ProblemDescription = "Testing the GetRowHeaders property",
TestCaseType = TestCaseType.Generic,
Client = Client.ATG,
Author = "Microsoft Corp.",
Description = new string[] {
"Precondition: None",
"Step: Get the Number of RowHeaders",
"Step: Get the Row Header control type",
"Verify: Number of Row headers >= 0",
"Verify: Control Type is header"
})]
public void GetRowHeaders(TestCaseAttribute testCaseAtrribute)
{
HeaderComment(testCaseAtrribute);
AutomationElement[] tableRowHeaders;
TS_GetRowHeaders(out tableRowHeaders, CheckType.Verification);
Comment("Number of RowHeaders: {0}", tableRowHeaders.Length);
if (tableRowHeaders.Length < 0)
{
ThrowMe(CheckType.Verification, "{0} : negative value returned for RowHeaders", tableRowHeaders.Length);
}
foreach (AutomationElement header in tableRowHeaders)
{
if (header.Current.ControlType == ControlType.HeaderItem)
{
Comment("Header Control Type verified for Row Header: {0}", header.Current.Name);
}
else
{
ThrowMe(CheckType.Verification, "{0} : Control Type on Row Header", header.Current.ControlType, header.Current.Name);
}
}
}
/// -------------------------------------------------------------------
/// <summary>
/// Test case for RowOrColumnMajor
/// </summary>
/// -------------------------------------------------------------------
void TS_GetRowOrColumnMajor(out RowOrColumnMajor rowOrColumnMajor, CheckType ct)
{
if (m_useCurrent)
{
rowOrColumnMajor = m_pattern.Current.RowOrColumnMajor;
}
else
{
rowOrColumnMajor = m_pattern.Cached.RowOrColumnMajor;
}
m_TestStep++;
}
/// -------------------------------------------------------------------
/// <summary>
/// Test case for ColumnCount
/// </summary>
/// -------------------------------------------------------------------
void TS_GetColumnCount(out int colCount, CheckType ct)
{
if (m_useCurrent)
{
colCount = m_pattern.Current.ColumnCount;
}
else
{
colCount = m_pattern.Cached.ColumnCount;
}
Comment("Getting column count(" + colCount + ")");
m_TestStep++;
}
/// -------------------------------------------------------------------
/// <summary>
/// Test case for RowCount
/// </summary>
/// -------------------------------------------------------------------
void TS_GetRowCount(out int rowCount, CheckType ct)
{
if (m_useCurrent)
{
rowCount = m_pattern.Current.RowCount;
}
else
{
rowCount = m_pattern.Cached.RowCount;
}
Comment("Getting row count(" + rowCount + ")");
m_TestStep++;
}
/// -------------------------------------------------------------------
/// <summary>
/// Test case for ColumnHeaders
/// </summary>
/// -------------------------------------------------------------------
void TS_GetColumnHeaders(out AutomationElement[] columnHeaders, CheckType ct)
{
if (m_useCurrent)
{
columnHeaders = m_pattern.Current.GetColumnHeaders();
}
else
{
columnHeaders = m_pattern.Cached.GetColumnHeaders();
}
m_TestStep++;
}
/// -------------------------------------------------------------------
/// <summary>
/// Test case for RowHeaders
/// </summary>
/// -------------------------------------------------------------------
void TS_GetRowHeaders(out AutomationElement[] rowHeaders, CheckType ct)
{
if (m_useCurrent)
{
rowHeaders = m_pattern.Current.GetRowHeaders();
}
else
{
rowHeaders = m_pattern.Cached.GetRowHeaders();
}
m_TestStep++;
}
#endregion Tests
#region Step/Verification
#endregion Step/Verification
}
}
| |
// ********************************************************************************************************
// Product Name: DotSpatial.Data.dll
// Description: The data access libraries for the DotSpatial project.
// ********************************************************************************************************
//
// The Original Code is from MapWindow.dll version 6.0
//
// The Initial Developer of this Original Code is Ted Dunsford. Created 3/2/2010 10:56:27 AM
//
// Contributor(s): (Open source contributors should list themselves and their modifications here).
//
// ********************************************************************************************************
using System;
using System.Collections;
using System.Collections.Generic;
namespace DotSpatial.Data
{
/// <summary>
/// The FeatureSetPack contains a MultiPoint, Line and Polygon FeatureSet which can
/// handle the various types of geometries that can arrive from a mixed geometry.
/// </summary>
public class FeatureSetPack : IEnumerable<IFeatureSet>
{
/// <summary>
/// The featureset with all the lines
/// </summary>
public IFeatureSet Lines;
/// <summary>
/// The featureset with all the points
/// </summary>
public IFeatureSet Points;
/// <summary>
/// The featureset with all the polygons
/// </summary>
public IFeatureSet Polygons;
private int _lineLength;
private List<double[]> _lineVertices;
private int _pointLength;
private List<double[]> _pointVertices;
private int _polygonLength;
/// <summary>
/// Stores the raw vertices from the different shapes in a list while being created.
/// That way, the final array can be created one time.
/// </summary>
private List<double[]> _polygonVertices;
/// <summary>
/// Creates a new instance of the FeatureSetPack
/// </summary>
public FeatureSetPack()
{
Polygons = new FeatureSet(FeatureType.Polygon);
Polygons.IndexMode = true;
Points = new FeatureSet(FeatureType.MultiPoint);
Points.IndexMode = true;
Lines = new FeatureSet(FeatureType.Line);
Lines.IndexMode = true;
_polygonVertices = new List<double[]>();
_pointVertices = new List<double[]>();
_lineVertices = new List<double[]>();
}
#region IEnumerable<IFeatureSet> Members
/// <inheritdoc />
public IEnumerator<IFeatureSet> GetEnumerator()
{
return new FeatureSetPackEnumerator(this);
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
#endregion
/// <summary>
/// Clears the vertices and sets up new featuresets.
/// </summary>
public void Clear()
{
_polygonVertices = new List<double[]>();
_pointVertices = new List<double[]>();
_lineVertices = new List<double[]>();
Polygons = new FeatureSet(FeatureType.Polygon);
Polygons.IndexMode = true;
Points = new FeatureSet(FeatureType.MultiPoint);
Points.IndexMode = true;
Lines = new FeatureSet(FeatureType.Line);
Lines.IndexMode = true;
_lineLength = 0;
_polygonLength = 0;
_pointLength = 0;
}
/// <summary>
/// Adds the shape. Assumes that the "part" indices are created with a 0 base, and the number of
/// vertices is specified. The start range of each part will be updated with the new shape range.
/// The vertices array itself iwll be updated during hte stop editing step.
/// </summary>
/// <param name="shapeVertices"></param>
/// <param name="shape"></param>
public void Add(double[] shapeVertices, ShapeRange shape)
{
if (shape.FeatureType == FeatureType.Point || shape.FeatureType == FeatureType.MultiPoint)
{
_pointVertices.Add(shapeVertices);
shape.StartIndex = _pointLength / 2; // point offset, not double offset
Points.ShapeIndices.Add(shape);
_pointLength += shapeVertices.Length;
}
if (shape.FeatureType == FeatureType.Line)
{
_lineVertices.Add(shapeVertices);
shape.StartIndex = _lineLength / 2; // point offset
Lines.ShapeIndices.Add(shape);
_lineLength += shapeVertices.Length;
}
if (shape.FeatureType == FeatureType.Polygon)
{
_polygonVertices.Add(shapeVertices);
shape.StartIndex = _polygonLength / 2; // point offset
Polygons.ShapeIndices.Add(shape);
_polygonLength += shapeVertices.Length / 2;
}
}
/// <summary>
/// Finishes the featuresets by converting the lists
/// </summary>
public void StopEditing()
{
Points.Vertex = Combine(_pointVertices, _pointLength);
Points.UpdateExtent();
Lines.Vertex = Combine(_lineVertices, _lineLength);
Lines.UpdateExtent();
Polygons.Vertex = Combine(_polygonVertices, _polygonLength);
Polygons.UpdateExtent();
}
/// <summary>
/// Combines the vertices, finalizing the creation
/// </summary>
/// <param name="verts"></param>
/// <param name="length"></param>
/// <returns></returns>
public static double[] Combine(IEnumerable<double[]> verts, int length)
{
double[] result = new double[length * 2];
int offset = 0;
foreach (double[] shape in verts)
{
Array.Copy(shape, 0, result, offset, shape.Length);
offset += shape.Length;
}
return result;
}
#region Nested type: FeatureSetPackEnumerator
/// <summary>
/// Enuemratres the FeatureSetPack in Polygon, Line, Point order. If any member
/// is null, it skips that member.
/// </summary>
public class FeatureSetPackEnumerator : IEnumerator<IFeatureSet>
{
private readonly FeatureSetPack _parent;
private IFeatureSet _current;
private int _index;
/// <summary>
/// Creates the FeatureSetPackEnumerator based on the specified FeaturSetPack
/// </summary>
/// <param name="parent">The Pack</param>
public FeatureSetPackEnumerator(FeatureSetPack parent)
{
_parent = parent;
_index = -1;
}
#region IEnumerator<IFeatureSet> Members
/// <inheritdoc />
public IFeatureSet Current
{
get { return _current; }
}
object IEnumerator.Current
{
get { return _current; }
}
/// <inheritdoc />
public void Dispose()
{
}
/// <inheritdoc />
public bool MoveNext()
{
_current = null;
while (_current == null || _current.Vertex == null || _current.Vertex.Length == 0)
{
_index++;
if (_index > 2) return false;
switch (_index)
{
case 0:
_current = _parent.Polygons;
break;
case 1:
_current = _parent.Lines;
break;
case 2:
_current = _parent.Points;
break;
}
}
return true;
}
/// <inheritdoc />
public void Reset()
{
_index = -1;
_current = null;
}
#endregion
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.Util;
namespace PushSharp.Client
{
[Android.Runtime.Preserve(AllMembers=true)]
public abstract class PushHandlerServiceBase : IntentService
{
const string TAG = "GCMBaseIntentService";
const string WAKELOCK_KEY = "GCM_LIB";
static PowerManager.WakeLock sWakeLock;
static object LOCK = new object();
static int serviceId = 1;
static string[] SenderIds = new string[] {};
//int sCounter = 1;
Random sRandom = new Random();
const int MAX_BACKOFF_MS = 3600000; //1 hour
string TOKEN = "";
const string EXTRA_TOKEN = "token";
protected PushHandlerServiceBase() : base() {}
public PushHandlerServiceBase(params string[] senderIds)
: base("GCMIntentService-" + (serviceId++).ToString())
{
SenderIds = senderIds;
}
protected abstract void OnMessage(Context context, Intent intent);
protected virtual void OnDeletedMessages(Context context, int total)
{
}
protected virtual bool OnRecoverableError(Context context, string errorId)
{
return true;
}
protected abstract void OnError(Context context, string errorId);
protected abstract void OnRegistered(Context context, string registrationId);
protected abstract void OnUnRegistered(Context context, string registrationId);
protected override void OnHandleIntent(Intent intent)
{
try
{
var context = this.ApplicationContext;
var action = intent.Action;
if (action.Equals(GCMConstants.INTENT_FROM_GCM_REGISTRATION_CALLBACK))
{
handleRegistration(context, intent);
}
else if (action.Equals(GCMConstants.INTENT_FROM_GCM_MESSAGE))
{
// checks for special messages
var messageType = intent.GetStringExtra(GCMConstants.EXTRA_SPECIAL_MESSAGE);
if (messageType != null)
{
if (messageType.Equals(GCMConstants.VALUE_DELETED_MESSAGES))
{
var sTotal = intent.GetStringExtra(GCMConstants.EXTRA_TOTAL_DELETED);
if (!string.IsNullOrEmpty(sTotal))
{
int nTotal = 0;
if (int.TryParse(sTotal, out nTotal))
{
Log.Verbose(TAG, "Received deleted messages notification: " + nTotal);
OnDeletedMessages(context, nTotal);
}
else
Log.Error(TAG, "GCM returned invalid number of deleted messages: " + sTotal);
}
}
else
{
// application is not using the latest GCM library
Log.Error(TAG, "Received unknown special message: " + messageType);
}
}
else
{
OnMessage(context, intent);
}
}
else if (action.Equals(GCMConstants.INTENT_FROM_GCM_LIBRARY_RETRY))
{
var token = intent.GetStringExtra(EXTRA_TOKEN);
if (!string.IsNullOrEmpty(token) && !TOKEN.Equals(token))
{
// make sure intent was generated by this class, not by a
// malicious app.
Log.Error(TAG, "Received invalid token: " + token);
return;
}
// retry last call
if (PushClient.IsRegistered(context))
PushClient.internalUnRegister(context);
else
PushClient.internalRegister(context, SenderIds);
}
}
finally
{
// Release the power lock, so phone can get back to sleep.
// The lock is reference-counted by default, so multiple
// messages are ok.
// If OnMessage() needs to spawn a thread or do something else,
// it should use its own lock.
lock (LOCK)
{
//Sanity check for null as this is a public method
if (sWakeLock != null)
{
Log.Verbose(TAG, "Releasing Wakelock");
sWakeLock.Release();
}
else
{
//Should never happen during normal workflow
Log.Error(TAG, "Wakelock reference is null");
}
}
}
}
internal static void RunIntentInService(Context context, Intent intent, Type classType)
{
lock (LOCK)
{
if (sWakeLock == null)
{
// This is called from BroadcastReceiver, there is no init.
var pm = PowerManager.FromContext(context);
sWakeLock = pm.NewWakeLock(WakeLockFlags.Partial, WAKELOCK_KEY);
}
}
Log.Verbose(TAG, "Acquiring wakelock");
sWakeLock.Acquire();
//intent.SetClassName(context, className);
intent.SetClass(context, classType);
context.StartService(intent);
}
private void handleRegistration(Context context, Intent intent)
{
var registrationId = intent.GetStringExtra(GCMConstants.EXTRA_REGISTRATION_ID);
var error = intent.GetStringExtra(GCMConstants.EXTRA_ERROR);
var unregistered = intent.GetStringExtra(GCMConstants.EXTRA_UNREGISTERED);
Log.Debug(TAG, "handleRegistration: registrationId = " + registrationId + ", error = " + error + ", unregistered = " + unregistered);
// registration succeeded
if (registrationId != null)
{
PushClient.ResetBackoff(context);
PushClient.SetRegistrationId(context, registrationId);
OnRegistered(context, registrationId);
return;
}
// unregistration succeeded
if (unregistered != null)
{
// Remember we are unregistered
PushClient.ResetBackoff(context);
var oldRegistrationId = PushClient.ClearRegistrationId(context);
OnUnRegistered(context, oldRegistrationId);
return;
}
// last operation (registration or unregistration) returned an error;
Log.Debug(TAG, "Registration error: " + error);
// Registration failed
if (GCMConstants.ERROR_SERVICE_NOT_AVAILABLE.Equals(error))
{
var retry = OnRecoverableError(context, error);
if (retry)
{
int backoffTimeMs = PushClient.GetBackoff(context);
int nextAttempt = backoffTimeMs / 2 + sRandom.Next(backoffTimeMs);
Log.Debug(TAG, "Scheduling registration retry, backoff = " + nextAttempt + " (" + backoffTimeMs + ")");
var retryIntent = new Intent(GCMConstants.INTENT_FROM_GCM_LIBRARY_RETRY);
retryIntent.PutExtra(EXTRA_TOKEN, TOKEN);
var retryPendingIntent = PendingIntent.GetBroadcast(context, 0, retryIntent, PendingIntentFlags.OneShot);
var am = AlarmManager.FromContext(context);
am.Set(AlarmType.ElapsedRealtime, SystemClock.ElapsedRealtime() + nextAttempt, retryPendingIntent);
// Next retry should wait longer.
if (backoffTimeMs < MAX_BACKOFF_MS)
{
PushClient.SetBackoff(context, backoffTimeMs * 2);
}
}
else
{
Log.Debug(TAG, "Not retrying failed operation");
}
}
else
{
// Unrecoverable error, notify app
OnError(context, error);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Orleans;
namespace UnitTests.GrainInterfaces
{
using Orleans.Concurrency;
public interface ISomeGrain : IGrainWithIntegerKey
{
Task Do(Outsider o);
}
[Unordered]
public interface ISomeGrainWithInvocationOptions : IGrainWithIntegerKey
{
[AlwaysInterleave]
Task AlwaysInterleave();
}
public interface ISerializationGenerationGrain : IGrainWithIntegerKey
{
Task<object> RoundTripObject(object input);
Task<SomeStruct> RoundTripStruct(SomeStruct input);
Task<SomeAbstractClass> RoundTripClass(SomeAbstractClass input);
Task<ISomeInterface> RoundTripInterface(ISomeInterface input);
Task<SomeAbstractClass.SomeEnum> RoundTripEnum(SomeAbstractClass.SomeEnum input);
Task SetState(SomeAbstractClass input);
Task<SomeAbstractClass> GetState();
}
}
public class Outsider { }
namespace UnitTests.GrainInterfaces
{
[Serializable]
public class RootType
{
public RootType()
{
MyDictionary = new Dictionary<string, object>();
MyDictionary.Add("obj1", new InnerType());
MyDictionary.Add("obj2", new InnerType());
MyDictionary.Add("obj3", new InnerType());
MyDictionary.Add("obj4", new InnerType());
}
public Dictionary<string, object> MyDictionary { get; set; }
public override bool Equals(object obj)
{
var actual = obj as RootType;
if (actual == null)
{
return false;
}
if (MyDictionary == null) return actual.MyDictionary == null;
if (actual.MyDictionary == null) return false;
var set1 = new HashSet<KeyValuePair<string, object>>(MyDictionary);
var set2 = new HashSet<KeyValuePair<string, object>>(actual.MyDictionary);
bool ret = set1.SetEquals(set2);
return ret;
}
public override int GetHashCode()
{
return base.GetHashCode();
}
}
[Serializable]
public struct SomeStruct
{
public Guid Id { get; set; }
public int PublicValue { get; set; }
public int ValueWithPrivateSetter { get; private set; }
public int ValueWithPrivateGetter { private get; set; }
private int PrivateValue { get; set; }
public readonly int ReadonlyField;
public SomeStruct(int readonlyField)
: this()
{
this.ReadonlyField = readonlyField;
}
public int GetValueWithPrivateGetter()
{
return this.ValueWithPrivateGetter;
}
public int GetPrivateValue()
{
return this.PrivateValue;
}
public void SetPrivateValue(int value)
{
this.PrivateValue = value;
}
public void SetValueWithPrivateSetter(int value)
{
this.ValueWithPrivateSetter = value;
}
}
public interface ISomeInterface { int Int { get; set; } }
[Serializable]
public abstract class SomeAbstractClass : ISomeInterface
{
[NonSerialized]
private int nonSerializedIntField;
public abstract int Int { get; set; }
public List<ISomeInterface> Interfaces { get; set; }
public List<SomeAbstractClass> Classes { get; set; }
[Obsolete("This field should not be serialized", true)]
public int ObsoleteIntWithError { get; set; }
[Obsolete("This field should be serialized")]
public int ObsoleteInt { get; set; }
public int NonSerializedInt
{
get
{
return this.nonSerializedIntField;
}
set
{
this.nonSerializedIntField = value;
}
}
[Serializable]
public enum SomeEnum
{
None,
Something,
SomethingElse
}
}
public class OuterClass
{
[Serializable]
public class SomeConcreteClass : SomeAbstractClass
{
public override int Int { get; set; }
public string String { get; set; }
}
}
[Serializable]
public class AnotherConcreteClass : SomeAbstractClass
{
public override int Int { get; set; }
public string AnotherString { get; set; }
}
[Serializable]
public class InnerType
{
public InnerType()
{
Id = Guid.NewGuid();
Something = Id.ToString();
}
public Guid Id { get; set; }
public string Something { get; set; }
public override bool Equals(object obj)
{
var actual = obj as InnerType;
if (actual == null)
{
return false;
}
return Id.Equals(actual.Id) && Equals(Something, actual.Something);
}
public override int GetHashCode()
{
return base.GetHashCode();
}
}
[Serializable]
public class ClassWithStructConstraint<T>
where T : struct
{
public T Value { get; set; }
}
}
| |
using System;
using System.Collections.Generic;
using Blueprint41;
using Blueprint41.Core;
using Blueprint41.Query;
namespace Domain.Data.Query
{
public partial class Node
{
public static EmployeeNode Employee { get { return new EmployeeNode(); } }
}
public partial class EmployeeNode : Blueprint41.Query.Node
{
protected override string GetNeo4jLabel()
{
return "Employee";
}
internal EmployeeNode() { }
internal EmployeeNode(EmployeeAlias alias, bool isReference = false)
{
NodeAlias = alias;
IsReference = isReference;
}
internal EmployeeNode(RELATIONSHIP relationship, DirectionEnum direction, string neo4jLabel = null) : base(relationship, direction, neo4jLabel) { }
public EmployeeNode Alias(out EmployeeAlias alias)
{
alias = new EmployeeAlias(this);
NodeAlias = alias;
return this;
}
public EmployeeNode UseExistingAlias(AliasResult alias)
{
NodeAlias = alias;
return this;
}
public EmployeeIn In { get { return new EmployeeIn(this); } }
public class EmployeeIn
{
private EmployeeNode Parent;
internal EmployeeIn(EmployeeNode parent)
{
Parent = parent;
}
public IFromIn_EMPLOYEE_BECOMES_SALESPERSON_REL EMPLOYEE_BECOMES_SALESPERSON { get { return new EMPLOYEE_BECOMES_SALESPERSON_REL(Parent, DirectionEnum.In); } }
public IFromIn_EMPLOYEE_HAS_EMPLOYEEDEPARTMENTHISTORY_REL EMPLOYEE_HAS_EMPLOYEEDEPARTMENTHISTORY { get { return new EMPLOYEE_HAS_EMPLOYEEDEPARTMENTHISTORY_REL(Parent, DirectionEnum.In); } }
public IFromIn_EMPLOYEE_HAS_EMPLOYEEPAYHISTORY_REL EMPLOYEE_HAS_EMPLOYEEPAYHISTORY { get { return new EMPLOYEE_HAS_EMPLOYEEPAYHISTORY_REL(Parent, DirectionEnum.In); } }
public IFromIn_EMPLOYEE_HAS_SHIFT_REL EMPLOYEE_HAS_SHIFT { get { return new EMPLOYEE_HAS_SHIFT_REL(Parent, DirectionEnum.In); } }
public IFromIn_EMPLOYEE_IS_JOBCANDIDATE_REL EMPLOYEE_IS_JOBCANDIDATE { get { return new EMPLOYEE_IS_JOBCANDIDATE_REL(Parent, DirectionEnum.In); } }
}
public EmployeeOut Out { get { return new EmployeeOut(this); } }
public class EmployeeOut
{
private EmployeeNode Parent;
internal EmployeeOut(EmployeeNode parent)
{
Parent = parent;
}
public IFromOut_DEPARTMENT_CONTAINS_EMPLOYEE_REL DEPARTMENT_CONTAINS_EMPLOYEE { get { return new DEPARTMENT_CONTAINS_EMPLOYEE_REL(Parent, DirectionEnum.Out); } }
public IFromOut_PERSON_BECOMES_EMPLOYEE_REL PERSON_BECOMES_EMPLOYEE { get { return new PERSON_BECOMES_EMPLOYEE_REL(Parent, DirectionEnum.Out); } }
public IFromOut_VENDOR_VALID_FOR_EMPLOYEE_REL VENDOR_VALID_FOR_EMPLOYEE { get { return new VENDOR_VALID_FOR_EMPLOYEE_REL(Parent, DirectionEnum.Out); } }
}
}
public class EmployeeAlias : AliasResult
{
internal EmployeeAlias(EmployeeNode parent)
{
Node = parent;
}
public override IReadOnlyDictionary<string, FieldResult> AliasFields
{
get
{
if (m_AliasFields == null)
{
m_AliasFields = new Dictionary<string, FieldResult>()
{
{ "NationalIDNumber", new StringResult(this, "NationalIDNumber", Datastore.AdventureWorks.Model.Entities["Employee"], Datastore.AdventureWorks.Model.Entities["Employee"].Properties["NationalIDNumber"]) },
{ "LoginID", new NumericResult(this, "LoginID", Datastore.AdventureWorks.Model.Entities["Employee"], Datastore.AdventureWorks.Model.Entities["Employee"].Properties["LoginID"]) },
{ "JobTitle", new StringResult(this, "JobTitle", Datastore.AdventureWorks.Model.Entities["Employee"], Datastore.AdventureWorks.Model.Entities["Employee"].Properties["JobTitle"]) },
{ "BirthDate", new DateTimeResult(this, "BirthDate", Datastore.AdventureWorks.Model.Entities["Employee"], Datastore.AdventureWorks.Model.Entities["Employee"].Properties["BirthDate"]) },
{ "MaritalStatus", new StringResult(this, "MaritalStatus", Datastore.AdventureWorks.Model.Entities["Employee"], Datastore.AdventureWorks.Model.Entities["Employee"].Properties["MaritalStatus"]) },
{ "Gender", new StringResult(this, "Gender", Datastore.AdventureWorks.Model.Entities["Employee"], Datastore.AdventureWorks.Model.Entities["Employee"].Properties["Gender"]) },
{ "HireDate", new DateTimeResult(this, "HireDate", Datastore.AdventureWorks.Model.Entities["Employee"], Datastore.AdventureWorks.Model.Entities["Employee"].Properties["HireDate"]) },
{ "SalariedFlag", new BooleanResult(this, "SalariedFlag", Datastore.AdventureWorks.Model.Entities["Employee"], Datastore.AdventureWorks.Model.Entities["Employee"].Properties["SalariedFlag"]) },
{ "VacationHours", new NumericResult(this, "VacationHours", Datastore.AdventureWorks.Model.Entities["Employee"], Datastore.AdventureWorks.Model.Entities["Employee"].Properties["VacationHours"]) },
{ "SickLeaveHours", new NumericResult(this, "SickLeaveHours", Datastore.AdventureWorks.Model.Entities["Employee"], Datastore.AdventureWorks.Model.Entities["Employee"].Properties["SickLeaveHours"]) },
{ "Currentflag", new BooleanResult(this, "Currentflag", Datastore.AdventureWorks.Model.Entities["Employee"], Datastore.AdventureWorks.Model.Entities["Employee"].Properties["Currentflag"]) },
{ "rowguid", new StringResult(this, "rowguid", Datastore.AdventureWorks.Model.Entities["Employee"], Datastore.AdventureWorks.Model.Entities["Employee"].Properties["rowguid"]) },
{ "ModifiedDate", new DateTimeResult(this, "ModifiedDate", Datastore.AdventureWorks.Model.Entities["Employee"], Datastore.AdventureWorks.Model.Entities["SchemaBase"].Properties["ModifiedDate"]) },
{ "Uid", new StringResult(this, "Uid", Datastore.AdventureWorks.Model.Entities["Employee"], Datastore.AdventureWorks.Model.Entities["Neo4jBase"].Properties["Uid"]) },
};
}
return m_AliasFields;
}
}
private IReadOnlyDictionary<string, FieldResult> m_AliasFields = null;
public EmployeeNode.EmployeeIn In { get { return new EmployeeNode.EmployeeIn(new EmployeeNode(this, true)); } }
public EmployeeNode.EmployeeOut Out { get { return new EmployeeNode.EmployeeOut(new EmployeeNode(this, true)); } }
public StringResult NationalIDNumber
{
get
{
if ((object)m_NationalIDNumber == null)
m_NationalIDNumber = (StringResult)AliasFields["NationalIDNumber"];
return m_NationalIDNumber;
}
}
private StringResult m_NationalIDNumber = null;
public NumericResult LoginID
{
get
{
if ((object)m_LoginID == null)
m_LoginID = (NumericResult)AliasFields["LoginID"];
return m_LoginID;
}
}
private NumericResult m_LoginID = null;
public StringResult JobTitle
{
get
{
if ((object)m_JobTitle == null)
m_JobTitle = (StringResult)AliasFields["JobTitle"];
return m_JobTitle;
}
}
private StringResult m_JobTitle = null;
public DateTimeResult BirthDate
{
get
{
if ((object)m_BirthDate == null)
m_BirthDate = (DateTimeResult)AliasFields["BirthDate"];
return m_BirthDate;
}
}
private DateTimeResult m_BirthDate = null;
public StringResult MaritalStatus
{
get
{
if ((object)m_MaritalStatus == null)
m_MaritalStatus = (StringResult)AliasFields["MaritalStatus"];
return m_MaritalStatus;
}
}
private StringResult m_MaritalStatus = null;
public StringResult Gender
{
get
{
if ((object)m_Gender == null)
m_Gender = (StringResult)AliasFields["Gender"];
return m_Gender;
}
}
private StringResult m_Gender = null;
public DateTimeResult HireDate
{
get
{
if ((object)m_HireDate == null)
m_HireDate = (DateTimeResult)AliasFields["HireDate"];
return m_HireDate;
}
}
private DateTimeResult m_HireDate = null;
public BooleanResult SalariedFlag
{
get
{
if ((object)m_SalariedFlag == null)
m_SalariedFlag = (BooleanResult)AliasFields["SalariedFlag"];
return m_SalariedFlag;
}
}
private BooleanResult m_SalariedFlag = null;
public NumericResult VacationHours
{
get
{
if ((object)m_VacationHours == null)
m_VacationHours = (NumericResult)AliasFields["VacationHours"];
return m_VacationHours;
}
}
private NumericResult m_VacationHours = null;
public NumericResult SickLeaveHours
{
get
{
if ((object)m_SickLeaveHours == null)
m_SickLeaveHours = (NumericResult)AliasFields["SickLeaveHours"];
return m_SickLeaveHours;
}
}
private NumericResult m_SickLeaveHours = null;
public BooleanResult Currentflag
{
get
{
if ((object)m_Currentflag == null)
m_Currentflag = (BooleanResult)AliasFields["Currentflag"];
return m_Currentflag;
}
}
private BooleanResult m_Currentflag = null;
public StringResult rowguid
{
get
{
if ((object)m_rowguid == null)
m_rowguid = (StringResult)AliasFields["rowguid"];
return m_rowguid;
}
}
private StringResult m_rowguid = null;
public DateTimeResult ModifiedDate
{
get
{
if ((object)m_ModifiedDate == null)
m_ModifiedDate = (DateTimeResult)AliasFields["ModifiedDate"];
return m_ModifiedDate;
}
}
private DateTimeResult m_ModifiedDate = null;
public StringResult Uid
{
get
{
if ((object)m_Uid == null)
m_Uid = (StringResult)AliasFields["Uid"];
return m_Uid;
}
}
private StringResult m_Uid = null;
}
}
| |
#region Disclaimer/Info
///////////////////////////////////////////////////////////////////////////////////////////////////
// Subtext WebLog
//
// Subtext is an open source weblog system that is a fork of the .TEXT
// weblog system.
//
// For updated news and information please visit http://subtextproject.com/
// Subtext is hosted at Google Code at http://code.google.com/p/subtext/
// The development mailing list is at subtext@googlegroups.com
//
// This project is licensed under the BSD license. See the License.txt file for more information.
///////////////////////////////////////////////////////////////////////////////////////////////////
#endregion
#undef Diagnostic
using System;
using System.ComponentModel;
using System.Globalization;
using System.Web.UI;
using System.Web.UI.Design;
namespace Subtext.Web.Controls
{
/// <summary>
/// Control used to render paging through records.
/// </summary>
[
Designer(typeof(PagerDesigner))
]
[ToolboxData("<{0}:PagingControl runat=\"server\" />")]
public class PagingControl : Control
{
protected const string DefaultActiveLinkFormat =
@"<a href=""{0}"" title=""page"" class=""Current"">»{1}«</a>";
protected const int DefaultDisplayPageCount = 9;
protected const string DefaultFirstPageText = "First";
protected const string DefaultGoToPageText = "Goto page ";
protected const string DefaultLastPageText = "Last";
protected const string DefaultLinkFormat = @"<a href=""{0}"" title=""Page"">{1}</a>";
protected const int DefaultPageSize = 10;
protected const string DefaultPageUrlFormat = "/?pageid={0}";
protected const string DefaultSuffixText = "";
protected const int FirstPageIndex = 0;
protected const int MinDisplayPageCount = 3;
protected const int MinPageSize = 1;
protected const string SpacerDefault = " ";
protected string _cssClass;
protected string _firstText = DefaultFirstPageText;
protected string _lastText = DefaultLastPageText;
protected string _linkFormat = DefaultLinkFormat;
protected string _linkFormatActive = DefaultActiveLinkFormat;
protected string _prefixText = DefaultGoToPageText;
protected string _spacer;
protected string _suffixText = DefaultSuffixText;
protected string _urlFormat = DefaultPageUrlFormat;
protected bool _usePrefixSuffix = true;
protected bool _useSpacer = true;
protected bool displayFirstLastPageLinks = true;
/// <summary>
/// Constructs an instance of this control.
/// </summary>
public PagingControl()
{
DisplayPageCount = DefaultDisplayPageCount;
}
protected override void OnInit(EventArgs args)
{
}
/// <summary>
/// Renders the link for the specified page index in the paging control.
/// </summary>
/// <param name="pageIndex"></param>
/// <param name="isCurrent">Whether or not the pageindex to render is the current page.</param>
/// <returns></returns>
protected string RenderLink(int pageIndex, bool isCurrent)
{
return RenderLink(pageIndex, (pageIndex + 1).ToString(CultureInfo.InvariantCulture), isCurrent);
}
/// <summary>
/// Renders the link for the specified page index in the paging control.
/// </summary>
/// <param name="pageIndex"></param>
/// <param name="display">The display text of the link</param>
/// <returns></returns>
protected string RenderLink(int pageIndex, string display)
{
return RenderLink(pageIndex, display, false);
}
/// <summary>
/// Renders the link for the specified page index in the paging control.
/// </summary>
/// <param name="pageIndex"></param>
/// <param name="display">The display text of the link</param>
/// <param name="isCurrent">Whether or not the pageindex to render is the current page.</param>
/// <returns></returns>
protected string RenderLink(int pageIndex, string display, bool isCurrent)
{
string url = String.Format(CultureInfo.InvariantCulture, _urlFormat, pageIndex);
return String.Format(CultureInfo.InvariantCulture, isCurrent ? _linkFormatActive : _linkFormat, url, display);
}
protected virtual void WriteConditional(HtmlTextWriter writer, string value, bool condition)
{
if(condition)
{
writer.Write(value);
}
}
#region Render
protected override void Render(HtmlTextWriter writer)
{
// there's only 1 page, a pager is useless so render nothing
if(TotalPageCount == 0 || FirstPageIndex == (TotalPageCount - 1))
{
return;
}
var currentPage = (int)ViewState[ViewStateKeys.PageIndex];
if(_cssClass.Length > 0)
{
writer.AddAttribute("class", _cssClass);
}
writer.RenderBeginTag(HtmlTextWriterTag.Div);
// write prepended label if appropriate and an optional spacer literal
WriteConditional(writer, _prefixText, _usePrefixSuffix);
// determine the start and end pages
int startPage = currentPage - DisplayPageCount / 2 < 0 ? 0 : currentPage - DisplayPageCount / 2;
int endPage = startPage + DisplayPageCount > LastPageIndex
? LastPageIndex + 1
: startPage + DisplayPageCount;
// if the start page isn't the first, then we display << to allow
// paging backwards DisplayCountPage
if(startPage != 0)
{
// if we specified including 'First' link back to pageindex 0,
// write it plus an optional spacer
if(displayFirstLastPageLinks)
{
writer.Write(RenderLink(FirstPageIndex, _firstText));
}
//we will page back DisplayPageCount unless that number is less than 0
//since you can't page less than that.
writer.Write(RenderLink(currentPage - DisplayPageCount <= 0 ? 0 : currentPage - DisplayPageCount - 1,
"<<"));
}
//Now, loop through start to end and display all the links.
for(int i = startPage; i < endPage; i++)
{
writer.Write(RenderLink(i, i == PageIndex));
}
// if we're already displaying the last page, no need for paging or Last Page link
if(endPage - 1 != LastPageIndex)
{
writer.Write(
RenderLink(
currentPage + DisplayPageCount + 1 < LastPageIndex
? currentPage + DisplayPageCount + 1
: LastPageIndex, ">>"));
// if we specified including 'Last' link back to the last page, write it plus
// an optional spacer
if(displayFirstLastPageLinks && PageIndex < LastPageIndex)
{
writer.Write(RenderLink(LastPageIndex, _lastText));
}
}
WriteConditional(writer, _suffixText, _usePrefixSuffix);
writer.RenderEndTag();
}
#endregion
#region Accessors
/// <summary>
/// Gets and sets the CssClass to use for this control.
/// </summary>
public string CssClass
{
get { return _cssClass; }
set { _cssClass = value; }
}
/// <summary>
/// ?
/// </summary>
public int ItemCount
{
get { return ViewState[ViewStateKeys.ItemCount] == null ? 0 : (int)ViewState[ViewStateKeys.ItemCount]; }
set {
ViewState[ViewStateKeys.ItemCount] = value < 0 ? 0 : value;
}
}
/// <summary>
/// The current page index.
/// </summary>
public int PageIndex
{
get
{
return ViewState[ViewStateKeys.PageIndex] == null
? FirstPageIndex
: (int)ViewState[ViewStateKeys.PageIndex];
}
set {
ViewState[ViewStateKeys.PageIndex] = value >= FirstPageIndex ? value : FirstPageIndex;
}
}
/// <summary>
/// Number of allowed records in a page.
/// </summary>
public int PageSize
{
get { return ViewState[ViewStateKeys.PageSize] == null ? 10 : (int)ViewState[ViewStateKeys.PageSize]; }
set {
ViewState[ViewStateKeys.PageSize] = value >= MinPageSize ? value : MinPageSize;
}
}
/// <summary>
/// The number of pages to display at a time.
/// </summary>
public int DisplayPageCount
{
get
{
return ViewState[ViewStateKeys.DisplayPageCount] == null
? 1
: (int)ViewState[ViewStateKeys.DisplayPageCount];
}
set
{
int dislpayPageCount = value;
if(dislpayPageCount < MinDisplayPageCount)
{
dislpayPageCount = MinDisplayPageCount;
}
ViewState[ViewStateKeys.DisplayPageCount] = dislpayPageCount;
}
}
/// <summary>
/// The total number of pages in the set we are
/// pagingi through.
/// </summary>
public int TotalPageCount
{
get
{
if(PageSize > 0)
{
return (int)Math.Ceiling((double)ItemCount / PageSize);
}
return 0;
}
}
public string UrlFormat
{
get { return _urlFormat; }
set { _urlFormat = value; }
}
public string LinkFormat
{
get { return _linkFormat; }
set { _linkFormat = value; }
}
public string LinkFormatActive
{
get { return _linkFormatActive; }
set { _linkFormatActive = value; }
}
public bool UseFirstLast
{
get { return displayFirstLastPageLinks; }
set { displayFirstLastPageLinks = value; }
}
public string FirstText
{
get { return _firstText; }
set { _firstText = value; }
}
public string LastText
{
get { return _lastText; }
set { _lastText = value; }
}
public bool UsePrefixSuffix
{
get { return _usePrefixSuffix; }
set { _usePrefixSuffix = value; }
}
public string SuffixText
{
get { return _suffixText; }
set { _suffixText = value; }
}
public string PrefixText
{
get { return _prefixText; }
set { _prefixText = value; }
}
/// <summary>
/// Returns the index of the very last page in the set.
/// </summary>
public int LastPageIndex
{
get { return TotalPageCount - 1; }
}
#endregion
#region Nested type: ViewStateKeys
internal sealed class ViewStateKeys
{
internal const string DisplayPageCount = "DisplayPages";
internal const string ItemCount = "ItemCount";
internal const string PageIndex = "PageIndex";
internal const string PageSize = "PageSize";
}
#endregion
}
/// <summary>
/// Gontrols the look of the control in the designer.
/// </summary>
public class PagerDesigner : ControlDesigner
{
public override void Initialize(IComponent component)
{
if(component is PagingControl)
{
var context = component as PagingControl;
context.PageSize = 10;
context.ItemCount = 120;
context.PageIndex++;
}
base.Initialize(component);
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.Azure.AcceptanceTestsSubscriptionIdApiVersion
{
using Fixtures.Azure;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Microsoft.Rest.Serialization;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
/// <summary>
/// Some cool documentation.
/// </summary>
public partial class MicrosoftAzureTestUrl : ServiceClient<MicrosoftAzureTestUrl>, IMicrosoftAzureTestUrl, IAzureClient
{
/// <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>
/// Credentials needed for the client to connect to Azure.
/// </summary>
public ServiceClientCredentials Credentials { get; private set; }
/// <summary>
/// Subscription Id.
/// </summary>
public string SubscriptionId { get; set; }
/// <summary>
/// API Version with value '2014-04-01-preview'.
/// </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 IGroupOperations.
/// </summary>
public virtual IGroupOperations Group { get; private set; }
/// <summary>
/// Initializes a new instance of the MicrosoftAzureTestUrl class.
/// </summary>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected MicrosoftAzureTestUrl(params DelegatingHandler[] handlers) : base(handlers)
{
Initialize();
}
/// <summary>
/// Initializes a new instance of the MicrosoftAzureTestUrl 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 MicrosoftAzureTestUrl(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers)
{
Initialize();
}
/// <summary>
/// Initializes a new instance of the MicrosoftAzureTestUrl 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>
protected MicrosoftAzureTestUrl(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 MicrosoftAzureTestUrl 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>
protected MicrosoftAzureTestUrl(System.Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the MicrosoftAzureTestUrl 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="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public MicrosoftAzureTestUrl(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers)
{
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the MicrosoftAzureTestUrl 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="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public MicrosoftAzureTestUrl(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the MicrosoftAzureTestUrl 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="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public MicrosoftAzureTestUrl(System.Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
BaseUri = baseUri;
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the MicrosoftAzureTestUrl 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="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public MicrosoftAzureTestUrl(System.Uri baseUri, ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
BaseUri = baseUri;
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// An optional partial-method to perform custom initialization.
/// </summary>
partial void CustomInitialize();
/// <summary>
/// Initializes client properties.
/// </summary>
private void Initialize()
{
Group = new GroupOperations(this);
BaseUri = new System.Uri("https://management.azure.com/");
ApiVersion = "2014-04-01-preview";
AcceptLanguage = "en-US";
LongRunningOperationRetryTimeout = 30;
GenerateClientRequestId = true;
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();
DeserializationSettings.Converters.Add(new CloudErrorJsonConverter());
}
}
}
| |
using DevExpress.Mvvm.DataAnnotations;
using DevExpress.Mvvm.Native;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Windows;
using System.Windows.Input;
#if !NETFX_CORE
using DevExpress.Mvvm.POCO;
#if !MONO
using System.Windows.Threading;
#endif
#else
using Windows.UI.Xaml;
#endif
namespace DevExpress.Mvvm {
#if !SILVERLIGHT && !NETFX_CORE
public abstract class ViewModelBase : BindableBase, ISupportParentViewModel, ISupportServices, ISupportParameter, ICustomTypeDescriptor {
#else
public abstract class ViewModelBase : BindableBase, ISupportParentViewModel, ISupportServices, ISupportParameter
#if !NETFX_CORE
,ICustomTypeProvider
#endif
{
#endif
static readonly object NotSetParameter = new object();
private object parameter = NotSetParameter;
static bool? isInDesignMode;
public static bool IsInDesignMode {
get {
if(ViewModelDesignHelper.IsInDesignModeOverride.HasValue)
return ViewModelDesignHelper.IsInDesignModeOverride.Value;
if(!isInDesignMode.HasValue) {
#if !MONO
#if SILVERLIGHT
isInDesignMode = DesignerProperties.IsInDesignTool;
#elif NETFX_CORE
isInDesignMode = Windows.ApplicationModel.DesignMode.DesignModeEnabled;
#else
DependencyPropertyDescriptor property = DependencyPropertyDescriptor.FromProperty(DesignerProperties.IsInDesignModeProperty, typeof(FrameworkElement));
isInDesignMode = (bool)property.Metadata.DefaultValue;
#endif
#else
isInDesignMode = false; // MONO TODO
#endif
}
return isInDesignMode.Value;
}
}
object parentViewModel;
object ISupportParentViewModel.ParentViewModel {
get { return parentViewModel; }
set {
if(parentViewModel == value)
return;
parentViewModel = value;
OnParentViewModelChanged(parentViewModel);
}
}
IServiceContainer serviceContainer;
IServiceContainer ISupportServices.ServiceContainer { get { return ServiceContainer; } }
protected IServiceContainer ServiceContainer { get { return serviceContainer ?? (serviceContainer = CreateServiceContainer()); } }
#if !NETFX_CORE
bool IsPOCOViewModel { get { return this is IPOCOViewModel; } }
#else
bool IsPOCOViewModel { get { return false; } }
#endif
public ViewModelBase() {
#if !NETFX_CORE
BuildCommandProperties();
#endif
if(IsInDesignMode) {
#if SILVERLIGHT
Deployment.Current.Dispatcher.BeginInvoke(new Action(OnInitializeInDesignMode));
#elif NETFX_CORE || MONO
OnInitializeInDesignMode();
#else
Dispatcher.CurrentDispatcher.BeginInvoke(new Action(OnInitializeInDesignMode));
#endif
} else {
OnInitializeInRuntime();
}
}
protected object Parameter {
get { return object.Equals(parameter, NotSetParameter) ? null : parameter; }
set {
if(parameter == value)
return;
parameter = value;
OnParameterChanged(value);
}
}
object ISupportParameter.Parameter { get { return Parameter; } set { Parameter = value; } }
protected virtual void OnParameterChanged(object parameter) {
}
protected virtual IServiceContainer CreateServiceContainer() {
return new ServiceContainer(this);
}
protected virtual void OnParentViewModelChanged(object parentViewModel) {
}
protected virtual void OnInitializeInDesignMode() {
OnParameterChanged(null);
}
protected virtual void OnInitializeInRuntime() {
}
protected virtual T GetService<T>() where T : class {
return GetService<T>(ServiceSearchMode.PreferLocal);
}
protected virtual T GetService<T>(string key) where T : class {
return GetService<T>(key, ServiceSearchMode.PreferLocal);
}
[EditorBrowsable(EditorBrowsableState.Never)]
protected virtual T GetService<T>(ServiceSearchMode searchMode) where T : class {
return ServiceContainer.GetService<T>(searchMode);
}
[EditorBrowsable(EditorBrowsableState.Never)]
protected virtual T GetService<T>(string key, ServiceSearchMode searchMode) where T : class {
return ServiceContainer.GetService<T>(key, searchMode);
}
#if !NETFX_CORE
#region CommandAttributeSupport
protected internal void RaiseCanExecuteChanged(Expression<Action> commandMethodExpression) {
if(IsPOCOViewModel) {
POCOViewModelExtensions.RaiseCanExecuteChangedCore(this, commandMethodExpression);
} else {
((IDelegateCommand)commandProperties[ExpressionHelper.GetMethod(commandMethodExpression)]
#if !SILVERLIGHT
.GetValue(this)
#else
.GetValue(this, null)
#endif
).RaiseCanExecuteChanged();
}
}
internal const string CommandNameSuffix = "Command";
const string CanExecuteSuffix = "Can";
const string Error_PropertyWithSameNameAlreadyExists = "Property with the same name already exists: {0}.";
internal const string Error_MethodShouldBePublic = "Method should be public: {0}.";
const string Error_MethodCannotHaveMoreThanOneParameter = "Method cannot have more than one parameter: {0}.";
const string Error_MethodCannotHaveOutORRefParameters = "Method cannot have out or reference parameter: {0}.";
const string Error_CanExecuteMethodHasIncorrectParameters = "Can execute method has incorrect parameters: {0}.";
const string Error_MethodNotFound = "Method not found: {0}.";
Dictionary<MethodInfo, CommandProperty> commandProperties;
internal static string GetCommandName(MethodInfo commandMethod) {
return commandMethod.Name + CommandNameSuffix;
}
internal static string GetCanExecuteMethodName(MethodInfo commandMethod) {
return CanExecuteSuffix + commandMethod.Name;
}
internal static T GetAttribute<T>(MethodInfo method) {
return MetadataHelper.GetAllAttributes(method).OfType<T>().FirstOrDefault();
}
static readonly Dictionary<Type, Dictionary<MethodInfo, CommandProperty>> propertiesCache = new Dictionary<Type, Dictionary<MethodInfo, CommandProperty>>();
void BuildCommandProperties() {
commandProperties = IsPOCOViewModel ? new Dictionary<MethodInfo, CommandProperty>() : GetCommandProperties(GetType());
}
static Dictionary<MethodInfo, CommandProperty> GetCommandProperties(Type type) {
Dictionary<MethodInfo, CommandProperty> result = propertiesCache.GetOrAdd(type, () => CreateCommandProperties(type));
return result;
}
static Dictionary<MethodInfo, CommandProperty> CreateCommandProperties(Type type) {
Dictionary<MethodInfo, CommandProperty> commandProperties = type.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)
.Where(x => GetAttribute<CommandAttribute>(x) != null).ToArray()
.Select(x => {
CommandAttribute attribute = GetAttribute<CommandAttribute>(x);
string name = attribute.Name ?? (x.Name.EndsWith(CommandNameSuffix) ? x.Name : GetCommandName(x));
MethodInfo canExecuteMethod = GetCanExecuteMethod(type, x, attribute, s => new CommandAttributeException(s));
var attributes = MetadataHelper.GetAllAttributes(x);
return new CommandProperty(x, canExecuteMethod, name, attribute.GetUseCommandManager(), attributes, type);
})
.ToDictionary(x => x.Method);
foreach(var property in commandProperties.Values) {
if(type.GetProperty(property.Name) != null || commandProperties.Values.Any(x => x.Name == property.Name && x != property))
throw new CommandAttributeException(string.Format(Error_PropertyWithSameNameAlreadyExists, property.Name));
if(!property.Method.IsPublic)
throw new CommandAttributeException(string.Format(Error_MethodShouldBePublic, property.Method.Name));
ValidateCommandMethodParameters(property.Method, x => new CommandAttributeException(x));
}
return commandProperties;
}
internal static bool ValidateCommandMethodParameters(MethodInfo method, Func<string, Exception> createException) {
ParameterInfo[] parameters = method.GetParameters();
if(CheckCommandMethodConditionValue(parameters.Length <= 1, method, Error_MethodCannotHaveMoreThanOneParameter, createException))
return false;
bool isValidSingleParameter = parameters.Length == 1 && (parameters[0].IsOut || parameters[0].ParameterType.IsByRef);
if(CheckCommandMethodConditionValue(!isValidSingleParameter, method, Error_MethodCannotHaveOutORRefParameters, createException)) {
return false;
}
return true;
}
static bool CheckCommandMethodConditionValue(bool value, MethodInfo method, string errorString, Func<string, Exception> createException) {
CommandAttribute attribute = GetAttribute<CommandAttribute>(method);
if(!value && attribute != null && attribute.IsCommand)
throw createException(string.Format(errorString, method.Name));
return !value;
}
internal static MethodInfo GetCanExecuteMethod(Type type, MethodInfo methodInfo, CommandAttribute commandAttribute, Func<string, Exception> createException) {
if(commandAttribute != null && commandAttribute.CanExecuteMethod != null) {
CheckCanExecuteMethod(methodInfo, createException, commandAttribute.CanExecuteMethod);
return commandAttribute.CanExecuteMethod;
}
bool hasCustomCanExecuteMethod = commandAttribute != null && !string.IsNullOrEmpty(commandAttribute.CanExecuteMethodName);
string canExecuteMethodName = hasCustomCanExecuteMethod ? commandAttribute.CanExecuteMethodName : GetCanExecuteMethodName(methodInfo);
MethodInfo canExecuteMethod = type.GetMethod(canExecuteMethodName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
if(hasCustomCanExecuteMethod && canExecuteMethod == null)
throw createException(string.Format(Error_MethodNotFound, commandAttribute.CanExecuteMethodName));
if(canExecuteMethod != null) {
CheckCanExecuteMethod(methodInfo, createException, canExecuteMethod);
}
return canExecuteMethod;
}
static void CheckCanExecuteMethod(MethodInfo methodInfo, Func<string, Exception> createException, MethodInfo canExecuteMethod) {
ParameterInfo[] parameters = methodInfo.GetParameters();
ParameterInfo[] canExecuteParameters = canExecuteMethod.GetParameters();
if(parameters.Length != canExecuteParameters.Length)
throw createException(string.Format(Error_CanExecuteMethodHasIncorrectParameters, canExecuteMethod.Name));
if(parameters.Length == 1 && (parameters[0].ParameterType != canExecuteParameters[0].ParameterType || parameters[0].IsOut != canExecuteParameters[0].IsOut))
throw createException(string.Format(Error_CanExecuteMethodHasIncorrectParameters, canExecuteMethod.Name));
if(!canExecuteMethod.IsPublic)
throw createException(string.Format(Error_MethodShouldBePublic, canExecuteMethod.Name));
}
public static class CreateCommandHelper<T> {
public static IDelegateCommand CreateCommand(object owner, MethodInfo method, MethodInfo canExecuteMethod, bool? useCommandManager, bool hasParameter) {
return new DelegateCommand<T>(
x => method.Invoke(owner, GetInvokeParameters(x, hasParameter)),
x => canExecuteMethod != null ? (bool)canExecuteMethod.Invoke(owner, GetInvokeParameters(x, hasParameter)) : true
#if !SILVERLIGHT && !MONO
, useCommandManager
#endif
);
}
static object[] GetInvokeParameters(object parameter, bool hasParameter) {
return hasParameter ? new[] { parameter } : new object[0];
}
}
readonly Dictionary<MethodInfo, IDelegateCommand> commands = new Dictionary<MethodInfo, IDelegateCommand>();
IDelegateCommand GetCommand(MethodInfo method, MethodInfo canExecuteMethod, bool? useCommandManager, bool hasParameter) {
return commands.GetOrAdd(method, () => CreateCommand(method, canExecuteMethod, useCommandManager, hasParameter));
}
IDelegateCommand CreateCommand(MethodInfo method, MethodInfo canExecuteMethod, bool? useCommandManager, bool hasParameter) {
Type commandType = hasParameter ? method.GetParameters()[0].ParameterType : typeof(object);
return (IDelegateCommand)typeof(CreateCommandHelper<>).MakeGenericType(commandType).GetMethod("CreateCommand", BindingFlags.Static | BindingFlags.Public).Invoke(null, new object[] { this, method, canExecuteMethod, useCommandManager, hasParameter });
}
#region CommandProperty
class CommandProperty :
#if !SILVERLIGHT && !NETFX_CORE
PropertyDescriptor
#else
PropertyInfo
#endif
{
readonly MethodInfo method;
readonly MethodInfo canExecuteMethod;
readonly bool? useCommandManager;
readonly bool hasParameter;
#if SILVERLIGHT
readonly string name;
readonly Attribute[] attributes;
readonly Type reflectedType;
#endif
public MethodInfo Method { get { return method; } }
public MethodInfo CanExecuteMethod { get { return canExecuteMethod; } }
public CommandProperty(MethodInfo method, MethodInfo canExecuteMethod, string name, bool? useCommandManager, Attribute[] attributes, Type reflectedType)
#if !SILVERLIGHT
: base(name, attributes)
#endif
{
this.method = method;
this.hasParameter = method.GetParameters().Length == 1;
this.canExecuteMethod = canExecuteMethod;
this.useCommandManager = useCommandManager;
#if SILVERLIGHT
this.name = name;
this.attributes = attributes;
this.reflectedType = reflectedType;
#endif
}
IDelegateCommand GetCommand(object component) {
return ((ViewModelBase)component).GetCommand(method, canExecuteMethod, useCommandManager, hasParameter);
}
#if !SILVERLIGHT
public override bool CanResetValue(object component) { return false; }
public override Type ComponentType { get { return method.DeclaringType; } }
public override object GetValue(object component) { return GetCommand(component); }
public override bool IsReadOnly { get { return true; } }
public override Type PropertyType { get { return typeof(ICommand); } }
public override void ResetValue(object component) { throw new NotSupportedException(); }
public override void SetValue(object component, object value) { throw new NotSupportedException(); }
public override bool ShouldSerializeValue(object component) { return false; }
#else
public override PropertyAttributes Attributes { get { return PropertyAttributes.None; } }
public override bool CanRead { get { return true; } }
public override bool CanWrite { get { return false; } }
public override MethodInfo[] GetAccessors(bool nonPublic) { throw new NotSupportedException(); }
public override MethodInfo GetGetMethod(bool nonPublic) { return null; }
public override MethodInfo GetSetMethod(bool nonPublic) { return null; }
public override void SetValue(object obj, object value, BindingFlags invokeAttr, Binder binder, object[] index, CultureInfo culture) { throw new NotSupportedException(); }
public override ParameterInfo[] GetIndexParameters() { return new ParameterInfo[0]; }
public override object GetValue(object obj, BindingFlags invokeAttr, Binder binder, object[] index, CultureInfo culture) { return GetCommand(obj); }
public override Type PropertyType { get { return typeof(ICommand); } }
public override Type DeclaringType { get { return method.DeclaringType; } }
public override object[] GetCustomAttributes(Type attributeType, bool inherit) { return new object[0]; }
public override object[] GetCustomAttributes(bool inherit) { return attributes; }
public override bool IsDefined(Type attributeType, bool inherit) { return false; }
public override string Name { get { return name; } }
public override Type ReflectedType { get { return reflectedType.GetType(); } }
#endif
}
#endregion
#if SILVERLIGHT
static readonly Dictionary<Type, CustomType> customTypes = new Dictionary<Type, CustomType>();
CustomType customType;
static CustomType GetCustomType(Type type, IEnumerable<CommandProperty> properties) {
return customTypes.GetOrAdd(type, () => new CustomType(type, properties));
}
Type ICustomTypeProvider.GetCustomType() {
return customType ?? (customType = GetCustomType(GetType(), commandProperties.Values));
}
#else
#if !NETFX_CORE
#region ICustomTypeDescriptor
AttributeCollection ICustomTypeDescriptor.GetAttributes() {
return TypeDescriptor.GetAttributes(this, true);
}
string ICustomTypeDescriptor.GetClassName() {
return TypeDescriptor.GetClassName(this, true);
}
string ICustomTypeDescriptor.GetComponentName() {
return TypeDescriptor.GetComponentName(this, true);
}
TypeConverter ICustomTypeDescriptor.GetConverter() {
return TypeDescriptor.GetConverter(this, true);
}
EventDescriptor ICustomTypeDescriptor.GetDefaultEvent() {
return TypeDescriptor.GetDefaultEvent(this, true);
}
PropertyDescriptor ICustomTypeDescriptor.GetDefaultProperty() {
return TypeDescriptor.GetDefaultProperty(this, true);
}
object ICustomTypeDescriptor.GetEditor(Type editorBaseType) {
return TypeDescriptor.GetEditor(this, editorBaseType, true);
}
EventDescriptorCollection ICustomTypeDescriptor.GetEvents(Attribute[] attributes) {
return TypeDescriptor.GetEvents(this, attributes, true);
}
EventDescriptorCollection ICustomTypeDescriptor.GetEvents() {
return TypeDescriptor.GetEvents(this, true);
}
PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties(Attribute[] attributes) {
return TypeDescriptor.GetProperties(this, attributes, true);
}
PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties() {
PropertyDescriptorCollection properties = new PropertyDescriptorCollection(TypeDescriptor.GetProperties(this, true).Cast<PropertyDescriptor>().Concat(commandProperties.Values).ToArray());
return properties;
}
object ICustomTypeDescriptor.GetPropertyOwner(PropertyDescriptor pd) {
return this;
}
#endregion
#endif
#endif
#endregion CommandAttributeSupport
#endif
}
#if !SILVERLIGHT && !NETFX_CORE
[Serializable]
#endif
public class CommandAttributeException : Exception {
public CommandAttributeException() { }
public CommandAttributeException(string message)
: base(message) {
}
}
}
| |
#region License
/* Copyright (c) 2003-2015 Llewellyn Pritchard
* All rights reserved.
* This source code is subject to terms and conditions of the BSD License.
* See license.txt. */
#endregion
#region Includes
using System;
using System.Collections;
using System.IO;
using System.Drawing;
using System.Windows.Forms;
using System.Reflection;
#endregion
namespace IronScheme.Editor.ComponentModel
{
/// <summary>
/// Provides services to associate images with .NET objects
/// </summary>
[Name("ImageList provider")]
public interface IImageListProviderService : IService
{
/// <summary>
/// Adds a type to the provider
/// </summary>
/// <param name="type">the type</param>
void Add (Type type);
/// <summary>
/// Adds a type to the provider
/// </summary>
/// <param name="type">the type</param>
/// <param name="img">the image</param>
void Add (Type type, Image img);
/// <summary>
/// Gets the imagelist storing all the images
/// </summary>
ImageList ImageList {get;}
/// <summary>
/// Gets the index of the image for the name
/// </summary>
/// <remarks>The image will be generated if it doesnt</remarks>
int this[string name] {get;}
/// <summary>
/// Gets the index of the image for the name
/// </summary>
/// <remarks>The image will be created if it does exist and has not been added</remarks>
int this[object typeorinstance] {get;}
/// <summary>
/// Gets an instance of Icon based on a image file
/// </summary>
/// <param name="imagefile">the name of the image file</param>
/// <returns>the icon</returns>
Icon GetIcon(string imagefile);
/// <summary>
/// Gets an instance of Image based on a image file
/// </summary>
/// <param name="imagefile">the name of the image file</param>
/// <returns>the icon</returns>
Image GetImage(string imagefile);
}
/// <summary>
/// Add image association to .NET objects/types
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Enum, Inherited=true, AllowMultiple=false)]
public class ImageAttribute : Attribute
{
string path;
/// <summary>
/// Creates an instance of ImageAttribute
/// </summary>
/// <param name="resourcepath">the resource path</param>
public ImageAttribute(string resourcepath)
{
path = resourcepath;
}
/// <summary>
/// The resource path
/// </summary>
public string Path
{
get
{
return
#if VS
"IronScheme.Editor.Resources." +
#endif
path;
}
}
/// <summary>
/// The alternative resource path
/// </summary>
public string AltPath
{
get
{
return
#if !VS
"IronScheme.Editor.Resources." +
#endif
path;
}
}
}
sealed class ImageListProvider : ServiceBase, IImageListProviderService
{
readonly ImageList images = new ImageList();
readonly Hashtable mapping = new Hashtable();
readonly Hashtable namemap = new Hashtable();
readonly Image Empty;
public ImageListProvider()
{
images.ColorDepth = ColorDepth.Depth24Bit;
images.ImageSize = new Size(16,16);
Assembly ass = typeof(ImageListProvider).Assembly;
using (Stream s = ass.GetManifestResourceStream(
#if VS
"IronScheme.Editor.Resources." +
#endif
"empty.png"))
{
Empty = Image.FromStream(s);
images.Images.Add(Empty);
}
Image img = Image.FromStream(ass.GetManifestResourceStream(
#if VS
"IronScheme.Editor.Resources." +
#endif
"Folder.Closed.png"));
images.Images.Add(img);
img = Image.FromStream(ass.GetManifestResourceStream(
#if VS
"IronScheme.Editor.Resources." +
#endif
"Folder.Open.png"));
images.Images.Add(img);
}
public Icon GetIcon(string imagefile)
{
try
{
Bitmap bmp = images.Images[this[imagefile]] as Bitmap;
if (bmp != null)
{
return Icon.FromHandle(bmp.GetHicon());
}
}
catch (NotImplementedException) // MONO
{
return ServiceHost.Window.MainForm.Icon;
}
return null;
}
public Image GetImage(string imagefile)
{
Bitmap bmp = images.Images[this[imagefile]] as Bitmap;
return bmp;
}
public void Add(Type type, Image img)
{
mapping[type] = images.Images.Count;
images.Images.Add( img );
}
public void Add(Type type)
{
if (!mapping.ContainsKey(type))
{
foreach(ImageAttribute iat in type.GetCustomAttributes(typeof(ImageAttribute),true))
{
//the one and only, i hope;
if (!namemap.ContainsKey(iat.Path))
{
//hopefully the user has an image
Stream ms = type.Assembly.GetManifestResourceStream(iat.Path);
if (ms == null)
{
ms = type.Assembly.GetManifestResourceStream(iat.AltPath);
}
if (ms == null)
{
foreach (Assembly ass in AppDomain.CurrentDomain.GetAssemblies())
{
if (ass == type.Assembly)
{
continue;
}
try
{
ms = ass.GetManifestResourceStream(iat.Path);
if (ms != null)
{
break;
}
}
catch
{
}
try
{
ms = ass.GetManifestResourceStream(iat.AltPath);
if (ms != null)
{
break;
}
}
catch
{
}
}
}
if (ms != null)
{
mapping.Add(type, images.Images.Count);
images.Images.Add( Image.FromStream( ms));
namemap.Add(iat.Path, mapping[type]);
return;
}
}
else
{
mapping.Add(type, namemap[iat.Path]);
return;
}
}
//not found
mapping.Add(type, 0);
}
}
public ImageList ImageList
{
get {return images;}
}
public int this[string name]
{
get
{
if (name == null)
{
return 0;
}
if (!namemap.ContainsKey(name))
{
//hopefully the user has an image
Stream ms = null;
foreach (Assembly ass in AppDomain.CurrentDomain.GetAssemblies())
{
try
{
ms = ass.GetManifestResourceStream(
#if VS
"IronScheme.Editor.Resources." +
#endif
name);
if (ms != null)
{
break;
}
}
catch
{
}
}
if (ms != null)
{
int i = images.Images.Count;
images.Images.Add( Image.FromStream( ms, false));
namemap.Add(name, i);
}
else
{
namemap.Add(name, 0);
Trace.WriteLine("Image not found: {0}", name);
}
}
return (int) namemap[name];
}
}
public int this[object typeorinstance]
{
get
{
try
{
if (typeorinstance == null)
{
return 0;
}
if (typeorinstance is Type)
{
Type t = typeorinstance as Type;
if (!mapping.ContainsKey(t))
{
Add(t);
}
return (int)mapping[t];
}
else
{
Type t = typeorinstance.GetType();
return this[t];
}
}
catch
{
}
return 0;
}
}
}
}
| |
//
// WebViewBackend.cs
//
// Author:
// Cody Russell <cody@xamarin.com>
// Vsevolod Kukol <sevo@sevo.org>
//
// Copyright (c) 2014 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 System.Reflection;
using System.Runtime.InteropServices.ComTypes;
using Xwt.Backends;
using Xwt.NativeMSHTML;
using Xwt.WPFBackend.Interop;
using SWC = System.Windows.Controls;
namespace Xwt.WPFBackend
{
public class WebViewBackend : WidgetBackend, IWebViewBackend, IDocHostUIHandler
{
string url;
SWC.WebBrowser view;
bool enableNavigatingEvent, enableLoadingEvent, enableLoadedEvent, enableTitleChangedEvent;
bool initialized;
ICustomDoc currentDocument;
static object mshtmlBrowser;
static PropertyInfo titleProperty;
static PropertyInfo silentProperty;
static MethodInfo stopMethod;
static FieldInfo mshtmlBrowserField;
static Type mshtmlDocType;
public WebViewBackend () : this (new SWC.WebBrowser ())
{
}
internal WebViewBackend (SWC.WebBrowser browser)
{
view = browser;
view.Navigating += HandleNavigating;
view.Navigated += HandleNavigated;
view.LoadCompleted += HandleLoadCompleted;
view.Loaded += HandleViewLoaded;
Widget = view;
view.Navigate ("about:blank"); // force Document initialization
Title = string.Empty;
}
void UpdateDocumentRef()
{
if (currentDocument != view.Document)
{
var doc = view.Document as ICustomDoc;
if (doc != null)
{
doc.SetUIHandler(this);
if (mshtmlDocType == null)
mshtmlDocType = view.Document.GetType();
}
if (currentDocument != null)
currentDocument.SetUIHandler(null);
currentDocument = doc;
}
// on initialization we load "about:blank" to initialize the document,
// in that case we load the requested url
if (currentDocument != null && !initialized)
{
initialized = true;
if (!string.IsNullOrEmpty (url))
view.Navigate(url);
}
}
void HandleViewLoaded(object sender, System.Windows.RoutedEventArgs e)
{
// get the MSHTML.IWebBrowser2 instance field
if (mshtmlBrowserField == null)
mshtmlBrowserField = typeof(SWC.WebBrowser).GetField("_axIWebBrowser2", BindingFlags.Instance | BindingFlags.NonPublic);
if (mshtmlBrowser == null)
mshtmlBrowser = mshtmlBrowserField.GetValue(view);
if (silentProperty == null)
silentProperty = mshtmlBrowserField?.FieldType?.GetProperty("Silent");
if (stopMethod == null)
stopMethod = mshtmlBrowserField?.FieldType?.GetMethod("Stop");
// load requested url if the view is still not initialized
// otherwise it would already have been loaded
if (!initialized && !string.IsNullOrEmpty(url))
{
initialized = true;
view.Navigate(url);
}
DisableJsErrors();
UpdateDocumentRef();
}
public string Url {
get {
return url; }
set {
url = value;
if (initialized && view.IsLoaded)
view.Navigate(url);
}
}
public string Title
{
get; private set;
}
public double LoadProgress { get; protected set; }
public bool CanGoBack {
get {
return view.CanGoBack;
}
}
public bool CanGoForward {
get {
return view.CanGoForward;
}
}
public bool ContextMenuEnabled { get; set; }
public bool ScrollBarsEnabled { get; set; }
public bool DrawsBackground { get; set; }
public string CustomCss { get; set; }
public void GoBack ()
{
view.GoBack ();
}
public void GoForward ()
{
view.GoForward ();
}
public void Reload ()
{
view.Refresh ();
}
public void StopLoading ()
{
if (stopMethod != null)
stopMethod.Invoke(mshtmlBrowser, null);
else
view.InvokeScript ("eval", "document.execCommand('Stop');");
}
public void LoadHtml (string content, string base_uri)
{
view.NavigateToString (content);
url = string.Empty;
}
string GetTitle()
{
if (titleProperty == null)
{
// Get the property with the document Title,
// property name depends on .NET/mshtml Version
titleProperty = mshtmlDocType?.GetProperty("Title") ?? mshtmlDocType?.GetProperty("IHTMLDocument2_title");
}
string title = null;
if (titleProperty != null)
{
try
{
title = titleProperty.GetValue(view.Document, null) as string;
}
catch {
// try to get the title using a script, if reflection fails
try
{
title = (string)view.InvokeScript("eval", "document.title.toString()");
}
#pragma warning disable RECS0022 // A catch clause that catches System.Exception and has an empty body
catch { }
#pragma warning restore RECS0022 // A catch clause that catches System.Exception and has an empty body
}
}
return title;
}
protected new IWebViewEventSink EventSink {
get { return (IWebViewEventSink)base.EventSink; }
}
public override void EnableEvent (object eventId)
{
base.EnableEvent (eventId);
if (eventId is WebViewEvent) {
switch ((WebViewEvent)eventId) {
case WebViewEvent.NavigateToUrl:
enableNavigatingEvent = true;
break;
case WebViewEvent.Loading:
enableLoadingEvent = true;
break;
case WebViewEvent.Loaded:
enableLoadedEvent = true;
break;
case WebViewEvent.TitleChanged:
enableTitleChangedEvent = true;
break;
}
}
}
public override void DisableEvent (object eventId)
{
base.DisableEvent (eventId);
if (eventId is WebViewEvent) {
switch ((WebViewEvent)eventId) {
case WebViewEvent.NavigateToUrl:
enableNavigatingEvent = false;
break;
case WebViewEvent.Loading:
enableLoadingEvent = false;
break;
case WebViewEvent.Loaded:
enableLoadedEvent = false;
break;
case WebViewEvent.TitleChanged:
enableTitleChangedEvent = false;
break;
}
}
}
void HandleNavigating (object sender, System.Windows.Navigation.NavigatingCancelEventArgs e)
{
if (enableNavigatingEvent) {
var newurl = string.Empty;
if (e.Uri != null)
newurl = e.Uri.AbsoluteUri;
Context.InvokeUserCode (delegate {
e.Cancel = EventSink.OnNavigateToUrl (newurl);
});
}
}
void HandleNavigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
{
LoadProgress = 0;
if (e.Uri != null && view.IsLoaded)
this.url = e.Uri.AbsoluteUri;
if (enableLoadingEvent)
Context.InvokeUserCode(delegate
{
EventSink.OnLoading();
});
}
void HandleLoadCompleted (object sender, System.Windows.Navigation.NavigationEventArgs e)
{
UpdateDocumentRef();
LoadProgress = 1;
if (enableLoadedEvent)
Context.InvokeUserCode (EventSink.OnLoaded);
}
static void DisableJsErrors()
{
if (silentProperty != null)
silentProperty.SetValue(mshtmlBrowser, true, null);
}
#region IDocHostUIHandler implementation
int IDocHostUIHandler.ShowContextMenu(DOCHOSTUICONTEXTMENU dwID, ref POINT ppt, object pcmdtReserved, object pdispReserved)
{
return (int)(ContextMenuEnabled ? HResult.S_FALSE : HResult.S_OK);
}
void IDocHostUIHandler.GetHostInfo(ref DOCHOSTUIINFO pInfo)
{
pInfo.dwFlags = DOCHOSTUIFLAG.DOCHOSTUIFLAG_DPI_AWARE;
if (!ScrollBarsEnabled)
pInfo.dwFlags = pInfo.dwFlags | DOCHOSTUIFLAG.DOCHOSTUIFLAG_SCROLL_NO | DOCHOSTUIFLAG.DOCHOSTUIFLAG_NO3DOUTERBORDER;
if (!string.IsNullOrEmpty(CustomCss))
pInfo.pchHostCss = CustomCss;
}
void IDocHostUIHandler.ShowUI(uint dwID, ref object pActiveObject, ref object pCommandTarget, ref object pFrame, ref object pDoc)
{
}
void IDocHostUIHandler.HideUI()
{
}
void IDocHostUIHandler.UpdateUI()
{
var newTitle = GetTitle();
if (newTitle != Title)
{
Title = newTitle;
if (enableTitleChangedEvent)
Context.InvokeUserCode(EventSink.OnTitleChanged);
}
}
void IDocHostUIHandler.EnableModeless(bool fEnable)
{
}
void IDocHostUIHandler.OnDocWindowActivate(bool fActivate)
{
}
void IDocHostUIHandler.OnFrameWindowActivate(bool fActivate)
{
}
void IDocHostUIHandler.ResizeBorder(ref RECT prcBorder, object pUIWindow, bool fFrameWindow)
{
}
int IDocHostUIHandler.TranslateAccelerator(ref MSG lpMsg, ref Guid pguidCmdGroup, uint nCmdID)
{
return (int)HResult.S_FALSE;
}
void IDocHostUIHandler.GetOptionKeyPath(out string pchKey, uint dw)
{
pchKey = null;
}
int IDocHostUIHandler.GetDropTarget(object pDropTarget, out object ppDropTarget)
{
ppDropTarget = pDropTarget;
return (int)HResult.S_FALSE;
}
void IDocHostUIHandler.GetExternal(out object ppDispatch)
{
ppDispatch = null;
}
int IDocHostUIHandler.TranslateUrl(uint dwTranslate, string pchURLIn, out string ppchURLOut)
{
ppchURLOut = pchURLIn;
return (int)HResult.S_FALSE;
}
int IDocHostUIHandler.FilterDataObject(IDataObject pDO, out IDataObject ppDORet)
{
ppDORet = null;
return (int)HResult.S_FALSE;
}
#endregion
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.